From f76a3b38917b885dced1dd72249a6bb98863308c Mon Sep 17 00:00:00 2001 From: Etienne Filhol Date: Wed, 2 Dec 2026 14:15:35 +0100 Subject: [PATCH] fix(standard): settle background Responses calls on polling --- app/nullius/standard/calls/relay.py | 79 +++++++++++++-- app/tests/test_standard_relay.py | 147 ++++++++++++++++++++++++++++ app/tests/test_standard_run.py | 43 ++++++++ 3 files changed, 262 insertions(+), 7 deletions(-) diff --git a/app/nullius/standard/calls/relay.py b/app/nullius/standard/calls/relay.py index 7a54f560a..abe297d81 100644 --- a/app/nullius/standard/calls/relay.py +++ b/app/nullius/standard/calls/relay.py @@ -15,6 +15,10 @@ user's price list, ``nullius.prices``), marked as an estimate. A Responses object answered 200 that failed (its ``end``) with no usage costs 0, marked as failed: the provider keeps no generation for it, and a key's usage compared with the relay's sum would show one billed after all. +A background Responses call keeps its booking until a terminal reply. Its +first terminal retrieval records the usage and cost under the original +model; repeated polls carry neither again. Polling, deletion and a known +response's cancellation remain available after admission closes. What the relay changes on the way is kept small, so a call through it costs what the same call made directly would: the connection to the provider is @@ -862,6 +866,8 @@ def __init__(self, base: str, key: str, record_dir: str, prices: Optional[Dict[s self.models: Dict[str, str] = {} self.embedding_models: Dict[str, str] = {} self.lock = threading.Lock() + self.response_lock = threading.Lock() + self.responses: Dict[tuple, dict] = {} # (route, response id): original call and its settlement self.pool = self.upstream.pool self.server: Optional[ThreadingHTTPServer] = None os.makedirs(record_dir, exist_ok=True) @@ -957,6 +963,10 @@ def _forward(self, h: BaseHTTPRequestHandler): return tag, rest = bits[1], "/" + bits[2] rest = rest[3:] if rest.startswith("/v1/") else rest + response_path = re.fullmatch(r"/responses/([^/]+)(/cancel)?", rest.split("?")[0]) + retrieval = response_path is not None and (h.command in ("GET", "DELETE") + or (h.command == "POST" and response_path[2] + and (tag, response_path[1]) in self.responses)) raw = h.rfile.read(int(h.headers.get("Content-Length") or 0)) try: req = json.loads(raw) if raw else {} @@ -991,10 +1001,10 @@ def _forward(self, h: BaseHTTPRequestHandler): if isinstance(req.get("model"), str) and self.reasoning.get(req["model"]): think(req, rest, self.reasoning[req["model"]], up.routed) raw, dumped = json.dumps(req).encode(), True - if not side and not self.models.get(tag) and self._asked(): + if not retrieval and not side and not self.models.get(tag) and self._asked(): h.send_error(400, "the unit was asked to stop") return - if self.max_calls and agent_route(tag) and h.command == "POST" and isinstance(req, dict) and req.get("model") and not _free(rest): + if self.max_calls and not retrieval and agent_route(tag) and h.command == "POST" and isinstance(req, dict) and req.get("model") and not _free(rest): with self.lock: made = self.answered.get(tag, 0) if made >= self.max_calls: @@ -1004,7 +1014,7 @@ def _forward(self, h: BaseHTTPRequestHandler): booking = booked = None # a call that names its model is booked, whatever its route, but a token count, which costs nothing and # reports no usage; one that names none (a cancellation, a body that is no request) has no price to book - if self.ledger is not None and h.command == "POST": + if self.ledger is not None and h.command == "POST" and not retrieval: if isinstance(req, dict) and req.get("model") and not _free(rest): booking, booked, why, by = self._book(req, raw, rest, tag, h) else: # nothing to price: sent as it is, but not once the run's cap is reached @@ -1051,12 +1061,41 @@ def _forward(self, h: BaseHTTPRequestHandler): back = [(n, v) for n, v in back if n.lower() in ("retry-after", "retry-after-ms")] body = json.dumps({"error": {"message": f"the endpoint answered 200 with {inside}"}}).encode() - def record(body): + def record_locked(body): + nonlocal booking, booked + response = None + if status == 200 and (response_path or rest.split("?")[0] == "/responses"): + chunks = [line[5:] for line in body.decode("utf-8", "replace").splitlines() + if line.startswith("data:")] if streamed else [body] + for chunk in chunks: + try: + candidate = json.loads(chunk) + except ValueError: + continue + if streamed and isinstance(candidate, dict): + candidate = candidate.get("response") + if isinstance(candidate, dict) and (candidate.get("object") == "response" or "output" in candidate): + response = candidate + state = None + if response_path and retrieval: + state = self.responses.get((tag, response_path[1])) + booking = booked = None + elif (rest.split("?")[0] == "/responses" and h.command == "POST" and response + and response.get("id") and (req.get("background") or response.get("status"))): + state = self.responses.setdefault((tag, response["id"]), + {"model": req.get("model"), "model_asked": asked, "side": side, + "booking": booking, "booked": booked, "done": False}) + terminal = response is not None and response.get("status") in ("completed", "failed", "incomplete", "cancelled") + charge = state is not None and terminal and not state["done"] + if state is not None: + booking, booked = (state["booking"], state["booked"]) if charge else (None, None) rec = {"t0": t0, "t1": time.time(), "path": rest, "model": req.get("model") if isinstance(req, dict) else None, "model_asked": asked, "status": status, "request": dict(_request_tail(req), sha256=_digest(req)) if isinstance(req, dict) else {}, "headers": sorted(k.lower() for k in forwarded(h.headers))} # the names sent on, never a value - if side: + if state is not None: + rec.update({k: state[k] for k in ("model", "model_asked")}) + if side or (state is not None and state["side"]): rec["side"] = True if isinstance(req, dict) and req.get("provider") is not None: # the routing as sent, and the caller's own the pin replaced: recorded copies, cleaned @@ -1067,7 +1106,7 @@ def record(body): rec["fields"] = request_fields(req) cost = None if status == 200 or cut_off: - if status == 200 and self.max_calls and agent_route(tag) and isinstance(req, dict) and req.get("model") and not _free(rest): + if status == 200 and not retrieval and self.max_calls and agent_route(tag) and isinstance(req, dict) and req.get("model") and not _free(rest): with self.lock: self.answered[tag] = self.answered.get(tag, 0) + 1 rec["reply"] = read_reply(rest, body, streamed) @@ -1078,6 +1117,9 @@ def record(body): pass cost, how = (0.0, "failed") if rec["reply"].get("end") == "failed" and not rec["reply"].get("usage") \ else self._cost(rec["model"], rec["reply"].get("usage")) + if (state is not None and not charge) or (retrieval and state is None): + cost = None + rec["reply"].pop("usage", None) if cost is not None: rec["cost_usd"], rec["cost_from"] = cost, how if status != 200: @@ -1094,7 +1136,19 @@ def record(body): rec["images"] = sent if empty: rec["answered"] = 200 - if booking is not None: + if charge and booking is not None: + whole = not (cut_off or rec.get("cost_from") == "failed") + state["settlement"] = (cost if whole or (cost is not None and cost > booked) else None, + ((rec.get("reply") or {}).get("usage") or {}).get("output") if whole else None) + rec["booked_usd"] = booked + if state is not None and "settlement" in state: + try: + known, output = state["settlement"] + self.ledger.settle(state["booking"], known, state["model"], output) + del state["settlement"] + except ledgers.Unavailable: + pass # a later poll retries settlement, without recording the cost twice + if booking is not None and state is None: rec["booked_usd"] = booked try: if status == 200 or cut or empty: # what it cost; unknown (no token count, cut off), the booking is kept whole @@ -1106,6 +1160,8 @@ def record(body): self.ledger.release(booking) except ledgers.Unavailable: pass # the booking stays held, against the cap + if charge: + state["done"] = True if number is not None: rec = {"n": number, **rec} with self.lock: @@ -1124,6 +1180,12 @@ def record(body): self.exchanges.write(tag, number, t0, rest, req if dumped else None, raw, {k: v for k, v in sent_headers.items() if not _CREDENTIAL.search(k)}, status, streamed, body) + def record(body): + # Polls can finish together. Claim the terminal usage and settle its + # original booking under one lock, including the calls.jsonl write. + with self.response_lock: + record_locked(body) + h.send_response(status) if not any(n.lower() == "content-type" for n, _ in back): back = back + [("Content-Type", kind)] @@ -1248,6 +1310,9 @@ def do_GET(self): def do_POST(self): self.forward() + def do_DELETE(self): + self.forward() + def forward(self): relay._forward(self) diff --git a/app/tests/test_standard_relay.py b/app/tests/test_standard_relay.py index a7376ca61..1e5996b62 100644 --- a/app/tests/test_standard_relay.py +++ b/app/tests/test_standard_relay.py @@ -1158,5 +1158,152 @@ def test_the_providers_word_on_when_to_call_again_is_read(self): self.assertIsNone(relay._code(b"not json")) + + +class BackgroundResponsesTest(unittest.TestCase): + """The provider finishes a booked call on retrieval, possibly many times.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.seen = [] + self.streamed = False + self.status = 200 + self.reply = {"object": "response", "id": "resp-1", "status": "queued", "output": [], "usage": None} + owner = self + + class Provider(Upstream): + def answer(self): + raw = self.rfile.read(int(self.headers.get("Content-Length", 0))) + owner.seen.append((self.command, self.path, self.headers.get("Authorization"), raw)) + body = json.dumps(owner.reply).encode() + if owner.streamed: + body = b'data: ' + json.dumps({"type": "response.completed", "response": owner.reply}).encode() + b'\n\ndata: [DONE]\n\n' + self.reply(owner.status, body, "text/event-stream" if owner.streamed else "application/json") + + do_POST = do_GET = do_DELETE = answer + + self.up = ThreadingHTTPServer(("127.0.0.1", 0), Provider) + threading.Thread(target=self.up.serve_forever, daemon=True).start() + self.addCleanup(self.up.server_close) + self.addCleanup(self.up.shutdown) + self.led = ledger.Ledger.create(os.path.join(self.tmp.name, "ledger.json"), 1.0) + self.r = relay.Relay(f"http://127.0.0.1:{self.up.server_address[1]}/v1", "provider-key", + os.path.join(self.tmp.name, "records"), model="m", + prices={"m": {"input": 100000, "output": 100000}}, + ledger=self.led.path, booking=lambda raw: 0.4).start() + self.addCleanup(self.r.stop) + + def call(self, method="POST", path="/responses", tag="u1", body=None): + data = json.dumps(body or {"model": "asked", "background": True, "input": "hi"}).encode() if method == "POST" else None + req = urllib.request.Request(self.r.url(tag) + path, data=data, method=method) + try: + with urllib.request.urlopen(req) as got: + return got.status, json.loads(got.read()) + except urllib.error.HTTPError as e: + return e.code, json.loads(e.read()) + + def finish(self, status="completed", usage=True): + self.reply.update(status=status, usage={"input_tokens": 2, "output_tokens": 3} if usage else None) + + def test_polls_settle_once_and_background_calls_reach_the_cap(self): + for i in range(2): + self.reply.update(id=f"resp-{i}", status="queued", usage=None) + self.assertEqual(self.call()[0], 200) + self.assertAlmostEqual(self.led.state()["held_usd"], 0.4) + self.assertEqual(self.led.state()["unsettled_usd"], 0) + path = f"/responses/resp-{i}" + self.assertEqual(self.call("GET", path)[1]["status"], "queued") + self.finish() + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(max_workers=4) as pool: + replies = list(pool.map(lambda _: self.call("GET", path + "?include=usage"), range(8))) + self.assertTrue(all(status == 200 and body == self.reply for status, body in replies)) + self.assertEqual(self.led.state()["held_usd"], 0) + self.assertAlmostEqual(self.led.state()["spent_usd"], (i + 1) * 0.5) + charged = [c for c in self.r.calls("u1") if "cost_usd" in c] + self.assertEqual([c["cost_usd"] for c in charged], [0.5, 0.5]) + self.assertTrue(all(c["model"] == "m" and c["model_asked"] == "asked" for c in charged)) + self.assertEqual(sum((c.get("reply", {}).get("usage") or {}).get("output", 0) for c in self.r.calls("u1")), 6) + sent = len(self.seen) + self.assertEqual(self.call()[0], 402) + self.assertEqual(len(self.seen), sent) + self.assertTrue(self.led.closed()) + self.assertEqual(self.call("GET", path)[0], 200) + self.assertEqual(self.call("DELETE", path)[0], 200) + self.assertEqual(self.seen[-1][:3], ("DELETE", "/v1" + path, "Bearer provider-key")) + self.assertEqual(self.led.state()["spent_usd"], 1.0) + + def test_failed_poll_retains_hold_and_other_routes_cannot_claim_it(self): + self.call() + self.finish() + self.call("GET", "/responses/resp-1", tag="u2") + self.assertEqual(self.led.state()["spent_usd"], 0) + self.assertEqual(self.led.state()["held_usd"], 0.4) + self.status = 503 + self.reply = {"error": {"message": "temporarily unavailable"}} + self.assertEqual(self.call("GET", "/responses/resp-1")[0], 503) + self.assertEqual(self.led.state()["held_usd"], 0.4) + self.status = 200 + self.reply = {"object": "response", "id": "resp-1", "output": []} + self.finish("incomplete") + self.call("GET", "/responses/resp-1") + self.assertEqual(self.led.state()["spent_usd"], 0.5) + + def test_terminal_failure_without_usage_keeps_conservative_unsettled_cost(self): + for status in ("failed", "cancelled", "completed"): + with self.subTest(status=status): + self.reply.update(id=status, status="queued", usage=None) + self.call() + self.finish(status, usage=False) + for _ in range(2): + self.call("GET", "/responses/" + status) + self.assertEqual(self.led.state()["held_usd"], 0) + if status != "completed": + # Give the next case room without changing the existing holds. + self.led.reopen(3.0) + self.assertAlmostEqual(self.led.state()["unsettled_usd"], 1.2) + self.assertEqual(self.led.state()["spent_usd"], 0) + + def test_immediate_completion_is_not_billed_again_on_poll(self): + self.finish() + self.call() + self.call("GET", "/responses/resp-1") + self.assertEqual(self.led.state()["spent_usd"], 0.5) + self.assertEqual(len([c for c in self.r.calls("u1") if "cost_usd" in c]), 1) + + def test_cancel_is_forwarded_after_cap_closes_and_settles_usage(self): + self.call() + self.led.reserve(2.0) # closes admission, but the outstanding call can be cancelled + self.finish("cancelled") + self.assertEqual(self.call("POST", "/responses/resp-1/cancel", body={})[0], 200) + self.assertEqual(self.seen[-1][:2], ("POST", "/v1/responses/resp-1/cancel")) + self.assertEqual(self.led.state()["spent_usd"], 0.5) + self.assertEqual(self.led.state()["held_usd"], 0) + + def test_settlement_failure_is_retried_without_duplicate_cost(self): + self.call() + self.finish() + with mock.patch.object(self.r.ledger, "settle", side_effect=ledger.Unavailable("try later")): + self.call("GET", "/responses/resp-1") + self.assertEqual(self.led.state()["held_usd"], 0.4) + self.call("GET", "/responses/resp-1") + self.assertEqual(self.led.state()["held_usd"], 0) + self.assertEqual(self.led.state()["spent_usd"], 0.5) + self.assertEqual(len([c for c in self.r.calls("u1") if "cost_usd" in c]), 1) + + def test_streamed_poll_and_uncapped_calls_also_record_usage_once(self): + self.r.ledger = None + self.call() + self.finish() + self.streamed = True + for _ in range(2): + with urllib.request.urlopen(self.r.url("u1") + "/responses/resp-1?stream=true") as got: + self.assertIn(b"response.completed", got.read()) + calls = self.r.calls("u1") + self.assertEqual([c["cost_usd"] for c in calls if "cost_usd" in c], [0.5]) + self.assertEqual(job._usage_total(calls)["output"], 3) + + if __name__ == "__main__": unittest.main() diff --git a/app/tests/test_standard_run.py b/app/tests/test_standard_run.py index 0a3d0f607..8a58e2a6c 100644 --- a/app/tests/test_standard_run.py +++ b/app/tests/test_standard_run.py @@ -489,6 +489,49 @@ def test_a_run_its_cap_stopped_before_any_verdict_is_no_failure(self): self.assertEqual(result["budget"]["spent_usd"], 0.0) self.assertFalse(failed) + def test_background_responses_stop_the_run_and_reach_trial_call_records(self): + import urllib.request + from nullius.standard.runner import job + + def respond(handler): + if handler.command == "POST": + handler.rfile.read(int(handler.headers["Content-Length"])) + completed = handler.command == "GET" + body = json.dumps({"object": "response", "id": "resp-1", + "status": "completed" if completed else "queued", "output": [], + "usage": {"input_tokens": 11, "output_tokens": 3} if completed else None}).encode() + handler.send_response(200) + handler.send_header("Content-Length", str(len(body))) + handler.end_headers() + handler.wfile.write(body) + + def background(runner, unit, ws, home, tag, setup, transcript, rl, *args, **kwargs): + request = urllib.request.Request(rl.unit_url + "/responses", + data=json.dumps({"model": "m-1", "background": True, "input": "hi"}).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(request) as got: + response = json.load(got) + for _ in range(2): + with urllib.request.urlopen(rl.unit_url + "/responses/" + response["id"]) as got: + json.load(got) + return "answer", job.trajectory_from_events([], rl.calls(tag), runner.other, "m-1", unit), {} + + with mock.patch.object(Echo, "do_POST", respond), mock.patch.object(Echo, "do_GET", respond), \ + mock.patch.object(run.Run, "drive_agent", background): + job_dir, failed, result, _ = self.calling(max_usd=0.00011) + self.assertFalse(failed) + self.assertTrue(result["budget"]["stopped"]) + self.assertEqual(result["budget"]["cut_off"], ["m3"]) + self.assertEqual(result["budget"]["not_run"], ["m4", "m5", "m6", "m7"]) + self.assertAlmostEqual(result["budget"]["spent_usd"], 0.00009) + calls = [] + for trial in parse.parse_job(job_dir).trials: + with open(os.path.join(job_dir, trial.trial_name, "agent", "calls.jsonl")) as f: + calls.extend(json.loads(line) for line in f) + self.assertEqual(len([c for c in calls if "cost_usd" in c]), 3) + self.assertAlmostEqual(job._usage_total(calls)["cost"], result["budget"]["spent_usd"]) + self.assertEqual(job._usage_total(calls)["output"], 9) + def test_a_repeated_runs_budget_names_each_attempt(self): job_dir, failed, result, said = self.calling(max_usd=0.00011, repeat=2) self.assertEqual(result["budget"]["cut_off"], ["m3 (attempt 1)"])