From daeba16ea98bbfd95dd6051887ed5b46c213a5ca Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Mon, 28 Sep 2026 10:57:33 +0300 Subject: [PATCH] Ship a reloadable prompt-cache TTL table priv/cache-ttl.json holds a prior per provider: whether a hit refreshes the lifetime, a fixed lifetime, or best-effort eviction; where the clock starts; the selectable TTL tiers with their write multipliers; the read multiplier; and how well each value is known, with its source. An optional remote copy (extensions.json cacheTtl.url) and a local $ALBEDO_HOME/cache-ttl.json merge over it by id, reloaded when a layer file changes and on /reload. GET /cache-ttl serves the merged table or the entry a request resolves to. The models catalog's bounded fetch-and-commit moves into albedo_cached_fetch, shared by both url-backed caches. --- priv/cache-ttl.json | 306 +++++++++++ robot-docs/cache-ttl.md | 52 ++ src/albedo/daemon/server.gleam | 28 + src/albedo/harness/albedo_cache_ttl.erl | 181 +++++++ src/albedo/harness/albedo_cached_fetch.erl | 90 ++++ src/albedo/harness/cache_ttl.gleam | 504 ++++++++++++++++++ .../extensions/commands/extension.gleam | 6 +- .../extensions/models/albedo_models.erl | 100 +--- test/e2e/cache_ttl_test.py | 211 ++++++++ 9 files changed, 1401 insertions(+), 77 deletions(-) create mode 100644 priv/cache-ttl.json create mode 100644 robot-docs/cache-ttl.md create mode 100644 src/albedo/harness/albedo_cache_ttl.erl create mode 100644 src/albedo/harness/albedo_cached_fetch.erl create mode 100644 src/albedo/harness/cache_ttl.gleam create mode 100644 test/e2e/cache_ttl_test.py diff --git a/priv/cache-ttl.json b/priv/cache-ttl.json new file mode 100644 index 000000000..a654cbe2c --- /dev/null +++ b/priv/cache-ttl.json @@ -0,0 +1,306 @@ +{ + "version": 1, + "entries": [ + { + "id": "claude-subscription", + "match": { + "extension": "claude" + }, + "policy": "refresh", + "clock": "request", + "tiers": [ + { + "seconds": 300, + "write": 1.25 + }, + { + "seconds": 3600, + "write": 2.0 + } + ], + "read": 0.1, + "evidence": "documented", + "source": "https://code.claude.com/docs/en/prompt-caching", + "note": "Claude OAuth. Claude Code writes the main conversation at 1h on a subscription and 5m once on usage credits; albedo's own marks are in each ledger row. Lifetime counts from request start, so streaming time uses it up.", + "checked": "2026-09-28" + }, + { + "id": "anthropic-api", + "match": { + "host": "api.anthropic.com" + }, + "policy": "refresh", + "clock": "request", + "tiers": [ + { + "seconds": 300, + "write": 1.25 + }, + { + "seconds": 3600, + "write": 2.0 + } + ], + "read": 0.1, + "evidence": "documented", + "source": "https://platform.claude.com/docs/en/build-with-claude/prompt-caching", + "note": "Every hit refreshes for free. 1h entries must precede 5m entries in one request. Minimum prefix is model-dependent (512-4096 tokens).", + "checked": "2026-09-28" + }, + { + "id": "bedrock-claude", + "match": { + "host": "bedrock-runtime.*.amazonaws.com", + "model": "*claude*" + }, + "policy": "refresh", + "clock": "request", + "tiers": [ + { + "seconds": 300, + "write": 1.25 + }, + { + "seconds": 3600, + "write": 2.0 + } + ], + "read": 0.1, + "evidence": "documented", + "source": "https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html", + "note": "Resets with each successful hit. Cross-region inference can route to a cold region and force extra writes.", + "checked": "2026-09-28" + }, + { + "id": "codex-subscription", + "match": { + "extension": "codex" + }, + "policy": "evict", + "survival": { + "typical": 1800, + "max": 86400 + }, + "evidence": "folklore", + "source": "https://developers.openai.com/api/docs/guides/prompt-caching", + "note": "ChatGPT/Codex OAuth: nothing published. Codex CLI sends only prompt_cache_key. Observed informally at about 30 minutes, which matches the API's GPT-5.6+ and 24h-retention behaviour.", + "checked": "2026-09-28" + }, + { + "id": "openai-5.6", + "match": { + "host": "api.openai.com", + "model": [ + "gpt-5.6*", + "gpt-6*" + ] + }, + "policy": "refresh", + "tiers": [ + { + "seconds": 1800, + "write": 1.25 + } + ], + "read": 0.1, + "evidence": "documented", + "source": "https://developers.openai.com/api/docs/guides/prompt-caching", + "note": "prompt_cache_options.ttl \"30m\" is the only value and the default; a minimum, OpenAI may retain longer. Minimum prefix 1024 tokens.", + "checked": "2026-09-28" + }, + { + "id": "openai", + "match": { + "host": "api.openai.com" + }, + "policy": "evict", + "survival": { + "typical": 450, + "max": 3600 + }, + "evidence": "documented", + "source": "https://developers.openai.com/api/docs/guides/prompt-caching", + "note": "Earlier models, prompt_cache_retention in_memory (albedo sends none): about 5-10 minutes idle, at most an hour. With \"24h\" retention: typically about 30 minutes, at most 24 hours.", + "checked": "2026-09-28" + }, + { + "id": "gemini-implicit", + "match": { + "host": [ + "generativelanguage.googleapis.com", + "*aiplatform.googleapis.com" + ] + }, + "policy": "evict", + "survival": { + "typical": 240, + "max": 86400 + }, + "evidence": "folklore", + "source": "https://ai.google.dev/gemini-api/docs/caching", + "note": "Google publishes no implicit TTL. OpenRouter reports 3-5 minutes on average; Vertex says implicit entries are cleared within 24 hours.", + "checked": "2026-09-28" + }, + { + "id": "antigravity", + "match": { + "extension": "antigravity" + }, + "policy": "unknown", + "survival": { + "typical": 240, + "max": 86400 + }, + "evidence": "unknown", + "source": "https://ai.google.dev/gemini-api/docs/caching", + "note": "Cloud Code Assist: no docs. Assumed to behave like Gemini implicit caching until measured.", + "checked": "2026-09-28" + }, + { + "id": "deepseek", + "match": { + "host": "api.deepseek.com" + }, + "policy": "evict", + "survival": { + "typical": 14400, + "max": 259200 + }, + "evidence": "documented", + "source": "https://api-docs.deepseek.com/guides/kv_cache", + "note": "Disk cache, on by default; unused entries are cleared \"usually within a few hours to a few days\". Matches whole cache units only.", + "checked": "2026-09-28" + }, + { + "id": "alibaba", + "match": { + "extension": "alibaba" + }, + "policy": "evict", + "survival": { + "typical": 300, + "max": 3600 + }, + "read": 0.2, + "evidence": "documented", + "source": "https://www.alibabacloud.com/help/en/model-studio/context-cache", + "note": "Implicit cache (albedo sends no cache_control): validity \"indeterminate\", periodically cleared; hits 20%, writes 100%. Explicit markers would give a 5m refresh-on-hit clock at 1.25x write, 0.1x read. The typical and max are placeholders.", + "checked": "2026-09-28" + }, + { + "id": "zai", + "match": { + "host": [ + "api.z.ai", + "open.bigmodel.cn" + ] + }, + "policy": "unknown", + "survival": { + "typical": 300, + "max": 3600 + }, + "evidence": "unknown", + "source": "https://docs.z.ai/guides/capabilities/cache", + "note": "Implicit only; docs give no validity period.", + "checked": "2026-09-28" + }, + { + "id": "kimi-coding", + "match": { + "host": "api.kimi.com" + }, + "policy": "evict", + "survival": { + "typical": 300, + "max": 1800 + }, + "evidence": "measured", + "source": "https://github.com/Leechael/pi-provider-kimi-code/blob/main/docs/caching.md", + "note": "kimi-for-coding endpoint: probes hit at 60s and 300s and missed at 1800s and beyond; markers are ignored and caching works in 256-token chunks.", + "checked": "2026-09-28" + }, + { + "id": "kimi-api", + "match": { + "host": [ + "api.moonshot.ai", + "api.moonshot.cn" + ] + }, + "policy": "refresh", + "tiers": [ + { + "seconds": 300 + }, + { + "seconds": 3600 + } + ], + "evidence": "documented", + "source": "https://platform.kimi.ai/docs/guide/context-caching", + "note": "5m unless prompt_cache_options.ttl asks for 1h; each hit renews under the TTL locked at first write. Organisation-scoped.", + "checked": "2026-09-28" + }, + { + "id": "xai", + "match": { + "host": "api.x.ai" + }, + "policy": "evict", + "survival": { + "typical": 300 + }, + "evidence": "documented", + "source": "https://docs.x.ai/developers/advanced-api-usage/prompt-caching/best-practices", + "note": "No TTL: entries \"can be evicted at any time due to server load or restarts\". x-grok-conv-id keeps requests on one cache. The typical is a placeholder.", + "checked": "2026-09-28" + }, + { + "id": "groq", + "match": { + "host": "api.groq.com" + }, + "policy": "refresh", + "tiers": [ + { + "seconds": 7200 + } + ], + "evidence": "documented", + "source": "https://console.groq.com/docs/prompt-caching", + "note": "Expires after 2 hours without use.", + "checked": "2026-09-28" + }, + { + "id": "openrouter", + "match": { + "host": "openrouter.ai" + }, + "policy": "unknown", + "survival": { + "typical": 300, + "max": 3600 + }, + "evidence": "documented", + "source": "https://openrouter.ai/docs/guides/best-practices/prompt-caching", + "note": "No cache of its own: the upstream's rules apply, and TTL syntax is not translated between providers. Sticky routing to one upstream lapses after 10 minutes idle. Several reports of no Anthropic caching through it.", + "checked": "2026-09-28" + }, + { + "id": "hyper", + "match": { + "host": "hyper.charm.land" + }, + "policy": "unknown", + "survival": { + "typical": 300, + "max": 3600 + }, + "evidence": "unknown", + "source": "https://hyper.charm.land/docs/models.html", + "note": "Gateway with no caching docs. Placeholder until measured.", + "checked": "2026-09-28" + } + ] +} diff --git a/robot-docs/cache-ttl.md b/robot-docs/cache-ttl.md new file mode 100644 index 000000000..91c9739b5 --- /dev/null +++ b/robot-docs/cache-ttl.md @@ -0,0 +1,52 @@ +# cache TTL table + +The prompt-cache TTL table is the prior the cache-warmth estimate starts from: how long each provider keeps a cached prefix, what a write costs, and whether a hit restarts the clock. It answers `lookup(extension, host, model)` in `src/albedo/harness/cache_ttl.gleam` until a session's request ledger has measured the real thing (robot-docs/usage-ledger.md); after that the ledger wins. + +The table is data, not code: `priv/cache-ttl.json` ships with the daemon, and nothing about a provider is hardcoded anywhere else. + +## format + +A file is `{"version": 1, "entries": [...]}`. One entry: + +- `id` — unique. Layers replace entries by it. +- `match` — which requests the entry describes: `extension` (albedo's extension name: claude, codex, openai, antigravity, alibaba, ...), `host` (endpoint host), `model` (model id). Each is one string or a list; each string is a glob where `*` matches any run of characters, case-insensitively. An absent field matches anything; a list matches if any element does. +- `policy` — `refresh` (every hit restarts the lifetime), `fixed` (lifetime runs from the write), `evict` (no clock, best-effort, only survival windows are known), or `unknown`. +- `clock` — `request` or `response` (default `response`): whether a lifetime counts from request start or response end. Anthropic counts from request start, so streaming time uses the cache up. +- `tiers` — the TTLs a request can ask for, each `{seconds, write}` with the write-price multiplier. +- `read` — the read-price multiplier, when the provider charges for hits. +- `survival` — `{typical, max?}` seconds, for `evict` and `unknown` entries. +- `evidence` — `documented`, `measured`, `implemented`, `folklore`, or `unknown`. +- `source` (url), `checked` (date), `note` (text). + +Unknown fields are ignored, so a newer file stays readable. A bad entry — missing `id`, `match`, `policy` or `evidence`, or a value that does not decode — is skipped with a logged reason and never fails the table. + +**Values marked `folklore` or `unknown` are placeholders.** They are the shape of the answer, not the answer: phase 2 replaces them with what the session's own ledger rows measure. + +## layers + +Three layers merge by id: + +1. `default` — the shipped `priv/cache-ttl.json`. +2. `remote` — a copy fetched from a url, cached at `$ALBEDO_HOME/cache-ttl-remote.json`: + ```json + { "cacheTtl": { "url": "https://example.com/cache-ttl.json", "refreshHours": 24 } } + ``` + in `$ALBEDO_HOME/extensions.json`. Absent `url` means no fetch; `refreshHours: 0` disables the background refresh. Only `https`, or `http` on the loopback host, is fetched, the response is capped at 1 MiB, and the write is a rename — a failed fetch keeps the previous copy. +3. `local` — `$ALBEDO_HOME/cache-ttl.json`, for hand edits. + +A later layer replaces an entry with the same id in place, and puts entries with new ids **before** all earlier-layer entries, so a local override can shadow a general default while the shipped specific-to-general order survives underneath. Within the merged table, **first match wins** a lookup: the files list specific entries before general ones, and that order is the precedence. + +## reload + +Each layer file is parsed once per revision (size + mtime) and the merged table is cached; a changed file is picked up on the next lookup without a restart. A malformed layer file keeps that layer's last good entries and reports the reason in `/cache-ttl`; fixing the file is live again. + +The remote copy refreshes in the background when it is stale, the same cadence as the models catalog. `/reload` (no target) re-fetches it immediately, alongside the models catalog: the command returns after the copy is atomically replaced, or with the fetch failure. + +## local api + +`GET /cache-ttl`, read-only, daemon-token authenticated like `/quota`: + +- no parameters — `{"entries": [...], "layers": [{"name": "default"|"remote"|"local", "path", "loaded", "error"?}]}`, each entry carrying the layer it came from and every field above it decoded. +- `?extension=&host=&model=` — the single resolved entry, or `null`, resolved exactly as `lookup` resolves it. + +`layers` is the state of each file: `loaded` false with an `error` means that layer's last good entries are still merged in (or it was never readable). An absent local override or unconfigured remote url is simply not loaded, with no error. diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 02fecedf7..bea2bb478 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -14,6 +14,7 @@ import albedo/daemon/session import albedo/daemon/session_provider import albedo/daemon/store import albedo/daemon/usage +import albedo/harness/cache_ttl import albedo/harness/command import albedo/harness/extension import albedo/harness/extensions/schedule/ledger as schedule @@ -1561,6 +1562,7 @@ fn uri_decode(segment: String) -> String { /// The daemon's own top-level routes; a service never shadows them. const daemon_routes = [ "health", "sessions", "models", "auth", "shutdown", "agents", "quota", + "cache-ttl", ] fn route( @@ -1702,6 +1704,32 @@ fn daemon_route( |> answered(200, fn(value) { value }, 400) } } + // The prompt-cache TTL table, read-only: every merged entry with the + // layer it came from, or with `extension`, `host` and `model`, the + // single resolved entry (or null). + Get, ["cache-ttl"] -> { + let parameters = query(req) + let asked = fn(key) { + parameters |> list.key_find(key) |> result.unwrap("") + } + case asked("extension"), asked("host"), asked("model") { + "", "", "" -> reply(200, cache_ttl.table_json(cache_ttl.table())) + _, _, _ -> + reply( + 200, + case + cache_ttl.lookup( + asked("extension"), + asked("host"), + asked("model"), + ) + { + Some(entry) -> cache_ttl.entry_json(entry) + None -> json.null() + }, + ) + } + } // `details` lists objects with catalog facts. Without it, plain ids. // Efforts come from where sessions of this extension look them up, // and facts from the endpoint, or there when none is given. diff --git a/src/albedo/harness/albedo_cache_ttl.erl b/src/albedo/harness/albedo_cache_ttl.erl new file mode 100644 index 000000000..708c895f1 --- /dev/null +++ b/src/albedo/harness/albedo_cache_ttl.erl @@ -0,0 +1,181 @@ +-module(albedo_cache_ttl). +%% The prompt-cache TTL table behind /cache-ttl and phase 2's warmth prior: +%% a shipped default, an optional remote copy, and a local override, merged by +%% id. Each layer file is parsed once per revision (size + mtime), like +%% albedo_models; a malformed file keeps that layer's last good entries, and +%% the merged table is re-encoded only when a layer revision changes. + +-include_lib("kernel/include/file.hrl"). + +-export([merged/0, refresh/3, reload/2]). + +-define(MAX_BYTES, 1048576). +-define(REFRESH_PROCESS, albedo_cache_ttl_refresh). + +%% Every error this cache reports is labelled with its own name. +-define(WHAT, <<"cache-ttl">>). + +%% The merged table as JSON: every entry tagged with the layer it came from, +%% plus the layer report the route serves. Always well-formed, even when no +%% layer loaded: an empty table is a valid answer. +merged() -> + try + Resolved = [resolve(Spec) || Spec <- specs()], + Key = [key(L) || L <- Resolved], + case persistent_term:get({?MODULE, merged}, undefined) of + {Key, Json} -> {ok, Json}; + _ -> rebuild(Resolved, Key) + end + catch + _:_ -> {error, <<"cache-ttl table could not be read">>} + end. + +rebuild(Resolved, Key) -> + Entries = lists:foldl(fun apply_layer/2, [], Resolved), + Json = iolist_to_binary(json:encode(#{ + <<"entries">> => Entries, + <<"layers">> => [layer_json(L) || L <- Resolved] + })), + persistent_term:put({?MODULE, merged}, {Key, Json}), + {ok, Json}. + +%% default, then remote, then local: later layers replace same-id entries in +%% place, and their new ids go before every earlier-layer entry, so a local +%% override can shadow a general default while specific defaults keep their +%% place ahead of general ones. +specs() -> + Home = albedo_extension_settings:home(), + Default = case code:priv_dir(albedo) of + {error, _} -> undefined; + Dir -> filename:join(Dir, <<"cache-ttl.json">>) + end, + [ + {<<"default">>, Default}, + {<<"remote">>, <>}, + {<<"local">>, <>} + ]. + +%% {Name, Path, Revision, Loaded, Error, Entries}: the entries of the last +%% good parse survive a malformed newer file. +resolve({Name, Path}) when Path =/= undefined -> + case file:read_file_info(Path, [{time, posix}]) of + {ok, #file_info{type = regular, size = Size, mtime = Mtime}} when Size =< ?MAX_BYTES -> + Revision = {Size, Mtime}, + case persistent_term:get({?MODULE, Path}, undefined) of + {Revision, {ok, Entries}} -> + layer(Name, Path, Revision, true, undefined, Entries); + _ -> parse(Name, Path, Revision) + end; + {ok, #file_info{type = regular}} -> + layer(Name, Path, missing, false, <<"cache-ttl table exceeds 1 MiB">>, []); + {ok, _} -> + layer(Name, Path, missing, false, <<"cache-ttl table is not a regular file">>, []); + {error, enoent} -> + Error = case Name of + <<"default">> -> <<"no shipped cache-ttl table">>; + _ -> undefined + end, + layer(Name, Path, missing, false, Error, []); + {error, _} -> + layer(Name, Path, missing, false, <<"cache-ttl table could not be read">>, []) + end; +resolve({Name, undefined}) -> + layer(Name, undefined, missing, false, <<"no shipped cache-ttl table">>, []). + +parse(Name, Path, Revision) -> + case table(albedo_credentials:read_json(Path)) of + {ok, Entries} -> + persistent_term:put({?MODULE, Path}, {Revision, {ok, Entries}}), + layer(Name, Path, Revision, true, undefined, Entries); + {error, Reason} -> + % The last good parse stays cached under its own revision; this + % file is only re-read once its revision changes again. + Entries = case persistent_term:get({?MODULE, Path}, undefined) of + {_, {ok, Previous}} -> Previous; + _ -> [] + end, + layer(Name, Path, Revision, false, Reason, Entries) + end. + +%% A table is an object with an entries list; each entry must be a map with a +%% binary id to be mergeable. Anything else is dropped, never fatal. +table({ok, #{<<"entries">> := Entries}}) when is_list(Entries) -> + Usable = [E || E <- Entries, is_map(E), is_binary(maps:get(<<"id">>, E, undefined))], + Dropped = length(Entries) - length(Usable), + (Dropped > 0) andalso log(Dropped), + {ok, Usable}; +table({ok, _}) -> {error, <<"cache-ttl table is not an object with an entries list">>}; +table({error, invalid}) -> {error, <<"cache-ttl table is not valid JSON">>}; +table({error, _}) -> {error, <<"cache-ttl table could not be read">>}. + +log(Dropped) -> + _ = try logger:warning("albedo_cache_ttl: ~B entries without an id were skipped", + [Dropped]) + catch _:_ -> ok end, + true. + +apply_layer({Name, _, _, _, _, Entries}, Acc) -> + Tagged = [E#{<<"layer">> => Name} || E <- Entries], + Replaced = lists:foldl(fun replace/2, Acc, Tagged), + Fresh = [E || E <- Tagged, not has_id(Replaced, id(E))], + Fresh ++ Replaced. + +replace(_Entry, []) -> []; +replace(Entry, [E | Rest]) -> + case id(E) =:= id(Entry) of + true -> [Entry | Rest]; + false -> [E | replace(Entry, Rest)] + end. + +has_id([], _) -> false; +has_id([E | Rest], Id) -> id(E) =:= Id orelse has_id(Rest, Id). + +id(Entry) -> maps:get(<<"id">>, Entry, <<>>). + +layer(Name, Path, Revision, Loaded, Error, Entries) -> + {Name, Path, Revision, Loaded, Error, Entries}. + +key({Name, Path, Revision, _, _, _}) -> {Name, Path, Revision}. + +layer_json({Name, Path, _, Loaded, Error, _}) -> + Base = #{<<"name">> => Name, <<"path">> => to_bin(Path), <<"loaded">> => Loaded}, + case Error of + undefined -> Base; + _ -> Base#{<<"error">> => Error} + end. + +to_bin(undefined) -> <<>>; +to_bin(Path) -> unicode:characters_to_binary(Path). + +%% The remote copy is fetched and cached the way the models catalog is: a +%% background refresh when stale, an explicit reload that reports failures, +%% and a failed fetch leaving the previous cache untouched. The machinery is +%% albedo_cached_fetch; only the table check and the merged-cache reset are +%% this table's own. +refresh(Cache, Url, MaxAgeMs) -> + albedo_cached_fetch:refresh(Cache, Url, MaxAgeMs, ?REFRESH_PROCESS, + ?WHAT, fun accept/1, fun after_write/1). + +reload(Cache, Url) -> + albedo_cached_fetch:reload(Cache, Url, ?WHAT, fun accept/1, fun after_write/1). + +%% A fetched table is committed as it came: no fields are trimmed, it is only +%% checked to be a table, at this cache's own size cap. +accept(Body) when byte_size(Body) =< ?MAX_BYTES -> + case table(json_bytes(Body)) of + {ok, _} -> {ok, Body}; + {error, Reason} -> {error, Reason} + end; +accept(_) -> + {error, <<"cache-ttl response is too large">>}. + +%% A replaced layer file changes the revision the merged cache is keyed by, +%% but the reset makes the next read see the new copy immediately. +after_write(_Cache) -> + _ = persistent_term:erase({?MODULE, merged}), + nil. + +json_bytes(Body) -> + try {ok, json:decode(Body)} + catch _:_ -> {error, invalid} + end. diff --git a/src/albedo/harness/albedo_cached_fetch.erl b/src/albedo/harness/albedo_cached_fetch.erl new file mode 100644 index 000000000..cef132397 --- /dev/null +++ b/src/albedo/harness/albedo_cached_fetch.erl @@ -0,0 +1,90 @@ +-module(albedo_cached_fetch). +%% The one bounded fetch every url-backed cache shares: the models.dev +%% catalog and the cache-ttl table. https-or-loopback urls only, a background +%% refresh when the cache is stale (one registered process per cache, a +%% duplicate spawn killed), an explicit reload that reports failures, and the +%% rename-commit write a failed fetch never reaches. +%% +%% `What` labels every error so each caller keeps its wording. `Accept` +%% validates — and may trim — the body, enforcing its own size cap, before +%% anything is committed. `After` runs once the cache file has been replaced, +%% for the caller's own derived state (the models catalog drops its parse +%% index). + +-export([safe_url/1, refresh/7, reload/5, commit/4, isolated/2]). + +-define(FETCH_TIMEOUT_MS, 30000). + +refresh(Cache0, Url0, MaxAgeMs, RefreshName, What, Accept, After) -> + Cache = text(Cache0), + Url = unicode:characters_to_binary(Url0), + case albedo_credentials:stale(Cache, MaxAgeMs) andalso safe_url(Url) of + false -> nil; + true -> + Pid = spawn(fun() -> fetch_commit(Cache, Url, What, Accept, After) end), + try register(RefreshName, Pid) of + true -> nil + catch + _:_ -> exit(Pid, kill), nil + end + end. + +reload(Cache0, Url0, What, Accept, After) -> + Cache = text(Cache0), + Url = unicode:characters_to_binary(Url0), + try + case safe_url(Url) of + true -> isolated(What, fun() -> fetch_commit(Cache, Url, What, Accept, After) end); + false -> {error, <>} + end + catch + _:_ -> {error, <>} + end. + +%% A partly written cache must never be readable, so the rename is the commit. +%% Exported for the models catalog's in-place retrim, which rewrites a cached +%% file the same way a fetch would. +commit(Cache0, Bytes, What, After) -> + Cache = text(Cache0), + case albedo_credentials:write(Cache, Bytes) of + ok -> After(Cache), {ok, nil}; + {error, {rename, _}} -> {error, <>}; + _ -> {error, <>} + end. + +%% https anywhere; plain http only on loopback, which keeps tests local. +safe_url(Url) -> + Parsed = uri_string:parse(Url), + Scheme = maps:get(scheme, Parsed, undefined), + Host = string:lowercase(maps:get(host, Parsed, <<>>)), + Scheme =:= <<"https">> orelse + (Scheme =:= <<"http">> andalso + lists:member(Host, [<<"localhost">>, <<"127.0.0.1">>, <<"::1">>])). + +fetch_commit(Cache, Url, What, Accept, After) -> + case fetch(Url, What, Accept) of + {ok, Bytes} -> commit(Cache, Bytes, What, After); + Error -> Error + end. + +fetch(Url, What, Accept) -> + Headers = [{"user-agent", "albedo"}, {"accept", "application/json"}], + case albedo_http:get(Url, Headers, ?FETCH_TIMEOUT_MS, 10000) of + {ok, {200, _, Body}} -> Accept(Body); + {ok, {Status, _, _}} -> + {error, iolist_to_binary([What, io_lib:format(" returned HTTP ~B", [Status])])}; + {error, _} -> {error, <>} + end. + +%% Runs Fun in a fresh process so a large decode's garbage dies with it +%% instead of growing the caller's heap for the rest of its life. Fun's result +%% crosses back as an exit reason, so it must be small. Exported because the +%% models catalog's parse path isolates its decode the same way. +isolated(What, Fun) -> + {Pid, Ref} = spawn_monitor(fun() -> exit({done, Fun()}) end), + receive + {'DOWN', Ref, process, Pid, {done, Result}} -> Result; + {'DOWN', Ref, process, Pid, _} -> {error, <>} + end. + +text(Value) -> unicode:characters_to_list(Value). diff --git a/src/albedo/harness/cache_ttl.gleam b/src/albedo/harness/cache_ttl.gleam new file mode 100644 index 000000000..9cad0cbd8 --- /dev/null +++ b/src/albedo/harness/cache_ttl.gleam @@ -0,0 +1,504 @@ +//// The prompt-cache TTL table: the prior phase 2's cache-warmth estimate +//// runs on until a session's request ledger has measured the real thing. +//// +//// Three layers merge by id — the shipped `priv/cache-ttl.json`, an optional +//// remote copy configured in extensions.json, and a local override in +//// `$ALBEDO_HOME` — with later layers replacing same-id entries in place and +//// putting new ids first, so an override can shadow a general default while +//// specific defaults keep their place. First match in table order wins a +//// lookup; values marked `folklore` or `unknown` are placeholders the ledger +//// replaces with measurements. The file I/O and revision cache live in +//// `albedo_cache_ttl.erl`; this module owns the shapes and the matching. + +import albedo/harness/settings +import gleam/dynamic/decode +import gleam/int +import gleam/io +import gleam/json.{type Json} +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string + +/// Whether a lifetime is restarted by every hit, counted from the write, or +/// left to the provider's eviction with no clock at all. +pub type Policy { + Refresh + Fixed + Evict + Unknown +} + +/// Whether a lifetime counts from request start or response end. +pub type Clock { + Request + Response +} + +/// How well the numbers are known. `Folklore` and `Unverified` are +/// placeholders phase 2 replaces with ledger measurements. +pub type Evidence { + Documented + Measured + Implemented + Folklore + Unverified +} + +/// One TTL a request can ask for, with the price of the write that buys it. +pub type Tier { + Tier(seconds: Int, write: Option(Float)) +} + +/// Best-effort eviction windows: typical survival, and a bound when known. +pub type Survival { + Survival(typical: Int, max: Option(Int)) +} + +/// Which requests an entry describes. An absent field matches anything; a +/// pattern matches case-insensitively, with `*` for any run of characters. +pub type Match { + Match( + extension: Option(List(String)), + host: Option(List(String)), + model: Option(List(String)), + ) +} + +pub type Entry { + Entry( + id: String, + /// The layer the entry came from: default, remote, or local. + layer: String, + match: Match, + policy: Policy, + clock: Clock, + tiers: Option(List(Tier)), + /// The read-price multiplier, when the provider charges for hits. + read: Option(Float), + survival: Option(Survival), + evidence: Evidence, + source: String, + checked: String, + note: String, + ) +} + +/// One layer of the merged table, as the route reports it. +pub type Layer { + Layer(name: String, path: String, loaded: Bool, error: Option(String)) +} + +pub type Table { + Table(entries: List(Entry), layers: List(Layer)) +} + +/// The remote layer's configuration in extensions.json: absent `url` means +/// no fetch, `refreshHours: 0` disables the background refresh. +pub type Config { + Config(url: Option(String), refresh_hours: Int) +} + +const remote_file = "cache-ttl-remote.json" + +/// The merged table: all layers, entries tagged with where they came from. +/// Triggers a background refresh of a stale remote copy, like the models +/// catalog's lookups do. +pub fn table() -> Table { + refresh() + case native_merged() { + Ok(encoded) -> + json.parse(encoded, table_decoder()) |> result.unwrap(Table([], [])) + Error(reason) -> { + io.println_error("cache-ttl: " <> reason) + Table([], []) + } + } +} + +/// The first entry in table order whose match covers the request. The file +/// lists specific entries before general ones, so order is the precedence. +pub fn lookup(extension: String, host: String, model: String) -> Option(Entry) { + table().entries + |> list.find(fn(entry) { matches(entry, extension, host, model) }) + |> option.from_result +} + +/// Fetch and replace the remote copy now, regardless of its age, so an +/// explicit `/reload` never claims stale data was refreshed. A failed fetch +/// keeps the previous copy; no configured url is nothing to do. +pub fn reload() -> Result(Nil, String) { + case settings.load("cacheTtl", config_decoder(), Config(None, 24)) { + Ok(Config(url: None, ..)) -> Ok(Nil) + Ok(Config(url: Some(url), ..)) -> native_reload(remote_path(), url) + Error(reason) -> Error(reason) + } +} + +fn refresh() -> Nil { + case settings.load("cacheTtl", config_decoder(), Config(None, 24)) { + Ok(Config(url: Some(url), refresh_hours: hours)) -> + case hours > 0 { + True -> native_refresh(remote_path(), url, hours * 3_600_000) + False -> Nil + } + _ -> Nil + } +} + +pub fn remote_path() -> String { + settings.home() <> "/" <> remote_file +} + +fn config_decoder() -> decode.Decoder(Config) { + use url <- decode.optional_field("url", None, decode.optional(decode.string)) + use hours <- decode.optional_field("refreshHours", 24, decode.int) + decode.success(Config(url, hours)) +} + +/// A bad entry never fails the table: it is skipped, and the reason logged. +fn table_decoder() -> decode.Decoder(Table) { + use entries <- decode.field("entries", entries_decoder()) + use layers <- decode.field("layers", decode.list(layer_decoder())) + decode.success(Table(entries, layers)) +} + +fn entries_decoder() -> decode.Decoder(List(Entry)) { + decode.map(decode.list(decode.dynamic), fn(raw) { + raw + |> list.index_map(fn(item, position) { + case decode.run(item, entry_decoder()) { + Ok(entry) -> Ok(entry) + Error(errors) -> { + report(position, errors) + Error(Nil) + } + } + }) + |> list.filter_map(fn(decoded) { decoded }) + }) +} + +fn layer_decoder() -> decode.Decoder(Layer) { + use name <- decode.field("name", decode.string) + use path <- decode.field("path", decode.string) + use loaded <- decode.field("loaded", decode.bool) + use error <- decode.optional_field( + "error", + None, + decode.optional(decode.string), + ) + decode.success(Layer(name, path, loaded, error)) +} + +fn entry_decoder() -> decode.Decoder(Entry) { + use id <- decode.field("id", decode.string) + use layer <- decode.field("layer", decode.string) + use match <- decode.optional_field( + "match", + Match(None, None, None), + match_decoder(), + ) + use policy <- decode.field("policy", policy_decoder()) + use clock <- decode.optional_field("clock", Response, clock_decoder()) + use tiers <- decode.optional_field( + "tiers", + None, + decode.optional(tiers_decoder()), + ) + use read <- decode.optional_field("read", None, decode.optional(multiplier())) + use survival <- decode.optional_field( + "survival", + None, + decode.optional(survival_decoder()), + ) + use evidence <- decode.field("evidence", evidence_decoder()) + use source <- decode.optional_field("source", "", decode.string) + use checked <- decode.optional_field("checked", "", decode.string) + use note <- decode.optional_field("note", "", decode.string) + decode.success(Entry( + id, + layer, + match, + policy, + clock, + tiers, + read, + survival, + evidence, + source, + checked, + note, + )) +} + +fn match_decoder() -> decode.Decoder(Match) { + use extension <- decode.optional_field("extension", None, globs_decoder()) + use host <- decode.optional_field("host", None, globs_decoder()) + use model <- decode.optional_field("model", None, globs_decoder()) + decode.success(Match(extension, host, model)) +} + +/// One pattern or a list of them, where a list matches if any element does. +fn globs_decoder() -> decode.Decoder(Option(List(String))) { + decode.one_of(decode.optional(decode.list(decode.string)), or: [ + decode.map(decode.optional(decode.string), fn(one) { + option.map(one, fn(pattern) { [pattern] }) + }), + ]) +} + +fn policy_decoder() -> decode.Decoder(Policy) { + decode.string + |> decode.then(fn(policy) { + case policy { + "refresh" -> decode.success(Refresh) + "fixed" -> decode.success(Fixed) + "evict" -> decode.success(Evict) + "unknown" -> decode.success(Unknown) + _ -> + decode.failure(Unknown, "a policy of refresh, fixed, evict or unknown") + } + }) +} + +fn clock_decoder() -> decode.Decoder(Clock) { + decode.string + |> decode.then(fn(clock) { + case clock { + "request" -> decode.success(Request) + "response" -> decode.success(Response) + _ -> decode.failure(Response, "a clock of request or response") + } + }) +} + +fn evidence_decoder() -> decode.Decoder(Evidence) { + decode.string + |> decode.then(fn(evidence) { + case evidence { + "documented" -> decode.success(Documented) + "measured" -> decode.success(Measured) + "implemented" -> decode.success(Implemented) + "folklore" -> decode.success(Folklore) + "unknown" -> decode.success(Unverified) + _ -> + decode.failure( + Unverified, + "evidence of documented, measured, implemented, folklore or unknown", + ) + } + }) +} + +fn tiers_decoder() -> decode.Decoder(List(Tier)) { + decode.list(tier_decoder()) +} + +fn tier_decoder() -> decode.Decoder(Tier) { + use seconds <- decode.field( + "seconds", + positive_int("a positive number of seconds"), + ) + use write <- decode.optional_field( + "write", + None, + decode.optional(multiplier()), + ) + decode.success(Tier(seconds, write)) +} + +fn survival_decoder() -> decode.Decoder(Survival) { + use typical <- decode.field( + "typical", + positive_int("a positive number of seconds"), + ) + use max <- decode.optional_field("max", None, decode.optional(decode.int)) + decode.success(Survival(typical, max)) +} + +fn multiplier() -> decode.Decoder(Float) { + decode.one_of(decode.float, or: [decode.map(decode.int, int.to_float)]) + |> decode.then(fn(value) { + case value >. 0.0 { + True -> decode.success(value) + False -> decode.failure(0.0, "a positive multiplier") + } + }) +} + +fn positive_int(expected: String) -> decode.Decoder(Int) { + decode.int + |> decode.then(fn(value) { + case value > 0 { + True -> decode.success(value) + False -> decode.failure(0, expected) + } + }) +} + +/// Every named field of the match must cover the request. +fn matches( + entry: Entry, + extension: String, + host: String, + model: String, +) -> Bool { + let Match(extensions, hosts, models) = entry.match + covers(extensions, extension) && covers(hosts, host) && covers(models, model) +} + +fn covers(patterns: Option(List(String)), value: String) -> Bool { + case patterns { + None -> True + Some(patterns) -> + list.any(patterns, fn(pattern) { matches_glob(pattern, value) }) + } +} + +fn matches_glob(pattern: String, value: String) -> Bool { + glob(string.lowercase(pattern), string.lowercase(value)) +} + +/// Glob matching where `*` covers any run of characters, including none. +fn glob(pattern: String, value: String) -> Bool { + case string.pop_grapheme(pattern) { + Error(Nil) -> value == "" + Ok(#("*", rest)) -> + glob(rest, value) + || case string.pop_grapheme(value) { + Ok(#(_, tail)) -> glob(pattern, tail) + Error(Nil) -> False + } + Ok(#(head, rest)) -> + case string.pop_grapheme(value) { + Ok(#(letter, tail)) -> head == letter && glob(rest, tail) + Error(Nil) -> False + } + } +} + +fn report(position: Int, errors: List(decode.DecodeError)) -> Nil { + let reasons = + list.map(errors, fn(error) { + let where = case error.path { + [] -> "the entry" + path -> "the entry at " <> string.join(path, ".") + } + error.expected <> " (found " <> error.found <> ") at " <> where + }) + |> string.join("; ") + io.println_error( + "cache-ttl: skipping entry " <> int.to_string(position) <> ": " <> reasons, + ) +} + +pub fn table_json(table: Table) -> Json { + json.object([ + #("entries", json.array(table.entries, entry_json)), + #("layers", json.array(table.layers, layer_json)), + ]) +} + +pub fn entry_json(entry: Entry) -> Json { + json.object([ + #("id", json.string(entry.id)), + #("layer", json.string(entry.layer)), + #("match", match_json(entry.match)), + #("policy", json.string(policy_name(entry.policy))), + #("clock", json.string(clock_name(entry.clock))), + #( + "tiers", + optional(entry.tiers, fn(tiers) { json.array(tiers, tier_json) }), + ), + #("read", optional(entry.read, json.float)), + #("survival", optional(entry.survival, survival_json)), + #("evidence", json.string(evidence_name(entry.evidence))), + #("source", json.string(entry.source)), + #("checked", json.string(entry.checked)), + #("note", json.string(entry.note)), + ]) +} + +fn layer_json(layer: Layer) -> Json { + json.object([ + #("name", json.string(layer.name)), + #("path", json.string(layer.path)), + #("loaded", json.bool(layer.loaded)), + #("error", optional(layer.error, json.string)), + ]) +} + +fn match_json(match: Match) -> Json { + let Match(extension, host, model) = match + json.object([ + #( + "extension", + optional(extension, fn(patterns) { json.array(patterns, json.string) }), + ), + #( + "host", + optional(host, fn(patterns) { json.array(patterns, json.string) }), + ), + #( + "model", + optional(model, fn(patterns) { json.array(patterns, json.string) }), + ), + ]) +} + +fn tier_json(tier: Tier) -> Json { + json.object([ + #("seconds", json.int(tier.seconds)), + #("write", optional(tier.write, json.float)), + ]) +} + +fn survival_json(survival: Survival) -> Json { + json.object([ + #("typical", json.int(survival.typical)), + #("max", optional(survival.max, json.int)), + ]) +} + +fn optional(value: Option(a), encode: fn(a) -> Json) -> Json { + case value { + Some(present) -> encode(present) + None -> json.null() + } +} + +fn policy_name(policy: Policy) -> String { + case policy { + Refresh -> "refresh" + Fixed -> "fixed" + Evict -> "evict" + Unknown -> "unknown" + } +} + +fn clock_name(clock: Clock) -> String { + case clock { + Request -> "request" + Response -> "response" + } +} + +fn evidence_name(evidence: Evidence) -> String { + case evidence { + Documented -> "documented" + Measured -> "measured" + Implemented -> "implemented" + Folklore -> "folklore" + Unverified -> "unknown" + } +} + +@external(erlang, "albedo_cache_ttl", "merged") +fn native_merged() -> Result(String, String) + +@external(erlang, "albedo_cache_ttl", "refresh") +fn native_refresh(path: String, url: String, max_age_ms: Int) -> Nil + +@external(erlang, "albedo_cache_ttl", "reload") +fn native_reload(path: String, url: String) -> Result(Nil, String) diff --git a/src/albedo/harness/extensions/commands/extension.gleam b/src/albedo/harness/extensions/commands/extension.gleam index 27c2151ba..028aa44e1 100644 --- a/src/albedo/harness/extensions/commands/extension.gleam +++ b/src/albedo/harness/extensions/commands/extension.gleam @@ -1,5 +1,6 @@ //// The built-in session commands and the Python kernel's `commands` object. +import albedo/harness/cache_ttl import albedo/harness/command.{ type Command, type Context, Argument, Command, Compact, ContextPage, ContextSummary, Data, EffortGet, EffortSelect, ModelCall, ModelGet, @@ -121,7 +122,7 @@ fn model() -> Command { fn reload() -> Command { Command( "/reload", - "Reload cached runtime data: the models.dev catalog, the session's skills catalog and extension context, or both. A session reload rescans in place — the kernel, its Python namespace, and the prompt cache keep running.", + "Reload cached runtime data: the models.dev catalog, the session's skills catalog and extension context, or both. A session reload rescans in place — the kernel, its Python namespace, and the prompt cache keep running. The cache TTL table's remote copy is re-fetched with the models catalog.", [ Argument( "target", @@ -143,11 +144,12 @@ fn reload() -> Command { ) Error(_) -> { use _ <- result.try(models.reload()) + use _ <- result.try(cache_ttl.reload()) use _ <- result.try(ctx.state(Refresh)) Ok( reloaded( "models+session", - "Models catalog reloaded; extension context, skills catalog, and session commands rescanned.", + "Models catalog and cache TTL table reloaded; extension context, skills catalog, and session commands rescanned.", [], ), ) diff --git a/src/albedo/harness/extensions/models/albedo_models.erl b/src/albedo/harness/extensions/models/albedo_models.erl index b45d275fb..5edfe47e8 100644 --- a/src/albedo/harness/extensions/models/albedo_models.erl +++ b/src/albedo/harness/extensions/models/albedo_models.erl @@ -6,61 +6,26 @@ -export([refresh/3, reload/2, lookup/3, lookup_provider/3, list/3]). -define(MAX_BYTES, 33554432). --define(FETCH_TIMEOUT_MS, 30000). -define(REFRESH_PROCESS, albedo_models_refresh). -refresh(Catalog0, Url0, MaxAgeMs) -> - Catalog = text(Catalog0), - Url = unicode:characters_to_binary(Url0), - case albedo_credentials:stale(Catalog, MaxAgeMs) andalso safe_url(Url) of - false -> nil; - true -> - Pid = spawn(fun() -> fetch(Catalog, Url) end), - try register(?REFRESH_PROCESS, Pid) of - true -> nil - catch - _:_ -> - exit(Pid, kill), - nil - end - end. +%% Every error the shared fetch reports on this cache's behalf keeps this +%% catalog's name, so the wording stays this module's own. +-define(WHAT, <<"models catalog">>). -reload(Catalog0, Url0) -> - Catalog = text(Catalog0), - Url = unicode:characters_to_binary(Url0), - try - case safe_url(Url) of - true -> isolated(fun() -> fetch(Catalog, Url) end); - false -> {error, <<"models catalog URL must use https or loopback http">>} - end - catch - _:_ -> {error, <<"models catalog URL is invalid">>} - end. +refresh(Catalog, Url, MaxAgeMs) -> + albedo_cached_fetch:refresh(Catalog, Url, MaxAgeMs, ?REFRESH_PROCESS, + ?WHAT, fun accept/1, fun after_write/1). -%% https anywhere; plain http only on loopback, which keeps tests local. -safe_url(Url) -> - Parsed = uri_string:parse(Url), - Scheme = maps:get(scheme, Parsed, undefined), - Host = string:lowercase(maps:get(host, Parsed, <<>>)), - Scheme =:= <<"https">> orelse - (Scheme =:= <<"http">> andalso - lists:member(Host, [<<"localhost">>, <<"127.0.0.1">>, <<"::1">>])). - -fetch(Catalog, Url) -> - Headers = [{"user-agent", "albedo"}, {"accept", "application/json"}], - case albedo_http:get(Url, Headers, ?FETCH_TIMEOUT_MS, 10000) of - {ok, {200, _, Body}} when byte_size(Body) =< ?MAX_BYTES -> - case compact(Body) of - {ok, Trimmed} -> store(Catalog, Trimmed); - error -> {error, <<"models catalog response is not valid">>} - end; - {ok, {200, _, _}} -> - {error, <<"models catalog response is too large">>}; - {ok, {Status, _, _}} -> - {error, iolist_to_binary(io_lib:format("models catalog returned HTTP ~B", [Status]))}; - {error, _} -> - {error, <<"models catalog request failed">>} - end. +reload(Catalog, Url) -> + albedo_cached_fetch:reload(Catalog, Url, ?WHAT, fun accept/1, fun after_write/1). + +accept(Body) when byte_size(Body) =< ?MAX_BYTES -> + case compact(Body) of + {ok, Trimmed} -> {ok, Trimmed}; + error -> {error, <<"models catalog response is not valid">>} + end; +accept(_) -> + {error, <<"models catalog response is too large">>}. %% A valid catalog re-encoded with only what provider/3 and model/1 read. Every %% provider stays: lookup falls back to matching a model id across all of them, @@ -105,28 +70,13 @@ trim_model(_, _) -> false. nonempty(_, Value, Map) when map_size(Value) =:= 0 -> Map; nonempty(Key, Value, Map) -> Map#{Key => Value}. -%% Runs Fun in a fresh process so a large decode's garbage dies with it instead -%% of growing the caller's heap for the rest of its life. Fun's result crosses -%% back as an exit reason, so it must be small. -isolated(Fun) -> - {Pid, Ref} = spawn_monitor(fun() -> exit({done, Fun()}) end), - receive - {'DOWN', Ref, process, Pid, {done, Result}} -> Result; - {'DOWN', Ref, process, Pid, _} -> {error, <<"models catalog could not be read">>} - end. - -%% A partly written catalog must never be readable, so the rename is the commit. -store(Catalog, Body) -> - case albedo_credentials:write(Catalog, Body) of - ok -> - _ = persistent_term:erase({?MODULE, Catalog}), - _ = file:delete(index_path(Catalog)), - {ok, nil}; - {error, {rename, _}} -> - {error, <<"models catalog cache could not be replaced">>}; - _ -> - {error, <<"models catalog cache could not be written">>} - end. +%% Once a catalog is replaced, its parse index and revision cache are stale; +%% both self-heal on the next parse, but dropping them keeps the next lookup +%% from trusting the old revision first. +after_write(Catalog) -> + _ = persistent_term:erase({?MODULE, Catalog}), + _ = file:delete(index_path(Catalog)), + nil. lookup(Catalog0, Model0, Endpoint0) -> Catalog = text(Catalog0), @@ -185,7 +135,7 @@ load(Catalog, Revision) -> case persistent_term:get({?MODULE, Catalog}, undefined) of {Revision, Index} -> {ok, Index}; _ -> - case isolated(fun() -> from_index(Catalog, Revision) end) of + case albedo_cached_fetch:isolated(?WHAT, fun() -> from_index(Catalog, Revision) end) of ok -> {ok, element(2, persistent_term:get({?MODULE, Catalog}))}; Error -> Error end @@ -239,7 +189,7 @@ retrim(Catalog, Decoded, {_, Modified} = Revision) -> case trimmed(Decoded) of true -> Revision; false -> - case store(Catalog, trim(Decoded)) of + case albedo_cached_fetch:commit(Catalog, trim(Decoded), ?WHAT, fun after_write/1) of {ok, nil} -> _ = file:write_file_info(Catalog, #file_info{mtime = Modified}, [{time, posix}]), case file:read_file_info(Catalog, [{time, posix}]) of diff --git a/test/e2e/cache_ttl_test.py b/test/e2e/cache_ttl_test.py new file mode 100644 index 000000000..697a2f573 --- /dev/null +++ b/test/e2e/cache_ttl_test.py @@ -0,0 +1,211 @@ +"""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. It touches extensions.json and cache-ttl.json in +the shared test home (the warmer suite writes its own override there), so the +class is exclusive and restores every file it wrote. + +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. +""" +import json +import time +import unittest +import urllib.error +import urllib.request + +from harness import ROOT, Albedo, Provider, exclusive, text + +SHIPPED = json.loads((ROOT / "priv" / "cache-ttl.json").read_text()) + +# `/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 = { + "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 = { + "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"}, + ], +} + + +def write_atomic(path, payload): + temporary = path.with_suffix(".tmp") + temporary.write_text(json.dumps(payload)) + temporary.replace(path) + + +@exclusive +class CacheTtlTests(unittest.TestCase): + def setUp(self): + self.provider = Provider(lambda _request: text("ok"), catalog=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.home / "cache-ttl.json").unlink(missing_ok=True) + (app.home / "cache-ttl-remote.json").unlink(missing_ok=True) + (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", + "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.restore_home) + self.addCleanup(self.app.__exit__, None, None, None) + + def restore_home(self): + (self.app.home / "cache-ttl.json").unlink(missing_ok=True) + (self.app.home / "cache-ttl-remote.json").unlink(missing_ok=True) + + def table(self): + with self.app.api("/cache-ttl") as response: + return json.load(response) + + def resolved(self, query): + with self.app.api("/cache-ttl" + query) as response: + return json.load(response) + + 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"]} + + def test_default_table_is_served_and_lookups_resolve(self): + table = self.table() + self.assertTrue(self.layers(table)["default"]["loaded"]) + self.assertIn("priv/cache-ttl.json", self.layers(table)["default"]["path"]) + self.assertFalse(self.layers(table)["local"]["loaded"]) + # Every shipped entry, each tagged with the layer it came from. + self.assertEqual(set(self.entries(table)), {e["id"] for e in SHIPPED["entries"]}) + for entry in table["entries"]: + self.assertEqual(entry["layer"], "default") + # First match in table order: the subscription entry shadows nothing, + # but a specific model glob beats the general host entry after it. + claude = self.resolved("?extension=claude") + self.assertEqual(claude["id"], "claude-subscription") + self.assertEqual(claude["policy"], "refresh") + self.assertEqual(claude["clock"], "request") + self.assertEqual([t["seconds"] for t in claude["tiers"]], [300, 3600]) + self.assertEqual(claude["read"], 0.1) + deepseek = self.resolved("?host=api.deepseek.com") + self.assertEqual(deepseek["id"], "deepseek") + self.assertEqual(deepseek["policy"], "evict") + self.assertEqual(deepseek["survival"]["typical"], 14400) + # Matching is case-insensitive. + self.assertEqual(self.resolved("?host=API.DEEPSEEK.COM")["id"], "deepseek") + # A model glob within a list of patterns, ahead of the plain host rule. + self.assertEqual( + self.resolved("?host=api.openai.com&model=gpt-5.6-turbo")["id"], "openai-5.6") + self.assertEqual(self.resolved("?host=api.openai.com&model=gpt-4o")["id"], "openai") + self.assertIsNone(self.resolved("?extension=never-heard-of-it")) + + def test_local_override_replaces_and_adds_without_restart(self): + write_atomic(self.app.home / "cache-ttl.json", LOCAL_OVERRIDE) + table = self.table() + local = self.layers(table)["local"] + self.assertTrue(local["loaded"]) + self.assertEqual(local["path"], str(self.app.home / "cache-ttl.json")) + 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_malformed_local_file_keeps_the_last_good_table(self): + write_atomic(self.app.home / "cache-ttl.json", LOCAL_OVERRIDE) + self.assertTrue(self.layers(self.table())["local"]["loaded"]) + (self.app.home / "cache-ttl.json").write_text("{ this is not json") + table = self.table() + local = self.layers(table)["local"] + self.assertFalse(local["loaded"]) + self.assertIn("not valid JSON", local["error"]) + 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.app.home / "cache-ttl.json", 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.app.home / "cache-ttl-remote.json")) + 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() + self.assertFalse((self.app.home / "cache-ttl-remote.json").exists()) + with self.app.api(f"/sessions/{session}/commands", + {"name": "/reload", "args": {}}) as response: + outcome = json.load(response)["result"] + self.assertEqual(outcome["reloaded"], "models+session") + table = self.table() + self.assertTrue(self.layers(table)["remote"]["loaded"]) + self.assertEqual(self.entries(table)["deepseek"]["note"], "remote override") + + def test_route_requires_authentication(self): + request = urllib.request.Request(self.app.base + "/cache-ttl") + with self.assertRaises(urllib.error.HTTPError) as refused: + urllib.request.urlopen(request, timeout=20) + self.assertEqual(refused.exception.code, 403) -- knotmirror 0.0.1