Repository navigation
Description
Problem
LLMClient.chat_messages returns a cache hit at src/devops_cli/ai/client/unified.py:739-742, before _retry_chat_dispatch. chat only calls chat_messages (unified.py:516-527). The hit comes from _check_chat_cache (unified.py:587-608) as an LLMResponse with cached=True, backend_info="cache" and no token counts. Only the dispatch path records a call. _dispatch_messages calls _record_response_telemetry_and_spend (unified.py:425-427, :460-499), which calls track_request_spend with cached=res.cached (:484-497). That value is always False there.
track_request_spend (src/devops_cli/ai/spend/ledger.py:610) is the only route to three consumers, so none of them hears about a hit:
- The spend ledger. Its cached count (
ledger.py:99, shown as "Cached Requests (Saved Spend)" atsrc/devops_cli/commands/ai_cost.py:37) is always 0. devops_cli_ai_requests_total(emitted atledger.py:696). It never carriescached="true", although its description says "whether the cache answered" (src/devops_cli/telemetry/instruments.py:90-95).- The review profiler. It is notified at
ledger.py:675through_notify_call_observers(:586-588).ReviewProfiler.observecountscached_callsonly for a call marked cached (src/devops_cli/ai/review/profile.py:216-218), so everyprofile.jsonreportscached_calls0.
Measured in review session 20261002-200610 (s4, a branch review of release/v0.2.25 at cf8ae47, 2026-10-02):
profile.jsonreportsllm_calls141 (persona_review 40, verification 101) andcached_calls0. The spend ledger has exactly 141 rows in the session window, all withcached0.- The cache answered 314 more calls. 301 persona pages were served from entries written before the session and read during it: 341 pages = 301 + 39 new entries + 1 cut reply. 13 verifier calls were served the same way: of 138 verified files, 24 were settled without a model, and the other 114 = 101 calls + 13 hits. So 69% of 455 requests came from the cache.
- In the earlier sessions, 192 of 268 persona replies (s2) and 238 of 319 (s3) came from the cache. Verifier hits were 3, 6 and 13 in s2, s3 and s4.
- The hits stood in for about 3.34M prompt tokens in s4, more than the 2.29M it sent. This is an estimate from the tokens stored with the entries that answered.
- At 21:40 UTC the ledger holds 9,868 rows, with
SUM(cached)0.
Where a hit shows today:
- the console's "handled by cache" line (
backend_infoset atunified.py:605; lines formatted atsrc/devops_cli/ai/review/pipeline.py:393-414and:2745-2749); - the span attribute
llm.cached(unified.py:599); - the entry's
hit_countandlast_accessed(src/devops_cli/ai/response_cache.py:213-216,:227-231).
No session file records a hit. The terminal Profile line prints only calls (src/devops_cli/ai/review/runner.py:2047-2058). devops ai cache status shows per-process counters (response_cache.py:158-159, :340-357; src/devops_cli/commands/ai_cache.py:30-31), so a new process shows 0. review.md has no LLM-usage section. It is rendered at runner.py:2159, inside the call at :2105, before the profile is built at :2116.
Further findings:
- Three gauges that cannot count.
devops_cli_llm_cache_hits,_missesand_writes(response_cache.py:217,:232,:236,:283) are single-point gauges of 1.0 (src/devops_cli/telemetry/tracer.py:872-888). They are not inINSTRUMENTS, and no issue covers them; feat(rag): embedding-cache hits and misses as counters #817 is the embedding cache. - The cache counts a hit before the client checks the entry.
get()raiseshit_count,_hitsand the gauge (response_cache.py:213-217,:227-232) before_check_chat_cachevalidates the entry (unified.py:594-598). An entry with empty content is then rejected, and the call is sent anyway. The append-cache starting-point lookup (unified.py:707-717) also counts a hit and then sends the call. A count taken at the cache layer would include these. - The stream and direct paths have no hit path. The stream path (
_dispatch_streamthrough_record_stream_spend,unified.py:758-918) never reads the cache, so itscached=False(:911) is true.ai/direct.pyuses no response cache (:108,:154,:199,:232), so leavingcachedunset (:118,:164) is true. Separately, the direct stream functions (direct.py:178-241) record no spend. Nothing insrc/calls them except the unusedLLMClient.direct_*methods (unified.py:929-1012), so that gap is latent. - Reusing the dispatch recorder for a hit goes wrong. A hit has no token counts, so
_record_response_telemetry_and_spendwould estimate them (unified.py:475-483). It would also record the servercache(unified.py:471, via:69), whichCOUNT(DISTINCT server)(ledger.py:100) adds to "Active Backend Servers" (ai_cost.py:38). - Request series will start counting hits. Once hits are recorded, "AI Requests in Range" (
k8s/monitoring/dashboards/ai-spend.json:194) and "Request Rate by Model" (:598) count them. So does the ledger's text exporter, under the help text "Total number of AI model requests executed" (src/devops_cli/ai/spend/prometheus.py:100-106).
Changes since this issue was written: the cited lines moved. Line references in this body are at e4ea2e0. Against ea49d6e, the version it was filed against on 2026-10-01:
unified.py:694-696is now:739-742. The hit return sits inchat_messages, whichchatcalls.unified.py:382is now:425-427,:441-449is:484-497, and:836-844is:903-916.direct.py:163is now:164.ledger.py:660is now:696, and:92is:99.instruments.py:70-75is now:90-95.ai-spend.json:223is now:292.
At the branch tip (79e1e93) only the pipeline.py lines moved, with #987: :393-414 is now :402-423, and :2745-2749 is :2915-2919.
The stream and direct paths are out of scope, since neither has a hit path.
Acceptance criteria
- A second identical
chat(use_cache=True)sends onedevops_cli_ai_requests_total{cached="true"}point, adds 0 todevops_cli_ai_tokens_total, and sends no spend point. The ledger gains one row withcached1, 0 prompt and 0 completion tokens, and cost 0. - A hit through the persona agent (
src/devops_cli/ai/agents/agent.py:887) and a hit through the verifier (src/devops_cli/ai/review/verification.py:2128) each record one cached row, in the same stage a dispatch there records (review.file_review,review.verification). - A profiled review runs over a pre-seeded tmp cache with a stub provider: two persona pages, one of them cached, and one verifier call, cached.
profile.jsonshowspersona_reviewwithllm_calls1 andcached_calls1, andverificationwithllm_calls0 andcached_calls1.llm_callscounts only calls sent to a model. - A cached entry the client rejects (empty content) and an append-cache starting-point lookup are not hits. Each call is recorded once, as a dispatch, with
cached="false". - After one dispatch and one hit,
devops ai spendreports 2 requests, 1 cached request and 1 active backend server. -
devops_cli_llm_cache_hits,_missesand_writesare removed.devops_cli_ai_requests_total{cached}carries the hit count. -
k8s/monitoring/dashboards/ai-spend.jsongains a response-cache hit-share panel:cached="true"over all requests, each insideincrease(...[1h]). The panel query passestests/test_telemetry_instruments.py. The "Active AI Backends" panel keeps itscached="false"filter (ai-spend.json:292). - The ledger exporter's
devops_cli_ai_requests_total(spend/prometheus.py:100-106) counts only requests sent to a model, as its help text says. - The tests are offline, use a tmp cache and a tmp ledger, and add well under 1 s to
uv run devops ci. -
changelog.d/816.mdrecords the fix under### Fixed.CHANGELOG.mdis not edited. -
uv run devops cipasses. - (person-run) Two branch reviews of the same commit on the homelab gateway: the second run's
profile.jsoncached_callsequals the cached rows the ledger gained during that run, is at least its count of "handled by cache" console lines (a file with several cached pages prints one line), anddevops ai spendshows those rows as cached requests.
Key questions
- Do cached hits add to
devops_cli_ai_tokens_total? (proposed) No. A hit records 0 prompt and 0 completion tokens, because no model processed them. - Where is a hit recorded: in the client or in the cache? (proposed) In the client, at the hit return in
chat_messages, after the cached entry passed its check. That one place coverschat, the persona agent and the verifier, and the persona workers' thread pool carries the stage context (src/devops_cli/ai/agents/pipeline.py:235). The cache layer counts before the check (response_cache.py:213-232), so it would count lookups the client then sends to a model. - Do the stream and direct paths need changes? (proposed) No. Neither reads the response cache, so their
cachedvalue is already true. The direct stream functions' missing spend is a separate, latent gap. - Which server does a hit row name? (proposed)
cache, so a hit is legible in the ledger. The ledger's distinct-server count skips cached rows, as the "Active AI Backends" panel already does. - Do the request panels count hits? (proposed) "AI Requests in Range" and "Request Rate by Model" count every request, hits included. That is what the counter's
cachedlabel is for, and the new panel shows the split. The ledger exporter keeps "requests executed" and counts uncached rows only, because its tokens and spend come only from those. - Remove the
devops_cli_llm_cache_*gauges, or make them counters? (proposed) Remove them. After this change the requests counter'scachedlabel carries hits. A gauge from a short-lived process holds only its last value (feat(cli): devops-cli dashboards chart the metrics the cli sends and the grafana sidecar provisions them #692), and pre-1.0 needs no deprecation. - Does this item show hits on the terminal, in review.md or in
devops ai cache status? (proposed) No. It records hits, soprofile.jsoncached_callsbecomes true. Showing them is feat(review): group analysis is profiled as its own stage, and analysis.json counts dispatched, replayed and failed jobs apart #482's per-run reporting: the terminal Profile line (runner.py:2047-2058), review.md, which is rendered before the profile is built and so needs the live profiler, andcache status.
Depends on: none. #692, the original dependency, is closed.
Order: before #482, which reports per-run hit rates from what this item records. #1013 edits the same hit return (unified.py:739-742) and makes the client delete a rejected entry; whichever lands second rebases, and a lookup #1013 rejects stays out of the hit count here. #987 has merged (b1fddd0) without touching runner.py:2040-2059, unified.py, ledger.py, profile.py or response_cache.py.
Related: #482 (per-run hit rates and prompt-prefix order). #817 (embedding-cache counters). #1013 (the cache stores and serves replies the review cannot use). #871 (which model produced a reply). #599 and #966 (finish reasons). #692 (dashboards query only INSTRUMENTS).
Update 2026-10-08
Delivered on fix/816-response-cache-hits-are-cached-requests (6cbb31f, from release/v0.2.29 at 910b823). How the delivered scope differs from the body above:
Line references at 910b823
unified.py: the hit return is at:723-726(now calls_record_cache_hit),_check_chat_cacheat:567-588, the dispatch recorder at:440-479, the append-cache lookup at:690-701, and the stream recorder at:868-902.ledger.py:track_request_spendat:612.profile.py: the cached branch at:238-240.- Persona agent call at
agent.py:934; verifier call atverification.py:2743. ai-spend.json: "Request Rate by Model" at:819.
Amended criteria and scope
- Command name.
devops ai spendis thecostapp, so criterion 5 is checked withdevops ai spend report --json. - Provider server count. It gets the same
cached = 0filter as the overall count. The provider reader'sor 1fallback becameor 0, so a provider whose rows are all hits shows 0 servers, not 1. - Local requests. Hits are left out of
local_requests: thecacheserver is never local. The body did not mention this side effect. - Exporter. It subtracts a new per-model
ModelSpendSummary.cached_requestsrather than redefiningrequest_count, so thedevops ai spendtables still count every request and match "Total Requests Processed". - Dashboard. The new "Response Cache Hit Share" panel (id 19) states the
increase()limits in its description. "AI Requests in Range" and "Request Rate by Model" now say they include cache answers. - Recording point. A hit is recorded only at the client's hit return, after the entry passed its check. A rejected entry and the append-cache lookup are recorded once, as dispatches, as the body proposed.
Corrected premises
None of the body's premises was wrong; only line references moved.
Tests
- The tmp-ledger fixture
spend_ledgermoved totests/conftest.py. - The review integration test reviews a YAML file with static scanners off, from the target directory: payload set-up probes the working directory for manifests. It runs in about 0.4 s.
- refactor(review): the model verifier, the hallucination catalog and the model-claim guards are deleted, and person-recorded verdicts become suppressions #1150 and refactor(review): the persona review stage, the legacy segment engine and review-time RAG are deleted, and devops review builds a model client only for the explanation stages #1151 delete the stages that test exercises, so it goes with them.
Still open
- The person-run gateway check, recorded as "Pending a person:" in the task file.
- Showing hits on the terminal, in review.md and in
ai cache status(feat(review): group analysis is profiled as its own stage, and analysis.json counts dispatched, replayed and failed jobs apart #482). - Found while testing, outside this item:
get_llm_response_cacheignorescache_enabled=Falseonce the singleton exists.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
dan-petty commentedon Oct 3, 2026
What S10 adds (review session
20261003-034353, release/v0.2.25 at d6ebe97;.data/review-evaluation-20261003-s10.md, section 3, Cache).profile.jsonreportsllm_calls16 andcached_calls0, yet 370 response-cache entries were replayed in the session window (03:43:53-03:56:33):dc091e4c, all created by S9);04f4c24c: 8 from S8 and 9 from S9, covering 23 findings).14 entries were created (7 persona, 7 verifier). The 2 cut verifier replies were not cached.
dan-petty commentedon Oct 3, 2026
Consolidation (2026-10-03): this item is a sub-issue of #817, which now converts every
record_metriccall site into a declared instrument. This item's scope and v0.2.29 placement are unchanged. The sweep in #817 leaves thedevops_cli_llm_cache_*gauges inai/response_cache.pyto this item.fix(ai): count response-cache hits as cached requests (#816) (#1378)
dan-petty-bot commentedon Oct 8, 2026
What changed
#1378, merged into
release/v0.2.29as 3f8df5f.15 file(s) changed.
How it was verified
Check runs at 6cbb31f:
Acceptance Criteria of
docs/agent/tasks/task-816-response-cache-hits-counted-as-cached-requests.md:chat(use_cache=True)sends onedevops_cli_ai_requests_total{cached="true"}point, adds 0 todevops_cli_ai_tokens_totaland sends no spend point; the ledger gains a row withcached1, 0 prompt and 0 completion tokens and cost 0, and the provider is called once:test_a_response_cache_hit_counts_one_cached_request_with_no_tokens_or_spend(a hostedgpt-4o, so the dispatch's spend point shows the contrast).review.file_review0 and 1 andreview.verification1 intest_a_profiled_review_counts_cached_persona_pages_and_verifier_replies_apart.profile.jsonwithpersona_review1 LLM call and 1 cached call, andverification0 and 1 (same test). Without the client change it reported 1/0 and 0/0.chat_dispatchwithcached0, and observers seecachedFalse:test_a_cache_lookup_that_answers_nothing_is_recorded_once_as_a_dispatch[empty-entry|append-cache].devops ai spend report --jsongives 2 requests, 1 cached request, 1 active backend server, the provider'sserver_count1 andlocal_requests1:test_spend_report_counts_a_cache_hit_as_a_cached_request_and_no_backend. Without the ledger change it reported 2 servers.devops_cli_llm_cache_hits,_missesand_writesare removed:test_response_cache_lookups_and_writes_send_no_metric_of_their_own. The requests counter'scachedlabel carries hits (first criterion).ai-spend.jsonhas the "Response Cache Hit Share" panel:test_the_hit_share_panel_divides_cached_requests_by_all_requests_over_an_hour, plus the existing dashboard checks (sent series,rate/increase, limits text,or vector(0), panel ids and overlaps intests/test_grafana_dashboards.py). "Active AI Backends" keepscached="false".devops_cli_ai_requests_totalcounts only requests sent to a model:test_the_exported_request_counter_counts_only_requests_sent_to_a_model.--durations).changelog.d/816.mdrecords the fix under### Fixedand the gauges under### Removed;CHANGELOG.mdis not edited.uv run devops cipasses.uv run devops ai spend report --json > before.json, thenuv run devops review branchtwice on the same commit, thenuv run devops ai spend report --json > after.json. The second run'sprofile.jsoncached_callsshould equal the cached rows the ledger gained during that run (cached_requestsinafter.jsonminus the value after the first run), be at least its count of "handled by cache" console lines (a file with several cached pages prints one line), anddevops ai spend reportshould list those rows as cached requests.feat(release): v0.2.29 (#1455)