Item 3: the newest usable version of a maker's class always wins; an older one never competes while it is usable (no evidence or price exception); route.supersede_guessed; one line asks the lead agent to record a class that cannot be read. done / next: inherited records (item 4)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8141d2e281
commit
d4ef00c4c0
6 files changed
+433
-31
No files matched your search
+2
-1
@@ -17,7 +17,8 @@
|
||||
"2": 60,
|
||||
"3": 85
|
||||
},
|
||||
"price_blend_input_parts": 3
|
||||
"price_blend_input_parts": 3,
|
||||
"supersede_guessed": true
|
||||
},
|
||||
"unit": {
|
||||
"stale_hours": 12
|
||||
|
||||
+95
-23
@@ -44,7 +44,12 @@ The rule, in order:
|
||||
6. About one low-stakes task in ten (difficulty 1, every tenth judged attempt for that kind and
|
||||
difficulty) goes to a cheaper worker with a thin record instead, so cheaper options keep
|
||||
gathering evidence. The slot is a function of the record, so the choice stays deterministic.
|
||||
7. Load balancing: within the same price tier and price, the worker that has taken the least work
|
||||
7. The newest usable version of a maker's class always wins over its older versions (see
|
||||
`superseded_by`): no better record and no cheaper plan on the older version brings it back.
|
||||
The older one competes again only while the newer one is unusable. The class is read from the
|
||||
id and overridden by what the lead agent recorded (sisi/modelid.py); a model whose class is
|
||||
unknown is never compared.
|
||||
8. Load balancing: within the same price tier and price, the worker that has taken the least work
|
||||
relative to its remaining allowance goes first (recorded uses divided by allowance left, an
|
||||
unknown allowance counting as half). Ties break on the worker id.
|
||||
|
||||
@@ -54,6 +59,8 @@ usable worker is offered, with the explanation saying so.
|
||||
"""
|
||||
import re
|
||||
|
||||
from . import modelid
|
||||
|
||||
MIN_ATTEMPTS = 8 # below this, a worker's record for a kind and difficulty is thin
|
||||
MIN_ACCEPTED_RATE = 0.6 # "good enough" among workers with at least MIN_ATTEMPTS attempts
|
||||
CONTRADICTION_REJECTIONS = 2 # a thin record with this many rejections below the bar cancels a prior
|
||||
@@ -313,32 +320,71 @@ def _standing_of(c):
|
||||
# ---------------------------------------------------------------- the pool, then the choice
|
||||
|
||||
|
||||
def _prepare(candidates, records, availability, now, exclude, avoid, review_of):
|
||||
"""The workers that may be recommended at all: (eligible, passed, stats, author_maker)."""
|
||||
def _unusable(c, availability, now):
|
||||
"""Why a candidate cannot be used right now (plain words), or None."""
|
||||
if "contributor" in str(c.get("model") or c["worker"]).lower():
|
||||
return "its id contains 'contributor', a tier that trains on prompts"
|
||||
down = _down_entry(c, availability, now)
|
||||
if down is not None:
|
||||
return "unavailable (%s) until its retry time" % (down.get("reason") or "down")
|
||||
if not c.get("usable", True):
|
||||
return c.get("reason") or "not usable now"
|
||||
if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0:
|
||||
return "its flat-rate allowance is spent"
|
||||
return None
|
||||
|
||||
|
||||
def _lineage(c):
|
||||
l = c.get("lineage")
|
||||
return l if isinstance(l, dict) else None
|
||||
|
||||
|
||||
def _comparable(c, opts):
|
||||
"""The model's lineage when its class takes part in comparisons of versions: a class that could not be read
|
||||
is never compared, and (with `supersede_guessed` off) neither is one that was only read from the id."""
|
||||
l = _lineage(c)
|
||||
if l and l.get("key") and (l.get("source") == "fact" or (opts or {}).get("supersede_guessed", True)):
|
||||
return l
|
||||
return None
|
||||
|
||||
|
||||
def superseded_by(pool, opts=None):
|
||||
"""{worker: the newest worker of its maker and class that replaces it}, over the usable `pool`. Workers
|
||||
that share a maker, a line and a class are versions of one model whichever provider carries them; the
|
||||
older version is replaced by the newest one whatever its record or price. Pure."""
|
||||
groups = {}
|
||||
for c in pool:
|
||||
l = _comparable(c, opts)
|
||||
if l:
|
||||
groups.setdefault(tuple(l["key"]), []).append(c)
|
||||
out = {}
|
||||
for group in groups.values():
|
||||
for c in group:
|
||||
newer = [d for d in group if modelid.compare(_lineage(d), _lineage(c)) > 0]
|
||||
if newer:
|
||||
out[c["worker"]] = min(newer, key=lambda d: (modelid.recency_key(_lineage(d)), d["worker"]))["worker"]
|
||||
return out
|
||||
|
||||
|
||||
def _prepare(candidates, records, availability, now, exclude, avoid, review_of, opts=None):
|
||||
"""The workers that may be recommended at all: (eligible, passed, stats, author_maker, superseded)."""
|
||||
exclude = {str(x) for x in exclude}
|
||||
stats = candidate_stats(candidates, records)
|
||||
passed = []
|
||||
eligible = []
|
||||
tried = [] # usable workers already tried in this delegation: still the newest version, so older ones stay out
|
||||
|
||||
for c in candidates:
|
||||
w = c["worker"]
|
||||
why = _unusable(c, availability, now)
|
||||
if w in exclude:
|
||||
passed.append((w, "already tried in this delegation"))
|
||||
continue
|
||||
if "contributor" in str(c.get("model") or w).lower():
|
||||
passed.append((w, "its id contains 'contributor', a tier that trains on prompts"))
|
||||
continue
|
||||
down = _down_entry(c, availability, now)
|
||||
if down is not None:
|
||||
passed.append((w, "unavailable (%s) until its retry time" % (down.get("reason") or "down")))
|
||||
continue
|
||||
if not c.get("usable", True):
|
||||
passed.append((w, c.get("reason") or "not usable now"))
|
||||
continue
|
||||
if c.get("plan") == "flat" and c.get("allowance_pct_left") == 0:
|
||||
passed.append((w, "its flat-rate allowance is spent"))
|
||||
continue
|
||||
eligible.append(c)
|
||||
if why is None:
|
||||
tried.append(c)
|
||||
elif why is not None:
|
||||
passed.append((w, why))
|
||||
else:
|
||||
eligible.append(c)
|
||||
|
||||
avoided = [(c, _pattern_match(c, avoid)) for c in eligible]
|
||||
kept = [c for c, m in avoided if m is None]
|
||||
@@ -349,6 +395,7 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of):
|
||||
passed.append((c["worker"], "avoided by the user's own pattern %r%s"
|
||||
% (pat, (" (%s)" % why) if why else "")))
|
||||
eligible = kept
|
||||
tried = [c for c in tried if _pattern_match(c, avoid) is None]
|
||||
|
||||
author_maker = ""
|
||||
if review_of:
|
||||
@@ -366,7 +413,15 @@ def _prepare(candidates, records, availability, now, exclude, avoid, review_of):
|
||||
else:
|
||||
rest.append(c)
|
||||
eligible = rest
|
||||
return eligible, passed, stats, author_maker
|
||||
tried = [c for c in tried if (c.get("maker") or maker_of(c.get("model") or c["worker"])) != author_maker]
|
||||
|
||||
superseded = superseded_by(eligible + tried, opts)
|
||||
if superseded:
|
||||
for c in eligible:
|
||||
if c["worker"] in superseded:
|
||||
passed.append((c["worker"], "superseded by %s (a newer version of the same class)" % superseded[c["worker"]]))
|
||||
eligible = [c for c in eligible if c["worker"] not in superseded]
|
||||
return eligible, passed, stats, author_maker, superseded
|
||||
|
||||
|
||||
def _assess_all(eligible, stats, kind, difficulty, floors):
|
||||
@@ -440,12 +495,13 @@ def _select(eligible, assessments, difficulty):
|
||||
|
||||
|
||||
def choose(candidates, records, availability, kind, difficulty, review_of=None, now=0.0, exclude=(),
|
||||
avoid=None, prefer=None, floors=None):
|
||||
avoid=None, prefer=None, floors=None, opts=None):
|
||||
"""Pick one candidate, or none. Returns {"choice", "passed_over", "stats", "author_maker", ...}.
|
||||
`passed_over` is [(worker, plain reason)] covering every candidate not chosen. `avoid` and
|
||||
`prefer` are the user's own [{"pattern", "why"}] constraints; `floors` the standing floors."""
|
||||
now = float(now or 0)
|
||||
eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of)
|
||||
eligible, passed, stats, author_maker, superseded = _prepare(candidates, records, availability, now, exclude,
|
||||
avoid, review_of, opts)
|
||||
assessments, best = _assess_all(eligible, stats, kind, difficulty, floors)
|
||||
key, rate, load_ratio = _make_key(stats, kind, difficulty, prefer)
|
||||
|
||||
@@ -511,9 +567,24 @@ def choose(candidates, records, availability, kind, difficulty, review_of=None,
|
||||
"load_ratios": {c["worker"]: load_ratio(c) for c in candidates},
|
||||
"assessments": assessments, "basis": basis, "capable_count": capable_n, "judged_first": judged_first,
|
||||
"best_standing": best, "passed_detail": detail, "floors": floors,
|
||||
"superseded": superseded, "class_ask": class_ask(eligible),
|
||||
"kind": kind, "difficulty": difficulty}
|
||||
|
||||
|
||||
def class_ask(eligible):
|
||||
"""What the lead agent should be asked to record, because it is about to matter: {"classify": [workers]}.
|
||||
A worker whose class could not be read from its id, when another usable worker has the same maker (the two
|
||||
may be versions of one class). A class read from the id with confidence is not asked about; a recorded one
|
||||
never is."""
|
||||
makers = {}
|
||||
for c in eligible:
|
||||
l = _lineage(c)
|
||||
if l:
|
||||
makers.setdefault(l.get("maker"), []).append(c["worker"])
|
||||
return {"classify": sorted(c["worker"] for c in eligible if _lineage(c)
|
||||
and _lineage(c).get("source") == "unknown" and len(makers.get(_lineage(c).get("maker"), [])) > 1)}
|
||||
|
||||
|
||||
def _why_not(a, difficulty, basis, cheaper):
|
||||
"""(plain reason, short per-worker detail) for a worker kept out of the pool by what is known
|
||||
about its capability. The reason text is the same for every worker it applies to, so reasons group."""
|
||||
@@ -553,7 +624,7 @@ def _why_not(a, difficulty, basis, cheaper):
|
||||
|
||||
|
||||
def retry_choice(candidates, records, availability, kind, difficulty, rejected, rejections,
|
||||
now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=None):
|
||||
now=0.0, exclude=(), avoid=None, prefer=None, floors=None, review_of=None, opts=None):
|
||||
"""Who gets a task again after `rejected` (a worker id) was rejected `rejections` times in this chain.
|
||||
The first retry goes back to the same worker while it is still usable and has no poor record.
|
||||
After that: the cheapest capable worker whose evidence is strictly better than the rejected one's, or, when there is none,
|
||||
@@ -561,7 +632,8 @@ def retry_choice(candidates, records, availability, kind, difficulty, rejected,
|
||||
else is usable). Returns {"choice", "step", "assessments", ...}; step is "same", "better",
|
||||
"strongest" or "only", and choice is None when nobody is usable. Pure; the caller supplies facts."""
|
||||
now = float(now or 0)
|
||||
eligible, passed, stats, author_maker = _prepare(candidates, records, availability, now, exclude, avoid, review_of)
|
||||
eligible, passed, stats, author_maker, _superseded = _prepare(candidates, records, availability, now, exclude,
|
||||
avoid, review_of, opts)
|
||||
assessments, best = _assess_all(eligible, stats, kind, difficulty, floors)
|
||||
key, _rate, _load = _make_key(stats, kind, difficulty, prefer)
|
||||
out = {"choice": None, "step": None, "passed_over": passed, "stats": stats, "author_maker": author_maker,
|
||||
|
||||
+24
-2
@@ -596,6 +596,13 @@ def model_words():
|
||||
return _WORDS[0]
|
||||
|
||||
|
||||
def route_opts():
|
||||
"""Routing options from the config: `route.supersede_guessed` (default true) lets a class read from the id with
|
||||
confidence, not yet recorded by the lead agent, take part in the rule that the newest version of a class wins."""
|
||||
v = route_cfg().get("supersede_guessed")
|
||||
return {"supersede_guessed": v if isinstance(v, bool) else True}
|
||||
|
||||
|
||||
def route_floors():
|
||||
"""{difficulty: percent of the best usable standing needed} from `route.standing_floor`."""
|
||||
return routing.standing_floors(route_cfg().get("standing_floor"))
|
||||
@@ -1203,7 +1210,8 @@ def run_delegation(candidates, kind, difficulty, prompt, cwd, explicit=None, rev
|
||||
prefs = effective_prefs(kind, difficulty, cwd)
|
||||
result = routing.choose(candidates, read_records(), read_availability(), kind, difficulty,
|
||||
review_of=review_of, now=time.time(), exclude=tried,
|
||||
avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors())
|
||||
avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(),
|
||||
opts=route_opts())
|
||||
cand = result["choice"]
|
||||
if cand is None:
|
||||
notes.append("sisi: no usable worker remains for kind %s at difficulty %s" % (kind, difficulty))
|
||||
@@ -1572,6 +1580,16 @@ def _route_setup(args):
|
||||
return kind, difficulty
|
||||
|
||||
|
||||
def class_line(result):
|
||||
"""The one line asking the lead agent to determine a class sisi cannot read from the id, or None."""
|
||||
names = (result.get("class_ask") or {}).get("classify") or []
|
||||
if not names:
|
||||
return None
|
||||
return ("sisi: the class of %s%s cannot be read from its id: decide it and record it with "
|
||||
"`sisi workers fact %s --class NAME --source S` (until then it is never compared with a newer or older version)"
|
||||
% (names[0], (" and %d more" % (len(names) - 1)) if len(names) > 1 else "", names[0]))
|
||||
|
||||
|
||||
def cmd_route(args=()):
|
||||
setup = _route_setup(args)
|
||||
if setup is None:
|
||||
@@ -1585,7 +1603,8 @@ def cmd_route(args=()):
|
||||
candidates, limited = apply_limits(candidates, prefs)
|
||||
result = routing.choose(candidates, records, read_availability(), kind, difficulty,
|
||||
review_of=_opt(args, "--review-of"), now=time.time(),
|
||||
avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors())
|
||||
avoid=prefs["avoid"], prefer=prefs["prefer"], floors=route_floors(),
|
||||
opts=route_opts())
|
||||
result["passed_over"] = list(result["passed_over"]) + limited
|
||||
by_worker = {c["worker"]: c for c in everyone}
|
||||
down = _down_now(read_availability(), time.time())
|
||||
@@ -1611,6 +1630,9 @@ def cmd_route(args=()):
|
||||
for line in notes_for(by_worker, result["choice"], result["passed_over"] if explain else [],
|
||||
limit=5 if explain else max(1, 5 - head)):
|
||||
print(line)
|
||||
ask = class_line(result)
|
||||
if ask:
|
||||
print(ask)
|
||||
if explain:
|
||||
for line in routing.explain_choice(result, kind, difficulty):
|
||||
print(line)
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""The newest usable version of a maker's class always wins over its older versions (hard rule), however good the
|
||||
older record or cheap its plan. Pure routing tests over invented ids shaped like real ones.
|
||||
Requirement ids: R-7.2-1, R-7.2-2, R-7.2-3."""
|
||||
import json, os, random, unittest
|
||||
from support import *
|
||||
from sisi import modelid, routing
|
||||
|
||||
WORDS = json.load(open(os.path.join(REPO, "canon", "model-words.json")))
|
||||
NOW = 1000000.0
|
||||
|
||||
|
||||
def cand(worker, plan="per-use", cost=1.0, fact=None, host_native=False, standing=None, **kw):
|
||||
model = worker.rsplit("/", 1)[-1]
|
||||
c = {"worker": worker, "tool": worker.split("/")[0] if "/" in worker else None, "model": model, "maker": "abc",
|
||||
"plan": plan, "cost": cost, "allowance_pct_left": None, "usable": True, "standing": standing,
|
||||
"aliases": [worker, model], "lineage": modelid.resolve(worker, WORDS, fact=fact, host_native=host_native)}
|
||||
c.update(kw)
|
||||
return c
|
||||
|
||||
|
||||
def attempts(worker, n, good, kind="impl", difficulty=1, start=0):
|
||||
return [{"kind": "attempt", "id": "%s-%d-%d" % (worker, difficulty, start + i), "type": kind, "difficulty": difficulty,
|
||||
"worker": worker, "outcome": "accepted" if i < good else "rejected", "check": "tests", "ts": NOW - 10}
|
||||
for i in range(n)]
|
||||
|
||||
|
||||
def pick(cands, records=(), difficulty=1, availability=None, **kw):
|
||||
r = routing.choose(cands, list(records), availability or {}, "impl", difficulty, now=NOW, **kw)
|
||||
return (r["choice"] or {}).get("worker"), r
|
||||
|
||||
|
||||
class SupersessionTests(unittest.TestCase):
|
||||
def test_the_newer_version_wins_over_an_older_one_with_a_better_record_and_a_cheaper_plan(self):
|
||||
"""The owner's rule: no evidence exception, no price exception."""
|
||||
old = cand("prov/abc-5.3", plan="flat", cost=0.0)
|
||||
new = cand("prov/abc-5.4", plan="per-use", cost=9.0)
|
||||
records = attempts("prov/abc-5.3", 30, 30, difficulty=1)
|
||||
who, r = pick([old, new], records)
|
||||
self.assertEqual(who, "prov/abc-5.4")
|
||||
self.assertIn(("prov/abc-5.3", "superseded by prov/abc-5.4 (a newer version of the same class)"), r["passed_over"])
|
||||
|
||||
def test_numeric_version_order(self):
|
||||
self.assertEqual(pick([cand("prov/abc-5.9"), cand("prov/abc-5.10")])[0], "prov/abc-5.10")
|
||||
self.assertEqual(pick([cand("prov/abc-5.3"), cand("prov/abc-5-4-20261101")])[0], "prov/abc-5-4-20261101")
|
||||
|
||||
def test_the_tier_word_before_or_after_the_version_is_one_class(self):
|
||||
self.assertEqual(pick([cand("prov/abc-5.3-flash"), cand("prov/abc-flash-5.4")])[0], "prov/abc-flash-5.4")
|
||||
|
||||
def test_different_classes_never_supersede_each_other(self):
|
||||
flash, std = cand("prov/abc-5.3-flash", cost=0.1), cand("prov/abc-5.4", cost=5.0)
|
||||
who, r = pick([flash, std])
|
||||
self.assertEqual(who, "prov/abc-5.3-flash") # the cheaper class still competes
|
||||
self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")])
|
||||
|
||||
def test_two_named_lines_of_one_maker_are_different_classes(self):
|
||||
a, b = cand("prov/abc-wonder-1.0", cost=1.0), cand("prov/abc-ember-1.3", cost=2.0)
|
||||
who, r = pick([a, b])
|
||||
self.assertEqual(who, "prov/abc-wonder-1.0")
|
||||
self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")])
|
||||
|
||||
def test_unknown_class_never_supersedes_or_is_superseded(self):
|
||||
a, b = cand("prov/abc-6.2-sol", cost=1.0), cand("prov/abc-6.3-sol", cost=2.0)
|
||||
self.assertIsNone(a["lineage"]["key"])
|
||||
who, r = pick([a, b])
|
||||
self.assertEqual(who, "prov/abc-6.2-sol")
|
||||
self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")])
|
||||
|
||||
def test_a_recorded_class_makes_an_unknown_one_comparable(self):
|
||||
fact = {"class": "sol", "maker": "abc"}
|
||||
a, b = cand("prov/abc-6.2-sol", fact=fact, cost=1.0), cand("prov/abc-6.3-sol", fact=fact, cost=2.0)
|
||||
self.assertEqual(pick([a, b])[0], "prov/abc-6.3-sol")
|
||||
|
||||
def test_the_newer_one_unusable_lets_the_older_compete_again(self):
|
||||
old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0)
|
||||
self.assertEqual(pick([old, new], availability={"prov/abc-5.4": {"reason": "limit", "retry_at": NOW + 99}})[0], "prov/abc-5.3")
|
||||
new2 = dict(new, usable=False, reason="not logged in")
|
||||
self.assertEqual(pick([old, new2])[0], "prov/abc-5.3")
|
||||
self.assertEqual(pick([old, new], avoid=[{"pattern": "5.4"}])[0], "prov/abc-5.3")
|
||||
spent = dict(new, plan="flat", allowance_pct_left=0)
|
||||
self.assertEqual(pick([old, spent])[0], "prov/abc-5.3")
|
||||
|
||||
def test_a_tried_newer_version_does_not_send_a_retry_back_to_the_older(self):
|
||||
old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0)
|
||||
who, r = pick([old, new], exclude=["prov/abc-5.4"])
|
||||
self.assertIsNone(who)
|
||||
|
||||
def test_a_newer_version_with_a_thick_bad_record_never_sends_work_back_to_the_older(self):
|
||||
old, new, other = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0), cand("prov/xyz-2.0", cost=3.0, maker="xyz")
|
||||
records = attempts("prov/abc-5.4", 10, 1, difficulty=1) + attempts("prov/xyz-2.0", 10, 10, difficulty=1)
|
||||
who, r = pick([old, new, other], records)
|
||||
self.assertEqual(who, "prov/xyz-2.0")
|
||||
who, r = pick([old, new], records)
|
||||
self.assertEqual(who, "prov/abc-5.4") # nobody else: the bad newer model is still not replaced by the older
|
||||
|
||||
def test_the_same_model_through_two_providers_is_one_model(self):
|
||||
old_a = cand("prova/abc-5.3", plan="flat", cost=0.0)
|
||||
new_a, new_b = cand("prova/abc-5.4", cost=5.0), cand("provb/abc-5.4", cost=2.0)
|
||||
who, r = pick([old_a, new_a, new_b])
|
||||
self.assertEqual(who, "provb/abc-5.4") # the existing cost comparison picks the provider
|
||||
self.assertEqual(sorted(w for w, why in r["passed_over"] if why.startswith("superseded")), ["prova/abc-5.3"])
|
||||
who, _ = pick([old_a, new_a, new_b], availability={"provb": {"reason": "limit", "retry_at": NOW + 9}})
|
||||
self.assertEqual(who, "prova/abc-5.4")
|
||||
|
||||
def test_a_bare_host_alias_with_a_recorded_class_is_the_newest(self):
|
||||
alias = cand("abc", fact={"class": "standard", "maker": "abc"}, host_native=True, cost=9.0)
|
||||
versioned = cand("prov/abc-9.9", cost=0.1)
|
||||
self.assertEqual(pick([alias, versioned])[0], "abc")
|
||||
bare = cand("abc", host_native=True, cost=9.0) # class not recorded: no comparison
|
||||
self.assertEqual(pick([bare, versioned])[0], "prov/abc-9.9")
|
||||
|
||||
def test_guessed_classes_take_part_unless_the_config_says_only_recorded_ones(self):
|
||||
old, new = cand("prov/abc-5.3", cost=1.0), cand("prov/abc-5.4", cost=2.0)
|
||||
self.assertEqual(pick([old, new])[0], "prov/abc-5.4")
|
||||
self.assertEqual(pick([old, new], opts={"supersede_guessed": False})[0], "prov/abc-5.3")
|
||||
fact = {"class": "standard"}
|
||||
old_r, new_r = cand("prov/abc-5.3", fact=fact, cost=1.0), cand("prov/abc-5.4", fact=fact, cost=2.0)
|
||||
self.assertEqual(pick([old_r, new_r], opts={"supersede_guessed": False})[0], "prov/abc-5.4")
|
||||
|
||||
def test_the_asking_line_is_only_for_a_class_that_could_not_be_read(self):
|
||||
a, b = cand("prov/abc-6.2-sol", cost=1.0), cand("prov/abc-6.3-luna", cost=2.0)
|
||||
r = pick([a, b])[1]
|
||||
self.assertEqual(sorted(r["class_ask"]["classify"]), ["prov/abc-6.2-sol", "prov/abc-6.3-luna"])
|
||||
lone = pick([cand("prov/abc-6.2-sol"), cand("prov/xyz-1.0", maker="xyz")])[1]
|
||||
self.assertEqual(lone["class_ask"]["classify"], []) # no sibling of the same maker: it cannot matter
|
||||
guessed = pick([cand("prov/abc-5.3"), cand("prov/abc-5.4")])[1]
|
||||
self.assertEqual(guessed["class_ask"]["classify"], []) # read with confidence: no question
|
||||
fact = {"class": "sol", "maker": "abc"}
|
||||
settled = pick([cand("prov/abc-6.2-sol", fact=fact), cand("prov/abc-6.3-luna", fact=fact)])[1]
|
||||
self.assertEqual(settled["class_ask"]["classify"], [])
|
||||
|
||||
|
||||
class SupersessionPropertyTests(unittest.TestCase):
|
||||
def fleet(self, rng):
|
||||
cands, records, down = [], [], {}
|
||||
for maker in rng.sample(["abc", "xyz", "qrs"], rng.randint(1, 3)):
|
||||
for cls in rng.sample(["", "-flash", "-mini", "-wonder", "-pro"], rng.randint(1, 3)):
|
||||
for ver in rng.sample(["5.3", "5.4", "5.9", "5.10", "6", "5-4-20261101", "5.4-20250101"], rng.randint(1, 4)):
|
||||
for prov in rng.sample(["pa", "pb"], rng.randint(1, 2)):
|
||||
w = "%s/%s%s-%s" % (prov, maker, cls, ver)
|
||||
if cls == "-wonder":
|
||||
w = "%s/%s-wonder-%s" % (prov, maker, ver)
|
||||
if any(c["worker"] == w for c in cands):
|
||||
continue
|
||||
cands.append(cand(w, plan=rng.choice(["flat", "per-use", None]),
|
||||
cost=rng.choice([None, 0.1, 1.0, 5.0]), maker=maker,
|
||||
allowance_pct_left=rng.choice([None, 0, 50])))
|
||||
if rng.random() < 0.15:
|
||||
down[w] = {"reason": "limit", "retry_at": NOW + 99}
|
||||
for d in (1, 2, 3):
|
||||
if rng.random() < 0.5:
|
||||
n = rng.choice([3, 10, 12])
|
||||
records += attempts(w, n, rng.randint(0, n), difficulty=d)
|
||||
return cands, records, down
|
||||
|
||||
def usable(self, c, down):
|
||||
return c["worker"] not in down and not (c["plan"] == "flat" and c["allowance_pct_left"] == 0)
|
||||
|
||||
def test_the_chosen_worker_is_never_an_older_version_of_a_class_with_a_newer_usable_version(self):
|
||||
"""Property: whatever the fleet, ledger, plans and availability."""
|
||||
rng = random.Random(20261123)
|
||||
checked = 0
|
||||
for _ in range(300 * ITERS):
|
||||
cands, records, down = self.fleet(rng)
|
||||
if not cands:
|
||||
continue
|
||||
d = rng.choice([1, 2, 3])
|
||||
who, r = pick(cands, records, d, availability=down)
|
||||
if who is None:
|
||||
continue
|
||||
chosen = next(c for c in cands if c["worker"] == who)
|
||||
lc = chosen["lineage"]
|
||||
for c in cands:
|
||||
if c is chosen or not self.usable(c, down):
|
||||
continue
|
||||
lo = c["lineage"]
|
||||
if lo["key"] == lc["key"]:
|
||||
self.assertLessEqual(modelid.compare(lo, lc), 0, (who, c["worker"]))
|
||||
checked += 1
|
||||
for w, why in r["passed_over"]:
|
||||
if why.startswith("superseded by "):
|
||||
newer = why[len("superseded by "):].split(" ")[0]
|
||||
a = next(c for c in cands if c["worker"] == w)["lineage"]
|
||||
b = next(c for c in cands if c["worker"] == newer)["lineage"]
|
||||
self.assertEqual(a["key"], b["key"], "a model never supersedes one of another maker or class")
|
||||
self.assertGreater(modelid.compare(b, a), 0)
|
||||
self.assertGreater(checked, 100)
|
||||
|
||||
def test_adding_a_newer_version_of_the_chosen_model_never_makes_the_choice_an_older_model_of_that_class(self):
|
||||
rng = random.Random(77)
|
||||
done = 0
|
||||
for _ in range(200 * ITERS):
|
||||
cands, records, down = self.fleet(rng)
|
||||
if not cands:
|
||||
continue
|
||||
d = rng.choice([1, 2, 3])
|
||||
who, _r = pick(cands, records, d, availability=down)
|
||||
if who is None:
|
||||
continue
|
||||
chosen = next(c for c in cands if c["worker"] == who)
|
||||
lc = chosen["lineage"]
|
||||
if not lc["version"] or lc["date"]:
|
||||
continue
|
||||
ver = ".".join(str(x) for x in lc["version"][:1] + (lc["version"][1] + 1 if len(lc["version"]) > 1 else 1,))
|
||||
prov = who.split("/")[0]
|
||||
maker = lc["maker"]
|
||||
tail = "" if lc["class"] == "standard" else "-" + lc["class"]
|
||||
new_w = "pc/%s%s-%s" % (maker, tail, ver) if lc["line"] == "" else None
|
||||
if new_w is None or any(c["worker"] == new_w for c in cands):
|
||||
continue
|
||||
new = cand(new_w, maker=chosen["maker"], cost=rng.choice([None, 0.1, 5.0]))
|
||||
if new["lineage"]["key"] != lc["key"] or modelid.compare(new["lineage"], lc) <= 0:
|
||||
continue
|
||||
after, _ = pick(cands + [new], records, d, availability=down)
|
||||
if after is None:
|
||||
continue
|
||||
got = next(c for c in cands + [new] if c["worker"] == after)["lineage"]
|
||||
if got["key"] == lc["key"]:
|
||||
self.assertGreaterEqual(modelid.compare(got, lc), 0, (who, after))
|
||||
done += 1
|
||||
self.assertGreater(done, 30)
|
||||
|
||||
def test_a_result_read_as_unknown_never_triggers_supersession(self):
|
||||
rng = random.Random(5)
|
||||
for _ in range(200 * ITERS):
|
||||
ids = ["prov/abc-%d.%d-%s" % (rng.randint(1, 9), rng.randint(0, 9), rng.choice(["sol", "luna", "astra"])) for _ in range(rng.randint(2, 5))]
|
||||
cands = [cand(w, cost=rng.choice([None, 1.0, 2.0])) for w in dict.fromkeys(ids)]
|
||||
who, r = pick(cands)
|
||||
self.assertFalse([w for w, why in r["passed_over"] if why.startswith("superseded")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -263,7 +263,9 @@ class RouteTests(OrchCase):
|
||||
self.assertIn("mechanism:", r.stdout)
|
||||
|
||||
def _big_catalogue(self, n=2000):
|
||||
names = ["m-%d" % i for i in range(n)] + ["contributor-%d" % i for i in range(40)]
|
||||
# letters only: a number in an id is a version, and the newest version of a class replaces the older ones
|
||||
names = ["mdl-%s" % "".join(chr(97 + (i // 26 ** k) % 26) for k in range(3)) for i in range(n)] \
|
||||
+ ["contributor-%d" % i for i in range(40)]
|
||||
script = FAKE_TOOL.replace('echo "beta-1"; echo "beta-2";', " ".join('echo "%s";' % x for x in names))
|
||||
with open(os.path.join(self.bindir, "muse"), "w") as f:
|
||||
f.write(script)
|
||||
@@ -272,7 +274,7 @@ class RouteTests(OrchCase):
|
||||
"""R-7.2-1: --explain prints at most 20 lines and 3 example names per reason group,
|
||||
and still shows every reason group, however many catalogue models were passed over."""
|
||||
self._big_catalogue()
|
||||
self.sisi("workers", "avoid", "m-7", "--why", "fixture avoid", env=self.env())
|
||||
self.sisi("workers", "avoid", "mdl-ab", "--why", "fixture avoid", env=self.env())
|
||||
r = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain", env=self.env())
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
lines = r.stdout.splitlines()
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
"""Model lines in the worker commands: the class a lead agent records beats the parser, and `sisi workers`
|
||||
shows maker, class and recency for each routable worker. Fixtures are invented ids shaped like real ones.
|
||||
Requirement ids: R-7.2-1, R-7.2-3."""
|
||||
import json, os, unittest
|
||||
import json, os, stat, unittest
|
||||
from support import *
|
||||
|
||||
FAKE_MUSE = """#!/bin/sh
|
||||
case "$1" in
|
||||
exec)
|
||||
if [ "$2" = "--list-models" ]; then for m in $MUSE_MODELS; do echo "$m"; done; exit 0; fi
|
||||
echo done ;;
|
||||
*) echo help ;;
|
||||
esac
|
||||
exit 0
|
||||
"""
|
||||
|
||||
|
||||
class ModelCase(SisiCase):
|
||||
def seed(self, spec, type="impl", difficulty=2):
|
||||
@@ -23,8 +33,20 @@ class ModelCase(SisiCase):
|
||||
p = os.path.join(self.data, "delegations.jsonl")
|
||||
return open(p).read().splitlines() if os.path.exists(p) else []
|
||||
|
||||
def env(self):
|
||||
return dict(PATH="")
|
||||
def env(self, models=None):
|
||||
"""No tool at all, or a fake `muse` tool that lists `models`."""
|
||||
if models is None:
|
||||
return dict(PATH="")
|
||||
bindir = os.path.join(self.tmp, "bin")
|
||||
os.makedirs(bindir, exist_ok=True)
|
||||
path = os.path.join(bindir, "muse")
|
||||
open(path, "w").write(FAKE_MUSE)
|
||||
os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
|
||||
return dict(PATH=bindir, MUSE_MODELS=" ".join(models))
|
||||
|
||||
def route(self, difficulty=1, *extra, models=("abc-5.3", "abc-5.4")):
|
||||
r = self.sisi("route", "--kind", "impl", "--difficulty", str(difficulty), *extra, env=self.env(models))
|
||||
return r
|
||||
|
||||
def listing(self):
|
||||
r = self.sisi("workers", env=self.env())
|
||||
@@ -70,5 +92,56 @@ class FactTests(ModelCase):
|
||||
self.assertNotIn("worker-models.json", out)
|
||||
|
||||
|
||||
class RouteSupersessionTests(ModelCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.priced = False
|
||||
|
||||
def route(self, difficulty=1, *extra, models=("abc-5.3", "abc-5.4")):
|
||||
if not self.priced: # a model is routable once it has a record, a price or a standing
|
||||
self.priced = True
|
||||
for w, price in (("muse/abc-5.3", "0.5"), ("muse/abc-5.4", "1")): # the older is the cheaper
|
||||
self.sisi("workers", "fact", w, "--price", price, "--source", "fixture", env=self.env(models))
|
||||
return super().route(difficulty, *extra, models=models)
|
||||
|
||||
def test_route_uses_the_newest_version_though_the_older_has_the_record(self):
|
||||
"""R-7.2-1: the newest usable version of a class is always taken; --explain says what it replaced."""
|
||||
self.seed([("muse/abc-5.3", 30, 30)], difficulty=1)
|
||||
r = self.route(1, "--explain")
|
||||
self.assertEqual(r.stdout.splitlines()[0], "muse/abc-5.4", r.stdout)
|
||||
self.assertIn("superseded by muse/abc-5.4", r.stdout)
|
||||
|
||||
def test_the_older_version_is_back_while_the_newer_is_marked_down(self):
|
||||
self.seed([("muse/abc-5.3", 30, 30)], difficulty=1)
|
||||
self.route(1)
|
||||
self.sisi("workers", "down", "muse/abc-5.4", "--reason", "limit", "--until", "2099-01-02", env=self.env(("abc-5.3", "abc-5.4")))
|
||||
self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.3")
|
||||
self.sisi("workers", "up", "muse/abc-5.4", env=self.env(("abc-5.3", "abc-5.4")))
|
||||
self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.4")
|
||||
|
||||
def test_only_recorded_classes_when_the_config_says_so(self):
|
||||
self.seed([("muse/abc-5.3", 30, 30)], difficulty=1)
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
json.dump({"route": {"supersede_guessed": False}}, open(os.path.join(self.data, "config.json"), "w"))
|
||||
self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.3")
|
||||
for w in ("muse/abc-5.3", "muse/abc-5.4"):
|
||||
self.sisi("workers", "fact", w, "--class", "standard", "--source", "lead", env=self.env(("abc-5.3", "abc-5.4")))
|
||||
self.assertEqual(self.route(1).stdout.splitlines()[0], "muse/abc-5.4")
|
||||
|
||||
def test_the_lead_agent_is_asked_once_for_a_class_that_cannot_be_read_and_then_not(self):
|
||||
"""A class read with confidence raises no question; an unreadable one does, in one line, until recorded."""
|
||||
models = ("abc-6.2-sol", "abc-6.3-luna")
|
||||
self.seed([("muse/abc-6.2-sol", 12, 12), ("muse/abc-6.3-luna", 12, 12)], difficulty=1)
|
||||
r = self.route(1, models=models)
|
||||
asks = [l for l in r.stdout.splitlines() if "cannot be read from its id" in l]
|
||||
self.assertEqual(len(asks), 1, r.stdout)
|
||||
self.assertLessEqual(len(r.stdout.splitlines()), 7, r.stdout)
|
||||
for w, c in (("muse/abc-6.2-sol", "sol"), ("muse/abc-6.3-luna", "luna")):
|
||||
self.sisi("workers", "fact", w, "--class", c, "--maker", "abc", "--source", "lead", env=self.env(models))
|
||||
self.assertNotIn("cannot be read", self.route(1, models=models).stdout)
|
||||
self.seed([("muse/abc-5.3", 12, 12), ("muse/abc-5.4", 12, 12)], difficulty=1)
|
||||
self.assertNotIn("cannot be read", self.route(1).stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user