Skip to content

fix(ai): response-cache hits are counted as cached requests #816

Closed

Description

@dan-petty

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)" at src/devops_cli/commands/ai_cost.py:37) is always 0.
  • devops_cli_ai_requests_total (emitted at ledger.py:696). It never carries cached="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:675 through _notify_call_observers (:586-588). ReviewProfiler.observe counts cached_calls only for a call marked cached (src/devops_cli/ai/review/profile.py:216-218), so every profile.json reports cached_calls 0.

Measured in review session 20261002-200610 (s4, a branch review of release/v0.2.25 at cf8ae47, 2026-10-02):

  • profile.json reports llm_calls 141 (persona_review 40, verification 101) and cached_calls 0. The spend ledger has exactly 141 rows in the session window, all with cached 0.
  • 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_info set at unified.py:605; lines formatted at src/devops_cli/ai/review/pipeline.py:393-414 and :2745-2749);
  • the span attribute llm.cached (unified.py:599);
  • the entry's hit_count and last_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, _misses and _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 in INSTRUMENTS, 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() raises hit_count, _hits and the gauge (response_cache.py:213-217, :227-232) before _check_chat_cache validates 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_stream through _record_stream_spend, unified.py:758-918) never reads the cache, so its cached=False (:911) is true. ai/direct.py uses no response cache (:108, :154, :199, :232), so leaving cached unset (:118, :164) is true. Separately, the direct stream functions (direct.py:178-241) record no spend. Nothing in src/ calls them except the unused LLMClient.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_spend would estimate them (unified.py:475-483). It would also record the server cache (unified.py:471, via :69), which COUNT(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-696 is now :739-742. The hit return sits in chat_messages, which chat calls.
  • unified.py:382 is now :425-427, :441-449 is :484-497, and :836-844 is :903-916.
  • direct.py:163 is now :164.
  • ledger.py:660 is now :696, and :92 is :99.
  • instruments.py:70-75 is now :90-95.
  • ai-spend.json:223 is 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 one devops_cli_ai_requests_total{cached="true"} point, adds 0 to devops_cli_ai_tokens_total, and sends no spend point. The ledger gains one row with cached 1, 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.json shows persona_review with llm_calls 1 and cached_calls 1, and verification with llm_calls 0 and cached_calls 1. llm_calls counts 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 spend reports 2 requests, 1 cached request and 1 active backend server.
  • devops_cli_llm_cache_hits, _misses and _writes are removed. devops_cli_ai_requests_total{cached} carries the hit count.
  • k8s/monitoring/dashboards/ai-spend.json gains a response-cache hit-share panel: cached="true" over all requests, each inside increase(...[1h]). The panel query passes tests/test_telemetry_instruments.py. The "Active AI Backends" panel keeps its cached="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.md records the fix under ### Fixed. CHANGELOG.md is not edited.
  • uv run devops ci passes.
  • (person-run) Two branch reviews of the same commit on the homelab gateway: the second run's profile.json cached_calls equals 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), and devops ai spend shows 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 covers chat, 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 cached value 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 cached label 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's cached label 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, so profile.json cached_calls becomes 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, and cache 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_cache at :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_spend at :612.
  • profile.py: the cached branch at :238-240.
  • Persona agent call at agent.py:934; verifier call at verification.py:2743.
  • ai-spend.json: "Request Rate by Model" at :819.

Amended criteria and scope

  • Command name. devops ai spend is the cost app, so criterion 5 is checked with devops ai spend report --json.
  • Provider server count. It gets the same cached = 0 filter as the overall count. The provider reader's or 1 fallback became or 0, so a provider whose rows are all hits shows 0 servers, not 1.
  • Local requests. Hits are left out of local_requests: the cache server is never local. The body did not mention this side effect.
  • Exporter. It subtracts a new per-model ModelSpendSummary.cached_requests rather than redefining request_count, so the devops ai spend tables 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

Still open

