okami.mom/strata

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

Niko1221setup seam: config_for / dsv41_config_for in strata_control, and the setup entry point in the config snapshot8feca419f

main
6.0 KiB147 linesraw
1"""Read golden files and print, as Markdown, where the entry points differ and (with --against) what changed between two sets of golden files.
2
3  python -m tests.snapshot.report                          (the golden files of this tree)
4  python -m tests.snapshot.report --golden A --against B   (A = this tree's, B = another tree's, e.g. the branch f-0213-df2ux)
5"""
6
7from __future__ import annotations
8
9import argparse
10import collections
11import json
12import sys
13from pathlib import Path
14
15from .matrix import ENTRY_POINTS, MACHINES, MODEL_SETS
16
17GOLDEN = Path(__file__).resolve().parent / "golden"
18
19#: config keys and variables that differ between the Terminal and the app by design: where things live and who they belong to (not what the engine runs).
20IDENTITY_KEYS = {"port", "api_key", "aliases", "log", "mcp", "engine_ready_s", "fit_max_tokens"}
21
22
23def load(root: Path):
24    out = {}
25    for m in MACHINES:
26        for s in MODEL_SETS:
27            p = root / m.key / f"{s.key}.json"
28            if p.is_file():
29                out[(m.key, s.key)] = json.loads(p.read_text(encoding="utf-8"))["entries"]
30    return out
31
32
33def flags(argv):
34    out, i = [], 0
35    while i < len(argv):
36        if argv[i].startswith("--") and i + 1 < len(argv) and not argv[i + 1].startswith("--"):
37            out.append((argv[i], argv[i + 1]))
38            i += 2
39        else:
40            out.append((argv[i], None))
41            i += 1
42    return out
43
44
45def drafter(rec) -> str:
46    eng = rec.get("engine")
47    if not eng:
48        return "not driven" if rec.get("not_driven") else "?"
49    a = eng["argv"]
50    if "--dspark" in a:
51        return "DSpark " + a[a.index("--dspark") + 1]
52    if "--draft" in a:
53        pack = a[a.index("--draft-model") + 1]
54        return "DFlash2 %s conf %s spec %s" % ("tuned" if "strata1" in pack else "stock", a[a.index("--draft-conf") + 1], a[a.index("--spec") + 1])
55    return "MTP" if "--mtp" in a else "none"
56
57
58def table(data) -> list[str]:
59    lines = ["| machine class | set | Terminal launch | app plain Load | app Models-screen Load | same? |", "|---|---|---|---|---|---|"]
60    for m in MACHINES:
61        for s in MODEL_SETS:
62            e = data.get((m.key, s.key))
63            if not e:
64                continue
65            la, pl, mo = drafter(e["launch"]), drafter(e["app_plain"]), drafter(e["app_models"])
66            lines.append(f"| {m.key} | {s.key} | {la} | {pl} | {mo} | {'yes' if la == pl == mo else '**NO**'} |")
67    return lines
68
69
70def differences(data, a="launch", b="app_plain"):
71    kinds = collections.defaultdict(list)
72    for (mk, sk), e in data.items():
73        A, B = e[a], e[b]
74        fa, fb = set(flags(A["engine"]["argv"])), set(flags(B["engine"]["argv"]))
75        for x in sorted(fa - fb, key=str):
76            kinds[("argument", f"only in {a}: {' '.join(v for v in x if v)}")].append(f"{mk}/{sk}")
77        for x in sorted(fb - fa, key=str):
78            kinds[("argument", f"only in {b}: {' '.join(v for v in x if v)}")].append(f"{mk}/{sk}")
79        ea, eb = A["engine"]["env_set"], B["engine"]["env_set"]
80        for k in sorted(set(ea) | set(eb)):
81            if ea.get(k) != eb.get(k):
82                kinds[("environment", f"{k}: {a} {ea.get(k, '<unset>')} | {b} {eb.get(k, '<unset>')}")].append(f"{mk}/{sk}")
83        ca, cb = A["config_file"], B["config_file"]
84        for k in sorted(set(ca) | set(cb)):
85            if k in ("args", "args_derived", "args_written"):
86                continue
87            if ca.get(k, "<absent>") != cb.get(k, "<absent>"):
88                kind = "identity/location" if k in IDENTITY_KEYS else "config key"
89                kinds[(kind, f"{k}: {a} {short(ca.get(k, '<absent>'))} | {b} {short(cb.get(k, '<absent>'))}")].append(f"{mk}/{sk}")
90        if [f["file"] for f in A.get("fetches") or []] != [f["file"] for f in B.get("fetches") or []]:
91            kinds[("download", f"drafter fetched: {a} vs {b}")].append(f"{mk}/{sk}")
92    return kinds
93
94
95def short(v) -> str:
96    s = json.dumps(v) if not isinstance(v, str) else v
97    s = s.replace("<ROOT>", "").replace("/local/Strata/launch/", "launch/")
98    return s if len(s) < 48 else s[:45] + "..."
99
100
101def render_differences(data, a, b) -> list[str]:
102    kinds = differences(data, a, b)
103    lines = [f"### {a} vs {b}", "", "| kind | difference | cells |", "|---|---|---|"]
104    for (kind, text), cells in sorted(kinds.items()):
105        shown = ", ".join(cells[:3]) + (f" ... ({len(cells)})" if len(cells) > 3 else "")
106        lines.append(f"| {kind} | {text} | {shown} |")
107    if not kinds:
108        lines.append("| - | none | - |")
109    return lines + [""]
110
111
112def changed(a, b) -> list[str]:
113    cnt = collections.defaultdict(list)
114    for key in sorted(a):
115        for entry in ENTRY_POINTS:
116            ra, rb = a[key].get(entry), (b.get(key) or {}).get(entry)
117            if ra != rb:
118                parts = sorted(k for k in set(ra or {}) | set(rb or {}) if (ra or {}).get(k) != (rb or {}).get(k))
119                cnt[(entry, tuple(parts))].append("%s/%s" % key)
120    lines = ["| entry | what changed | cells |", "|---|---|---|"]
121    for (entry, parts), cells in sorted(cnt.items()):
122        lines.append(f"| {entry} | {', '.join(parts)} | {len(cells)}: {', '.join(cells[:4])}{' ...' if len(cells) > 4 else ''} |")
123    return lines
124
125
126def main(argv=None) -> int:
127    ap = argparse.ArgumentParser()
128    ap.add_argument("--golden", default=str(GOLDEN))
129    ap.add_argument("--against")
130    a = ap.parse_args(argv)
131    data = load(Path(a.golden))
132    print("## Drafter each entry point starts the engine with\n")
133    print("\n".join(table(data)) + "\n")
134    print("## Where the entry points differ\n")
135    for x, y in (("launch", "app_plain"), ("launch", "app_models"), ("app_models", "app_plain")):
136        print("\n".join(render_differences(data, x, y)))
137    if a.against:
138        other = load(Path(a.against))
139        print("## Changes between the two sets of golden files\n")
140        print("\n".join(changed(data, other)) + "\n")
141        print("## The other set's drafter table\n")
142        print("\n".join(table(other)) + "\n")
143    return 0
144
145
146if __name__ == "__main__":
147    sys.exit(main())