"""The reloadable prompt-cache TTL table: layers, merge precedence, live reload. The table is daemon-wide state read from files, so this is where its behaviour is visible: the shipped default served with every entry, lookups resolving through match order, a local override replacing an entry by id and winning with a new more-specific one — without a restart — and a malformed file keeping the last good table. A turn's usage carries the steps its cached count fades through by that table, which the chat footer counts down from and which must survive a restart. The table is the cache section of the model facts, and the overrides from before it, cache-ttl.json and the cacheTtl setting, still apply. It writes extensions.json and the model-facts layers, so tests that change those layers are exclusive, on a home of their own. How layers merge by id, and that a layer naming one id twice is refused whole, is checked over generated layers in packages/albedo_sdk/test/albedo_sdk/model_facts_test.gleam. The remote layer's fetch is background (like the models catalog's), so the fixture provider serves the remote table on a loopback URL and the test waits for it to land; `/reload` fetches it synchronously. No live network is reached. """ from typing import Any import json from datetime import datetime import os import time import unittest from harness import Albedo, Provider, exclusive, text def milliseconds(timestamp): return round( datetime.fromisoformat(timestamp.replace("Z", "+00:00")).timestamp() * 1000 ) # `/reload` fetches the models catalog before the TTL table, so it needs a # fixture url too — the default would reach the live models.dev. MODELS_CATALOG = { "fixture": { "id": "fixture", "name": "Fixture", "models": { "fixture-model": {"id": "fixture-model", "limit": {"context": 8000}} }, } } REMOTE_TABLE: dict[str, Any] = { "version": 1, "entries": [ # Replaces the shipped deepseek entry by id, in place. { "id": "deepseek", "match": {"host": "api.deepseek.com"}, "policy": "fixed", "clock": "response", "evidence": "measured", "source": "fixture", "note": "remote override", }, # A new id, which goes before every default entry. { "id": "fixture-gateway", "match": {"host": "gateway.fixture"}, "policy": "evict", "survival": {"typical": 600}, "evidence": "measured", "source": "fixture", "note": "new remote entry", }, ], } LOCAL_OVERRIDE: dict[str, Any] = { "version": 1, "entries": [ # Replaces the remote or default deepseek entry by id, in place. { "id": "deepseek", "match": {"host": "api.deepseek.com"}, "policy": "fixed", "clock": "request", "evidence": "measured", "source": "local", "note": "local override", }, # A new id, more specific than anything shipped, which must win. { "id": "laptop-gateway", "match": {"host": "gateway.laptop"}, "policy": "refresh", "tiers": [{"seconds": 600, "write": 1.5}], "evidence": "measured", "source": "local", "note": "new local entry", }, ], } CACHE_FIELDS = ("policy", "clock", "tiers", "read", "survival") def sectioned(table): """The table in model-facts.json's shape, each policy in a cache section.""" entries = [] for entry in table["entries"]: kept = {key: value for key, value in entry.items() if key not in CACHE_FIELDS} cache = {key: value for key, value in entry.items() if key in CACHE_FIELDS} entries.append({**kept, "cache": cache}) return {**table, "entries": entries} def write_atomic(path, payload): temporary = path.with_suffix(".tmp") temporary.write_text(json.dumps(payload)) temporary.replace(path) # exclusive: configures daemon-wide TTL/catalog layers and writes cache files @exclusive class CacheTtlTests(unittest.TestCase): def setUp(self): self.provider = Provider( lambda _request: text("ok"), catalog=sectioned(REMOTE_TABLE) ) self.addCleanup(self.provider.close) self.catalog = Provider(lambda _request: text("ok"), catalog=MODELS_CATALOG) self.addCleanup(self.catalog.close) def prepare(app): app.write_extensions( { "models": {"url": self.catalog.url + "/models.json"}, "modelFacts": { "url": self.provider.url + "/model-facts.json", "refreshHours": 24, }, } ) self.app = Albedo( self.provider, prepare=prepare, providers={ "fixture": { "baseUrl": self.provider.url, "apiKey": "fixture-key", "model": "fixture-model", "protocol": "chat_completions", }, }, ) self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) def table(self): with self.app.api("/models?view=cache-policy&limit=200") as response: return json.load(response) def resolved(self, query): with self.app.api("/models?view=cache-policy" + query) as response: return json.load(response)["matched"] def layers(self, table): return {layer["name"]: layer for layer in table["layers"]} def entries(self, table): return {entry["id"]: entry for entry in table["entries"]} @property def local(self): return self.app.home / "model-facts.json" @property def remote(self): return self.app.home / "model-facts-remote.json" def test_local_override_replaces_and_adds_without_restart(self): write_atomic(self.local, sectioned(LOCAL_OVERRIDE)) table = self.table() local = self.layers(table)["local"] self.assertTrue(local["loaded"]) self.assertEqual(local["path"], str(self.local)) entries = self.entries(table) # Replaced by id: same entry, now from the local layer. self.assertEqual(entries["deepseek"]["layer"], "local") self.assertEqual(entries["deepseek"]["note"], "local override") self.assertEqual(entries["deepseek"]["clock"], "request") # New ids go before all earlier-layer entries and win the lookup. self.assertEqual(table["entries"][0]["id"], "laptop-gateway") self.assertEqual(self.resolved("&host=gateway.laptop")["id"], "laptop-gateway") # The replaced default keeps answering, with the override's values. self.assertEqual( self.resolved("&host=api.deepseek.com")["note"], "local override" ) # Untouched defaults still resolve. self.assertEqual( self.resolved("&extension=claude")["id"], "claude-subscription" ) def test_the_old_cache_ttl_file_still_overrides_below_the_local_facts(self): old = self.app.home / "cache-ttl.json" write_atomic(old, LOCAL_OVERRIDE) table = self.table() layer = self.layers(table)["cache-ttl"] self.assertTrue(layer["loaded"]) self.assertEqual(layer["path"], str(old)) entries = self.entries(table) self.assertEqual(entries["deepseek"]["layer"], "cache-ttl") self.assertEqual(entries["deepseek"]["clock"], "request") self.assertEqual(self.resolved("&host=gateway.laptop")["id"], "laptop-gateway") newer = sectioned(LOCAL_OVERRIDE) newer["entries"] = newer["entries"][:1] newer["entries"][0]["note"] = "model facts win" write_atomic(self.local, newer) entries = self.entries(self.table()) self.assertEqual(entries["deepseek"]["layer"], "local") self.assertEqual(entries["deepseek"]["note"], "model facts win") self.assertEqual(entries["laptop-gateway"]["layer"], "cache-ttl") def test_an_entry_of_other_facts_leaves_the_cache_entry_below_it(self): write_atomic( self.local, { "entries": [ { "id": "deepseek-media", "match": {"host": "api.deepseek.com"}, "media": {"maxFps": 2}, } ] }, ) table = self.table() self.assertTrue(self.layers(table)["local"]["loaded"]) self.assertNotIn("deepseek-media", self.entries(table)) self.assertEqual(self.resolved("&host=api.deepseek.com")["id"], "deepseek") def test_duplicate_remote_ids_are_rejected_before_replacement(self): session = self.app.session(name="cache ttl test") with self.app.api(f"/sessions/{session}/reload", {"target": "both"}): pass path = self.remote before = path.read_bytes() self.provider.catalog = {"entries": [sectioned(REMOTE_TABLE)["entries"][0]] * 2} with self.app.api( f"/sessions/{session}/reload", {"target": "both"} ) as response: outcome = json.load(response)["cache_policy"] self.assertEqual(outcome["state"], "failed") self.assertIn("duplicate id", outcome["failure"]["detail"]) self.assertEqual(path.read_bytes(), before) self.assertEqual( self.entries(self.table())["deepseek"]["note"], "remote override" ) def test_same_revision_remote_replacement_invalidates_parsed_layer(self): session = self.app.session(name="cache ttl test") path = self.remote remote = sectioned(REMOTE_TABLE) write_atomic(path, remote) # A future mtime prevents background refresh. Restoring it after reload # keeps the cached revision unchanged without depending on scheduling. replacement = json.loads(json.dumps(remote)) replacement["entries"][0]["note"] = "remote revised!" self.assertEqual(len(json.dumps(replacement)), len(json.dumps(remote))) self.provider.catalog = replacement timestamp = int(time.time()) + 60 os.utime(path, (timestamp, timestamp)) self.assertEqual( self.entries(self.table())["deepseek"]["note"], "remote override" ) with self.app.api(f"/sessions/{session}/reload", {"target": "both"}): pass os.utime(path, (timestamp, timestamp)) self.assertEqual( self.entries(self.table())["deepseek"]["note"], "remote revised!" ) def test_malformed_local_file_keeps_the_last_good_table(self): write_atomic(self.local, sectioned(LOCAL_OVERRIDE)) self.assertTrue(self.layers(self.table())["local"]["loaded"]) self.local.write_text("{ this is not json") table = self.table() local = self.layers(table)["local"] self.assertFalse(local["loaded"]) self.assertEqual(set(local["error"]), {"code", "detail"}) self.assertEqual(local["error"]["code"], "cache_policy_layer_failed") self.assertIn("not valid JSON", local["error"]["detail"]) self.assertLessEqual(len(local["error"]["detail"]), 4096) entries = self.entries(table) self.assertEqual(entries["deepseek"]["layer"], "local") self.assertEqual(entries["deepseek"]["note"], "local override") self.assertEqual(self.resolved("&host=gateway.laptop")["id"], "laptop-gateway") # Fixing the file is picked up live, without a restart. write_atomic(self.local, sectioned(LOCAL_OVERRIDE)) self.assertTrue(self.layers(self.table())["local"]["loaded"]) def test_remote_url_is_fetched_and_merged(self): deadline = time.monotonic() + 20 table = self.table() while ( not self.layers(table)["remote"]["loaded"] and time.monotonic() < deadline ): time.sleep(0.1) table = self.table() remote = self.layers(table)["remote"] self.assertTrue(remote["loaded"]) self.assertEqual(remote["path"], str(self.remote)) entries = self.entries(table) # Replaced by id, in the default entry's place, ahead of general rules. ids = [entry["id"] for entry in table["entries"]] self.assertEqual(entries["deepseek"]["layer"], "remote") self.assertEqual(entries["deepseek"]["note"], "remote override") self.assertEqual(entries["deepseek"]["policy"], "fixed") self.assertLess(ids.index("claude-subscription"), ids.index("deepseek")) # The remote layer's new id sits in front of the default entries. self.assertEqual(ids[0], "fixture-gateway") self.assertEqual( self.resolved("&host=gateway.fixture")["id"], "fixture-gateway" ) def test_session_reload_refetches_the_remote_copy(self): session = self.app.session(name="cache ttl test") self.assertFalse(self.remote.exists()) with self.app.api( f"/sessions/{session}/reload", {"target": "both"} ) as response: outcome = json.load(response) self.assertEqual(outcome["session"]["state"], "applied") self.assertEqual(outcome["cache_policy"]["state"], "refreshed") table = self.table() self.assertTrue(self.layers(table)["remote"]["loaded"]) self.assertEqual(self.entries(table)["deepseek"]["note"], "remote override") def test_the_old_cache_ttl_setting_still_names_the_remote_copy(self): # write_extensions would add the harness's modelFacts setting, which wins. (self.app.home / "extensions.json").write_text( json.dumps( { "models": { "url": self.catalog.url + "/models.json", "refreshHours": 0, }, "cacheTtl": {"url": self.provider.url + "/cache-ttl.json"}, } ) ) self.provider.catalog = REMOTE_TABLE session = self.app.session(name="cache ttl test") with self.app.api( f"/sessions/{session}/reload", {"target": "both"} ) as response: self.assertEqual(json.load(response)["cache_policy"]["state"], "refreshed") table = self.table() self.assertTrue(self.layers(table)["remote"]["loaded"]) self.assertEqual(self.entries(table)["deepseek"]["note"], "remote override") self.assertEqual(self.entries(table)["deepseek"]["layer"], "remote") def test_a_turns_usage_says_when_its_cache_fades_across_a_restart(self): # A provider that only evicts: the count is unknown past typical # survival and gone past the bound, counted from the response's end. write_atomic( self.local, { "version": 1, "entries": [ { "id": "fixture-evict", "match": {"host": "127.0.0.1"}, "cache": { "policy": "evict", "survival": {"typical": 600, "max": 3600}, }, "evidence": "measured", } ], }, ) session = self.app.session(name="cache ttl test") self.app.prompt(session, "hello").close() self.app.idle(session) with self.app.api(f"/sessions/{session}/requests") as response: finished = milliseconds(json.load(response)["items"][0]["ended_at"]) fading = [(finished + 600_000, None), (finished + 3_600_000, 0)] def latest_fade(): with self.app.api(f"/sessions/{session}?tail=0") as response: fade = json.load(response)["usage"]["cache_fade"] return [(milliseconds(step["at"]), step["cached_tokens"]) for step in fade] self.assertEqual(latest_fade(), fading) # The steps are stored with the usage, so a client attaching to a # restarted daemon still counts down from the same call. self.app.restart() self.assertEqual(latest_fade(), fading)