Merge t3/discover-learn-new-workers into the reconciled line: conflicts resolved (session-start blocks, after-tool discovery, failure classifier and down-marking). done / next: unit suite on the merged tree, then the six integration points
This commit is contained in:
commit
29101c63e7
13 files changed
+3197
-50
No files matched your search
@@ -0,0 +1,706 @@
|
||||
"""A changing environment: workers installed or reachable after sisi was installed are found and used.
|
||||
|
||||
Requirements: R-7.2-1 and R-7.2-2 (least expensive sufficiently capable worker, from the record), R-7.2-3 (the routing
|
||||
policy is empirical and revisable: an unproven worker earns difficulty by its judged record), R-12-1 (what was learned
|
||||
is persisted so it is not rediscovered), R-16-3 and R-16-7 (a driver file is untrusted input: validated, least
|
||||
privilege), R-16-4 (the brief never reaches a shell), R-16-6 (a tool's output is data), R-16-8 (consequential changes
|
||||
are recorded), R-16-11 (a learned driver cannot widen permissions: approvals-off waits for the owner)."""
|
||||
import json, os, stat, sys, time, unittest
|
||||
from unittest import mock
|
||||
|
||||
from support import *
|
||||
from sisi import brief as brief_contract, discovery, routing, workers
|
||||
|
||||
FAKE_AGENT = """#!/bin/sh
|
||||
# a fake agent tool: `models` lists, anything else runs one task and echoes the prompt it was given
|
||||
if [ "$1" = "models" ]; then echo "fa-1"; echo "fa-2"; exit 0; fi
|
||||
if [ -n "$FAKE_MARK" ]; then echo ran >> "$FAKE_MARK"; fi
|
||||
n=0; last=""
|
||||
for a in "$@"; do n=$((n+1)); last="$a"; done
|
||||
if [ -n "$FAKE_ARGS" ]; then echo "$n" > "$FAKE_ARGS"; fi
|
||||
case "$FAKE_MODE" in
|
||||
login) echo "Error: you are not authenticated. Run 'fa login'" >&2; exit 1 ;;
|
||||
quota) echo "weekly allowance used up for this plan" ; exit 0 ;;
|
||||
flag) echo "error: unknown flag --print-all" >&2; exit 2 ;;
|
||||
hang) while true; do :; done ;;
|
||||
silent) echo "hello"; exit 0 ;;
|
||||
esac
|
||||
echo "$last"
|
||||
echo "total tokens: 321"
|
||||
exit 0
|
||||
"""
|
||||
|
||||
BRIEF = ("You are a worker.\n\n## Outcome and scope\nDo the toy task.\n\n## Context and sources of truth\nThis brief.\n\n"
|
||||
"## Constraints and interfaces\nNone.\n\n## Acceptance\nThe final report says done.\n\n"
|
||||
"## Deliverables and report format\nA short report.\n\n## Files you may change\ntoy.txt only.\n\n"
|
||||
"## Verification\nNone needed.\n\n## Budget and escalation\nFive minutes; escalate if blocked.\n")
|
||||
|
||||
LISTING = {"providers": [
|
||||
{"providerInstanceId": "alpha", "driverKind": "kindA", "displayName": "Alpha",
|
||||
"models": [{"id": "m-1", "label": "M One", "options": []}, {"id": "m-2", "label": "M Two", "options": []}],
|
||||
"canRunChildTask": True, "constraints": []},
|
||||
{"providerInstanceId": "beta", "driverKind": "kindB", "displayName": "Beta",
|
||||
"models": [{"id": "b-1", "label": "B One", "options": []}],
|
||||
"canRunChildTask": False, "constraints": ["Provider instance is disabled."]}]}
|
||||
LISTING_TOOL = "mcp__t3-code__orchestrator_capabilities"
|
||||
DELEGATE_TOOL = "mcp__t3-code__delegate_task"
|
||||
|
||||
|
||||
def driver_file(path, **over):
|
||||
d = {"name": "fakeagent", "exe": "fakeagent", "run": ["fakeagent", "-p", "{prompt}", "{model_flag}"],
|
||||
"list": ["fakeagent", "models"], "list_kind": "lines", "model_flag": "--model", "effort_flag": None,
|
||||
"cwd_flag": None, "plan": "flat", "auth_signatures": None, "limit_signatures": ["allowance used up"],
|
||||
"tokens_regex": "total tokens: (\\d+)", "approvals_off_reason": None, "notes": "a test driver"}
|
||||
d.update(over)
|
||||
with open(path, "w") as f:
|
||||
json.dump(d, f)
|
||||
return path
|
||||
|
||||
|
||||
def hook_payload(tool, result=None, tool_input=None):
|
||||
out = {"hook_event_name": "PostToolUse", "tool_name": tool, "session_id": "s1", "cwd": os.getcwd(),
|
||||
"tool_input": tool_input or {}}
|
||||
if result is not None:
|
||||
out["tool_response"] = result
|
||||
return out
|
||||
|
||||
|
||||
def wrapped(listing):
|
||||
return {"content": [{"type": "text", "text": json.dumps(listing)}]}
|
||||
|
||||
|
||||
class DiscoveryCase(SisiCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.userbin = os.path.join(self.home, ".local", "bin")
|
||||
self.bindir = os.path.join(self.tmp, "sysbin")
|
||||
os.makedirs(self.userbin)
|
||||
os.makedirs(self.bindir)
|
||||
self.marker = os.path.join(self.tmp, "mark")
|
||||
self.argsfile = os.path.join(self.tmp, "args")
|
||||
patcher = mock.patch.dict(os.environ, {"PATH": self.userbin + os.pathsep + self.bindir,
|
||||
"FAKE_MARK": self.marker, "FAKE_ARGS": self.argsfile})
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
discovery._DATA.clear()
|
||||
|
||||
def exe(self, name, body=FAKE_AGENT, where=None):
|
||||
p = os.path.join(where or self.userbin, name)
|
||||
with open(p, "w") as f:
|
||||
f.write(body)
|
||||
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
|
||||
return p
|
||||
|
||||
def runs(self):
|
||||
return open(self.marker).read().split() if os.path.exists(self.marker) else []
|
||||
|
||||
def write_cfg(self, obj):
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
with open(os.path.join(self.data, "config.json"), "w") as f:
|
||||
json.dump(obj, f)
|
||||
|
||||
def write_data(self, name, obj):
|
||||
os.makedirs(self.data, exist_ok=True)
|
||||
with open(os.path.join(self.data, name), "w") as f:
|
||||
json.dump(obj, f)
|
||||
|
||||
def feed(self, tool, result=None, tool_input=None):
|
||||
"""The after-tool hook's call, in process; returns what it printed."""
|
||||
import contextlib, io
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
discovery.after_tool(hook_payload(tool, result, tool_input))
|
||||
return out.getvalue()
|
||||
|
||||
def host_state(self):
|
||||
with open(discovery.host_state_file()) as f:
|
||||
return json.load(f)
|
||||
|
||||
def learn(self, **over):
|
||||
self.exe("fakeagent")
|
||||
f = driver_file(os.path.join(self.tmp, "driver.json"), **over)
|
||||
return self.sisi("workers", "learn", "fakeagent", "--record", f, "--by", "tester")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 2: a new tool on PATH
|
||||
|
||||
|
||||
class NewToolOnPath(DiscoveryCase):
|
||||
def test_first_run_prints_nothing_second_run_names_the_new_tool_once(self):
|
||||
self.exe("oldtool", "#!/bin/sh\n")
|
||||
self.assertEqual(discovery.session_start(now=1000.0), "") # stores the list, says nothing
|
||||
time.sleep(0.02)
|
||||
self.exe("shinyagent", "#!/bin/sh\necho ran >> %s\n" % self.marker)
|
||||
line = discovery.session_start(now=1001.0)
|
||||
self.assertIn("shinyagent", line)
|
||||
self.assertNotIn("oldtool", line)
|
||||
self.assertIn("sisi workers learn", line)
|
||||
self.assertEqual(len(line.splitlines()), 1)
|
||||
self.assertEqual(discovery.session_start(now=1002.0), "", "the same name is announced once")
|
||||
self.assertEqual(discovery.session_start(now=1000.0 + 7 * 3600), "", "and not again after the age passes")
|
||||
self.assertEqual(self.runs(), [], "nothing on PATH is ever executed")
|
||||
|
||||
def test_a_name_that_leaves_and_comes_back_is_not_announced_again(self):
|
||||
discovery.session_start(now=1.0)
|
||||
time.sleep(0.02)
|
||||
p = self.exe("wanderer")
|
||||
self.assertIn("wanderer", discovery.session_start(now=2.0))
|
||||
time.sleep(0.02)
|
||||
os.unlink(p)
|
||||
self.assertEqual(discovery.session_start(now=3.0), "")
|
||||
time.sleep(0.02)
|
||||
self.exe("wanderer")
|
||||
self.assertEqual(discovery.session_start(now=4.0), "")
|
||||
|
||||
def test_the_tick_hook_prints_the_notice_once_over_two_session_starts(self):
|
||||
env = {"PATH": self.userbin + os.pathsep + os.environ["PATH"]}
|
||||
first = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a1", "source": "startup", "cwd": self.proj}), env=env)
|
||||
self.assertNotIn("new command-line tool", first.stdout)
|
||||
time.sleep(0.02)
|
||||
self.exe("brandnew")
|
||||
second = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a2", "source": "startup", "cwd": self.proj}), env=env)
|
||||
self.assertEqual(second.stdout.count("brandnew"), 1, second.stdout + second.stderr)
|
||||
third = self.sisi_proc("tick", stdin=json.dumps({"session_id": "a3", "source": "startup", "cwd": self.proj}), env=env)
|
||||
self.assertNotIn("brandnew", third.stdout)
|
||||
|
||||
def test_only_user_level_folders_are_listed(self):
|
||||
discovery.session_start(now=1.0)
|
||||
self.exe("sysonly", where=self.bindir) # outside the home: a system folder
|
||||
self.assertEqual(self.sisi_free(), "")
|
||||
|
||||
def sisi_free(self):
|
||||
return discovery.session_start(now=2.0)
|
||||
|
||||
def test_at_most_five_names_agent_looking_ones_first(self):
|
||||
discovery.session_start(now=1.0)
|
||||
time.sleep(0.02)
|
||||
for n in ("aaa", "bbb", "ccc", "ddd", "eee", "fff", "my-agent"):
|
||||
self.exe(n)
|
||||
line = discovery.session_start(now=2.0)
|
||||
self.assertIn("my-agent", line)
|
||||
self.assertIn("and 2 more", line)
|
||||
self.assertEqual(sum(1 for n in ("aaa", "bbb", "ccc", "ddd", "eee", "fff", "my-agent") if n in line), 5)
|
||||
|
||||
def test_shells_and_tools_sisi_already_knows_are_not_announced(self):
|
||||
discovery.session_start(now=1.0)
|
||||
time.sleep(0.02)
|
||||
for n in ("bash", "codex"):
|
||||
self.exe(n)
|
||||
self.assertEqual(discovery.session_start(now=2.0), "")
|
||||
|
||||
def test_the_cached_list_is_not_rescanned_until_something_changes(self):
|
||||
discovery.session_start(now=1.0)
|
||||
with mock.patch.object(discovery, "list_executables", side_effect=AssertionError("rescanned")):
|
||||
self.assertEqual(discovery.session_start(now=2.0), "")
|
||||
# the counter and the age each force a rescan
|
||||
with mock.patch.object(discovery, "list_executables", return_value=[]) as m:
|
||||
discovery.session_start(now=1.0 + 7 * 3600)
|
||||
self.assertTrue(m.called)
|
||||
self.write_cfg({"discovery": {"path_every_starts": 2}})
|
||||
with mock.patch.object(discovery, "list_executables", return_value=[]) as m:
|
||||
discovery.session_start(now=1.0 + 7 * 3600 + 1)
|
||||
self.assertFalse(m.called)
|
||||
discovery.session_start(now=1.0 + 7 * 3600 + 2)
|
||||
self.assertTrue(m.called)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 1: what the host can reach
|
||||
|
||||
|
||||
class HostListing(DiscoveryCase):
|
||||
def test_listing_records_enabled_workers_exactly_as_named_and_says_so_once(self):
|
||||
out = self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
msg = json.loads(out)
|
||||
self.assertIn("2 new workers", msg["systemMessage"])
|
||||
self.assertEqual(len(out.splitlines()), 1)
|
||||
prov = self.host_state()["hosts"]["t3-code"]["providers"]
|
||||
self.assertEqual(sorted(prov["alpha"]["models"]), ["m-1", "m-2"])
|
||||
self.assertTrue(prov["alpha"]["usable"])
|
||||
self.assertFalse(prov["beta"]["usable"])
|
||||
self.assertEqual(self.feed(LISTING_TOOL, wrapped(LISTING)), "", "once per set of new workers")
|
||||
bigger = json.loads(json.dumps(LISTING))
|
||||
bigger["providers"][0]["models"].append({"id": "m-3", "label": "M Three"})
|
||||
self.assertIn("1 new worker ", json.loads(self.feed(LISTING_TOOL, bigger))["systemMessage"])
|
||||
|
||||
def test_every_shape_a_host_may_wrap_the_result_in_is_read(self):
|
||||
for result in (LISTING, wrapped(LISTING), json.dumps(LISTING), [{"type": "text", "text": json.dumps(LISTING)}]):
|
||||
if os.path.exists(discovery.host_state_file()):
|
||||
os.unlink(discovery.host_state_file())
|
||||
self.assertIn("2 new workers", self.feed(LISTING_TOOL, result))
|
||||
|
||||
def test_a_disabled_provider_is_never_routable(self):
|
||||
self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
cands = {c["worker"]: c for c in workers.build_candidates()}
|
||||
self.assertTrue(cands["alpha/m-1"]["usable"])
|
||||
self.assertFalse(cands["beta/b-1"]["usable"])
|
||||
self.assertIn("disabled", cands["beta/b-1"]["reason"])
|
||||
self.assertFalse(cands["beta/b-1"].get("unproven_ok"))
|
||||
self.assertNotIn("beta/b-1", workers.facts_line())
|
||||
self.assertIn("alpha/m-1", workers.facts_line())
|
||||
self.assertNotIn("beta", self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[0])
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("beta - not usable now", shown)
|
||||
self.assertIn("alpha - usable now", shown)
|
||||
|
||||
def test_a_routed_host_worker_names_the_provider_and_model_to_pass_to_the_hosts_delegation_tool(self):
|
||||
self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
r = self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
lines = r.stdout.splitlines()
|
||||
self.assertEqual(lines[0], "alpha/m-1")
|
||||
self.assertIn("mechanism: use the host's cross-provider delegation", lines[1])
|
||||
self.assertIn("delegate_task", lines[1])
|
||||
self.assertIn("target.providerInstanceId=alpha", lines[1])
|
||||
self.assertIn("target.model=m-1", lines[1])
|
||||
self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout)
|
||||
|
||||
def test_sisi_delegate_does_not_run_a_host_worker_it_says_how_the_host_starts_it(self):
|
||||
self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
brief = os.path.join(self.proj, "b.md")
|
||||
open(brief, "w").write(BRIEF)
|
||||
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", brief, "--worker", "alpha/m-1")
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("target.providerInstanceId=alpha", r.stdout)
|
||||
self.assertIn("target.model=m-1", r.stdout)
|
||||
|
||||
def test_a_worker_gone_from_enough_listings_is_dropped(self):
|
||||
self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
only_beta = {"providers": [LISTING["providers"][1]]}
|
||||
self.feed(LISTING_TOOL, wrapped(only_beta))
|
||||
self.feed(LISTING_TOOL, wrapped(only_beta))
|
||||
self.assertIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"], "two listings: still kept")
|
||||
self.feed(LISTING_TOOL, wrapped(only_beta))
|
||||
self.assertNotIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"])
|
||||
self.write_cfg({"discovery": {"drop_after_listings": 1}})
|
||||
self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
self.feed(LISTING_TOOL, wrapped(only_beta))
|
||||
self.assertNotIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"])
|
||||
|
||||
def test_a_delegation_seen_in_use_is_recorded_and_not_announced(self):
|
||||
out = self.feed(DELEGATE_TOOL, tool_input={"task": "x", "target": {"providerInstanceId": "gamma", "model": "g-1"}})
|
||||
self.assertEqual(out, "")
|
||||
rec = self.host_state()["hosts"]["t3-code"]["providers"]["gamma"]["models"]["g-1"]
|
||||
self.assertEqual(rec["source"], "delegation")
|
||||
self.assertEqual([c["worker"] for c in workers.build_candidates() if c["tool"] == "gamma"], ["gamma/g-1"])
|
||||
self.feed(DELEGATE_TOOL, tool_input={"target": {"providerInstanceId": 5, "model": None}}) # malformed: ignored
|
||||
|
||||
def test_hundreds_of_models_are_stored_but_only_used_priced_or_ranked_ones_are_candidates(self):
|
||||
big = {"providers": [{"providerInstanceId": "big", "driverKind": "k", "displayName": "Big", "canRunChildTask": True,
|
||||
"constraints": [], "models": [{"id": "m-%d" % i, "label": "m"} for i in range(300)]}]}
|
||||
self.assertEqual(self.feed(LISTING_TOOL, wrapped(big)), "", "a catalogue is not announced worker by worker")
|
||||
self.assertEqual(len(self.host_state()["hosts"]["t3-code"]["providers"]["big"]["models"]), 300)
|
||||
self.write_data("worker-prices.json", {"models": {"big/m-7": {"plan": "per-use", "cost_per_million_tokens": 2.0,
|
||||
"source": "s", "date": "2026-11-01"}}})
|
||||
self.write_data("model-strength.json", {"models": {"big/m-9": {"standing": 50, "source": "s", "date": "2026-11-01"}}})
|
||||
cands = workers.build_candidates()
|
||||
self.assertEqual(len([c for c in cands if c["tool"] == "big"]), 300)
|
||||
keep, cold, excluded = workers.routable_candidates(cands, [])
|
||||
self.assertEqual(sorted(c["worker"] for c in keep), ["big/m-7", "big/m-9"])
|
||||
self.assertEqual(excluded, 298)
|
||||
self.assertFalse(cold)
|
||||
|
||||
def test_input_that_is_not_json_is_ignored(self):
|
||||
env = {"SISI_STATE": self.state}
|
||||
for stdin in ("this is not json", "[1,2]", "", '{"tool_name": 7}', json.dumps(hook_payload(LISTING_TOOL, "not json at all"))):
|
||||
r = self.sisi_proc("watch", "--after", stdin=stdin, env=env)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertEqual(r.stdout, "")
|
||||
self.assertFalse(os.path.exists(discovery.host_state_file()))
|
||||
|
||||
def test_the_real_hook_command_records_and_prints_one_line(self):
|
||||
r = self.sisi_proc("watch", "--after", stdin=json.dumps(hook_payload(LISTING_TOOL, wrapped(LISTING))))
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(len(r.stdout.splitlines()), 1, r.stdout)
|
||||
self.assertIn("2 new workers", json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"])
|
||||
|
||||
def test_a_payload_that_is_not_an_object_does_nothing(self):
|
||||
for payload in (None, [1], "x", 5, {}, {"tool_name": None}, {"tool_name": LISTING_TOOL}):
|
||||
discovery.after_tool(payload)
|
||||
self.assertFalse(os.path.exists(discovery.host_state_file()))
|
||||
|
||||
def test_other_tools_cost_nothing_and_are_left_alone(self):
|
||||
self.assertEqual(self.feed("Read", {"x": 1}), "")
|
||||
self.assertEqual(self.feed("Bash"), "")
|
||||
self.assertFalse(os.path.exists(discovery.host_state_file()))
|
||||
|
||||
def test_forgetting_a_host_provider(self):
|
||||
self.feed(LISTING_TOOL, wrapped(LISTING))
|
||||
r = self.sisi("workers", "forget", "alpha")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertNotIn("alpha", self.host_state()["hosts"]["t3-code"]["providers"])
|
||||
self.assertEqual(self.sisi("workers", "forget", "nobody").returncode, 1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 3: a driver learned as data
|
||||
|
||||
|
||||
class LearnedDriver(DiscoveryCase):
|
||||
def check_file(self, **over):
|
||||
self.exe("fakeagent")
|
||||
f = driver_file(os.path.join(self.tmp, "d.json"), **over)
|
||||
return self.sisi("workers", "learn", "fakeagent", "--check", f)
|
||||
|
||||
def test_the_brief_is_a_valid_delegation_contract_naming_the_format(self):
|
||||
self.exe("fakeagent")
|
||||
r = self.sisi("workers", "learn", "fakeagent")
|
||||
self.assertEqual(r.returncode, 0, r.stderr)
|
||||
self.assertEqual(brief_contract.missing_required(r.stdout), [])
|
||||
for word in ("{prompt}", "approvals_off_reason", "--record", "tokens_regex", "limit_signatures", "help"):
|
||||
self.assertIn(word, r.stdout)
|
||||
self.assertEqual(self.sisi("workers", "learn", "nosuchtool").returncode, 1)
|
||||
|
||||
def test_record_validates_stores_runs_one_smoke_task_and_marks_the_driver_usable(self):
|
||||
r = self.learn()
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("PASSED", r.stdout)
|
||||
self.assertEqual(self.runs(), ["ran"], "exactly one task: the smoke task")
|
||||
rec = discovery.load_drivers()["fakeagent"]
|
||||
self.assertEqual(rec["state"], "usable")
|
||||
self.assertEqual(rec["learned_by"], "tester")
|
||||
self.assertEqual(rec["models"], ["fa-1", "fa-2"])
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("fakeagent - usable now", shown)
|
||||
self.assertIn("learned by tester on", shown)
|
||||
self.assertIn("models: fa-1, fa-2", shown)
|
||||
self.assertTrue(os.path.exists(os.path.join(self.data, "worker-drivers.json")))
|
||||
|
||||
def test_a_template_that_tries_shell_injection_through_the_placeholder_is_refused(self):
|
||||
self.exe("fakeagent")
|
||||
cases = [dict(run=["sh", "-c", "fakeagent {prompt}"], exe="sh"),
|
||||
dict(run=["fakeagent", "-p", "--prompt={prompt}"]),
|
||||
dict(run=["fakeagent", "-c", "echo {prompt}; {prompt}"]),
|
||||
dict(run=["fakeagent", "-p", "{prompt}", "{prompt}"]),
|
||||
dict(run=["fakeagent", "-p", "x"]),
|
||||
dict(run=["fakeagent", "-p", "{prompt}\n; rm -rf ~"]),
|
||||
dict(run=["fakeagent", "-p", "{prompt}", "{unknown}"]),
|
||||
dict(run=["bash", "-c", "{prompt}"], exe="bash", name="fakeagent")]
|
||||
for over in cases:
|
||||
f = driver_file(os.path.join(self.tmp, "bad.json"), **over)
|
||||
r = self.sisi("workers", "learn", "fakeagent", "--record", f)
|
||||
self.assertEqual(r.returncode, 1, (over, r.stdout))
|
||||
self.assertIn("not valid", r.stdout)
|
||||
self.assertEqual(self.runs(), [], "a refused file never runs anything")
|
||||
self.assertEqual(discovery.load_drivers(), {})
|
||||
|
||||
def test_a_binary_not_on_path_or_another_tool_than_the_one_named_is_refused(self):
|
||||
self.exe("fakeagent")
|
||||
for over in (dict(exe="ghostagent", name="ghostagent", run=["ghostagent", "{prompt}"]),
|
||||
dict(exe="/bin/sh", run=["/bin/sh", "{prompt}"]),
|
||||
dict(exe="fakeagent", name="codex"),
|
||||
dict(unexpected=1)):
|
||||
f = driver_file(os.path.join(self.tmp, "bad.json"), **over)
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", f).returncode, 1, over)
|
||||
other = self.exe("otheragent")
|
||||
f = driver_file(os.path.join(self.tmp, "o.json"), name="otheragent", exe="otheragent", run=["otheragent", "{prompt}"],
|
||||
list=None, list_kind=None)
|
||||
r = self.sisi("workers", "learn", "fakeagent", "--record", f) # a file for another tool than the one named
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("must both be 'fakeagent'", r.stdout)
|
||||
self.assertEqual(self.runs(), [])
|
||||
|
||||
def test_a_shell_or_interpreter_is_not_a_tool_even_when_the_name_matches(self):
|
||||
self.exe("sh") # a command on PATH that is not an agent tool
|
||||
f = driver_file(os.path.join(self.tmp, "sh.json"), name="sh", exe="sh", run=["sh", "{prompt}"], list=None,
|
||||
list_kind=None, model_flag=None)
|
||||
r = self.sisi("workers", "learn", "sh", "--check", f)
|
||||
self.assertEqual(r.returncode, 1, r.stdout)
|
||||
self.assertIn("shell or interpreter", r.stdout)
|
||||
|
||||
def test_a_file_that_is_not_json_or_too_large_is_refused(self):
|
||||
self.exe("fakeagent")
|
||||
p = os.path.join(self.tmp, "x.json")
|
||||
open(p, "w").write("{not json")
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", p).returncode, 1)
|
||||
open(p, "w").write(json.dumps({"name": "fakeagent", "notes": "x" * 30000}))
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", p).returncode, 1)
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", os.path.join(self.tmp, "nope")).returncode, 1)
|
||||
|
||||
def test_the_brief_reaches_the_tool_as_one_argument_never_a_shell_string(self):
|
||||
self.learn()
|
||||
os.unlink(self.marker)
|
||||
brief = os.path.join(self.proj, "b.md")
|
||||
pwn = os.path.join(self.tmp, "pwned")
|
||||
open(brief, "w").write(BRIEF + '\n"; touch %s; $(touch %s) `touch %s` \'\n' % (pwn, pwn, pwn))
|
||||
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", brief, "--worker", "fakeagent/default")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertFalse(os.path.exists(pwn))
|
||||
self.assertEqual(open(self.argsfile).read().strip(), "2", "the tool saw -p and ONE prompt argument")
|
||||
|
||||
def test_a_learned_driver_runs_like_a_built_in_one_usage_and_judging(self):
|
||||
self.learn()
|
||||
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief())
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("Do the toy task", r.stdout) # the report: the tool echoed the brief
|
||||
self.assertIn("worker: fakeagent/default", r.stdout)
|
||||
self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout)
|
||||
run = [x for x in workers.read_records() if x.get("kind") == "run"][-1]
|
||||
self.assertEqual(run["tokens"], 321)
|
||||
self.assertEqual(run["tokens_class"], "measured")
|
||||
j = self.sisi("delegate", "judge", run["id"], "--outcome", "accepted", "--check", "read")
|
||||
self.assertEqual(j.returncode, 0, j.stdout + j.stderr)
|
||||
self.assertEqual([r["worker"] for r in workers.read_records() if r.get("kind") == "attempt"], ["fakeagent/default"])
|
||||
|
||||
def brief(self):
|
||||
p = os.path.join(self.proj, "brief.md")
|
||||
open(p, "w").write(BRIEF)
|
||||
return p
|
||||
|
||||
def test_the_drivers_own_limit_phrase_is_unavailability_and_the_next_worker_runs(self):
|
||||
self.learn()
|
||||
self.exe("second", FAKE_AGENT.replace("echo \"$last\"", "echo \"$last\"; echo \"second worker report\""))
|
||||
f = driver_file(os.path.join(self.tmp, "s.json"), name="second", exe="second", run=["second", "-p", "{prompt}"],
|
||||
list=None, list_kind=None, model_flag=None)
|
||||
self.assertEqual(self.sisi("workers", "learn", "second", "--record", f).returncode, 0)
|
||||
# `fakeagent` now reports its allowance used up (the learned phrase); the second tool answers
|
||||
self.exe("fakeagent", FAKE_AGENT.replace('case "$FAKE_MODE"', 'FAKE_MODE=quota\ncase "$FAKE_MODE"'))
|
||||
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", "fakeagent/default")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("second worker report", r.stdout)
|
||||
self.assertIn("fakeagent/default is unavailable (limit", r.stdout)
|
||||
|
||||
def test_a_smoke_task_that_fails_leaves_the_driver_unusable_with_the_reason(self):
|
||||
for mode, kind in (("login", "login"), ("quota", "quota"), ("flag", "bad-template"), ("silent", "no-answer")):
|
||||
discovery.save_drivers({})
|
||||
with mock.patch.dict(os.environ, {"FAKE_MODE": mode}):
|
||||
r = self.learn()
|
||||
self.assertEqual(r.returncode, 1, (mode, r.stdout))
|
||||
self.assertIn("FAILED (%s)" % kind, r.stdout)
|
||||
rec = discovery.load_drivers()["fakeagent"]
|
||||
self.assertNotEqual(rec["state"], "usable")
|
||||
self.assertIn(kind, rec["reason"])
|
||||
self.assertIsNone(discovery.driver_for("fakeagent"))
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("fakeagent - not usable now", shown)
|
||||
self.assertIn(kind, shown)
|
||||
cands = {c["worker"]: c for c in workers.build_candidates()}
|
||||
self.assertFalse(cands["fakeagent/default"]["usable"])
|
||||
# a login the owner then completes: --verify proves it
|
||||
discovery.save_drivers({})
|
||||
with mock.patch.dict(os.environ, {"FAKE_MODE": "login"}):
|
||||
self.learn()
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--verify").returncode, 1)
|
||||
r = self.sisi("workers", "learn", "fakeagent", "--verify")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertIsNotNone(discovery.driver_for("fakeagent"))
|
||||
|
||||
def test_a_task_that_waits_for_a_question_is_stopped_by_the_time_limit(self):
|
||||
self.write_cfg({"discovery": {"smoke_timeout_s": 1}})
|
||||
with mock.patch.dict(os.environ, {"FAKE_MODE": "hang"}):
|
||||
r = self.learn()
|
||||
self.assertEqual(r.returncode, 1)
|
||||
self.assertIn("FAILED (timeout)", r.stdout)
|
||||
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "failed")
|
||||
|
||||
def test_the_smoke_task_runs_in_a_temporary_folder_with_no_input(self):
|
||||
body = FAKE_AGENT.replace('echo "$last"', 'pwd > "$FAKE_ARGS.cwd"; read x && echo "got input" >> "$FAKE_ARGS.cwd"; echo "$last"')
|
||||
self.exe("fakeagent", body)
|
||||
f = driver_file(os.path.join(self.tmp, "d.json"))
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--record", f).returncode, 0)
|
||||
seen = open(self.argsfile + ".cwd").read()
|
||||
self.assertIn("sisi-smoke-", seen)
|
||||
self.assertNotIn("got input", seen)
|
||||
self.assertFalse(os.path.exists(seen.splitlines()[0]), "the temporary folder is removed")
|
||||
|
||||
def test_forget_removes_a_learned_driver(self):
|
||||
self.learn()
|
||||
self.assertEqual(self.sisi("workers", "forget", "fakeagent").returncode, 0)
|
||||
self.assertEqual(discovery.load_drivers(), {})
|
||||
self.assertNotIn("fakeagent", self.sisi("workers").stdout)
|
||||
|
||||
def test_the_bypass_flag_patterns_catch_the_known_spellings(self):
|
||||
for flag in ("--dangerously-skip-permissions", "--dangerously-bypass-approvals-and-sandbox", "--yolo", "-y",
|
||||
"--always-approve", "--allow-all", "--force", "--auto", "--no-sandbox", "--full-auto",
|
||||
"--approval-mode=yolo", "--sandbox=off"):
|
||||
self.assertEqual(discovery.bypass_args(["t", "-p", flag]), [flag], flag)
|
||||
for flag in ("-p", "--print", "--model", "--output-format", "--sandbox", "text"):
|
||||
self.assertEqual(discovery.bypass_args(["t", flag]), [], flag)
|
||||
|
||||
|
||||
class WaitsForTheOwner(DiscoveryCase):
|
||||
def bypass(self):
|
||||
self.exe("fakeagent")
|
||||
f = driver_file(os.path.join(self.tmp, "d.json"), run=["fakeagent", "--dangerously-skip-permissions", "-p", "{prompt}"],
|
||||
approvals_off_reason="cannot run unattended without it")
|
||||
return self.sisi("workers", "learn", "fakeagent", "--record", f)
|
||||
|
||||
def test_an_approvals_off_driver_is_stored_waiting_and_nothing_runs(self):
|
||||
r = self.bypass()
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("WAITING FOR THE OWNER", r.stdout)
|
||||
self.assertIn("fakeagent --dangerously-skip-permissions -p {prompt}", r.stdout)
|
||||
self.assertIn("cannot run unattended without it", r.stdout)
|
||||
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||
self.assertEqual(self.runs(), [], "not even the smoke task ran")
|
||||
self.assertIsNone(discovery.driver_for("fakeagent"))
|
||||
cands = {c["worker"]: c for c in workers.build_candidates()}
|
||||
self.assertFalse(cands["fakeagent/default"]["usable"])
|
||||
self.assertIn("waiting for the owner", self.sisi("workers").stdout)
|
||||
self.assertNotEqual(self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[:1], ["fakeagent/default"])
|
||||
brief = os.path.join(self.proj, "b.md")
|
||||
open(brief, "w").write(BRIEF)
|
||||
d = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", brief, "--worker", "fakeagent/default")
|
||||
self.assertEqual(d.returncode, 1)
|
||||
self.assertEqual(self.runs(), [])
|
||||
self.assertEqual(self.sisi("workers", "learn", "fakeagent", "--verify").returncode, 1)
|
||||
self.assertEqual(self.runs(), [])
|
||||
|
||||
def test_approve_lists_the_exact_command_and_an_agent_cannot_decide(self):
|
||||
self.bypass()
|
||||
listing = self.sisi("approve").stdout
|
||||
self.assertIn("drv-fakeagent", listing)
|
||||
self.assertIn("fakeagent --dangerously-skip-permissions -p {prompt}", listing)
|
||||
refused = self.sisi("approve", "drv-fakeagent", "--yes")
|
||||
self.assertEqual(refused.returncode, 2)
|
||||
self.assertIn("owner in a terminal", refused.stderr)
|
||||
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "waiting-owner")
|
||||
self.assertEqual(self.runs(), [])
|
||||
self.assertEqual(self.sisi("approve", "drv-ghost", "--yes").returncode, 2)
|
||||
|
||||
def test_the_owners_yes_runs_the_smoke_task_and_only_then_the_driver_is_usable(self):
|
||||
self.bypass()
|
||||
self.write_cfg({"learning": {"agent_relayed_approval": True}}) # stands in for the owner's terminal here
|
||||
r = self.sisi("approve", "drv-fakeagent", "--yes")
|
||||
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||
self.assertIn("PASSED", r.stdout)
|
||||
self.assertEqual(discovery.load_drivers()["fakeagent"]["state"], "usable")
|
||||
self.assertEqual(self.runs(), ["ran"])
|
||||
|
||||
def test_the_owners_no_removes_the_driver(self):
|
||||
self.bypass()
|
||||
self.write_cfg({"learning": {"agent_relayed_approval": True}})
|
||||
self.assertEqual(self.sisi("approve", "drv-fakeagent", "--no").returncode, 0)
|
||||
self.assertEqual(discovery.load_drivers(), {})
|
||||
self.assertEqual(self.runs(), [])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 4: new workers earn their place
|
||||
|
||||
|
||||
def cand(worker, plan=None, cost=None, unproven=False, **kw):
|
||||
tool, model = worker.split("/")
|
||||
return dict({"worker": worker, "tool": tool, "model": model, "plan": plan, "cost": cost, "usable": True,
|
||||
"allowance_pct_left": None, "aliases": [worker], "maker": model, "unproven": unproven,
|
||||
"unproven_ok": unproven}, **kw)
|
||||
|
||||
|
||||
def attempts(worker, n, kind="read", difficulty=1, outcome="accepted"):
|
||||
return [{"kind": "attempt", "worker": worker, "type": kind, "difficulty": difficulty, "outcome": outcome,
|
||||
"id": "%s-%d-%d" % (worker, difficulty, i)} for i in range(n)]
|
||||
|
||||
|
||||
class NewWorkersEarnTheirPlace(unittest.TestCase):
|
||||
def test_a_new_worker_is_never_chosen_above_routine_work(self):
|
||||
proven = cand("old/a", plan="flat")
|
||||
new = cand("new/b", plan="flat", unproven=True)
|
||||
records = attempts("old/a", 8, "impl", 3)
|
||||
for d in (2, 3):
|
||||
r = routing.choose([proven, new], records, {}, "impl", d, now=1.0)
|
||||
self.assertEqual(r["choice"]["worker"], "old/a")
|
||||
self.assertTrue(any(w == "new/b" and "unproven" in why for w, why in r["passed_over"]))
|
||||
alone = routing.choose([new], [], {}, "impl", 3, now=1.0)
|
||||
self.assertIsNone(alone["choice"], "nobody else: the main agent does it, the new worker is not tried on hard work")
|
||||
self.assertIsNone(routing.choose([new], [], {}, "impl", 2, now=1.0)["choice"])
|
||||
self.assertEqual(routing.choose([new], [], {}, "impl", 1, now=1.0)["choice"]["worker"], "new/b")
|
||||
|
||||
def test_a_benchmark_standing_does_not_unlock_hard_work_for_an_unproven_worker(self):
|
||||
new = cand("new/b", plan="flat", unproven=True, standing=99.0)
|
||||
old = cand("old/a", plan="per-use", cost=1.0, standing=10.0)
|
||||
self.assertEqual(routing.choose([new, old], [], {}, "impl", 3, now=1.0)["choice"]["worker"], "old/a")
|
||||
|
||||
def test_after_enough_judged_attempts_it_competes_by_the_ordinary_rules(self):
|
||||
worker = cand("new/b", plan="flat", unproven=False)
|
||||
r = routing.choose([worker], attempts("new/b", 8, "impl", 2), {}, "impl", 2, now=1.0)
|
||||
self.assertEqual(r["choice"]["worker"], "new/b")
|
||||
|
||||
def test_a_free_new_worker_gets_one_routine_task_in_three_a_paid_one_never_by_this_slot(self):
|
||||
old = cand("old/a", plan="flat", cost=1.0)
|
||||
free = cand("new/b", plan="flat", unproven=True)
|
||||
paid = cand("new/c", plan="per-use", cost=0.5, unproven=True)
|
||||
picks = {}
|
||||
for total in range(8, 14):
|
||||
records = attempts("old/a", total)
|
||||
picks[total] = routing.choose([old, free], records, {}, "read", 1, now=1.0, explore_free_every=3)["choice"]["worker"]
|
||||
self.assertEqual([picks[t] for t in range(8, 14)],
|
||||
["new/b" if t % 3 == 2 else "old/a" for t in range(8, 14)], picks)
|
||||
r = routing.choose([old, free], attempts("old/a", 8), {}, "read", 1, now=1.0, explore_free_every=3)
|
||||
self.assertTrue(r["explored_free"])
|
||||
self.assertTrue(any("costs nothing extra" in why for w, why in r["passed_over"] if w == "old/a"))
|
||||
# the config knob: every task, or never
|
||||
self.assertEqual(routing.choose([old, free], attempts("old/a", 9), {}, "read", 1, now=1.0,
|
||||
explore_free_every=1)["choice"]["worker"], "new/b")
|
||||
self.assertEqual(routing.choose([old, free], attempts("old/a", 8), {}, "read", 1, now=1.0,
|
||||
explore_free_every=0)["choice"]["worker"], "old/a")
|
||||
# a paid unproven worker is not in the free slot (the existing one-in-ten covers it)
|
||||
self.assertEqual(routing.choose([old, paid], attempts("old/a", 8), {}, "read", 1, now=1.0,
|
||||
explore_free_every=3)["choice"]["worker"], "old/a")
|
||||
|
||||
def test_the_rate_is_read_from_config(self):
|
||||
with mock.patch.object(workers, "route_cfg", return_value={"explore_free_one_in": 5}):
|
||||
self.assertEqual(workers.explore_free_every(), 5)
|
||||
with mock.patch.object(workers, "route_cfg", return_value={}):
|
||||
self.assertEqual(workers.explore_free_every(), 3)
|
||||
with mock.patch.object(workers, "route_cfg", return_value={"explore_free_one_in": "x"}):
|
||||
self.assertEqual(workers.explore_free_every(), 3)
|
||||
self.assertEqual(json.load(open(os.path.join(REPO, "config.default.json")))["route"]["explore_free_one_in"], 3)
|
||||
|
||||
|
||||
class NewWorkersThroughTheCommands(DiscoveryCase):
|
||||
def test_route_says_unproven_until_the_record_has_enough_attempts(self):
|
||||
self.learn()
|
||||
r = self.sisi("route", "--kind", "read", "--difficulty", "1", "--explain")
|
||||
self.assertEqual(r.stdout.splitlines()[0], "fakeagent/default", r.stdout)
|
||||
self.assertIn("unproven: check this result with at least the tests or a read of the diff", r.stdout)
|
||||
self.assertNotEqual(self.sisi("route", "--kind", "read", "--difficulty", "3").stdout.splitlines()[:1], ["fakeagent/default"])
|
||||
for w in ("fakeagent/default", "fakeagent/fa-1", "fakeagent/fa-2"):
|
||||
for row in attempts(w, 8):
|
||||
workers.append_record(row)
|
||||
r = self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertTrue(r.stdout.startswith("fakeagent/"))
|
||||
self.assertNotIn("unproven", r.stdout)
|
||||
|
||||
def test_a_flat_plan_from_the_driver_or_a_fact_is_a_flat_plan_and_unknown_is_per_use(self):
|
||||
self.learn()
|
||||
c = {c["worker"]: c for c in workers.build_candidates()}["fakeagent/default"]
|
||||
self.assertEqual(c["plan"], "flat")
|
||||
discovery.save_drivers(dict(discovery.load_drivers(), fakeagent=dict(
|
||||
discovery.load_drivers()["fakeagent"], driver=dict(discovery.load_drivers()["fakeagent"]["driver"], plan=None))))
|
||||
c = {c["worker"]: c for c in workers.build_candidates()}["fakeagent/default"]
|
||||
self.assertEqual(c["plan"], "per-use")
|
||||
self.write_data("worker-prices.json", {"tools": {"fakeagent": {"plan": "flat", "source": "s", "date": "2026-11-01"}}})
|
||||
c = {c["worker"]: c for c in workers.build_candidates()}["fakeagent/default"]
|
||||
self.assertEqual(c["plan"], "flat")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 5: facts follow
|
||||
|
||||
|
||||
class FactsNameTheNewWorkers(DiscoveryCase):
|
||||
def test_the_missing_facts_line_names_at_most_five_new_workers(self):
|
||||
self.write_data("worker-prices.json", {"models": {"other/x": {"plan": "per-use", "cost_per_million_tokens": 1.0,
|
||||
"source": "s", "date": time.strftime("%Y-%m-%d")}}})
|
||||
self.assertEqual(workers.facts_line(), "", "facts are fresh and nobody new lacks any")
|
||||
many = {"providers": [{"providerInstanceId": "p%d" % i, "driverKind": "k", "displayName": "P", "canRunChildTask": True,
|
||||
"constraints": [], "models": [{"id": "m", "label": "m"}]} for i in range(7)]}
|
||||
self.feed(LISTING_TOOL, wrapped(many))
|
||||
line = workers.facts_line()
|
||||
self.assertIn("worker facts are missing for the new workers p0/m", line)
|
||||
self.assertIn("and 2 more", line)
|
||||
self.assertEqual(sum(1 for i in range(7) if "p%d/m" % i in line), 5)
|
||||
self.assertIn("sisi workers fact WORKER --price N", line)
|
||||
for i in range(7):
|
||||
self.write_data("model-strength.json", {"models": {"p%d/m" % j: {"standing": 40, "source": "s", "date": "2026-11-01"}
|
||||
for j in range(7)}})
|
||||
self.assertEqual(workers.facts_line(), "")
|
||||
|
||||
def test_with_nothing_new_the_line_is_the_one_it_always_was(self):
|
||||
line = workers.facts_line()
|
||||
self.assertIn("worker facts are missing (no prices or benchmark standing recorded yet)", line)
|
||||
self.assertNotIn("new workers", line)
|
||||
|
||||
def test_a_learned_tool_is_a_target_too(self):
|
||||
self.learn()
|
||||
self.assertIn("fakeagent/default", workers.facts_line())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,557 @@
|
||||
"""One tool, several providers: per-provider plans, the owner's vouch, allowance probes and failure phrases.
|
||||
|
||||
Requirements: R-7.2-1 and R-7.2-2 (the least expensive sufficiently capable worker: a flat plan with allowance left
|
||||
costs nothing extra, a lighter model of the plan first), R-7.2-3 (empirical and revisable: a vouch is a prior that the
|
||||
judged record replaces), R-7.3-1 (cost counts what a plan really charges), R-16-3 and R-16-4 (a key is used for one
|
||||
request and never stored, printed or logged; least privilege: a redirect never carries it), R-16-6 and R-16-7
|
||||
(tool output and server answers are data, validated), R-16-8 (a consequential definition waits for the owner),
|
||||
R-16-11 (an agent cannot widen what routing trusts: a relayed vouch counts up to difficulty 2)."""
|
||||
import http.server, json, os, threading, time, unittest
|
||||
from unittest import mock
|
||||
|
||||
import test_discovery as TD
|
||||
from support import *
|
||||
from sisi import discovery, routing, workers
|
||||
|
||||
SECRET = "SECRETKEYVALUE123456"
|
||||
|
||||
MULTI = """#!/bin/sh
|
||||
if [ "$1" = "models" ]; then echo "zai/a"; echo "zai/b"; echo "other/c"; exit 0; fi
|
||||
if [ -n "$FAKE_MARK" ]; then echo "$@" >> "$FAKE_MARK"; fi
|
||||
n=0; last=""
|
||||
for a in "$@"; do n=$((n+1)); last="$a"; done
|
||||
model=""; prev=""
|
||||
for a in "$@"; do if [ "$prev" = "--model" ]; then model="$a"; fi; prev="$a"; done
|
||||
case "$FAKE_MODE:$model" in
|
||||
quota:zai/*) echo "weekly allowance used up for this plan"; exit 0 ;;
|
||||
code1113:zai/*) echo '{"error":{"code":"1113","message":"Insufficient balance or no resource package","usage limit":true}}'; exit 1 ;;
|
||||
reset:zai/*) echo '{"error":{"code":"1308","message":"limit reached","resetAt":"RESETAT"}}'; exit 1 ;;
|
||||
esac
|
||||
echo "$last"
|
||||
exit 0
|
||||
"""
|
||||
|
||||
AUTH_EXPORT = ('#!/bin/sh\necho \'[{"integrationID":"other","active":true,"value":{"type":"api","key":"NOTTHISKEYXXXX"}},'
|
||||
'{"integrationID":"zai","active":true,"value":{"type":"api","key":"%s"}}]\'\n' % SECRET)
|
||||
LEAKY_EXPORT = '#!/bin/sh\necho "%s" ; echo "%s" >&2\nexit 1\n' % (SECRET, SECRET)
|
||||
PATHS = ["--remaining-path", "data.limits[type=CREDIT_LIMIT].remaining", "--reset-path", "data.limits[type=CREDIT_LIMIT].nextResetTime",
|
||||
"--total-path", "data.limits[type=CREDIT_LIMIT].total"]
|
||||
|
||||
|
||||
class Quota:
|
||||
"""A local stand-in for a provider's allowance endpoint."""
|
||||
|
||||
def __init__(self):
|
||||
owner = self
|
||||
self.hits, self.leaks, self.mode = [], [], "ok"
|
||||
self.windows = [(100, 1000, 4102444800000), (900, 1000, 4102444900000)]
|
||||
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
auth = self.headers.get("Authorization")
|
||||
if self.path == "/leak":
|
||||
owner.leaks.append(auth)
|
||||
self.send_response(200); self.end_headers(); self.wfile.write(b"{}")
|
||||
return
|
||||
owner.hits.append(auth)
|
||||
if owner.mode == "redirect":
|
||||
self.send_response(302); self.send_header("Location", "http://127.0.0.1:%d/leak" % owner.port); self.end_headers()
|
||||
elif owner.mode == "hang":
|
||||
time.sleep(3)
|
||||
elif auth != SECRET:
|
||||
body = ('{"error":"bad key %s"}' % auth).encode()
|
||||
self.send_response(401); self.end_headers(); self.wfile.write(body)
|
||||
else:
|
||||
body = json.dumps({"data": {"limits": [{"type": "CREDIT_LIMIT", "remaining": r, "total": t, "nextResetTime": n}
|
||||
for r, t, n in owner.windows]}}).encode()
|
||||
self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
self.port = self.server.server_address[1]
|
||||
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
return "http://127.0.0.1:%d/quota" % self.port
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
self.server.server_close()
|
||||
|
||||
|
||||
class ProviderCase(TD.DiscoveryCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.exe("multi", MULTI)
|
||||
f = TD.driver_file(os.path.join(self.tmp, "m.json"), name="multi", exe="multi",
|
||||
run=["multi", "{model_flag}", "-p", "{prompt}"], list=["multi", "models"], plan=None,
|
||||
limit_signatures=["allowance used up"], tokens_regex=None)
|
||||
r = self.sisi("workers", "learn", "multi", "--record", f)
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.write_cfg({"learning": {"agent_relayed_approval": True}, "discovery": {"allowance_timeout_s": 1}})
|
||||
|
||||
def cands(self):
|
||||
return {c["worker"]: c for c in workers.build_candidates()}
|
||||
|
||||
def brief(self):
|
||||
p = os.path.join(self.proj, "brief.md")
|
||||
open(p, "w").write(TD.BRIEF)
|
||||
return p
|
||||
|
||||
def fact(self, worker, price, plan=None):
|
||||
args = ["workers", "fact", worker, "--price", str(price), "--source", "test"] + (["--plan", plan] if plan else [])
|
||||
self.assertEqual(self.sisi(*args).returncode, 0)
|
||||
|
||||
def define_probe(self, quota, approve=True, export=AUTH_EXPORT, extra=()):
|
||||
self.exe("authexport", export)
|
||||
r = self.sisi("workers", "allowance", "zai", "--url", quota.url, "--header", "Authorization={secret}",
|
||||
"--secret-from-command", "authexport", "--secret-path", "[integrationID=zai][active=true].value.key",
|
||||
*PATHS, *extra)
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
if approve:
|
||||
self.assertEqual(self.sisi("approve", "probe-zai", "--yes").returncode, 0)
|
||||
return r
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 7: one tool, several providers
|
||||
|
||||
|
||||
def c(worker, tool, **kw):
|
||||
model = worker if "/" in worker else worker.split("/")[-1]
|
||||
return dict({"worker": worker, "tool": tool, "model": worker if tool == "multi" else worker.split("/", 1)[-1],
|
||||
"plan": "flat", "cost": None, "usable": True, "allowance_pct_left": None, "aliases": [worker],
|
||||
"maker": "m"}, **kw)
|
||||
|
||||
|
||||
class PerProviderConstraints(unittest.TestCase):
|
||||
"""A constraint on provider `a-b` never reaches provider `a-b-c`, nor a model `a-b` under another tool."""
|
||||
|
||||
def setUp(self):
|
||||
self.ab, self.abc, self.other = c("a-b/x", "multi"), c("a-b-c/y", "multi"), c("other/a-b", "other")
|
||||
|
||||
def test_a_provider_pattern_matches_the_provider_exactly(self):
|
||||
hits = [w["worker"] for w in (self.ab, self.abc, self.other) if routing._pattern_match(w, [{"pattern": "a-b/"}])]
|
||||
self.assertEqual(hits, ["a-b/x"])
|
||||
self.assertEqual(routing._pattern_match(c("xa-b/z", "multi"), [{"pattern": "a-b/"}]), None)
|
||||
|
||||
def test_avoid_and_prefer_by_provider_pattern(self):
|
||||
avoid = routing.choose([self.ab, self.abc, self.other], [], {}, "read", 1, now=1.0, avoid=[{"pattern": "a-b/"}])
|
||||
self.assertNotEqual(avoid["choice"]["worker"], "a-b/x")
|
||||
self.assertIn(avoid["choice"]["worker"], ("a-b-c/y", "other/a-b"))
|
||||
prefer = routing.choose([self.abc, self.other, self.ab], [], {}, "read", 1, now=1.0, prefer=[{"pattern": "a-b/"}])
|
||||
self.assertEqual(prefer["choice"]["worker"], "a-b/x")
|
||||
|
||||
def test_a_provider_availability_mark_reaches_that_provider_only(self):
|
||||
down = {"a-b": {"reason": "limit", "retry_at": 9e9, "scope": "provider"}}
|
||||
self.assertIsNotNone(routing._down_entry(self.ab, down, 1.0))
|
||||
self.assertIsNone(routing._down_entry(self.abc, down, 1.0))
|
||||
self.assertIsNone(routing._down_entry(self.other, down, 1.0), "a model named a-b under another tool is not the provider")
|
||||
r = routing.choose([self.ab, self.abc, self.other], [], down, "read", 1, now=1.0)
|
||||
self.assertNotEqual(r["choice"]["worker"], "a-b/x")
|
||||
|
||||
def test_only_scopes_to_its_provider(self):
|
||||
kept, out = workers.apply_limits([self.ab, self.abc, self.other],
|
||||
{"only": [{"provider": "a-b", "patterns": ["zzz"], "why": "w"}]})
|
||||
self.assertEqual([w["worker"] for w in kept], ["a-b-c/y", "other/a-b"])
|
||||
self.assertEqual([w for w, _ in out], ["a-b/x"])
|
||||
|
||||
def test_notes_by_provider_pattern(self):
|
||||
by = {w["worker"]: w for w in (self.ab, self.abc, self.other)}
|
||||
lines = workers.notes_for(by, self.abc, [("a-b/x", "r"), ("other/a-b", "r")], notes=[{"pattern": "a-b/", "text": "T", "why": "w"}])
|
||||
self.assertEqual(len(lines), 1)
|
||||
self.assertIn("passed over: a-b/x", lines[0])
|
||||
self.assertNotIn("the chosen worker", lines[0])
|
||||
self.assertNotIn("other/a-b", lines[0])
|
||||
|
||||
|
||||
class ProviderPlans(ProviderCase):
|
||||
def test_a_providers_plan_costs_its_workers_as_flat_and_others_stay_unknown(self):
|
||||
self.assertEqual(self.sisi("workers", "plan", "zai", "flat", "--source", "owner", "--note", "quarterly subscription").returncode, 0)
|
||||
cands = self.cands()
|
||||
self.assertEqual(cands["zai/a"]["plan"], "flat")
|
||||
self.assertEqual(cands["zai/b"]["plan"], "flat")
|
||||
self.assertEqual(cands["other/c"]["plan"], "per-use") # unproven and no plan fact: per-use
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("provider zai: flat-rate plan - quarterly subscription (owner,", shown)
|
||||
self.assertIn("models: a, b", shown)
|
||||
|
||||
def test_free_counts_as_flat_and_a_models_own_plan_fact_wins(self):
|
||||
self.sisi("workers", "plan", "zai", "free", "--source", "s")
|
||||
self.assertEqual(self.cands()["zai/a"]["plan"], "flat")
|
||||
self.fact("zai/a", 2, plan="per-use")
|
||||
self.assertEqual(self.cands()["zai/a"]["plan"], "per-use")
|
||||
self.assertEqual(self.cands()["zai/b"]["plan"], "flat")
|
||||
|
||||
def test_the_lighter_model_of_a_flat_plan_takes_routine_work(self):
|
||||
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
|
||||
self.fact("zai/a", 3)
|
||||
self.fact("zai/b", 1)
|
||||
r = self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertEqual(r.stdout.splitlines()[0], "zai/b", r.stdout)
|
||||
|
||||
def test_a_plan_needs_a_source_and_a_known_kind_and_can_be_removed(self):
|
||||
for args in (("zai", "flat"), ("zai", "monthly", "--source", "s"), ("Bad Name", "flat", "--source", "s"), ()):
|
||||
self.assertEqual(self.sisi("workers", "plan", *args).returncode, 1, args)
|
||||
self.sisi("workers", "plan", "zai", "flat", "--source", "s")
|
||||
self.assertEqual(self.sisi("workers", "plan", "zai", "--remove").returncode, 0)
|
||||
self.assertEqual(self.cands()["zai/a"]["plan"], "per-use")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 8: the owner's word
|
||||
|
||||
|
||||
class Vouch(unittest.TestCase):
|
||||
def new(self, worker, **kw):
|
||||
return dict(c(worker, "multi"), unproven=True, unproven_ok=True, **kw)
|
||||
|
||||
def test_a_vouched_worker_is_capable_up_to_its_level_with_the_owners_word_as_evidence(self):
|
||||
a = self.new("zai/a", vouch={"level": 2, "why": "Verified by hand", "date": "2026-11-23", "relayed": False})
|
||||
for d, ok in ((1, True), (2, True), (3, False)):
|
||||
r = routing.choose([a], [], {}, "impl", d, now=1.0)
|
||||
self.assertEqual(r["choice"] is not None, ok, d)
|
||||
r = routing.choose([a], [], {}, "impl", 2, now=1.0)
|
||||
text = "\n".join(routing.explain_choice(r, "impl", 2))
|
||||
self.assertIn("evidence (the owner's word): vouched for up to difficulty 2", text)
|
||||
self.assertIn("Verified by hand", text)
|
||||
|
||||
def test_proof_before_benchmark_a_vouch_outranks_a_benchmark_above_routine_work(self):
|
||||
vouched = self.new("zai/a", vouch={"level": 2, "why": "w", "date": "d", "relayed": False}, cost=5.0)
|
||||
bench = dict(c("big/b", "multi"), standing=95.0, cost=1.0)
|
||||
r = routing.choose([bench, vouched], [], {}, "impl", 2, now=1.0)
|
||||
self.assertEqual(r["choice"]["worker"], "zai/a")
|
||||
self.assertTrue(r["judged_first"])
|
||||
|
||||
def test_a_vouch_ranks_with_judged_proof_and_a_thick_bad_record_overrides_it(self):
|
||||
recs = TD.attempts("old/p", 8, "impl", 2)
|
||||
vouched = self.new("zai/a", vouch={"level": 2, "why": "w", "date": "d", "relayed": False}, cost=0.1)
|
||||
proven = c("old/p", "multi", cost=9.0)
|
||||
self.assertEqual(routing.choose([vouched, proven], recs, {}, "impl", 2, now=1.0)["choice"]["worker"], "zai/a",
|
||||
"both are proof: the cheaper takes it")
|
||||
dear = dict(vouched, cost=20.0)
|
||||
self.assertEqual(routing.choose([dear, proven], recs, {}, "impl", 2, now=1.0)["choice"]["worker"], "old/p")
|
||||
bad = TD.attempts("zai/a", 8, "impl", 2, outcome="rejected")
|
||||
a = routing.assess(routing.candidate_stats([vouched], bad), "zai/a", "impl", 2, vouch=2)
|
||||
self.assertTrue(a["bad"])
|
||||
self.assertFalse(a["capable"])
|
||||
|
||||
def test_a_thin_record_with_repeated_rejections_cancels_the_word(self):
|
||||
a = routing.assess(routing.candidate_stats([c("zai/a", "multi")], TD.attempts("zai/a", 2, "impl", 2, outcome="rejected")),
|
||||
"zai/a", "impl", 2, vouch=2)
|
||||
self.assertFalse(a["capable"])
|
||||
|
||||
def test_an_unvouched_new_worker_stays_on_routine_work(self):
|
||||
flash = self.new("zai/flash")
|
||||
self.assertIsNone(routing.choose([flash], [], {}, "impl", 2, now=1.0)["choice"])
|
||||
self.assertEqual(routing.choose([flash], [], {}, "impl", 1, now=1.0)["choice"]["worker"], "zai/flash")
|
||||
|
||||
|
||||
class VouchCommand(ProviderCase):
|
||||
def route_line(self, *a):
|
||||
return self.sisi("route", *a).stdout.splitlines()[:1]
|
||||
|
||||
def setup_prices(self):
|
||||
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
|
||||
self.fact("zai/a", 3)
|
||||
self.fact("zai/b", 1)
|
||||
|
||||
def typed_session(self, words):
|
||||
from sisi import store
|
||||
tp = os.path.join(self.tmp, "t.jsonl")
|
||||
with open(tp, "w") as f:
|
||||
f.write(json.dumps({"type": "user", "message": {"content": words}}) + "\n")
|
||||
f.write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "the agent says: invented owner words"}]}}) + "\n")
|
||||
store.save_session("s1", {"session_id": "s1", "transcript_path": tp})
|
||||
return {"SISI_SESSION_ID": "s1"}
|
||||
|
||||
def test_the_owner_vouches_and_routing_uses_it_then_remove_undoes_it(self):
|
||||
self.setup_prices()
|
||||
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "2"), ["zai/a"])
|
||||
env = self.typed_session("Verified: opencode run -m zai/a completes a tool-using edit-and-test task")
|
||||
r = self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "Verified: opencode run -m zai/a completes a tool-using edit-and-test task", env=env)
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertIn("typed by the owner", r.stdout)
|
||||
out = self.sisi("route", "--kind", "impl", "--difficulty", "2", "--explain").stdout
|
||||
self.assertEqual(out.splitlines()[0], "zai/a", out)
|
||||
self.assertIn("the owner's word", out)
|
||||
self.assertIn("unproven: check this result", out, "a vouched worker is still checked a level more carefully")
|
||||
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "3"), ["zai/a"])
|
||||
self.assertIn("Vouched: zai/a up to difficulty 2", self.sisi("workers").stdout)
|
||||
self.assertEqual(self.sisi("workers", "vouch", "zai/a", "--remove").returncode, 0)
|
||||
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "2"), ["zai/a"])
|
||||
|
||||
def test_a_vouch_with_invented_owner_words_counts_only_up_to_difficulty_two(self):
|
||||
self.setup_prices()
|
||||
for env in (None, self.typed_session("something else the owner typed entirely")):
|
||||
r = self.sisi("workers", "vouch", "zai/a", "--up-to", "3", "--why", "the owner said it works for everything", env=env)
|
||||
self.assertEqual(r.returncode, 0)
|
||||
self.assertIn("relayed by an agent", r.stdout)
|
||||
self.assertIn("counted only up to difficulty 2", r.stdout)
|
||||
self.assertEqual(discovery.load_vouches()["zai/a"]["origin"], "relayed by an agent")
|
||||
self.assertEqual(self.cands()["zai/a"]["vouch"]["level"], 2)
|
||||
self.assertEqual(self.route_line("--kind", "impl", "--difficulty", "2"), ["zai/a"])
|
||||
self.assertNotEqual(self.route_line("--kind", "impl", "--difficulty", "3"), ["zai/a"])
|
||||
env = self.typed_session("Verified by hand: it handles everything")
|
||||
self.sisi("workers", "vouch", "zai/a", "--up-to", "3", "--why", "Verified by hand: it handles everything", env=env)
|
||||
self.assertEqual(self.cands()["zai/a"]["vouch"]["level"], 3)
|
||||
|
||||
def test_once_it_has_its_own_thick_record_the_vouch_is_ignored(self):
|
||||
self.setup_prices()
|
||||
self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "x words")
|
||||
self.assertIn("vouch", self.cands()["zai/a"])
|
||||
for row in TD.attempts("zai/a", 8, "impl", 1):
|
||||
workers.append_record(row)
|
||||
self.assertNotIn("vouch", self.cands()["zai/a"])
|
||||
self.assertIn("ignored now: its own record decides", self.sisi("workers").stdout)
|
||||
|
||||
def test_bad_arguments_are_refused(self):
|
||||
for args in (("zai/a",), ("zai/a", "--up-to", "5", "--why", "x"), ("zai/a", "--up-to", "2"), ("zai/a", "--up-to", "2", "--why", " ")):
|
||||
self.assertEqual(self.sisi("workers", "vouch", *args).returncode, 1, args)
|
||||
self.assertEqual(discovery.load_vouches(), {})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- item 9: allowance probes and failure phrases
|
||||
|
||||
|
||||
class PathLanguage(unittest.TestCase):
|
||||
def test_paths_over_the_shapes_the_probe_reads(self):
|
||||
export = [{"integrationID": "x", "active": True, "value": {"key": "k0"}},
|
||||
{"integrationID": "zai", "active": False, "value": {"key": "k1"}},
|
||||
{"integrationID": "zai", "active": True, "value": {"key": "k2"}}]
|
||||
self.assertEqual(discovery.path_values(export, "[integrationID=zai][active=true].value.key"), ["k2"])
|
||||
self.assertEqual(discovery.path_values(export, "[2].value.key"), ["k2"])
|
||||
self.assertEqual(discovery.path_values(export, "[*].integrationID"), ["x", "zai", "zai"])
|
||||
body = {"data": {"limits": [{"type": "A", "remaining": 1}, {"type": "CREDIT_LIMIT", "remaining": 2}, {"type": "CREDIT_LIMIT", "remaining": 3}]}}
|
||||
self.assertEqual(discovery.path_values(body, "data.limits[type=CREDIT_LIMIT].remaining"), [2, 3])
|
||||
self.assertEqual(discovery.path_values("tokens left: 42 of 100", "re:left: (\\d+)"), ["42"])
|
||||
self.assertEqual(discovery.path_values(body, "data.nothing.here"), [])
|
||||
for bad in ("", "data..x", "data[", "a b"):
|
||||
with self.assertRaises(ValueError):
|
||||
discovery.path_values(body, bad)
|
||||
|
||||
def test_times_in_seconds_milliseconds_and_dates(self):
|
||||
self.assertEqual(discovery.time_value(1795000000), 1795000000.0)
|
||||
self.assertEqual(discovery.time_value(1795000000000), 1795000000.0)
|
||||
self.assertEqual(discovery.time_value("1795000000000"), 1795000000.0)
|
||||
self.assertEqual(discovery.time_value("2026-11-23T10:00:00+00:00"), 1795428000.0)
|
||||
self.assertIsNone(discovery.time_value("soon"))
|
||||
self.assertIsNone(discovery.time_value(True))
|
||||
|
||||
def test_several_windows_decide_by_the_smallest_remaining_and_the_reset_that_restores_service(self):
|
||||
st = discovery.allowance_state({"windows": [{"remaining": 0, "reset": 100.0}, {"remaining": 0, "reset": 500.0}, {"remaining": 9, "reset": 50.0}]})
|
||||
self.assertTrue(st["exhausted"])
|
||||
self.assertEqual(st["until"], 500.0, "back only when every exhausted window has reset")
|
||||
st = discovery.allowance_state({"windows": [{"remaining": 0, "reset": 100.0, "total": 10}, {"remaining": 5, "reset": 500.0, "total": 10}]})
|
||||
self.assertEqual(st["until"], 100.0)
|
||||
self.assertEqual(st["pct"], 0.0)
|
||||
self.assertIsNone(discovery.allowance_state({"windows": [{"remaining": 0, "reset": None}]})["until"])
|
||||
self.assertFalse(discovery.allowance_state({"windows": [{"remaining": 3, "reset": 1.0}]})["exhausted"])
|
||||
|
||||
|
||||
class AllowanceProbe(ProviderCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.q = Quota()
|
||||
self.addCleanup(self.q.close)
|
||||
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
|
||||
self.fact("zai/a", 3)
|
||||
self.fact("zai/b", 1)
|
||||
self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "words")
|
||||
self.fact("other/c", 5, plan="flat")
|
||||
|
||||
def everything_stored(self):
|
||||
text = ""
|
||||
for root in (self.data, self.state):
|
||||
for dp, _dn, fns in os.walk(root):
|
||||
for f in fns:
|
||||
try:
|
||||
text += open(os.path.join(dp, f), errors="replace").read()
|
||||
except OSError:
|
||||
pass
|
||||
return text
|
||||
|
||||
def test_a_probe_waits_for_the_owner_and_is_never_read_before(self):
|
||||
self.define_probe(self.q, approve=False)
|
||||
self.assertIn("WAITING FOR THE OWNER", self.sisi("approve").stdout)
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("allowance probe waits for the owner", shown)
|
||||
self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertEqual(self.q.hits, [], "not one request before the owner approved")
|
||||
self.write_cfg({"discovery": {"allowance_timeout_s": 1}}) # no relay: an agent cannot decide
|
||||
self.assertEqual(self.sisi("approve", "probe-zai", "--yes").returncode, 2)
|
||||
self.assertEqual(self.q.hits, [])
|
||||
|
||||
def test_workers_shows_the_allowance_and_the_key_is_used_once_and_stored_nowhere(self):
|
||||
self.define_probe(self.q)
|
||||
r = self.sisi("workers")
|
||||
self.assertIn("allowance left: 10% (smallest window)", r.stdout)
|
||||
self.assertRegex(r.stdout, "next reset (2099|2100)-")
|
||||
self.assertEqual(self.q.hits, [SECRET])
|
||||
out = self.sisi("route", "--kind", "read", "--difficulty", "1", "--explain")
|
||||
self.assertEqual(self.q.hits, [SECRET], "routing reads the cached reading: it is younger than a few minutes")
|
||||
for text in (r.stdout, r.stderr, out.stdout, out.stderr, self.everything_stored()):
|
||||
self.assertNotIn(SECRET, text)
|
||||
self.assertNotIn("NOTTHISKEYXXXX", self.everything_stored())
|
||||
|
||||
def test_routing_reads_again_when_the_reading_is_old(self):
|
||||
self.define_probe(self.q)
|
||||
self.sisi("workers")
|
||||
with mock.patch.object(time, "time", return_value=time.time() + 400):
|
||||
self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertEqual(len(self.q.hits), 2)
|
||||
|
||||
def test_a_failing_probe_command_that_echoes_the_key_leaks_nothing(self):
|
||||
self.define_probe(self.q, export=LEAKY_EXPORT)
|
||||
r = self.sisi("workers")
|
||||
self.assertIn("the probe failed (the secret command exited with status 1)", r.stdout)
|
||||
for text in (r.stdout, r.stderr, self.everything_stored()):
|
||||
self.assertNotIn(SECRET, text)
|
||||
self.assertEqual(self.q.hits, [])
|
||||
|
||||
def test_a_server_that_echoes_the_key_back_leaks_nothing(self):
|
||||
self.define_probe(self.q, export=AUTH_EXPORT.replace(SECRET, SECRET + "WRONG"))
|
||||
r = self.sisi("workers")
|
||||
self.assertIn("the server answered HTTP 401", r.stdout)
|
||||
for text in (r.stdout, r.stderr, self.everything_stored()):
|
||||
self.assertNotIn(SECRET + "WRONG", text)
|
||||
|
||||
def test_a_redirect_is_never_followed_so_the_key_goes_nowhere_else(self):
|
||||
self.q.mode = "redirect"
|
||||
self.define_probe(self.q)
|
||||
r = self.sisi("workers")
|
||||
self.assertIn("a redirect, which is never followed", r.stdout)
|
||||
self.assertEqual(self.q.leaks, [])
|
||||
self.assertEqual(self.q.hits, [SECRET])
|
||||
|
||||
def test_a_probe_that_times_out_or_fails_changes_nothing_and_says_so_in_workers_only(self):
|
||||
self.q.mode = "hang"
|
||||
self.define_probe(self.q)
|
||||
before = self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertEqual(before.returncode, 0, before.stdout)
|
||||
self.assertNotIn("probe", before.stdout)
|
||||
self.assertEqual(workers.read_availability(), {})
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("the probe failed (the request failed", shown)
|
||||
self.assertEqual(workers.read_availability(), {})
|
||||
|
||||
def test_a_definition_that_could_send_the_key_somewhere_else_is_refused(self):
|
||||
self.exe("authexport", AUTH_EXPORT)
|
||||
base = ["workers", "allowance", "zai", "--header", "Authorization={secret}", "--secret-from-command", "authexport",
|
||||
"--secret-path", "a.b", *PATHS]
|
||||
for url in ("http://example.com/quota", "ftp://x/y", "https://user:pw@example.com/q", "https://example.com/q?k={secret}", ""):
|
||||
self.assertEqual(self.sisi(*base, "--url", url).returncode, 1, url)
|
||||
self.assertEqual(self.sisi("workers", "allowance", "zai", "--url", self.q.url, "--header", "Authorization=fixed",
|
||||
"--secret-from-command", "authexport", "--secret-path", "a.b", *PATHS).returncode, 1)
|
||||
self.assertEqual(self.sisi("workers", "allowance", "zai", "--url", self.q.url, "--header", "Authorization={secret}",
|
||||
"--secret-from-command", "authexport", "--secret-path", "a..b", *PATHS).returncode, 1)
|
||||
self.assertEqual(load_providers_allowance(), None)
|
||||
|
||||
def test_zero_remaining_marks_the_provider_down_until_the_probe_reset_and_routing_falls_back(self):
|
||||
self.q.windows = [(0, 1000, 4102444800000), (500, 1000, 4102444900000)]
|
||||
self.define_probe(self.q)
|
||||
shown = self.sisi("workers").stdout
|
||||
self.assertIn("NONE LEFT", shown)
|
||||
down = workers.read_availability()["zai"]
|
||||
self.assertEqual(down["retry_at"], 4102444800.0)
|
||||
self.assertEqual(down["scope"], "provider")
|
||||
r = self.sisi("route", "--kind", "read", "--difficulty", "1", "--explain")
|
||||
self.assertEqual(r.stdout.splitlines()[0], "other/c", r.stdout)
|
||||
self.assertIn("zai", r.stdout)
|
||||
# the provider's allowance comes back: the probe's own mark is cleared and zai is routable again
|
||||
self.q.windows = [(800, 1000, 4102444800000)]
|
||||
with mock.patch.object(time, "time", return_value=time.time() + 400):
|
||||
r = self.sisi("route", "--kind", "read", "--difficulty", "1")
|
||||
self.assertEqual(r.stdout.splitlines()[0], "zai/b")
|
||||
self.assertNotIn("zai", workers.read_availability())
|
||||
|
||||
def test_a_spent_explicit_worker_falls_back_to_another_automatically(self):
|
||||
self.q.windows = [(0, 1000, 4102444800000)]
|
||||
self.define_probe(self.q)
|
||||
r = self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", "zai/b")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertIn("has no allowance left until its reset; choosing another worker", r.stdout)
|
||||
self.assertNotIn("worker: zai/", r.stdout)
|
||||
|
||||
def test_a_limit_failure_takes_its_reset_time_from_the_probe(self):
|
||||
self.q.windows = [(50, 1000, 4102444800000)]
|
||||
self.define_probe(self.q)
|
||||
self.sisi("workers") # reads 5% left; the reading stays fresh for a few minutes
|
||||
self.q.windows = [(0, 1000, 4102444800000)] # spent by the time the run fails
|
||||
with mock.patch.dict(os.environ, {"FAKE_MODE": "quota"}):
|
||||
self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", "zai/b")
|
||||
self.assertEqual(self.q.hits.count(SECRET), 2, "once for `workers`, once more when the limit was reported")
|
||||
self.assertEqual(workers.read_availability()["zai"]["retry_at"], 4102444800.0)
|
||||
|
||||
|
||||
def load_providers_allowance():
|
||||
return (discovery.load_providers().get("zai") or {}).get("allowance")
|
||||
|
||||
|
||||
class FailurePhrases(ProviderCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.sisi("workers", "plan", "zai", "flat", "--source", "owner")
|
||||
self.sisi("workers", "vouch", "zai/a", "--up-to", "2", "--why", "words")
|
||||
self.fact("zai/a", 3)
|
||||
self.fact("zai/b", 1)
|
||||
self.fact("other/c", 2)
|
||||
|
||||
def run_a(self, mode, worker="zai/b"):
|
||||
with mock.patch.dict(os.environ, {"FAKE_MODE": mode}):
|
||||
return self.sisi("delegate", "--kind", "read", "--difficulty", "1", "--brief", self.brief(), "--worker", worker)
|
||||
|
||||
def test_the_providers_own_code_is_an_auth_problem_not_a_limit_and_only_that_provider_is_down(self):
|
||||
text = self.run_a("code1113").stdout
|
||||
self.assertIn("is unavailable (limit", text, "without the provider's phrase the built-in classifier says limit")
|
||||
workers.write_json(workers.availability_path(), {})
|
||||
self.assertEqual(self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth").returncode, 0)
|
||||
r = self.run_a("code1113")
|
||||
self.assertIn("zai/b is unavailable (auth", r.stdout)
|
||||
avail = workers.read_availability()
|
||||
self.assertIn("zai", avail)
|
||||
self.assertEqual(avail["zai"]["reason"], "auth")
|
||||
self.assertNotIn("multi", avail, "the tool is not marked down: its other provider still works")
|
||||
route = self.sisi("route", "--kind", "read", "--difficulty", "1").stdout.splitlines()[0]
|
||||
self.assertEqual(route, "other/c")
|
||||
self.assertIn("other/c", self.run_a("", worker="other/c").stdout)
|
||||
self.assertIn("failure phrase", self.sisi("workers").stdout)
|
||||
|
||||
def test_a_phrase_can_name_the_reset_time(self):
|
||||
reset = time.time() + 7200
|
||||
iso = time.strftime("%Y-%m-%dT%H:%M:%S+00:00", time.gmtime(reset))
|
||||
self.sisi("workers", "signature", "zai", "--match", "limit reached", "--class", "limit", "--until-path", "error.resetAt")
|
||||
self.exe("multi", MULTI.replace("RESETAT", iso))
|
||||
self.run_a("reset")
|
||||
got = workers.read_availability()["zai"]
|
||||
self.assertEqual(got["reason"], "limit")
|
||||
self.assertAlmostEqual(got["retry_at"], reset, delta=5)
|
||||
|
||||
def test_signature_arguments_are_checked_and_listed_and_removed(self):
|
||||
for args in (("zai", "--match", "ab", "--class", "auth"), ("zai", "--match", "something", "--class", "weird"),
|
||||
("zai", "--match", "re:(", "--class", "auth"), ("zai", "--match", "something", "--class", "auth", "--until-path", "a..b")):
|
||||
self.assertEqual(self.sisi("workers", "signature", *args).returncode, 1, args)
|
||||
self.sisi("workers", "signature", "zai", "--match", "some phrase", "--class", "error")
|
||||
self.assertIn("'some phrase' is error", self.sisi("workers", "signature").stdout)
|
||||
self.sisi("workers", "signature", "zai", "--match", "some phrase", "--remove")
|
||||
self.assertNotIn("some phrase", self.sisi("workers", "signature").stdout)
|
||||
|
||||
def test_a_phrase_of_one_provider_never_classifies_another_providers_output(self):
|
||||
self.sisi("workers", "signature", "zai", "--match", "re:\\b1113\\b", "--class", "auth")
|
||||
self.assertIsNone(discovery.provider_failure({"worker": "other/c"}, "code 1113"))
|
||||
self.assertIsNone(discovery.provider_failure({"worker": "zai-x/c"}, "code 1113"))
|
||||
self.assertIsNotNone(discovery.provider_failure({"worker": "zai/c"}, "code 1113"))
|
||||
|
||||
def test_the_other_provider_works_beside_one_that_is_out(self):
|
||||
self.run_a("quota")
|
||||
self.assertIn("zai", workers.read_availability())
|
||||
r = self.run_a("quota", worker="other/c")
|
||||
self.assertEqual(r.returncode, 0, r.stdout)
|
||||
self.assertIn("worker: other/c", r.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user