From 33ca3d3c4d0aa03e799ad790ad050342f5675446 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Tue, 1 Dec 2026 15:24:09 -0700 Subject: [PATCH] Scale wheel weight by recent good/bad quality factor Multiply each worker's wheel weight by a normalized Laplace quality factor over its last 10 good/bad verdicts, ((good+1)/(n+2))/((n+1)/(n+2)) = (good+1)/(n+1), ignoring out and extend. Workers with no bad runs keep their full weight (factor 1.0); workers with all bad runs floor at 1/11 so they remain pickable and picks are never refused. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++-- sisi/models.py | 58 ++++++++++++++++++++++------------------------ tests/test_core.py | 54 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index e7ff190..463bf5f 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,9 @@ organizes the rules. It routes by a models table: which workers you have, what each is good at, what it costs. A research worker rebuilds that table when it gets old, and every judged delegation feeds the next research. The lead does not choose the worker: `sisi pick CLASS` spins a wheel over the workers of that class (a capability tier: each model is -in exactly one class, so the wheel never mixes tiers; weighted by table order and by the square of the speed ratio), -and a delegation to a worker the wheel did not give gets a note. One pick, one delegation. A worker that failed for a +in exactly one class, so the wheel never mixes tiers; weighted by table order and by the cube of the speed ratio), +and a delegation to a worker the wheel did not give gets a note. Recent `bad` verdicts over a worker's last 10 +good/bad jobs also scale its weight down (never to zero), while workers with no bad runs keep their full weight. One pick, one delegation. A worker that failed for a limit is judged `out` with the provider's message: it is off the wheel for 6 hours, then the wheel tries it again (at most 4 times a day), and the pick that hands it out says it is a retry. A host that names its models shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker diff --git a/sisi/models.py b/sisi/models.py index 6f34df4..763ffad 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -88,20 +88,16 @@ def sync_shared(cwd=None): def age_days(): - try: - return (time.time() - os.path.getmtime(table())) / 86400.0 - except OSError: - return None + try: return (time.time() - os.path.getmtime(table())) / 86400.0 + except OSError: return None def stale(mark=None): """One line when the table is missing, old, or missed a worker, else "".""" who = re.sub(r"[^\w./:+-]", "", str(store.read(store.data("models.stale")) if mark is None else mark), flags=re.A)[:80] if mark is not None and who: - try: - store.write(store.data("models.stale"), who + "\n") - except Exception: # best effort: a refusal never depends on it - pass + try: store.write(store.data("models.stale"), who + "\n") + except Exception: pass # best effort: a refusal never depends on it age = age_days() if age is None or age > store.config()["research_days"]: return "sisi: " + ("there is no models table yet. " if age is None else "the models table is %d days old. " % age) + ASK @@ -250,26 +246,34 @@ def speeds(): return {w: v[-10:] for w, v in out.items()} -def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None): +def qualities(): + """Each worker's quality factor over its last 10 good/bad outcomes: ((good+1)/(n+2))/((n+1)/(n+2)) = (good+1)/(n+1).""" + out = {} + for o in store.records("outcomes.jsonl"): + w = o["model"] if isinstance(o.get("model"), str) and o["model"].strip() else (o["worker"] if isinstance(o.get("worker"), str) else "") + if o.get("verdict") in ("good", "bad") and w.strip(): out.setdefault(short(w), []).append(o["verdict"] == "good") + return {w: (sum(v[-10:]) + 1) / (len(v[-10:]) + 1) for w, v in out.items()} + + +def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, now=None, quality=None): """One worker of this class, by a wheel weighted by table order (the first of n has weight n, the last 1) - times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs). + times its speed: the fastest candidate's median minutes over its own, cubed, at least 0.02 (1 with no timed jobs), + times its quality factor over its last 10 good/bad outcomes ((good+1)/(n+1), so no bad runs keeps weight 1). A worker last said out less than OUT seconds ago (`gone`, from `outs`) is not on the wheel.""" table_rows, gone, now = rows(text), gone or {}, now or time.time() bad = next((maker(r) for r in table_rows if short(r[0]) == short(review)), None) if review else None left = [r for r in table_rows if r[2].strip().lower() == cls and not out(r, skip, bad, gone, now)] - if not left: - return None + if not left: return None if rand is None: import random rand = random.random med = {short(r[0]): median(speed[short(r[0])]) for r in left if (speed or {}).get(short(r[0]))} - fast = min(med.values(), default=1) - weights = [w * max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else w for w, r in zip(range(len(left), 0, -1), left)] + fast, qual = min(med.values(), default=1), quality or {} + weights = [w * (max(0.02, (fast / med[short(r[0])]) ** 3) if short(r[0]) in med else 1) + * max(1 / 11, qual.get(short(r[0]), 1)) for w, r in zip(range(len(left), 0, -1), left)] x = rand() * sum(weights) for weight, r in zip(weights, left): - x -= weight - if x < 0: - return r + if (x := x - weight) < 0: return r return left[-1] @@ -294,8 +298,8 @@ def pick(args, cwd=None, rand=None): if review is not None and not any(short(r[0]) == short(review) for r in rows(text)): print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review) return 1 - speed, gone, now = speeds(), away(), time.time() - r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now) + speed, gone, qual, now = speeds(), away(), qualities(), time.time() + r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual) if not r: bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None) again = {"routine": " Choose again from ordinary.", "ordinary": " Choose again from hard."}.get(cls, "") @@ -422,12 +426,9 @@ def judge(args, cwd=None): rec = {"ts": iso(now), "ended": iso(now), "worker": args[0], "model": model, "verdict": args[1], "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)), "project_key": store.project_key(cwd)} - if sid: - rec["session_id"] = sid - if began is not None: - rec["started"] = iso(began) - if minutes: - rec["minutes"] = minutes + if sid: rec["session_id"] = sid + if began is not None: rec["started"] = iso(began) + if minutes: rec["minutes"] = minutes log = store.data("outcomes.jsonl") store.append(log, json.dumps(rec, sort_keys=True)) ok = store.commit("delegation judged", log) @@ -444,11 +445,8 @@ def run(args, cwd=None): gone, now, listed = away(), time.time(), {short(r[0]) for r in rows(text)} if sitting := sorted((t, w) for w, (t, _) in gone.items() if w in listed and now - t < OUT): print("\nOff the wheel now:\n" + "\n".join("%s: %s" % (w, SINCE % (clock(t), clock(t + OUT))) for t, w in sitting)) - recent = outcomes(15) - if recent: - print("\nHow recent delegations went:\n" + "\n".join(recent)) - if stale(): - print("\n" + stale()) + if recent := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent)) + if stale(): print("\n" + stale()) return 0 if args == ["research"]: return print(research_brief()) or 0 diff --git a/tests/test_core.py b/tests/test_core.py index 0487296..9003240 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1982,6 +1982,60 @@ cli.main(["tick"]) wins = [models.choose(table, "ordinary", rand=rng.random, speed={"slow": [45], "fast": [9]})[0] for _ in range(2000)] self.assertLess(wins.count("slow"), 100) # 2 * the 0.02 floor against 1: about 4%; it was a third + def test_bad_verdicts_lower_wheel_weight_without_dropping_to_zero(self): + sys.path.insert(0, REPO) + from sisi import models + two = HEADER + "| alpha | `alpha \"\"` | ordinary | flat | x | |\n| beta | `beta \"\"` | ordinary | flat | x | |\n" + self.table(two) + # Same speed (10 min): alpha has 1 good + 4 bad (factor 2/6 = 1/3; weight 2/3 vs beta's 1 -> 40/60 split); out and extend are ignored. + self.jsonl("outcomes.jsonl", + self.outcome("alpha", "good", 10), + *[self.outcome("alpha", "bad", 10)] * 4, + self.outcome("alpha", "out", 1), + self.outcome("alpha", "extend", 1), + *[self.outcome("beta", "good", 10)] * 5) + picked = [] + for i in range(100): + rc, out = self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100) + self.assertEqual(rc, 0, out) + picked.append(out.splitlines()[0].split()[1]) + self.assertEqual(picked.count("alpha"), 40) + self.assertEqual(picked.count("beta"), 60) + self.assertGreater(picked.count("alpha"), 0) + self.assertLess(picked.count("alpha"), picked.count("beta")) + # 12 straight bad runs: only the last 10 count (factor 1/11, weight 2/11 vs 1 -> 16/84 split, still pickable). + self.jsonl("outcomes.jsonl", *[self.outcome("alpha", "bad", 10)] * 12, *[self.outcome("beta", "good", 10)] * 5) + picked2 = [self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)[1].splitlines()[0].split()[1] for i in range(100)] + self.assertEqual(picked2.count("alpha"), 16) + self.assertGreater(picked2.count("alpha"), 0) + q, _ = self.in_process(models.qualities) + self.assertAlmostEqual(q["alpha"], 1 / 11) + self.assertEqual(q["beta"], 1.0) + # Never refuses a pick even when the sole worker has only bad verdicts. + self.table(HEADER + "| alpha | `alpha \"\"` | ordinary | flat | x | |\n") + rc, out = self.in_process(models.pick, ["ordinary"], self.proj, lambda: 0.99) + self.assertEqual((rc, out.splitlines()[0].split()[1]), (0, "alpha")) + + def test_only_good_runs_keep_old_wheel_weight(self): + sys.path.insert(0, REPO) + from sisi import models + two = HEADER + "| alpha | `alpha \"\"` | ordinary | flat | x | |\n| beta | `beta \"\"` | ordinary | flat | x | |\n" + self.table(two) + spin = lambda: [self.in_process(models.pick, ["ordinary"], self.proj, lambda i=i: i / 100)[1].splitlines()[0].split()[1] for i in range(100)] + baseline = spin() + self.assertEqual((baseline.count("alpha"), baseline.count("beta")), (67, 33)) # table order alone: weights 2 and 1 + # Only good runs (and 5 older bad runs rolled off the last-10 window, plus ignored out/extend) keep the exact old weight. + self.jsonl("outcomes.jsonl", + *[self.outcome("alpha", "bad", 10)] * 5, + *[self.outcome("alpha", "good", 10)] * 10, + self.outcome("alpha", "out", 1), + self.outcome("alpha", "extend", 1), + *[self.outcome("beta", "good", 10)] * 4) + after = spin() + self.assertEqual((after.count("alpha"), after.count("beta")), (67, 33)) + q, _ = self.in_process(models.qualities) + self.assertEqual((q["alpha"], q["beta"]), (1.0, 1.0)) + def test_pick_and_models_show_the_minutes(self): self.table(WORKERS) self.hook("tick")