From 9fb2a61920202349d2cca54895cdadc35717e4e7 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 4 Dec 2026 07:03:51 -0700 Subject: [PATCH] Attach a running job to a plan node; honour a provider's stated reset for its whole plan Fault 36: `sisi pick --node ID --started WORKER` records that a job already running (a worker sent a message, which no delegation hook sees) does the node; re-recording a plan keeps a running node whose id and branch are unchanged. Fault 37: `judge WORKER out` keeps the worker off the wheel until the reset its message states (ISO time or "resets in ..." span; else 6 h), together with every worker on the same provider in the models table. Also: tests/test_models_research.py no longer reads the running agent's CLAUDE_CODE_ENTRYPOINT. The line-count cap (test_the_product_stays_small) is left for the join: sisi/ is 3330 lines against 3264. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 11 +++-- sisi/cli.py | 5 ++- sisi/models.py | 79 ++++++++++++++++++++++++++--------- sisi/plan.py | 30 +++++++++++-- tests/test_core.py | 41 +++++++++++++++++- tests/test_models_research.py | 4 ++ tests/test_plan.py | 40 ++++++++++++++---- 7 files changed, 174 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index e7eecbf..d8de679 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,11 @@ choose the worker: `sisi pick CLASS` spins a wheel over the workers of that clas 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 +limit is judged `out` with the provider's message: it and every worker on the same provider in the table are off the wheel +until the reset the message states (`resets at 2026-12-07T00:00:00Z`, `Resets in 108h11m37s`, `try again in 45 minutes`), +else for 6 hours, then the wheel tries again (at most 4 times a day), and the pick that hands one out says it is a retry. +A job already running that no delegation hook saw (a worker you sent a message) is attached to its plan node with +`sisi pick --node ID --started WORKER`. 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 by its full model id (`claude-sonnet-5-5`); anywhere else the name must match whole. @@ -91,7 +94,7 @@ its limits are. | `sisi done --goal … --check … [--check …] --next …` | Record what done means and what comes next; nothing starts before | | `sisi done --pass N "…"` / `--fail N "…"` | Give a check its verdict and evidence; `sisi done` alone shows it | | `sisi fault ""` / `--started\|--blocked\|--fixed N "…"` | Record an open fault in this project, start a fix, name a blocker, or close it; `sisi fault` alone lists them | -| `sisi pick routine\|ordinary\|hard\|deep [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker (a `deep` pick falls back to `hard` when the table has no `deep` row); a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) | +| `sisi pick routine\|ordinary\|hard\|deep [--review-of WORKER] [--not WORKER] [--limit MINUTES] [--branch REF]` | The wheel gives one worker (a `deep` pick falls back to `hard` when the table has no `deep` row); a review goes to a different maker. `--limit` sets this delegation's lateness limit (default `worker_minutes`) and `--branch` names the branch whose last commit shows its progress; `sisi pick --node ID --started WORKER` records that a job already running does the node, without spinning the wheel; picks of one worker are matched to its delegations in order. A job past twice its limit becomes a late-worker fault in the session that started it (only that session is stopped by it; `sisi fault --fixed N "…"` from any other session clears it) | | `sisi retro` | Print what happened in this piece of work and known problems, to set against the objective | | `sisi retro --gap … --cause … --improve … --term T --problem N\|"…" --level core\|user\|project` | Record the gap, the term of the objective it fell short on, and the problem (`N` to cite an existing one or words to open a new one); the improvement is a rule at once, and a 2nd miss (3rd citation) opens a fault | | `sisi retro --no-gap … --term T --better …` | Nothing fell short, but work can always be done better: name the term and the one concrete thing that would have scored better (recorded with the retro; it becomes a rule only if it recurs, when the rules are organized) | @@ -102,7 +105,7 @@ its limits are. | `sisi plan brief` / `sisi plan --record FILE` / `sisi plan` / `sisi plan --done\|--fail ID "…"` | The dependency graph of a piece of work, recorded before any delegation: `\| node \| class \| needs \| branch \| files \| check \| why \|`, one join every node reaches; refused on a cycle, a missing need, a shared branch, or overlapping files between nodes that can run at once. Prints the waves to dispatch together. `sisi pick --node ID` gives the worker and a header for the brief; the hook denies a lead's delegation outside the plan, out of order, unpicked, or without its own worktree, and the end of a turn sends the lead back while ready nodes wait. `sisi judge` closes or reopens the node. A `sisi chore:` brief (models research, plan brief) needs no plan. `"enforce": false` turns denials into reminders | | `sisi models` / `sisi models research [--record FILE]` | The workers table: at most one row per provider (the plan or account a call draws on) per class (`routine`, `ordinary`, `hard`, `deep`), the cheapest among those within one point of the class's best score (a tie never goes to the dearer one; the dearest tier is its own class, `deep`, never a default for `hard`, `ordinary` or `routine`), the one whose published allowance goes furthest, with its source and quota windows (`5h: N req; week: N req`); the wheel picks a plan less the more of its windows sisi's own delegations have used (never below 5%); research is redone every 3 days by a hard worker. (the shared baseline table ships with sisi in `canon/models.md`), and each worker that is out with when it is back on the wheel; have a worker rebuild it | | `sisi models offered [--record FILE]` | Save the host's raw offered-model list from stdin and print the chore to match it against the table; `--record FILE` saves the harness's wheel so `sisi pick` only returns models this harness offers | -| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: off the wheel for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first (and if another open job has `--node`/`--chore`, a note names the closed job and the remaining ones with their targeting flags), `--newest` the newest, `--node ID` closes or reopens the job running that plan node, and `--chore ID` closes that chore job | +| `sisi judge WORKER good\|bad\|out "…" [--minutes N] [--newest] [--node ID \| --chore ID]` | How a delegation went (`out` with the provider's own message when it hit a limit: its whole provider is off the wheel until the stated reset, else for 6 hours, then tried again); the minutes are measured from the pick's delegation (or `--minutes N`) and make the wheel favour faster workers. With several of one worker's jobs open, the oldest is judged first (and if another open job has `--node`/`--chore`, a note names the closed job and the remaining ones with their targeting flags), `--newest` the newest, `--node ID` closes or reopens the job running that plan node, and `--chore ID` closes that chore job | | `sisi judge WORKER extend MINUTES "" [--newest] [--node ID \| --chore ID]` | Give a late job more time instead of judging it: the job that is past its limit (past twice it first, else past once, else the oldest, or the job for `--node ID` / `--chore ID`) gets MINUTES more from now, and its late fault clears | | `sisi direct "…"` | Allow more direct tool calls this turn, with the reason | diff --git a/sisi/cli.py b/sisi/cli.py index 7e8d77e..b601650 100644 --- a/sisi/cli.py +++ b/sisi/cli.py @@ -38,12 +38,15 @@ Delegation a node you did yourself (the join) is done; or reopen a node sisi chore show ID print the chore brief under this one-time id; delegate just its first line plus "Run `sisi chore show ` and do what it says" sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] + sisi pick --node ID --started WORKER + record that a job already running (a worker you sent a message) does this node sisi pick routine|ordinary|hard|deep [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME] the wheel gives you one worker for a ready plan node (or of a class, for a `sisi chore:` brief); one pick, one delegation sisi judge WORKER good|bad|out WHY | extend MINUTES WHY [--newest] [--node ID | --chore ID] how a delegation went (`out` with the provider's own message when it hit a - limit: sisi tries it again by itself), or give a running job more time; + limit: its whole plan is off until the reset the message states, else 6 h, and + sisi tries it again by itself), or give a running job more time; --node ID or --chore ID names the job itself when a worker runs several sisi direct REASON allow yourself more direct tool calls this turn, with the reason diff --git a/sisi/models.py b/sisi/models.py index dbe42c2..79a36aa 100644 --- a/sisi/models.py +++ b/sisi/models.py @@ -2,7 +2,7 @@ A research worker writes it, the lead reads it to route, and `sisi judge` adds how each delegation went so the next research knows. The table is plain text a person can read and correct.""" -import json, math, os, re, sys, time +import datetime, json, math, os, re, sys, time from . import rules, store ASK_FRESH = ("which providers and models from the shipped baseline table below are usable on this machine, how to call each, and what each costs here; map them to whatever providers this user has", @@ -273,32 +273,63 @@ def waiting(s): return isinstance(s.get("starts"), dict) and any(isinstance(v, list) and v for v in s["starts"].values()) -OUT = 6 * 3600 # a worker judged `out` sits out this long, then the wheel tries it again: 24 h / 6 h = at most 4 tries a day +OUT = 6 * 3600 # a worker judged `out` with no reset stated sits out this long, then the wheel tries it again: 24 h / 6 h = at most 4 tries a day clock = lambda t: time.strftime("%m-%d %H:%M", time.localtime(t)) SINCE = "out since %s, back on the wheel at %s" -def outs(log, now=None): - """{worker: (since, why)}: each worker last said to be out, and when: an `out` verdict in the log says it, and any - later verdict takes it back. A time OUT or more ahead of `now` is a wrong clock and says nothing.""" - last, now = {}, now or time.time() +RESET = r"(?i)\b(?:resets?|try again|retry)" +STAMP = RESET + r"(?:\s+(?:at|on|after))?[\s:]+(\d{4}-\d\d-\d\d[T ]\d\d:\d\d(?::\d\d(?:\.\d+)?)?(?:Z|[+-]\d\d:?\d\d)?)" +UNIT = r"(\d+)\s*(days?|hours?|hrs?|minutes?|mins?|seconds?|secs?|d|h|m|s)(?![a-z])" +SPAN = RESET + r"\s+(?:in|after)\s+((?:%s[\s,]*(?:and\s+)?)+)" % UNIT +LONGEST = 35 * 86400 # no allowance window is longer than a month: a reset stated further off is misread + + +def stated(why, said): + """The time the provider's message says the limit resets, or None. A span counts from `said`, when it was recorded.""" + until = None + if m := re.search(STAMP, why): + try: until = datetime.datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp() + except ValueError: pass + elif m := re.search(SPAN, why): + until = said + sum(int(n) * {"d": 86400, "h": 3600, "m": 60, "s": 1}[u[0].lower()] for n, u in re.findall("(?i)" + UNIT, m.group(1))) + return until if until and said < until <= said + LONGEST else None + + +def outs(log, now=None, pool=None): + """{worker: (since, why, until)}: each worker that is or was last said to be out: an `out` verdict in the log says it + for the worker and every other on its plan (`pool`, from `pools`), until the reset its message states, else for OUT; + a later good or bad verdict takes that worker back. A time OUT or more ahead of `now` is a wrong clock and says nothing.""" + last, now, pool = {}, now or time.time(), pool or {} for o in log: try: t = time.mktime(time.strptime(o["ts"], "%Y-%m-%dT%H:%M:%S")) - t - now < OUT and last.__setitem__(short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), (t, o.get("verdict"), str(o.get("why") or ""))) + w, verdict, why = short(o["model"] if isinstance(o.get("model"), str) and o["model"] else o["worker"]), o.get("verdict"), str(o.get("why") or "") except (KeyError, TypeError, ValueError): - pass # a damaged line is no verdict - return {w: (t, why) for w, (t, verdict, why) in last.items() if verdict == "out"} + continue # a damaged line is no verdict + if t - now >= OUT: continue + if verdict != "out": + last.pop(w, None) + continue + until = stated(why, t) + for x in [w] + [x for x, p in pool.items() if x != w and p == pool.get(w)]: # a message with no reset shortens no stated one + last[x] = (t, why if x == w else "%s, on the same plan: %s" % (w, why), until or max(t + OUT, last[x][2] if x in last else 0)) + return last -def away(): return outs(store.records("outcomes.jsonl"), time.time()) +def pools(): + """{worker: provider}: the plan each worker draws on, as the models table and the wheel group them.""" + return {short(r[0]): pkey(r[7]) for r in rows(store.read(table()) + "\n" + wheel()[0]) if pkey(r[7])} + + +def away(): return outs(store.records("outcomes.jsonl"), time.time(), pools()) def out(r, skip, bad, gone, now): """Why this worker is off the wheel, "" when it is on: excluded, the maker of the work under review, or out.""" - since = gone.get(short(r[0])) + gone = gone.get(short(r[0])) return ("excluded" if short(r[0]) in skip else "same maker as the work under review" if maker(r) == bad - else SINCE % (clock(since[0]), clock(since[0] + OUT)) if since and now - since[0] < OUT else "") + else SINCE % (clock(gone[0]), clock(gone[2])) if gone and now < gone[2] else "") def median(v): @@ -362,7 +393,7 @@ def choose(text, cls, skip=(), review=None, rand=None, speed=None, gone=None, no 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), times its provider's share of plan left (`share`, from `shares`: at least FLOOR), so no plan runs dry early. - A worker last said out less than OUT seconds ago (`gone`, from `outs`) is not on the wheel.""" + A worker that is still out (`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)] @@ -385,6 +416,7 @@ def pick(args, cwd=None, rand=None): node = None if args[:1] == ["--node"]: # the class and branch come from the plan node from . import plan + if "--started" in args: return plan.attach(args, cwd) args, node = plan.for_pick(args, cwd) if node is None: return 1 cls, skip, review, limit, branch, i = (args[0] if args and args[0] in CLASSES else None), set(), None, None, None, 1 @@ -396,7 +428,8 @@ def pick(args, cwd=None, rand=None): else: cls = None i += 2 if not cls: - print("usage: sisi pick routine|ordinary|hard|deep [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]") + print("usage: sisi pick routine|ordinary|hard|deep [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] [--branch NAME]\n" + " sisi pick --node ID [--review-of WORKER] [--not WORKER ...] [--limit MINUTES] | sisi pick --node ID --started WORKER") return 1 text, why = wheel() if why: return print("sisi pick: %s: %s" % (why, "run `sisi models offered < FILE` and hand the printed `models offered` chore to any model the host offers." if why == "no offered model has a row" else REFRESH)) or 1 @@ -412,7 +445,7 @@ def pick(args, cwd=None, rand=None): 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.", "deep": " Choose again from hard."}.get(picked_cls, "") - first = min((gone[short(x[0])][0] + OUT for x in mine if out(x, skip, bad, gone, now).startswith("out since")), default=None) + first = min((gone[short(x[0])][2] for x in mine if out(x, skip, bad, gone, now).startswith("out since")), default=None) print(("sisi pick: every worker of class %s is out or excluded: %s." % (picked_cls, "; ".join( "%s (%s)" % (x[0], out(x, skip, bad, gone, now)) for x in mine)) if mine else "sisi pick: the models table has no worker of class %s." % picked_cls) @@ -512,6 +545,14 @@ def sync_late(s, cwd, sid, add=True): except OSError: pass +def named(name): + """The rows a worker's name means: those with that id, else those it names shortly. A worker's wheel row wins over its + table row (the list is the truth), and is counted once.""" + wrows = rows(wheel()[0]) + trows = wrows + [r for r in rows(store.read(table())) if short(r[0]) not in {short(x[0]) for x in wrows}] + return [r for r in trows if short(r[0]) == short(name)] or [r for r in trows if claim({"picked": [short(r[0])]}, name, True)] + + def judge(args, cwd=None): """`sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]`. Without --node/--chore a verdict closes the worker's oldest open job (--newest: its newest); with --node, the job that runs that @@ -533,9 +574,7 @@ def judge(args, cwd=None): or (node is not None and not re.fullmatch(r"[a-z0-9-]{1,30}", node)) or chore == "" or (node is not None and chore is not None): print('usage: sisi judge WORKER good|bad|out "" [--minutes N] [--newest] [--node ID | --chore ID] | extend MINUTES "" [--newest] [--node ID | --chore ID]') return 1 - wrows = rows(wheel()[0]) # a worker's wheel row wins over its table row (the list is the truth), and is counted once - trows = wrows + [r for r in rows(store.read(table())) if short(r[0]) not in {short(x[0]) for x in wrows}] - hits = [r for r in trows if short(r[0]) == short(args[0])] or [r for r in trows if claim({"picked": [short(r[0])]}, args[0], True)] + hits = named(args[0]) sid, ohits = store.current_session(cwd), [] if not hits and sid: try: st = json.loads(store.read(store._session_path(sid)) or "{}") @@ -616,8 +655,8 @@ def run(args, cwd=None): if text: print("\n(researched %d days ago)" % age_days()) 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)) + if sitting := sorted((t, w, u) for w, (t, _, u) in gone.items() if w in listed and now < u): + print("\nOff the wheel now:\n" + "\n".join("%s: %s" % (w, SINCE % (clock(t), clock(u))) for t, w, u in sitting)) if use := plan_use(text, cwd, now): print("\nPlan use by sisi's own delegations (an estimate; the plan's own usage page is exact):\n" + "\n".join( "%s: %s" % (p, ", ".join("%s %d%%" % (w, round(100 * x)) for w, x in u.items())) for p, u in sorted(use.items()))) diff --git a/sisi/plan.py b/sisi/plan.py index db644b4..a15b804 100644 --- a/sisi/plan.py +++ b/sisi/plan.py @@ -224,9 +224,8 @@ def run(args, cwd=None): why = why or check(nodes) or ("" if sid else "no session; run this from the agent's session") with store.session(sid) if sid else contextlib.nullcontext({}) as s: old, new = get(s) or {"nodes": [], "state": {}}, {n["id"]: n for n in nodes or []} - moved = [i for i, v in old["state"].items() if v.get("st") == "running" and (i not in new or ( - new[i]["branch"], new[i]["files"]) != (node(old, i)["branch"], node(old, i)["files"]))] - why = why or (moved and "node %s is running: keep its id, branch and files in the new plan, or judge it first" % moved[0]) + moved = [i for i, v in old["state"].items() if v.get("st") == "running" and (i not in new or new[i]["branch"] != node(old, i)["branch"])] + why = why or (moved and "node %s is running: keep its id and branch in the new plan, or judge it first" % moved[0]) if why: return print("sisi plan: %s. Nothing was recorded." % why) or 1 keep = {i for i, v in old["state"].items() if v.get("st") == "running" or node(old, i) == new.get(i)} @@ -277,6 +276,31 @@ def for_pick(args, cwd=None): return [n["cls"]] + args[2:] + ["--branch", n["branch"]], i +def attach(args, cwd=None): + """`sisi pick --node ID --started WORKER`: record that a job already running does this node (a worker continued with a + message, which no delegation hook sees). A pick made for the node is withdrawn; `sisi judge` closes it as any other.""" + from . import models + if len(args) != 4 or args[2] != "--started" or not args[3].strip(): + return print('usage: sisi pick --node ID --started ""') or 1 + if for_pick(args[:2], cwd)[1] is None: return 1 + hits = models.named(args[3]) + i, w = args[1], models.short(hits[0][0] if len(hits) == 1 else args[3]) + with store.session(store.current_session(cwd)) as s: + q = s["pending"] if isinstance(s.get("pending"), dict) else {} + for other, picks in q.items(): + for m in [m for m in picks if isinstance(m, dict) and m.get("node") == i]: + picks.remove(m) + other in s.get("picked", []) and s["picked"].remove(other) + s["pending"] = {**q, w: q.get(w, []) + [{"node": i, "branch": node(get(s), i)["branch"]}]} + s.setdefault("picked", []).insert(0, w) + models.claim(s, w, node=i) # from here on it is a delegation like one the hooks saw + s["delegations_since"] = s.get("delegations_since", 0) + 1 + s.pop("paused", None) + start(s, i, w, s["starts"][w][-1]) + print('node %s is running on %s. When it reports: `sisi judge %s good|bad|out "" --node %s`' % (i, w, w, i)) + return 0 + + def header(p, i): return "\n".join(["paste at the top of the brief (its first line):", "sisi node: " + i, "branch: %s (its own worktree and build folder)" % (n := node(p, i))["branch"], "may change: " + (", ".join(n["files"]) or "nothing"), "check: " + n["check"], diff --git a/tests/test_core.py b/tests/test_core.py index 33afcca..a6ae9ae 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -3,7 +3,7 @@ Learning: work is done, the retro is forced, its improvement is a rule in the next session, the rules are organized and the change can be undone. Delegation: the lead is stopped when it should be delegating, and the models table is researched, read and kept fresh.""" -import glob, hashlib, json, os, random, re, shlex, shutil, subprocess, sys, tempfile, time, unittest +import calendar, glob, hashlib, json, os, random, re, shlex, shutil, subprocess, sys, tempfile, time, unittest from unittest import mock REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -3038,6 +3038,45 @@ cli.main(["tick"]) first = time.mktime(time.strptime("2026-" + out.split("The first is back on the wheel at ")[1][:11], "%Y-%m-%d %H:%M")) self.assertLess(abs(first - (time.time() + 5 * 3600)), 120) + def test_a_stated_reset_time_keeps_the_whole_plan_off_the_wheel_until_then(self): + """Fault 37, with the providers' own messages.""" + row = "| %s | %s | host subagent model `%s` | %s | flat | work | |\n" + self.table("| worker | provider | how to call it | use for | cost | good at, bad at | notes |\n|---|---|---|---|---|---|---|\n" + "".join( + row % (w, p, w, c) for w, p, c in (("muse-wonder", "Muse Code", "ordinary"), ("muse-ember", "Muse Code", "routine"), + ("gemini-4-neon", "Antigravity", "ordinary"), ("gemini-4-hydrogen", "Antigravity", "routine"), + ("alpha", "Other", "routine")))) + sys.path.insert(0, REPO) + from sisi import models + stamp = lambda t: time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(t)) + utc = lambda s: calendar.timegm(time.strptime(s, "%Y-%m-%dT%H:%M:%S")) + said, reset = utc("2026-12-02T21:33:21"), utc("2026-12-07T00:00:00") + muse = "API error 429: Subscription quota exhausted. Your usage window resets at 2026-12-07T00:00:00Z." + pool = {"muse-wonder": "muse code", "muse-ember": "muse code", "alpha": "other"} + verdict = lambda why, t, w="muse-wonder", kind="out": {"ts": stamp(t), "worker": w, "verdict": kind, "why": why} + for log in ([verdict(muse, said)], [verdict(muse, said), verdict("connection lost again here", said + 60, "muse-ember")]): + gone = models.outs(log, reset - 60, pool) + self.assertEqual(sorted(gone), ["muse-ember", "muse-wonder"]) + self.assertEqual({w: g[2] for w, g in gone.items()}, dict.fromkeys(gone, reset)) # a later message with no time shortens nothing + gone = models.outs([verdict(muse, said)], reset - 60, pool) + off = lambda now: models.out(["muse-ember"] + [""] * 8, set(), None, gone, now) + self.assertEqual((off(reset - 60).startswith("out since"), off(reset)), (True, "")) + self.assertEqual(sorted(models.outs([verdict(muse, said), verdict("did it all well", said + 60, "muse-ember", "good")], said + 90, pool)), ["muse-wonder"]) + for why, wait in (("Individual quota reached. Resets in 108h11m37s.", 108 * 3600 + 11 * 60 + 37), ("limit hit, resets in 3 days", 3 * 86400), + ("Rate limited: try again in 45 minutes", 45 * 60), ("Resets in 4h 14m (shared account quota)", 4 * 3600 + 14 * 60), + (LIMIT, 6 * 3600), ("started 2026-12-30T00:00:00Z and hit a limit", 6 * 3600), + ("usage window resets at 2026-11-01T00:00:00Z", 6 * 3600), ("resets in 9000 days", 6 * 3600)): + self.assertEqual(models.outs([verdict(why, said)], said)["muse-wonder"][2] - said, wait, why) + # through the command: the model out and its sibling are both off, long after six hours + self.judged("gemini-4-neon", "out", "Individual quota reached. Resets in 108h11m37s.") + self.dated(108 * 60 + 10) + for cls, args in (("ordinary", ("--not", "muse-wonder")), ("routine", ("--not", "alpha", "--not", "muse-ember"))): + got, out = self.picked(cls, *args) + self.assertEqual((got, "(out since" in out), (False, True), out) + self.assertIn("gemini-4-hydrogen: out since", self.sisi("models")[1]) + self.assertEqual(self.picked("routine", "--not", "muse-ember", "--not", "gemini-4-hydrogen")[0], True) # another plan stays on + self.dated(108 * 60 + 12) + self.assertEqual(self.picked("routine", "--not", "alpha", "--not", "muse-ember")[0], True) + def test_pick_says_a_returning_worker_is_a_retry(self): self.table(ONE) self.judged("alpha", "out", LIMIT + ", please try later. " * 30) diff --git a/tests/test_models_research.py b/tests/test_models_research.py index a61a917..440d1ea 100644 --- a/tests/test_models_research.py +++ b/tests/test_models_research.py @@ -58,6 +58,10 @@ class ModelsResearch(unittest.TestCase): CLAUDE_CONFIG_DIR=os.path.join(self.tmp, "claude")) for name in ("SISI_SESSION_ID", "CLAUDE_ENV_FILE", "XDG_DATA_HOME", "XDG_STATE_HOME", "CODEX_HOME", "CLAUDE_CODE_ENTRYPOINT"): self.env.pop(name, None) + hide = mock.patch.dict(os.environ) # in-process calls read os.environ: the harness running this suite must not leak in + hide.start() + self.addCleanup(hide.stop) + os.environ.pop("CLAUDE_CODE_ENTRYPOINT", None) subprocess.run(["git", "init", "-q", self.data], check=True, capture_output=True, stdin=subprocess.DEVNULL) def in_process(self, fn, *args): diff --git a/tests/test_plan.py b/tests/test_plan.py index afaa31e..ac4b5d3 100644 --- a/tests/test_plan.py +++ b/tests/test_plan.py @@ -142,13 +142,39 @@ class Plan(unittest.TestCase): self.assertEqual(self.nodes(), {"a": "running"}) self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0) self.assertEqual(self.nodes(), {"a": "running"}) # a running node keeps its state by id - rc, out, _ = self.record(PLAN.replace("| sisi/a.py |", "| sisi/a2.py |")) - self.assertEqual(rc, 1, out) - self.assertIn("node a is running", out) - self.assertIn("a", self.nodes()) - rc, out, _ = self.record(PLAN.replace("| a | routine | - |", "| a2 | routine | - |").replace("| a, b |", "| a2, b |")) - self.assertEqual(rc, 1, out) - self.assertIn("node a is running", out) + self.assertEqual(self.record(PLAN.replace("| sisi/a.py |", "| sisi/a.py, sisi/a2.py |"))[0], 0) + self.assertEqual(self.nodes(), {"a": "running"}) # same id and branch: still running + for changed in (PLAN.replace("| p-a |", "| p-a2 |"), PLAN.replace("| a | routine | - |", "| a2 | routine | - |").replace("| a, b |", "| a2, b |")): + rc, out, _ = self.record(changed) + self.assertEqual(rc, 1, out) + self.assertIn("node a is running", out) + self.assertEqual(self.nodes(), {"a": "running"}) + + def test_a_job_already_running_is_attached_to_a_node_without_a_delegation(self): + """Fault 36: a node continued on an existing worker by a message stayed "ready and not started".""" + self.ready_plan() + self.assertEqual(self.sisi("plan", "--done", "b", "done by hand and tested", sid="s1")[0], 0) + attach = lambda node, worker: self.sisi("pick", "--node", node, "--started", worker, sid="s1") + rc, out, _ = attach("c", "gamma") + self.assertEqual((rc, "not ready" in out), (1, True), out) + self.assertIn("ready and not started", self.hook("gate")[1]) + self.pick("a") # the wheel said alpha, but the lead sent it to a running agent + rc, out, _ = attach("a", "gate-solver") + self.assertEqual(rc, 0, out) + self.assertEqual(self.nodes()["a"], "running") + self.assertEqual(self.state()["picked"], []) # the pick made for this node is withdrawn + self.assertNotIn("ready and not started", self.hook("gate")[1]) + rc, out, _ = attach("a", "gate-solver") + self.assertEqual((rc, "already running" in out), (1, True), out) + self.assertEqual(self.record(PLAN.replace("test a passes", "test a2 passes"))[0], 0) + self.assertEqual(self.nodes()["a"], "running") + rc, out, _ = self.sisi("judge", "gate-solver", "good", "did the node in one pass", "--node", "a", sid="s1") + self.assertEqual(rc, 0, out) + self.assertEqual(self.nodes()["a"], "done") + self.pick("c") # a table worker named shortly is stored as the table names it + self.assertEqual(attach("c", "GAMMA")[0], 0) + self.assertEqual((list(self.state()["starts"]).count("gamma"), self.state()["picked"]), (1, [])) + self.assertEqual(self.sisi("judge", "gamma", "good", "did the node in one pass", "--node", "c", sid="s1")[0], 0) def pick_header(self, node, sid="s1"): st = self.state(sid)