okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
29.2 KiB684 linesraw
1#!/usr/bin/env python3
2"""The settings register: every STRATA_* environment setting the engine reads, in one file (data/settings-register.json).
3
4    python tools/settings_register.py             # regenerate data/settings-register.json (keeps the hand-kept fields)
5    python tools/settings_register.py --check     # scan only; print what is missing from / extra in the register; exit 1 on a difference
6    python tools/settings_register.py --names     # print the names the engine reads, one per line
7    python tools/settings_register.py --no-git    # regenerate without the git history fields (fast)
8    python tools/settings_register.py --docs      # write docs/SETTINGS.md from the register
9
10What counts as "the engine reads it": the name is the string literal argument of a ``getenv`` call or of one of the engine's env
11helpers (``env_on``, ``env_int``, ``pipe_dbg_env`` ...) in src/, include/, metal/src/ or sycl/src/. Calls that write or remove a
12variable (``_putenv_s``, ``put_env``, ``set_env``, ``unset_env``) are not reads; they are listed as ``engine_sets``.
13
14Automatic fields (rebuilt on every run): backends, reads, parse, code_default, default_state, engine_sets, launch_sets, launch_reads,
15doc_mentions, first/last commit and the first release that has the name.
16
17Hand-kept fields (copied over from the old file on every run, never written by the scan): status, owner, note, retire_after, retired_in.
18``status`` is one of STATUSES below. A new name comes in with status "" and the test refuses an empty status until somebody sets it.
19
20Only the standard library is used.
21"""
22from __future__ import annotations
23
24import argparse
25import collections
26import json
27import os
28import re
29import subprocess
30import sys
31from pathlib import Path
32
33ROOT = Path(__file__).resolve().parent.parent
34REGISTER = ROOT / "data" / "settings-register.json"
35SETTINGS_PAGE = "docs/SETTINGS.md"
36
37ENGINE_DIRS = ("src", "include", "metal/src", "sycl/src")
38LAUNCH_PATHS = ("strata_control", "strata_cli", "setup.py", "apps/host/server", "serve")
39DOC_PATHS = ("docs", "README.md", "AGENTS.md")
40LAUNCH_EXT = (".py", ".mjs", ".js", ".cjs", ".ts")
41SKIP_PARTS = ("node_modules", "/tests/", "/test/", "__pycache__")
42
43STATUSES = ("default", "rollback", "opt-in", "research", "retire-candidate", "unsure", "retired")
44HAND_FIELDS = ("status", "owner", "note", "retire_after", "retired_in")
45
46NAME_RE = re.compile(r"STRATA_[A-Z0-9_]+")
47# a call whose first argument is the name literal: getenv, env_on, env_int, pipe_dbg_env, il_env_on, kva_env_flag ...
48CALL_RE = re.compile(r'(\w*(?:getenv|env\w*|\w*_env\w*)\s*\(\s*)"(STRATA_[A-Z0-9_]+)"')
49WRITE_FN_RE = re.compile(r"put|set_env|unset|setenv")
50
51FLAG_FNS = {"env_on", "env_flag", "il_env_on", "kva_env_flag", "env_tri"}
52INT_FNS = {"env_int", "env_int_or", "kva_env_i64", "a_env", "env_count", "lanes_env"}
53FLOAT_FNS = {"env_num", "env_f"}
54
55HIP_MACROS = {"STRATA_USE_HIP", "__HIPCC__", "STRATA_HIP_GFX906", "FNX_HIP", "__HIP_PLATFORM_AMD__", "STRATA_HIPBLASLT_AVAILABLE",
56              "STRATA_ROCBLAS_AVAILABLE", "__HIP_DEVICE_COMPILE__", "STRATA_PREFILL_MMQ_HIP"}
57CUDA_ONLY_MACROS = {"__CUDA_ARCH__", "CUDART_VERSION", "__NVPTX__", "STRATA_EXPERIMENTAL_SM60"}
58METAL_MACROS = {"STRATA_METAL", "STRATA_GPU_METAL", "__APPLE__"}
59
60
61# ---------------------------------------------------------------- file walking
62
63def _files(rel_paths, exts=None):
64    for rel in rel_paths:
65        base = ROOT / rel
66        if base.is_file():
67            yield base
68            continue
69        for dirpath, dirnames, filenames in os.walk(base):
70            dirnames[:] = [d for d in dirnames if d not in ("node_modules", "__pycache__", ".git")]
71            for fn in filenames:
72                if exts and not fn.endswith(exts):
73                    continue
74                yield Path(dirpath) / fn
75
76
77def _rel(p: Path) -> str:
78    return p.relative_to(ROOT).as_posix()
79
80
81def _read_lines(p: Path):
82    try:
83        return p.read_text(encoding="utf-8", errors="replace").split("\n")
84    except OSError:
85        return []
86
87
88# ---------------------------------------------------------------- preprocessor reachability (CUDA / HIP / Metal)
89
90_TOKEN = re.compile(r"!|&&|\|\||\(|\)|defined\s*\(\s*(\w+)\s*\)|defined\s+(\w+)|[A-Za-z_]\w*|\d+")
91
92
93def _eval(expr: str, cfg: str):
94    """Three-valued evaluation of a preprocessor condition for one build flavour; None is unknown (treated as possibly true)."""
95    toks = []
96    for m in _TOKEN.finditer(expr):
97        toks.append(m)
98    pos = 0
99
100    def val(sym: str):
101        if sym in HIP_MACROS:
102            return cfg == "hip"
103        if sym in CUDA_ONLY_MACROS:
104            return cfg == "cuda"
105        if sym in METAL_MACROS:
106            return cfg == "metal"
107        return None
108
109    def primary():
110        nonlocal pos
111        if pos >= len(toks):
112            return None
113        m = toks[pos]
114        t = m.group(0)
115        if t == "!":
116            pos += 1
117            v = primary()
118            return None if v is None else (not v)
119        if t == "(":
120            pos += 1
121            v = orx()
122            if pos < len(toks) and toks[pos].group(0) == ")":
123                pos += 1
124            return v
125        pos += 1
126        if t.startswith("defined"):
127            return val(m.group(1) or m.group(2))
128        if t.isdigit():
129            return None if t not in ("0", "1") else (t == "1")
130        return val(t)
131
132    def andx():
133        nonlocal pos
134        v = primary()
135        while pos < len(toks) and toks[pos].group(0) == "&&":
136            pos += 1
137            w = primary()
138            v = False if (v is False or w is False) else (None if (v is None or w is None) else True)
139        return v
140
141    def orx():
142        nonlocal pos
143        v = andx()
144        while pos < len(toks) and toks[pos].group(0) == "||":
145            pos += 1
146            w = andx()
147            v = True if (v is True or w is True) else (None if (v is None or w is None) else False)
148        return v
149
150    # comparisons (">=", "<") make the whole condition unknown; the tokenizer skips them, so give up on such a line
151    if re.search(r"[<>=]=?|[+\-*/]", re.sub(r"&&|\|\||!defined|!\s*\(|!\s*\w", "", expr)):
152        return None
153    return orx()
154
155
156def _pp_states(lines):
157    """For every line, the set of build flavours in which it can be compiled: a subset of {"cuda", "hip", "metal"}."""
158    flavours = ("cuda", "hip", "metal")
159    stack = []   # each: (cond_values {cfg: bool|None}, parent_alive set) for the current branch
160    out = []
161    alive = set(flavours)
162    for line in lines:
163        s = line.lstrip()
164        if s.startswith("#"):
165            d = re.sub(r"^#\s*", "", s)
166            m = re.match(r"(ifdef|ifndef|if|elif|else|endif)\b(.*)", d)
167            if m:
168                kw, rest = m.group(1), re.sub(r"(//.*|/\*.*)$", "", m.group(2)).strip()
169                if kw in ("if", "ifdef", "ifndef"):
170                    if kw == "ifdef":
171                        cond = {c: _eval(f"defined({rest.split()[0]})" if rest.split() else "", c) for c in flavours}
172                    elif kw == "ifndef":
173                        cond = {c: _eval(f"!defined({rest.split()[0]})" if rest.split() else "", c) for c in flavours}
174                    else:
175                        cond = {c: _eval(rest, c) for c in flavours}
176                    stack.append({"parent": set(alive), "cond": cond, "taken": {c: (cond[c] is True) for c in flavours}})
177                    alive = {c for c in stack[-1]["parent"] if cond[c] is not False}
178                elif kw == "elif" and stack:
179                    top = stack[-1]
180                    cond = {c: _eval(rest, c) for c in flavours}
181                    alive = {c for c in top["parent"] if cond[c] is not False and not top["taken"][c]}
182                    for c in flavours:
183                        top["taken"][c] = top["taken"][c] or cond[c] is True
184                elif kw == "else" and stack:
185                    top = stack[-1]
186                    alive = {c for c in top["parent"] if not top["taken"][c]}
187                elif kw == "endif" and stack:
188                    top = stack.pop()
189                    alive = set(top["parent"])
190        out.append(alive)
191    return out
192
193
194# ---------------------------------------------------------------- engine scan
195
196def _backend_of(path: str, flavours: set[str]) -> list[str]:
197    p = path
198    if p.startswith("sycl/src"):
199        return ["sycl"]
200    if p.startswith("metal/src"):
201        return ["metal"]
202    if "/cpu/" in p or p.endswith(("_cpu.cpp", "_cpu.hpp")):
203        return ["cpu"]
204    fl = flavours
205    if fl >= {"cuda", "hip"}:
206        res = ["cuda-hip"]
207    elif fl == {"cuda"}:
208        res = ["cuda"]
209    elif fl == {"hip"}:
210        res = ["hip"]
211    elif fl == {"metal"}:
212        res = ["metal"]
213    elif not fl:
214        res = ["cuda-hip"]
215    else:
216        res = ["cuda-hip"] if "cuda" in fl or "hip" in fl else sorted(fl)
217    base = os.path.basename(p).lower()
218    if res == ["cuda-hip"]:
219        if "hipblaslt" in base or "rocblas" in base or "/hip" in p or "hip_" in base:
220            res = ["hip"]
221        elif re.search(r"sm\d\d|nv_defaults|nvfp4|cublas|/nvidia", p.lower()) and "hip" not in base:
222            res = ["cuda"]
223    return res
224
225
226_INT_RE = re.compile(r"\b(atoi|stoi|strtol|strtoll|strtoul|strtoull|atol|atoll|stoll|stoul|stoull)\b")
227_FLOAT_RE = re.compile(r"\b(atof|strtod|strtof|stof|stod)\b")
228_NUM = r"-?(?:0x[0-9a-fA-F]+|\d[\d.']*(?:e[+-]?\d+)?)[fFuUlL]*"
229
230
231def _num_clean(s: str) -> str:
232    return re.sub(r"[fFuUlL]+$", "", s.replace("'", ""))
233
234
235def _analyze(lines, i, name, fn, col):
236    """parse kind and code default for one read. i is the 0-based line index, col the column where the call starts."""
237    fn0 = fn.strip().rstrip("(").strip()
238    short = fn0.split("::")[-1]
239    first = lines[i][col:]
240    # arguments of a helper that takes a default: env_int("X", 5)
241    argm = re.match(r'[^"]*"' + re.escape(name) + r'"\s*,\s*([^),;]+(?:\([^)]*\))?[^),;]*)\)', first)
242    if short in FLAG_FNS or short in INT_FNS or short in FLOAT_FNS or short == "pipe_dbg_env":
243        arg = argm.group(1).strip() if argm else None
244        if short == "il_env_on":
245            return "flag", "on", "set to 0 turns it off"
246        if short in ("env_on", "env_flag"):
247            return "flag", "off", "unset is off"
248        if short == "kva_env_flag":
249            d = None if arg is None else ("on" if arg in ("true", "1") else "off" if arg in ("false", "0") else None)
250            return "flag", d, arg
251        if short == "env_tri":
252            return "flag", None, "unset / 0 / non-zero"
253        if short in INT_FNS:
254            return "int", None, (_num_clean(arg) if arg else None)
255        if short in FLOAT_FNS:
256            return "float", None, (_num_clean(arg) if arg else None)
257        if short == "pipe_dbg_env":
258            return "debug-gated", None, "read only when STRATA_PIPELINE_DEBUG=1"
259    # std::getenv: look at the rest of the statement and the next two lines
260    win = [first]
261    for k in range(1, 4):
262        if i + k < len(lines):
263            win.append(lines[i + k])
264    text = "\n".join(win)
265    cut = re.search(r'getenv\(\s*"STRATA_', text[len(first.split(name, 1)[0]) + len(name):])
266    if cut:
267        text = text[: len(first.split(name, 1)[0]) + len(name) + cut.start()]
268    prev = lines[i - 1] if i > 0 else ""
269    kind = None
270    if _FLOAT_RE.search(text):
271        kind = "float"
272    elif _INT_RE.search(text):
273        kind = "int"
274    elif re.search(r"'0'|\"0\"|!=\s*nullptr|==\s*nullptr|!=\s*NULL|==\s*NULL|\[0\]|\*\w+\s*(?:!=|==)|&&|\|\||\bif\s*\(|!\w", text):
275        kind = "flag"
276    else:
277        kind = "string"
278    default_state = None
279    code_default = None
280    if kind == "flag":
281        # Only the exact shapes are read; anything else stays None ("not readable from the call").
282        t = re.sub(r"\s+", " ", text)
283        on = (re.search(r"(?:==\s*(?:nullptr|NULL)|!\s*\w+)\s*\|\|\s*\(?\w+(?:\[0\]|\s*\[\s*0\s*\])\s*!=\s*'0'", t)       # unset or not "0"
284              or re.search(r"!\(\s*\w+\s*&&\s*\w+\[0\]\s*==\s*'0'\s*\)", t)                                               # !(e && e[0]=='0')
285              or re.search(r"(?:==\s*(?:nullptr|NULL)|!\s*\w+)\s*\|\|\s*std::strcmp\(\s*\w+\s*,\s*\"0\"\s*\)\s*!=\s*0", t)
286              or re.search(r"\b\w+\s*&&\s*\w+\[0\]\s*==\s*'0'\s*\)?\s*(?:return|\{)", t))                                # if (e && e[0]=='0') off
287        off = (re.search(r"!=\s*(?:nullptr|NULL)\s*&&\s*\(?\w+\[0\]\s*!=\s*'0'", t)
288               or re.search(r"!=\s*(?:nullptr|NULL)\s*&&\s*\*?\w+\s*!=\s*'0'", t)
289               or re.search(r"\b\w+\s*&&\s*\w+\[0\]\s*(?:!=\s*'0'|==\s*'1')", t)
290               or re.search(r"return\s+\w+\s*&&\s*std::atoi\(\s*\w+\s*\)\s*!=\s*0", t)
291               or re.search(r"!=\s*(?:nullptr|NULL)\s*&&\s*std::atoi\(", t))
292        if on and not off:
293            default_state = "on"
294        elif off and not on:
295            default_state = "off"
296        elif not on and not off:
297            # presence only: getenv("X") != nullptr (set = on) / == nullptr (set = off)
298            pres = re.match(r'getenv\("' + re.escape(name) + r'"\)\s*(!=|==)\s*(?:nullptr|NULL)\b(?!\s*&&)', t)
299            if pres:
300                default_state = "off" if pres.group(1) == "!=" else "on"
301    elif kind in ("int", "float"):
302        m = re.search(r"\)\s*:\s*(" + _NUM + r")", text) or re.search(r"\?\s*[^:;]*:\s*(" + _NUM + r")\s*[;,)]", text)
303        if m:
304            code_default = _num_clean(m.group(1))
305        else:
306            m = re.search(r"=\s*(" + _NUM + r")\s*;\s*$", prev)
307            if m and re.search(r"\bif\s*\(", text):
308                code_default = _num_clean(m.group(1))
309    return kind, default_state, code_default
310
311
312def scan_engine():
313    reads = collections.defaultdict(list)
314    sets = collections.defaultdict(list)
315    for p in _files(ENGINE_DIRS):
316        rel = _rel(p)
317        lines = _read_lines(p)
318        if not any("STRATA_" in l for l in lines):
319            continue
320        states = None
321        for i, l in enumerate(lines):
322            if "STRATA_" not in l:
323                continue
324            for m in CALL_RE.finditer(l):
325                fn, name = m.group(1), m.group(2)
326                if states is None:
327                    states = _pp_states(lines)
328                if WRITE_FN_RE.search(fn):
329                    sets[name].append({"file": rel, "line": i + 1})
330                    continue
331                kind, dstate, dflt = _analyze(lines, i, name, fn, m.start())
332                reads[name].append({
333                    "file": rel, "line": i + 1,
334                    "backend": _backend_of(rel, states[i])[0],
335                    "fn": fn.strip().rstrip("(").strip().split("::")[-1],
336                    "parse": kind, "default_state": dstate, "code_default": dflt,
337                })
338    return reads, sets
339
340
341# ---------------------------------------------------------------- launch code
342
343_SET_PATTERNS = [
344    re.compile(r"""["'`]NAME["'`]\s*:\s*(?P<v>[^,}\n]+)"""),                      # {"NAME": "1"}
345    re.compile(r"""\(\s*["']NAME["']\s*,\s*(?P<v>[^)\n]+)\)"""),                  # ("NAME", "1")
346    re.compile(r"""\[\s*["']NAME["']\s*\]\s*=(?!=)\s*(?P<v>[^\n]+)"""),           # env["NAME"] = x
347    re.compile(r"""setdefault\(\s*["']NAME["']\s*,\s*(?P<v>[^)\n]+)\)"""),
348    re.compile(r"""\.NAME\s*=(?!=)\s*(?P<v>[^\n;]+)"""),                           # process.env.NAME = x
349    re.compile(r"""(?<![A-Z0-9_])NAME=(?P<v>[^\s"'`,;)\]]+)"""),                   # NAME=1 in a string / command
350    re.compile(r"""["'`]NAME["'`]\s*,\s*(?P<v>["'`][^"'`\n]*["'`])"""),            # ["NAME", "1"] / env.set("NAME","1")
351]
352
353
354def _is_test(rel: str) -> bool:
355    b = os.path.basename(rel)
356    return (b.startswith("test_") or b.endswith(("_test.py", ".test.mjs", ".test.js", ".spec.mjs")) or b == "conftest.py"
357            or any(s in "/" + rel for s in SKIP_PARTS))
358
359
360def scan_launch(names):
361    sets = collections.defaultdict(list)
362    reads = collections.defaultdict(list)
363    named = collections.defaultdict(set)
364    for p in _files(LAUNCH_PATHS, LAUNCH_EXT):
365        rel = _rel(p)
366        if _is_test(rel):
367            continue
368        lines = _read_lines(p)
369        in_doc = False
370        for i, l in enumerate(lines):
371            was_doc = in_doc
372            if p.suffix == ".py" and l.count('"""') % 2 == 1:
373                in_doc = not in_doc
374            if "STRATA_" not in l:
375                continue
376            stripped = l.strip()
377            is_comment = stripped.startswith(("#", "//", "*", "/*")) or was_doc or (in_doc and not was_doc and '"""' in l and False)
378            for nm in set(re.findall(r"STRATA_[A-Z0-9_]+(?![A-Z0-9_])", l)):
379                if nm not in names:
380                    continue
381                named[nm].add(rel)
382                got = None
383                if not is_comment:
384                    for pat in _SET_PATTERNS:
385                        m = re.search(pat.pattern.replace("NAME", re.escape(nm)), l)
386                        if m:
387                            got = m.group("v").strip().rstrip(",;").strip()
388                            break
389                if got is not None and (got.startswith(("\"STRATA_", "'STRATA_")) or "\\d" in got or got.endswith(":") or got in ('"reason"', '"when"', '"value"')):
390                    got = None
391                if got is not None and not re.search(r"environ\.get|getenv|\.get\(", l[: l.find(nm)]):
392                    sets[nm].append({"file": rel, "line": i + 1, "value": got[:80]})
393                elif not is_comment and re.search(r"environ\.get|environ\[|getenv|process\.env|env\.get|env\[", l):
394                    reads[nm].append({"file": rel, "line": i + 1})
395    return sets, reads, named
396
397
398# ---------------------------------------------------------------- engine default tables
399
400DEFAULT_TABLE_FILES = ("src/core/arch_defaults.cpp", "src/core/nv_defaults.cpp", "src/core/amd_community.cpp", "src/core/gfx12_extra.cpp",
401                       "src/core/defaults_026.cpp")
402
403
404_ARCH_LABELS = (
405    (re.compile(r"gfx_arch_is_gfx12\b|gfx12\b"), "gfx12"),
406    (re.compile(r'gfx_arch_is_gfx1151|"gfx1151"'), "gfx1151"),
407    (re.compile(r'"gfx1103"|"gfx1150"'), "gfx1103/gfx1150"),
408    (re.compile(r"mj\s*==\s*8\s*&&\s*mn\s*==\s*6"), "sm_86"),
409    (re.compile(r"mj\s*==\s*6\s*&&\s*mn\s*==\s*0"), "sm_60"),
410    (re.compile(r"mj\s*==\s*12\s*&&\s*mn\s*==\s*1"), "sm_121"),
411    (re.compile(r"nv_kq_default_env|cc_major_of\(min_major\)"), "NVIDIA cc>=8"),
412)
413
414
415def scan_engine_defaults(names):
416    """Entries of the engine's own default tables: {"STRATA_X", "v"} / push_back({"STRATA_X", "v"}). The engine applies them for a GPU
417    architecture when the person has not set the name. "arch" is the nearest architecture test above the entry (a label, to be checked
418    by eye; "windows" is added when a Windows-only test sits between that test and the entry)."""
419    out = collections.defaultdict(list)
420    for rel in DEFAULT_TABLE_FILES:
421        p = ROOT / rel
422        lines = _read_lines(p)
423        for i, l in enumerate(lines):
424            for m in re.finditer(r'\{\s*"(STRATA_[A-Z0-9_]+)"\s*,\s*"([^"]*)"\s*\}', l):
425                if m.group(1) not in names:
426                    continue
427                label, win = "", False
428                for k in range(i, max(-1, i - 80), -1):
429                    if re.search(r"\bwin\s*&&|\bwindows\b\s*(?:&&|\))|!windows", lines[k]) and not label:
430                        win = True
431                    hit = next((lab for rx, lab in _ARCH_LABELS if rx.search(lines[k])), None)
432                    if hit:
433                        label = hit
434                        break
435                    if lines[k].startswith(("std::vector", "bool ", "void ")) and k != i:
436                        break
437                out[m.group(1)].append({"file": rel, "line": i + 1, "value": m.group(2), "arch": (label + (" (Windows)" if win and label else "")) or "?"})
438    return out
439
440
441# ---------------------------------------------------------------- docs
442
443def scan_docs(names):
444    out = collections.defaultdict(list)
445    for p in _files(DOC_PATHS, (".md",)):
446        rel = _rel(p)
447        if rel == SETTINGS_PAGE:   # the generated page lists the names itself; it is not a source of documentation
448            continue
449        for i, l in enumerate(_read_lines(p)):
450            if "STRATA_" not in l:
451                continue
452            for nm in set(re.findall(r"STRATA_[A-Z0-9_]+(?![A-Z0-9_])", l)):
453                if nm in names:
454                    out[nm].append(f"{rel}:{i + 1}")
455    return out
456
457
458# ---------------------------------------------------------------- git history
459
460def _git(*args):
461    return subprocess.run(["git", "-C", str(ROOT), *args], capture_output=True, text=True, encoding="utf-8", errors="replace").stdout
462
463
464def _tag_of_commits():
465    """{commit: first release tag that contains it}, from the release tags in date order."""
466    tags = [t for t in _git("tag", "--sort=creatordate").split() if re.fullmatch(r"v\d+\.\d+\.\d+(\.\d+)?", t)]
467    seen = set()
468    first = {}
469    for t in tags:
470        revs = _git("rev-list", t).split()
471        for c in revs:
472            if c not in seen:
473                seen.add(c)
474                first[c] = t
475    return first
476
477
478def scan_git(names):
479    """first and last commit that adds or removes a line holding the name, in the engine directories."""
480    out = _git("log", "--reverse", "--no-color", "-U0", "--format=@@C %H %cs", "-G", "STRATA_[A-Z0-9_]+", "-p", "--", *ENGINE_DIRS)
481    tagmap = _tag_of_commits()
482    first, last = {}, {}
483    cur = None
484    for line in out.split("\n"):
485        if line.startswith("@@C "):
486            _, h, d = line.split(" ", 2)
487            cur = (h, d)
488            continue
489        if cur is None or not line or line[0] not in "+-" or line.startswith(("+++", "---")):
490            continue
491        for nm in set(NAME_RE.findall(line)):
492            if nm in names:
493                if line[0] == "+" and nm not in first:
494                    first[nm] = cur
495                last[nm] = cur
496    res = {}
497    for nm in names:
498        f, l = first.get(nm), last.get(nm)
499        res[nm] = {
500            "first_commit": f[0][:10] if f else None, "first_date": f[1] if f else None, "since": tagmap.get(f[0]) if f else None,
501            "last_commit": l[0][:10] if l else None, "last_date": l[1] if l else None,
502        }
503    return res
504
505
506
507# ---------------------------------------------------------------- the settings page (docs/SETTINGS.md)
508
509_BACKEND_WORDS = {"cuda-hip": "NVIDIA and AMD", "cuda": "NVIDIA", "hip": "AMD", "sycl": "Intel Arc", "metal": "Mac", "cpu": "CPU"}
510
511
512def _where(e):
513    have = set(e["backends"])
514    if "cuda-hip" in have:
515        have -= {"cuda", "hip"}
516    words = [_BACKEND_WORDS[b] for b in ("cuda-hip", "cuda", "hip", "sycl", "metal", "cpu") if b in have]
517    return ", ".join(words)
518
519
520def _kind(e):
521    return {"flag": "on / off", "int": "number", "float": "number", "string": "text", "debug-gated": "on / off"}.get(e["parse"], e["parse"])
522
523
524def _doc_links(e, limit=3):
525    seen, out = set(), []
526    for m in e["doc_mentions"]:
527        f = m.rsplit(":", 1)[0]
528        if f in seen or f.startswith(("docs/work", "docs/paper")):
529            continue
530        seen.add(f)
531        out.append(f"[{os.path.basename(f)}]({os.path.relpath(f, 'docs').replace(os.sep, '/') if f.startswith('docs/') else '../' + f})")
532        if len(out) == limit:
533            break
534    return ", ".join(out) or "-"
535
536
537def render_page(entries):
538    optin = [e for e in entries if e.get("status") == "opt-in"]
539    roll = [e for e in entries if e.get("status") == "rollback"]
540    out = [
541        "# Engine settings",
542        "",
543        "<!-- Generated from data/settings-register.json by tools/settings_register.py --docs. Do not edit by hand; change the register. -->",
544        "",
545        "The engine reads its settings from environment variables whose names start with `STRATA_`. The Terminal and the app choose what",
546        "your hardware needs, so most people never set one. This page lists the ones meant for people: switches that are off until you",
547        "turn them on, and switches that take a newer default back to the earlier behaviour. The other settings are for measuring and",
548        "debugging and are kept in `data/settings-register.json`.",
549        "",
550        "A number or a word is set like any environment variable, for example `STRATA_KVA=1`. In the Terminal, `strata launch --set NAME=value`",
551        "puts it in the model's run configuration.",
552        "",
553        f"## Switches you can turn on ({len(optin)})",
554        "",
555        "Off unless you set them. The last column says where each one is described.",
556        "",
557        "| Setting | Value | Applies to | Described in |",
558        "|---|---|---|---|",
559    ]
560    for e in optin:
561        out.append(f"| `{e['name']}` | {_kind(e)} | {_where(e)} | {_doc_links(e)} |")
562    out += [
563        "",
564        f"## Switches that go back to earlier behaviour ({len(roll)})",
565        "",
566        "These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which",
567        "version made it the default.",
568        "",
569        "| Setting | Value | Applies to | Named in the engine since | Described in |",
570        "|---|---|---|---|---|",
571    ]
572    for e in roll:
573        out.append(f"| `{e['name']}` | {_kind(e)} | {_where(e)} | {e.get('since') or '-'} | {_doc_links(e)} |")
574    out.append("")
575    return "\n".join(out)
576
577
578# ---------------------------------------------------------------- build
579
580def engine_names() -> set[str]:
581    reads, _ = scan_engine()
582    return set(reads)
583
584
585def _merge_parse(sites):
586    kinds = [s["parse"] for s in sites]
587    kind = next((k for k in ("int", "float", "flag", "string", "debug-gated") if k in kinds), "string")
588    if len(set(kinds)) > 1:
589        kind = collections.Counter(kinds).most_common(1)[0][0]
590    states = [s["default_state"] for s in sites if s["default_state"]]
591    dstate = collections.Counter(states).most_common(1)[0][0] if states else None
592    dflts = [s["code_default"] for s in sites if s["code_default"] and s["parse"] in ("int", "float")]
593    dflt = collections.Counter(dflts).most_common(1)[0][0] if dflts else None
594    return kind, dstate, dflt
595
596
597def build(with_git=True):
598    reads, esets = scan_engine()
599    names = set(reads)
600    lsets, lreads, lnamed = scan_launch(names)
601    edefs = scan_engine_defaults(names)
602    docs = scan_docs(names)
603    git = scan_git(names) if with_git else {}
604    old = {}
605    if REGISTER.exists():
606        try:
607            old = {e["name"]: e for e in json.loads(REGISTER.read_text(encoding="utf-8"))["settings"]}
608        except (OSError, ValueError, KeyError):
609            old = {}
610    entries = []
611    for nm in sorted(names):
612        sites = reads[nm]
613        kind, dstate, dflt = _merge_parse(sites)
614        backends = sorted({s["backend"] for s in sites})
615        e = {
616            "name": nm,
617            "backends": backends,
618            "reads": [{"file": s["file"], "line": s["line"], "backend": s["backend"], "fn": s["fn"]} for s in sites],
619            "parse": kind,
620            "default_state": dstate,
621            "code_default": dflt,
622            "engine_sets": esets.get(nm, []),
623            "engine_defaults": edefs.get(nm, []),
624            "launch_files": sorted(lnamed.get(nm, [])),
625            "launch_sets": lsets.get(nm, []),
626            "launch_reads": lreads.get(nm, []),
627            "doc_mentions": docs.get(nm, []),
628        }
629        if with_git:
630            e.update(git.get(nm, {}))
631        elif nm in old:
632            for k in ("first_commit", "first_date", "since", "last_commit", "last_date"):
633                if k in old[nm]:
634                    e[k] = old[nm][k]
635        for k in HAND_FIELDS:
636            e[k] = old.get(nm, {}).get(k, "")
637        entries.append(e)
638    # entries that the engine no longer reads but were retired on purpose stay (status "retired" with retired_in)
639    for nm, o in sorted(old.items()):
640        if nm not in names and o.get("status") == "retired" and o.get("retired_in"):
641            entries.append(o)
642    entries.sort(key=lambda e: e["name"])
643    return {"version": 1, "scanned": list(ENGINE_DIRS), "launch": list(LAUNCH_PATHS), "statuses": list(STATUSES), "settings": entries}
644
645
646def write(doc):
647    REGISTER.parent.mkdir(parents=True, exist_ok=True)
648    REGISTER.write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")
649
650
651def main(argv=None):
652    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
653    ap.add_argument("--check", action="store_true")
654    ap.add_argument("--names", action="store_true")
655    ap.add_argument("--no-git", action="store_true")
656    ap.add_argument("--docs", action="store_true", help="write docs/SETTINGS.md from the register (opt-in and rollback entries)")
657    a = ap.parse_args(argv)
658    if a.names:
659        print("\n".join(sorted(engine_names())))
660        return 0
661    if a.check:
662        have = engine_names()
663        entries = json.loads(REGISTER.read_text(encoding="utf-8"))["settings"]
664        reg = {e["name"] for e in entries}
665        retired = {e["name"] for e in entries if e.get("status") == "retired" and e.get("retired_in")}   # kept on purpose: not read any more
666        missing, extra = sorted(have - reg), sorted(reg - have - retired)
667        for n in missing:
668            print("not in the register:", n)
669        for n in extra:
670            print("in the register, not read by the engine:", n)
671        return 1 if (missing or extra) else 0
672    if a.docs:
673        entries = json.loads(REGISTER.read_text(encoding="utf-8"))["settings"]
674        (ROOT / SETTINGS_PAGE).write_text(render_page(entries), encoding="utf-8", newline="\n")
675        print(f"wrote {ROOT / SETTINGS_PAGE}")
676        return 0
677    doc = build(with_git=not a.no_git)
678    write(doc)
679    print(f"wrote {REGISTER} with {len(doc['settings'])} settings")
680    return 0
681
682
683if __name__ == "__main__":
684    sys.exit(main())