Merge branch 'p5-wheel-bad'

This commit is contained in:
swaits committed 2026-12-01 15:31:28 -07:00
commit 6632a82f77
3 files changed
+85 -32

No files matched your search

+3 -2
View File
@@ -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 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 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 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), 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. One pick, one delegation. A worker that failed for a 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 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 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 shortly (Claude Code's `Agent` tool says `sonnet`) may give one whole segment of the picked model id, so name a worker
+28 -30
View File
@@ -88,20 +88,16 @@ def sync_shared(cwd=None):
def age_days(): def age_days():
try: try: return (time.time() - os.path.getmtime(table())) / 86400.0
return (time.time() - os.path.getmtime(table())) / 86400.0 except OSError: return None
except OSError:
return None
def stale(mark=None): def stale(mark=None):
"""One line when the table is missing, old, or missed a worker, else "".""" """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] 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: if mark is not None and who:
try: try: store.write(store.data("models.stale"), who + "\n")
store.write(store.data("models.stale"), who + "\n") except Exception: pass # best effort: a refusal never depends on it
except Exception: # best effort: a refusal never depends on it
pass
age = age_days() age = age_days()
if age is None or age > store.config()["research_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 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()} 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) """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.""" 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() 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 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)] left = [r for r in table_rows if r[2].strip().lower() == cls and not out(r, skip, bad, gone, now)]
if not left: if not left: return None
return None
if rand is None: if rand is None:
import random import random
rand = random.random rand = random.random
med = {short(r[0]): median(speed[short(r[0])]) for r in left if (speed or {}).get(short(r[0]))} 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) 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 w for w, r in zip(range(len(left), 0, -1), left)] 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) x = rand() * sum(weights)
for weight, r in zip(weights, left): for weight, r in zip(weights, left):
x -= weight if (x := x - weight) < 0: return r
if x < 0:
return r
return left[-1] 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)): 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) print("sisi pick: %r is not a worker in the models table; --review-of names the worker whose work is reviewed." % review)
return 1 return 1
speed, gone, now = speeds(), away(), time.time() speed, gone, qual, now = speeds(), away(), qualities(), time.time()
r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now) r = choose(text, cls, skip, review, rand, speed=speed, gone=gone, now=now, quality=qual)
if not r: if not r:
bad = next((maker(x) for x in rows(text) if short(x[0]) == short(review)), None) 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, "") 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], 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)), "why": retro.clean(args[2]), "project": os.path.basename(store.project_root(cwd)),
"project_key": store.project_key(cwd)} "project_key": store.project_key(cwd)}
if sid: if sid: rec["session_id"] = sid
rec["session_id"] = sid if began is not None: rec["started"] = iso(began)
if began is not None: if minutes: rec["minutes"] = minutes
rec["started"] = iso(began)
if minutes:
rec["minutes"] = minutes
log = store.data("outcomes.jsonl") log = store.data("outcomes.jsonl")
store.append(log, json.dumps(rec, sort_keys=True)) store.append(log, json.dumps(rec, sort_keys=True))
ok = store.commit("delegation judged", log) 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)} 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): 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)) 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 := outcomes(15): print("\nHow recent delegations went:\n" + "\n".join(recent))
if recent: if stale(): print("\n" + stale())
print("\nHow recent delegations went:\n" + "\n".join(recent))
if stale():
print("\n" + stale())
return 0 return 0
if args == ["research"]: if args == ["research"]:
return print(research_brief()) or 0 return print(research_brief()) or 0
+54
View File
@@ -1998,6 +1998,60 @@ cli.main(["tick"])
wins = [models.choose(table, "ordinary", rand=rng.random, speed={"slow": [45], "fast": [9]})[0] for _ in range(2000)] 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 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 \"<brief>\"` | ordinary | flat | x | |\n| beta | `beta \"<brief>\"` | 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 \"<brief>\"` | 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 \"<brief>\"` | ordinary | flat | x | |\n| beta | `beta \"<brief>\"` | 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): def test_pick_and_models_show_the_minutes(self):
self.table(WORKERS) self.table(WORKERS)
self.hook("tick") self.hook("tick")