Activity

  1. added
    type/bug
    scope/ai
    priority/p2-medium
    on Oct 1, 2026
  2. added
    scope/telemetry
    priority/p1-high
    and removed
    priority/p2-medium
    on Oct 2, 2026
  3. added this to the v0.2.29 milestone on Oct 2, 2026
  4. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    What S10 adds (review session 20261003-034353, release/v0.2.25 at d6ebe97; .data/review-evaluation-20261003-s10.md, section 3, Cache).

    profile.json reports llm_calls 16 and cached_calls 0, yet 370 response-cache entries were replayed in the session window (03:43:53-03:56:33):

    • 353 persona pages (system hash dc091e4c, all created by S9);
    • 17 verifier entries (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.

  5. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Consolidation (2026-10-03): this item is a sub-issue of #817, which now converts every record_metric call site into a declared instrument. This item's scope and v0.2.29 placement are unchanged. The sweep in #817 leaves the devops_cli_llm_cache_* gauges in ai/response_cache.py to this item.

  6. dan-petty-bot commented on Oct 8, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1378, merged into release/v0.2.29 as 3f8df5f.

    Closes #816

    Cache hits were never recorded, so the ledger, devops_cli_ai_requests_total{cached="true"} and every profile.json showed 0 cached calls.

    • Client: LLMClient.chat_messages records each hit once the cached entry passes the client's check: one cached request, 0 tokens, cost 0, server cache, in the caller's stage. Because it sits in the client, chat, the persona agent and the verifier all record through it. A rejected entry and the append-cache lookup still go to the model and are recorded once, as dispatches.
    • Ledger: hits are left out of the overall and per-provider server counts. The provider count no longer turns 0 into 1, hits are not counted as local requests, and each model carries a cached count.
    • Exporter: counts only requests sent to a model, as its help text says.
    • Gauges: the three devops_cli_llm_cache_* gauges are removed. devops_cli_ai_requests_total{cached} carries the hit count.
    • Dashboard: ai-spend.json gains a "Response Cache Hit Share" panel, and the two request panels' descriptions say they include cache answers.

    Each fix's tests fail without it. uv run devops ci passes locally.

    Pending a person after merge: two branch reviews of the same commit on the gateway; the second run's profile shows cached calls.
    Follow-up found while building this: #1375 (the response-cache singleton ignores cache_enabled=False).

    15 file(s) changed.

    How it was verified

    Check runs at 6cbb31f:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Static Analysis: pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • Analyze (actions): pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-816-response-cache-hits-counted-as-cached-requests.md:

    • A second identical chat(use_cache=True) sends one devops_cli_ai_requests_total{cached="true"} point, adds 0 to devops_cli_ai_tokens_total and sends no spend point; the ledger gains a row with cached 1, 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 hosted gpt-4o, so the dispatch's spend point shows the contrast).
    • A persona-agent hit and a verifier hit each record one cached row in the stage a dispatch there records: the ledger's (stage, cached) rows are review.file_review 0 and 1 and review.verification 1 in test_a_profiled_review_counts_cached_persona_pages_and_verifier_replies_apart.
    • A profiled review over a seeded cache with a stub provider, two persona pages with one cached and one cached verifier reply, writes a profile.json with persona_review 1 LLM call and 1 cached call, and verification 0 and 1 (same test). Without the client change it reported 1/0 and 0/0.
    • A cached entry with empty content and an append-cache starting-point lookup are recorded once each, as chat_dispatch with cached 0, and observers see cached False: test_a_cache_lookup_that_answers_nothing_is_recorded_once_as_a_dispatch[empty-entry|append-cache].
    • After one dispatch and one hit, devops ai spend report --json gives 2 requests, 1 cached request, 1 active backend server, the provider's server_count 1 and local_requests 1: 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, _misses and _writes are removed: test_response_cache_lookups_and_writes_send_no_metric_of_their_own. The requests counter's cached label carries hits (first criterion).
    • ai-spend.json has 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 in tests/test_grafana_dashboards.py). "Active AI Backends" keeps cached="false".
    • The exporter's devops_cli_ai_requests_total counts only requests sent to a model: test_the_exported_request_counter_counts_only_requests_sent_to_a_model.
    • The new tests are offline, use the tmp response cache and a tmp ledger, and each call phase is under 0.5 s (--durations).
    • changelog.d/816.md records the fix under ### Fixed and the gauges under ### Removed; CHANGELOG.md is not edited.
    • uv run devops ci passes.
    • Pending a person: on the homelab gateway, run uv run devops ai spend report --json > before.json, then uv run devops review branch twice on the same commit, then uv run devops ai spend report --json > after.json. The second run's profile.json cached_calls should equal the cached rows the ledger gained during that run (cached_requests in after.json minus 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), and devops ai spend report should list those rows as cached requests.
  7. added a commit that references this issue on Oct 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/aiscope/telemetrytype/bug

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions