Routing: capable enough for the difficulty, proof before benchmark, nearest evidence, standing and accepted rate kept apart, input and output prices

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-23 14:31:30 -07:00
commit c547024e35
11 files changed
+1425 -163

No files matched your search

+6 -3
View File
@@ -27,9 +27,12 @@ present; nothing here names one. Read on demand: `sisi delegate guide`.
- Give each task to the least expensive worker that is sufficiently capable,
counting rework as cost: cheap work that must be redone is expensive.
- Evidence decides, in this order: the judged record for that kind of task and
difficulty; then price; then benchmark standing. A thin record is a reason
for care, not a verdict.
- Evidence decides which workers are capable enough, in this order: the judged
record for that kind and difficulty, the nearest judged record, then benchmark
standing against other workers' standing (never against an accepted rate). Above
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.
- 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.
+8
View File
@@ -10,5 +10,13 @@
},
"retro": {
"required": true
},
"route": {
"standing_floor": {
"1": 0,
"2": 60,
"3": 85
},
"price_blend_input_parts": 3
}
}
+4 -3
View File
@@ -284,9 +284,10 @@ worker).
restricts routing to matching models of one provider; both are honoured by `sisi route`.
`sisi workers down --until` accepts a date or a time, after which the worker is usable again.
- `sisi route --kind K --difficulty N [--explain]`: the recommendation. Candidates are only
workers with a judged record, a known price or a benchmark prior. With a thin record it
ranks by price and prior instead of arbitrarily, and about one low-stakes task in ten goes
to a cheaper worker with a thin record. `sisi workers avoid|prefer PATTERN --why` holds the
workers with a judged record, a known price or a benchmark standing. It picks the cheapest
worker that is capable enough for the kind and difficulty (judged record, then the nearest
judged evidence, then benchmark standing against other standings, see docs/workers.md), and
about one low-stakes task in ten goes to a cheaper worker with a thin record. `sisi workers avoid|prefer PATTERN --why` holds the
user's own constraints.
- `sisi delegate judge …` is the only way a result enters the ledger (type, difficulty, worker,
outcome, strongest check applied, minutes, tokens, retry-of). `amend` marks one that later
+30 -10
View File
@@ -13,9 +13,13 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano
record as three tables: by task type and difficulty (attempts, accepted, checked well, later
wrong, median minutes; thin rows marked), what fixed each rejection, and difficulty-guess
calibration.
- `sisi workers fact WORKER --price N|--score N --source S [--date D] [--plan flat|per-use]
[--maker M]` — record a price (per million tokens) or a benchmark standing (0–100), each with
its source and date, in the user store. A fact without a source is refused.
- `sisi workers fact WORKER --price-in N --price-out N | --price N | --standing N --source S
[--date D] [--plan flat|per-use] [--maker M]` — record a price as published (input and output,
per million tokens), one blended price for a source that publishes only that, or a benchmark
standing (0–100; `--score` is the old name), each with its source and date, in the user store.
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 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.
@@ -47,7 +51,7 @@ or learned from judged results. The strategy is [canon/orchestration.md](../cano
## How the choice is made
Candidates are only workers with a judged record, a known price or a benchmark prior; discovered
Candidates are only workers with a judged record, a known price or a benchmark standing; discovered
catalogue models with none of those are listed but never routed to. On a cold start nobody
qualifies: the pick is then a trial among usable workers, `--explain` says so, and asks for the
result to be judged and facts recorded.
@@ -55,12 +59,28 @@ result to be judged and facts recorded.
In order: a tier that trains on prompts is never chosen; unavailable and allowance-spent workers
are skipped and named; `avoid` patterns remove a worker unless that leaves nobody; a reviewer
comes from a different maker than the author (a stored `maker` fact, else derived from the model
id). Proven workers (enough attempts at or above the accepted-rate bar, not later found wrong)
come first above difficulty 1; proven-bad workers are passed over. Cheapest first within that:
flat-rate allowance before per-use prices, unknown prices last, the benchmark prior ordering a
thin record at equal price, `prefer` patterns first, then load balancing across allowances.
About one difficulty-1 task in ten goes to a cheaper thin-record worker instead, so cheaper
options gather evidence. The choice is deterministic for one fixed record.
id). Then the cheapest worker that is capable enough for the kind and difficulty, judged by the
best evidence about each worker, in this order: (a) its judged record for that kind and
difficulty (enough attempts at or above the accepted-rate bar, not later found wrong); (b) the
nearest judged evidence: the same kind at a harder difficulty proves an easier one, then all
kinds at that difficulty or a harder one (the same kind at an easier difficulty is weak evidence,
used only when no usable worker is capable otherwise); (c) benchmark standing as a prior, compared
only with other workers' standing: at least 85 percent of the best usable standing for difficulty
3, 60 percent for difficulty 2, no floor for difficulty 1 (`route.standing_floor` in the config);
(d) nothing known: difficulty 1 only, as an exploration. Above difficulty 1 a benchmark is a reason
to try a worker, not to prefer it to proof: when any usable worker is capable by a judged record for
the kind (a, or b from a harder difficulty of the kind), only those compete; the record across all
kinds counts as proof only when nobody has evidence from the kind; standing decides only when nobody
has a judged record for the request. A thick bad record at this or an easier
difficulty, or a thin one with repeated rejections, keeps a worker off its benchmark. The two
scales never meet: a standing is never compared with an accepted rate. Cheapest first among the
competing workers: flat-rate allowance before per-use prices (blended input and output), unknown prices
last, then standing, `prefer` patterns first, then load balancing across allowances. When no
worker is capable by the evidence, the strongest known usable worker is recommended and `--explain`
says that none is proven. About one difficulty-1 task in ten goes to a cheaper thin-record worker
instead, so cheaper options gather evidence. The choice is deterministic for one fixed record.
`--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.
## Costs and failures
+1 -1
View File
@@ -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)',
'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 "<claim>" 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 "<work>" 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|--score 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 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',
+441 -80
View File
@@ -1,8 +1,14 @@
"""Choosing a worker: pure arithmetic over the delegation record. No model call, no file access.
A candidate is a plain dict: worker (canonical id), tool, model, maker, plan ("flat", "per-use" or
None), cost (a comparable per-use price or None), allowance_pct_left (0..100 or None), usable,
reason (why not usable), and aliases (every spelling the record may use for this worker).
None), cost (a comparable blended per-million-token price or None), allowance_pct_left (0..100 or
None), usable, reason (why not usable), standing (a published benchmark's figure or None, with
standing_source and standing_date), and aliases (every spelling the record may use for this worker).
Two scales are kept apart. A benchmark standing is a figure from outside; an accepted rate is what
this organization measured by judging delegations. They are never compared with each other: a
standing is compared only with other workers' standings, a rate only with the bar and with other
rates. Judged evidence outranks the benchmark wherever both exist.
The rule, in order:
1. Never a model whose id contains "contributor" (those tiers train on prompts).
@@ -11,36 +17,51 @@ The rule, in order:
that would leave nobody.
3. For a review, never the author's maker while another maker is available. A stored `maker`
fact wins; otherwise the maker is derived from the model id (see maker_of).
4. Among the rest, a worker is proven for a kind and difficulty with MIN_ATTEMPTS judged attempts
and an accepted rate of at least MIN_ACCEPTED_RATE (accepted and not later found wrong). Above
difficulty 1, proven workers are preferred; at difficulty 1, workers with a thin record stay in
the pool so they gather attempts on low-stakes work. A worker proven bad (enough attempts, rate
below the bar) is passed over whenever anything else remains.
5. Cheapest first: a flat-rate plan with allowance left costs nothing more per task, so it comes
before anything billed per use; per-use workers order by their known price; an unknown price is
treated as the most expensive until learned. A stored benchmark prior (`prior_score`) ranks
within the same price, so a thin record is ordered by price and prior, never arbitrarily.
A user's `prefer` patterns put a worker first within the eligible pool.
4. Capable enough. For a kind and difficulty each remaining worker is judged by the best
evidence about it, in this order (see `assess`):
a. its judged record for that kind and difficulty: MIN_ATTEMPTS judged attempts and an
accepted rate of at least MIN_ACCEPTED_RATE (accepted and not later found wrong);
b. the nearest judged evidence: the same kind at a harder difficulty proves an easier one;
then all kinds at that difficulty (or a harder one). The same kind at an easier
difficulty is only weak evidence, used when no usable worker is capable otherwise;
c. benchmark standing as a prior, against other workers' standing only: at least a share of
the best standing among the usable workers (`standing_floor`: 85 percent at difficulty 3,
60 percent at difficulty 2, none at difficulty 1);
d. nothing known: capable for difficulty 1 only, as an exploration.
A worker with a thick bad record (MIN_ATTEMPTS attempts, rate under the bar) for the kind at
this or an easier difficulty is never capable, so never rides on a benchmark. A thin record
that already shows repeated rejections also cancels the benchmark prior.
5. Above difficulty 1 a benchmark is a reason to try a worker, not to prefer it to proof: when any
usable worker is capable by a judged record for the kind (evidence a, or b from a harder
difficulty of the kind), only those compete; the record across all kinds counts as proof only
when no usable worker has evidence from the kind; benchmark standing decides only when nobody
has a judged record for the request. At difficulty 1 every capable worker competes.
Among those the cheapest wins: a flat-rate plan with allowance left first
(it costs nothing more per task), then the blended price (an unknown price counts as most
expensive), then the benchmark standing, then load. A user's `prefer` patterns come first.
If no worker is capable, the weak evidence decides; failing that, the strongest known usable
worker is recommended and the explanation says plainly that none is proven for this.
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
for one fixed record.
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
relative to its remaining allowance goes first (recorded uses divided by allowance left, an
unknown allowance counting as half). Because every delegation is recorded, the choice rotates
as work is done, yet stays deterministic for one fixed record. Ties break on the worker id.
unknown allowance counting as half). Ties break on the worker id.
Candidates reach here already restricted to workers with a judged record, a known price or a
benchmark prior (see workers.routable_candidates); on a cold start none qualifies and every usable
worker is offered, with the explanation saying so.
benchmark standing (see workers.routable_candidates); on a cold start none qualifies and every
usable worker is offered, with the explanation saying so.
"""
import re
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
UNKNOWN_ALLOWANCE = 50.0 # allowance weight when a tool reports none
STRONG_BAND = 10.0 # strength points from the best still counts as among the strongest
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_PRICE_BLEND = 3.0 # parts of input price to one part of output price in a blended price
def maker_of(name):
@@ -53,6 +74,44 @@ def maker_of(name):
return re.split(r"[-_:. ]", model)[0] or model
def blended_price(price_in, price_out, ratio=DEFAULT_PRICE_BLEND):
"""One comparable per-million-token price from a published input and output price: `ratio` parts
of input to one part of output. None when either is missing."""
if not isinstance(price_in, (int, float)) or not isinstance(price_out, (int, float)):
return None
try:
ratio = float(ratio)
except (TypeError, ValueError):
ratio = DEFAULT_PRICE_BLEND
if ratio < 0:
ratio = DEFAULT_PRICE_BLEND
return (float(price_in) * ratio + float(price_out)) / (ratio + 1.0)
def standing_floors(configured=None):
"""{difficulty: percent of the best usable standing needed}, the defaults overridden by whatever
valid entries the configured mapping has (keys 1..3, values 0..100)."""
table = dict(DEFAULT_STANDING_FLOOR)
if isinstance(configured, dict):
for k, v in configured.items():
try:
d, pct = int(k), float(v)
except (TypeError, ValueError):
continue
if d >= 1 and 0 <= pct <= 100:
table[d] = pct
return table
def _floor_pct(floors, difficulty):
table = standing_floors(floors)
if difficulty in table:
return table[difficulty]
if difficulty is None or difficulty < min(table):
return 0.0
return table[max(table)]
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."""
@@ -129,12 +188,133 @@ def _cell(stats, worker, kind, difficulty):
return stats.get(worker, {}).get("by_cell", {}).get((kind, difficulty), {"n": 0, "good": 0})
def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(),
avoid=None, prefer=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."""
now = float(now or 0)
# ---------------------------------------------------------------- capability evidence
_TIER_RANK = {"a": 0, "b-higher": 1, "b-all": 2} # smaller is closer to the request
_NO_CELL = {"n": 0, "good": 0}
def _thick(cell):
return cell["n"] >= MIN_ATTEMPTS
def _rate(cell):
return cell["good"] / cell["n"] if cell["n"] else None
def _proven(cell):
return _thick(cell) and _rate(cell) >= MIN_ACCEPTED_RATE
def _poor(cell):
return _thick(cell) and _rate(cell) < MIN_ACCEPTED_RATE
def _contradicts(cell):
"""A thin record that already shows repeated rejections below the bar."""
return (not _thick(cell) and cell["n"] - cell["good"] >= CONTRADICTION_REJECTIONS
and _rate(cell) < MIN_ACCEPTED_RATE)
def _by_difficulty(stats, worker, kind):
"""({difficulty: cell} for this kind, {difficulty: cell} pooled over every kind), whole numbers only."""
own, pooled = {}, {}
for (k, d), cell in stats.get(worker, {}).get("by_cell", {}).items():
if not isinstance(d, int) or isinstance(d, bool):
continue
if k == kind:
own[d] = cell
p = pooled.setdefault(d, {"n": 0, "good": 0})
p["n"] += cell["n"]
p["good"] += cell["good"]
return own, pooled
def assess(stats, worker, kind, difficulty, standing=None, best_standing=None, floors=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
bad a thick bad record for this kind at this or an easier difficulty: never capable
weak a proven record for this kind at an easier difficulty (weak evidence, last resort)
contradicted a thin record for this kind that already shows repeated rejections
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."""
d = difficulty
own, pooled = _by_difficulty(stats, worker, kind)
out = {"tier": "none", "capable": False, "bad": False, "weak": False, "contradicted": False,
"level": 0, "standing": standing, "measure": None}
easier = sorted(k for k in own if isinstance(d, int) and k <= d)
out["bad"] = any(_poor(own[k]) for k in easier)
if out["bad"]:
k = next(k for k in easier if _poor(own[k]))
out.update(level=-1, at=k, n=own[k]["n"], good=own[k]["good"], measure=_rate(own[k]))
return out
out["contradicted"] = any(_contradicts(own[k]) for k in easier)
easier_proven = [k for k in easier if k < d and _proven(own[k])]
out["weak"] = bool(easier_proven)
if easier_proven:
k = max(easier_proven)
out.update(weak_at=k, weak_n=own[k]["n"], weak_good=own[k]["good"], weak_rate=_rate(own[k]))
proof = None
if isinstance(d, int):
exact = own.get(d, _NO_CELL)
if _proven(exact):
proof = ("a", d, exact)
else:
higher = sorted(k for k in own if k > d and _proven(own[k]))
if higher:
proof = ("b-higher", higher[0], own[higher[0]])
else:
wide = sorted(k for k in pooled if k >= d and _proven(pooled[k]))
if wide:
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))
return out
if standing is not None:
pct = _floor_pct(floors, d)
needed = (best_standing or 0.0) * pct / 100.0
capable = standing >= needed - 1e-9
out.update(floor=pct, needed=needed, best=best_standing, below=not capable)
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 d == 1 and not out["contradicted"]:
out.update(tier="unknown", capable=True, level=0)
return out
if out["weak"]:
out["level"] = 1
return out
def strength(a):
"""How strong the evidence about a worker is, as a tuple that orders workers from weakest to
strongest. Kinds of evidence are ordered first (judged proof, then benchmark, then weak, then
nothing); only inside one kind are figures compared, so a standing never meets a rate."""
if a["bad"]:
return (-1, 0, 0.0)
if a["tier"] in _TIER_RANK:
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["weak"]:
return (2, 0, a["weak_rate"])
return (1, 0, 0.0)
def _standing_of(c):
s = c.get("standing")
return float(s) if isinstance(s, (int, float)) and not isinstance(s, bool) else None
# ---------------------------------------------------------------- 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)."""
exclude = {str(x) for x in exclude}
stats = candidate_stats(candidates, records)
passed = []
@@ -186,39 +366,22 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None,
else:
rest.append(c)
eligible = rest
return eligible, passed, stats, author_maker
def _assess_all(eligible, stats, kind, difficulty, floors):
"""({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)
for c in eligible}, best)
def _make_key(stats, kind, difficulty, prefer):
def rate(c):
cell = _cell(stats, c["worker"], kind, difficulty)
return (cell["good"] / cell["n"]) if cell["n"] else None
def proven_good(c):
cell = _cell(stats, c["worker"], kind, difficulty)
return cell["n"] >= MIN_ATTEMPTS and rate(c) is not None and rate(c) >= MIN_ACCEPTED_RATE
def proven_bad(c):
cell = _cell(stats, c["worker"], kind, difficulty)
return cell["n"] >= MIN_ATTEMPTS and rate(c) is not None and rate(c) < MIN_ACCEPTED_RATE
pool = list(eligible)
if difficulty and difficulty > 1:
good = [c for c in eligible if proven_good(c)]
if good:
for c in eligible:
if c not in good:
cell = _cell(stats, c["worker"], kind, difficulty)
passed.append((c["worker"],
"record too thin for this difficulty (%d of %d attempts) while a proven worker is available"
% (cell["n"], MIN_ATTEMPTS) if cell["n"] < MIN_ATTEMPTS
else "accepted rate below the bar for this kind and difficulty"))
pool = good
if pool:
bad = [c for c in pool if proven_bad(c)]
if bad and len(bad) < len(pool):
for c in bad:
passed.append((c["worker"], "accepted rate below the bar over %d attempts"
% _cell(stats, c["worker"], kind, difficulty)["n"]))
pool = [c for c in pool if c not in bad]
def load_ratio(c):
left = c.get("allowance_pct_left")
if left is None and c.get("host_native"):
@@ -226,40 +389,104 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None,
weight = float(left) if left else UNKNOWN_ALLOWANCE
return stats.get(c["worker"], {}).get("uses", 0) / max(weight, 1.0)
def prior_key(c):
score = c.get("prior_score")
return -float(score) if isinstance(score, (int, float)) else 1.0
def standing_key(c):
s = _standing_of(c)
return -s if s is not None else 1.0
def key(c):
r = rate(c)
return (0 if _pattern_match(c, prefer) else 1,
_price_tier(c),
float(c["cost"]) if c.get("cost") is not None else float("inf"),
prior_key(c),
standing_key(c),
load_ratio(c),
-(r if r is not None else -1.0),
c["worker"])
return key, rate, load_ratio
def _prefer_judged(capable, assessments, difficulty):
"""(workers, judged): above difficulty 1 a benchmark standing is a reason to try a worker on low-stakes
work, not to prefer it to measured proof. When any capable worker is capable by a judged record for
this kind (evidence a, or b from a harder difficulty of the kind), only those compete; failing that,
those capable by the judged record across all kinds; failing that, everyone capable."""
if difficulty is None or difficulty < 2:
return list(capable), False
for tiers in (("a", "b-higher"), ("b-all",)):
own = [c for c in capable if assessments[c["worker"]]["tier"] in tiers]
if own:
return own, True
return list(capable), False
def _select(eligible, assessments, difficulty):
"""(pool, basis): the workers to rank by price, and what put them there.
basis is "capable" (see _prefer_judged), "weak" (nobody capable; judged evidence at an easier difficulty),
"strongest" (nobody capable; the strongest known by evidence), "nothing" (nobody has any
evidence) or "all-bad" (every usable worker has a thick bad record)."""
live = [c for c in eligible if not assessments[c["worker"]]["bad"]]
if not live:
return list(eligible), "all-bad"
capable = [c for c in live if assessments[c["worker"]]["capable"]]
if capable:
return _prefer_judged(capable, assessments, difficulty)[0], "capable"
weak = [c for c in live if assessments[c["worker"]]["weak"]]
if weak:
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")
def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(),
avoid=None, prefer=None, floors=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)
assessments, best = _assess_all(eligible, stats, kind, difficulty, floors)
key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer)
pool, basis = _select(eligible, assessments, difficulty) if eligible else ([], "none")
detail = {}
ranked = sorted(pool, key=key)
def price_of(c):
return (_price_tier(c), float(c["cost"]) if c.get("cost") is not None else float("inf"))
pool.sort(key=key)
choice = pool[0] if pool else None
if basis == "all-bad":
ranked = sorted(pool, key=lambda c: (-(assessments[c["worker"]].get("measure") or 0.0), key(c)))
choice = ranked[0] if ranked else None
explored = None
if (choice is not None and difficulty == 1 and not _pattern_match(choice, prefer)
if (choice is not None and difficulty == 1 and basis == "capable" and not _pattern_match(choice, prefer)
and _cell(stats, choice["worker"], kind, difficulty)["n"] >= MIN_ATTEMPTS):
total = sum(_cell(stats, c["worker"], kind, difficulty)["n"] for c in candidates)
if total >= EXPLORE_EVERY - 1 and total % EXPLORE_EVERY == EXPLORE_EVERY - 1:
thinner = [c for c in pool
thinner = [c for c in ranked
if c is not choice
and _cell(stats, c["worker"], kind, difficulty)["n"] < MIN_ATTEMPTS
and price_of(c) <= price_of(choice)]
if thinner:
thinner.sort(key=key)
explored, choice = choice, thinner[0]
pool = [choice] + [c for c in pool if c is not choice]
ranked = [choice] + [c for c in ranked if c is not choice]
in_pool = {c["worker"] for c in ranked}
if choice is not None:
for c in pool[1:]:
cheaper_than = price_of(choice)
for c in eligible:
if c is choice:
continue
a = assessments[c["worker"]]
w = c["worker"]
if w not in in_pool:
reason, extra = _why_not(a, difficulty, basis, cheaper=price_of(c) < cheaper_than)
passed.append((w, reason))
if extra:
detail[w] = extra
continue
if explored is not None and c is explored:
reason = ("the usual choice, passed over this once so a cheaper thin-record worker "
"gathers evidence on low-stakes work (about one task in %d)" % EXPLORE_EVERY)
@@ -276,45 +503,178 @@ 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 came first in worker-id order")
passed.append((c["worker"], reason))
passed.append((w, reason))
judged_first = basis == "capable" and _prefer_judged(pool, assessments, difficulty)[1]
capable_n = len(pool) if basis == "capable" else 0
return {"choice": choice, "passed_over": passed, "stats": stats, "author_maker": author_maker,
"explored": explored["worker"] if explored else None,
"load_ratios": {c["worker"]: load_ratio(c) for c in candidates}}
"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,
"kind": kind, "difficulty": difficulty}
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."""
lead = "cheaper than the choice but " if cheaper else ""
if a["bad"]:
where = "" if a.get("at") == difficulty else " (at an easier difficulty, which counts against a harder one)"
return ("%saccepted rate below the bar over %d attempts%s" % ("cheaper but " if cheaper else "", a["n"], where),
"%d of %d accepted" % (a["good"], a["n"]))
if basis == "capable":
if a["capable"]:
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",
("standing %g" % a["standing"]) if a["standing"] is not None else 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"]),
"standing %g" % a["standing"])
if a["contradicted"]:
return (lead + "not capable enough: its own thin record for this kind repeats rejections, which "
"cancels its benchmark standing", None)
if a["weak"]:
return (lead + "not capable enough for difficulty %d: its only judged proof is at an easier "
"difficulty, and a worker with better evidence is usable" % difficulty, None)
return (lead + "not capable enough for difficulty %d: nothing is recorded about it that proves it; "
"unknown workers are tried on difficulty 1 only" % difficulty, None)
if basis == "weak":
return (lead + "less evidence: no worker is capable by the evidence, so the one with judged proof at an "
"easier difficulty was taken", None)
return (lead + "weaker known evidence than the strongest known usable worker",
("standing %g" % a["standing"]) if a["standing"] is not None else None)
# ---------------------------------------------------------------- the retry ladder
def retry_choice(candidates, records, availability, kind, difficulty, rejected, rejections,
now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=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,
the strongest known usable worker other than it (and only the rejected one itself when nobody
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)
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,
"assessments": assessments, "best_standing": best, "kind": kind, "difficulty": difficulty,
"rejected": rejected, "rejections": rejections}
mine = next((c for c in eligible if c["worker"] == rejected), None)
if int(rejections or 0) <= 1 and mine is not None and not assessments[rejected]["bad"]:
out.update(choice=mine, step="same")
return out
others = [c for c in eligible if c["worker"] != rejected and not assessments[c["worker"]]["bad"]]
if not others:
if mine is not None:
out.update(choice=mine, step="only")
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)))
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:
out.update(choice=sorted(better, key=key)[0], step="better")
return out
top = max(strength(assessments[c["worker"]]) for c in others)
out.update(choice=sorted([c for c in others if strength(assessments[c["worker"]]) == top], key=key)[0],
step="strongest")
return out
# ---------------------------------------------------------------- the explanation
MAX_EXPLAIN_LINES = 20
EXPLAIN_TAIL_LINES = 5 # worker, mechanism, exclusion note, cold-start notice, request for facts
def _pct(x):
return "%d%%" % round(100.0 * x)
def _short(text, width=60):
text = str(text or "no source stated")
return text if len(text) <= width else text[:width - 3].rstrip() + "..."
def evidence_line(a, kind, difficulty, choice, basis):
"""One line saying which evidence decided that the chosen worker is capable, with the numbers."""
if a is None:
return "evidence: none recorded"
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))
tier = a["tier"]
if tier == "a":
return ("evidence (a), judged record: %d of %d accepted for %s at difficulty %d (%s, bar %s)"
% (a["good"], a["n"], kind, difficulty, _pct(a["measure"]), _pct(MIN_ACCEPTED_RATE)))
if tier == "b-higher":
return ("evidence (b), judged record at a harder difficulty: %d of %d accepted for %s at difficulty %d "
"(%s), which proves difficulty %d" % (a["good"], a["n"], kind, a["at"], _pct(a["measure"]), difficulty))
if tier == "b-all":
return ("evidence (b), judged record across all kinds at difficulty %d: %d of %d accepted (%s)"
% (a["at"], a["good"], a["n"], _pct(a["measure"])))
if tier == "standing":
src = _short(choice.get("standing_source"))
if a["capable"]:
if a["floor"]:
need = "above the %g needed (%g%% of the best usable standing, %g)" % (a["needed"], a["floor"], a["best"])
else:
need = "no floor at difficulty %d" % difficulty
return ("evidence (c), benchmark standing: %g (%s, %s), %s; no judged record for this decides it"
% (a["standing"], src, choice.get("standing_date") or "no date stated", need))
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 == "unknown":
return "evidence (d): nothing is known about this worker yet; it is an exploration on low-stakes work"
if a.get("weak"):
return ("evidence (b, weak): %d of %d accepted for %s at the easier difficulty %d; no worker has better evidence"
% (a["weak_good"], a["weak_n"], kind, a["weak_at"]))
return "evidence: nothing is recorded about any usable worker for %s at difficulty %d" % (kind, difficulty)
def explain_choice(result, kind, difficulty):
"""Plain lines for `--explain`, from a choose() result."""
choice = result["choice"]
lines = []
basis = result.get("basis")
if choice is None:
lines.append("no usable worker for kind %s at difficulty %s" % (kind, difficulty))
else:
cell = _cell(result["stats"], choice["worker"], kind, difficulty)
a = (result.get("assessments") or {}).get(choice["worker"])
if choice.get("plan") == "flat":
price = "a flat-rate plan with allowance left, so one more task costs nothing extra"
elif choice.get("cost") is not None:
price = "the cheapest known per-use price among the workers that are good enough"
price = "the cheapest known per-use price among the workers that are capable enough"
elif choice.get("plan") == "per-use":
price = "billed per use; no cheaper flat-rate worker is usable"
else:
price = "price unknown, treated as most expensive until learned; nothing priced cheaper is usable"
if cell["n"] >= MIN_ATTEMPTS:
record = "%d judged attempts for this kind and difficulty, %d accepted" % (cell["n"], cell["good"])
elif cell["n"]:
record = "a thin record (%d of %d attempts for this kind and difficulty)" % (cell["n"], MIN_ATTEMPTS)
price = "price unknown, treated as most expensive until learned; nothing priced cheaper is capable"
if basis in (None, "capable"):
head = "chose %s: %s" % (choice["worker"], price)
if result.get("capable_count"):
head += "; %d usable worker(s) capable %s" % (
result["capable_count"], "by a judged record" if result.get("judged_first") else "enough")
else:
record = "no judged attempts yet for this kind and difficulty"
lines.append("chose %s: %s; %s; load so far is %s recorded use(s) against the allowance it has left, "
"the lowest in its price tier, so work spreads instead of draining one plan"
% (choice["worker"], price, record, result["stats"].get(choice["worker"], {}).get("uses", 0)))
if isinstance(choice.get("prior_score"), (int, float)) and cell["n"] < MIN_ATTEMPTS:
lines.append("its benchmark prior is %g (%s, %s); with a thin record, price and prior decide the order"
% (float(choice["prior_score"]), choice.get("prior_source") or "no source stated",
choice.get("prior_date") or "no date stated"))
head = "chose %s: none is proven capable for %s at difficulty %s" % (choice["worker"], kind, difficulty)
head += ("; taken for the strongest known evidence (%s)" % price if basis == "strongest" else
"; %s" % ("every usable worker has a poor record" if basis == "all-bad" else
"nothing is recorded about any usable worker, so this is a trial" if basis == "nothing" else
"taken for the judged proof at an easier difficulty (%s)" % price))
lines.append(head)
if a is not None:
lines.append(evidence_line(a, kind, difficulty, choice, basis))
if result.get("explored"):
lines.append("this is an exploration pick: %s was the usual choice, passed over once so a cheaper "
"thin-record worker gathers evidence" % result["explored"])
@@ -325,6 +685,7 @@ def explain_choice(result, kind, difficulty):
else:
lines.append("no worker from a different maker than the author (%s) is available, "
"so the review stays with the same maker" % result["author_maker"])
detail = result.get("passed_detail") or {}
groups, order = {}, []
for worker, reason in result["passed_over"]:
if reason not in groups:
@@ -336,7 +697,7 @@ def explain_choice(result, kind, difficulty):
# smallest groups share one closing line that still names each reason and its count.
def group_line(reason):
names = groups[reason]
shown = ", ".join(names[:3])
shown = ", ".join(("%s [%s]" % (n, detail[n])) if n in detail else n for n in names[:3])
more = " and %d more" % (len(names) - 3) if len(names) > 3 else ""
return "passed over %d worker(s) (%s%s): %s" % (len(names), shown, more, reason)
+172 -62
View File
@@ -13,11 +13,14 @@ Personal files (all in the personal data folder):
`sisi delegate judge` is the only way a result enters it.
worker-availability.json unavailability (limit, login, missing, error) with retry times
worker-prices.json worker facts (prices): {"models": {"<model or worker>":
{"plan": "flat"|"per-use", "cost_per_million_tokens": number,
{"plan": "flat"|"per-use", "price_in": number, "price_out": number (as
published; ranked by a blend, `route.price_blend_input_parts` input to one
output) or "cost_per_million_tokens": one blended figure,
"maker": name, "source": text, "date": "YYYY-MM-DD"}},
"tools": {"<tool>": same shape}}, written by `sisi workers fact`
model-strength.json worker facts (benchmark standing): {"models": {"<model or worker>":
{"score": 0..100, "source": text, "date": "YYYY-MM-DD"}}}
model-strength.json worker facts (benchmark standing, a published figure; never the measured
accepted rate): {"models": {"<model or worker>":
{"standing": 0..100, "source": text, "date": "YYYY-MM-DD"}}}
worker-prefs.json the user's own routing constraints: {"avoid": [{"pattern", "why"}],
"prefer": [...], "only": [{"provider", "patterns", "why"}]}, written by
`sisi workers avoid|prefer|only`
@@ -501,12 +504,75 @@ def load_prices():
return read_json(prices_path())
def standing_of(entry):
"""The benchmark standing in a stored fact, or None. Facts recorded before standing had its own
name carry it as "score": read the same way, with their source and date."""
if not isinstance(entry, dict):
return None
for field in ("standing", "score"):
v = entry.get(field)
if isinstance(v, (int, float)) and not isinstance(v, bool):
return float(v)
return None
def load_strength_prior():
d = read_json(strength_path())
models = d.get("models")
return models if isinstance(models, dict) else {}
def migrate_standing_facts():
"""Facts recorded before standing had its own name store it as "score". Rename each to "standing",
keeping its source, date and maker. Returns how many moved; repeating it moves none."""
path = strength_path()
data = read_json(path)
models = data.get("models")
if not isinstance(models, dict):
return 0
moved = 0
for key, entry in list(models.items()):
if isinstance(entry, dict) and "score" in entry:
rest = {k: v for k, v in entry.items() if k not in ("score", "standing")}
models[key] = dict({"standing": entry["standing"] if "standing" in entry else entry["score"]}, **rest)
moved += 1
if moved:
try:
write_json(path, data)
except OSError:
return 0
return moved
def route_cfg():
cfg = store.config().get("route")
return cfg if isinstance(cfg, dict) else {}
def price_blend():
"""Parts of input price to one part of output price in the blended price used for ranking and
cost estimates: `route.price_blend_input_parts`, default 3."""
v = route_cfg().get("price_blend_input_parts")
return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) and v >= 0 else routing.DEFAULT_PRICE_BLEND
def entry_cost(entry):
"""One per-million-token price from a stored price fact, or None: an input and output price pair is
blended at the configured ratio, a single figure is taken as the blended figure it was recorded as."""
if not isinstance(entry, dict):
return None
blended = routing.blended_price(entry.get("price_in"), entry.get("price_out"), price_blend())
if blended is not None:
return blended
single = entry.get("cost_per_million_tokens", entry.get("cost"))
return float(single) if isinstance(single, (int, float)) and not isinstance(single, bool) else None
def route_floors():
"""{difficulty: percent of the best usable standing needed} from `route.standing_floor`."""
return routing.standing_floors(route_cfg().get("standing_floor"))
def _price_for(prices, tool, model, worker):
models = prices.get("models") if isinstance(prices.get("models"), dict) else {}
tools = prices.get("tools") if isinstance(prices.get("tools"), dict) else {}
@@ -558,18 +624,18 @@ def build_candidates(disc=None, records=None):
return None
seen.add(worker.lower())
price = _price_for(prices, tool, model, worker)
cost = price.get("cost_per_million_tokens", price.get("cost"))
cost = entry_cost(price)
prior_entry = next((prior[k] for k in (worker, model)
if k and isinstance(prior.get(k), dict)), {})
score = prior_entry.get("score")
standing = standing_of(prior_entry)
c = {"worker": worker, "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": float(cost) if isinstance(cost, (int, float)) else None,
"cost": cost,
"allowance_pct_left": allowance, "usable": usable, "reason": reason,
"price_source": price.get("source"), "price_date": price.get("date"),
"prior_score": float(score) if isinstance(score, (int, float)) else None,
"prior_source": prior_entry.get("source"), "prior_date": prior_entry.get("date"),
"standing": standing,
"standing_source": prior_entry.get("source"), "standing_date": prior_entry.get("date"),
"aliases": [worker, model, ("%s/%s" % (tool, model)) if tool and model else None,
tool if model is None else None]}
c["aliases"] = [a for a in c["aliases"] if a]
@@ -801,7 +867,7 @@ 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 --score N --source S`. Until then routing "
"and `sisi workers fact WORKER --standing N --source S`. Until then routing "
"goes by the judged record alone." % what)
@@ -809,10 +875,10 @@ def estimate_cost(tokens, price_entry):
"""Estimated cost from a known per-million-token price, or None. The caller labels it estimated."""
if not isinstance(tokens, (int, float)) or not isinstance(price_entry, dict):
return None
per_million = price_entry.get("cost_per_million_tokens", price_entry.get("cost"))
if not isinstance(per_million, (int, float)):
per_million = entry_cost(price_entry)
if per_million is None:
return None
return float(tokens) / 1000000.0 * float(per_million)
return float(tokens) / 1000000.0 * per_million
def routable_candidates(candidates, records):
@@ -825,7 +891,7 @@ def routable_candidates(candidates, records):
keep = []
for c in candidates:
judged = sum(cell["n"] for cell in stats.get(c["worker"], {}).get("by_cell", {}).values())
if judged or c.get("price_source") or c.get("prior_score") is not None:
if judged or c.get("price_source") or c.get("standing") is not None:
keep.append(c)
if not keep:
return list(candidates), True, 0
@@ -883,7 +949,7 @@ def digest_lines(records=None, days=None, now=None):
% (days, len(attempts), routing.MIN_ATTEMPTS)]
if not attempts:
lines.append(" No judged delegations yet. Judge each result with `sisi delegate judge`; "
"until then routing goes on price and benchmark prior alone.")
"until then routing goes on price and benchmark standing alone.")
return lines
cells = {}
for a in attempts:
@@ -901,10 +967,10 @@ def digest_lines(records=None, days=None, now=None):
rows = rows[:MAX_DIGEST_ROWS]
rows.sort(key=lambda r: (str(r["type"]), r["diff"] or 0, -(r["ok"] / r["n"] if r["n"] else 0), -r["n"]))
lines += ["", "Workers by task", "",
"Accepted counts results that passed the check and were not reported wrong later. "
"Accepted rate counts results that passed the check and were not reported wrong later. "
"Checked well is the share of those verified by tests, a read, or a second reviewer; "
"the rest were accepted on a lighter check.", "",
"| Type | Diff | Worker | Attempts | Accepted | Checked well | Later wrong | Median min |",
"| Type | Diff | Worker | Attempts | Accepted rate | Checked well | Later wrong | Median min |",
"|---|---|---|---|---|---|---|---|"]
for r in rows:
thin = " (thin)" if r["n"] < routing.MIN_ATTEMPTS else ""
@@ -1104,7 +1170,7 @@ 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"])
avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors())
cand = result["choice"]
if cand is None:
notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty))
@@ -1171,29 +1237,21 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
# ---------------------------------------------------------------- strength and session lines
def strength_scores(candidates, records):
"""{worker: (score, how)} from the judged record where it is thick enough, else from the
stored prior (model-strength.json, each figure with its source and date). No shipped ranking:
a model with neither is simply absent here, and its strength is unknown."""
def strength_scores(candidates):
"""{worker: (standing, how)} from the stored benchmark standing (model-strength.json, each figure with
its source and date). Only standings are here: the accepted rate measured from judged delegations is a
different scale and is never mixed in. No shipped ranking: a model with no stored standing is simply
absent, and its strength is unknown."""
prior = load_strength_prior()
stats = routing.candidate_stats(candidates, records)
out = {}
for c in candidates:
cells = stats.get(c["worker"], {}).get("by_cell", {})
n = sum(v["n"] for v in cells.values())
good = sum(v["good"] for v in cells.values())
if n >= routing.MIN_ATTEMPTS:
out[c["worker"]] = (100.0 * good / n, "measured from %d judged delegations" % n)
continue
entry = None
for key in [c["worker"], c.get("model")] + list(c.get("aliases") or []):
if key and isinstance(prior.get(key), dict):
standing = standing_of(prior.get(key)) if key else None
if standing is not None:
entry = prior[key]
out[c["worker"]] = (standing, "benchmark standing (%s, %s)" % (entry.get("source") or "no source stated",
entry.get("date") or "no date stated"))
break
if entry and isinstance(entry.get("score"), (int, float)):
how = "stored prior (%s, %s)" % (entry.get("source") or "no source stated",
entry.get("date") or "no date stated")
out[c["worker"]] = (float(entry["score"]), how)
return out
@@ -1235,14 +1293,14 @@ def session_lines(model, payload=None):
suffix = " One delegation is waiting for a judgement: run `sisi workers`, then `sisi delegate judge`."
elif waiting:
suffix = " %d delegations are waiting for a judgement: run `sisi workers` to see, then `sisi delegate judge`." % waiting
scores = strength_scores(candidates, records) if candidates else {}
scores = strength_scores(candidates) if candidates else {}
cand = resolve_worker(model, candidates) if candidates else None
own = scores.get(cand["worker"]) if cand else None
if own is None:
prior = load_strength_prior().get(model)
if isinstance(prior, dict) and isinstance(prior.get("score"), (int, float)):
own = (float(prior["score"]), "stored prior (%s, %s)" % (prior.get("source") or "no source stated",
prior.get("date") or "no date stated"))
if standing_of(prior) is not None:
own = (standing_of(prior), "benchmark standing (%s, %s)" % (prior.get("source") or "no source stated",
prior.get("date") or "no date stated"))
lines = []
if own is not None:
best_score = max([s for s, _h in scores.values()] + [own[0]])
@@ -1284,7 +1342,21 @@ def _when(ts):
return "unknown time"
def _price_lines(tool_name, models, prices):
def _price_bits(p):
bits = []
if p.get("plan"):
bits.append("%s plan" % ("flat-rate" if p["plan"] == "flat" else "per-use"))
if isinstance(p.get("price_in"), (int, float)) and isinstance(p.get("price_out"), (int, float)):
bits.append("%g in / %g out per million tokens (blended %g at %g:1 input to output)"
% (p["price_in"], p["price_out"], entry_cost(p), price_blend()))
elif entry_cost(p) is not None:
bits.append("%g per million tokens (one blended figure)" % entry_cost(p))
if p.get("source"):
bits.append("from %s, %s" % (p["source"], p.get("date") or "no date stated"))
return bits
def _price_lines(tool_name, models, prices, shown_keys=None):
lines = []
tool_price = _price_for(prices, tool_name, None, None)
shown = set()
@@ -1292,18 +1364,13 @@ def _price_lines(tool_name, models, prices):
p = _price_for(prices, tool_name, m, _canonical(tool_name, m)) or tool_price
if not p:
continue
if shown_keys is not None:
shown_keys.update(k for k in (m, _canonical(tool_name, m)) if k)
key = json.dumps(p, sort_keys=True)
if key in shown:
continue
shown.add(key)
bits = []
if p.get("plan"):
bits.append("%s plan" % ("flat-rate" if p["plan"] == "flat" else "per-use"))
cost = p.get("cost_per_million_tokens", p.get("cost"))
if isinstance(cost, (int, float)):
bits.append("%g per million tokens" % cost)
if p.get("source"):
bits.append("from %s, %s" % (p["source"], p.get("date") or "no date stated"))
bits = _price_bits(p)
if bits:
lines.append(" price%s: %s" % ((" for %s" % m) if m and len(models) > 1 else "", "; ".join(bits)))
return lines
@@ -1325,10 +1392,12 @@ def cmd_workers(args=()):
return _cmd_up(args[1:])
if args[:1] == ["import"]:
return _cmd_import(args[1:])
migrate_standing_facts()
disc = discover(force="--refresh" in args)
records = read_records()
avail = read_availability()
prices = load_prices()
shown_keys = set()
print("Workers found on this machine (checked %s):" % _when(disc.get("checked")))
missing = []
for t in disc.get("tools") or []:
@@ -1356,12 +1425,25 @@ def cmd_workers(args=()):
print(" allowance left: %s" % t["allowance_text"])
elif t.get("allowance_pct_left") is not None:
print(" allowance left: %g%%" % t["allowance_pct_left"])
for line in _price_lines(t["name"], models, prices):
for line in _price_lines(t["name"], models, prices, shown_keys):
print(line)
if t.get("plan") == "flat" and not _price_lines(t["name"], models, prices):
print(" price: flat-rate plan (the tool reports an allowance, so one more task costs nothing extra)")
if missing:
print("Not found on PATH: %s" % ", ".join(missing))
own_prices = prices.get("models") if isinstance(prices.get("models"), dict) else {}
for worker, entry in sorted(own_prices.items()):
bits = _price_bits(entry) if isinstance(entry, dict) and worker not in shown_keys else []
if bits:
print("price for %s: %s" % (worker, "; ".join(bits)))
standings = sorted(((standing_of(e), k, e) for k, e in load_strength_prior().items() if standing_of(e) is not None),
key=lambda t: (-t[0], t[1]))
if standings:
print("Benchmark standing (a published figure; routing compares it only with other workers' standing, "
"never with the accepted rate measured below):")
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"))
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 []}:
@@ -1434,7 +1516,7 @@ 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"])
avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors())
result["passed_over"] = list(result["passed_over"]) + limited
by_worker = {c["worker"]: c for c in everyone}
down = _down_now(read_availability(), time.time())
@@ -1796,8 +1878,9 @@ def _cmd_import(args):
def _cmd_fact(args):
usage = ("usage: sisi workers fact WORKER --price N [--plan flat|per-use] [--maker M] --source S [--date YYYY-MM-DD]\n"
" sisi workers fact WORKER --score 0..100 --source S [--date YYYY-MM-DD]")
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)")
if not args:
print(usage)
return 1
@@ -1805,14 +1888,31 @@ def _cmd_fact(args):
source = _opt(args, "--source")
date = _opt(args, "--date") or time.strftime("%Y-%m-%d", time.localtime())
price, price_ok = _number_opt(args, "--price")
score, score_ok = _number_opt(args, "--score")
if not price_ok or not score_ok or (price is None and score is None):
price_in, in_ok = _number_opt(args, "--price-in")
price_out, out_ok = _number_opt(args, "--price-out")
standing, standing_ok = _number_opt(args, "--standing")
old_name, old_ok = _number_opt(args, "--score")
if standing is None:
standing = old_name
if not (price_ok and in_ok and out_ok and standing_ok and old_ok):
print(usage)
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:
print(usage)
return 1
if min([v for v in (price, price_in, price_out) if v is not None] or [0]) < 0:
print("sisi: a price cannot be negative", file=sys.stderr)
return 1
if not source:
print("sisi: a fact needs its --source (where the figure came from); nothing recorded", file=sys.stderr)
return 1
if price is not None:
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 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"):
print("sisi: --plan wants flat or per-use", file=sys.stderr)
@@ -1820,7 +1920,14 @@ def _cmd_fact(args):
prices = load_prices()
models = prices.get("models") if isinstance(prices.get("models"), dict) else {}
entry = dict(models.get(worker) or {})
entry.update({"cost_per_million_tokens": price, "source": source, "date": date})
entry.pop("cost", None)
if price_in is not None:
entry.pop("cost_per_million_tokens", None)
entry.update({"price_in": price_in, "price_out": price_out, "source": source, "date": date})
else:
entry.pop("price_in", None)
entry.pop("price_out", None)
entry.update({"cost_per_million_tokens": price, "source": source, "date": date})
if plan:
entry["plan"] = plan
maker = _opt(args, "--maker")
@@ -1829,22 +1936,25 @@ def _cmd_fact(args):
models[worker] = entry
prices["models"] = models
write_json(prices_path(), prices)
print("recorded price for %s: %g per million tokens (from %s, %s)" % (worker, price, source, date))
if score is not None:
if not (0 <= score <= 100):
print("sisi: --score wants a number from 0 to 100", file=sys.stderr)
return 1
if price_in is not None:
print("recorded price for %s: %g in / %g out per million tokens, blended %g for ranking (from %s, %s)"
% (worker, price_in, price_out, entry_cost(entry), source, date))
else:
print("recorded price for %s: %g per million tokens (from %s, %s)" % (worker, price, source, date))
if standing is not None:
migrate_standing_facts()
data = read_json(strength_path())
models = data.get("models") if isinstance(data.get("models"), dict) else {}
entry = dict(models.get(worker) or {})
entry.update({"score": score, "source": source, "date": date})
entry.pop("score", None)
entry.update({"standing": standing, "source": source, "date": date})
maker = _opt(args, "--maker")
if maker:
entry["maker"] = maker
models[worker] = entry
data["models"] = models
write_json(strength_path(), data)
print("recorded benchmark standing for %s: %g (from %s, %s)" % (worker, score, source, date))
print("recorded benchmark standing for %s: %g (from %s, %s)" % (worker, standing, source, date))
return 0
+603
View File
@@ -0,0 +1,603 @@
"""Choosing the cheapest worker that is capable enough for a kind and difficulty, from the best evidence
about each worker: judged record (exact, a harder difficulty, all kinds), then benchmark standing against other
workers' standing only, then nothing known (difficulty 1 only). Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3,
R-7.3-3. Property tests are seeded and scale with SISI_TEST_ITERS."""
import json, os, random, unittest
from support import *
from sisi import routing
KIND = "research"
def cand(name, cost=None, standing=None, plan="per-use", allowance=None, maker=None, usable=True):
w = "t/%s" % name
return {"worker": w, "tool": "t", "model": name, "maker": maker or name.split("-")[0], "plan": plan,
"cost": cost, "allowance_pct_left": allowance, "usable": usable, "reason": None,
"standing": standing, "standing_source": "fixture benchmark", "standing_date": "2000-01-01",
"aliases": [w, name]}
_n = [0]
def attempts(worker, kind, difficulty, good, bad, kind_name="attempt"):
rows = []
for i in range(good + bad):
_n[0] += 1
rows.append({"kind": kind_name, "id": "x%d" % _n[0], "type": kind, "difficulty": difficulty,
"worker": worker, "outcome": "accepted" if i < good else "rejected", "check": "tests"})
return rows
def pick(cands, records, difficulty, kind=KIND, **kw):
return routing.choose(cands, records, {}, kind, difficulty, now=1000.0, **kw)
def chosen(cands, records, difficulty, **kw):
r = pick(cands, records, difficulty, **kw)
return r["choice"]["worker"] if r["choice"] else None
class SufficientCapabilityTests(unittest.TestCase):
def fleet(self):
# the shape that went wrong: the cheapest worker has the weakest standing
return [cand("weak-1", cost=0.2, standing=40.0), cand("mid-1", cost=4.0, standing=64.0),
cand("top-1", cost=8.0, standing=66.0)]
def test_a_hard_task_goes_to_a_worker_near_the_top_not_the_cheapest(self):
"""R-7.2-2: difficulty 3 needs at least 85 percent of the best standing; the cheapest of those wins."""
self.assertEqual(chosen(self.fleet(), [], 3), "t/mid-1")
self.assertEqual(chosen(self.fleet(), [], 1), "t/weak-1") # no floor at difficulty 1
self.assertEqual(chosen(self.fleet(), [], 2), "t/weak-1") # 40 is 60.6 percent of 66, above the 60 percent floor
def test_the_floor_is_configurable(self):
got = chosen(self.fleet(), [], 2, floors={"2": 80})
self.assertEqual(got, "t/mid-1")
self.assertEqual(chosen(self.fleet(), [], 3, floors={3: 100}), "t/top-1")
def test_a_flat_plan_with_low_standing_does_not_take_a_hard_task(self):
cands = [cand("flat-1", standing=30.0, plan="flat", allowance=80), cand("pay-1", cost=5.0, standing=64.0)]
self.assertEqual(chosen(cands, [], 3), "t/pay-1")
self.assertEqual(chosen(cands, [], 2), "t/pay-1") # 30 is under 60 percent of 64
self.assertEqual(chosen(cands, [], 1), "t/flat-1") # flat first where nothing is needed
def test_a_judged_record_proves_capability_whatever_the_standing(self):
"""The record outranks the benchmark: 9 of 10 at this kind and difficulty beats a low standing."""
cands = self.fleet()
recs = attempts("t/weak-1", KIND, 3, 9, 1)
r = pick(cands, recs, 3)
self.assertEqual(r["choice"]["worker"], "t/weak-1")
self.assertEqual(r["assessments"]["t/weak-1"]["tier"], "a")
def test_a_harder_difficulty_of_the_same_kind_proves_an_easier_one(self):
cands = [cand("a-1", cost=1.0), cand("b-1", cost=2.0)]
recs = attempts("t/b-1", KIND, 3, 10, 0)
r = pick(cands, recs, 2)
self.assertEqual(r["choice"]["worker"], "t/b-1")
self.assertEqual(r["assessments"]["t/b-1"]["tier"], "b-higher")
self.assertFalse(r["assessments"]["t/a-1"]["capable"])
def test_an_easier_difficulty_is_weak_evidence_used_only_as_a_last_resort(self):
cands = [cand("a-1", cost=1.0), cand("b-1", cost=2.0)]
recs = attempts("t/b-1", KIND, 1, 10, 0)
r = pick(cands, recs, 3)
self.assertEqual(r["choice"]["worker"], "t/b-1")
self.assertEqual(r["basis"], "weak")
# with a capable worker on hand, the weak evidence does not count
cands2 = cands + [cand("c-1", cost=9.0, standing=70.0)]
r2 = pick(cands2, recs, 3)
self.assertEqual(r2["choice"]["worker"], "t/c-1")
self.assertEqual(r2["basis"], "capable")
def test_the_same_difficulty_across_all_kinds_counts_when_the_kind_has_no_record(self):
cands = [cand("a-1", cost=1.0), cand("b-1", cost=2.0)]
recs = attempts("t/b-1", "other-kind", 2, 6, 0) + attempts("t/b-1", "third-kind", 2, 5, 1)
r = pick(cands, recs, 2)
self.assertEqual(r["choice"]["worker"], "t/b-1")
self.assertEqual(r["assessments"]["t/b-1"]["tier"], "b-all")
def test_unknown_workers_are_an_exploration_at_difficulty_one_only(self):
cands = [cand("a-1", cost=1.0), cand("b-1", cost=2.0, standing=50.0)]
r1 = pick(cands, [], 1)
self.assertEqual(r1["choice"]["worker"], "t/a-1")
self.assertEqual(r1["assessments"]["t/a-1"]["tier"], "unknown")
r2 = pick(cands, [], 2)
self.assertEqual(r2["choice"]["worker"], "t/b-1")
self.assertFalse(r2["assessments"]["t/a-1"]["capable"])
def test_all_workers_unknown_still_gives_an_answer_and_says_nothing_is_proven(self):
cands = [cand("a-1", cost=1.0), cand("b-1", cost=2.0)]
for d in (2, 3):
r = pick(cands, [], d)
self.assertEqual(r["choice"]["worker"], "t/a-1")
self.assertEqual(r["basis"], "nothing")
def test_no_capable_worker_falls_back_to_the_strongest_known(self):
"""When the best-standing worker is itself out (a poor record), nobody clears the floor: the strongest known
usable worker is taken and the result says that nothing is proven."""
cands = [cand("great-1", cost=1.0, standing=99.0), cand("ok-1", cost=3.0, standing=70.0),
cand("low-1", cost=0.5, standing=50.0)]
recs = attempts("t/great-1", KIND, 3, 3, 7)
r = pick(cands, recs, 3)
self.assertEqual(r["choice"]["worker"], "t/ok-1")
self.assertEqual(r["basis"], "strongest")
def test_a_great_benchmark_never_rescues_a_thick_bad_record(self):
cands = [cand("great-1", cost=1.0, standing=99.0), cand("ok-1", cost=30.0, standing=70.0)]
recs = attempts("t/great-1", KIND, 3, 3, 7)
self.assertEqual(chosen(cands, recs, 3), "t/ok-1")
# a bad record at difficulty 3 says nothing about difficulty 1: there the cheaper great-1 is fine
self.assertEqual(chosen(cands, recs, 1), "t/great-1")
def test_a_bad_record_at_an_easier_difficulty_also_blocks_the_benchmark(self):
cands = [cand("great-1", cost=1.0, standing=99.0), cand("ok-1", cost=30.0, standing=98.0)]
recs = attempts("t/great-1", KIND, 2, 2, 8)
self.assertEqual(chosen(cands, recs, 3), "t/ok-1")
self.assertEqual(chosen(cands, recs, 2), "t/ok-1")
def test_a_thin_record_of_repeated_rejections_cancels_the_prior(self):
cands = [cand("cheap-1", cost=0.2, standing=40.0), cand("mid-1", cost=4.0, standing=64.0)]
recs = attempts("t/cheap-1", KIND, 2, 0, 2)
r = pick(cands, recs, 2)
self.assertEqual(r["choice"]["worker"], "t/mid-1")
self.assertTrue(r["assessments"]["t/cheap-1"]["contradicted"])
def test_every_usable_worker_poor_still_names_the_best_rate(self):
cands = [cand("a-1", cost=1.0), cand("b-1", cost=2.0)]
recs = attempts("t/a-1", KIND, 2, 1, 9) + attempts("t/b-1", KIND, 2, 4, 6)
r = pick(cands, recs, 2)
self.assertEqual(r["choice"]["worker"], "t/b-1")
self.assertEqual(r["basis"], "all-bad")
def test_equal_evidence_and_price_is_stable_and_explained(self):
cands = [cand("b-1", cost=2.0, standing=60.0), cand("a-1", cost=2.0, standing=60.0)]
for _ in range(3):
r = pick(list(reversed(cands)), [], 3)
self.assertEqual(r["choice"]["worker"], "t/a-1")
text = " ".join(reason for _w, reason in r["passed_over"])
self.assertIn("equal on price and load", text)
def test_a_single_usable_worker_is_recommended_whatever_it_knows(self):
for d in (1, 2, 3):
self.assertEqual(chosen([cand("only-1")], [], d), "t/only-1")
self.assertEqual(chosen([cand("only-1", standing=5.0)], [], d), "t/only-1")
self.assertEqual(pick([cand("only-1")], [], 3)["basis"], "nothing")
def test_the_existing_constraints_still_hold(self):
cands = [cand("a-1", cost=1.0, standing=60.0), cand("b-1", cost=2.0, standing=60.0),
cand("c-contributor-1", cost=0.1, standing=60.0), cand("d-1", cost=0.5, standing=60.0, usable=False)]
r = pick(cands, [], 2, review_of="t/a-1")
self.assertEqual(r["choice"]["worker"], "t/b-1") # another maker reviews
reasons = dict(r["passed_over"])
self.assertIn("trains on prompts", reasons["t/c-contributor-1"])
self.assertIn("t/d-1", reasons)
avoided = pick(cands, [], 2, avoid=[{"pattern": "a-1", "why": "mine"}])
self.assertEqual(avoided["choice"]["worker"], "t/b-1")
preferred = pick(cands, [], 2, prefer=[{"pattern": "b-1"}])
self.assertEqual(preferred["choice"]["worker"], "t/b-1")
down = routing.choose(cands, [], {"t": {"retry_at": 5000.0, "reason": "limit"}}, KIND, 2, now=1000.0)
self.assertIsNone(down["choice"])
def test_the_two_scales_are_never_compared(self):
"""R-7.2-2: V (standing 60, the best) is cheaper than W (standing 55, and 5 of 5 accepted: a thin record that
proves nothing). At difficulty 3 both clear the floor on standing and the cheaper, V, wins. A comparison of
W's accepted rate (100) with a standing would make 100 the 'best' and V (60) incapable."""
cands = [cand("v-1", cost=1.0, standing=60.0), cand("w-1", cost=5.0, standing=55.0)]
recs = attempts("t/w-1", KIND, 3, 5, 0)
r = pick(cands, recs, 3)
self.assertEqual(r["choice"]["worker"], "t/v-1")
self.assertEqual(r["best_standing"], 60.0)
def test_a_standing_scaled_by_any_factor_changes_nothing(self):
rng = random.Random(7)
for _ in range(60 * ITERS):
cands, recs = gen_world(rng)
for d in (1, 2, 3):
base = pick(cands, recs, d)
for k in (0.01, 0.37, 3.0, 40.0):
scaled = [dict(c, standing=(c["standing"] * k if c["standing"] is not None else None)) for c in cands]
got = pick(scaled, recs, d)
self.assertEqual((got["choice"] or {}).get("worker"), (base["choice"] or {}).get("worker"), (d, k))
self.assertEqual(got["basis"], base["basis"])
class MeasuredProofBeatsABenchmarkTests(unittest.TestCase):
"""Above difficulty 1 a benchmark standing is a reason to try a worker, not to prefer it to a judged record.
The grid's case: a cheap worker whose standing is just over the floor, no record; a dearer one with a thick,
good record for exactly this kind and difficulty. R-7.2-2, R-7.2-3, R-7.3-3."""
def pair(self):
# 40 is 60.8 percent of the best usable standing, 65.8: over the difficulty-2 floor of 60
return [cand("cheap-1", cost=0.2, standing=40.0), cand("proven-1", cost=4.0, standing=65.8)]
def test_the_proven_worker_takes_ordinary_work_the_cheap_one_takes_routine_work(self):
recs = attempts("t/proven-1", KIND, 2, 21, 0)
r2 = pick(self.pair(), recs, 2)
self.assertEqual(r2["choice"]["worker"], "t/proven-1")
self.assertEqual(r2["assessments"]["t/proven-1"]["tier"], "a")
self.assertTrue(r2["assessments"]["t/cheap-1"]["capable"]) # capable by standing, still not preferred
self.assertEqual(chosen(self.pair(), recs, 1), "t/cheap-1")
self.assertEqual(chosen(self.pair(), attempts("t/proven-1", KIND, 3, 12, 0), 3), "t/proven-1")
def test_with_the_proven_worker_unavailable_the_cheap_one_is_taken_on_its_standing(self):
recs = attempts("t/proven-1", KIND, 2, 21, 0)
down = {"t/proven-1": {"retry_at": 5000.0, "reason": "limit"}}
r = routing.choose(self.pair(), recs, down, KIND, 2, now=1000.0)
self.assertEqual(r["choice"]["worker"], "t/cheap-1")
self.assertIn("evidence (c)", routing.explain_choice(r, KIND, 2)[1])
def test_the_explanation_says_why_the_cheaper_benchmark_worker_was_passed_over(self):
recs = attempts("t/proven-1", KIND, 2, 21, 0)
r = pick(self.pair(), recs, 2)
lines = routing.explain_choice(r, KIND, 2)
self.assertIn("evidence (a)", lines[1])
self.assertIn("by a judged record", lines[0])
self.assertTrue([l for l in lines if "cheap-1" in l and "judged record is preferred to a benchmark" in l], lines)
def test_the_judged_record_across_all_kinds_counts_only_when_nobody_has_evidence_from_the_kind(self):
cands = [cand("pooled-1", cost=1.0), cand("kind-1", cost=5.0)]
pooled = attempts("t/pooled-1", "other", 2, 10, 0)
self.assertEqual(chosen(cands, pooled, 2), "t/pooled-1") # nobody has the kind: the pooled record counts
both = pooled + attempts("t/kind-1", KIND, 2, 9, 1)
r = pick(cands, both, 2)
self.assertEqual(r["choice"]["worker"], "t/kind-1") # the kind's own record outranks it
self.assertEqual(r["assessments"]["t/pooled-1"]["tier"], "b-all")
def test_a_record_from_a_harder_difficulty_of_the_kind_is_the_kinds_own_evidence(self):
cands = [cand("cheap-1", cost=0.2, standing=40.0), cand("hard-1", cost=4.0, standing=65.8)]
recs = attempts("t/hard-1", KIND, 3, 10, 0)
self.assertEqual(chosen(cands, recs, 2), "t/hard-1")
def test_nobody_with_a_record_means_the_benchmark_decides_as_before(self):
self.assertEqual(chosen(self.pair(), [], 2), "t/cheap-1")
self.assertEqual(chosen(self.pair(), [], 3), "t/proven-1") # 40 is under 85 percent of 65.8
def test_a_worker_with_a_judged_record_is_always_chosen_when_one_is_capable(self):
"""With at least one usable worker capable by a judged record at difficulty 2 or 3, the choice has a judged
record: evidence a or b, from the kind when any usable worker has it."""
rng = random.Random(31337)
covered = 0
for _ in range(400 * ITERS):
cands, recs = gen_world(rng)
for d in (2, 3):
r = pick(cands, recs, d)
a = r["assessments"]
same_kind = [w for w in a if a[w]["tier"] in ("a", "b-higher")]
pooled = [w for w in a if a[w]["tier"] == "b-all"]
if not (same_kind or pooled):
continue
covered += 1
self.assertEqual(r["basis"], "capable")
self.assertIn(a[r["choice"]["worker"]]["tier"], ("a", "b-higher") if same_kind else ("b-all",),
(d, a[r["choice"]["worker"]]["tier"]))
self.assertGreater(covered, 100)
def test_difficulty_one_is_unchanged_and_the_cheapest_capable_wins_whatever_the_evidence(self):
rng = random.Random(77)
for _ in range(200 * ITERS):
cands, recs = gen_world(rng)
r = pick(cands, recs, 1)
if r["basis"] != "capable" or r["explored"]:
continue
price = lambda c: (routing._price_tier(c), c["cost"] if c.get("cost") is not None else float("inf"))
for c in cands:
if r["assessments"][c["worker"]]["capable"]:
self.assertGreaterEqual(price(c), price(r["choice"]))
def gen_world(rng, kinds=("research", "edit")):
"""Generated workers and a judged ledger: prices, plans, standings (or none), cells of every size."""
cands, recs = [], []
for i in range(rng.randint(1, 6)):
flat = rng.random() < 0.2
c = cand("w%d-%d" % (i, rng.randint(0, 9)), cost=None if flat else rng.choice([None, 0.2, 1.0, 4.0, 8.0, 30.0]),
standing=rng.choice([None, None, rng.uniform(10, 100)]), plan="flat" if flat else rng.choice(["per-use", None]),
allowance=rng.choice([None, 40, 90]) if flat else None)
cands.append(c)
for kind in kinds:
for d in (1, 2, 3):
n = rng.choice([0, 0, 2, 3, 8, 8, 12, 30])
good = rng.randint(0, n)
recs += attempts(c["worker"], kind, d, good, n - good)
rng.shuffle(recs)
return cands, recs
class CapabilityPropertyTests(unittest.TestCase):
def test_raising_the_difficulty_never_gives_weaker_evidence(self):
"""R-7.2-2, R-7.2-3: for the same data, a worker capable at difficulty d+1 is capable at d, its evidence at d is
at least as strong, and the worker chosen for a harder task on evidence is capable on the easier one."""
rng = random.Random(20261123)
for _ in range(300 * ITERS):
cands, recs = gen_world(rng)
runs = {d: pick(cands, recs, d) for d in (1, 2, 3)}
for d in (1, 2):
lo, hi = runs[d]["assessments"], runs[d + 1]["assessments"]
for w in lo:
self.assertLessEqual(hi[w]["capable"], lo[w]["capable"], (d, w, lo[w], hi[w]))
self.assertGreaterEqual(lo[w]["level"], hi[w]["level"], (d, w, lo[w], hi[w]))
got = runs[d + 1]["choice"]
if got is not None and runs[d + 1]["basis"] == "capable":
self.assertTrue(lo[got["worker"]]["capable"], (d, got["worker"]))
def test_a_capable_worker_that_is_as_good_and_cheaper_is_never_passed_over(self):
"""R-7.2-2: the choice is the cheapest of the capable workers that compete (above difficulty 1 those capable
by a judged record when there are any); a prefer pattern aside, none here."""
rng = random.Random(4242)
for _ in range(300 * ITERS):
cands, recs = gen_world(rng)
for d in (1, 2, 3):
r = pick(cands, recs, d)
if r["choice"] is None or r["basis"] != "capable":
continue
x = r["choice"]
price = lambda c: (routing._price_tier(c), c["cost"] if c.get("cost") is not None else float("inf"))
capable = [c for c in cands if r["assessments"][c["worker"]]["capable"]]
competing, _judged = routing._prefer_judged(capable, r["assessments"], d)
self.assertIn(x["worker"], [c["worker"] for c in competing])
for c in competing:
if c["worker"] != x["worker"]:
self.assertGreaterEqual(price(c), price(x), (d, c["worker"], x["worker"]))
def test_a_thick_bad_record_is_never_chosen_over_a_usable_worker_without_one(self):
"""R-7.2-3, R-7.3-3."""
rng = random.Random(99)
seen = 0
for _ in range(400 * ITERS):
cands, recs = gen_world(rng)
for d in (1, 2, 3):
r = pick(cands, recs, d)
if r["choice"] is None:
continue
cell = routing._cell(r["stats"], r["choice"]["worker"], KIND, d)
if cell["n"] >= routing.MIN_ATTEMPTS and cell["good"] / cell["n"] < routing.MIN_ACCEPTED_RATE:
seen += 1
self.assertTrue(all(a["bad"] for a in r["assessments"].values()), (d, r["choice"]["worker"]))
self.assertGreater(seen, 0, "the generator never produced the case it is meant to test")
def test_the_choice_does_not_depend_on_candidate_order(self):
rng = random.Random(5)
for _ in range(120 * ITERS):
cands, recs = gen_world(rng)
d = rng.choice([1, 2, 3])
a = chosen(cands, recs, d)
b = chosen(list(reversed(cands)), recs, d)
self.assertEqual(a, b)
def explain(cands, records, difficulty, **kw):
r = pick(cands, records, difficulty, **kw)
return r, routing.explain_choice(r, KIND, difficulty)
def line_with(lines, start):
got = [l for l in lines if l.startswith(start)]
return got
class ExplainTests(unittest.TestCase):
"""R-7.2-1, R-7.2-2: --explain says which evidence decided, why cheaper workers were not capable enough, and when
the choice is an exploration or a fallback; one line each, 20 lines at most."""
def test_the_evidence_for_each_tier_is_one_line_with_its_numbers(self):
cases = []
cands = [cand("w-1", cost=1.0)]
_r, lines = explain(cands, attempts("t/w-1", KIND, 3, 9, 1), 3)
cases.append((lines, ["evidence (a)", "9 of 10 accepted", "difficulty 3", "90%"]))
_r, lines = explain(cands, attempts("t/w-1", KIND, 3, 10, 0), 2)
cases.append((lines, ["evidence (b)", "harder difficulty", "10 of 10", "difficulty 3", "proves difficulty 2"]))
_r, lines = explain(cands, attempts("t/w-1", "other", 2, 8, 2), 2)
cases.append((lines, ["evidence (b)", "all kinds", "8 of 10", "difficulty 2"]))
_r, lines = explain([cand("w-1", cost=1.0, standing=64.0), cand("w-2", cost=5.0, standing=66.0)], [], 3)
cases.append((lines, ["evidence (c)", "benchmark standing", "64", "fixture benchmark", "2000-01-01", "85%", "66"]))
_r, lines = explain(cands, [], 1)
cases.append((lines, ["evidence (d)", "nothing is known", "exploration"]))
_r, lines = explain(cands, attempts("t/w-1", KIND, 1, 10, 0), 3)
cases.append((lines, ["evidence (b, weak)", "10 of 10", "easier difficulty 1"]))
for lines, words in cases:
ev = line_with(lines, "evidence")
self.assertEqual(len(ev), 1, lines)
for w in words:
self.assertIn(w, ev[0], lines)
def test_standing_and_accepted_rate_are_named_apart(self):
_r, a = explain([cand("w-1", cost=1.0)], attempts("t/w-1", KIND, 3, 9, 1), 3)
_r, c = explain([cand("w-1", cost=1.0, standing=64.0)], [], 3)
self.assertNotIn("standing", line_with(a, "evidence")[0])
self.assertNotIn("accepted", line_with(c, "evidence")[0])
def test_cheaper_workers_that_were_not_capable_are_one_grouped_line_with_a_count(self):
cands = [cand("c%d-1" % i, cost=0.1 + i / 100, standing=10.0 + i) for i in range(5)]
cands += [cand("good-1", cost=4.0, standing=64.0), cand("best-1", cost=8.0, standing=66.0)]
r, lines = explain(cands, [], 3)
self.assertEqual(r["choice"]["worker"], "t/good-1")
grp = [l for l in lines if "not capable enough" in l]
self.assertEqual(len(grp), 1, lines)
self.assertIn("passed over 5 worker(s)", grp[0])
self.assertIn("cheaper than the choice", grp[0])
self.assertIn("56.1", grp[0]) # the standing needed: 85 percent of 66 = 56.1
self.assertIn("and 2 more", grp[0]) # three example names at most
self.assertLessEqual(len(lines) + routing.EXPLAIN_TAIL_LINES, routing.MAX_EXPLAIN_LINES)
def test_a_fallback_says_plainly_that_nothing_is_proven(self):
cands = [cand("a-1", cost=1.0, standing=99.0), cand("b-1", cost=3.0, standing=70.0)]
r, lines = explain(cands, attempts("t/a-1", KIND, 3, 2, 8), 3)
self.assertEqual(r["basis"], "strongest")
head = lines[0]
self.assertIn("none is proven capable", head)
self.assertIn("strongest known", head)
self.assertEqual(len(line_with(lines, "evidence")), 1)
_r, cold = explain([cand("a-1"), cand("b-1")], [], 3)
self.assertIn("none is proven capable", cold[0])
self.assertIn("nothing is recorded", cold[0] + cold[1])
def test_an_exploration_is_called_one(self):
cands = [cand("a-1", cost=5.0, standing=90.0), cand("b-1", cost=5.0, standing=10.0)]
recs = attempts("t/a-1", "read", 1, 9, 0)
r = routing.choose(cands, recs, {}, "read", 1, now=1000.0)
self.assertEqual(r["choice"]["worker"], "t/b-1")
lines = routing.explain_choice(r, "read", 1)
self.assertTrue(line_with(lines, "this is an exploration pick"), lines)
def test_the_explanation_stays_within_twenty_lines_with_many_workers(self):
rng = random.Random(3)
for _ in range(80 * ITERS):
cands = [cand("w%d-%d" % (i, rng.randint(0, 5)), cost=rng.choice([None, 0.1, 2.0]),
standing=rng.choice([None, rng.uniform(5, 100)])) for i in range(rng.randint(1, 60))]
cands = list({c["worker"]: c for c in cands}.values())
d = rng.choice([1, 2, 3])
_r, lines = explain(cands, [], d)
self.assertLessEqual(len(lines) + routing.EXPLAIN_TAIL_LINES, routing.MAX_EXPLAIN_LINES, lines)
class ExplainCliTests(SisiCase):
def seed_world(self):
os.makedirs(self.data, exist_ok=True)
rows = []
for w, d, good, bad in (("wk-mid", 2, 9, 1), ("wk-weak", 2, 0, 2)):
for i in range(good + bad):
rows.append({"kind": "attempt", "id": "%s-%d" % (w, i), "ts": 1760000000 + i, "project": "p", "type": "research",
"difficulty": d, "worker": w, "outcome": "accepted" if i < good else "rejected",
"check": "tests", "minutes": 1})
open(os.path.join(self.data, "delegations.jsonl"), "w").write("".join(json.dumps(r) + "\n" for r in rows))
json.dump({"models": {"wk-weak": {"standing": 40, "source": "fixture board", "date": "2000-01-01"},
"wk-mid": {"standing": 64, "source": "fixture board", "date": "2000-01-01"},
"wk-top": {"standing": 66, "source": "fixture board", "date": "2000-01-01"}}},
open(os.path.join(self.data, "model-strength.json"), "w"))
json.dump({"models": {"wk-weak": {"cost_per_million_tokens": 0.2, "source": "fixture", "date": "2000-01-01"},
"wk-mid": {"cost_per_million_tokens": 4, "source": "fixture", "date": "2000-01-01"},
"wk-top": {"cost_per_million_tokens": 8, "source": "fixture", "date": "2000-01-01"}}},
open(os.path.join(self.data, "worker-prices.json"), "w"))
def test_a_hard_task_is_not_given_to_the_cheapest_weak_worker(self):
"""The reported fault: with prices and standings recorded, a hard research task went to the cheapest, weakest
worker. Now it goes to the cheapest worker near the top, and `--explain` says why."""
self.seed_world()
env = dict(PATH="")
plain = self.sisi("route", "--kind", "research", "--difficulty", "3", env=env)
self.assertEqual(plain.returncode, 0, plain.stderr)
self.assertEqual(plain.stdout.splitlines()[0], "wk-mid")
self.assertLessEqual(len(plain.stdout.splitlines()), 6)
self.assertNotIn("evidence", plain.stdout)
ex = self.sisi("route", "--kind", "research", "--difficulty", "3", "--explain", env=env)
lines = ex.stdout.splitlines()
self.assertLessEqual(len(lines), 20, ex.stdout)
self.assertEqual(len([l for l in lines if l.startswith("evidence")]), 1, ex.stdout)
self.assertIn("evidence (c)", ex.stdout)
self.assertTrue([l for l in lines if l.startswith("passed over 1 worker(s) (wk-weak") and "not capable enough" in l], ex.stdout)
easy = self.sisi("route", "--kind", "research", "--difficulty", "1", env=env)
self.assertEqual(easy.stdout.splitlines()[0], "wk-weak")
def retry(cands, records, difficulty, rejected, rejections, **kw):
return routing.retry_choice(cands, records, {}, KIND, difficulty, rejected, rejections, now=1000.0, **kw)
class RetryLadderTests(unittest.TestCase):
"""The pure ladder behind `sisi route --retry-of`: the same worker for the first retry, then the cheapest capable
worker with strictly better evidence, else the strongest known. R-7.2-2, R-7.3-1 (retries cost)."""
def fleet(self):
return [cand("r-1", cost=4.0, standing=64.0), cand("s-1", cost=8.0, standing=66.0),
cand("t-1", cost=6.0, standing=65.0), cand("u-1", cost=0.5, standing=40.0)]
def test_the_first_retry_goes_back_to_the_same_worker(self):
r = retry(self.fleet(), [], 2, "t/r-1", 1)
self.assertEqual((r["choice"]["worker"], r["step"]), ("t/r-1", "same"))
def test_the_first_retry_moves_on_when_the_worker_is_not_usable(self):
cands = self.fleet()
cands[0]["usable"] = False
r = retry(cands, [], 2, "t/r-1", 1)
self.assertEqual(r["step"], "better")
self.assertNotEqual(r["choice"]["worker"], "t/r-1")
def test_later_retries_take_the_cheapest_capable_worker_with_better_evidence(self):
r = retry(self.fleet(), [], 2, "t/r-1", 2)
self.assertEqual((r["choice"]["worker"], r["step"]), ("t/t-1", "better")) # 65 beats 64; 66 costs more; 40 is weaker
r3 = retry(self.fleet(), [], 2, "t/t-1", 3)
self.assertEqual((r3["choice"]["worker"], r3["step"]), ("t/s-1", "better"))
def test_a_judged_proof_is_better_than_a_benchmark_and_a_benchmark_never_beats_a_proof(self):
cands = [cand("r-1", cost=4.0, standing=64.0), cand("p-1", cost=9.0, standing=10.0), cand("h-1", cost=5.0, standing=100.0)]
recs = attempts("t/p-1", KIND, 2, 9, 1)
self.assertEqual(retry(cands[:2], recs, 2, "t/r-1", 2)["choice"]["worker"], "t/p-1")
# r-1 has the proof now: h-1's standing 100 is not 'better' than 7 of 10 accepted; the two scales do not meet
recs2 = attempts("t/r-1", KIND, 2, 7, 3)
r = retry([c for c in cands if c["worker"] != "t/p-1"], recs2, 2, "t/r-1", 2)
self.assertEqual((r["choice"]["worker"], r["step"]), ("t/h-1", "strongest"))
def test_a_higher_accepted_rate_in_the_same_kind_of_evidence_is_better(self):
cands = [cand("r-1", cost=4.0), cand("a-1", cost=3.0), cand("b-1", cost=2.0), cand("c-1", cost=9.0)]
recs = (attempts("t/r-1", KIND, 2, 8, 2) + attempts("t/a-1", KIND, 2, 8, 2) # equal: not better
+ attempts("t/b-1", KIND, 2, 7, 3) + attempts("t/c-1", KIND, 2, 10, 0)) # lower, higher
r = retry(cands, recs, 2, "t/r-1", 2)
self.assertEqual((r["choice"]["worker"], r["step"]), ("t/c-1", "better"))
def test_when_nobody_has_better_evidence_the_strongest_known_other_is_taken(self):
cands = [cand("top-1", cost=9.0, standing=90.0), cand("a-1", cost=2.0, standing=70.0), cand("b-1", cost=1.0, standing=60.0)]
r = retry(cands, [], 3, "t/top-1", 2)
self.assertEqual((r["choice"]["worker"], r["step"]), ("t/a-1", "strongest"))
def test_the_rejected_worker_alone_is_returned_as_the_only_option(self):
r = retry([cand("r-1", cost=4.0, standing=64.0)], [], 2, "t/r-1", 3)
self.assertEqual((r["choice"]["worker"], r["step"]), ("t/r-1", "only"))
self.assertIsNone(retry([cand("r-1", usable=False)], [], 2, "t/r-1", 3)["choice"])
def test_a_worker_with_a_poor_record_is_never_on_the_ladder(self):
cands = [cand("r-1", cost=4.0, standing=60.0), cand("bad-1", cost=1.0, standing=99.0), cand("ok-1", cost=9.0, standing=61.0)]
recs = attempts("t/bad-1", KIND, 2, 2, 8)
r = retry(cands, recs, 2, "t/r-1", 2)
self.assertEqual(r["choice"]["worker"], "t/ok-1")
def test_the_ladder_keeps_the_users_constraints_and_other_workers_that_are_down(self):
cands = self.fleet()
r = routing.retry_choice(cands, [], {"t": {"retry_at": 5000.0, "reason": "limit"}}, KIND, 2, "t/r-1", 2, now=1000.0)
self.assertIsNone(r["choice"])
avoided = retry(cands, [], 2, "t/r-1", 2, avoid=[{"pattern": "t-1", "why": "mine"}])
self.assertEqual(avoided["choice"]["worker"], "t/s-1")
tried = retry(cands, [], 2, "t/r-1", 2, exclude=["t/t-1"])
self.assertEqual(tried["choice"]["worker"], "t/s-1")
def test_the_ladder_over_generated_worlds(self):
"""The step names what happened: better means capable, strictly stronger, and the cheapest such; strongest
means no capable worker was stronger and the pick has the greatest strength among the rest."""
rng = random.Random(8128)
steps = set()
for _ in range(300 * ITERS):
cands, recs = gen_world(rng)
d = rng.choice([1, 2, 3])
rejected = rng.choice(cands)["worker"]
n = rng.choice([1, 2, 3])
r = retry(cands, recs, d, rejected, n)
steps.add(r["step"])
if r["choice"] is None:
continue
a = r["assessments"]
w = r["choice"]["worker"]
self.assertFalse(a[w]["bad"] and r["step"] != "only", (w, r["step"]))
if r["step"] == "same":
self.assertEqual((w, n), (rejected, 1))
self.assertFalse(a[w]["bad"])
continue
if r["step"] == "only":
self.assertEqual(w, rejected)
continue
self.assertNotEqual(w, rejected)
rejected_strength = routing.strength(a[rejected])
stronger = [c for c in cands if a[c["worker"]]["capable"] and c["worker"] != rejected
and routing.strength(a[c["worker"]]) > rejected_strength]
stronger = routing._prefer_judged(stronger, a, d)[0]
if r["step"] == "better":
self.assertTrue(a[w]["capable"] and routing.strength(a[w]) > rejected_strength)
price = lambda c: (routing._price_tier(c), c["cost"] if c.get("cost") is not None else float("inf"))
self.assertTrue(all(price(c) >= price(r["choice"]) for c in stronger))
else:
self.assertEqual(stronger, [])
others = [x for x in a if x != rejected and not a[x]["bad"]]
self.assertEqual(routing.strength(a[w]), max(routing.strength(a[x]) for x in others))
self.assertTrue({"same", "better", "strongest"} <= steps, steps)
if __name__ == "__main__":
unittest.main()
+2 -1
View File
@@ -4,7 +4,8 @@ import ast, collections, glob, os, re, unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Seams that are documented and exercised by real-behaviour tests (docs/evaluation.md); keep them.
SEAMS = {"validate_check", "capture_case", "compare_for_candidate"}
# retry_choice is the pure ladder the `sisi route --retry-of` command calls; it lands with that command.
SEAMS = {"validate_check", "capture_case", "compare_for_candidate", "retry_choice"}
def _files():
+4 -3
View File
@@ -237,7 +237,8 @@ class FactsTests(OrchCase):
"--source", "test fixture benchmark", env=self.env())
self.assertEqual(r.returncode, 0, r.stderr)
prior = json.load(open(os.path.join(self.data, "model-strength.json")))
self.assertEqual(prior["models"]["muse/beta-1"]["score"], 70)
self.assertEqual(prior["models"]["muse/beta-1"]["standing"], 70)
self.assertNotIn("score", prior["models"]["muse/beta-1"])
def test_avoid_and_prefer_are_honoured(self):
"""A user's own avoid/prefer constraints shape the recommendation."""
@@ -366,8 +367,8 @@ class ExplorationTests(unittest.TestCase):
]
# Same price: alpha (proven, stronger prior) is the usual pick. Every tenth judged
# attempt for the kind and difficulty, the thin-record beta gets the task instead.
cands[0]["prior_score"] = 90.0
cands[1]["prior_score"] = 10.0
cands[0]["standing"] = 90.0
cands[1]["standing"] = 10.0
records = [{"kind": "attempt", "id": "e%d" % i, "type": "read", "difficulty": 1,
"worker": "tool/alpha-1", "outcome": "accepted", "check": "tests"}
for i in range(9)]
+154
View File
@@ -0,0 +1,154 @@
"""Two scales kept apart (benchmark standing, measured accepted rate) and prices as published (input and output,
blended for ranking). Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3, R-7.3-1. Workers are host-native (bare ids from
the ledger) so no command-line tool is needed."""
import json, os, time, unittest
from support import *
class FactsCase(SisiCase):
def seed(self, workers, kind="read", difficulty=1, n=1):
os.makedirs(self.data, exist_ok=True)
with open(os.path.join(self.data, "delegations.jsonl"), "a") as f:
for w in workers:
for i in range(n):
f.write(json.dumps({"kind": "attempt", "id": "%s-%d-%s-%d" % (w, i, kind, difficulty), "ts": round(time.time()) - i,
"project": "p", "type": kind, "difficulty": difficulty, "worker": w,
"outcome": "accepted", "check": "tests", "minutes": 1}) + "\n")
def run_sisi(self, *args):
r = self.sisi(*args, env=dict(PATH=""))
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r
def stored(self, name):
return json.load(open(os.path.join(self.data, name)))
class StandingFieldTests(FactsCase):
LEGACY = {"models": {"wk-a": {"score": 64.5, "source": "fixture board https://example.test/x read 2000-01-01", "date": "2000-01-01"},
"wk-b": {"score": 40, "source": "fixture board", "date": "2000-01-02", "maker": "mk"}}}
def write_legacy(self):
os.makedirs(self.data, exist_ok=True)
json.dump(self.LEGACY, open(os.path.join(self.data, "model-strength.json"), "w"))
def test_existing_score_facts_move_to_standing_with_their_sources(self):
"""R-7.2-3: `sisi workers` renames each stored score to standing, keeping source, date and maker; repeating it
changes nothing."""
self.seed(["wk-a", "wk-b"])
self.write_legacy()
self.run_sisi("workers")
got = self.stored("model-strength.json")["models"]
self.assertEqual(got["wk-a"], {"standing": 64.5, "source": self.LEGACY["models"]["wk-a"]["source"], "date": "2000-01-01"})
self.assertEqual(got["wk-b"], {"standing": 40, "source": "fixture board", "date": "2000-01-02", "maker": "mk"})
before = open(os.path.join(self.data, "model-strength.json")).read()
self.run_sisi("workers")
self.assertEqual(open(os.path.join(self.data, "model-strength.json")).read(), before)
def test_routing_reads_an_unmigrated_score_fact(self):
"""Nothing is lost if `sisi route` runs before the migration: the old field is read as standing."""
self.seed(["wk-a", "wk-b"])
self.write_legacy()
self.run_sisi("workers", "fact", "wk-a", "--price", "9", "--source", "fixture")
self.run_sisi("workers", "fact", "wk-b", "--price", "1", "--source", "fixture")
# restore the legacy file: fact above may have migrated it
self.write_legacy()
r = self.run_sisi("route", "--kind", "read", "--difficulty", "3", "--explain")
self.assertEqual(r.stdout.splitlines()[0], "wk-a") # 40 is under 85 percent of 64.5
self.assertIn("benchmark standing", r.stdout)
def test_fact_standing_and_the_old_score_flag_both_store_standing(self):
"""R-7.2-3: the stored fact has its own name; --score stays as an alias."""
self.run_sisi("workers", "fact", "wk-a", "--standing", "70", "--source", "fixture board")
self.run_sisi("workers", "fact", "wk-b", "--score", "55", "--source", "fixture board")
got = self.stored("model-strength.json")["models"]
self.assertEqual(got["wk-a"]["standing"], 70)
self.assertEqual(got["wk-b"]["standing"], 55)
self.assertNotIn("score", got["wk-a"])
self.assertNotIn("score", got["wk-b"])
bad = self.sisi("workers", "fact", "wk-a", "--standing", "101", "--source", "x", env=dict(PATH=""))
self.assertNotEqual(bad.returncode, 0)
def test_workers_shows_standing_and_accepted_rate_under_their_own_names(self):
self.seed(["wk-a"], kind="read", difficulty=1, n=9)
self.run_sisi("workers", "fact", "wk-a", "--standing", "64.5", "--source", "fixture board", "--date", "2000-01-01")
out = self.run_sisi("workers").stdout
self.assertIn("benchmark standing 64.5", out)
self.assertIn("fixture board", out)
self.assertIn("Accepted rate", out)
self.assertNotIn("score", out.lower().replace("scorecard", ""))
def test_the_session_line_compares_standing_with_standing_only(self):
"""A worker measured at 100 percent accepted with a low standing is not 'among the strongest' on the strength
of that rate; a worker with a record but no standing has no standing to compare."""
from sisi import routing, workers
cands = [{"worker": "wk-a", "model": "wk-a", "standing": 40.0, "aliases": ["wk-a"]},
{"worker": "wk-b", "model": "wk-b", "standing": 60.0, "aliases": ["wk-b"]},
{"worker": "wk-c", "model": "wk-c", "standing": None, "aliases": ["wk-c"]}]
recs = [{"kind": "attempt", "id": "r%d" % i, "type": "read", "difficulty": 1, "worker": w, "outcome": "accepted"}
for w in ("wk-a", "wk-c") for i in range(20)]
os.makedirs(self.data, exist_ok=True)
json.dump({"models": {"wk-a": {"standing": 40, "source": "s"}, "wk-b": {"standing": 60, "source": "s"}}},
open(os.path.join(self.data, "model-strength.json"), "w"))
got = workers.strength_scores(cands)
self.assertEqual({w: s for w, (s, _how) in got.items()}, {"wk-a": 40.0, "wk-b": 60.0})
self.assertIn("benchmark standing", got["wk-a"][1])
class PriceTests(FactsCase):
def setUp(self):
super().setUp()
self.seed(["wk-a", "wk-b"])
def route(self, difficulty="1"):
return self.run_sisi("route", "--kind", "read", "--difficulty", difficulty, "--explain").stdout
def test_input_and_output_prices_are_stored_as_published(self):
"""R-7.3-1."""
self.run_sisi("workers", "fact", "wk-a", "--price-in", "1", "--price-out", "9", "--source", "fixture price list")
e = self.stored("worker-prices.json")["models"]["wk-a"]
self.assertEqual((e["price_in"], e["price_out"], e["source"]), (1, 9, "fixture price list"))
self.assertNotIn("cost_per_million_tokens", e)
bad = self.sisi("workers", "fact", "wk-a", "--price-in", "1", "--source", "x", env=dict(PATH=""))
self.assertNotEqual(bad.returncode, 0) # both or neither
both = self.sisi("workers", "fact", "wk-a", "--price", "2", "--price-in", "1", "--price-out", "9", "--source", "x", env=dict(PATH=""))
self.assertNotEqual(both.returncode, 0)
def test_a_single_blended_price_still_works_and_replaces_an_input_output_pair(self):
self.run_sisi("workers", "fact", "wk-a", "--price-in", "1", "--price-out", "9", "--source", "s")
self.run_sisi("workers", "fact", "wk-a", "--price", "2", "--source", "s")
e = self.stored("worker-prices.json")["models"]["wk-a"]
self.assertEqual(e["cost_per_million_tokens"], 2)
self.assertNotIn("price_in", e)
def test_ranking_uses_the_blend_three_input_to_one_output(self):
"""wk-a: 1 in, 9 out blends to 3 at 3:1; wk-b: a single blended 3.5. wk-a is cheaper by the default ratio."""
self.run_sisi("workers", "fact", "wk-a", "--price-in", "1", "--price-out", "9", "--source", "s")
self.run_sisi("workers", "fact", "wk-b", "--price", "3.5", "--source", "s")
self.assertEqual(self.route().splitlines()[0], "wk-a")
def test_the_blend_ratio_is_configurable(self):
"""At 1:1 wk-a blends to 5, dearer than wk-b's 3.5."""
self.run_sisi("workers", "fact", "wk-a", "--price-in", "1", "--price-out", "9", "--source", "s")
self.run_sisi("workers", "fact", "wk-b", "--price", "3.5", "--source", "s")
json.dump({"route": {"price_blend_input_parts": 1}}, open(os.path.join(self.data, "config.json"), "w"))
self.assertEqual(self.route().splitlines()[0], "wk-b")
def test_workers_shows_both_prices_and_the_blend(self):
self.run_sisi("workers", "fact", "wk-a", "--price-in", "2", "--price-out", "10", "--source", "fixture price list")
out = self.run_sisi("workers").stdout
self.assertIn("wk-a", out)
self.assertIn("2 in", out)
self.assertIn("10 out", out)
self.assertIn("blended 4", out)
def test_estimated_cost_uses_the_blend(self):
from sisi import workers
self.assertEqual(workers.estimate_cost(2000000, {"price_in": 1, "price_out": 9}), 6.0)
self.assertEqual(workers.estimate_cost(2000000, {"cost_per_million_tokens": 2}), 4.0)
self.assertEqual(workers.estimate_cost(2000000, {"cost": 3}), 6.0)
self.assertIsNone(workers.estimate_cost(2000000, {"price_in": 1}))
if __name__ == "__main__":
unittest.main()