"""The prompt-cache warmer: an idle session whose children or background jobs still run re-sends its last request with a tiny output budget before the provider cache would expire. Catches: pings that rebuild the request instead of repeating the one the turn sent (which would compact or summarize), ping request rows that do not carry the turn's prefix identity, pings that commit or publish anything, warming that continues after the waking work finished, a session let go cold while its job runs on a remote host its kernel cannot list or kept warm for a remote service, a call lost or rebuilt differently across a daemon restart, a warmer stopped by the idle and unload sweeps, and a submit that cannot get through while a ping holds the session. None of this is observable from the transcript alone; the provider and the request rows are the witnesses. When pings go out (the budget, the interval, stale and late ticks, a lost cache, compaction) is the warmer's own decision, checked without a daemon by the model in extensions/warm/test/albedo_ext_warm/warmer_model_test.gleam. What counts as awaited work (listed jobs that are not services or cells, counted remote jobs, open children in a turn or on a job, beneath open children) is apps/albedo/test/albedo/session/awaited_test.gleam, and the call a restart rebuilds over generated tool histories is apps/albedo/test/albedo/session/last_call_restore_test.gleam. Turning the extension off globally or for one session is composition selection, which composition's selection tests own. """ import json import os import sqlite3 import threading import time import unittest from harness import ( LOOPBACK_REMOTE, Albedo, Provider, exclusive, operation_id, python, release_fifo, text, wait_until, ) # A warm ping repeats the turn's request with this output limit; turns now carry # the model's own ceiling, so the limit itself tells a ping from a turn. PING_TOKENS = 16 # A prefix big enough to matter: 4096 cached tokens against the 1024 floor. PARENT_USAGE = { "input_tokens": 6000, "output_tokens": 4, "input_tokens_details": {"cached_tokens": 4096}, } CHILD_USAGE = { "input_tokens": 300, "output_tokens": 4, "input_tokens_details": {"cached_tokens": 100}, } TASK = "hold the fort until released" JOB_PROMPT = "wait for the job" # A local cache-table override matching the fixture host: a short refresh TTL, # bought at 1.0x and read at 0.3x, so pings come 2.7s apart and at most # floor(1.0 / 0.3) - 1 = 2 of them pay for themselves. A tick later than the # 2s jitter floor (the 0.3s margin is under the 5s landing time) is dropped. TTL_SECONDS = 3 # Longer than a ping interval by more than a loaded machine's jitter: a ping # that was due would have gone out within it. QUIET_SECONDS = 2 * TTL_SECONDS CACHE_TTL = { "version": 1, "entries": [ { "id": "fixture", "match": {"host": "127.0.0.1"}, "policy": "refresh", "clock": "request", "tiers": [{"seconds": TTL_SECONDS, "write": 1.0}], "read": 0.3, "evidence": "measured", } ], } # At RESTART_TIME_SCALE=10, this leaves 11 real seconds for a slow daemon # restart: pings are due 9s after the turn's send and dropped after 11s. The # ordinary 20s logical TTL would expire after only 2 real seconds. The 1s idle # and unload sweeps run before the first ping. The budget is # floor(1.0 / 0.1) - 1 = 9 pings. RESTART_TTL = { **CACHE_TTL, "entries": [ { **CACHE_TTL["entries"][0], "tiers": [{"seconds": 100, "write": 1.0}], "read": 0.1, } ], } TIME_SCALE = 5 RESTART_TIME_SCALE = 10 def fast_seconds(seconds): return seconds / TIME_SCALE def release(gate): wait_for(lambda: release_fifo(gate)) def wait_for(predicate, timeout=30): return wait_until(predicate, timeout, "warming never arrived") class WarmTest(unittest.TestCase): def setUp(self): # The child's turn blocks here until the test releases it, so the # parent sits idle on work that will wake it. self.gate = threading.Event() self.job_code = "" self.provider = Provider(self.reply) providers = { "orchestrator": { "baseUrl": self.provider.url + "/parent/v1", "apiKey": "key", "model": "fixture-model", "protocol": "responses", }, "scout": { "baseUrl": self.provider.url + "/child/v1", "apiKey": "key", "model": "scout-model", "protocol": "responses", }, } def prepare(app): app.env["ALBEDO_TEST_TIME_SCALE"] = "5" (app.home / "cache-ttl.json").write_text(json.dumps(CACHE_TTL)) app.write_extensions( {"enabled": {"warm": True}, "warm": {"minCachedTokens": 1024}} ) self.app = Albedo( self.provider, protocol="responses", providers=providers, prepare=prepare ) self.app.__enter__() self.addCleanup(self.provider.close) self.addCleanup(self.app.__exit__, None, None, None) # A failed test must not leave the scout's request blocked. self.addCleanup(self.gate.set) def reply(self, request): sent = json.dumps(request) if TASK in sent: self.gate.wait(timeout=90) return text("scout finished", usage=CHILD_USAGE) if JOB_PROMPT in sent and "function_call_output" not in sent: return python(self.job_code) return text("orchestrator reply", usage=PARENT_USAGE) def api(self, path, body=None, method=None): with self.app.api(path, body, method=method) as response: return json.load(response) def requests(self, fragment): return [ record["request"] for record in self.provider.requests if fragment in record["path"] ] def pings(self, session_requests): return [ request for request in session_requests if request.get("max_output_tokens") == PING_TOKENS ] def rows(self, session): with self.app.api(f"/sessions/{session}/requests") as response: return json.load(response)["items"] def history(self, session): items, after = [], 0 while True: with self.app.api( f"/sessions/{session}/history?after={after}&limit=100" ) as response: page = json.load(response) items.extend(page["items"]) if page["newer"] is None: return items after = items[-1]["position"] def spawn(self, parent, task): """The parent's scout, started on `task`.""" child = operation_id() self.app.api( f"/sessions/{child}", { "kind": "child", "parent_id": parent, "address": "scout", "name": "scout", "initial_input_id": operation_id(), "task": task, "model": "scout/scout-model", }, method="PUT", headers={"If-None-Match": "*"}, ).close() return child def swarm(self, parent=None): """A parent whose turn has run while its scout is still working.""" parent = parent or self.app.session(name="warm test") child = self.spawn(parent, TASK) wait_for(lambda: self.requests("/child/") or None) self.app.prompt(parent, "run the swarm").close() self.app.idle(parent) return parent, child def job_gate(self, service, remote=False): """The fifo a job started by `self.job_code` runs until. A remote job runs on a loopback host: the parent's kernel cannot list it, only hear its remote kernel count it.""" gate = self.app.workspace / "job-release" os.mkfifo(gate) program = f"open({str(gate)!r}, 'rb').read(1)" flag = ", service=True" if service else "" start = f"run(sys.executable, '-c', {program!r}{flag})" if remote: # The cell ends once the remote kernel has started the job. self.job_code = ( LOOPBACK_REMOTE + f"""import asyncio, sys job = rem.{start} for _ in range(200): if job.id is not None: break await asyncio.sleep(0.05) job.id""" ) else: self.job_code = f"import sys\njob = {start}\njob.id" # A failed test must not leave the job blocked. self.addCleanup(release_fifo, gate) return gate def job(self, service, remote=False): """A parent whose turn started a job that runs until released, and then went idle waiting on it.""" gate = self.job_gate(service, remote) parent = self.app.session(name="warm test") self.app.prompt(parent, JOB_PROMPT).close() self.app.idle(parent) return parent, gate def turns(self, fragment): return [ request for request in self.requests(fragment) if request.get("max_output_tokens") != PING_TOKENS ] # exclusive: writes daemon-wide cache TTL and warmer settings @exclusive def test_the_warmer_survives_a_kernel_restart_and_ends_when_disabled(self): # The warm worker is a BEAM process, so no pid records it; its # pings are the observable effect. A kernel restart drops the # kernel and keeps the composition, so pings must continue. # Disabling warm retires that composition, so they must stop # even though the child still runs. parent, child = self.swarm() wait_for(lambda: self.pings(self.requests("/parent/")) or None) self.api(f"/sessions/{parent}/kernel/restart", {}) self.app.idle(parent) # A fresh turn after the restart gets a fresh warming budget, so # a ping repeating it proves the worker still runs; the spent # budget of the turn before the restart cannot mask its death. self.app.prompt(parent, "real work now").close() self.app.idle(parent) turn = self.turns("/parent/")[-1] wait_for( lambda: ( [ ping for ping in self.pings(self.requests("/parent/")) if ping == {**turn, "max_output_tokens": PING_TOKENS} ] or None ) ) # A ping holds the session until its row is written, and a selection # change waits for an idle session; the turn's budget runs out after # two, so once both rows land no ping is in flight. self.settle_pings(parent, turn) with self.app.api(f"/sessions/{parent}/configuration") as response: json.load(response) revision = response.headers["ETag"] with self.app.api( f"/sessions/{parent}/configuration", {"selection": {"extensions": {"warm": False}}}, method="PATCH", headers={"If-Match": revision}, ) as response: self.assertFalse( json.load(response)["resource"]["value"]["selection"]["extensions"][ "warm" ] ) self.api(f"/sessions/{parent}/reload", {"target": "session"}) # The child still runs, so a fresh turn would be warmed again had the # worker outlived its composition. self.app.prompt(parent, "after disabling").close() self.app.idle(parent) turn = self.turns("/parent/")[-1] time.sleep(fast_seconds(QUIET_SECONDS)) self.assertNotIn( {**turn, "max_output_tokens": PING_TOKENS}, self.pings(self.requests("/parent/")), ) def settle_pings(self, parent, turn): """Wait until `turn` has had its two pings and every ping's request row is written, so none still holds the session.""" ping = {**turn, "max_output_tokens": PING_TOKENS} def settled(): pings = self.pings(self.requests("/parent/")) rows = self.rows(parent) background = [row for row in rows if row["kind"] == "background"] return pings.count(ping) == 2 and len(background) == len(pings) wait_for(settled) # exclusive: writes daemon-wide cache TTL and warmer settings @exclusive def test_a_submit_during_warming_answers_and_warming_ends_with_the_children(self): parent, child = self.swarm() first = wait_for(lambda: self.pings(self.requests("/parent/")) or None) turn = self.requests("/parent/")[0] self.assertEqual(first[0], {**turn, "max_output_tokens": PING_TOKENS}) # A real submit while warming gets through and is answered normally. self.app.prompt(parent, "real work now").close() self.app.idle(parent) self.assertIn( "orchestrator reply", [ part["text"] for entry in self.history(parent) for part in entry["content"] if part["kind"] == "text" ], ) # The work that kept the parent warm is done; warming ends with it. self.gate.set() self.app.idle(child) self.app.idle(parent) settled = len(self.pings(self.requests("/parent/"))) time.sleep(fast_seconds(QUIET_SECONDS)) self.assertEqual(len(self.pings(self.requests("/parent/"))), settled) # Every ping that did go out repeated a turn's request, budget aside. turns = self.turns("/parent/") for ping in self.pings(self.requests("/parent/")): self.assertIn( ping, [{**repeated, "max_output_tokens": PING_TOKENS} for repeated in turns], ) def assert_warm_until_the_job_ends(self, remote): parent, gate = self.job(service=False, remote=remote) before = self.history(parent) pings = wait_for(lambda: self.pings(self.requests("/parent/")) or None) turn = self.turns("/parent/")[-1] # A ping is the turn's request as sent, with only the output budget # lowered to the Responses protocol's minimum. self.assertEqual(pings[0], {**turn, "max_output_tokens": PING_TOKENS}) # Its request row carries the prefix identity and cache marks of the # turn call it repeats, and no transcript row: the provider sees the # ping before the daemon writes its row. rows = wait_for( lambda: (rows := self.rows(parent))[-1]["kind"] == "background" and rows ) head = [row for row in rows if row["kind"] == "turn"][-1] row = rows[-1] for field in ( "head_hash", "input_count", "replaced_input_count", "projection_hash", "cache_marks", "provider_profile", "model", ): self.assertEqual(row[field], head[field], field) self.assertEqual(row["cached_tokens"]["observed"], 4096) self.assertEqual(row["transcript_positions"], []) self.assertEqual(row["outcome"], "completed") self.assertEqual(self.history(parent), before) # The job's end wakes the parent with an ordinary turn, and warming # ends with the work that kept it up. release(gate) wait_for( lambda: any( "background job finished" in json.dumps(request) for request in self.requests("/parent/") ) ) self.app.idle(parent) settled = len(self.pings(self.requests("/parent/"))) time.sleep(fast_seconds(QUIET_SECONDS)) self.assertEqual(len(self.pings(self.requests("/parent/"))), settled) # exclusive: writes daemon-wide cache TTL and warmer settings @exclusive def test_a_running_job_keeps_the_cache_warm_until_it_finishes(self): self.assert_warm_until_the_job_ends(remote=False) # exclusive: writes daemon-wide cache TTL and warmer settings @exclusive def test_a_remote_job_keeps_the_cache_warm_until_it_finishes(self): self.assert_warm_until_the_job_ends(remote=True) # exclusive: writes daemon-wide cache TTL and warmer settings @exclusive def test_a_remote_service_job_does_not_keep_the_cache_warm(self): # The remote kernel counts the jobs its session awaits; a service is # not one of them. parent, _ = self.job(service=True, remote=True) time.sleep(fast_seconds(QUIET_SECONDS)) self.assertEqual(len(self.requests("/parent/")), 2) self.assertEqual([row["kind"] for row in self.rows(parent)], ["turn", "turn"]) # exclusive: writes daemon-wide cache TTL and warmer settings, restarts @exclusive def test_a_restart_keeps_warming_a_session_waiting_on_a_job(self): (self.app.home / "cache-ttl.json").write_text(json.dumps(RESTART_TTL)) parent, gate = self.job(service=False) turn = self.turns("/parent/")[-1] self.app.restart( prepare=lambda app: app.env.update( ALBEDO_TEST_TIME_SCALE=str(RESTART_TIME_SCALE) ) ) before = len(self.provider.requests) def pings(): return self.pings( [ record["request"] for record in self.provider.requests[before:] if "/parent/" in record["path"] ] ) # The warmer's call lived in memory only; the restarted session # rebuilds it from the transcript, exactly as the turn sent it. ping = wait_for(pings)[0] self.assertEqual(ping, {**turn, "max_output_tokens": PING_TOKENS}) # The provider answers before the ping's request row is written. rows = wait_for( lambda: (rows := self.rows(parent))[-1]["kind"] == "background" and rows ) head = [row for row in rows if row["kind"] == "turn"][-1] self.assertEqual(rows[-1]["head_hash"], head["head_hash"]) self.assertEqual(rows[-1]["input_count"], head["input_count"]) release(gate) wait_for( lambda: any( "background job finished" in json.dumps(request) for request in self.requests("/parent/") ) ) self.app.idle(parent) # exclusive: shortens the daemon's idle and unload limits, restarts @exclusive def test_a_parent_waiting_on_its_child_keeps_warming_once_released(self): (self.app.home / "cache-ttl.json").write_text(json.dumps(RESTART_TTL)) self.app.restart( prepare=lambda app: app.env.update( ALBEDO_TEST_TIME_SCALE=str(RESTART_TIME_SCALE), ALBEDO_IDLE_SECONDS="1", ALBEDO_UNLOAD_SECONDS="1", ) ) parent, child = self.swarm() def released(): with sqlite3.connect(self.app.home / "albedo.sqlite") as database: return not database.execute( "SELECT pid FROM kernel_links WHERE session=?", (parent,) ).fetchone() # The kernel is released long before the first ping is due, and the # unload sweep would stop the session with its warmer. wait_for(released) self.assertEqual(self.pings(self.requests("/parent/")), []) wait_for(lambda: self.pings(self.requests("/parent/")), timeout=40) self.gate.set() self.app.idle(child) self.app.idle(parent)