From ce6a5b89b9fc0a7fab818a2d2947e0e4783286e0 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:04:18 -0700 Subject: [PATCH 1/8] Item 1: a model id read into maker, line, class and version (tier words are data); unknown when it cannot be read with confidence. done / next: facts (item 2) Co-Authored-By: Claude Sonnet 5.5 --- canon/model-words.json | 5 + sisi/modelid.py | 205 +++++++++++++++++++++++++++++++++++++++++ tests/test_modelid.py | 119 ++++++++++++++++++++++++ 3 files changed, 329 insertions(+) create mode 100644 canon/model-words.json create mode 100644 sisi/modelid.py create mode 100644 tests/test_modelid.py diff --git a/canon/model-words.json b/canon/model-words.json new file mode 100644 index 0000000..07fb29f --- /dev/null +++ b/canon/model-words.json @@ -0,0 +1,5 @@ +{ + "about": "Words that appear in model ids. They are data, not code: edit this file when a maker invents a new tier word. A tier word names the class of a model inside its line (it comes before or after the version number; no tier word means the line's standard model). An ignored word is neither the line nor the class (a stage, a price label, a style). A word in neither list that follows the version is a word this file does not know, so the class of that model is reported as unknown until the lead agent records it with `sisi workers fact WORKER --class NAME --source S`.", + "tiers": ["air", "base", "code", "coder", "fast", "flash", "full", "highspeed", "large", "lite", "max", "medium", "micro", "mini", "nano", "plus", "pro", "small", "tiny", "turbo", "ultra"], + "ignore": ["beta", "chat", "contributor", "default", "exp", "experimental", "free", "instruct", "latest", "new", "preview", "rc", "stable", "thinking"] +} diff --git a/sisi/modelid.py b/sisi/modelid.py new file mode 100644 index 0000000..a2ad2cf --- /dev/null +++ b/sisi/modelid.py @@ -0,0 +1,205 @@ +"""Reading a model id: its maker, line, class and version. Pure: no file access, no clock. + +A first guess from the name alone, and the recorded facts that override it. The words that mark +a class (tier words) or mean nothing (ignored words) are data passed in, loaded from +canon/model-words.json by the caller. + +What is read from an id (the part after the provider, case aside): + version the numbers in it, as a tuple compared numerically (5.10 is newer than 5.9); a date in it + (20261101 or 2026-11-01) is kept apart and compared as a date. A letter in front of a number + (v4.1, k2.7) is a marker and is dropped. + line the name words before the version that identify the model line (the maker's own name leading + them is dropped: "abc-flash-5.4" and "abc-5.4-flash" both have no extra line name). + class the tier words, before or after the version, or "standard" when there is none. The class + label for ordering and display adds the line when there is one: "wonder", "wonder-full". + maker a recorded maker fact, else the first name word. +An id with no version, or with a word after the version that the data does not know, cannot be read +with confidence: its class is "unknown" and it takes part in no comparison of versions. + +A recorded fact (class, family, released, maker) always beats the reading. A bare host alias with no +version in it (the host resolves it to its current model of that class) counts as the newest version +of its class, once a class fact says which class that is. +""" +import re + +STANDARD = "standard" +UNKNOWN = "unknown" +_DATE = re.compile(r"(? 1 or not names): + names.append(prefix) + number(num) + elif _SUFFIXED.fullmatch(t): + num, suffix = _SUFFIXED.fullmatch(t).groups() + number(num) + if suffix in ignored: + continue + word(suffix) + elif _WORD.fullmatch(t): + word(t) + else: + unknown.append(t) + if started: + closed = True + first = names[0] if names else "" + mk = (str(maker).lower() if maker else first) + line = list(names) + if line and line[0] == mk: + line = line[1:] + cls = "-".join(tiers) if tiers else STANDARD + version = tuple(nums) + date = max(dates) if dates else None + confident = bool(names) and bool(version or date) and not unknown + return {"maker": mk, "line": "-".join(line), "family": "-".join(names), "tiers": tuple(tiers), + "class": cls if confident else UNKNOWN, "label": _label("-".join(line), cls) if confident else UNKNOWN, + "version": version or None, "date": date, "confident": confident, "unknown_tokens": unknown} + + +def _label(line, cls): + """The class as the maker's classes are listed: the line name and the tier, or "standard".""" + if cls in (None, "", STANDARD): + return line or STANDARD + return "%s-%s" % (line, cls) if line else cls + + +def _normal_class(line, cls): + """A recorded class, lower case, with the line name taken off when the lead agent wrote the whole label.""" + c = str(cls or "").strip().lower() + if c in (line, "") and line: + return STANDARD + if line and c.startswith(line + "-"): + return c[len(line) + 1:] + return c or STANDARD + + +def resolve(worker, words, fact=None, host_native=False, maker_hint=None): + """The model's identity: parse the id, then let a recorded fact override it. Returns + {key, maker, line, class, label, version, date, released, alias, source} + source is "fact" (recorded), "guess" (read from the id, not yet confirmed) or "unknown" + (no key: the model takes part in no comparison of versions).""" + fact = fact if isinstance(fact, dict) else {} + p = parse(worker, words, maker=fact.get("maker") or maker_hint) + released = str(fact["released"]) if fact.get("released") else None + maker = p["maker"] + line = str(fact["family"]).strip().lower() if fact.get("family") else p["line"] + if fact.get("family") and line == maker: + line = "" + out = {"key": None, "maker": maker, "line": line, "class": UNKNOWN, "label": UNKNOWN, "version": p["version"], + "date": p["date"], "released": released, "alias": False, "source": UNKNOWN} + if fact.get("class"): + cls = _normal_class(line, fact["class"]) + out.update(source="fact") + elif p["confident"]: + cls = p["class"] + out.update(source="guess") + else: + return out + out.update({"class": cls, "label": _label(line, cls), "key": (maker, line, cls)}) + if host_native and not (p["version"] or p["date"]) and out["source"] == "fact": + out["alias"] = True + return out + + +def compare(a, b): + """1 when a is the more recently released model, -1 when b is, 0 when equal or unknowable. A recorded + release date on both decides; else the version numbers on both; else the dates in the ids on both. A bare + alias is the newest of its class.""" + if a.get("alias") or b.get("alias"): + return (1 if a.get("alias") else 0) - (1 if b.get("alias") else 0) + ra, rb = a.get("released"), b.get("released") + if ra and rb and ra != rb: + return 1 if ra > rb else -1 + va, vb = a.get("version"), b.get("version") + if va and vb: + n = max(len(va), len(vb)) + pa, pb = tuple(va) + (0,) * (n - len(va)), tuple(vb) + (0,) * (n - len(vb)) + if pa != pb: + return 1 if pa > pb else -1 + da, db = a.get("date"), b.get("date") + if da and db and da != db: + return 1 if da > db else -1 + return 0 + if not va and not vb: + da, db = a.get("date"), b.get("date") + if da and db and da != db: + return 1 if da > db else -1 + return 0 + + +def recency_key(l): + """A tuple that sorts the more recently released first, for tie-breaks: recorded release date, then version + inside one line (the line first, so versions of different lines are never compared), then the id's date.""" + if not l: + return (0, 0, "", (), 0) + rel = l.get("released") or "" + days = int(rel[0:4]) * 372 + int(rel[5:7]) * 31 + int(rel[8:10]) if len(rel) >= 10 and rel[:4].isdigit() else 0 + ver = tuple(-x for x in (tuple(l.get("version") or ()) + (0,) * 6)[:6]) + d = l.get("date") or "" + dd = int(d[0:4]) * 372 + int(d[5:7]) * 31 + int(d[8:10]) if len(d) >= 10 else 0 + return (0 if l.get("alias") else 1, -days, "|".join(l.get("key") or ()), ver, -dd) diff --git a/tests/test_modelid.py b/tests/test_modelid.py new file mode 100644 index 0000000..d619166 --- /dev/null +++ b/tests/test_modelid.py @@ -0,0 +1,119 @@ +"""Reading a model id: maker, line, class, version, and which of two is the more recently released. +Fixtures are invented ids shaped like real ones. Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" +import json, os, random, unittest +from support import * +from sisi import modelid + +WORDS = json.load(open(os.path.join(REPO, "canon", "model-words.json"))) + + +def p(worker, **kw): + return modelid.parse(worker, WORDS, **kw) + + +def r(worker, **kw): + return modelid.resolve(worker, WORDS, **kw) + + +class ParseTests(unittest.TestCase): + def test_version_line_and_class_from_the_name(self): + """R-7.2-1: the class is read from the id; no tier word means the line's standard model.""" + a = p("prov/abc-5.3") + self.assertEqual((a["maker"], a["class"], a["version"], a["confident"]), ("abc", "standard", (5, 3), True)) + self.assertEqual(p("prov/abc-5.3-flash")["class"], "flash") + + def test_a_tier_word_before_or_after_the_version_parses_the_same(self): + after, before = p("prov/abc-5.4-flash"), p("prov/abc-flash-5.4") + for k in ("maker", "line", "class", "label", "version", "confident"): + self.assertEqual(after[k], before[k], k) + + def test_versions_compare_numerically(self): + """5.10 is newer than 5.9, not older (the string order would say so).""" + self.assertGreater(modelid.compare(r("prov/abc-5.10"), r("prov/abc-5.9")), 0) + self.assertLess(modelid.compare(r("prov/abc-5.9"), r("prov/abc-5.10")), 0) + self.assertEqual(modelid.compare(r("prov/abc-5"), r("prov/abc-5.0")), 0) + + def test_a_dated_suffix_compares_as_a_date_and_does_not_disturb_the_version(self): + dated = p("prov/abc-5-4-20261101") + self.assertEqual((dated["version"], dated["date"], dated["class"]), ((5, 4), "2026-11-01", "standard")) + self.assertEqual(p("prov/abc-5.4-2026-11-01")["date"], "2026-11-01") + self.assertGreater(modelid.compare(r("prov/abc-5-4-20261101"), r("prov/abc-5.3")), 0) + self.assertEqual(modelid.compare(r("prov/abc-5-4-20261101"), r("prov/abc-5.4")), 0) + self.assertGreater(modelid.compare(r("prov/abc-5.4-20261101"), r("prov/abc-5.4-20260901")), 0) + self.assertGreater(modelid.compare(r("prov/abc-20261101"), r("prov/abc-20250301")), 0) + self.assertEqual(modelid.compare(r("prov/abc-20261101"), r("prov/abc-5.3")), 0) # not comparable + self.assertIsNone(p("prov/abc-5.4-20261345")["date"]) # not a date + + def test_two_tier_words_make_one_class_and_letter_prefixed_versions_read(self): + self.assertEqual(p("prov/abc-flash-lite-5.4")["class"], "flash-lite") + self.assertEqual(p("prov/xyz-v4.1-pro")["version"], (4, 1)) + self.assertEqual(p("prov/xyz-k2.7-code")["class"], "code") + self.assertEqual(p("prov/xyz3.8-flash")["version"], (3, 8)) + + def test_ignored_words_are_neither_line_nor_class(self): + self.assertEqual(p("prov/abc-5.4-preview-free")["class"], "standard") + self.assertEqual(p("prov/abc-5.4-flash-latest")["class"], "flash") + + def test_a_named_line_is_the_class_label(self): + """Item 7: for a maker whose lines are the classes the line name is the class label.""" + a, b = p("prov/abc-wonder-1.0"), p("prov/abc-wonder-full-1.0") + self.assertEqual((a["line"], a["label"]), ("wonder", "wonder")) + self.assertEqual((b["line"], b["class"], b["label"]), ("wonder", "full", "wonder-full")) + self.assertEqual(p("prov/abc-ember-1.0")["label"], "ember") + + def test_what_cannot_be_read_with_confidence_says_unknown(self): + """R-7.2-3: no version, or a word after the version that the data does not know: class unknown.""" + for ident in ("prov/xyz-mini", "prov/abc", "prov/abc-6.2-sol", "prov/abc-3-5-sonnet", "prov/5.4"): + got = p(ident) + self.assertFalse(got["confident"], ident) + self.assertEqual(got["class"], "unknown", ident) + self.assertIsNone(r(ident)["key"], ident) + self.assertEqual(r(ident)["source"], "unknown", ident) + + def test_tier_words_are_data_not_code(self): + """Adding a tier word to the data changes the reading; the code names none.""" + self.assertFalse(p("prov/abc-5.4-sol")["confident"]) + got = modelid.parse("prov/abc-5.4-sol", {"tiers": ["sol"], "ignore": []}) + self.assertEqual((got["class"], got["confident"]), ("sol", True)) + text = open(os.path.join(REPO, "sisi", "modelid.py")).read() + for word in WORDS["tiers"] + WORDS["ignore"]: + self.assertNotRegex(text.replace("standard", ""), r'"%s"' % word) + + def test_a_recorded_fact_beats_the_reading(self): + got = r("prov/abc-6.2-sol", fact={"class": "sol", "maker": "abc"}) + self.assertEqual((got["source"], got["class"], got["key"]), ("fact", "sol", ("abc", "", "sol"))) + flipped = r("prov/abc-5.3-flash", fact={"class": "standard"}) + self.assertEqual(flipped["class"], "standard") + self.assertEqual(r("prov/abc-5.4", fact={"family": "wonder", "class": "full"})["label"], "wonder-full") + self.assertEqual(r("prov/abc-5.4", fact={"family": "wonder", "class": "wonder-full"})["label"], "wonder-full") + self.assertEqual(r("prov/abc-5.4")["source"], "guess") + + def test_a_recorded_release_date_beats_version_numbers(self): + old_but_later = r("prov/abc-5.3", fact={"released": "2026-09-01"}) + new_but_earlier = r("prov/abc-5.4", fact={"released": "2026-03-01"}) + self.assertGreater(modelid.compare(old_but_later, new_but_earlier), 0) + self.assertGreater(modelid.compare(r("prov/abc-5.4"), r("prov/abc-5.3")), 0) + + def test_a_bare_host_alias_is_the_newest_of_its_class_once_the_class_is_recorded(self): + alias = r("abc", host_native=True, fact={"class": "standard", "maker": "abc"}) + self.assertTrue(alias["alias"]) + self.assertGreater(modelid.compare(alias, r("prov/abc-9.9")), 0) + self.assertEqual(alias["key"], r("prov/abc-5.3")["key"]) + unrecorded = r("abc", host_native=True) + self.assertFalse(unrecorded["alias"]) + self.assertIsNone(unrecorded["key"]) + + def test_the_parser_never_raises_and_compare_is_antisymmetric(self): + rng = random.Random(7) + pool = ["abc", "xyz", "5", "4", "10", "3.2", "flash", "mini", "pro", "preview", "20261101", "v2", "k3", "x", "", "-", "70b", "sol", "4o", "2026", "11", "01"] + for _ in range(500 * ITERS): + ident = "prov/" + "-".join(rng.choice(pool) for _ in range(rng.randint(0, 6))) + a, b = r(ident), r("prov/" + "-".join(rng.choice(pool) for _ in range(rng.randint(0, 6)))) + self.assertEqual(modelid.compare(a, b), -modelid.compare(b, a), ident) + if a["source"] == "unknown": + self.assertIsNone(a["key"]) + modelid.recency_key(a) + + +if __name__ == "__main__": + unittest.main() From 8141d2e281dd5ae3922006b9ab1f92ab708dd187 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:05:53 -0700 Subject: [PATCH 2/8] Item 2: class, family and release date recorded by the lead agent (sisi workers fact --class/--family/--released) beat the parser; sisi workers shows maker, class and recency of each routable worker, marks guesses. done / next: supersession and the one asking line (item 3) Co-Authored-By: Claude Sonnet 5.5 --- sisi/helptext.py | 2 +- sisi/workers.py | 126 ++++++++++++++++++++++++++++++++++-- tests/test_worker_models.py | 74 +++++++++++++++++++++ 3 files changed, 194 insertions(+), 8 deletions(-) create mode 100644 tests/test_worker_models.py diff --git a/sisi/helptext.py b/sisi/helptext.py index 8b9209a..0039aca 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -31,7 +31,7 @@ LONG = { 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score); --learning prints only the learning report', 'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library', 'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "" best-matching recipe', - 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', + 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --class NAME [--family NAME] [--released DATE] --source S the class, line and release date you decided for a model; beats the parser\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', 'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why', 'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id', 'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only', diff --git a/sisi/workers.py b/sisi/workers.py index 41cbc13..e250e5b 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -21,6 +21,12 @@ Personal files (all in the personal data folder): model-strength.json worker facts (benchmark standing, a published figure; never the measured accepted rate): {"models": {"": {"standing": 0..100, "source": text, "date": "YYYY-MM-DD"}}} + worker-models.json what the lead agent decided about each model: {"models": {"": + {"class": name, "family": name, "maker": name, "released": "YYYY-MM-DD", + "source": text, "date": "YYYY-MM-DD"}}, "classes": {"": {"order": [class, + most capable first], "source": text, "date": "YYYY-MM-DD"}}}, written by + `sisi workers fact --class ...` and `sisi workers classes`. A recorded + fact always beats what the parser reads from the id (sisi/modelid.py). worker-prefs.json the user's own routing constraints: {"avoid": [{"pattern", "why"}], "prefer": [...], "only": [{"provider", "patterns", "why"}]}, written by `sisi workers avoid|prefer|only` @@ -33,7 +39,7 @@ researched when they are missing or old. No price, score or model name ships in import datetime, json, os, re, shutil, statistics, subprocess, sys, time, uuid from . import brief as brief_contract -from . import paths, routing, store +from . import modelid, paths, routing, store LIST_TIMEOUT_S = 30 DEFAULT_REFRESH_AFTER_S = 24 * 3600 @@ -568,6 +574,28 @@ def entry_cost(entry): return float(single) if isinstance(single, (int, float)) and not isinstance(single, bool) else None +def models_path(): + return _data_file("worker-models.json") + + +def load_model_facts(): + """({worker or model: class fact}, {maker: class order}) from worker-models.json.""" + d = read_json(models_path()) + models = d.get("models") if isinstance(d.get("models"), dict) else {} + classes = d.get("classes") if isinstance(d.get("classes"), dict) else {} + return models, classes + + +_WORDS = [] + + +def model_words(): + """The tier words and ignored words in canon/model-words.json (data the parser reads; cached).""" + if not _WORDS: + _WORDS.append(read_json(paths.canon("model-words.json"))) + return _WORDS[0] + + def route_floors(): """{difficulty: percent of the best usable standing needed} from `route.standing_floor`.""" return routing.standing_floors(route_cfg().get("standing_floor")) @@ -615,10 +643,11 @@ def build_candidates(disc=None, records=None): records = read_records() if records is None else records prices = load_prices() prior = load_strength_prior() + model_facts = load_model_facts()[0] disc_tools = disc.get("tools") or [] cands, seen = [], set() - def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None): + def add(tool, model, usable=True, reason=None, allowance=None, tool_plan=None, host_native=False): worker = _canonical(tool, model) if tool else str(model) if worker.lower() in seen: return None @@ -628,7 +657,11 @@ def build_candidates(disc=None, records=None): prior_entry = next((prior[k] for k in (worker, model) if k and isinstance(prior.get(k), dict)), {}) standing = standing_of(prior_entry) - c = {"worker": worker, "tool": tool, "model": model, + fact = next((model_facts[k] for k in (worker, model) if k and isinstance(model_facts.get(k), dict)), {}) + maker_fact = price.get("maker") or prior_entry.get("maker") or fact.get("maker") + lineage = modelid.resolve(worker, model_words(), fact=dict(fact, maker=maker_fact) if maker_fact else fact, + host_native=host_native) + c = {"worker": worker, "lineage": lineage, "tool": tool, "model": model, "maker": price.get("maker") or prior_entry.get("maker") or routing.maker_of(model or worker), "plan": price.get("plan") or tool_plan, "cost": cost, @@ -664,7 +697,7 @@ def build_candidates(disc=None, records=None): if "/" not in str(w): # No provider prefix: the host tool's own subagent model. It needs no discovered # command-line tool and is usable unless marked down (routing checks that). - c = add(None, str(w), usable=True) + c = add(None, str(w), usable=True, host_native=True) if c is not None: c["host_native"] = True alias_set.add(str(w).lower()) @@ -777,7 +810,7 @@ def notes_for(candidates_by_worker, chosen, passed, notes=None, limit=5): DATA_FILES = ("delegations.jsonl", "worker-availability.json", "worker-prices.json", - "model-strength.json", "worker-prefs.json", "worker-notes.json") + "model-strength.json", "worker-prefs.json", "worker-notes.json", "worker-models.json") def _data_state(): @@ -1376,6 +1409,36 @@ def _price_lines(tool_name, models, prices, shown_keys=None): return lines +def _recency_text(l): + if l.get("alias"): + return "newest of its class (a bare host alias)" + bits = [] + if l.get("released"): + bits.append("released %s (recorded)" % l["released"]) + if l.get("version"): + bits.append("version %s" % ".".join(str(x) for x in l["version"])) + if l.get("date"): + bits.append("dated %s" % l["date"]) + return ", ".join(bits) or "no version or date in the id" + + +def model_lines(cands, limit=40): + """One line per routable worker: its maker, class (recorded, or a guess read from the id, or unknown) and + how recent it is. Workers whose class is only a guess say so; unknown ones say how to record it.""" + out = [] + for c in sorted(cands, key=lambda c: c["worker"]): + l = c.get("lineage") or {} + if l.get("source") == "unknown" or not l: + what = "class unknown: the id does not say it with confidence" + else: + what = "maker %s, class %s (%s)" % (l["maker"], l["label"], "recorded" if l["source"] == "fact" + else "a guess read from the id") + out.append(" %s: %s; %s" % (c["worker"], what, _recency_text(l))) + if len(out) > limit: + out = out[:limit] + [" ... and %d more" % (len(out) - limit)] + return out + + def cmd_workers(args=()): args = list(args) if args[:1] == ["fact"]: @@ -1444,6 +1507,12 @@ def cmd_workers(args=()): for standing, worker, entry in standings: print(" benchmark standing %g - %s: %s (%s)" % (standing, worker, entry.get("source") or "no source stated", entry.get("date") or "no date stated")) + routable, cold, _excluded = routable_candidates(build_candidates(disc, records), records) + if routable and not cold: + print("Model lines (the class of each routable worker; a guess is read from the id alone: confirm it " + "with `sisi workers fact WORKER --class NAME --source S`):") + for line in model_lines(routable): + print(line) down_now = [(k, v) for k, v in sorted(avail.items()) if isinstance(v, dict)] for k, v in down_now: if k in {t["name"] for t in disc.get("tools") or []}: @@ -1880,7 +1949,9 @@ def _cmd_import(args): def _cmd_fact(args): usage = ("usage: sisi workers fact WORKER --price-in N --price-out N [--plan flat|per-use] [--maker M] --source S [--date YYYY-MM-DD]\n" " sisi workers fact WORKER --price N (one blended figure) [--plan ...] [--maker M] --source S\n" - " sisi workers fact WORKER --standing 0..100 --source S [--date YYYY-MM-DD] (--score is the old name)") + " sisi workers fact WORKER --standing 0..100 --source S [--date YYYY-MM-DD] (--score is the old name)\n" + " sisi workers fact WORKER --class NAME [--family NAME] [--maker M] [--released YYYY-MM-DD] --source S\n" + " (the class, family and release date the lead agent decided for a model; a recorded fact beats the parser)") if not args: print(usage) return 1 @@ -1897,10 +1968,13 @@ def _cmd_fact(args): if not (price_ok and in_ok and out_ok and standing_ok and old_ok): print(usage) return 1 + model_fact = _model_fact_args(args) + if model_fact is False: + return 1 if (price_in is None) != (price_out is None) or (price is not None and price_in is not None): print("sisi: record either --price-in with --price-out, or one blended --price, not a mix", file=sys.stderr) return 1 - if price is None and price_in is None and standing is None: + if price is None and price_in is None and standing is None and not model_fact: print(usage) return 1 if min([v for v in (price, price_in, price_out) if v is not None] or [0]) < 0: @@ -1912,6 +1986,16 @@ def _cmd_fact(args): if standing is not None and not (0 <= standing <= 100): print("sisi: --standing wants a number from 0 to 100", file=sys.stderr) return 1 + if model_fact: + data = read_json(models_path()) + models = data.get("models") if isinstance(data.get("models"), dict) else {} + entry = dict(models.get(worker) or {}) + entry.update(model_fact, source=source, date=date) + models[worker] = entry + data["models"] = models + write_json(models_path(), data) + print("recorded for %s: %s (from %s, %s)" % (worker, ", ".join("%s %s" % kv for kv in sorted(model_fact.items())), + source, date)) if price is not None or price_in is not None: plan = _opt(args, "--plan") if plan is not None and plan not in ("flat", "per-use"): @@ -1958,6 +2042,34 @@ def _cmd_fact(args): return 0 +_NAME = re.compile(r"[a-z0-9][a-z0-9.+-]*") + + +def _model_fact_args(args): + """{class, family, maker, released} from the command line, {} when none is given, False (after saying why) + when one is malformed. The maker alone belongs to a price or standing fact, so it is read here only + beside a class, family or release date.""" + out = {} + for opt, field in (("--class", "class"), ("--family", "family"), ("--released", "released")): + v = _opt(args, opt) + if v is None: + continue + v = v.strip().lower() + if field == "released": + try: + datetime.date.fromisoformat(v) + except ValueError: + print("sisi: --released wants a date as YYYY-MM-DD", file=sys.stderr) + return False + elif not _NAME.fullmatch(v): + print("sisi: %s wants a short name (letters, digits, hyphens)" % opt, file=sys.stderr) + return False + out[field] = v + if out and _opt(args, "--maker"): + out["maker"] = _opt(args, "--maker").strip().lower() + return out + + def _cmd_pref(kind, args): prefs = load_prefs() if not args: diff --git a/tests/test_worker_models.py b/tests/test_worker_models.py new file mode 100644 index 0000000..94acece --- /dev/null +++ b/tests/test_worker_models.py @@ -0,0 +1,74 @@ +"""Model lines in the worker commands: the class a lead agent records beats the parser, and `sisi workers` +shows maker, class and recency for each routable worker. Fixtures are invented ids shaped like real ones. +Requirement ids: R-7.2-1, R-7.2-3.""" +import json, os, unittest +from support import * + + +class ModelCase(SisiCase): + def seed(self, spec, type="impl", difficulty=2): + """spec: [(worker, attempts, accepted)]""" + os.makedirs(self.data, exist_ok=True) + n = len(self.rows()) + with open(os.path.join(self.data, "delegations.jsonl"), "a") as f: + for worker, attempts, accepted in spec: + for i in range(attempts): + n += 1 + f.write(json.dumps({"kind": "attempt", "id": "m%d" % n, "ts": 1760000000 + n, "project": "p", + "type": type, "difficulty": difficulty, "worker": worker, + "outcome": "accepted" if i < accepted else "rejected", + "check": "tests", "minutes": 5}) + "\n") + + def rows(self): + p = os.path.join(self.data, "delegations.jsonl") + return open(p).read().splitlines() if os.path.exists(p) else [] + + def env(self): + return dict(PATH="") + + def listing(self): + r = self.sisi("workers", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + return r.stdout + + +class FactTests(ModelCase): + def test_a_class_fact_is_recorded_with_its_source_and_shown(self): + """R-7.2-3: the lead agent's decision about a model is stored, with its source, and shown.""" + self.seed([("prov/abc-6.2-sol", 9, 9), ("prov/abc-5.3", 9, 9)]) + before = self.listing() + self.assertIn("prov/abc-6.2-sol: class unknown", before) + self.assertIn("prov/abc-5.3: maker abc, class standard (a guess read from the id)", before) + r = self.sisi("workers", "fact", "prov/abc-6.2-sol", "--class", "sol", "--released", "2026-11-01", + "--source", "lead agent, read the maker's page", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + stored = json.load(open(os.path.join(self.data, "worker-models.json")))["models"]["prov/abc-6.2-sol"] + self.assertEqual((stored["class"], stored["released"], stored["source"]), + ("sol", "2026-11-01", "lead agent, read the maker's page")) + after = self.listing() + self.assertIn("prov/abc-6.2-sol: maker abc, class sol (recorded); released 2026-11-01 (recorded), version 6.2", after) + + def test_a_recorded_class_beats_the_parser(self): + self.seed([("prov/abc-5.3-flash", 9, 9)]) + self.assertIn("class flash (a guess", self.listing()) + self.sisi("workers", "fact", "prov/abc-5.3-flash", "--class", "standard", "--source", "lead", env=self.env()) + self.assertIn("class standard (recorded)", self.listing()) + + def test_bad_input_is_refused_and_nothing_is_recorded(self): + self.seed([("prov/abc-5.3", 9, 9)]) + for args in (("--class", "sol"), ("--class", "so l", "--source", "x"), ("--released", "next week", "--source", "x"), + ("--released", "2026-13-40", "--source", "x")): + r = self.sisi("workers", "fact", "prov/abc-5.3", *args, env=self.env()) + self.assertEqual(r.returncode, 1, args) + self.assertFalse(os.path.exists(os.path.join(self.data, "worker-models.json"))) + + def test_the_fact_file_is_committed_with_the_other_worker_data(self): + self.seed([("prov/abc-5.3", 9, 9)]) + self.sisi("workers", "fact", "prov/abc-5.3", "--class", "standard", "--source", "lead", env=self.env()) + import subprocess + out = subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True).stdout + self.assertNotIn("worker-models.json", out) + + +if __name__ == "__main__": + unittest.main() From d4ef00c4c05efc099223a7dacbd4c06405952c28 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:21:23 -0700 Subject: [PATCH 3/8] Item 3: the newest usable version of a maker's class always wins; an older one never competes while it is usable (no evidence or price exception); route.supersede_guessed; one line asks the lead agent to record a class that cannot be read. done / next: inherited records (item 4) Co-Authored-By: Claude Sonnet 5.5 --- config.default.json | 3 +- sisi/routing.py | 118 +++++++++++++--- sisi/workers.py | 26 +++- tests/test_model_supersession.py | 232 +++++++++++++++++++++++++++++++ tests/test_orchestration.py | 6 +- tests/test_worker_models.py | 79 ++++++++++- 6 files changed, 433 insertions(+), 31 deletions(-) create mode 100644 tests/test_model_supersession.py diff --git a/config.default.json b/config.default.json index 128649f..01138db 100644 --- a/config.default.json +++ b/config.default.json @@ -17,7 +17,8 @@ "2": 60, "3": 85 }, - "price_blend_input_parts": 3 + "price_blend_input_parts": 3, + "supersede_guessed": true }, "unit": { "stale_hours": 12 diff --git a/sisi/routing.py b/sisi/routing.py index 354dc6d..f28e2bc 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -44,7 +44,12 @@ The rule, in order: 6. About one low-stakes task in ten (difficulty 1, every tenth judged attempt for that kind and difficulty) goes to a cheaper worker with a thin record instead, so cheaper options keep gathering evidence. The slot is a function of the record, so the choice stays deterministic. - 7. Load balancing: within the same price tier and price, the worker that has taken the least work + 7. The newest usable version of a maker's class always wins over its older versions (see + `superseded_by`): no better record and no cheaper plan on the older version brings it back. + The older one competes again only while the newer one is unusable. The class is read from the + id and overridden by what the lead agent recorded (sisi/modelid.py); a model whose class is + unknown is never compared. + 8. Load balancing: within the same price tier and price, the worker that has taken the least work relative to its remaining allowance goes first (recorded uses divided by allowance left, an unknown allowance counting as half). Ties break on the worker id. @@ -54,6 +59,8 @@ usable worker is offered, with the explanation saying so. """ import re +from . import modelid + MIN_ATTEMPTS = 8 # below this, a worker's record for a kind and difficulty is thin MIN_ACCEPTED_RATE = 0.6 # "good enough" among workers with at least MIN_ATTEMPTS attempts CONTRADICTION_REJECTIONS = 2 # a thin record with this many rejections below the bar cancels a prior @@ -313,32 +320,71 @@ def _standing_of(c): # ---------------------------------------------------------------- the pool, then the choice -def _prepare(candidates, records, availability, now, exclude, avoid, review_of): - """The workers that may be recommended at all: (eligible, passed, stats, author_maker).""" +def _unusable(c, availability, now): + """Why a candidate cannot be used right now (plain words), or None.""" + if "contributor" in str(c.get("model") or c["worker"]).lower(): + return "its id contains 'contributor', a tier that trains on prompts" + down = _down_entry(c, availability, now) + if down is not None: + return "unavailable (%s) until its retry time" % (down.get("reason") or "down") + if not c.get("usable", True): + return c.get("reason") or "not usable now" + if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0: + return "its flat-rate allowance is spent" + return None + + +def _lineage(c): + l = c.get("lineage") + return l if isinstance(l, dict) else None + + +def _comparable(c, opts): + """The model's lineage when its class takes part in comparisons of versions: a class that could not be read + is never compared, and (with `supersede_guessed` off) neither is one that was only read from the id.""" + l = _lineage(c) + if l and l.get("key") and (l.get("source") == "fact" or (opts or {}).get("supersede_guessed", True)): + return l + return None + + +def superseded_by(pool, opts=None): + """{worker: the newest worker of its maker and class that replaces it}, over the usable `pool`. Workers + that share a maker, a line and a class are versions of one model whichever provider carries them; the + older version is replaced by the newest one whatever its record or price. Pure.""" + groups = {} + for c in pool: + l = _comparable(c, opts) + if l: + groups.setdefault(tuple(l["key"]), []).append(c) + out = {} + for group in groups.values(): + for c in group: + newer = [d for d in group if modelid.compare(_lineage(d), _lineage(c)) > 0] + if newer: + out[c["worker"]] = min(newer, key=lambda d: (modelid.recency_key(_lineage(d)), d["worker"]))["worker"] + return out + + +def _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts=None): + """The workers that may be recommended at all: (eligible, passed, stats, author_maker, superseded).""" exclude = {str(x) for x in exclude} stats = candidate_stats(candidates, records) passed = [] eligible = [] + tried = [] # usable workers already tried in this delegation: still the newest version, so older ones stay out for c in candidates: w = c["worker"] + why = _unusable(c, availability, now) if w in exclude: passed.append((w, "already tried in this delegation")) - continue - if "contributor" in str(c.get("model") or w).lower(): - passed.append((w, "its id contains 'contributor', a tier that trains on prompts")) - continue - down = _down_entry(c, availability, now) - if down is not None: - passed.append((w, "unavailable (%s) until its retry time" % (down.get("reason") or "down"))) - continue - if not c.get("usable", True): - passed.append((w, c.get("reason") or "not usable now")) - continue - if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0: - passed.append((w, "its flat-rate allowance is spent")) - continue - eligible.append(c) + if why is None: + tried.append(c) + elif why is not None: + passed.append((w, why)) + else: + eligible.append(c) avoided = [(c, _pattern_match(c, avoid)) for c in eligible] kept = [c for c, m in avoided if m is None] @@ -349,6 +395,7 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of): passed.append((c["worker"], "avoided by the user's own pattern %r%s" % (pat, (" (%s)" % why) if why else ""))) eligible = kept + tried = [c for c in tried if _pattern_match(c, avoid) is None] author_maker = "" if review_of: @@ -366,7 +413,15 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of): else: rest.append(c) eligible = rest - return eligible, passed, stats, author_maker + tried = [c for c in tried if (c.get("maker") or maker_of(c.get("model") or c["worker"])) != author_maker] + + superseded = superseded_by(eligible + tried, opts) + if superseded: + for c in eligible: + if c["worker"] in superseded: + passed.append((c["worker"], "superseded by %s (a newer version of the same class)" % superseded[c["worker"]])) + eligible = [c for c in eligible if c["worker"] not in superseded] + return eligible, passed, stats, author_maker, superseded def _assess_all(eligible, stats, kind, difficulty, floors): @@ -440,12 +495,13 @@ def _select(eligible, assessments, difficulty): def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(), - avoid=None, prefer=None, floors=None): + avoid=None, prefer=None, floors=None, opts=None): """Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker", ...}. `passed_over` is [(worker, plain reason)] covering every candidate not chosen. `avoid` and `prefer` are the user's own [{"pattern", "why"}] constraints; `floors` the standing floors.""" now = float(now or 0) - eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of) + eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude, + avoid, review_of, opts) assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer) @@ -511,9 +567,24 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}, "assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first, "best_standing": best, "passed_detail": detail, "floors": floors, + "superseded": superseded, "class_ask": class_ask(eligible), "kind": kind, "difficulty": difficulty} +def class_ask(eligible): + """What the lead agent should be asked to record, because it is about to matter: {"classify": [workers]}. + A worker whose class could not be read from its id, when another usable worker has the same maker (the two + may be versions of one class). A class read from the id with confidence is not asked about; a recorded one + never is.""" + makers = {} + for c in eligible: + l = _lineage(c) + if l: + makers.setdefault(l.get("maker"), []).append(c["worker"]) + return {"classify": sorted(c["worker"] for c in eligible if _lineage(c) + and _lineage(c).get("source") == "unknown" and len(makers.get(_lineage(c).get("maker"), [])) > 1)} + + def _why_not(a, difficulty, basis, cheaper): """(plain reason, short per-worker detail) for a worker kept out of the pool by what is known about its capability. The reason text is the same for every worker it applies to, so reasons group.""" @@ -553,7 +624,7 @@ def _why_not(a, difficulty, basis, cheaper): def retry_choice(candidates, records, availability, kind, difficulty, rejected, rejections, - now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=None): + now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=None, opts=None): """Who gets a task again after `rejected` (a worker id) was rejected `rejections` times in this chain. The first retry goes back to the same worker while it is still usable and has no poor record. After that: the cheapest capable worker whose evidence is strictly better than the rejected one's, or, when there is none, @@ -561,7 +632,8 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, else is usable). Returns {"choice", "step", "assessments", ...}; step is "same", "better", "strongest" or "only", and choice is None when nobody is usable. Pure; the caller supplies facts.""" now = float(now or 0) - eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of) + eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude, + avoid, review_of, opts) assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) key, _rate, _load = _make_key(stats, kind, difficulty, prefer) out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker, diff --git a/sisi/workers.py b/sisi/workers.py index e250e5b..f4b24c6 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -596,6 +596,13 @@ def model_words(): return _WORDS[0] +def route_opts(): + """Routing options from the config: `route.supersede_guessed` (default true) lets a class read from the id with + confidence, not yet recorded by the lead agent, take part in the rule that the newest version of a class wins.""" + v = route_cfg().get("supersede_guessed") + return {"supersede_guessed": v if isinstance(v, bool) else True} + + def route_floors(): """{difficulty: percent of the best usable standing needed} from `route.standing_floor`.""" return routing.standing_floors(route_cfg().get("standing_floor")) @@ -1203,7 +1210,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev prefs = effective_prefs(kind, difficulty, cwd) result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty, review_of=review_of, now=time.time(), exclude=tried, - avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) + avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), + opts=route_opts()) cand = result["choice"] if cand is None: notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty)) @@ -1572,6 +1580,16 @@ def _route_setup(args): return kind, difficulty +def class_line(result): + """The one line asking the lead agent to determine a class sisi cannot read from the id, or None.""" + names = (result.get("class_ask") or {}).get("classify") or [] + if not names: + return None + return ("sisi: the class of %s%s cannot be read from its id: decide it and record it with " + "`sisi workers fact %s --class NAME --source S` (until then it is never compared with a newer or older version)" + % (names[0], (" and %d more" % (len(names) - 1)) if len(names) > 1 else "", names[0])) + + def cmd_route(args=()): setup = _route_setup(args) if setup is None: @@ -1585,7 +1603,8 @@ def cmd_route(args=()): candidates, limited = apply_limits(candidates, prefs) result = routing.choose(candidates, records, read_availability(), kind, difficulty, review_of=_opt(args, "--review-of"), now=time.time(), - avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors()) + avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(), + opts=route_opts()) result["passed_over"] = list(result["passed_over"]) + limited by_worker = {c["worker"]: c for c in everyone} down = _down_now(read_availability(), time.time()) @@ -1611,6 +1630,9 @@ def cmd_route(args=()): for line in notes_for(by_worker, result["choice"], result["passed_over"] if explain else [], limit=5 if explain else max(1, 5 - head)): print(line) + ask = class_line(result) + if ask: + print(ask) if explain: for line in routing.explain_choice(result, kind, difficulty): print(line) diff --git a/tests/test_model_supersession.py b/tests/test_model_supersession.py new file mode 100644 index 0000000..199c57a --- /dev/null +++ b/tests/test_model_supersession.py @@ -0,0 +1,232 @@ +"""The newest usable version of a maker's class always wins over its older versions (hard rule), however good the +older record or cheap its plan. Pure routing tests over invented ids shaped like real ones. +Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" +import json, os, random, unittest +from support import * +from sisi import modelid, routing + +WORDS = json.load(open(os.path.join(REPO, "canon", "model-words.json"))) +NOW = 1000000.0 + + +def cand(worker, plan="per-use", cost=1.0, fact=None, host_native=False, standing=None, **kw): + model = worker.rsplit("/", 1)[-1] + c = {"worker": worker, "tool": worker.split("/")[0] if "/" in worker else None, "model": model, "maker": "abc", + "plan": plan, "cost": cost, "allowance_pct_left": None, "usable": True, "standing": standing, + "aliases": [worker, model], "lineage": modelid.resolve(worker, WORDS, fact=fact, host_native=host_native)} + c.update(kw) + return c + + +def attempts(worker, n, good, kind="impl", difficulty=1, start=0): + return [{"kind": "attempt", "id": "%s-%d-%d" % (worker, difficulty, start + i), "type": kind, "difficulty": difficulty, + "worker": worker, "outcome": "accepted" if i < good else "rejected", "check": "tests", "ts": NOW - 10} + for i in range(n)] + + +def pick(cands, records=(), difficulty=1, availability=None, **kw): + r = routing.choose(cands, list(records), availability or {}, "impl", difficulty, now=NOW, **kw) + return (r["choice"] or {}).get("worker"), r + + +class SupersessionTests(unittest.TestCase): + def test_the_newer_version_wins_over_an_older_one_with_a_better_record_and_a_cheaper_plan(self): + """The owner's rule: no evidence exception, no price exception.""" + old = cand("prov/abc-5.3", plan="flat", cost=0.0) + new = cand("prov/abc-5.4", plan="per-use", cost=9.0) + records = attempts("prov/abc-5.3", 30, 30, difficulty=1) + who, r = pick([old, new], records) + self.assertEqual(who, "prov/abc-5.4") + self.assertIn(("prov/abc-5.3", "superseded by prov/abc-5.4 (a newer version of the same class)"), r["passed_over"]) + + def test_numeric_version_order(self): + self.assertEqual(pick([cand("prov/abc-5.9"), cand("prov/abc-5.10")])[0], "prov/abc-5.10") + self.assertEqual(pick([cand("prov/abc-5.3"), cand("prov/abc-5-4-20261101")])[0], "prov/abc-5-4-20261101") + + def test_the_tier_word_before_or_after_the_version_is_one_class(self): + self.assertEqual(pick([cand("prov/abc-5.3-flash"), cand("prov/abc-flash-5.4")])[0], "prov/abc-flash-5.4") + + def test_different_classes_never_supersede_each_other(self): + flash, std = cand("prov/abc-5.3-flash", cost=0.1), cand("prov/abc-5.4", cost=5.0) + who, r = pick([flash, std]) + self.assertEqual(who, "prov/abc-5.3-flash") # the cheaper class still competes + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + def test_two_named_lines_of_one_maker_are_different_classes(self): + a, b = cand("prov/abc-wonder-1.0", cost=1.0), cand("prov/abc-ember-1.3", cost=2.0) + who, r = pick([a, b]) + self.assertEqual(who, "prov/abc-wonder-1.0") + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + def test_unknown_class_never_supersedes_or_is_superseded(self): + a, b = cand("prov/abc-6.2-sol", cost=1.0), cand("prov/abc-6.3-sol", cost=2.0) + self.assertIsNone(a["lineage"]["key"]) + who, r = pick([a, b]) + self.assertEqual(who, "prov/abc-6.2-sol") + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + def test_a_recorded_class_makes_an_unknown_one_comparable(self): + fact = {"class": "sol", "maker": "abc"} + a, b = cand("prov/abc-6.2-sol", fact=fact, cost=1.0), cand("prov/abc-6.3-sol", fact=fact, cost=2.0) + self.assertEqual(pick([a, b])[0], "prov/abc-6.3-sol") + + def test_the_newer_one_unusable_lets_the_older_compete_again(self): + old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) + self.assertEqual(pick([old, new], availability={"prov/abc-5.4": {"reason": "limit", "retry_at": NOW + 99}})[0], "prov/abc-5.3") + new2 = dict(new, usable=False, reason="not logged in") + self.assertEqual(pick([old, new2])[0], "prov/abc-5.3") + self.assertEqual(pick([old, new], avoid=[{"pattern": "5.4"}])[0], "prov/abc-5.3") + spent = dict(new, plan="flat", allowance_pct_left=0) + self.assertEqual(pick([old, spent])[0], "prov/abc-5.3") + + def test_a_tried_newer_version_does_not_send_a_retry_back_to_the_older(self): + old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) + who, r = pick([old, new], exclude=["prov/abc-5.4"]) + self.assertIsNone(who) + + def test_a_newer_version_with_a_thick_bad_record_never_sends_work_back_to_the_older(self): + old, new, other = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0), cand("prov/xyz-2.0", cost=3.0, maker="xyz") + records = attempts("prov/abc-5.4", 10, 1, difficulty=1) + attempts("prov/xyz-2.0", 10, 10, difficulty=1) + who, r = pick([old, new, other], records) + self.assertEqual(who, "prov/xyz-2.0") + who, r = pick([old, new], records) + self.assertEqual(who, "prov/abc-5.4") # nobody else: the bad newer model is still not replaced by the older + + def test_the_same_model_through_two_providers_is_one_model(self): + old_a = cand("prova/abc-5.3", plan="flat", cost=0.0) + new_a, new_b = cand("prova/abc-5.4", cost=5.0), cand("provb/abc-5.4", cost=2.0) + who, r = pick([old_a, new_a, new_b]) + self.assertEqual(who, "provb/abc-5.4") # the existing cost comparison picks the provider + self.assertEqual(sorted(w for w, why in r["passed_over"] if why.startswith("superseded")), ["prova/abc-5.3"]) + who, _ = pick([old_a, new_a, new_b], availability={"provb": {"reason": "limit", "retry_at": NOW + 9}}) + self.assertEqual(who, "prova/abc-5.4") + + def test_a_bare_host_alias_with_a_recorded_class_is_the_newest(self): + alias = cand("abc", fact={"class": "standard", "maker": "abc"}, host_native=True, cost=9.0) + versioned = cand("prov/abc-9.9", cost=0.1) + self.assertEqual(pick([alias, versioned])[0], "abc") + bare = cand("abc", host_native=True, cost=9.0) # class not recorded: no comparison + self.assertEqual(pick([bare, versioned])[0], "prov/abc-9.9") + + def test_guessed_classes_take_part_unless_the_config_says_only_recorded_ones(self): + old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) + self.assertEqual(pick([old, new])[0], "prov/abc-5.4") + self.assertEqual(pick([old, new], opts={"supersede_guessed": False})[0], "prov/abc-5.3") + fact = {"class": "standard"} + old_r, new_r = cand("prov/abc-5.3", fact=fact, cost=1.0), cand("prov/abc-5.4", fact=fact, cost=2.0) + self.assertEqual(pick([old_r, new_r], opts={"supersede_guessed": False})[0], "prov/abc-5.4") + + def test_the_asking_line_is_only_for_a_class_that_could_not_be_read(self): + a, b = cand("prov/abc-6.2-sol", cost=1.0), cand("prov/abc-6.3-luna", cost=2.0) + r = pick([a, b])[1] + self.assertEqual(sorted(r["class_ask"]["classify"]), ["prov/abc-6.2-sol", "prov/abc-6.3-luna"]) + lone = pick([cand("prov/abc-6.2-sol"), cand("prov/xyz-1.0", maker="xyz")])[1] + self.assertEqual(lone["class_ask"]["classify"], []) # no sibling of the same maker: it cannot matter + guessed = pick([cand("prov/abc-5.3"), cand("prov/abc-5.4")])[1] + self.assertEqual(guessed["class_ask"]["classify"], []) # read with confidence: no question + fact = {"class": "sol", "maker": "abc"} + settled = pick([cand("prov/abc-6.2-sol", fact=fact), cand("prov/abc-6.3-luna", fact=fact)])[1] + self.assertEqual(settled["class_ask"]["classify"], []) + + +class SupersessionPropertyTests(unittest.TestCase): + def fleet(self, rng): + cands, records, down = [], [], {} + for maker in rng.sample(["abc", "xyz", "qrs"], rng.randint(1, 3)): + for cls in rng.sample(["", "-flash", "-mini", "-wonder", "-pro"], rng.randint(1, 3)): + for ver in rng.sample(["5.3", "5.4", "5.9", "5.10", "6", "5-4-20261101", "5.4-20250101"], rng.randint(1, 4)): + for prov in rng.sample(["pa", "pb"], rng.randint(1, 2)): + w = "%s/%s%s-%s" % (prov, maker, cls, ver) + if cls == "-wonder": + w = "%s/%s-wonder-%s" % (prov, maker, ver) + if any(c["worker"] == w for c in cands): + continue + cands.append(cand(w, plan=rng.choice(["flat", "per-use", None]), + cost=rng.choice([None, 0.1, 1.0, 5.0]), maker=maker, + allowance_pct_left=rng.choice([None, 0, 50]))) + if rng.random() < 0.15: + down[w] = {"reason": "limit", "retry_at": NOW + 99} + for d in (1, 2, 3): + if rng.random() < 0.5: + n = rng.choice([3, 10, 12]) + records += attempts(w, n, rng.randint(0, n), difficulty=d) + return cands, records, down + + def usable(self, c, down): + return c["worker"] not in down and not (c["plan"] == "flat" and c["allowance_pct_left"] == 0) + + def test_the_chosen_worker_is_never_an_older_version_of_a_class_with_a_newer_usable_version(self): + """Property: whatever the fleet, ledger, plans and availability.""" + rng = random.Random(20261123) + checked = 0 + for _ in range(300 * ITERS): + cands, records, down = self.fleet(rng) + if not cands: + continue + d = rng.choice([1, 2, 3]) + who, r = pick(cands, records, d, availability=down) + if who is None: + continue + chosen = next(c for c in cands if c["worker"] == who) + lc = chosen["lineage"] + for c in cands: + if c is chosen or not self.usable(c, down): + continue + lo = c["lineage"] + if lo["key"] == lc["key"]: + self.assertLessEqual(modelid.compare(lo, lc), 0, (who, c["worker"])) + checked += 1 + for w, why in r["passed_over"]: + if why.startswith("superseded by "): + newer = why[len("superseded by "):].split(" ")[0] + a = next(c for c in cands if c["worker"] == w)["lineage"] + b = next(c for c in cands if c["worker"] == newer)["lineage"] + self.assertEqual(a["key"], b["key"], "a model never supersedes one of another maker or class") + self.assertGreater(modelid.compare(b, a), 0) + self.assertGreater(checked, 100) + + def test_adding_a_newer_version_of_the_chosen_model_never_makes_the_choice_an_older_model_of_that_class(self): + rng = random.Random(77) + done = 0 + for _ in range(200 * ITERS): + cands, records, down = self.fleet(rng) + if not cands: + continue + d = rng.choice([1, 2, 3]) + who, _r = pick(cands, records, d, availability=down) + if who is None: + continue + chosen = next(c for c in cands if c["worker"] == who) + lc = chosen["lineage"] + if not lc["version"] or lc["date"]: + continue + ver = ".".join(str(x) for x in lc["version"][:1] + (lc["version"][1] + 1 if len(lc["version"]) > 1 else 1,)) + prov = who.split("/")[0] + maker = lc["maker"] + tail = "" if lc["class"] == "standard" else "-" + lc["class"] + new_w = "pc/%s%s-%s" % (maker, tail, ver) if lc["line"] == "" else None + if new_w is None or any(c["worker"] == new_w for c in cands): + continue + new = cand(new_w, maker=chosen["maker"], cost=rng.choice([None, 0.1, 5.0])) + if new["lineage"]["key"] != lc["key"] or modelid.compare(new["lineage"], lc) <= 0: + continue + after, _ = pick(cands + [new], records, d, availability=down) + if after is None: + continue + got = next(c for c in cands + [new] if c["worker"] == after)["lineage"] + if got["key"] == lc["key"]: + self.assertGreaterEqual(modelid.compare(got, lc), 0, (who, after)) + done += 1 + self.assertGreater(done, 30) + + def test_a_result_read_as_unknown_never_triggers_supersession(self): + rng = random.Random(5) + for _ in range(200 * ITERS): + ids = ["prov/abc-%d.%d-%s" % (rng.randint(1, 9), rng.randint(0, 9), rng.choice(["sol", "luna", "astra"])) for _ in range(rng.randint(2, 5))] + cands = [cand(w, cost=rng.choice([None, 1.0, 2.0])) for w in dict.fromkeys(ids)] + who, r = pick(cands) + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_orchestration.py b/tests/test_orchestration.py index dc31833..3ce4c49 100644 --- a/tests/test_orchestration.py +++ b/tests/test_orchestration.py @@ -263,7 +263,9 @@ class RouteTests(OrchCase): self.assertIn("mechanism:", r.stdout) def _big_catalogue(self, n=2000): - names = ["m-%d" % i for i in range(n)] + ["contributor-%d" % i for i in range(40)] + # letters only: a number in an id is a version, and the newest version of a class replaces the older ones + names = ["mdl-%s" % "".join(chr(97 + (i // 26 ** k) % 26) for k in range(3)) for i in range(n)] \ + + ["contributor-%d" % i for i in range(40)] script = FAKE_TOOL.replace('echo "beta-1"; echo "beta-2";', " ".join('echo "%s";' % x for x in names)) with open(os.path.join(self.bindir, "muse"), "w") as f: f.write(script) @@ -272,7 +274,7 @@ class RouteTests(OrchCase): """R-7.2-1: --explain prints at most 20 lines and 3 example names per reason group, and still shows every reason group, however many catalogue models were passed over.""" self._big_catalogue() - self.sisi("workers", "avoid", "m-7", "--why", "fixture avoid", env=self.env()) + self.sisi("workers", "avoid", "mdl-ab", "--why", "fixture avoid", env=self.env()) r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env()) self.assertEqual(r.returncode, 0, r.stderr) lines = r.stdout.splitlines() diff --git a/tests/test_worker_models.py b/tests/test_worker_models.py index 94acece..24f393c 100644 --- a/tests/test_worker_models.py +++ b/tests/test_worker_models.py @@ -1,9 +1,19 @@ """Model lines in the worker commands: the class a lead agent records beats the parser, and `sisi workers` shows maker, class and recency for each routable worker. Fixtures are invented ids shaped like real ones. Requirement ids: R-7.2-1, R-7.2-3.""" -import json, os, unittest +import json, os, stat, unittest from support import * +FAKE_MUSE = """#!/bin/sh +case "$1" in + exec) + if [ "$2" = "--list-models" ]; then for m in $MUSE_MODELS; do echo "$m"; done; exit 0; fi + echo done ;; + *) echo help ;; +esac +exit 0 +""" + class ModelCase(SisiCase): def seed(self, spec, type="impl", difficulty=2): @@ -23,8 +33,20 @@ class ModelCase(SisiCase): p = os.path.join(self.data, "delegations.jsonl") return open(p).read().splitlines() if os.path.exists(p) else [] - def env(self): - return dict(PATH="") + def env(self, models=None): + """No tool at all, or a fake `muse` tool that lists `models`.""" + if models is None: + return dict(PATH="") + bindir = os.path.join(self.tmp, "bin") + os.makedirs(bindir, exist_ok=True) + path = os.path.join(bindir, "muse") + open(path, "w").write(FAKE_MUSE) + os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR) + return dict(PATH=bindir, MUSE_MODELS=" ".join(models)) + + def route(self, difficulty=1, *extra, models=("abc-5.3", "abc-5.4")): + r = self.sisi("route", "--kind", "impl", "--difficulty", str(difficulty), *extra, env=self.env(models)) + return r def listing(self): r = self.sisi("workers", env=self.env()) @@ -70,5 +92,56 @@ class FactTests(ModelCase): self.assertNotIn("worker-models.json", out) +class RouteSupersessionTests(ModelCase): + def setUp(self): + super().setUp() + self.priced = False + + def route(self, difficulty=1, *extra, models=("abc-5.3", "abc-5.4")): + if not self.priced: # a model is routable once it has a record, a price or a standing + self.priced = True + for w, price in (("muse/abc-5.3", "0.5"), ("muse/abc-5.4", "1")): # the older is the cheaper + self.sisi("workers", "fact", w, "--price", price, "--source", "fixture", env=self.env(models)) + return super().route(difficulty, *extra, models=models) + + def test_route_uses_the_newest_version_though_the_older_has_the_record(self): + """R-7.2-1: the newest usable version of a class is always taken; --explain says what it replaced.""" + self.seed([("muse/abc-5.3", 30, 30)], difficulty=1) + r = self.route(1, "--explain") + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout) + self.assertIn("superseded by muse/abc-5.4", r.stdout) + + def test_the_older_version_is_back_while_the_newer_is_marked_down(self): + self.seed([("muse/abc-5.3", 30, 30)], difficulty=1) + self.route(1) + self.sisi("workers", "down", "muse/abc-5.4", "--reason", "limit", "--until", "2099-01-02", env=self.env(("abc-5.3", "abc-5.4"))) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.3") + self.sisi("workers", "up", "muse/abc-5.4", env=self.env(("abc-5.3", "abc-5.4"))) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.4") + + def test_only_recorded_classes_when_the_config_says_so(self): + self.seed([("muse/abc-5.3", 30, 30)], difficulty=1) + os.makedirs(self.data, exist_ok=True) + json.dump({"route": {"supersede_guessed": False}}, open(os.path.join(self.data, "config.json"), "w")) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.3") + for w in ("muse/abc-5.3", "muse/abc-5.4"): + self.sisi("workers", "fact", w, "--class", "standard", "--source", "lead", env=self.env(("abc-5.3", "abc-5.4"))) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.4") + + def test_the_lead_agent_is_asked_once_for_a_class_that_cannot_be_read_and_then_not(self): + """A class read with confidence raises no question; an unreadable one does, in one line, until recorded.""" + models = ("abc-6.2-sol", "abc-6.3-luna") + self.seed([("muse/abc-6.2-sol", 12, 12), ("muse/abc-6.3-luna", 12, 12)], difficulty=1) + r = self.route(1, models=models) + asks = [l for l in r.stdout.splitlines() if "cannot be read from its id" in l] + self.assertEqual(len(asks), 1, r.stdout) + self.assertLessEqual(len(r.stdout.splitlines()), 7, r.stdout) + for w, c in (("muse/abc-6.2-sol", "sol"), ("muse/abc-6.3-luna", "luna")): + self.sisi("workers", "fact", w, "--class", c, "--maker", "abc", "--source", "lead", env=self.env(models)) + self.assertNotIn("cannot be read", self.route(1, models=models).stdout) + self.seed([("muse/abc-5.3", 12, 12), ("muse/abc-5.4", 12, 12)], difficulty=1) + self.assertNotIn("cannot be read", self.route(1).stdout) + + if __name__ == "__main__": unittest.main() From 64a45cfccdad6f48b7e5501f7307e2f366bc1fdb Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:24:12 -0700 Subject: [PATCH 4/8] Item 4: a new version starts from its predecessor's judged record (walks back one version at a time, never a bad record, never over its own thick record, routable through its predecessor, named in the explanation). done / next: recency tie-break and rule text (item 5) Co-Authored-By: Claude Sonnet 5.5 --- sisi/routing.py | 75 +++++++++++++++++- sisi/workers.py | 3 + tests/test_model_inheritance.py | 130 ++++++++++++++++++++++++++++++++ tests/test_worker_models.py | 18 +++++ 4 files changed, 222 insertions(+), 4 deletions(-) create mode 100644 tests/test_model_inheritance.py diff --git a/sisi/routing.py b/sisi/routing.py index f28e2bc..db96633 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -183,6 +183,60 @@ def candidate_stats(candidates, records): return stats +def _versions_newest_first(models): + """[[workers of one version], ...] from the newest version to the oldest (one model through several + providers is one version).""" + out = [] + for d in sorted(models, key=lambda d: (modelid.recency_key(_lineage(d)), d["worker"])): + if out and modelid.compare(_lineage(out[-1][0]), _lineage(d)) == 0: + out[-1].append(d) + else: + out.append([d]) + return out + + +def inherit_stats(candidates, stats, opts=None): + """Judged cells as evidence sees them: a model with no thick record of its own for a kind and difficulty + starts from the thick record of the closest older version of the same maker and class (walking back one + version at a time, the first thick record decides). Only a record that proves the work is inherited: a + predecessor's bad record starts the newer model from its benchmark or from nothing, and a thin record of the + model's own that already repeats rejections is not papered over. The model's own thick record always stands + alone. An inherited cell carries `from`, the worker whose record it is.""" + eff = {w: {"uses": st["uses"], "by_cell": dict(st["by_cell"])} for w, st in stats.items()} + groups = {} + for c in candidates: + l = _comparable(c, opts) + if l: + groups.setdefault(tuple(l["key"]), []).append(c) + for group in groups.values(): + for c in group: + older = [d for d in group if modelid.compare(_lineage(c), _lineage(d)) > 0] + if not older: + continue + levels = _versions_newest_first(older) + own = stats[c["worker"]]["by_cell"] + for ck in sorted({k for d in older for k in stats[d["worker"]]["by_cell"]}, key=str): + mine = own.get(ck, _NO_CELL) + if _thick(mine) or _contradicts(mine): + continue + for level in levels: + cells = [(d["worker"], stats[d["worker"]]["by_cell"].get(ck)) for d in level] + cells = [(w, x) for w, x in cells if x] + merged = {"n": sum(x["n"] for _w, x in cells), "good": sum(x["good"] for _w, x in cells)} + if _thick(merged): + if _proven(merged): + eff[c["worker"]]["by_cell"][ck] = dict(merged, **{"from": max(cells, key=lambda t: (t[1]["n"], t[0]))[0]}) + break + return eff + + +def has_predecessor(c, among, opts=None): + """Whether some worker in `among` is an older version of the same maker and class as `c`.""" + l = _comparable(c, opts) + return bool(l) and any(_comparable(d, opts) and tuple(_lineage(d)["key"]) == tuple(l["key"]) + and modelid.compare(l, _lineage(d)) > 0 for d in among) + + def _price_tier(c): if c.get("plan") == "flat": return 0 @@ -234,6 +288,8 @@ def _by_difficulty(stats, worker, kind): p = pooled.setdefault(d, {"n": 0, "good": 0}) p["n"] += cell["n"] p["good"] += cell["good"] + if cell.get("from"): + p["from"] = cell["from"] return own, pooled @@ -279,7 +335,8 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f proof = ("b-all", wide[0], pooled[wide[0]]) if proof is not None: tier, at, cell = proof - out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell)) + out.update(tier=tier, capable=True, level=3, at=at, n=cell["n"], good=cell["good"], measure=_rate(cell), + inherited_from=cell.get("from")) return out if standing is not None: pct = _floor_pct(floors, d) @@ -304,6 +361,8 @@ def strength(a): if a["bad"]: return (-1, 0, 0.0) if a["tier"] in _TIER_RANK: + if a.get("inherited_from"): + return (3, 1, a["measure"]) # a predecessor's record: above a benchmark, below the model's own return (4, -_TIER_RANK[a["tier"]], a["measure"]) if a["standing"] is not None and not a["contradicted"]: return (3, 0, float(a["standing"])) @@ -502,7 +561,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, now = float(now or 0) eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts) - assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) + assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors) key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer) pool, basis = _select(eligible, assessments, difficulty) if eligible else ([], "none") @@ -634,7 +693,8 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, now = float(now or 0) eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts) - assessments, best = _assess_all(eligible, stats, kind, difficulty, floors) + eff = inherit_stats(candidates, stats, opts) + assessments, best = _assess_all(eligible, eff, kind, difficulty, floors) key, _rate, _load = _make_key(stats, kind, difficulty, prefer) out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker, "assessments": assessments, "best_standing": best, "kind": kind, "difficulty": difficulty, @@ -650,7 +710,7 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, return out gone = next((c for c in candidates if c["worker"] == rejected), None) floor = (strength(assessments[rejected]) if mine is not None else - strength(assess(stats, rejected, kind, difficulty, _standing_of(gone) if gone else None, best, floors))) + strength(assess(eff, rejected, kind, difficulty, _standing_of(gone) if gone else None, best, floors))) better = [c for c in others if assessments[c["worker"]]["capable"] and strength(assessments[c["worker"]]) > floor] better = _prefer_judged(better, assessments, difficulty)[0] if better: @@ -685,6 +745,13 @@ def evidence_line(a, kind, difficulty, choice, basis): if a["bad"]: return ("evidence: none favourable; every usable worker has a poor record, so this one has the best " "accepted rate (%d of %d for %s)" % (a["good"], a["n"], kind)) + line = _evidence_line(a, kind, difficulty, choice, basis) + if a.get("inherited_from"): + line += " (the record of its predecessor %s; it has none of its own yet)" % a["inherited_from"] + return line + + +def _evidence_line(a, kind, difficulty, choice, basis): tier = a["tier"] if tier == "a": return ("evidence (a), judged record: %d of %d accepted for %s at difficulty %d (%s, bar %s)" diff --git a/sisi/workers.py b/sisi/workers.py index f4b24c6..bb5b146 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -935,6 +935,9 @@ def routable_candidates(candidates, records): keep.append(c) if not keep: return list(candidates), True, 0 + # a new version of a model that has a record, price or standing starts from its predecessor's record + opts = route_opts() + keep = keep + [c for c in candidates if c not in keep and routing.has_predecessor(c, keep, opts)] return keep, False, len(candidates) - len(keep) diff --git a/tests/test_model_inheritance.py b/tests/test_model_inheritance.py new file mode 100644 index 0000000..5f63f7b --- /dev/null +++ b/tests/test_model_inheritance.py @@ -0,0 +1,130 @@ +"""A new version of a model starts from its predecessor's judged record: inherited evidence ranks below the model's +own record and above a benchmark, counts as judged proof, stops once the model has a thick record of its own, and a +predecessor's bad record does not block it. Invented ids. Requirement ids: R-7.2-1, R-7.2-3.""" +import random, unittest +from support import * +from sisi import routing +from test_model_supersession import cand, attempts, pick, NOW + + +def assessed(cands, records, worker, difficulty=2, kind="impl", **kw): + r = routing.choose(cands, list(records), {}, kind, difficulty, now=NOW, **kw) + return r["assessments"].get(worker), r + + +class InheritanceTests(unittest.TestCase): + def test_a_new_version_inherits_the_record_of_its_predecessor_and_says_so(self): + old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) + records = attempts("prov/abc-5.3", 12, 11, difficulty=2) + a, r = assessed([old, new], records, "prov/abc-5.4") + self.assertEqual((a["tier"], a["capable"], a["inherited_from"]), ("a", True, "prov/abc-5.3")) + self.assertEqual(r["choice"]["worker"], "prov/abc-5.4") + line = routing.evidence_line(a, "impl", 2, r["choice"], r["basis"]) + self.assertIn("the record of its predecessor prov/abc-5.3", line) + self.assertIn("11 of 12", line) + + def test_it_walks_back_one_predecessor_at_a_time(self): + cands = [cand("prov/abc-5.2", cost=1.0), cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0)] + records = attempts("prov/abc-5.2", 12, 12, difficulty=2) + attempts("prov/abc-5.3", 3, 3, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertEqual(a["inherited_from"], "prov/abc-5.2") # 5.3 has only a thin record + records += attempts("prov/abc-5.3", 9, 9, difficulty=2, start=50) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertEqual(a["inherited_from"], "prov/abc-5.3") # now the closest thick one + + def test_a_predecessors_bad_record_does_not_block_the_newer_model(self): + cands = [cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0, standing=70.0)] + records = attempts("prov/abc-5.3", 12, 2, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertFalse(a["bad"]) + self.assertEqual(a["tier"], "standing") # it starts from its benchmark, not from the old verdict + bare = assessed([cands[0], cand("prov/abc-5.4", cost=1.0)], records, "prov/abc-5.4")[0] + self.assertFalse(bare["bad"]) + self.assertFalse(bare["capable"]) + + def test_the_models_own_thick_record_replaces_the_inherited_one(self): + cands = [cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0)] + records = attempts("prov/abc-5.3", 12, 12, difficulty=2) + attempts("prov/abc-5.4", 9, 1, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertTrue(a["bad"]) + self.assertIsNone(a.get("inherited_from")) + records = attempts("prov/abc-5.3", 12, 2, difficulty=2) + attempts("prov/abc-5.4", 9, 9, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertEqual((a["tier"], a.get("inherited_from")), ("a", None)) + + def test_a_thin_record_that_already_contradicts_is_not_papered_over(self): + cands = [cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0)] + records = attempts("prov/abc-5.3", 12, 12, difficulty=2) + attempts("prov/abc-5.4", 3, 0, difficulty=2) + a, _ = assessed(cands, records, "prov/abc-5.4") + self.assertIsNone(a.get("inherited_from")) + self.assertFalse(a["capable"]) + + def test_nothing_is_inherited_across_classes_or_makers(self): + flash, new = cand("prov/abc-5.3-flash", cost=1.0), cand("prov/abc-5.4", cost=1.0) + records = attempts("prov/abc-5.3-flash", 12, 12, difficulty=2) + self.assertFalse(assessed([flash, new], records, "prov/abc-5.4")[0]["capable"]) + other = cand("prov/xyz-5.4", cost=1.0, maker="xyz") + self.assertFalse(assessed([cand("prov/abc-5.3"), other], attempts("prov/abc-5.3", 12, 12, difficulty=2), "prov/xyz-5.4")[0]["capable"]) + + def test_nothing_is_inherited_by_an_unreadable_class(self): + cands = [cand("prov/abc-6.2-sol"), cand("prov/abc-6.3-sol")] + records = attempts("prov/abc-6.2-sol", 12, 12, difficulty=2) + self.assertFalse(assessed(cands, records, "prov/abc-6.3-sol")[0]["capable"]) + + def test_inherited_evidence_counts_as_a_judged_record_before_a_benchmark(self): + """Difficulty 2 and 3: proof comes before benchmark, and an inherited record is proof.""" + new = cand("prov/abc-5.4", cost=5.0) + rival = cand("prov/xyz-2.0", cost=0.1, maker="xyz", standing=90.0) + records = attempts("prov/abc-5.3", 12, 12, difficulty=3) + who, r = pick([cand("prov/abc-5.3", cost=5.0), new, rival], records, 3) + self.assertEqual(who, "prov/abc-5.4") + self.assertTrue(r["judged_first"]) + + def test_inherited_ranks_below_the_models_own_record_in_strength(self): + own = routing.assess({"w": {"uses": 0, "by_cell": {("impl", 2): {"n": 10, "good": 10}}}}, "w", "impl", 2) + inherited = routing.assess({"w": {"uses": 0, "by_cell": {("impl", 2): {"n": 10, "good": 10, "from": "old"}}}}, "w", "impl", 2) + bench = routing.assess({"w": {"uses": 0, "by_cell": {}}}, "w", "impl", 2, standing=80.0, best_standing=80.0) + self.assertGreater(routing.strength(own), routing.strength(inherited)) + self.assertGreater(routing.strength(inherited), routing.strength(bench)) + self.assertEqual(inherited["inherited_from"], "old") + + def test_a_model_with_no_data_of_its_own_is_routable_through_its_predecessor(self): + from sisi import workers + old, new, lone = cand("prov/abc-5.3"), cand("prov/abc-5.4"), cand("prov/xyz-9.9", maker="xyz") + for c in (old, new, lone): + c["price_source"] = None + old["price_source"] = "fixture" + keep, cold, excluded = workers.routable_candidates([old, new, lone], []) + self.assertEqual(sorted(c["worker"] for c in keep), ["prov/abc-5.3", "prov/abc-5.4"]) + self.assertEqual(excluded, 1) + + def test_property_inherited_evidence_never_outranks_a_thick_record_of_the_models_own(self): + rng = random.Random(41) + seen = 0 + for _ in range(300 * ITERS): + versions = rng.sample(["5.1", "5.2", "5.3", "5.4", "5.10"], rng.randint(2, 4)) + cands = [cand("prov/abc-%s" % v, cost=rng.choice([None, 1.0, 2.0])) for v in versions] + records = [] + for c in cands: + for d in (1, 2, 3): + if rng.random() < 0.6: + n = rng.choice([2, 8, 12]) + records += attempts(c["worker"], n, rng.randint(0, n), difficulty=d, start=d * 100) + stats = routing.candidate_stats(cands, records) + eff = routing.inherit_stats(cands, stats) + for c in cands: + for ck, cell in stats[c["worker"]]["by_cell"].items(): + if cell["n"] >= routing.MIN_ATTEMPTS: + self.assertEqual(eff[c["worker"]]["by_cell"][ck], cell) + seen += 1 + for ck, cell in eff[c["worker"]]["by_cell"].items(): + if cell.get("from"): + own = stats[c["worker"]]["by_cell"].get(ck, {"n": 0}) + self.assertLess(own["n"], routing.MIN_ATTEMPTS) + self.assertGreaterEqual(cell["n"], routing.MIN_ATTEMPTS) + self.assertGreaterEqual(cell["good"] / cell["n"], routing.MIN_ACCEPTED_RATE) # a bad record is never inherited + self.assertGreater(seen, 100) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_worker_models.py b/tests/test_worker_models.py index 24f393c..fa8652c 100644 --- a/tests/test_worker_models.py +++ b/tests/test_worker_models.py @@ -143,5 +143,23 @@ class RouteSupersessionTests(ModelCase): self.assertNotIn("cannot be read", self.route(1).stdout) +class RouteInheritanceTests(ModelCase): + def test_a_new_release_with_no_data_of_its_own_gets_ordinary_work_at_once(self): + """R-7.2-1: discovered, unpriced, unjudged, yet routable and capable through its predecessor's record.""" + self.seed([("muse/abc-5.3", 12, 12)], difficulty=2) + r = self.route(2, "--explain") + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout) + self.assertIn("the record of its predecessor muse/abc-5.3", r.stdout) + self.assertLessEqual(len(r.stdout.splitlines()), 20, r.stdout) + plain = self.route(2).stdout.splitlines() + self.assertLessEqual(len(plain), 6, plain) + + def test_once_it_has_a_thick_record_of_its_own_the_inherited_one_stops_applying(self): + self.seed([("muse/abc-5.3", 12, 12), ("muse/abc-5.4", 9, 9)], difficulty=2) + r = self.route(2, "--explain") + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout) + self.assertNotIn("predecessor", r.stdout) + + if __name__ == "__main__": unittest.main() From 7db6584388e69f7b8f2756c876d80c9bc55021f5 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:28:05 -0700 Subject: [PATCH 5/8] Item 5: recency breaks ties (recorded release date, else version inside a class); the rule in rule 6, the playbook and docs/workers.md; session start asks for release dates. done / next: class order and sisi workers classes (item 7) Co-Authored-By: Claude Sonnet 5.5 --- canon/core.md | 4 ++- canon/orchestration.md | 10 ++++++ docs/workers.md | 28 +++++++++++++++ sisi/modelid.py | 18 ++++------ sisi/routing.py | 40 +++++++++++++++++---- sisi/workers.py | 3 +- tests/test_model_recency.py | 69 +++++++++++++++++++++++++++++++++++++ tests/test_modelid.py | 1 - 8 files changed, 152 insertions(+), 21 deletions(-) create mode 100644 tests/test_model_recency.py diff --git a/canon/core.md b/canon/core.md index 70f6f92..224735b 100644 --- a/canon/core.md +++ b/canon/core.md @@ -81,7 +81,9 @@ wrong work. You own the whole outcome; workers are specialists whose reports are evidence for you to judge. Give each task to the least expensive worker that is capable enough, counting rework as cost, -and keep your own context for judgement. Use the host's own delegation first. Run independent +and keep your own context for judgement. Always use the most recently released model of a class +when it is usable, never an older version of it; classify a maker's models before comparing them, +because different classes are different things. Use the host's own delegation first. Run independent work in parallel when it shortens the critical path. Brief a worker with a contract (`sisi delegate brief`), check what comes back in proportion to the risk, and record the judgement (`sisi delegate judge`). `sisi route` recommends a worker from that record, and diff --git a/canon/orchestration.md b/canon/orchestration.md index e5e5d75..7ea3b82 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -33,6 +33,16 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. routine work measured proof outranks a benchmark: the cheapest worker with a judged record wins, and standing decides only when nobody has one. A thin record is a reason for care, not a verdict. +- Always use the most recently released model of a class when it is usable, and never an older + version of it: newer models are almost always better and almost always cheaper, so neither a + better old record nor a cheaper old plan brings an older version back. A new version starts + from its predecessor's judged record until it has its own. Two exceptions only: the newer model + is unusable right now (down, out of allowance, avoided), or its class is not known yet. Classes + are not versions of each other: a maker's "flash" is a different thing from its standard model, + and a maker's separately named lines are different classes. Determine the class of a model + before comparing it with another (`sisi workers fact W --class NAME`), and a maker's classes, + most capable first, with `sisi workers classes`. A newer model that measures badly is replaced + by a different class or maker, never by its older version. - Ask `sisi route --kind K --difficulty N` before delegating; `--explain` says why. Difficulty is 1 routine, 2 ordinary, 3 hard. Say the guess out loud; the record shows how good the guesses were. diff --git a/docs/workers.md b/docs/workers.md index 2927c93..eee3339 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -82,6 +82,34 @@ instead, so cheaper options gather evidence. The choice is deterministic for one `--explain` prints one line for the evidence behind the choice (which of a to d, with the numbers), one per group of workers passed over as not capable enough, and names an exploration or a fallback. +## Newest version of a class, always + +Newer models are almost always better and almost always cheaper, so `sisi route` always uses the +most recently released model of a class that is usable, and never an older version of it. A +model's identity is its maker, its line and its class, read from the id by `sisi/modelid.py` +(version numbers compared numerically, a date in the id as a date, tier words such as a "flash" or +"mini" from `canon/model-words.json`) and overridden by what the lead agent records: +`sisi workers fact WORKER --class NAME [--family NAME] [--maker M] [--released YYYY-MM-DD] --source S`. +A recorded release date beats version numbers for recency. The same model through two providers is +one model: if its newest version is usable through any provider, older versions do not compete +through any provider, and the existing cost comparison picks the provider. There is no exception for +a better old record or a cheaper old plan. The older version competes again only while the newer is +unusable (marked down, allowance spent, avoided by the user, or limited away), or when its class is +unknown. A newer model with a thick bad record is not replaced by its older version either: routing +moves to another class or maker by the usual rules. Different classes are different things and never +supersede each other. A class read from the id with confidence takes part at once +(`route.supersede_guessed`, default true; false lets only recorded classes take part); a class that +cannot be read (no version, or a word the data does not know) never does, and `sisi route` adds one +line asking the lead agent to record it. + +A new version starts from its predecessor's judged record: a model with no thick record of its own +for a kind and difficulty inherits, as evidence, the thick record of the closest older version of +its maker and class (one version back at a time), named in `--explain`. It ranks below the model's +own record and above a benchmark, counts as a judged record for the rule that proof comes before +benchmark, stops once the model has a thick record of its own, and a predecessor's bad record is not +inherited. A discovered model with no data of its own is routable when its predecessor is. Where the +arithmetic falls back to a stable tie-break, the more recently released model wins first. + ## Costs and failures Tokens and cost are captured where the worker's output reports them, and marked `unavailable` diff --git a/sisi/modelid.py b/sisi/modelid.py index a2ad2cf..eaf8adb 100644 --- a/sisi/modelid.py +++ b/sisi/modelid.py @@ -192,14 +192,10 @@ def compare(a, b): return 0 -def recency_key(l): - """A tuple that sorts the more recently released first, for tie-breaks: recorded release date, then version - inside one line (the line first, so versions of different lines are never compared), then the id's date.""" - if not l: - return (0, 0, "", (), 0) - rel = l.get("released") or "" - days = int(rel[0:4]) * 372 + int(rel[5:7]) * 31 + int(rel[8:10]) if len(rel) >= 10 and rel[:4].isdigit() else 0 - ver = tuple(-x for x in (tuple(l.get("version") or ()) + (0,) * 6)[:6]) - d = l.get("date") or "" - dd = int(d[0:4]) * 372 + int(d[5:7]) * 31 + int(d[8:10]) if len(d) >= 10 else 0 - return (0 if l.get("alias") else 1, -days, "|".join(l.get("key") or ()), ver, -dd) +def days(date): + """A YYYY-MM-DD date as a number of days that sorts correctly (months of 31 days: only the order matters); 0 when + there is no date.""" + d = str(date or "") + if len(d) >= 10 and d[:4].isdigit() and d[5:7].isdigit() and d[8:10].isdigit(): + return int(d[0:4]) * 372 + int(d[5:7]) * 31 + int(d[8:10]) + return 0 diff --git a/sisi/routing.py b/sisi/routing.py index db96633..b3109b8 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -51,12 +51,14 @@ The rule, in order: unknown is never compared. 8. Load balancing: within the same price tier and price, the worker that has taken the least work relative to its remaining allowance goes first (recorded uses divided by allowance left, an - unknown allowance counting as half). Ties break on the worker id. + unknown allowance counting as half). Ties break on the more recently released model (a recorded + release date, else the version inside one maker's class), then on the worker id. Candidates reach here already restricted to workers with a judged record, a known price or a benchmark standing (see workers.routable_candidates); on a cold start none qualifies and every usable worker is offered, with the explanation saying so. """ +import functools import re from . import modelid @@ -187,7 +189,9 @@ def _versions_newest_first(models): """[[workers of one version], ...] from the newest version to the oldest (one model through several providers is one version).""" out = [] - for d in sorted(models, key=lambda d: (modelid.recency_key(_lineage(d)), d["worker"])): + ordered = sorted(models, key=lambda d: d["worker"]) + ordered.sort(key=functools.cmp_to_key(lambda a, b: modelid.compare(_lineage(b), _lineage(a)))) + for d in ordered: if out and modelid.compare(_lineage(out[-1][0]), _lineage(d)) == 0: out[-1].append(d) else: @@ -421,7 +425,7 @@ def superseded_by(pool, opts=None): for c in group: newer = [d for d in group if modelid.compare(_lineage(d), _lineage(c)) > 0] if newer: - out[c["worker"]] = min(newer, key=lambda d: (modelid.recency_key(_lineage(d)), d["worker"]))["worker"] + out[c["worker"]] = _versions_newest_first(newer)[0][0]["worker"] return out @@ -491,7 +495,26 @@ def _assess_all(eligible, stats, kind, difficulty, floors): for c in eligible}, best) -def _make_key(stats, kind, difficulty, prefer): +def recency_order(candidates): + """{worker: (recorded release date as days, negated; position among the versions of its class, newest first)}. + Smaller sorts first, so the more recently released model goes first; what cannot be compared is (0, 0). + A recorded release date counts across makers; the version only inside one maker's class.""" + out = {c["worker"]: (0, 0) for c in candidates} + groups = {} + for c in candidates: + l = _lineage(c) + if l and l.get("key"): + groups.setdefault(tuple(l["key"]), []).append(c) + for group in groups.values(): + for i, level in enumerate(_versions_newest_first(group)): + for d in level: + out[d["worker"]] = (-modelid.days(_lineage(d).get("released")), i) + return out + + +def _make_key(stats, kind, difficulty, prefer, recency=None): + recency = recency or {} + def rate(c): cell = _cell(stats, c["worker"], kind, difficulty) return (cell["good"] / cell["n"]) if cell["n"] else None @@ -515,9 +538,10 @@ def _make_key(stats, kind, difficulty, prefer): standing_key(c), load_ratio(c), -(r if r is not None else -1.0), + recency.get(c["worker"], (0, 0)), c["worker"]) - return key, rate, load_ratio + return key, rate, load_ratio, recency def _prefer_judged(capable, assessments, difficulty): @@ -562,7 +586,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts) assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors) - key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer) + key, rate, load_ratio, recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible)) pool, basis = _select(eligible, assessments, difficulty) if eligible else ([], "none") detail = {} @@ -617,6 +641,8 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, r, cr = rate(c), rate(choice) reason = ("lower measured accepted rate for this kind and difficulty" if r is not None and cr is not None and r < cr else + "equal on price and load; the choice is the more recently released" + if recency.get(choice["worker"], (0, 0)) < recency.get(c["worker"], (0, 0)) else "equal on price and load; the choice came first in worker-id order") passed.append((w, reason)) judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1] @@ -695,7 +721,7 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, avoid, review_of, opts) eff = inherit_stats(candidates, stats, opts) assessments, best = _assess_all(eligible, eff, kind, difficulty, floors) - key, _rate, _load = _make_key(stats, kind, difficulty, prefer) + key, _rate, _load, _recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible)) out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker, "assessments": assessments, "best_standing": best, "kind": kind, "difficulty": difficulty, "rejected": rejected, "rejections": rejections} diff --git a/sisi/workers.py b/sisi/workers.py index bb5b146..0a0f5ec 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -907,7 +907,8 @@ def facts_line(now=None): return ("sisi: %s: ask a fast, cheap worker to research current prices and " "software-engineering benchmark standing for the workers found here (`sisi workers`) " "and record each with its source: `sisi workers fact WORKER --price N --source S` " - "and `sisi workers fact WORKER --standing N --source S`. Until then routing " + "and `sisi workers fact WORKER --standing N --source S`; also the release date of each " + "worker that lacks one: `sisi workers fact WORKER --released YYYY-MM-DD --source S`. Until then routing " "goes by the judged record alone." % what) diff --git a/tests/test_model_recency.py b/tests/test_model_recency.py new file mode 100644 index 0000000..1bc5ddb --- /dev/null +++ b/tests/test_model_recency.py @@ -0,0 +1,69 @@ +"""Recency breaks ties: where the arithmetic falls back to a stable order, the more recently released model wins +first (a recorded release date, else the version within one line, else the old tie-break by worker id), and the +rule is in the text agents and people read. Requirement ids: R-7.2-1, R-7.2-2.""" +import os, unittest +from support import * +from sisi import routing +from test_model_supersession import cand, pick + + +class RecencyTieBreakTests(unittest.TestCase): + def test_a_recorded_release_date_decides_a_tie_between_unrelated_models(self): + a = cand("prov/aaa-1.0", cost=1.0, fact={"released": "2026-01-10"}, maker="aaa") + b = cand("prov/bbb-2.0", cost=1.0, fact={"released": "2026-08-01"}, maker="bbb") + who, r = pick([a, b]) + self.assertEqual(who, "prov/bbb-2.0") + self.assertIn(("prov/aaa-1.0", "equal on price and load; the choice is the more recently released"), r["passed_over"]) + + def test_the_version_inside_one_line_decides_when_nothing_supersedes(self): + old, new = cand("prov/abc-5.9", cost=1.0), cand("prov/abc-5.10", cost=1.0) + who, r = pick([old, new], opts={"supersede_guessed": False}) + self.assertEqual(who, "prov/abc-5.10") + self.assertEqual(pick([new, old], opts={"supersede_guessed": False})[0], "prov/abc-5.10") + + def test_unknown_recency_keeps_the_old_tie_break(self): + a, b = cand("prov/aaa-1.0", cost=1.0, maker="aaa"), cand("prov/bbb-9.0", cost=1.0, maker="bbb") + who, r = pick([a, b]) + self.assertEqual(who, "prov/aaa-1.0") + self.assertIn(("prov/bbb-9.0", "equal on price and load; the choice came first in worker-id order"), r["passed_over"]) + + def test_price_and_load_still_come_before_recency(self): + cheap_old = cand("prov/aaa-1.0", cost=0.5, fact={"released": "2026-01-10"}, maker="aaa") + dear_new = cand("prov/bbb-2.0", cost=1.0, fact={"released": "2026-08-01"}, maker="bbb") + self.assertEqual(pick([cheap_old, dear_new])[0], "prov/aaa-1.0") + + +class TextTests(unittest.TestCase): + def read(self, *parts): + with open(os.path.join(REPO, *parts), encoding="utf-8") as f: + return f.read() + + def test_the_rule_is_in_the_always_loaded_rulebook_the_playbook_and_the_docs(self): + core = self.read("canon", "core.md") + rule6 = core[core.index("## 6. Orchestrate"):core.index("## 7.")] + self.assertIn("most recently released", rule6) + self.assertIn("never an older version", rule6) + self.assertIn("class", rule6) + for path in (("canon", "orchestration.md"), ("docs", "workers.md")): + text = self.read(*path).lower() + self.assertIn("most recently released", text, path) + self.assertIn("different classes", text, path) + self.assertIn("cheaper", text, path) # the reason: newer models are better and cheaper + + def test_the_rulebook_is_inside_its_budget(self): + from sisi import overlay + lines, chars = overlay.size(self.read("canon", "core.md")) + self.assertLessEqual(lines, overlay.MAX_LINES) + self.assertLessEqual(chars, overlay.MAX_CHARS) + + +class SessionLineTests(SisiCase): + def test_session_start_asks_for_the_release_date_of_each_worker_that_lacks_one(self): + from sisi import workers + line = workers.facts_line() + self.assertIn("release date", line) + self.assertIn("--released", line) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_modelid.py b/tests/test_modelid.py index d619166..b0c8516 100644 --- a/tests/test_modelid.py +++ b/tests/test_modelid.py @@ -112,7 +112,6 @@ class ParseTests(unittest.TestCase): self.assertEqual(modelid.compare(a, b), -modelid.compare(b, a), ident) if a["source"] == "unknown": self.assertIsNone(a["key"]) - modelid.recency_key(a) if __name__ == "__main__": From d6bdb799c565d1e1f1c99f444a7ee2dc0c239c22 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:32:58 -0700 Subject: [PATCH 6/8] Item 7: a maker's classes, most capable first (sisi workers classes), as a prior between its classes below any judged record or benchmark; configurable span per difficulty; the strongest-known fallback follows it; one line asks for the order. done / next: the grid on the copy (item 6), repeat runs Co-Authored-By: Claude Sonnet 5.5 --- config.default.json | 7 +- docs/workers.md | 16 +++++ sisi/helptext.py | 2 +- sisi/routing.py | 98 ++++++++++++++++++++----- sisi/workers.py | 65 +++++++++++++++-- tests/test_model_classes.py | 138 ++++++++++++++++++++++++++++++++++++ 6 files changed, 302 insertions(+), 24 deletions(-) create mode 100644 tests/test_model_classes.py diff --git a/config.default.json b/config.default.json index 01138db..7e1bda5 100644 --- a/config.default.json +++ b/config.default.json @@ -18,7 +18,12 @@ "3": 85 }, "price_blend_input_parts": 3, - "supersede_guessed": true + "supersede_guessed": true, + "class_span": { + "1": 100, + "2": 70, + "3": 35 + } }, "unit": { "stale_hours": 12 diff --git a/docs/workers.md b/docs/workers.md index eee3339..efba62e 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -20,6 +20,12 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano A fact without a source is refused. Ranking uses one blend of the two prices, by default three parts input to one part output (`route.price_blend_input_parts`); `sisi workers` shows both prices and the blend, and lists each benchmark standing apart from the accepted rates it prints. +- `sisi workers fact WORKER --class NAME [--family NAME] [--maker M] [--released YYYY-MM-DD] --source S` — the + class, line and release date the lead agent decided for a model; a recorded fact beats the parser. + `sisi workers` lists each routable worker's maker, class (recorded, or a guess read from the id) and recency. +- `sisi workers classes MAKER CLASS [CLASS...] --source S` — a maker's classes from most capable to least + (`--remove` forgets them). A class is the tier word of one line (a "flash" beside the standard model) or, + for a maker whose lines are the classes, the line's own name; `sisi workers` shows both as the class label. - `sisi workers avoid|prefer PATTERN --why TEXT` — the user's own routing constraints. - `sisi workers only PROVIDER PATTERN... --why TEXT` — only the matching models of that provider are routable; anything else from it (a newly discovered model, say) is passed over with the reason. @@ -102,6 +108,16 @@ supersede each other. A class read from the id with confidence takes part at onc cannot be read (no version, or a word the data does not know) never does, and `sisi route` adds one line asking the lead agent to record it. +The class order is a prior and nothing more. A worker with no judged proof and no benchmark standing, +whose class is in its maker's recorded order, is capable when the class sits high enough for the +difficulty: `route.class_span` (default routine work 100, ordinary 70, hard 35) is the share of the order, +counted from the most capable class down, that each difficulty reaches. With four classes routine work +reaches all four, ordinary work the top three, hard work the top two; the cheapest capable worker then +wins, so routine work goes to the lowest class and hard work to the upper ones. A judged record or a +benchmark standing always outranks the order; when nobody is proven, the strongest known worker is the +one in the highest class. Classes of different makers are never compared. Until a maker with two or +more classes among the usable workers has an order recorded, `sisi route` adds one line asking for it. + A new version starts from its predecessor's judged record: a model with no thick record of its own for a kind and difficulty inherits, as evidence, the thick record of the closest older version of its maker and class (one version back at a time), named in `--explain`. It ranks below the model's diff --git a/sisi/helptext.py b/sisi/helptext.py index 0039aca..f629492 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -31,7 +31,7 @@ LONG = { 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score); --learning prints only the learning report', 'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library', 'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "" best-matching recipe', - 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --class NAME [--family NAME] [--released DATE] --source S the class, line and release date you decided for a model; beats the parser\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', + 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --class NAME [--family NAME] [--released DATE] --source S the class, line and release date you decided for a model; beats the parser\n sisi workers classes MAKER CLASS... --source S | MAKER --remove the classes of a maker, most capable first (a prior between them)\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', 'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why', 'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id', 'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only', diff --git a/sisi/routing.py b/sisi/routing.py index b3109b8..e374603 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -70,6 +70,7 @@ UNKNOWN_ALLOWANCE = 50.0 # allowance weight when a tool reports none STRONG_BAND = 10.0 # standing points from the best still counts as among the strongest EXPLORE_EVERY = 10 # about one low-stakes task in ten tries a cheaper thin-record worker DEFAULT_STANDING_FLOOR = {1: 0.0, 2: 60.0, 3: 85.0} # percent of the best usable standing needed +DEFAULT_CLASS_SPAN = {1: 100.0, 2: 70.0, 3: 35.0} # how far down a maker's class order still counts as capable DEFAULT_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price @@ -121,6 +122,32 @@ def _floor_pct(floors, difficulty): return table[max(table)] +def class_spans(configured=None): + """{difficulty: percent of a maker's class order, from the most capable class down, that is capable enough}. + With four classes: routine work (100) reaches all four, ordinary work (70) the top three, hard work (35) the + top two. The defaults are overridden by valid entries of the configured mapping (keys 1..3, values 0..100).""" + table = dict(DEFAULT_CLASS_SPAN) + if isinstance(configured, dict): + for k, v in configured.items(): + try: + d, pct = int(k), float(v) + except (TypeError, ValueError): + continue + if 1 <= d <= 3 and 0 <= pct <= 100: + table[d] = pct + return table + + +def class_rank(c, opts=None): + """(position, count) of the model's class in its maker's recorded order (0 is the most capable), or None when + the maker has no recorded order, the class could not be read, or the class is not in the order.""" + l = _lineage(c) + order = ((opts or {}).get("class_orders") or {}).get(l.get("maker")) if l and l.get("key") else None + if not order or l.get("label") not in order: + return None + return order.index(l["label"]), len(order) + + def _pattern_match(c, patterns): """The (pattern, why) a candidate matches, or None. A pattern matches as a substring of the worker, model or tool name, case aside.""" @@ -297,7 +324,7 @@ def _by_difficulty(stats, worker, kind): return own, pooled -def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None): +def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=None, rank=None, spans=None): """What the evidence says about one worker for a kind and difficulty. Returns a dict: tier "a", "b-higher", "b-all", "standing", "unknown" or "none" capable whether the evidence says it is capable enough @@ -307,7 +334,12 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f level 3 judged proof, 2 benchmark, 1 weak, 0 nothing, -1 bad: never rises with difficulty n, good, at the judged cell behind a, b-higher, b-all and the weak tier (and its difficulty) share, needed, floor for the standing tier: percent of the best, the figure needed, the floor - Standing is compared only with the best standing; a rate only with the bar.""" + class_pos, class_n, class_share, class_allowed for the class tier (see below) + inherited_from the worker whose record this is, when it is a predecessor's (see inherit_stats) + The class tier is the last prior: a worker with no judged proof and no standing of its own, whose class has a + place in its maker's recorded order (`rank`, from class_rank), is capable when that place is within the span the + difficulty allows (`spans`, see class_spans). Standing is compared only with the best standing; a rate only with + the bar; neither is ever compared with a class.""" d = difficulty own, pooled = _by_difficulty(stats, worker, kind) out = {"tier": "none", "capable": False, "bad": False, "weak": False, "contradicted": False, @@ -350,6 +382,14 @@ def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, f if not out["contradicted"]: out.update(tier="standing", capable=capable, level=2 if capable else (1 if out["weak"] else 0)) return out + if standing is None and rank is not None and not out["contradicted"]: + pos, n = rank + share = 100.0 * pos / (n - 1) if n > 1 else 0.0 + allowed = class_spans(spans).get(d, 100.0 if d is None or d < 1 else class_spans(spans)[3]) + capable = share <= allowed + 1e-9 + out.update(tier="class", capable=capable, level=1 if capable else 0, class_pos=pos, class_n=n, + class_share=share, class_allowed=allowed) + return out if standing is None and d == 1 and not out["contradicted"]: out.update(tier="unknown", capable=True, level=0) return out @@ -370,6 +410,8 @@ def strength(a): return (4, -_TIER_RANK[a["tier"]], a["measure"]) if a["standing"] is not None and not a["contradicted"]: return (3, 0, float(a["standing"])) + if a["tier"] == "class": + return (1, 1, 1.0 - a["class_share"] / 100.0) # the maker's own order: below a weak judged record if a["weak"]: return (2, 0, a["weak_rate"]) return (1, 0, 0.0) @@ -487,11 +529,13 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of, return eligible, passed, stats, author_maker, superseded -def _assess_all(eligible, stats, kind, difficulty, floors): +def _assess_all(eligible, stats, kind, difficulty, floors, opts=None): """({worker: assessment}, best standing among the usable workers).""" standings = [s for s in (_standing_of(c) for c in eligible) if s is not None] best = max(standings) if standings else None - return ({c["worker"]: assess(stats, c["worker"], kind, difficulty, _standing_of(c), best, floors) + spans = (opts or {}).get("class_span") + return ({c["worker"]: assess(stats, c["worker"], kind, difficulty, _standing_of(c), best, floors, + rank=class_rank(c, opts), spans=spans) for c in eligible}, best) @@ -555,6 +599,9 @@ def _prefer_judged(capable, assessments, difficulty): own = [c for c in capable if assessments[c["worker"]]["tier"] in tiers] if own: return own, True + benchmarked = [c for c in capable if assessments[c["worker"]]["tier"] == "standing"] + if benchmarked and len(benchmarked) < len(capable): + return benchmarked, False # a benchmark standing outranks a class's place in its maker's order return list(capable), False @@ -574,7 +621,7 @@ def _select(eligible, assessments, difficulty): return weak, "weak" top = max(strength(assessments[c["worker"]]) for c in live) pool = [c for c in live if strength(assessments[c["worker"]]) == top] - return pool, ("nothing" if top[0] <= 1 else "strongest") + return pool, ("nothing" if top[:2] <= (1, 0) else "strongest") def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(), @@ -585,7 +632,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, now = float(now or 0) eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts) - assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors) + assessments, best = _assess_all(eligible, inherit_stats(candidates, stats, opts), kind, difficulty, floors, opts) key, rate, load_ratio, recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible)) pool, basis = _select(eligible, assessments, difficulty) if eligible else ([], "none") @@ -652,22 +699,27 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}, "assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first, "best_standing": best, "passed_detail": detail, "floors": floors, - "superseded": superseded, "class_ask": class_ask(eligible), + "superseded": superseded, "class_ask": class_ask(eligible, opts), "kind": kind, "difficulty": difficulty} -def class_ask(eligible): - """What the lead agent should be asked to record, because it is about to matter: {"classify": [workers]}. - A worker whose class could not be read from its id, when another usable worker has the same maker (the two - may be versions of one class). A class read from the id with confidence is not asked about; a recorded one - never is.""" - makers = {} +def class_ask(eligible, opts=None): + """What the lead agent should be asked to record, because it is about to matter: + {"classify": [workers], "order": [(maker, [class labels])]}. + classify: a worker whose class could not be read from its id, when another usable worker has the same maker (the + two may be versions of one class). A class read from the id with confidence is not asked about; a recorded one + never is. order: a maker with two or more classes among the usable workers and no recorded class order.""" + makers, labels = {}, {} for c in eligible: l = _lineage(c) if l: makers.setdefault(l.get("maker"), []).append(c["worker"]) + if l.get("key"): + labels.setdefault(l.get("maker"), set()).add(l.get("label")) + recorded = (opts or {}).get("class_orders") or {} return {"classify": sorted(c["worker"] for c in eligible if _lineage(c) - and _lineage(c).get("source") == "unknown" and len(makers.get(_lineage(c).get("maker"), [])) > 1)} + and _lineage(c).get("source") == "unknown" and len(makers.get(_lineage(c).get("maker"), [])) > 1), + "order": [(m, sorted(ls)) for m, ls in sorted(labels.items()) if len(ls) > 1 and m not in recorded]} def _why_not(a, difficulty, basis, cheaper): @@ -683,9 +735,14 @@ def _why_not(a, difficulty, basis, cheaper): if a["tier"] == "b-all": return (lead + "its only judged proof is across other kinds, and a worker with a judged record " "for this kind is usable", None) - return (lead + "capable only by benchmark standing or as an exploration; above difficulty 1 a worker " - "with a judged record is preferred to a benchmark", + return (lead + "capable only by benchmark standing, its class's place in its maker's order, or as an " + "exploration; above difficulty 1 a worker with a judged record is preferred to a benchmark, and a " + "benchmark to a class order", ("standing %g" % a["standing"]) if a["standing"] is not None else None) + if a["tier"] == "class": + return (lead + "not capable enough for difficulty %d: its class is place %d of %d in its maker's recorded order, " + "and difficulty %d reaches only the top %g%% of it" % (difficulty, a["class_pos"] + 1, a["class_n"], + difficulty, a["class_allowed"]), None) if a.get("below"): return (lead + "not capable enough for difficulty %d: benchmark standing under the %g needed " "(%g%% of the best usable standing, %g)" % (difficulty, a["needed"], a["floor"], a["best"]), @@ -720,7 +777,7 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts) eff = inherit_stats(candidates, stats, opts) - assessments, best = _assess_all(eligible, eff, kind, difficulty, floors) + assessments, best = _assess_all(eligible, eff, kind, difficulty, floors, opts) key, _rate, _load, _recency = _make_key(stats, kind, difficulty, prefer, recency_order(eligible)) out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker, "assessments": assessments, "best_standing": best, "kind": kind, "difficulty": difficulty, @@ -736,7 +793,8 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected, return out gone = next((c for c in candidates if c["worker"] == rejected), None) floor = (strength(assessments[rejected]) if mine is not None else - strength(assess(eff, rejected, kind, difficulty, _standing_of(gone) if gone else None, best, floors))) + strength(assess(eff, rejected, kind, difficulty, _standing_of(gone) if gone else None, best, floors, + rank=class_rank(gone, opts) if gone else None, spans=(opts or {}).get("class_span")))) better = [c for c in others if assessments[c["worker"]]["capable"] and strength(assessments[c["worker"]]) > floor] better = _prefer_judged(better, assessments, difficulty)[0] if better: @@ -800,6 +858,10 @@ def _evidence_line(a, kind, difficulty, choice, basis): return ("evidence (c), benchmark standing only: %g (%s, %s), the strongest known; it is under the %g " "needed for difficulty %d" % (a["standing"], src, choice.get("standing_date") or "no date stated", a["needed"], difficulty)) + if tier == "class": + return ("evidence (class order): place %d of %d in its maker's recorded class order, which reaches the top %g%% " + "for difficulty %d; no judged record or benchmark decides" % (a["class_pos"] + 1, a["class_n"], + a["class_allowed"], difficulty)) if tier == "unknown": return "evidence (d): nothing is known about this worker yet; it is an exploration on low-stakes work" if a.get("weak"): diff --git a/sisi/workers.py b/sisi/workers.py index 0a0f5ec..f884f61 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -597,10 +597,15 @@ def model_words(): def route_opts(): - """Routing options from the config: `route.supersede_guessed` (default true) lets a class read from the id with - confidence, not yet recorded by the lead agent, take part in the rule that the newest version of a class wins.""" + """Routing options: `route.supersede_guessed` (default true) lets a class read from the id with confidence, not yet + recorded by the lead agent, take part in the rule that the newest version of a class wins; the maker class orders + the lead agent recorded (`sisi workers classes`); and `route.class_span`, how far down an order each difficulty + reaches.""" v = route_cfg().get("supersede_guessed") - return {"supersede_guessed": v if isinstance(v, bool) else True} + orders = {m: [str(x) for x in e["order"]] for m, e in load_model_facts()[1].items() + if isinstance(e, dict) and isinstance(e.get("order"), list)} + return {"supersede_guessed": v if isinstance(v, bool) else True, "class_orders": orders, + "class_span": route_cfg().get("class_span")} def route_floors(): @@ -1461,6 +1466,8 @@ def cmd_workers(args=()): return _cmd_only(args[1:]) if args[:1] == ["note"]: return _cmd_note(args[1:]) + if args[:1] == ["classes"]: + return _cmd_classes(args[1:]) if args[:1] == ["down"]: return _cmd_down(args[1:]) if args[:1] == ["up"]: @@ -1519,6 +1526,9 @@ def cmd_workers(args=()): for standing, worker, entry in standings: print(" benchmark standing %g - %s: %s (%s)" % (standing, worker, entry.get("source") or "no source stated", entry.get("date") or "no date stated")) + for maker, e in sorted(load_model_facts()[1].items()): + if isinstance(e, dict): + print(_classes_line(maker, e)) routable, cold, _excluded = routable_candidates(build_candidates(disc, records), records) if routable and not cold: print("Model lines (the class of each routable worker; a guess is read from the id alone: confirm it " @@ -1586,7 +1596,12 @@ def _route_setup(args): def class_line(result): """The one line asking the lead agent to determine a class sisi cannot read from the id, or None.""" - names = (result.get("class_ask") or {}).get("classify") or [] + ask = result.get("class_ask") or {} + names = ask.get("classify") or [] + if not names and ask.get("order"): + maker, labels = ask["order"][0] + return ("sisi: classify %s's models and record the order, most capable first: `sisi workers classes %s %s --source S` " + "(classes seen: %s)" % (maker, maker, " ".join(labels), ", ".join(labels))) if not names: return None return ("sisi: the class of %s%s cannot be read from its id: decide it and record it with " @@ -2096,6 +2111,48 @@ def _model_fact_args(args): return out +def _cmd_classes(args): + """`sisi workers classes MAKER CLASS [CLASS...] --source S` records a maker's classes, most capable first; + `sisi workers classes MAKER --remove` forgets them; no arguments lists them.""" + usage = ("usage: sisi workers classes MAKER CLASS [CLASS...] --source S [--date YYYY-MM-DD] (most capable class first)\n" + " sisi workers classes MAKER --remove") + data = read_json(models_path()) + classes = data.get("classes") if isinstance(data.get("classes"), dict) else {} + pos = _positional(args, ("--source", "--date")) + if not pos: + for maker, e in sorted(classes.items()): + print(_classes_line(maker, e)) + return 0 if classes else (print("no class order recorded yet.\n" + usage) or 0) + maker, names = pos[0].strip().lower(), [x.strip().lower() for x in pos[1:]] + if "--remove" in args: + if names or maker not in classes: + print(usage if names else "sisi: no class order is recorded for %s" % maker, file=sys.stderr) + return 1 + del classes[maker] + data["classes"] = classes + write_json(models_path(), data) + print("removed the class order of %s" % maker) + return 0 + source = _opt(args, "--source") + if not names or not source: + print(usage, file=sys.stderr) + return 1 + if any(not _NAME.fullmatch(x) for x in [maker] + names) or len(set(names)) != len(names): + print("sisi: a maker and each class is one short name (letters, digits, hyphens), none repeated", file=sys.stderr) + return 1 + entry = {"order": names, "source": source, "date": _opt(args, "--date") or time.strftime("%Y-%m-%d", time.localtime())} + classes[maker] = entry + data["classes"] = classes + write_json(models_path(), data) + print(_classes_line(maker, entry).strip().replace("Classes of", "recorded the classes of", 1)) + return 0 + + +def _classes_line(maker, e): + return "Classes of %s, most capable first: %s (%s, %s)" % (maker, ", ".join(e.get("order") or []), + e.get("source") or "no source stated", e.get("date") or "no date stated") + + def _cmd_pref(kind, args): prefs = load_prefs() if not args: diff --git a/tests/test_model_classes.py b/tests/test_model_classes.py new file mode 100644 index 0000000..2578df0 --- /dev/null +++ b/tests/test_model_classes.py @@ -0,0 +1,138 @@ +"""A maker's classes, most capable first: a prior between classes of that maker where nothing better exists, never +above a judged record or a benchmark standing. Invented ids: for this maker each class is a named line. +Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" +import json, os, random, unittest +from support import * +from sisi import routing +from test_model_supersession import cand, attempts, pick, NOW +from test_worker_models import ModelCase + +ORDER = {"abc": ["fable", "opus", "sonnet", "haiku"]} +COST = {"fable": 9.0, "opus": 6.0, "sonnet": 3.0, "haiku": 1.0} + + +def fleet(**extra): + return [cand("prov/abc-%s-5" % c, **dict({"cost": COST[c]}, **extra.get(c, {}))) for c in ("fable", "opus", "sonnet", "haiku")] + + +def best(cands, difficulty, records=(), **kw): + opts = {"class_orders": ORDER} + opts.update(kw.pop("opts", {})) + return pick(cands, records, difficulty, opts=opts, **kw) + + +class ClassOrderTests(unittest.TestCase): + def test_routine_work_goes_to_the_lowest_class_and_hard_work_to_the_upper_ones(self): + """Nothing judged, no benchmark: the order is the prior and the cheapest capable class wins.""" + cands = fleet() + self.assertEqual(best(cands, 1)[0], "prov/abc-haiku-5") + self.assertEqual(best(cands, 2)[0], "prov/abc-sonnet-5") + who, r = best(cands, 3) + self.assertEqual(who, "prov/abc-opus-5") + self.assertEqual(r["assessments"]["prov/abc-opus-5"]["tier"], "class") + self.assertFalse(r["assessments"]["prov/abc-sonnet-5"]["capable"]) + + def test_the_mapping_is_configurable(self): + cands = fleet() + self.assertEqual(best(cands, 3, opts={"class_span": {"3": 0}})[0], "prov/abc-fable-5") + self.assertEqual(best(cands, 3, opts={"class_span": {"3": 100}})[0], "prov/abc-haiku-5") + self.assertEqual(routing.class_spans({"2": "x", "9": 50, "1": 101})[1], 100.0) + + def test_without_a_recorded_order_a_class_is_no_evidence(self): + who, r = pick(fleet(), (), 3) + self.assertEqual(r["basis"], "nothing") + self.assertFalse(any(a["tier"] == "class" for a in r["assessments"].values())) + + def test_a_judged_record_outranks_the_order(self): + records = attempts("prov/abc-haiku-5", 12, 12, difficulty=3) + who, r = best(fleet(), 3, records) + self.assertEqual(who, "prov/abc-haiku-5") + self.assertEqual(r["assessments"]["prov/abc-haiku-5"]["tier"], "a") + + def test_a_benchmark_standing_outranks_the_order(self): + cands = fleet(haiku={"standing": 80.0, "cost": 5.0}) + who, r = best(cands, 2) + self.assertEqual(who, "prov/abc-haiku-5") # sonnet is capable by class and cheaper than none, but the standing is preferred + self.assertEqual(r["assessments"]["prov/abc-haiku-5"]["tier"], "standing") + self.assertTrue(any("benchmark" in why for w, why in r["passed_over"] if w == "prov/abc-sonnet-5")) + + def test_when_nobody_is_proven_the_strongest_known_means_the_highest_class(self): + cands = [c for c in fleet() if c["worker"] in ("prov/abc-sonnet-5", "prov/abc-haiku-5")] + who, r = best(cands, 3) + self.assertEqual((who, r["basis"]), ("prov/abc-sonnet-5", "strongest")) + + def test_another_makers_models_are_not_placed_by_this_order(self): + other = cand("prov/xyz-opus-5", cost=0.1, maker="xyz") + who, r = best(fleet() + [other], 3) + self.assertEqual(who, "prov/abc-opus-5") + self.assertNotEqual(r["assessments"]["prov/xyz-opus-5"]["tier"], "class") + + def test_a_class_missing_from_the_order_is_not_placed(self): + extra = cand("prov/abc-ember-1", cost=0.1) + who, r = best(fleet() + [extra], 3) + self.assertNotEqual(r["assessments"]["prov/abc-ember-1"]["tier"], "class") + + def test_the_asking_line_wants_the_order_of_a_maker_with_several_classes(self): + r = pick(fleet(), (), 3)[1] + self.assertEqual(r["class_ask"]["order"], [("abc", ["fable", "haiku", "opus", "sonnet"])]) + r = best(fleet(), 3)[1] + self.assertEqual(r["class_ask"]["order"], []) + one = pick([cand("prov/abc-opus-5"), cand("prov/abc-opus-6")], (), 3)[1] + self.assertEqual(one["class_ask"]["order"], []) # one class only: nothing to order + + def test_property_the_order_never_outranks_a_record_or_a_standing(self): + rng = random.Random(9) + for _ in range(300 * ITERS): + cands = [cand("prov/abc-%s-5" % c, cost=rng.choice([1.0, 2.0, 5.0]), + standing=rng.choice([None, None, 40.0, 90.0])) for c in rng.sample(list(COST), rng.randint(2, 4))] + records = [] + for c in cands: + for d in (1, 2, 3): + if rng.random() < 0.4: + n = rng.choice([3, 10, 12]) + records += attempts(c["worker"], n, rng.randint(0, n), difficulty=d) + d = rng.choice([2, 3]) + who, r = best(cands, d, records) + if who is None or r["basis"] != "capable": + continue + tiers = {w: a["tier"] for w, a in r["assessments"].items() if a["capable"]} + if any(t in ("a", "b-higher", "b-all") for t in tiers.values()): + self.assertIn(tiers[who], ("a", "b-higher", "b-all")) + elif any(t == "standing" for t in tiers.values()): + self.assertEqual(tiers[who], "standing") + + +class ClassesCommandTests(ModelCase): + def test_a_makers_classes_are_recorded_shown_and_removed(self): + self.seed([("prov/abc-5.3", 9, 9)]) + r = self.sisi("workers", "classes", "abc", "fable", "opus", "sonnet", "haiku", "--source", "owner, in his words", env=self.env()) + self.assertEqual(r.returncode, 0, r.stderr) + stored = json.load(open(os.path.join(self.data, "worker-models.json")))["classes"]["abc"] + self.assertEqual((stored["order"], stored["source"]), (["fable", "opus", "sonnet", "haiku"], "owner, in his words")) + self.assertIn("Classes of abc, most capable first: fable, opus, sonnet, haiku (owner, in his words", self.listing()) + self.assertEqual(self.sisi("workers", "classes", "abc", "--remove", env=self.env()).returncode, 0) + self.assertNotIn("Classes of abc", self.listing()) + + def test_bad_input_is_refused(self): + for args in (("abc", "opus"), ("abc", "--source", "x"), ("abc", "o pus", "--source", "x"), ("abc", "opus", "opus", "--source", "x")): + r = self.sisi("workers", "classes", *args, env=self.env()) + self.assertEqual(r.returncode, 1, args) + self.assertFalse(os.path.exists(os.path.join(self.data, "worker-models.json"))) + + def test_route_uses_the_recorded_order_and_asks_for_it_until_then(self): + models = ("abc-fable-5", "abc-opus-5", "abc-sonnet-5", "abc-haiku-5") + for m in models: + self.sisi("workers", "fact", "muse/" + m, "--price", str(COST[m.split("-")[1]]), "--source", "fixture", env=self.env(models)) + first = self.route(3, models=models) + self.assertIn("record the order", first.stdout) + self.assertLessEqual(len(first.stdout.splitlines()), 7, first.stdout) + self.sisi("workers", "classes", "abc", "fable", "opus", "sonnet", "haiku", "--source", "owner", env=self.env(models)) + after = self.route(3, "--explain", models=models) + self.assertEqual(after.stdout.splitlines()[0], "muse/abc-opus-5", after.stdout) + self.assertNotIn("record the order", after.stdout) + self.assertIn("class order", after.stdout) + self.assertEqual(self.route(1, models=models).stdout.splitlines()[0], "muse/abc-haiku-5") + + +if __name__ == "__main__": + unittest.main() From d36550d00f514e418a916d551d2ae0ba1ed4d538 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:45:08 -0700 Subject: [PATCH 7/8] Classification by recorded facts only: no name parser or tier words, no guessed classes; sisi workers classify prints the question for a cheap worker and --record validates and stores its answer; identity (maker, class) and release date drive supersession, inheritance, tie-break; route and session start ask only when it matters. done / next: proof on a copy, repeat runs, report Co-Authored-By: Claude Sonnet 5.5 --- canon/model-words.json | 5 - canon/orchestration.md | 9 +- config.default.json | 1 - docs/workers.md | 43 +++--- sisi/helptext.py | 2 +- sisi/modelid.py | 201 ------------------------- sisi/routing.py | 111 +++++++++----- sisi/workers.py | 212 +++++++++++++++++--------- tests/test_model_classes.py | 13 +- tests/test_model_inheritance.py | 33 +++-- tests/test_model_recency.py | 32 ++-- tests/test_model_supersession.py | 245 ++++++++++++++++--------------- tests/test_modelid.py | 118 --------------- tests/test_worker_classify.py | 128 ++++++++++++++++ tests/test_worker_models.py | 143 +++++++++--------- 15 files changed, 619 insertions(+), 677 deletions(-) delete mode 100644 canon/model-words.json delete mode 100644 sisi/modelid.py delete mode 100644 tests/test_modelid.py create mode 100644 tests/test_worker_classify.py diff --git a/canon/model-words.json b/canon/model-words.json deleted file mode 100644 index 07fb29f..0000000 --- a/canon/model-words.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "about": "Words that appear in model ids. They are data, not code: edit this file when a maker invents a new tier word. A tier word names the class of a model inside its line (it comes before or after the version number; no tier word means the line's standard model). An ignored word is neither the line nor the class (a stage, a price label, a style). A word in neither list that follows the version is a word this file does not know, so the class of that model is reported as unknown until the lead agent records it with `sisi workers fact WORKER --class NAME --source S`.", - "tiers": ["air", "base", "code", "coder", "fast", "flash", "full", "highspeed", "large", "lite", "max", "medium", "micro", "mini", "nano", "plus", "pro", "small", "tiny", "turbo", "ultra"], - "ignore": ["beta", "chat", "contributor", "default", "exp", "experimental", "free", "instruct", "latest", "new", "preview", "rc", "stable", "thinking"] -} diff --git a/canon/orchestration.md b/canon/orchestration.md index 7ea3b82..0f6b02a 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -37,10 +37,11 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. version of it: newer models are almost always better and almost always cheaper, so neither a better old record nor a cheaper old plan brings an older version back. A new version starts from its predecessor's judged record until it has its own. Two exceptions only: the newer model - is unusable right now (down, out of allowance, avoided), or its class is not known yet. Classes - are not versions of each other: a maker's "flash" is a different thing from its standard model, - and a maker's separately named lines are different classes. Determine the class of a model - before comparing it with another (`sisi workers fact W --class NAME`), and a maker's classes, + is unusable right now (down, out of allowance, avoided), or its class is not recorded yet. + Classes are not versions of each other: a maker's "flash" is a different thing from its + standard model, and a maker's separately named lines are different classes. Never guess a class + from a name: have a cheap, fast worker research each model's maker, class and release date, + record them (`sisi workers fact W --maker M --class C --released D`), and record a maker's classes, most capable first, with `sisi workers classes`. A newer model that measures badly is replaced by a different class or maker, never by its older version. - Ask `sisi route --kind K --difficulty N` before delegating; `--explain` says diff --git a/config.default.json b/config.default.json index 7e1bda5..23351c2 100644 --- a/config.default.json +++ b/config.default.json @@ -18,7 +18,6 @@ "3": 85 }, "price_blend_input_parts": 3, - "supersede_guessed": true, "class_span": { "1": 100, "2": 70, diff --git a/docs/workers.md b/docs/workers.md index efba62e..de30cd1 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -20,9 +20,16 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano A fact without a source is refused. Ranking uses one blend of the two prices, by default three parts input to one part output (`route.price_blend_input_parts`); `sisi workers` shows both prices and the blend, and lists each benchmark standing apart from the accepted rates it prints. -- `sisi workers fact WORKER --class NAME [--family NAME] [--maker M] [--released YYYY-MM-DD] --source S` — the - class, line and release date the lead agent decided for a model; a recorded fact beats the parser. - `sisi workers` lists each routable worker's maker, class (recorded, or a guess read from the id) and recency. +- `sisi workers fact WORKER --maker M --class NAME [--released YYYY-MM-DD] --source S` — the maker, class and + release date researched for a model. `sisi workers` lists each routable worker's recorded maker, class and release date. +- `sisi workers classify [--record FILE [--by WORKER]]` — sisi reads nothing from a model's name. Without + arguments it prints a short instruction and the ids of routable workers that have no classification; hand + that to a fast, cheap worker (it takes seconds). The answer is one small JSON object: for each id its maker, + class and release date (`unknown` where it does not know), and for each maker its classes from most to least + capable. `--record FILE` validates it (an id that was not asked about refuses the whole answer; `unknown` is + stored as unknown and changes nothing in routing) and stores the facts with the classifying worker as the + source; a class order already recorded is never overwritten. Session start names unclassified workers in its + one facts line, and `sisi route` adds one line only when an unclassified worker is in the running. - `sisi workers classes MAKER CLASS [CLASS...] --source S` — a maker's classes from most capable to least (`--remove` forgets them). A class is the tier word of one line (a "flash" beside the standard model) or, for a maker whose lines are the classes, the line's own name; `sisi workers` shows both as the class label. @@ -91,22 +98,20 @@ one per group of workers passed over as not capable enough, and names an explora ## Newest version of a class, always Newer models are almost always better and almost always cheaper, so `sisi route` always uses the -most recently released model of a class that is usable, and never an older version of it. A -model's identity is its maker, its line and its class, read from the id by `sisi/modelid.py` -(version numbers compared numerically, a date in the id as a date, tier words such as a "flash" or -"mini" from `canon/model-words.json`) and overridden by what the lead agent records: -`sisi workers fact WORKER --class NAME [--family NAME] [--maker M] [--released YYYY-MM-DD] --source S`. -A recorded release date beats version numbers for recency. The same model through two providers is -one model: if its newest version is usable through any provider, older versions do not compete -through any provider, and the existing cost comparison picks the provider. There is no exception for -a better old record or a cheaper old plan. The older version competes again only while the newer is -unusable (marked down, allowance spent, avoided by the user, or limited away), or when its class is -unknown. A newer model with a thick bad record is not replaced by its older version either: routing -moves to another class or maker by the usual rules. Different classes are different things and never -supersede each other. A class read from the id with confidence takes part at once -(`route.supersede_guessed`, default true; false lets only recorded classes take part); a class that -cannot be read (no version, or a word the data does not know) never does, and `sisi route` adds one -line asking the lead agent to record it. +most recently released model of a class that is usable, and never an older version of it. sisi reads +nothing from a model's name: a model's maker, class and release date are facts, researched by a cheap, +fast worker (session start and `sisi route` say when they are missing) and recorded with +`sisi workers fact WORKER --maker M --class C --released YYYY-MM-DD --source S`. A model's identity is its +maker and class; recency is its release date. For a maker whose lines are the classes the class is the +line's own name; for a maker with a "flash" beside its standard model it is `flash` or `standard`. A model +with no recorded maker and class is never compared with another. The same model through two providers is +one model: if its newest version is usable through any provider, older versions do not compete through any +provider, and the existing cost comparison picks the provider. There is no exception for a better old +record or a cheaper old plan. The older version competes again only while the newer is unusable (marked +down, allowance spent, avoided by the user, or limited away) or has no recorded class. A newer model with a +thick bad record is not replaced by its older version either: routing moves to another class or maker by the +usual rules. Different classes are different things and never supersede each other. A bare host alias with a +recorded class and no release date counts as the newest version of its class. The class order is a prior and nothing more. A worker with no judged proof and no benchmark standing, whose class is in its maker's recorded order, is capable when the class sits high enough for the diff --git a/sisi/helptext.py b/sisi/helptext.py index f629492..bb9ab49 100644 --- a/sisi/helptext.py +++ b/sisi/helptext.py @@ -31,7 +31,7 @@ LONG = { 'status': ' sisi status [--json] [--learning] recent units with their scorecards, then trends by project, risk profile, model and policy version (median and p95; no single score); --learning prints only the learning report', 'verifiers': ' sisi verifiers [WORDS] [--lang L] [--kind K] [--rung N] [--section S] [--installed] [--json]\n list ways to know work is correct, by section\n sisi verifiers show ID [--trace] one entry in full, and whether its tool is installed here; --trace also prints where each folded lesson lives in it\n sisi verifiers for "" best-matching verifiers for a claim or piece of work\n sisi verifiers doctor | lint which tools are installed; validate the library', 'done': ' sisi done [ID] [--trace] recipes: which checks make a kind of work done; --trace also prints where each folded lesson lives in the recipe\n sisi done for "" best-matching recipe', - 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --class NAME [--family NAME] [--released DATE] --source S the class, line and release date you decided for a model; beats the parser\n sisi workers classes MAKER CLASS... --source S | MAKER --remove the classes of a maker, most capable first (a prior between them)\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', + 'workers': ' sisi workers [--refresh] the agent tools and models found here, what is usable now and why not, allowance and price where known, delegations waiting for a judgement, and the judged record as three tables\n sisi workers fact W --price N|--standing N --source S record a price (per million tokens) or benchmark standing (0-100), with its source and date\n sisi workers fact W --maker M --class C [--released DATE] --source S the maker, class and release date researched for a model\n sisi workers classify [--record FILE [--by WORKER]] the question for a cheap worker (maker, class, release date of routable models), or store its answer\n sisi workers classes MAKER CLASS... --source S | MAKER --remove the classes of a maker, most capable first (a prior between them)\n sisi workers avoid|prefer PATTERN --why TEXT your own routing constraints, honoured by `sisi route`\n sisi workers only PROVIDER PATTERN... --why TEXT | --remove make only the matching models of that provider routable\n sisi workers note PATTERN \"TEXT\" --why SOURCE | --remove a standing fact about workers matching PATTERN, shown with route results\n sisi workers down W --reason limit|auth|missing|error [--until DATE|TIME] | up W mark a worker unavailable / available again\n sisi workers import FILE merge another ledger file into the delegation ledger (row counts printed; safe to repeat)', 'route': ' sisi route --kind K --difficulty N [--review-of W] [--explain]\n the most affordable usable worker for this kind and difficulty, and the mechanism to start it with (host subagents, host cross-provider delegation, or sisi delegate); --explain says why', 'delegate': ' sisi delegate brief | check FILE | guide the delegation-contract template (eight parts); which parts a brief lacks; the orchestration playbook\n sisi delegate --kind K --difficulty N --brief FILE [--worker W] [--review-of W] [--cwd DIR]\n run one brief on the chosen worker unattended; prints only its final report, the transcript path, and the judge command; a brief without outcome, acceptance or files it may change is refused\n sisi delegate judge ID --outcome accepted|rejected --check none|diffstat|tests|read|review [--minutes N]\n record your judgement of a delegation run, so the next choice learns from it; judge work run any other way with --worker W --type K --difficulty N instead of ID\n sisi delegate amend ID | recent [-n N] [--project P] mark a judged delegation that later proved wrong; list recent judgements to find an id', 'eval': ' sisi eval list|add|run|compare|shadow|judge|status|import\n the evaluation harness: benchmark cases from real work, isolated\n replay, policy comparison and independent judging (see docs/evaluation.md);\n `sisi eval` alone prints status; run without --tasks replays check cases only', diff --git a/sisi/modelid.py b/sisi/modelid.py deleted file mode 100644 index eaf8adb..0000000 --- a/sisi/modelid.py +++ /dev/null @@ -1,201 +0,0 @@ -"""Reading a model id: its maker, line, class and version. Pure: no file access, no clock. - -A first guess from the name alone, and the recorded facts that override it. The words that mark -a class (tier words) or mean nothing (ignored words) are data passed in, loaded from -canon/model-words.json by the caller. - -What is read from an id (the part after the provider, case aside): - version the numbers in it, as a tuple compared numerically (5.10 is newer than 5.9); a date in it - (20261101 or 2026-11-01) is kept apart and compared as a date. A letter in front of a number - (v4.1, k2.7) is a marker and is dropped. - line the name words before the version that identify the model line (the maker's own name leading - them is dropped: "abc-flash-5.4" and "abc-5.4-flash" both have no extra line name). - class the tier words, before or after the version, or "standard" when there is none. The class - label for ordering and display adds the line when there is one: "wonder", "wonder-full". - maker a recorded maker fact, else the first name word. -An id with no version, or with a word after the version that the data does not know, cannot be read -with confidence: its class is "unknown" and it takes part in no comparison of versions. - -A recorded fact (class, family, released, maker) always beats the reading. A bare host alias with no -version in it (the host resolves it to its current model of that class) counts as the newest version -of its class, once a class fact says which class that is. -""" -import re - -STANDARD = "standard" -UNKNOWN = "unknown" -_DATE = re.compile(r"(? 1 or not names): - names.append(prefix) - number(num) - elif _SUFFIXED.fullmatch(t): - num, suffix = _SUFFIXED.fullmatch(t).groups() - number(num) - if suffix in ignored: - continue - word(suffix) - elif _WORD.fullmatch(t): - word(t) - else: - unknown.append(t) - if started: - closed = True - first = names[0] if names else "" - mk = (str(maker).lower() if maker else first) - line = list(names) - if line and line[0] == mk: - line = line[1:] - cls = "-".join(tiers) if tiers else STANDARD - version = tuple(nums) - date = max(dates) if dates else None - confident = bool(names) and bool(version or date) and not unknown - return {"maker": mk, "line": "-".join(line), "family": "-".join(names), "tiers": tuple(tiers), - "class": cls if confident else UNKNOWN, "label": _label("-".join(line), cls) if confident else UNKNOWN, - "version": version or None, "date": date, "confident": confident, "unknown_tokens": unknown} - - -def _label(line, cls): - """The class as the maker's classes are listed: the line name and the tier, or "standard".""" - if cls in (None, "", STANDARD): - return line or STANDARD - return "%s-%s" % (line, cls) if line else cls - - -def _normal_class(line, cls): - """A recorded class, lower case, with the line name taken off when the lead agent wrote the whole label.""" - c = str(cls or "").strip().lower() - if c in (line, "") and line: - return STANDARD - if line and c.startswith(line + "-"): - return c[len(line) + 1:] - return c or STANDARD - - -def resolve(worker, words, fact=None, host_native=False, maker_hint=None): - """The model's identity: parse the id, then let a recorded fact override it. Returns - {key, maker, line, class, label, version, date, released, alias, source} - source is "fact" (recorded), "guess" (read from the id, not yet confirmed) or "unknown" - (no key: the model takes part in no comparison of versions).""" - fact = fact if isinstance(fact, dict) else {} - p = parse(worker, words, maker=fact.get("maker") or maker_hint) - released = str(fact["released"]) if fact.get("released") else None - maker = p["maker"] - line = str(fact["family"]).strip().lower() if fact.get("family") else p["line"] - if fact.get("family") and line == maker: - line = "" - out = {"key": None, "maker": maker, "line": line, "class": UNKNOWN, "label": UNKNOWN, "version": p["version"], - "date": p["date"], "released": released, "alias": False, "source": UNKNOWN} - if fact.get("class"): - cls = _normal_class(line, fact["class"]) - out.update(source="fact") - elif p["confident"]: - cls = p["class"] - out.update(source="guess") - else: - return out - out.update({"class": cls, "label": _label(line, cls), "key": (maker, line, cls)}) - if host_native and not (p["version"] or p["date"]) and out["source"] == "fact": - out["alias"] = True - return out - - -def compare(a, b): - """1 when a is the more recently released model, -1 when b is, 0 when equal or unknowable. A recorded - release date on both decides; else the version numbers on both; else the dates in the ids on both. A bare - alias is the newest of its class.""" - if a.get("alias") or b.get("alias"): - return (1 if a.get("alias") else 0) - (1 if b.get("alias") else 0) - ra, rb = a.get("released"), b.get("released") - if ra and rb and ra != rb: - return 1 if ra > rb else -1 - va, vb = a.get("version"), b.get("version") - if va and vb: - n = max(len(va), len(vb)) - pa, pb = tuple(va) + (0,) * (n - len(va)), tuple(vb) + (0,) * (n - len(vb)) - if pa != pb: - return 1 if pa > pb else -1 - da, db = a.get("date"), b.get("date") - if da and db and da != db: - return 1 if da > db else -1 - return 0 - if not va and not vb: - da, db = a.get("date"), b.get("date") - if da and db and da != db: - return 1 if da > db else -1 - return 0 - - -def days(date): - """A YYYY-MM-DD date as a number of days that sorts correctly (months of 31 days: only the order matters); 0 when - there is no date.""" - d = str(date or "") - if len(d) >= 10 and d[:4].isdigit() and d[5:7].isdigit() and d[8:10].isdigit(): - return int(d[0:4]) * 372 + int(d[5:7]) * 31 + int(d[8:10]) - return 0 diff --git a/sisi/routing.py b/sisi/routing.py index e374603..b859d70 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -47,12 +47,12 @@ The rule, in order: 7. The newest usable version of a maker's class always wins over its older versions (see `superseded_by`): no better record and no cheaper plan on the older version brings it back. The older one competes again only while the newer one is unusable. The class is read from the - id and overridden by what the lead agent recorded (sisi/modelid.py); a model whose class is - unknown is never compared. + recorded facts (see lineage_from_fact): maker, class and release date; a model with no recorded class + is never compared. 8. Load balancing: within the same price tier and price, the worker that has taken the least work relative to its remaining allowance goes first (recorded uses divided by allowance left, an - unknown allowance counting as half). Ties break on the more recently released model (a recorded - release date, else the version inside one maker's class), then on the worker id. + unknown allowance counting as half). Ties break on the more recently released model (its recorded + release date), then on the worker id. Candidates reach here already restricted to workers with a judged record, a known price or a benchmark standing (see workers.routable_candidates); on a cold start none qualifies and every @@ -61,8 +61,6 @@ usable worker is offered, with the explanation saying so. import functools import re -from . import modelid - MIN_ATTEMPTS = 8 # below this, a worker's record for a kind and difficulty is thin MIN_ACCEPTED_RATE = 0.6 # "good enough" among workers with at least MIN_ATTEMPTS attempts CONTRADICTION_REJECTIONS = 2 # a thin record with this many rejections below the bar cancels a prior @@ -74,6 +72,55 @@ DEFAULT_CLASS_SPAN = {1: 100.0, 2: 70.0, 3: 35.0} # how far down a maker's clas DEFAULT_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price +# ---------------------------------------------------------------- a model's identity, from recorded facts only +# +# sisi reads nothing from a model's name. A model's maker, class and release date are facts, researched by a +# cheap, fast worker (`sisi workers classify`) and recorded with `sisi workers fact`. A model with no recorded +# maker and class has no identity and takes part in no comparison of versions. +# identity (maker, class). For a maker whose lines are the classes, the class is the line's own name; for a +# maker with a "flash" beside its standard model, the class is "flash" or "standard". Different +# classes are different things and never replace each other. +# recency the recorded release date (YYYY-MM-DD or YYYY-MM). A bare host alias with a recorded class and no +# release date counts as the newest version of its class. + +UNKNOWN = "unknown" + + +def lineage_from_fact(fact=None, host_native=False): + """{key, maker, class, label, released, alias, source} from a model's recorded facts. source is "fact" when + both a maker and a class are recorded, else "unknown" (key None: no comparison of versions).""" + fact = fact if isinstance(fact, dict) else {} + cls = str(fact.get("class") or "").strip().lower() + maker = str(fact.get("maker") or "").strip().lower() + cls, maker = ("" if cls == UNKNOWN else cls), ("" if maker == UNKNOWN else maker) # "unknown" is an answer, not a fact + released = str(fact["released"]) if fact.get("released") and fact["released"] != UNKNOWN else None + out = {"key": None, "maker": maker, "class": cls or UNKNOWN, "label": cls or UNKNOWN, "released": released, + "alias": False, "source": UNKNOWN} + if cls and maker: + out.update(key=(maker, cls), source="fact", alias=bool(host_native and not released)) + return out + + +def compare_release(a, b): + """1 when a is the more recently released model, -1 when b is, 0 when equal or unknowable. A bare alias is the + newest of its class; otherwise the recorded release dates decide.""" + if a.get("alias") or b.get("alias"): + return (1 if a.get("alias") else 0) - (1 if b.get("alias") else 0) + da, db = days(a.get("released")), days(b.get("released")) + if da and db and da != db: + return 1 if da > db else -1 + return 0 + + +def days(date): + """A YYYY-MM-DD or YYYY-MM date as a number that sorts correctly (months of 31 days: only the order matters); + 0 when there is no date.""" + d = str(date or "") + if len(d) >= 7 and d[:4].isdigit() and d[5:7].isdigit() and (len(d) == 7 or (len(d) >= 10 and d[8:10].isdigit())): + return int(d[0:4]) * 372 + int(d[5:7]) * 31 + (int(d[8:10]) if len(d) >= 10 else 0) + return 0 + + def maker_of(name): """A best-effort maker derived from a worker or model id: the first word of the model part. A stored `maker` fact wins wherever a candidate carries one; no table of names ships here.""" @@ -217,9 +264,9 @@ def _versions_newest_first(models): providers is one version).""" out = [] ordered = sorted(models, key=lambda d: d["worker"]) - ordered.sort(key=functools.cmp_to_key(lambda a, b: modelid.compare(_lineage(b), _lineage(a)))) + ordered.sort(key=functools.cmp_to_key(lambda a, b: compare_release(_lineage(b), _lineage(a)))) for d in ordered: - if out and modelid.compare(_lineage(out[-1][0]), _lineage(d)) == 0: + if out and compare_release(_lineage(out[-1][0]), _lineage(d)) == 0: out[-1].append(d) else: out.append([d]) @@ -241,7 +288,7 @@ def inherit_stats(candidates, stats, opts=None): groups.setdefault(tuple(l["key"]), []).append(c) for group in groups.values(): for c in group: - older = [d for d in group if modelid.compare(_lineage(c), _lineage(d)) > 0] + older = [d for d in group if compare_release(_lineage(c), _lineage(d)) > 0] if not older: continue levels = _versions_newest_first(older) @@ -265,7 +312,7 @@ def has_predecessor(c, among, opts=None): """Whether some worker in `among` is an older version of the same maker and class as `c`.""" l = _comparable(c, opts) return bool(l) and any(_comparable(d, opts) and tuple(_lineage(d)["key"]) == tuple(l["key"]) - and modelid.compare(l, _lineage(d)) > 0 for d in among) + and compare_release(l, _lineage(d)) > 0 for d in among) def _price_tier(c): @@ -444,18 +491,15 @@ def _lineage(c): return l if isinstance(l, dict) else None -def _comparable(c, opts): - """The model's lineage when its class takes part in comparisons of versions: a class that could not be read - is never compared, and (with `supersede_guessed` off) neither is one that was only read from the id.""" +def _comparable(c, opts=None): + """The model's lineage when its maker and class are recorded; a model without them is never compared.""" l = _lineage(c) - if l and l.get("key") and (l.get("source") == "fact" or (opts or {}).get("supersede_guessed", True)): - return l - return None + return l if l and l.get("key") else None def superseded_by(pool, opts=None): """{worker: the newest worker of its maker and class that replaces it}, over the usable `pool`. Workers - that share a maker, a line and a class are versions of one model whichever provider carries them; the + that share a recorded maker and class are versions of one model whichever provider carries them; the older version is replaced by the newest one whatever its record or price. Pure.""" groups = {} for c in pool: @@ -465,7 +509,7 @@ def superseded_by(pool, opts=None): out = {} for group in groups.values(): for c in group: - newer = [d for d in group if modelid.compare(_lineage(d), _lineage(c)) > 0] + newer = [d for d in group if compare_release(_lineage(d), _lineage(c)) > 0] if newer: out[c["worker"]] = _versions_newest_first(newer)[0][0]["worker"] return out @@ -541,8 +585,7 @@ def _assess_all(eligible, stats, kind, difficulty, floors, opts=None): def recency_order(candidates): """{worker: (recorded release date as days, negated; position among the versions of its class, newest first)}. - Smaller sorts first, so the more recently released model goes first; what cannot be compared is (0, 0). - A recorded release date counts across makers; the version only inside one maker's class.""" + Smaller sorts first, so the more recently released model goes first; what cannot be compared is (0, 0).""" out = {c["worker"]: (0, 0) for c in candidates} groups = {} for c in candidates: @@ -552,7 +595,7 @@ def recency_order(candidates): for group in groups.values(): for i, level in enumerate(_versions_newest_first(group)): for d in level: - out[d["worker"]] = (-modelid.days(_lineage(d).get("released")), i) + out[d["worker"]] = (-days(_lineage(d).get("released")), i) return out @@ -699,26 +742,24 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, "load_ratios": {c["worker"]: load_ratio(c) for c in candidates}, "assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first, "best_standing": best, "passed_detail": detail, "floors": floors, - "superseded": superseded, "class_ask": class_ask(eligible, opts), + "superseded": superseded, "class_ask": class_ask(eligible, pool, opts), "kind": kind, "difficulty": difficulty} -def class_ask(eligible, opts=None): - """What the lead agent should be asked to record, because it is about to matter: - {"classify": [workers], "order": [(maker, [class labels])]}. - classify: a worker whose class could not be read from its id, when another usable worker has the same maker (the - two may be versions of one class). A class read from the id with confidence is not asked about; a recorded one - never is. order: a maker with two or more classes among the usable workers and no recorded class order.""" - makers, labels = {}, {} +def class_ask(eligible, pool, opts=None): + """What the lead agent should be asked to have recorded, because the answer could depend on it: + {"classify": [workers], "order": [(maker, [classes])]}. + classify: a worker with no classification (none stored, not even "unknown") that is in the pool competing for the + request while another usable worker exists; a worker kept out for lack of capability could not change the answer. + order: a maker with two or more recorded classes among the usable workers and no recorded class order.""" + labels = {} for c in eligible: - l = _lineage(c) + l = _comparable(c) if l: - makers.setdefault(l.get("maker"), []).append(c["worker"]) - if l.get("key"): - labels.setdefault(l.get("maker"), set()).add(l.get("label")) + labels.setdefault(l["maker"], set()).add(l["label"]) recorded = (opts or {}).get("class_orders") or {} - return {"classify": sorted(c["worker"] for c in eligible if _lineage(c) - and _lineage(c).get("source") == "unknown" and len(makers.get(_lineage(c).get("maker"), [])) > 1), + return {"classify": sorted(c["worker"] for c in pool if not _comparable(c) and not c.get("classified")) + if len(eligible) > 1 else [], "order": [(m, sorted(ls)) for m, ls in sorted(labels.items()) if len(ls) > 1 and m not in recorded]} diff --git a/sisi/workers.py b/sisi/workers.py index f884f61..0baf5fa 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -22,11 +22,11 @@ Personal files (all in the personal data folder): accepted rate): {"models": {"": {"standing": 0..100, "source": text, "date": "YYYY-MM-DD"}}} worker-models.json what the lead agent decided about each model: {"models": {"": - {"class": name, "family": name, "maker": name, "released": "YYYY-MM-DD", + {"class": name, "maker": name, "released": "YYYY-MM-DD", "source": text, "date": "YYYY-MM-DD"}}, "classes": {"": {"order": [class, most capable first], "source": text, "date": "YYYY-MM-DD"}}}, written by - `sisi workers fact --class ...` and `sisi workers classes`. A recorded - fact always beats what the parser reads from the id (sisi/modelid.py). + `sisi workers fact --class ...` and `sisi workers classes`. sisi reads + nothing from a model's name: these facts are researched by a cheap worker. worker-prefs.json the user's own routing constraints: {"avoid": [{"pattern", "why"}], "prefer": [...], "only": [{"provider", "patterns", "why"}]}, written by `sisi workers avoid|prefer|only` @@ -39,7 +39,7 @@ researched when they are missing or old. No price, score or model name ships in import datetime, json, os, re, shutil, statistics, subprocess, sys, time, uuid from . import brief as brief_contract -from . import modelid, paths, routing, store +from . import paths, routing, store LIST_TIMEOUT_S = 30 DEFAULT_REFRESH_AFTER_S = 24 * 3600 @@ -586,26 +586,12 @@ def load_model_facts(): return models, classes -_WORDS = [] - - -def model_words(): - """The tier words and ignored words in canon/model-words.json (data the parser reads; cached).""" - if not _WORDS: - _WORDS.append(read_json(paths.canon("model-words.json"))) - return _WORDS[0] - - def route_opts(): - """Routing options: `route.supersede_guessed` (default true) lets a class read from the id with confidence, not yet - recorded by the lead agent, take part in the rule that the newest version of a class wins; the maker class orders - the lead agent recorded (`sisi workers classes`); and `route.class_span`, how far down an order each difficulty - reaches.""" - v = route_cfg().get("supersede_guessed") + """Routing options: the maker class orders the lead agent recorded (`sisi workers classes`) and + `route.class_span`, how far down an order each difficulty reaches.""" orders = {m: [str(x) for x in e["order"]] for m, e in load_model_facts()[1].items() if isinstance(e, dict) and isinstance(e.get("order"), list)} - return {"supersede_guessed": v if isinstance(v, bool) else True, "class_orders": orders, - "class_span": route_cfg().get("class_span")} + return {"class_orders": orders, "class_span": route_cfg().get("class_span")} def route_floors(): @@ -671,9 +657,8 @@ def build_candidates(disc=None, records=None): standing = standing_of(prior_entry) fact = next((model_facts[k] for k in (worker, model) if k and isinstance(model_facts.get(k), dict)), {}) maker_fact = price.get("maker") or prior_entry.get("maker") or fact.get("maker") - lineage = modelid.resolve(worker, model_words(), fact=dict(fact, maker=maker_fact) if maker_fact else fact, - host_native=host_native) - c = {"worker": worker, "lineage": lineage, "tool": tool, "model": model, + lineage = routing.lineage_from_fact(dict(fact, maker=maker_fact) if maker_fact else fact, host_native=host_native) + c = {"worker": worker, "lineage": lineage, "classified": bool(fact), "tool": tool, "model": model, "maker": price.get("maker") or prior_entry.get("maker") or routing.maker_of(model or worker), "plan": price.get("plan") or tool_plan, "cost": cost, @@ -900,11 +885,15 @@ def facts_status(now=None): return {"state": "ok", "newest": newest, "max_age_days": max_age} -def facts_line(now=None): - """One session-start line asking for worker facts to be researched, or "" when they are fresh.""" +def facts_line(now=None, unclassified=0): + """One session-start line asking for worker facts to be researched, or "" when they are fresh and every routable + worker is classified. `unclassified` is how many routable workers have no recorded maker, class and release date.""" status = facts_status(now) + ask = ("%d routable worker%s no recorded maker, class and release date, so %s never compared with a newer or older " + "version: run `sisi workers classify`, hand its output to a fast, cheap worker, then `sisi workers classify " + "--record FILE`." % (unclassified, " has" if unclassified == 1 else "s have", "it is" if unclassified == 1 else "they are")) if status["state"] == "ok": - return "" + return ("sisi: " + ask) if unclassified else "" if status["state"] == "missing": what = "worker facts are missing (no prices or benchmark standing recorded yet)" else: @@ -912,9 +901,8 @@ def facts_line(now=None): return ("sisi: %s: ask a fast, cheap worker to research current prices and " "software-engineering benchmark standing for the workers found here (`sisi workers`) " "and record each with its source: `sisi workers fact WORKER --price N --source S` " - "and `sisi workers fact WORKER --standing N --source S`; also the release date of each " - "worker that lacks one: `sisi workers fact WORKER --released YYYY-MM-DD --source S`. Until then routing " - "goes by the judged record alone." % what) + "and `sisi workers fact WORKER --standing N --source S`. Until then routing " + "goes by the judged record alone.%s" % (what, (" Also: " + ask) if unclassified else "")) def estimate_cost(tokens, price_entry): @@ -1322,8 +1310,8 @@ def is_subagent_payload(payload): return "/subagents/" in tp or tp.endswith("/subagents") -def _with_facts(lines): - line = facts_line() +def _with_facts(lines, unclassified=0): + line = facts_line(unclassified=unclassified) return lines + [line] if line else lines @@ -1368,7 +1356,7 @@ def session_lines(model, payload=None): suffix)) elif suffix: lines.append("sisi:" + suffix) - return _with_facts(lines) + return _with_facts(lines, len(unclassified_workers(candidates, records))) # ---------------------------------------------------------------- commands @@ -1426,31 +1414,17 @@ def _price_lines(tool_name, models, prices, shown_keys=None): return lines -def _recency_text(l): - if l.get("alias"): - return "newest of its class (a bare host alias)" - bits = [] - if l.get("released"): - bits.append("released %s (recorded)" % l["released"]) - if l.get("version"): - bits.append("version %s" % ".".join(str(x) for x in l["version"])) - if l.get("date"): - bits.append("dated %s" % l["date"]) - return ", ".join(bits) or "no version or date in the id" - - def model_lines(cands, limit=40): - """One line per routable worker: its maker, class (recorded, or a guess read from the id, or unknown) and - how recent it is. Workers whose class is only a guess say so; unknown ones say how to record it.""" + """One line per routable worker: its recorded maker, class and release date, or that none is recorded.""" out = [] for c in sorted(cands, key=lambda c: c["worker"]): l = c.get("lineage") or {} - if l.get("source") == "unknown" or not l: - what = "class unknown: the id does not say it with confidence" - else: - what = "maker %s, class %s (%s)" % (l["maker"], l["label"], "recorded" if l["source"] == "fact" - else "a guess read from the id") - out.append(" %s: %s; %s" % (c["worker"], what, _recency_text(l))) + if l.get("source") != "fact": + out.append(" %s: no maker and class recorded" % c["worker"]) + continue + when = ("released %s" % l["released"]) if l.get("released") else ( + "newest of its class (a bare host alias)" if l.get("alias") else "no release date recorded") + out.append(" %s: maker %s, class %s; %s" % (c["worker"], l["maker"], l["label"], when)) if len(out) > limit: out = out[:limit] + [" ... and %d more" % (len(out) - limit)] return out @@ -1468,6 +1442,8 @@ def cmd_workers(args=()): return _cmd_note(args[1:]) if args[:1] == ["classes"]: return _cmd_classes(args[1:]) + if args[:1] == ["classify"]: + return _cmd_classify(args[1:]) if args[:1] == ["down"]: return _cmd_down(args[1:]) if args[:1] == ["up"]: @@ -1531,8 +1507,8 @@ def cmd_workers(args=()): print(_classes_line(maker, e)) routable, cold, _excluded = routable_candidates(build_candidates(disc, records), records) if routable and not cold: - print("Model lines (the class of each routable worker; a guess is read from the id alone: confirm it " - "with `sisi workers fact WORKER --class NAME --source S`):") + print("Model lines (the recorded maker, class and release date of each routable worker; sisi reads nothing " + "from a name: `sisi workers classify` asks a cheap worker):") for line in model_lines(routable): print(line) down_now = [(k, v) for k, v in sorted(avail.items()) if isinstance(v, dict)] @@ -1595,7 +1571,8 @@ def _route_setup(args): def class_line(result): - """The one line asking the lead agent to determine a class sisi cannot read from the id, or None.""" + """The one line asking the lead agent to have the maker, class and release date recorded for the workers that + lack them (a cheap, fast worker does the research), or None.""" ask = result.get("class_ask") or {} names = ask.get("classify") or [] if not names and ask.get("order"): @@ -1604,9 +1581,9 @@ def class_line(result): "(classes seen: %s)" % (maker, maker, " ".join(labels), ", ".join(labels))) if not names: return None - return ("sisi: the class of %s%s cannot be read from its id: decide it and record it with " - "`sisi workers fact %s --class NAME --source S` (until then it is never compared with a newer or older version)" - % (names[0], (" and %d more" % (len(names) - 1)) if len(names) > 1 else "", names[0])) + return ("sisi: no maker, class and release date are recorded for %s%s, so it is never compared with a newer or older " + "version: run `sisi workers classify`, hand its output to a fast, cheap worker, then `sisi workers classify --record FILE`" + % (names[0], (" and %d more" % (len(names) - 1)) if len(names) > 1 else "")) def cmd_route(args=()): @@ -1991,8 +1968,8 @@ def _cmd_fact(args): usage = ("usage: sisi workers fact WORKER --price-in N --price-out N [--plan flat|per-use] [--maker M] --source S [--date YYYY-MM-DD]\n" " sisi workers fact WORKER --price N (one blended figure) [--plan ...] [--maker M] --source S\n" " sisi workers fact WORKER --standing 0..100 --source S [--date YYYY-MM-DD] (--score is the old name)\n" - " sisi workers fact WORKER --class NAME [--family NAME] [--maker M] [--released YYYY-MM-DD] --source S\n" - " (the class, family and release date the lead agent decided for a model; a recorded fact beats the parser)") + " sisi workers fact WORKER --maker M --class NAME [--released YYYY-MM-DD] --source S\n" + " (the maker, class and release date of a model, as researched; sisi reads nothing from a name)") if not args: print(usage) return 1 @@ -2087,11 +2064,11 @@ _NAME = re.compile(r"[a-z0-9][a-z0-9.+-]*") def _model_fact_args(args): - """{class, family, maker, released} from the command line, {} when none is given, False (after saying why) - when one is malformed. The maker alone belongs to a price or standing fact, so it is read here only - beside a class, family or release date.""" + """{class, maker, released} from the command line, {} when none is given, False (after saying why) when one is + malformed. The maker alone belongs to a price or standing fact, so it is read here only beside a class or a + release date.""" out = {} - for opt, field in (("--class", "class"), ("--family", "family"), ("--released", "released")): + for opt, field in (("--class", "class"), ("--released", "released")): v = _opt(args, opt) if v is None: continue @@ -2111,6 +2088,109 @@ def _model_fact_args(args): return out +CLASSIFY_BATCH = 40 +CLASSIFY_INSTRUCTION = """Classify these AI models. For each id below give: its maker; its class (the line or tier of that maker it +belongs to: a "flash" or "mini" beside a standard model, or a separately named line; one short lowercase word, +"standard" for a plain flagship); and its release date (YYYY-MM-DD, or YYYY-MM when the day is unknown). +For each maker also give its classes in order from most to least capable. Say "unknown" wherever you do not +know; do not guess. Answer with one JSON object and nothing else, in this shape: +{"workers": {"": {"maker": "...", "class": "...", "released": "..."}}, + "classes": {"": ["most capable class", "...", "least capable class"]}} +Ids to classify:""" + + +def unclassified_workers(candidates, records): + """Ids of routable workers with no classification stored (an answer of "unknown" counts as stored).""" + routable, cold, _ = routable_candidates(candidates, records) + return [] if cold else sorted(c["worker"] for c in routable if not c.get("classified")) + + +def _classify_answer(text): + """The JSON object in a worker's answer (it may be wrapped in prose or a code fence), or None.""" + for chunk in (text, text[text.find("{"):text.rfind("}") + 1] if "{" in text and "}" in text else ""): + try: + d = json.loads(chunk) + except ValueError: + continue + if isinstance(d, dict): + return d + return None + + +def _valid_name(v): + return isinstance(v, str) and (v.strip().lower() == "unknown" or bool(_NAME.fullmatch(v.strip().lower()))) + + +def _cmd_classify(args): + """`sisi workers classify` prints the question for a cheap, fast worker: the routable workers with no + classification and the instruction. `--record FILE [--by WORKER]` validates the answer and stores it.""" + records = read_records() + asked = unclassified_workers(build_candidates(records=records), records) + path = _opt(args, "--record") + if path is None: + if not asked: + print("every routable worker is classified.") + return 0 + print(CLASSIFY_INSTRUCTION) + for w in asked[:CLASSIFY_BATCH]: + print(w) + if len(asked) > CLASSIFY_BATCH: + print("(%d more: ask again after recording these)" % (len(asked) - CLASSIFY_BATCH)) + return 0 + try: + with open(path, encoding="utf-8") as f: + text = f.read() + except OSError as e: + print("sisi: cannot read %s: %s" % (path, e), file=sys.stderr) + return 1 + answer = _classify_answer(text) + given = answer.get("workers") if isinstance(answer, dict) else None + if not isinstance(given, dict): + print('sisi: the answer is not a JSON object with a "workers" object; nothing recorded', file=sys.stderr) + return 1 + strangers = sorted(w for w in given if w not in set(asked)) + if strangers: + print("sisi: not asked about (or already classified): %s; nothing recorded" % ", ".join(strangers[:5]), file=sys.stderr) + return 1 + clean = {} + for w, e in given.items(): + released = e.get("released", "unknown") if isinstance(e, dict) else None + ok = isinstance(e, dict) and _valid_name(e.get("maker")) and _valid_name(e.get("class")) + if ok and str(released).lower() != "unknown": + try: + ok = routing.days(released) > 0 and (len(released) == 7 or datetime.date.fromisoformat(released) is not None) + except (ValueError, TypeError): + ok = False + if not ok: + print("sisi: the entry for %s is not {maker, class, released} with short names and a YYYY-MM[-DD] date " + "(or unknown); nothing recorded" % w, file=sys.stderr) + return 1 + clean[w] = {"maker": e["maker"].strip().lower(), "class": e["class"].strip().lower(), + "released": str(released).strip().lower() if str(released).lower() != "unknown" else "unknown"} + orders = answer.get("classes") if isinstance(answer.get("classes"), dict) else {} + source = "classified by %s" % (_opt(args, "--by") or "a cheap worker") + date = time.strftime("%Y-%m-%d", time.localtime()) + data = read_json(models_path()) + models = data.get("models") if isinstance(data.get("models"), dict) else {} + classes = data.get("classes") if isinstance(data.get("classes"), dict) else {} + for w, e in clean.items(): + entry = {k: v for k, v in e.items() if not (k == "released" and v == "unknown")} + models[w] = dict(entry, source=source, date=date) + stored_orders = 0 + for maker, order in orders.items(): + names = [str(x).strip().lower() for x in order] if isinstance(order, list) else [] + maker = str(maker).strip().lower() + if (maker and maker != "unknown" and maker not in classes and len(names) > 1 and len(set(names)) == len(names) + and all(_NAME.fullmatch(x) for x in names)): + classes[maker] = {"order": names, "source": source, "date": date} + stored_orders += 1 + data["models"], data["classes"] = models, classes + write_json(models_path(), data) + unknown = sum(1 for e in clean.values() if "unknown" in (e["maker"], e["class"])) + print("recorded %d classification(s) (%d unknown) and %d class order(s), from %s" % (len(clean), unknown, stored_orders, source)) + return 0 + + def _cmd_classes(args): """`sisi workers classes MAKER CLASS [CLASS...] --source S` records a maker's classes, most capable first; `sisi workers classes MAKER --remove` forgets them; no arguments lists them.""" diff --git a/tests/test_model_classes.py b/tests/test_model_classes.py index 2578df0..b284dba 100644 --- a/tests/test_model_classes.py +++ b/tests/test_model_classes.py @@ -4,7 +4,7 @@ Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" import json, os, random, unittest from support import * from sisi import routing -from test_model_supersession import cand, attempts, pick, NOW +from test_model_supersession import cand, attempts, pick, NOW, R1, R2 from test_worker_models import ModelCase ORDER = {"abc": ["fable", "opus", "sonnet", "haiku"]} @@ -12,7 +12,7 @@ COST = {"fable": 9.0, "opus": 6.0, "sonnet": 3.0, "haiku": 1.0} def fleet(**extra): - return [cand("prov/abc-%s-5" % c, **dict({"cost": COST[c]}, **extra.get(c, {}))) for c in ("fable", "opus", "sonnet", "haiku")] + return [cand("prov/abc-%s-5" % c, **dict({"cost": COST[c], "cls": c}, **extra.get(c, {}))) for c in ("fable", "opus", "sonnet", "haiku")] def best(cands, difficulty, records=(), **kw): @@ -62,13 +62,13 @@ class ClassOrderTests(unittest.TestCase): self.assertEqual((who, r["basis"]), ("prov/abc-sonnet-5", "strongest")) def test_another_makers_models_are_not_placed_by_this_order(self): - other = cand("prov/xyz-opus-5", cost=0.1, maker="xyz") + other = cand("prov/xyz-opus-5", cls="opus", cost=0.1, maker="xyz") who, r = best(fleet() + [other], 3) self.assertEqual(who, "prov/abc-opus-5") self.assertNotEqual(r["assessments"]["prov/xyz-opus-5"]["tier"], "class") def test_a_class_missing_from_the_order_is_not_placed(self): - extra = cand("prov/abc-ember-1", cost=0.1) + extra = cand("prov/abc-ember-1", cls="ember", cost=0.1) who, r = best(fleet() + [extra], 3) self.assertNotEqual(r["assessments"]["prov/abc-ember-1"]["tier"], "class") @@ -77,13 +77,13 @@ class ClassOrderTests(unittest.TestCase): self.assertEqual(r["class_ask"]["order"], [("abc", ["fable", "haiku", "opus", "sonnet"])]) r = best(fleet(), 3)[1] self.assertEqual(r["class_ask"]["order"], []) - one = pick([cand("prov/abc-opus-5"), cand("prov/abc-opus-6")], (), 3)[1] + one = pick([cand("prov/abc-opus-5", cls="opus", rel=R1), cand("prov/abc-opus-6", cls="opus", rel=R2)], (), 3)[1] self.assertEqual(one["class_ask"]["order"], []) # one class only: nothing to order def test_property_the_order_never_outranks_a_record_or_a_standing(self): rng = random.Random(9) for _ in range(300 * ITERS): - cands = [cand("prov/abc-%s-5" % c, cost=rng.choice([1.0, 2.0, 5.0]), + cands = [cand("prov/abc-%s-5" % c, cls=c, cost=rng.choice([1.0, 2.0, 5.0]), standing=rng.choice([None, None, 40.0, 90.0])) for c in rng.sample(list(COST), rng.randint(2, 4))] records = [] for c in cands: @@ -123,6 +123,7 @@ class ClassesCommandTests(ModelCase): models = ("abc-fable-5", "abc-opus-5", "abc-sonnet-5", "abc-haiku-5") for m in models: self.sisi("workers", "fact", "muse/" + m, "--price", str(COST[m.split("-")[1]]), "--source", "fixture", env=self.env(models)) + self.record("muse/" + m, m.split("-")[1], models=models) first = self.route(3, models=models) self.assertIn("record the order", first.stdout) self.assertLessEqual(len(first.stdout.splitlines()), 7, first.stdout) diff --git a/tests/test_model_inheritance.py b/tests/test_model_inheritance.py index 5f63f7b..8294d20 100644 --- a/tests/test_model_inheritance.py +++ b/tests/test_model_inheritance.py @@ -4,7 +4,7 @@ predecessor's bad record does not block it. Invented ids. Requirement ids: R-7.2 import random, unittest from support import * from sisi import routing -from test_model_supersession import cand, attempts, pick, NOW +from test_model_supersession import cand, attempts, pick, NOW, R1, R2, R3, R4 def assessed(cands, records, worker, difficulty=2, kind="impl", **kw): @@ -12,9 +12,12 @@ def assessed(cands, records, worker, difficulty=2, kind="impl", **kw): return r["assessments"].get(worker), r +m_ = {'5.1': '2026-01-01', '5.2': '2026-03-01', '5.3': '2026-06-01', '5.4': '2026-09-01', '5.10': '2026-10-01'} + + class InheritanceTests(unittest.TestCase): def test_a_new_version_inherits_the_record_of_its_predecessor_and_says_so(self): - old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) + old, new = cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=2.0) records = attempts("prov/abc-5.3", 12, 11, difficulty=2) a, r = assessed([old, new], records, "prov/abc-5.4") self.assertEqual((a["tier"], a["capable"], a["inherited_from"]), ("a", True, "prov/abc-5.3")) @@ -24,7 +27,7 @@ class InheritanceTests(unittest.TestCase): self.assertIn("11 of 12", line) def test_it_walks_back_one_predecessor_at_a_time(self): - cands = [cand("prov/abc-5.2", cost=1.0), cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0)] + cands = [cand("prov/abc-5.2", rel="2026-03-01", cost=1.0), cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)] records = attempts("prov/abc-5.2", 12, 12, difficulty=2) + attempts("prov/abc-5.3", 3, 3, difficulty=2) a, _ = assessed(cands, records, "prov/abc-5.4") self.assertEqual(a["inherited_from"], "prov/abc-5.2") # 5.3 has only a thin record @@ -33,17 +36,17 @@ class InheritanceTests(unittest.TestCase): self.assertEqual(a["inherited_from"], "prov/abc-5.3") # now the closest thick one def test_a_predecessors_bad_record_does_not_block_the_newer_model(self): - cands = [cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0, standing=70.0)] + cands = [cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0, standing=70.0)] records = attempts("prov/abc-5.3", 12, 2, difficulty=2) a, _ = assessed(cands, records, "prov/abc-5.4") self.assertFalse(a["bad"]) self.assertEqual(a["tier"], "standing") # it starts from its benchmark, not from the old verdict - bare = assessed([cands[0], cand("prov/abc-5.4", cost=1.0)], records, "prov/abc-5.4")[0] + bare = assessed([cands[0], cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)], records, "prov/abc-5.4")[0] self.assertFalse(bare["bad"]) self.assertFalse(bare["capable"]) def test_the_models_own_thick_record_replaces_the_inherited_one(self): - cands = [cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0)] + cands = [cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)] records = attempts("prov/abc-5.3", 12, 12, difficulty=2) + attempts("prov/abc-5.4", 9, 1, difficulty=2) a, _ = assessed(cands, records, "prov/abc-5.4") self.assertTrue(a["bad"]) @@ -53,30 +56,30 @@ class InheritanceTests(unittest.TestCase): self.assertEqual((a["tier"], a.get("inherited_from")), ("a", None)) def test_a_thin_record_that_already_contradicts_is_not_papered_over(self): - cands = [cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=1.0)] + cands = [cand("prov/abc-5.3", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0)] records = attempts("prov/abc-5.3", 12, 12, difficulty=2) + attempts("prov/abc-5.4", 3, 0, difficulty=2) a, _ = assessed(cands, records, "prov/abc-5.4") self.assertIsNone(a.get("inherited_from")) self.assertFalse(a["capable"]) def test_nothing_is_inherited_across_classes_or_makers(self): - flash, new = cand("prov/abc-5.3-flash", cost=1.0), cand("prov/abc-5.4", cost=1.0) + flash, new = cand("prov/abc-5.3-flash", cls="flash", rel="2026-06-01", cost=1.0), cand("prov/abc-5.4", rel="2026-09-01", cost=1.0) records = attempts("prov/abc-5.3-flash", 12, 12, difficulty=2) self.assertFalse(assessed([flash, new], records, "prov/abc-5.4")[0]["capable"]) - other = cand("prov/xyz-5.4", cost=1.0, maker="xyz") - self.assertFalse(assessed([cand("prov/abc-5.3"), other], attempts("prov/abc-5.3", 12, 12, difficulty=2), "prov/xyz-5.4")[0]["capable"]) + other = cand("prov/xyz-5.4", rel="2026-09-01", cost=1.0, maker="xyz") + self.assertFalse(assessed([cand("prov/abc-5.3", rel="2026-06-01"), other], attempts("prov/abc-5.3", 12, 12, difficulty=2), "prov/xyz-5.4")[0]["capable"]) def test_nothing_is_inherited_by_an_unreadable_class(self): - cands = [cand("prov/abc-6.2-sol"), cand("prov/abc-6.3-sol")] + cands = [cand("prov/abc-6.2-sol", known=False), cand("prov/abc-6.3-sol", known=False)] records = attempts("prov/abc-6.2-sol", 12, 12, difficulty=2) self.assertFalse(assessed(cands, records, "prov/abc-6.3-sol")[0]["capable"]) def test_inherited_evidence_counts_as_a_judged_record_before_a_benchmark(self): """Difficulty 2 and 3: proof comes before benchmark, and an inherited record is proof.""" - new = cand("prov/abc-5.4", cost=5.0) + new = cand("prov/abc-5.4", rel="2026-09-01", cost=5.0) rival = cand("prov/xyz-2.0", cost=0.1, maker="xyz", standing=90.0) records = attempts("prov/abc-5.3", 12, 12, difficulty=3) - who, r = pick([cand("prov/abc-5.3", cost=5.0), new, rival], records, 3) + who, r = pick([cand("prov/abc-5.3", rel="2026-06-01", cost=5.0), new, rival], records, 3) self.assertEqual(who, "prov/abc-5.4") self.assertTrue(r["judged_first"]) @@ -90,7 +93,7 @@ class InheritanceTests(unittest.TestCase): def test_a_model_with_no_data_of_its_own_is_routable_through_its_predecessor(self): from sisi import workers - old, new, lone = cand("prov/abc-5.3"), cand("prov/abc-5.4"), cand("prov/xyz-9.9", maker="xyz") + old, new, lone = cand("prov/abc-5.3", rel="2026-06-01"), cand("prov/abc-5.4", rel="2026-09-01"), cand("prov/xyz-9.9", rel="2026-09-01", maker="xyz") for c in (old, new, lone): c["price_source"] = None old["price_source"] = "fixture" @@ -103,7 +106,7 @@ class InheritanceTests(unittest.TestCase): seen = 0 for _ in range(300 * ITERS): versions = rng.sample(["5.1", "5.2", "5.3", "5.4", "5.10"], rng.randint(2, 4)) - cands = [cand("prov/abc-%s" % v, cost=rng.choice([None, 1.0, 2.0])) for v in versions] + cands = [cand("prov/abc-%s" % v, rel=m_[v], cost=rng.choice([None, 1.0, 2.0])) for v in versions] records = [] for c in cands: for d in (1, 2, 3): diff --git a/tests/test_model_recency.py b/tests/test_model_recency.py index 1bc5ddb..28b299c 100644 --- a/tests/test_model_recency.py +++ b/tests/test_model_recency.py @@ -1,5 +1,5 @@ """Recency breaks ties: where the arithmetic falls back to a stable order, the more recently released model wins -first (a recorded release date, else the version within one line, else the old tie-break by worker id), and the +first (its recorded release date, else the old tie-break by worker id), and the rule is in the text agents and people read. Requirement ids: R-7.2-1, R-7.2-2.""" import os, unittest from support import * @@ -9,27 +9,25 @@ from test_model_supersession import cand, pick class RecencyTieBreakTests(unittest.TestCase): def test_a_recorded_release_date_decides_a_tie_between_unrelated_models(self): - a = cand("prov/aaa-1.0", cost=1.0, fact={"released": "2026-01-10"}, maker="aaa") - b = cand("prov/bbb-2.0", cost=1.0, fact={"released": "2026-08-01"}, maker="bbb") + a = cand("prov/aaa-1.0", cost=1.0, rel="2026-01-10", maker="aaa") + b = cand("prov/bbb-2.0", cost=1.0, rel="2026-08-01", maker="bbb") who, r = pick([a, b]) self.assertEqual(who, "prov/bbb-2.0") self.assertIn(("prov/aaa-1.0", "equal on price and load; the choice is the more recently released"), r["passed_over"]) - - def test_the_version_inside_one_line_decides_when_nothing_supersedes(self): - old, new = cand("prov/abc-5.9", cost=1.0), cand("prov/abc-5.10", cost=1.0) - who, r = pick([old, new], opts={"supersede_guessed": False}) - self.assertEqual(who, "prov/abc-5.10") - self.assertEqual(pick([new, old], opts={"supersede_guessed": False})[0], "prov/abc-5.10") + self.assertEqual(pick([b, a])[0], "prov/bbb-2.0") def test_unknown_recency_keeps_the_old_tie_break(self): - a, b = cand("prov/aaa-1.0", cost=1.0, maker="aaa"), cand("prov/bbb-9.0", cost=1.0, maker="bbb") + a, b = cand("prov/aaa-1.0", cost=1.0, maker="aaa"), cand("prov/bbb-9.0", cost=1.0, maker="bbb", rel="2026-08-01") who, r = pick([a, b]) + self.assertEqual(who, "prov/bbb-9.0") # a recorded date beats none + a2, b2 = cand("prov/aaa-1.0", cost=1.0, maker="aaa", known=False), cand("prov/bbb-9.0", cost=1.0, maker="bbb", known=False) + who, r = pick([a2, b2]) self.assertEqual(who, "prov/aaa-1.0") self.assertIn(("prov/bbb-9.0", "equal on price and load; the choice came first in worker-id order"), r["passed_over"]) def test_price_and_load_still_come_before_recency(self): - cheap_old = cand("prov/aaa-1.0", cost=0.5, fact={"released": "2026-01-10"}, maker="aaa") - dear_new = cand("prov/bbb-2.0", cost=1.0, fact={"released": "2026-08-01"}, maker="bbb") + cheap_old = cand("prov/aaa-1.0", cost=0.5, rel="2026-01-10", maker="aaa") + dear_new = cand("prov/bbb-2.0", cost=1.0, rel="2026-08-01", maker="bbb") self.assertEqual(pick([cheap_old, dear_new])[0], "prov/aaa-1.0") @@ -58,11 +56,13 @@ class TextTests(unittest.TestCase): class SessionLineTests(SisiCase): - def test_session_start_asks_for_the_release_date_of_each_worker_that_lacks_one(self): + def test_session_start_names_unclassified_workers_in_the_one_facts_line(self): from sisi import workers - line = workers.facts_line() - self.assertIn("release date", line) - self.assertIn("--released", line) + line = workers.facts_line(unclassified=2) + self.assertEqual(len(line.splitlines()), 1) + self.assertIn("2 routable workers have no recorded maker, class and release date", line) + self.assertIn("sisi workers classify", line) + self.assertNotIn("classify", workers.facts_line(unclassified=0)) if __name__ == "__main__": diff --git a/tests/test_model_supersession.py b/tests/test_model_supersession.py index 199c57a..1cffd72 100644 --- a/tests/test_model_supersession.py +++ b/tests/test_model_supersession.py @@ -1,19 +1,22 @@ """The newest usable version of a maker's class always wins over its older versions (hard rule), however good the -older record or cheap its plan. Pure routing tests over invented ids shaped like real ones. +older record or cheap its plan. Identity and recency come from recorded facts. Pure routing tests over invented ids. Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" -import json, os, random, unittest +import random, unittest from support import * -from sisi import modelid, routing +from sisi import routing -WORDS = json.load(open(os.path.join(REPO, "canon", "model-words.json"))) NOW = 1000000.0 +R1, R2, R3, R4 = "2026-03-01", "2026-06-01", "2026-09-01", "2026-11-01" -def cand(worker, plan="per-use", cost=1.0, fact=None, host_native=False, standing=None, **kw): +def cand(worker, cls="standard", rel=None, maker="abc", plan="per-use", cost=1.0, host_native=False, standing=None, + known=True, **kw): + """A candidate whose maker, class and release date were recorded (known=False: nothing recorded).""" model = worker.rsplit("/", 1)[-1] - c = {"worker": worker, "tool": worker.split("/")[0] if "/" in worker else None, "model": model, "maker": "abc", + fact = {"class": cls, "maker": maker, "released": rel} if known else {} + c = {"worker": worker, "tool": worker.split("/")[0] if "/" in worker else None, "model": model, "maker": maker, "plan": plan, "cost": cost, "allowance_pct_left": None, "usable": True, "standing": standing, - "aliases": [worker, model], "lineage": modelid.resolve(worker, WORDS, fact=fact, host_native=host_native)} + "aliases": [worker, model], "lineage": routing.lineage_from_fact(fact, host_native=host_native)} c.update(kw) return c @@ -29,121 +32,145 @@ def pick(cands, records=(), difficulty=1, availability=None, **kw): return (r["choice"] or {}).get("worker"), r +class IdentityTests(unittest.TestCase): + def test_no_recorded_class_and_maker_means_no_identity(self): + for fact in (None, {}, {"class": "flash"}, {"maker": "abc"}, {"released": "2026-01-01"}): + got = routing.lineage_from_fact(fact) + self.assertIsNone(got["key"], fact) + self.assertEqual(got["source"], "unknown") + + def test_a_recorded_maker_and_class_are_the_identity_whatever_the_name(self): + a = routing.lineage_from_fact({"class": "Flash", "maker": "ABC", "released": "2026-03-01"}) + self.assertEqual((a["key"], a["source"], a["released"]), (("abc", "flash"), "fact", "2026-03-01")) + self.assertNotEqual(routing.lineage_from_fact({"class": "standard", "maker": "abc"})["key"], a["key"]) + + def test_the_more_recent_release_date_is_newer_and_dates_compare_as_dates(self): + old = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-09-30"}) + new = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-10-02"}) + self.assertGreater(routing.compare_release(new, old), 0) + self.assertLess(routing.compare_release(old, new), 0) + self.assertEqual(routing.compare_release(old, old), 0) + self.assertEqual(routing.compare_release(old, routing.lineage_from_fact({"class": "x", "maker": "m"})), 0) # unknowable + self.assertGreater(routing.days("2026-10-02"), routing.days("2026-09-30")) + self.assertEqual(routing.days("soon"), 0) + + def test_a_bare_host_alias_without_a_release_date_is_the_newest_of_its_class(self): + alias = routing.lineage_from_fact({"class": "x", "maker": "m"}, host_native=True) + dated = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2030-01-01"}) + self.assertTrue(alias["alias"]) + self.assertGreater(routing.compare_release(alias, dated), 0) + self.assertFalse(routing.lineage_from_fact({"class": "x", "maker": "m"})["alias"]) + self.assertFalse(routing.lineage_from_fact({}, host_native=True)["alias"]) # no class recorded: no comparison + self.assertFalse(routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-01-01"}, host_native=True)["alias"]) + + def test_unknown_answers_and_partial_dates(self): + self.assertIsNone(routing.lineage_from_fact({"class": "unknown", "maker": "abc"})["key"]) + self.assertIsNone(routing.lineage_from_fact({"class": "x", "maker": "unknown"})["key"]) + self.assertIsNone(routing.lineage_from_fact({"class": "x", "maker": "abc", "released": "unknown"})["released"]) + a = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-09"}) + b = routing.lineage_from_fact({"class": "x", "maker": "m", "released": "2026-10-15"}) + self.assertGreater(routing.compare_release(b, a), 0) + self.assertGreater(routing.days("2026-10"), routing.days("2026-09-30")) + + def test_no_code_reads_a_model_name(self): + import os, re as _re + self.assertFalse(os.path.exists(os.path.join(REPO, "sisi", "modelid.py"))) + self.assertFalse(os.path.exists(os.path.join(REPO, "canon", "model-words.json"))) + text = open(os.path.join(REPO, "sisi", "routing.py")).read() + self.assertEqual(_re.findall(r"modelid|tier word|parse_model", text), []) + + class SupersessionTests(unittest.TestCase): def test_the_newer_version_wins_over_an_older_one_with_a_better_record_and_a_cheaper_plan(self): """The owner's rule: no evidence exception, no price exception.""" - old = cand("prov/abc-5.3", plan="flat", cost=0.0) - new = cand("prov/abc-5.4", plan="per-use", cost=9.0) - records = attempts("prov/abc-5.3", 30, 30, difficulty=1) + old = cand("prov/abc-old", rel=R1, plan="flat", cost=0.0) + new = cand("prov/abc-new", rel=R2, plan="per-use", cost=9.0) + records = attempts("prov/abc-old", 30, 30, difficulty=1) who, r = pick([old, new], records) - self.assertEqual(who, "prov/abc-5.4") - self.assertIn(("prov/abc-5.3", "superseded by prov/abc-5.4 (a newer version of the same class)"), r["passed_over"]) + self.assertEqual(who, "prov/abc-new") + self.assertIn(("prov/abc-old", "superseded by prov/abc-new (a newer version of the same class)"), r["passed_over"]) - def test_numeric_version_order(self): - self.assertEqual(pick([cand("prov/abc-5.9"), cand("prov/abc-5.10")])[0], "prov/abc-5.10") - self.assertEqual(pick([cand("prov/abc-5.3"), cand("prov/abc-5-4-20261101")])[0], "prov/abc-5-4-20261101") - - def test_the_tier_word_before_or_after_the_version_is_one_class(self): - self.assertEqual(pick([cand("prov/abc-5.3-flash"), cand("prov/abc-flash-5.4")])[0], "prov/abc-flash-5.4") + def test_the_release_date_decides_not_the_name(self): + """A name that looks newer but was released earlier is the older model.""" + a = cand("prov/abc-9.9", rel=R1) + b = cand("prov/abc-1.0", rel=R3) + self.assertEqual(pick([a, b])[0], "prov/abc-1.0") def test_different_classes_never_supersede_each_other(self): - flash, std = cand("prov/abc-5.3-flash", cost=0.1), cand("prov/abc-5.4", cost=5.0) + flash, std = cand("prov/abc-a", cls="flash", rel=R1, cost=0.1), cand("prov/abc-b", rel=R2, cost=5.0) who, r = pick([flash, std]) - self.assertEqual(who, "prov/abc-5.3-flash") # the cheaper class still competes + self.assertEqual(who, "prov/abc-a") # the cheaper class still competes self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) def test_two_named_lines_of_one_maker_are_different_classes(self): - a, b = cand("prov/abc-wonder-1.0", cost=1.0), cand("prov/abc-ember-1.3", cost=2.0) + a, b = cand("prov/abc-w", cls="wonder", rel=R1, cost=1.0), cand("prov/abc-e", cls="ember", rel=R2, cost=2.0) who, r = pick([a, b]) - self.assertEqual(who, "prov/abc-wonder-1.0") + self.assertEqual(who, "prov/abc-w") self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) - def test_unknown_class_never_supersedes_or_is_superseded(self): - a, b = cand("prov/abc-6.2-sol", cost=1.0), cand("prov/abc-6.3-sol", cost=2.0) - self.assertIsNone(a["lineage"]["key"]) - who, r = pick([a, b]) - self.assertEqual(who, "prov/abc-6.2-sol") - self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + def test_different_makers_never_supersede_each_other(self): + a, b = cand("prov/abc-a", rel=R1, cost=1.0), cand("prov/xyz-b", rel=R3, cost=2.0, maker="xyz") + self.assertEqual(pick([a, b])[0], "prov/abc-a") - def test_a_recorded_class_makes_an_unknown_one_comparable(self): - fact = {"class": "sol", "maker": "abc"} - a, b = cand("prov/abc-6.2-sol", fact=fact, cost=1.0), cand("prov/abc-6.3-sol", fact=fact, cost=2.0) - self.assertEqual(pick([a, b])[0], "prov/abc-6.3-sol") + def test_a_model_with_nothing_recorded_is_never_compared(self): + a, b = cand("prov/abc-a", known=False, cost=1.0), cand("prov/abc-b", rel=R3, cost=2.0) + who, r = pick([a, b]) + self.assertEqual(who, "prov/abc-a") + self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) + no_date = cand("prov/abc-c", cost=1.0) # class recorded, no date: not comparable with a dated one + self.assertFalse([w for w, why in pick([no_date, cand("prov/abc-d", rel=R3)])[1]["passed_over"] if why.startswith("superseded")]) def test_the_newer_one_unusable_lets_the_older_compete_again(self): - old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) - self.assertEqual(pick([old, new], availability={"prov/abc-5.4": {"reason": "limit", "retry_at": NOW + 99}})[0], "prov/abc-5.3") - new2 = dict(new, usable=False, reason="not logged in") - self.assertEqual(pick([old, new2])[0], "prov/abc-5.3") - self.assertEqual(pick([old, new], avoid=[{"pattern": "5.4"}])[0], "prov/abc-5.3") - spent = dict(new, plan="flat", allowance_pct_left=0) - self.assertEqual(pick([old, spent])[0], "prov/abc-5.3") + old, new = cand("prov/abc-old", rel=R1, cost=1.0), cand("prov/abc-new", rel=R2, cost=2.0) + self.assertEqual(pick([old, new], availability={"prov/abc-new": {"reason": "limit", "retry_at": NOW + 99}})[0], "prov/abc-old") + self.assertEqual(pick([old, dict(new, usable=False, reason="not logged in")])[0], "prov/abc-old") + self.assertEqual(pick([old, new], avoid=[{"pattern": "abc-new"}])[0], "prov/abc-old") + self.assertEqual(pick([old, dict(new, plan="flat", allowance_pct_left=0)])[0], "prov/abc-old") def test_a_tried_newer_version_does_not_send_a_retry_back_to_the_older(self): - old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) - who, r = pick([old, new], exclude=["prov/abc-5.4"]) - self.assertIsNone(who) + old, new = cand("prov/abc-old", rel=R1, cost=1.0), cand("prov/abc-new", rel=R2, cost=2.0) + self.assertIsNone(pick([old, new], exclude=["prov/abc-new"])[0]) def test_a_newer_version_with_a_thick_bad_record_never_sends_work_back_to_the_older(self): - old, new, other = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0), cand("prov/xyz-2.0", cost=3.0, maker="xyz") - records = attempts("prov/abc-5.4", 10, 1, difficulty=1) + attempts("prov/xyz-2.0", 10, 10, difficulty=1) - who, r = pick([old, new, other], records) - self.assertEqual(who, "prov/xyz-2.0") - who, r = pick([old, new], records) - self.assertEqual(who, "prov/abc-5.4") # nobody else: the bad newer model is still not replaced by the older + old, new = cand("prov/abc-old", rel=R1, cost=1.0), cand("prov/abc-new", rel=R2, cost=2.0) + other = cand("prov/xyz-2", cost=3.0, maker="xyz") + records = attempts("prov/abc-new", 10, 1, difficulty=1) + attempts("prov/xyz-2", 10, 10, difficulty=1) + self.assertEqual(pick([old, new, other], records)[0], "prov/xyz-2") + self.assertEqual(pick([old, new], records)[0], "prov/abc-new") # nobody else: still not the older version def test_the_same_model_through_two_providers_is_one_model(self): - old_a = cand("prova/abc-5.3", plan="flat", cost=0.0) - new_a, new_b = cand("prova/abc-5.4", cost=5.0), cand("provb/abc-5.4", cost=2.0) + old_a = cand("prova/abc-old", rel=R1, plan="flat", cost=0.0) + new_a, new_b = cand("prova/abc-new", rel=R2, cost=5.0), cand("provb/abc-new", rel=R2, cost=2.0) who, r = pick([old_a, new_a, new_b]) - self.assertEqual(who, "provb/abc-5.4") # the existing cost comparison picks the provider - self.assertEqual(sorted(w for w, why in r["passed_over"] if why.startswith("superseded")), ["prova/abc-5.3"]) - who, _ = pick([old_a, new_a, new_b], availability={"provb": {"reason": "limit", "retry_at": NOW + 9}}) - self.assertEqual(who, "prova/abc-5.4") + self.assertEqual(who, "provb/abc-new") # the existing cost comparison picks the provider + self.assertEqual(sorted(w for w, why in r["passed_over"] if why.startswith("superseded")), ["prova/abc-old"]) + self.assertEqual(pick([old_a, new_a, new_b], availability={"provb": {"reason": "limit", "retry_at": NOW + 9}})[0], "prova/abc-new") - def test_a_bare_host_alias_with_a_recorded_class_is_the_newest(self): - alias = cand("abc", fact={"class": "standard", "maker": "abc"}, host_native=True, cost=9.0) - versioned = cand("prov/abc-9.9", cost=0.1) + def test_a_bare_host_alias_is_the_newest_of_its_class(self): + alias = cand("abc", host_native=True, cost=9.0) + versioned = cand("prov/abc-9", rel=R4, cost=0.1) self.assertEqual(pick([alias, versioned])[0], "abc") - bare = cand("abc", host_native=True, cost=9.0) # class not recorded: no comparison - self.assertEqual(pick([bare, versioned])[0], "prov/abc-9.9") + self.assertEqual(pick([cand("abc", host_native=True, known=False, cost=9.0), versioned])[0], "prov/abc-9") - def test_guessed_classes_take_part_unless_the_config_says_only_recorded_ones(self): - old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0) - self.assertEqual(pick([old, new])[0], "prov/abc-5.4") - self.assertEqual(pick([old, new], opts={"supersede_guessed": False})[0], "prov/abc-5.3") - fact = {"class": "standard"} - old_r, new_r = cand("prov/abc-5.3", fact=fact, cost=1.0), cand("prov/abc-5.4", fact=fact, cost=2.0) - self.assertEqual(pick([old_r, new_r], opts={"supersede_guessed": False})[0], "prov/abc-5.4") - - def test_the_asking_line_is_only_for_a_class_that_could_not_be_read(self): - a, b = cand("prov/abc-6.2-sol", cost=1.0), cand("prov/abc-6.3-luna", cost=2.0) - r = pick([a, b])[1] - self.assertEqual(sorted(r["class_ask"]["classify"]), ["prov/abc-6.2-sol", "prov/abc-6.3-luna"]) - lone = pick([cand("prov/abc-6.2-sol"), cand("prov/xyz-1.0", maker="xyz")])[1] - self.assertEqual(lone["class_ask"]["classify"], []) # no sibling of the same maker: it cannot matter - guessed = pick([cand("prov/abc-5.3"), cand("prov/abc-5.4")])[1] - self.assertEqual(guessed["class_ask"]["classify"], []) # read with confidence: no question - fact = {"class": "sol", "maker": "abc"} - settled = pick([cand("prov/abc-6.2-sol", fact=fact), cand("prov/abc-6.3-luna", fact=fact)])[1] - self.assertEqual(settled["class_ask"]["classify"], []) + def test_the_asking_line_names_workers_with_nothing_recorded_when_a_choice_is_made_among_several(self): + a, b = cand("prov/abc-a", known=False), cand("prov/abc-b", rel=R2) + self.assertEqual(pick([a, b])[1]["class_ask"]["classify"], ["prov/abc-a"]) + self.assertEqual(pick([a])[1]["class_ask"]["classify"], []) + self.assertEqual(pick([cand("prov/abc-a", rel=R1), cand("prov/abc-b", rel=R2)])[1]["class_ask"]["classify"], []) class SupersessionPropertyTests(unittest.TestCase): def fleet(self, rng): cands, records, down = [], [], {} for maker in rng.sample(["abc", "xyz", "qrs"], rng.randint(1, 3)): - for cls in rng.sample(["", "-flash", "-mini", "-wonder", "-pro"], rng.randint(1, 3)): - for ver in rng.sample(["5.3", "5.4", "5.9", "5.10", "6", "5-4-20261101", "5.4-20250101"], rng.randint(1, 4)): + for cls in rng.sample(["standard", "flash", "mini", "wonder"], rng.randint(1, 3)): + for rel in rng.sample(["2026-01-05", "2026-03-01", "2026-06-01", "2026-09-30", "2026-10-02", None], rng.randint(1, 4)): for prov in rng.sample(["pa", "pb"], rng.randint(1, 2)): - w = "%s/%s%s-%s" % (prov, maker, cls, ver) - if cls == "-wonder": - w = "%s/%s-wonder-%s" % (prov, maker, ver) - if any(c["worker"] == w for c in cands): - continue - cands.append(cand(w, plan=rng.choice(["flat", "per-use", None]), - cost=rng.choice([None, 0.1, 1.0, 5.0]), maker=maker, - allowance_pct_left=rng.choice([None, 0, 50]))) + w = "%s/%s-%s-%s" % (prov, maker, cls, rel) + c = cand(w, cls=cls, rel=rel, maker=maker, plan=rng.choice(["flat", "per-use", None]), + cost=rng.choice([None, 0.1, 1.0, 5.0]), allowance_pct_left=rng.choice([None, 0, 50]), + known=rng.random() < 0.9) + cands.append(c) if rng.random() < 0.15: down[w] = {"reason": "limit", "retry_at": NOW + 99} for d in (1, 2, 3): @@ -161,20 +188,16 @@ class SupersessionPropertyTests(unittest.TestCase): checked = 0 for _ in range(300 * ITERS): cands, records, down = self.fleet(rng) - if not cands: - continue - d = rng.choice([1, 2, 3]) - who, r = pick(cands, records, d, availability=down) + who, r = pick(cands, records, rng.choice([1, 2, 3]), availability=down) if who is None: continue chosen = next(c for c in cands if c["worker"] == who) lc = chosen["lineage"] for c in cands: - if c is chosen or not self.usable(c, down): + if c is chosen or not self.usable(c, down) or not lc["key"]: continue - lo = c["lineage"] - if lo["key"] == lc["key"]: - self.assertLessEqual(modelid.compare(lo, lc), 0, (who, c["worker"])) + if c["lineage"]["key"] == lc["key"]: + self.assertLessEqual(routing.compare_release(c["lineage"], lc), 0, (who, c["worker"])) checked += 1 for w, why in r["passed_over"]: if why.startswith("superseded by "): @@ -182,7 +205,8 @@ class SupersessionPropertyTests(unittest.TestCase): a = next(c for c in cands if c["worker"] == w)["lineage"] b = next(c for c in cands if c["worker"] == newer)["lineage"] self.assertEqual(a["key"], b["key"], "a model never supersedes one of another maker or class") - self.assertGreater(modelid.compare(b, a), 0) + self.assertIsNotNone(a["key"]) + self.assertGreater(routing.compare_release(b, a), 0) self.assertGreater(checked, 100) def test_adding_a_newer_version_of_the_chosen_model_never_makes_the_choice_an_older_model_of_that_class(self): @@ -190,40 +214,27 @@ class SupersessionPropertyTests(unittest.TestCase): done = 0 for _ in range(200 * ITERS): cands, records, down = self.fleet(rng) - if not cands: - continue d = rng.choice([1, 2, 3]) who, _r = pick(cands, records, d, availability=down) if who is None: continue - chosen = next(c for c in cands if c["worker"] == who) - lc = chosen["lineage"] - if not lc["version"] or lc["date"]: - continue - ver = ".".join(str(x) for x in lc["version"][:1] + (lc["version"][1] + 1 if len(lc["version"]) > 1 else 1,)) - prov = who.split("/")[0] - maker = lc["maker"] - tail = "" if lc["class"] == "standard" else "-" + lc["class"] - new_w = "pc/%s%s-%s" % (maker, tail, ver) if lc["line"] == "" else None - if new_w is None or any(c["worker"] == new_w for c in cands): - continue - new = cand(new_w, maker=chosen["maker"], cost=rng.choice([None, 0.1, 5.0])) - if new["lineage"]["key"] != lc["key"] or modelid.compare(new["lineage"], lc) <= 0: + lc = next(c for c in cands if c["worker"] == who)["lineage"] + if not lc["key"] or not lc["released"]: continue + new = cand("pc/newest", cls=lc["class"], maker=lc["maker"], rel="2027-01-01", cost=rng.choice([None, 0.1, 5.0])) after, _ = pick(cands + [new], records, d, availability=down) if after is None: continue got = next(c for c in cands + [new] if c["worker"] == after)["lineage"] if got["key"] == lc["key"]: - self.assertGreaterEqual(modelid.compare(got, lc), 0, (who, after)) + self.assertGreaterEqual(routing.compare_release(got, lc), 0, (who, after)) done += 1 self.assertGreater(done, 30) - def test_a_result_read_as_unknown_never_triggers_supersession(self): + def test_a_model_with_nothing_recorded_never_triggers_supersession(self): rng = random.Random(5) - for _ in range(200 * ITERS): - ids = ["prov/abc-%d.%d-%s" % (rng.randint(1, 9), rng.randint(0, 9), rng.choice(["sol", "luna", "astra"])) for _ in range(rng.randint(2, 5))] - cands = [cand(w, cost=rng.choice([None, 1.0, 2.0])) for w in dict.fromkeys(ids)] + for _ in range(100 * ITERS): + cands = [cand("prov/m-%d" % i, known=False, cost=rng.choice([None, 1.0, 2.0])) for i in range(rng.randint(2, 5))] who, r = pick(cands) self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")]) diff --git a/tests/test_modelid.py b/tests/test_modelid.py deleted file mode 100644 index b0c8516..0000000 --- a/tests/test_modelid.py +++ /dev/null @@ -1,118 +0,0 @@ -"""Reading a model id: maker, line, class, version, and which of two is the more recently released. -Fixtures are invented ids shaped like real ones. Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3.""" -import json, os, random, unittest -from support import * -from sisi import modelid - -WORDS = json.load(open(os.path.join(REPO, "canon", "model-words.json"))) - - -def p(worker, **kw): - return modelid.parse(worker, WORDS, **kw) - - -def r(worker, **kw): - return modelid.resolve(worker, WORDS, **kw) - - -class ParseTests(unittest.TestCase): - def test_version_line_and_class_from_the_name(self): - """R-7.2-1: the class is read from the id; no tier word means the line's standard model.""" - a = p("prov/abc-5.3") - self.assertEqual((a["maker"], a["class"], a["version"], a["confident"]), ("abc", "standard", (5, 3), True)) - self.assertEqual(p("prov/abc-5.3-flash")["class"], "flash") - - def test_a_tier_word_before_or_after_the_version_parses_the_same(self): - after, before = p("prov/abc-5.4-flash"), p("prov/abc-flash-5.4") - for k in ("maker", "line", "class", "label", "version", "confident"): - self.assertEqual(after[k], before[k], k) - - def test_versions_compare_numerically(self): - """5.10 is newer than 5.9, not older (the string order would say so).""" - self.assertGreater(modelid.compare(r("prov/abc-5.10"), r("prov/abc-5.9")), 0) - self.assertLess(modelid.compare(r("prov/abc-5.9"), r("prov/abc-5.10")), 0) - self.assertEqual(modelid.compare(r("prov/abc-5"), r("prov/abc-5.0")), 0) - - def test_a_dated_suffix_compares_as_a_date_and_does_not_disturb_the_version(self): - dated = p("prov/abc-5-4-20261101") - self.assertEqual((dated["version"], dated["date"], dated["class"]), ((5, 4), "2026-11-01", "standard")) - self.assertEqual(p("prov/abc-5.4-2026-11-01")["date"], "2026-11-01") - self.assertGreater(modelid.compare(r("prov/abc-5-4-20261101"), r("prov/abc-5.3")), 0) - self.assertEqual(modelid.compare(r("prov/abc-5-4-20261101"), r("prov/abc-5.4")), 0) - self.assertGreater(modelid.compare(r("prov/abc-5.4-20261101"), r("prov/abc-5.4-20260901")), 0) - self.assertGreater(modelid.compare(r("prov/abc-20261101"), r("prov/abc-20250301")), 0) - self.assertEqual(modelid.compare(r("prov/abc-20261101"), r("prov/abc-5.3")), 0) # not comparable - self.assertIsNone(p("prov/abc-5.4-20261345")["date"]) # not a date - - def test_two_tier_words_make_one_class_and_letter_prefixed_versions_read(self): - self.assertEqual(p("prov/abc-flash-lite-5.4")["class"], "flash-lite") - self.assertEqual(p("prov/xyz-v4.1-pro")["version"], (4, 1)) - self.assertEqual(p("prov/xyz-k2.7-code")["class"], "code") - self.assertEqual(p("prov/xyz3.8-flash")["version"], (3, 8)) - - def test_ignored_words_are_neither_line_nor_class(self): - self.assertEqual(p("prov/abc-5.4-preview-free")["class"], "standard") - self.assertEqual(p("prov/abc-5.4-flash-latest")["class"], "flash") - - def test_a_named_line_is_the_class_label(self): - """Item 7: for a maker whose lines are the classes the line name is the class label.""" - a, b = p("prov/abc-wonder-1.0"), p("prov/abc-wonder-full-1.0") - self.assertEqual((a["line"], a["label"]), ("wonder", "wonder")) - self.assertEqual((b["line"], b["class"], b["label"]), ("wonder", "full", "wonder-full")) - self.assertEqual(p("prov/abc-ember-1.0")["label"], "ember") - - def test_what_cannot_be_read_with_confidence_says_unknown(self): - """R-7.2-3: no version, or a word after the version that the data does not know: class unknown.""" - for ident in ("prov/xyz-mini", "prov/abc", "prov/abc-6.2-sol", "prov/abc-3-5-sonnet", "prov/5.4"): - got = p(ident) - self.assertFalse(got["confident"], ident) - self.assertEqual(got["class"], "unknown", ident) - self.assertIsNone(r(ident)["key"], ident) - self.assertEqual(r(ident)["source"], "unknown", ident) - - def test_tier_words_are_data_not_code(self): - """Adding a tier word to the data changes the reading; the code names none.""" - self.assertFalse(p("prov/abc-5.4-sol")["confident"]) - got = modelid.parse("prov/abc-5.4-sol", {"tiers": ["sol"], "ignore": []}) - self.assertEqual((got["class"], got["confident"]), ("sol", True)) - text = open(os.path.join(REPO, "sisi", "modelid.py")).read() - for word in WORDS["tiers"] + WORDS["ignore"]: - self.assertNotRegex(text.replace("standard", ""), r'"%s"' % word) - - def test_a_recorded_fact_beats_the_reading(self): - got = r("prov/abc-6.2-sol", fact={"class": "sol", "maker": "abc"}) - self.assertEqual((got["source"], got["class"], got["key"]), ("fact", "sol", ("abc", "", "sol"))) - flipped = r("prov/abc-5.3-flash", fact={"class": "standard"}) - self.assertEqual(flipped["class"], "standard") - self.assertEqual(r("prov/abc-5.4", fact={"family": "wonder", "class": "full"})["label"], "wonder-full") - self.assertEqual(r("prov/abc-5.4", fact={"family": "wonder", "class": "wonder-full"})["label"], "wonder-full") - self.assertEqual(r("prov/abc-5.4")["source"], "guess") - - def test_a_recorded_release_date_beats_version_numbers(self): - old_but_later = r("prov/abc-5.3", fact={"released": "2026-09-01"}) - new_but_earlier = r("prov/abc-5.4", fact={"released": "2026-03-01"}) - self.assertGreater(modelid.compare(old_but_later, new_but_earlier), 0) - self.assertGreater(modelid.compare(r("prov/abc-5.4"), r("prov/abc-5.3")), 0) - - def test_a_bare_host_alias_is_the_newest_of_its_class_once_the_class_is_recorded(self): - alias = r("abc", host_native=True, fact={"class": "standard", "maker": "abc"}) - self.assertTrue(alias["alias"]) - self.assertGreater(modelid.compare(alias, r("prov/abc-9.9")), 0) - self.assertEqual(alias["key"], r("prov/abc-5.3")["key"]) - unrecorded = r("abc", host_native=True) - self.assertFalse(unrecorded["alias"]) - self.assertIsNone(unrecorded["key"]) - - def test_the_parser_never_raises_and_compare_is_antisymmetric(self): - rng = random.Random(7) - pool = ["abc", "xyz", "5", "4", "10", "3.2", "flash", "mini", "pro", "preview", "20261101", "v2", "k3", "x", "", "-", "70b", "sol", "4o", "2026", "11", "01"] - for _ in range(500 * ITERS): - ident = "prov/" + "-".join(rng.choice(pool) for _ in range(rng.randint(0, 6))) - a, b = r(ident), r("prov/" + "-".join(rng.choice(pool) for _ in range(rng.randint(0, 6)))) - self.assertEqual(modelid.compare(a, b), -modelid.compare(b, a), ident) - if a["source"] == "unknown": - self.assertIsNone(a["key"]) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_worker_classify.py b/tests/test_worker_classify.py new file mode 100644 index 0000000..a01e564 --- /dev/null +++ b/tests/test_worker_classify.py @@ -0,0 +1,128 @@ +"""`sisi workers classify`: the question for a cheap, fast worker and the validated recording of its answer. +Invented ids. Requirement ids: R-7.2-1, R-7.2-3.""" +import json, os, unittest +from support import * +from test_worker_models import ModelCase + +MODELS = ("abc-old", "abc-new", "xyz-one") +ANSWER = {"workers": {"muse/abc-old": {"maker": "abc", "class": "standard", "released": "2026-03"}, + "muse/abc-new": {"maker": "abc", "class": "standard", "released": "2026-09-01"}, + "muse/xyz-one": {"maker": "xyz", "class": "unknown", "released": "unknown"}}, + "classes": {"abc": ["standard", "flash"]}} + + +class ClassifyCase(ModelCase): + def setUp(self): + super().setUp() + self.seed([("muse/abc-old", 12, 12), ("muse/abc-new", 3, 3), ("muse/xyz-one", 12, 12)], difficulty=2) + self.file = os.path.join(self.tmp, "answer.json") + + def classify(self, *args): + return self.sisi("workers", "classify", *args, env=self.env(MODELS)) + + def answer(self, obj, wrap=lambda t: t): + open(self.file, "w").write(wrap(obj if isinstance(obj, str) else json.dumps(obj))) + return self.classify("--record", self.file, "--by", "cheap-worker-x") + + def stored(self): + p = os.path.join(self.data, "worker-models.json") + return json.load(open(p)) if os.path.exists(p) else {} + + +class QuestionTests(ClassifyCase): + def test_it_prints_a_short_instruction_and_the_ids_that_have_no_classification(self): + out = self.classify().stdout.splitlines() + ids = [l for l in out if l.startswith("muse/")] + self.assertEqual(sorted(ids), ["muse/abc-new", "muse/abc-old", "muse/xyz-one"]) + self.assertLessEqual(len(out) - len(ids), 15, out) + text = "\n".join(out) + for must in ("maker", "class", "release date", "unknown", "JSON"): + self.assertIn(must, text) + + def test_classified_workers_are_not_asked_again_and_nothing_is_left_to_ask_at_the_end(self): + self.record("muse/abc-old", "standard", "2026-03-01", models=MODELS) + ids = [l for l in self.classify().stdout.splitlines() if l.startswith("muse/")] + self.assertEqual(sorted(ids), ["muse/abc-new", "muse/xyz-one"]) + self.assertEqual(self.answer({"workers": {w: ANSWER["workers"][w] for w in ids}}).returncode, 0) + self.assertIn("every routable worker is classified", self.classify().stdout) + + +class RecordTests(ClassifyCase): + def test_a_valid_answer_is_stored_with_the_classifying_worker_as_the_source(self): + r = self.answer(ANSWER) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn("3 classification(s) (1 unknown) and 1 class order(s)", r.stdout) + data = self.stored() + self.assertEqual(data["models"]["muse/abc-new"]["source"], "classified by cheap-worker-x") + self.assertEqual((data["models"]["muse/abc-old"]["class"], data["models"]["muse/abc-old"]["released"]), ("standard", "2026-03")) + self.assertEqual(data["classes"]["abc"]["order"], ["standard", "flash"]) + self.assertEqual(data["models"]["muse/xyz-one"]["class"], "unknown") + self.assertNotIn("released", data["models"]["muse/xyz-one"]) + + def test_an_answer_wrapped_in_prose_or_a_code_fence_is_read(self): + r = self.answer(ANSWER, wrap=lambda t: "Here you go:\n```json\n%s\n```\nDone." % t) + self.assertEqual(r.returncode, 0, r.stderr) + + def test_an_id_that_was_not_asked_about_is_refused_and_nothing_is_recorded(self): + bad = json.loads(json.dumps(ANSWER)) + bad["workers"]["muse/never-heard-of-it"] = {"maker": "abc", "class": "standard", "released": "2026-01"} + r = self.answer(bad) + self.assertEqual(r.returncode, 1) + self.assertIn("muse/never-heard-of-it", r.stderr) + self.assertEqual(self.stored(), {}) + self.record("muse/abc-old", "standard", models=MODELS) # an id that is already classified is not asked about either + r = self.answer({"workers": {"muse/abc-old": ANSWER["workers"]["muse/abc-old"]}}) + self.assertEqual(r.returncode, 1) + + def test_malformed_answers_are_refused_and_nothing_is_recorded(self): + for bad in ("not json at all", "[1, 2]", json.dumps({"workers": []}), + json.dumps({"workers": {"muse/abc-old": {"maker": "abc", "class": "so l", "released": "2026-01"}}}), + json.dumps({"workers": {"muse/abc-old": {"maker": "abc", "class": "x", "released": "last year"}}}), + json.dumps({"workers": {"muse/abc-old": "standard"}})): + self.assertEqual(self.answer(bad).returncode, 1, bad) + self.assertEqual(self.stored(), {}) + self.assertEqual(self.classify("--record", os.path.join(self.tmp, "missing.json")).returncode, 1) + + def test_a_recorded_class_order_is_never_overwritten_by_an_answer(self): + self.sisi("workers", "classes", "abc", "flash", "standard", "--source", "owner", env=self.env(MODELS)) + self.answer(ANSWER) + self.assertEqual(self.stored()["classes"]["abc"]["order"], ["flash", "standard"]) + + def test_an_unknown_answer_changes_nothing_in_routing_and_is_not_asked_again(self): + def route(): + return self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env(MODELS)).stdout + before = route() + self.answer({"workers": {w: {"maker": "unknown", "class": "unknown", "released": "unknown"} for w in ANSWER["workers"]}}) + after = route() + strip = lambda t: [l for l in t.splitlines() if not l.startswith("sisi:")] + self.assertEqual(strip(before), strip(after)) + self.assertIn("every routable worker is classified", self.classify().stdout) + self.assertNotIn("sisi: no maker", after) + + def test_after_recording_the_newest_version_wins(self): + self.answer(ANSWER) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env(MODELS)) + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertIn("superseded by muse/abc-new", r.stdout) + self.assertIn("the record of its predecessor muse/abc-old", r.stdout) + + +class AskingLineTests(ClassifyCase): + def test_route_asks_only_when_an_unclassified_worker_is_in_the_running(self): + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env(MODELS)) + self.assertEqual(len([l for l in r.stdout.splitlines() if "sisi workers classify" in l]), 1, r.stdout) + self.assertLessEqual(len(r.stdout.splitlines()), 7) + self.answer(ANSWER) + r = self.sisi("route", "--kind", "impl", "--difficulty", "2", env=self.env(MODELS)) + self.assertNotIn("sisi workers classify", r.stdout) + + def test_session_start_names_the_unclassified_workers_in_its_one_facts_line(self): + from sisi import workers + r = self.sisi("tick", stdin=json.dumps({"session_id": "s-cls", "cwd": self.proj, "source": "startup", "model": "mystery-9"}), + env=self.env(MODELS)) + lines = [l for l in r.stdout.splitlines() if "worker facts" in l or "sisi workers classify" in l] + self.assertEqual(len(lines), 1, r.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_worker_models.py b/tests/test_worker_models.py index fa8652c..aebe79f 100644 --- a/tests/test_worker_models.py +++ b/tests/test_worker_models.py @@ -1,7 +1,7 @@ -"""Model lines in the worker commands: the class a lead agent records beats the parser, and `sisi workers` -shows maker, class and recency for each routable worker. Fixtures are invented ids shaped like real ones. -Requirement ids: R-7.2-1, R-7.2-3.""" -import json, os, stat, unittest +"""The worker commands and the model facts: the maker, class and release date a cheap worker researched are +recorded with `sisi workers fact`, shown by `sisi workers`, and drive `sisi route`. sisi reads nothing from a name. +Invented ids. Requirement ids: R-7.2-1, R-7.2-3.""" +import json, os, stat, subprocess, unittest from support import * FAKE_MUSE = """#!/bin/sh @@ -44,9 +44,15 @@ class ModelCase(SisiCase): os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR) return dict(PATH=bindir, MUSE_MODELS=" ".join(models)) - def route(self, difficulty=1, *extra, models=("abc-5.3", "abc-5.4")): - r = self.sisi("route", "--kind", "impl", "--difficulty", str(difficulty), *extra, env=self.env(models)) - return r + def record(self, worker, cls, released=None, maker="abc", models=None): + args = ["workers", "fact", worker, "--maker", maker, "--class", cls, "--source", "fixture research"] + if released: + args += ["--released", released] + r = self.sisi(*args, env=self.env(models)) + self.assertEqual(r.returncode, 0, r.stderr) + + def route(self, difficulty=1, *extra, models=("abc-old", "abc-new")): + return self.sisi("route", "--kind", "impl", "--difficulty", str(difficulty), *extra, env=self.env(models)) def listing(self): r = self.sisi("workers", env=self.env()) @@ -55,39 +61,26 @@ class ModelCase(SisiCase): class FactTests(ModelCase): - def test_a_class_fact_is_recorded_with_its_source_and_shown(self): - """R-7.2-3: the lead agent's decision about a model is stored, with its source, and shown.""" - self.seed([("prov/abc-6.2-sol", 9, 9), ("prov/abc-5.3", 9, 9)]) - before = self.listing() - self.assertIn("prov/abc-6.2-sol: class unknown", before) - self.assertIn("prov/abc-5.3: maker abc, class standard (a guess read from the id)", before) - r = self.sisi("workers", "fact", "prov/abc-6.2-sol", "--class", "sol", "--released", "2026-11-01", - "--source", "lead agent, read the maker's page", env=self.env()) - self.assertEqual(r.returncode, 0, r.stderr) - stored = json.load(open(os.path.join(self.data, "worker-models.json")))["models"]["prov/abc-6.2-sol"] - self.assertEqual((stored["class"], stored["released"], stored["source"]), - ("sol", "2026-11-01", "lead agent, read the maker's page")) - after = self.listing() - self.assertIn("prov/abc-6.2-sol: maker abc, class sol (recorded); released 2026-11-01 (recorded), version 6.2", after) - - def test_a_recorded_class_beats_the_parser(self): - self.seed([("prov/abc-5.3-flash", 9, 9)]) - self.assertIn("class flash (a guess", self.listing()) - self.sisi("workers", "fact", "prov/abc-5.3-flash", "--class", "standard", "--source", "lead", env=self.env()) - self.assertIn("class standard (recorded)", self.listing()) + def test_a_maker_class_and_release_date_are_recorded_with_their_source_and_shown(self): + """R-7.2-3: what a cheap worker researched about a model is stored, with its source, and shown.""" + self.seed([("prov/abc-x", 9, 9)]) + self.assertIn("prov/abc-x: no maker and class recorded", self.listing()) + self.record("prov/abc-x", "flash", "2026-11-01") + stored = json.load(open(os.path.join(self.data, "worker-models.json")))["models"]["prov/abc-x"] + self.assertEqual((stored["class"], stored["maker"], stored["released"], stored["source"]), + ("flash", "abc", "2026-11-01", "fixture research")) + self.assertIn("prov/abc-x: maker abc, class flash; released 2026-11-01", self.listing()) def test_bad_input_is_refused_and_nothing_is_recorded(self): - self.seed([("prov/abc-5.3", 9, 9)]) + self.seed([("prov/abc-x", 9, 9)]) for args in (("--class", "sol"), ("--class", "so l", "--source", "x"), ("--released", "next week", "--source", "x"), ("--released", "2026-13-40", "--source", "x")): - r = self.sisi("workers", "fact", "prov/abc-5.3", *args, env=self.env()) - self.assertEqual(r.returncode, 1, args) + self.assertEqual(self.sisi("workers", "fact", "prov/abc-x", *args, env=self.env()).returncode, 1, args) self.assertFalse(os.path.exists(os.path.join(self.data, "worker-models.json"))) def test_the_fact_file_is_committed_with_the_other_worker_data(self): - self.seed([("prov/abc-5.3", 9, 9)]) - self.sisi("workers", "fact", "prov/abc-5.3", "--class", "standard", "--source", "lead", env=self.env()) - import subprocess + self.seed([("prov/abc-x", 9, 9)]) + self.record("prov/abc-x", "flash") out = subprocess.run(["git", "status", "--porcelain"], cwd=self.data, capture_output=True, text=True).stdout self.assertNotIn("worker-models.json", out) @@ -95,69 +88,73 @@ class FactTests(ModelCase): class RouteSupersessionTests(ModelCase): def setUp(self): super().setUp() - self.priced = False + self.ready = False - def route(self, difficulty=1, *extra, models=("abc-5.3", "abc-5.4")): - if not self.priced: # a model is routable once it has a record, a price or a standing - self.priced = True - for w, price in (("muse/abc-5.3", "0.5"), ("muse/abc-5.4", "1")): # the older is the cheaper + def route(self, difficulty=1, *extra, models=("abc-old", "abc-new")): + if not self.ready: # a model is routable once it has a record, a price or a standing + self.ready = True + for w, price, rel in (("muse/abc-old", "0.5", "2026-03-01"), ("muse/abc-new", "1", "2026-09-01")): # the older is the cheaper self.sisi("workers", "fact", w, "--price", price, "--source", "fixture", env=self.env(models)) + self.record(w, "standard", rel, models=models) return super().route(difficulty, *extra, models=models) def test_route_uses_the_newest_version_though_the_older_has_the_record(self): """R-7.2-1: the newest usable version of a class is always taken; --explain says what it replaced.""" - self.seed([("muse/abc-5.3", 30, 30)], difficulty=1) + self.seed([("muse/abc-old", 30, 30)], difficulty=1) r = self.route(1, "--explain") - self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout) - self.assertIn("superseded by muse/abc-5.4", r.stdout) + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertIn("superseded by muse/abc-new", r.stdout) def test_the_older_version_is_back_while_the_newer_is_marked_down(self): - self.seed([("muse/abc-5.3", 30, 30)], difficulty=1) + self.seed([("muse/abc-old", 30, 30)], difficulty=1) self.route(1) - self.sisi("workers", "down", "muse/abc-5.4", "--reason", "limit", "--until", "2099-01-02", env=self.env(("abc-5.3", "abc-5.4"))) - self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.3") - self.sisi("workers", "up", "muse/abc-5.4", env=self.env(("abc-5.3", "abc-5.4"))) - self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.4") + env = self.env(("abc-old", "abc-new")) + self.sisi("workers", "down", "muse/abc-new", "--reason", "limit", "--until", "2099-01-02", env=env) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-old") + self.sisi("workers", "up", "muse/abc-new", env=env) + self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-new") - def test_only_recorded_classes_when_the_config_says_so(self): - self.seed([("muse/abc-5.3", 30, 30)], difficulty=1) - os.makedirs(self.data, exist_ok=True) - json.dump({"route": {"supersede_guessed": False}}, open(os.path.join(self.data, "config.json"), "w")) - self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.3") - for w in ("muse/abc-5.3", "muse/abc-5.4"): - self.sisi("workers", "fact", w, "--class", "standard", "--source", "lead", env=self.env(("abc-5.3", "abc-5.4"))) - self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.4") - - def test_the_lead_agent_is_asked_once_for_a_class_that_cannot_be_read_and_then_not(self): - """A class read with confidence raises no question; an unreadable one does, in one line, until recorded.""" - models = ("abc-6.2-sol", "abc-6.3-luna") - self.seed([("muse/abc-6.2-sol", 12, 12), ("muse/abc-6.3-luna", 12, 12)], difficulty=1) - r = self.route(1, models=models) - asks = [l for l in r.stdout.splitlines() if "cannot be read from its id" in l] + def test_the_lead_agent_is_asked_once_for_workers_with_nothing_recorded_and_then_not(self): + models = ("abc-old", "abc-new") + self.seed([("muse/abc-old", 12, 12), ("muse/abc-new", 12, 12)], difficulty=1) + r = self.route(1, models=models) # route() records facts first + self.assertNotIn("no maker, class", r.stdout) + self.seed([("muse/abc-zzz", 12, 12)], difficulty=1) + r = self.sisi("route", "--kind", "impl", "--difficulty", "1", env=self.env(models + ("abc-zzz",))) + asks = [l for l in r.stdout.splitlines() if "no maker, class and release date are recorded" in l] self.assertEqual(len(asks), 1, r.stdout) + self.assertIn("muse/abc-zzz", asks[0]) self.assertLessEqual(len(r.stdout.splitlines()), 7, r.stdout) - for w, c in (("muse/abc-6.2-sol", "sol"), ("muse/abc-6.3-luna", "luna")): - self.sisi("workers", "fact", w, "--class", c, "--maker", "abc", "--source", "lead", env=self.env(models)) - self.assertNotIn("cannot be read", self.route(1, models=models).stdout) - self.seed([("muse/abc-5.3", 12, 12), ("muse/abc-5.4", 12, 12)], difficulty=1) - self.assertNotIn("cannot be read", self.route(1).stdout) + self.record("muse/abc-zzz", "flash", "2026-01-01", models=models + ("abc-zzz",)) + self.assertNotIn("no maker, class", self.sisi("route", "--kind", "impl", "--difficulty", "1", + env=self.env(models + ("abc-zzz",))).stdout) class RouteInheritanceTests(ModelCase): + def setUp(self): + super().setUp() + self.ready = False + + def route(self, difficulty=1, *extra, models=("abc-old", "abc-new")): + if not self.ready: + self.ready = True + self.record("muse/abc-old", "standard", "2026-03-01", models=models) + self.record("muse/abc-new", "standard", "2026-09-01", models=models) + return super().route(difficulty, *extra, models=models) + def test_a_new_release_with_no_data_of_its_own_gets_ordinary_work_at_once(self): """R-7.2-1: discovered, unpriced, unjudged, yet routable and capable through its predecessor's record.""" - self.seed([("muse/abc-5.3", 12, 12)], difficulty=2) + self.seed([("muse/abc-old", 12, 12)], difficulty=2) r = self.route(2, "--explain") - self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout) - self.assertIn("the record of its predecessor muse/abc-5.3", r.stdout) + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) + self.assertIn("the record of its predecessor muse/abc-old", r.stdout) self.assertLessEqual(len(r.stdout.splitlines()), 20, r.stdout) - plain = self.route(2).stdout.splitlines() - self.assertLessEqual(len(plain), 6, plain) + self.assertLessEqual(len(self.route(2).stdout.splitlines()), 6) def test_once_it_has_a_thick_record_of_its_own_the_inherited_one_stops_applying(self): - self.seed([("muse/abc-5.3", 12, 12), ("muse/abc-5.4", 9, 9)], difficulty=2) + self.seed([("muse/abc-old", 12, 12), ("muse/abc-new", 9, 9)], difficulty=2) r = self.route(2, "--explain") - self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout) + self.assertEqual(r.stdout.splitlines()[0], "muse/abc-new", r.stdout) self.assertNotIn("predecessor", r.stdout) From f2a5d3d96d44688e057fcc5c39f10103d2123a74 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Mon, 23 Nov 2026 16:49:51 -0700 Subject: [PATCH 8/8] Recency only among versions of the same model (never across makers or classes); --released accepts YYYY-MM; rule text says newest version of a given model. done / next: repeat runs, report Co-Authored-By: Claude Sonnet 5.5 --- canon/core.md | 6 +++--- canon/orchestration.md | 6 ++++-- docs/workers.md | 9 +++++--- sisi/routing.py | 21 ++++++++++--------- sisi/workers.py | 20 ++++++++++-------- tests/test_model_recency.py | 41 ++++++++++++++++++------------------- 6 files changed, 56 insertions(+), 47 deletions(-) diff --git a/canon/core.md b/canon/core.md index 224735b..69d0073 100644 --- a/canon/core.md +++ b/canon/core.md @@ -81,9 +81,9 @@ wrong work. You own the whole outcome; workers are specialists whose reports are evidence for you to judge. Give each task to the least expensive worker that is capable enough, counting rework as cost, -and keep your own context for judgement. Always use the most recently released model of a class -when it is usable, never an older version of it; classify a maker's models before comparing them, -because different classes are different things. Use the host's own delegation first. Run independent +and keep your own context for judgement. Always use the newest version of a given model +(same maker and class) when it is usable, never an older version of it; a newer release of a +different model or class is a different thing, so classify models before comparing them. Use the host's own delegation first. Run independent work in parallel when it shortens the critical path. Brief a worker with a contract (`sisi delegate brief`), check what comes back in proportion to the risk, and record the judgement (`sisi delegate judge`). `sisi route` recommends a worker from that record, and diff --git a/canon/orchestration.md b/canon/orchestration.md index 0f6b02a..404993a 100644 --- a/canon/orchestration.md +++ b/canon/orchestration.md @@ -33,8 +33,10 @@ present; nothing here names one. Read on demand: `sisi delegate guide`. routine work measured proof outranks a benchmark: the cheapest worker with a judged record wins, and standing decides only when nobody has one. A thin record is a reason for care, not a verdict. -- Always use the most recently released model of a class when it is usable, and never an older - version of it: newer models are almost always better and almost always cheaper, so neither a +- Always use the newest version of a given model (same maker and class) when it is usable, and + never an older version of it. This is about versions of one model, not about whichever model + was released last: a newer release of a different model or class never wins for being newer. + A newer version is almost always better and almost always cheaper, so neither a better old record nor a cheaper old plan brings an older version back. A new version starts from its predecessor's judged record until it has its own. Two exceptions only: the newer model is unusable right now (down, out of allowance, avoided), or its class is not recorded yet. diff --git a/docs/workers.md b/docs/workers.md index de30cd1..ad39248 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -97,8 +97,10 @@ one per group of workers passed over as not capable enough, and names an explora ## Newest version of a class, always -Newer models are almost always better and almost always cheaper, so `sisi route` always uses the -most recently released model of a class that is usable, and never an older version of it. sisi reads +Newer versions of a model are almost always better and almost always cheaper, so `sisi route` always uses +the newest version of a given model (the same maker and class) that is usable, and never an older version of +it. This is about versions of one model: a newer release of a different model or class never wins for being +newer. sisi reads nothing from a model's name: a model's maker, class and release date are facts, researched by a cheap, fast worker (session start and `sisi route` say when they are missing) and recorded with `sisi workers fact WORKER --maker M --class C --released YYYY-MM-DD --source S`. A model's identity is its @@ -129,7 +131,8 @@ its maker and class (one version back at a time), named in `--explain`. It ranks own record and above a benchmark, counts as a judged record for the rule that proof comes before benchmark, stops once the model has a thick record of its own, and a predecessor's bad record is not inherited. A discovered model with no data of its own is routable when its predecessor is. Where the -arithmetic falls back to a stable tie-break, the more recently released model wins first. +arithmetic falls back to a stable tie-break, the newer version of the same model goes first (never across makers +or classes). ## Costs and failures diff --git a/sisi/routing.py b/sisi/routing.py index b859d70..323aee1 100644 --- a/sisi/routing.py +++ b/sisi/routing.py @@ -51,8 +51,8 @@ The rule, in order: is never compared. 8. Load balancing: within the same price tier and price, the worker that has taken the least work relative to its remaining allowance goes first (recorded uses divided by allowance left, an - unknown allowance counting as half). Ties break on the more recently released model (its recorded - release date), then on the worker id. + unknown allowance counting as half). Ties break on the newer version of the same model (never across + makers or classes), then on the worker id. Candidates reach here already restricted to workers with a judged record, a known price or a benchmark standing (see workers.routable_candidates); on a cold start none qualifies and every @@ -584,18 +584,19 @@ def _assess_all(eligible, stats, kind, difficulty, floors, opts=None): def recency_order(candidates): - """{worker: (recorded release date as days, negated; position among the versions of its class, newest first)}. - Smaller sorts first, so the more recently released model goes first; what cannot be compared is (0, 0).""" - out = {c["worker"]: (0, 0) for c in candidates} + """{worker: position among the versions of its own model, newest first (0)}. Only versions of the same model + (the same recorded maker and class) are ever compared; models of different makers or classes are different + things, however recently each was released, and stay at 0 so the old tie-break decides between them.""" + out = {c["worker"]: 0 for c in candidates} groups = {} for c in candidates: - l = _lineage(c) - if l and l.get("key"): + l = _comparable(c) + if l: groups.setdefault(tuple(l["key"]), []).append(c) for group in groups.values(): for i, level in enumerate(_versions_newest_first(group)): for d in level: - out[d["worker"]] = (-days(_lineage(d).get("released")), i) + out[d["worker"]] = i return out @@ -625,7 +626,7 @@ def _make_key(stats, kind, difficulty, prefer, recency=None): standing_key(c), load_ratio(c), -(r if r is not None else -1.0), - recency.get(c["worker"], (0, 0)), + recency.get(c["worker"], 0), c["worker"]) return key, rate, load_ratio, recency @@ -732,7 +733,7 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None, reason = ("lower measured accepted rate for this kind and difficulty" if r is not None and cr is not None and r < cr else "equal on price and load; the choice is the more recently released" - if recency.get(choice["worker"], (0, 0)) < recency.get(c["worker"], (0, 0)) else + if recency.get(choice["worker"], 0) < recency.get(c["worker"], 0) else "equal on price and load; the choice came first in worker-id order") passed.append((w, reason)) judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1] diff --git a/sisi/workers.py b/sisi/workers.py index 0baf5fa..f01b4fa 100644 --- a/sisi/workers.py +++ b/sisi/workers.py @@ -2074,10 +2074,8 @@ def _model_fact_args(args): continue v = v.strip().lower() if field == "released": - try: - datetime.date.fromisoformat(v) - except ValueError: - print("sisi: --released wants a date as YYYY-MM-DD", file=sys.stderr) + if not _valid_date(v): + print("sisi: --released wants a date as YYYY-MM-DD (or YYYY-MM)", file=sys.stderr) return False elif not _NAME.fullmatch(v): print("sisi: %s wants a short name (letters, digits, hyphens)" % opt, file=sys.stderr) @@ -2117,6 +2115,15 @@ def _classify_answer(text): return None +def _valid_date(v): + """A release date as YYYY-MM-DD or YYYY-MM.""" + try: + datetime.date.fromisoformat(v if len(v) == 10 else v + "-01") + except (ValueError, TypeError): + return False + return len(v) in (7, 10) + + def _valid_name(v): return isinstance(v, str) and (v.strip().lower() == "unknown" or bool(_NAME.fullmatch(v.strip().lower()))) @@ -2157,10 +2164,7 @@ def _cmd_classify(args): released = e.get("released", "unknown") if isinstance(e, dict) else None ok = isinstance(e, dict) and _valid_name(e.get("maker")) and _valid_name(e.get("class")) if ok and str(released).lower() != "unknown": - try: - ok = routing.days(released) > 0 and (len(released) == 7 or datetime.date.fromisoformat(released) is not None) - except (ValueError, TypeError): - ok = False + ok = isinstance(released, str) and _valid_date(released) if not ok: print("sisi: the entry for %s is not {maker, class, released} with short names and a YYYY-MM[-DD] date " "(or unknown); nothing recorded" % w, file=sys.stderr) diff --git a/tests/test_model_recency.py b/tests/test_model_recency.py index 28b299c..6474277 100644 --- a/tests/test_model_recency.py +++ b/tests/test_model_recency.py @@ -1,5 +1,5 @@ """Recency breaks ties: where the arithmetic falls back to a stable order, the more recently released model wins -first (its recorded release date, else the old tie-break by worker id), and the +first (a newer version of the same model, never across makers or classes), and the rule is in the text agents and people read. Requirement ids: R-7.2-1, R-7.2-2.""" import os, unittest from support import * @@ -8,27 +8,26 @@ from test_model_supersession import cand, pick class RecencyTieBreakTests(unittest.TestCase): - def test_a_recorded_release_date_decides_a_tie_between_unrelated_models(self): + def test_a_newer_release_never_beats_a_different_model_just_for_being_newer(self): + """The owner: newer means a newer version of the SAME model, not the newest release across models.""" a = cand("prov/aaa-1.0", cost=1.0, rel="2026-01-10", maker="aaa") b = cand("prov/bbb-2.0", cost=1.0, rel="2026-08-01", maker="bbb") who, r = pick([a, b]) - self.assertEqual(who, "prov/bbb-2.0") - self.assertIn(("prov/aaa-1.0", "equal on price and load; the choice is the more recently released"), r["passed_over"]) - self.assertEqual(pick([b, a])[0], "prov/bbb-2.0") + self.assertEqual(who, "prov/aaa-1.0") # the old tie-break (worker id), whatever the release dates + self.assertEqual(pick([b, a])[0], "prov/aaa-1.0") + flash = cand("prov/abc-flash", cls="flash", cost=1.0, rel="2026-01-10") + std = cand("prov/abc-std", cls="standard", cost=1.0, rel="2026-08-01") + self.assertEqual(pick([flash, std])[0], "prov/abc-flash") + self.assertEqual(routing.recency_order([a, b, flash, std]), {w: 0 for w in ("prov/aaa-1.0", "prov/bbb-2.0", "prov/abc-flash", "prov/abc-std")}) - def test_unknown_recency_keeps_the_old_tie_break(self): - a, b = cand("prov/aaa-1.0", cost=1.0, maker="aaa"), cand("prov/bbb-9.0", cost=1.0, maker="bbb", rel="2026-08-01") - who, r = pick([a, b]) - self.assertEqual(who, "prov/bbb-9.0") # a recorded date beats none - a2, b2 = cand("prov/aaa-1.0", cost=1.0, maker="aaa", known=False), cand("prov/bbb-9.0", cost=1.0, maker="bbb", known=False) - who, r = pick([a2, b2]) - self.assertEqual(who, "prov/aaa-1.0") - self.assertIn(("prov/bbb-9.0", "equal on price and load; the choice came first in worker-id order"), r["passed_over"]) + def test_within_one_model_the_newer_version_goes_first(self): + old, new = cand("prov/abc-old", rel="2026-01-10"), cand("prov/abc-new", rel="2026-08-01") + self.assertEqual(routing.recency_order([old, new]), {"prov/abc-new": 0, "prov/abc-old": 1}) - def test_price_and_load_still_come_before_recency(self): - cheap_old = cand("prov/aaa-1.0", cost=0.5, rel="2026-01-10", maker="aaa") - dear_new = cand("prov/bbb-2.0", cost=1.0, rel="2026-08-01", maker="bbb") - self.assertEqual(pick([cheap_old, dear_new])[0], "prov/aaa-1.0") + def test_price_and_load_still_come_before_the_tie_break(self): + cheap = cand("prov/aaa-1.0", cost=0.5, maker="aaa") + dear = cand("prov/bbb-2.0", cost=1.0, maker="bbb", rel="2026-08-01") + self.assertEqual(pick([cheap, dear])[0], "prov/aaa-1.0") class TextTests(unittest.TestCase): @@ -39,13 +38,13 @@ class TextTests(unittest.TestCase): def test_the_rule_is_in_the_always_loaded_rulebook_the_playbook_and_the_docs(self): core = self.read("canon", "core.md") rule6 = core[core.index("## 6. Orchestrate"):core.index("## 7.")] - self.assertIn("most recently released", rule6) + self.assertIn("newest version of a given model", rule6) self.assertIn("never an older version", rule6) - self.assertIn("class", rule6) + self.assertIn("different model or class", rule6) for path in (("canon", "orchestration.md"), ("docs", "workers.md")): text = self.read(*path).lower() - self.assertIn("most recently released", text, path) - self.assertIn("different classes", text, path) + self.assertIn("newest version of a given model", text.replace("\n", " ").replace(" ", " "), path) + self.assertIn("different model or class", text.replace("\n", " ").replace(" ", " "), path) self.assertIn("cheaper", text, path) # the reason: newer models are better and cheaper def test_the_rulebook_is_inside_its_budget(self):