"""Compaction decisions use the last request's usage without corrupting replay. How a request is sized from what earlier replies reported (a measurement used only while the request continues the measured one, new tool results added on, a reply without usage falling back to the estimate, a count endpoint winning) is checked over generated request sequences in apps/albedo/test/albedo/model_loop/measured_test.gleam. These scenarios keep the wiring: the measurement carried within a turn and across a restart, the count endpoint, a changed projection or model, and the transcript's row links.""" import json import sqlite3 import unittest from harness import Albedo, Provider, Reply, exclusive, text class CompactionProviderUsageTest(unittest.TestCase): def session_with_window(self, app, tokens=50000): session = app.session() route = f"/sessions/{session}/configuration" with app.api(route) as response: etag = response.headers["ETag"] app.api( route, {"context_window": tokens}, method="PATCH", headers={"If-Match": etag}, ).close() return session # exclusive: restarts the daemon between the turns @exclusive def test_low_usage_survives_a_daemon_restart(self): """A reply's low reported usage sizes the next step of its turn, so a large opaque replay is neither compacted nor re-estimated by its bytes, and a new turn after a restart still continues that measurement.""" usage = {"input_tokens": 10, "output_tokens": 2} opaque = "opaque:" + "x" * 400000 summaries = [] observations = [] armed = False called = 0 def reply(request): nonlocal called inputs = request["input"] last = inputs[-1] if inputs else {} content = last.get("content", "") if isinstance(content, list): content = "".join(part.get("text", "") for part in content) replayed_summary = last.get("role") == "user" and ( '' in content ) if request.get("tool_choice") == "none" or replayed_summary: summaries.append(called) return text("older history summarized") if armed and called == 0: called += 1 response = { "id": "response", "status": "completed", "output": [ { "type": "reasoning", "id": "reasoning", "summary": [], "encrypted_content": opaque, }, { "type": "function_call", "id": "call", "call_id": "call-1", "name": "python", "arguments": '{"code":"print(123)"}', "status": "completed", }, ], "usage": usage, } return Reply( "raw", events=[{"type": "response.completed", "response": response}] ) if armed: with app.api(f"/sessions/{session}/context") as response: observations.append(json.load(response)["compaction"]) return text("done") # The replay carries a large encrypted blob that a provider counts as # few tokens, not by its bytes, so the plain replies stay flat. provider = Provider(reply, chunk_size=64000, usage="flat") self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = self.session_with_window(app) for prompt in ("older one", "older two", "older three"): app.prompt(session, prompt + " history" * 4000).close() app.idle(session) summaries.clear() armed = True app.prompt(session, "run a tool").close() app.idle(session) self.assertEqual(called, 1) self.assertEqual(summaries, []) self.assertTrue(observations) size = observations[-1]["size"] self.assertGreater(size["tokens"], 12) self.assertLess(size["tokens"], 1000) self.assertEqual(size["measured"]["source"], "reported_usage") request = provider.requests[-1]["request"] replay = [ item for item in request["input"] if item.get("type") == "reasoning" ] self.assertTrue( any(item.get("encrypted_content") == opaque for item in replay) ) self.assertTrue( any( item.get("type") == "function_call_output" for item in request["input"] ) ) requests_before = len(provider.requests) app.restart() app.prompt(session, "keep going in a new turn").close() app.idle(session) self.assertFalse(summaries, "the new turn discarded usable provider usage") self.assertGreater(len(provider.requests), requests_before) self.assertIn("done", json.dumps(app.history(session))) def test_high_usage_without_evictable_history_keeps_the_turn_running(self): def reply(request): if request["input"][-1].get("type") == "function_call_output": return text("continued without dropping the newest unit") return Reply( "python", "print(123)", usage={"input_tokens": 40000, "output_tokens": 2}, ) provider = Provider(reply) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = self.session_with_window(app) app.prompt(session, "run a tool").close() app.idle(session) self.assertIn( "continued without dropping the newest unit", json.dumps(app.history(session)), ) self.assertEqual(len(provider.requests), 2) def test_the_inspector_sizes_a_sent_request_by_its_reported_usage(self): # Without a count endpoint the request was estimated when prepared; # once its reply reports usage, that number measures the very request. provider = Provider( lambda _request: text( "done", usage={"input_tokens": 4321, "output_tokens": 5} ) ) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = self.session_with_window(app) app.prompt(session, "hello").close() app.idle(session) with app.api(f"/sessions/{session}/context") as response: size = json.load(response)["compaction"]["size"] self.assertEqual(size["measured"], {"tokens": 4321, "source": "reported_usage"}) self.assertIsNone(size["estimated"]) def test_the_trigger_reads_the_providers_count_of_the_request(self): counted = {"tokens": 100} summaries = [] def reply(request): if request.get("tool_choice") == "none": summaries.append(request) return text("older history summarized") return text("done", usage={"input_tokens": 100, "output_tokens": 2}) provider = Provider(reply, count=lambda _request: counted["tokens"]) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = self.session_with_window(app) for prompt in ("older one", "older two", "older three"): app.prompt(session, prompt + " history" * 4000).close() app.idle(session) self.assertEqual(summaries, []) self.assertTrue(provider.counts) with app.api(f"/sessions/{session}/context") as response: compaction = json.load(response)["compaction"] self.assertEqual(compaction["size"]["measured"]["source"], "count_endpoint") # The provider now counts the request near the window: it compacts # though its reported usage says the request is small. counted["tokens"] = 48000 app.prompt(session, "one more").close() app.idle(session) self.assertTrue(summaries) def test_a_changed_projection_or_model_discards_the_saved_measurement(self): observations = [] inspect = False def reply(_request): if inspect: with app.api(f"/sessions/{session}/context") as response: observations.append(json.load(response)["compaction"]) return text("ready", usage={"input_tokens": 10, "output_tokens": 2}) provider = Provider(reply) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = self.session_with_window(app) for prompt in ("older one", "older two", "older three"): app.prompt(session, prompt).close() app.idle(session) response = app.compact(session, {}) self.assertEqual(response["state"], "compacted") app.idle(session) # Compaction made no call: the footer's counts are the strategy's # size, and say so, not a call's own report. with app.api(f"/sessions/{session}") as response: footer = json.load(response)["usage"] self.assertIsNotNone(footer["size"]) self.assertEqual(footer["size"]["tokens"], footer["prompt_tokens"]) inspect = True app.prompt(session, "after compaction").close() app.idle(session) self.assertIsNotNone(observations[-1]["size"]["estimated"]) app.prompt(session, "same projection again").close() app.idle(session) # The same projection is still all estimate, now corrected by what # the route reported. size = observations[-1]["size"] self.assertIsNone(size["measured"]) self.assertEqual(size["estimated"]["correction"]["state"], "calibrated") route = f"/sessions/{session}/configuration" with app.api(route) as response: etag = response.headers["ETag"] app.api( route, {"model": "changed-model"}, method="PATCH", headers={"If-Match": etag}, ).close() app.prompt(session, "after model change").close() app.idle(session) self.assertIsNotNone(observations[-1]["size"]["estimated"]) class RowLinksTest(unittest.TestCase): def test_rows_link_to_the_calls_that_produced_and_first_sent_them(self): def reply(request): if request["input"][-1].get("type") == "function_call_output": return text("done", usage={"input_tokens": 120, "output_tokens": 3}) return Reply( "python", "print(1)", usage={"input_tokens": 100, "output_tokens": 7} ) provider = Provider(reply) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = app.session() app.prompt(session, "run a tool").close() app.idle(session) database = f"file:{app.home / 'albedo.sqlite'}?mode=ro" with sqlite3.connect(database, uri=True) as db: calls = [ row[0] for row in db.execute( "SELECT id FROM provider_requests WHERE session=? " "AND kind='turn' ORDER BY id", (session,), ) ] rows = db.execute( "SELECT row_class, produced_by, first_sent_by FROM transcript " "WHERE session=? ORDER BY seq", (session,), ).fetchall() self.assertEqual(len(calls), 2, rows) first, second = calls # The prompt went out with the first call; the tool call it answered # and the tool's result went out with the second; the answer is unsent. self.assertEqual(rows[0], ("user", None, first)) self.assertEqual(rows[-1][1:], (second, None)) middle = rows[1:-1] self.assertTrue(middle) for _, produced, sent in middle: self.assertIn(produced, (first, None), rows) self.assertEqual(sent, second, rows) self.assertIn(None, [produced for _, produced, _ in middle]) @exclusive def test_a_restart_keeps_the_one_boundary_of_unlinked_rows(self): # Rows written before links existed stay unlinked through a boundary # recorded once; a later boot must not record another. provider = Provider(lambda _request: text("done")) self.addCleanup(provider.close) with Albedo(provider, protocol="responses") as app: session = app.session() app.prompt(session, "before the restart").close() app.idle(session) app.restart() app.restart() database = f"file:{app.home / 'albedo.sqlite'}?mode=ro" with sqlite3.connect(database, uri=True) as db: boundaries = db.execute("SELECT since FROM transcript_links").fetchall() self.assertEqual(boundaries, [(0,)])