Skip to content

fix(dash): single-flight key includes the route, so /api/stats never answers with another route's body - #574

Merged
amiddavid merged 1 commit into
mainfrom
fix/dash-singleflight-key
Oct 20, 2026
Merged

amiddavid merged 1 commit into
mainfrom
fix/dash-singleflight-key

Conversation

@OsherElhadad

Copy link
Copy Markdown
Collaborator

Hotfix. Concurrent cold reads of two different dashboard routes can answer with the wrong body.

Bug

serveJSON collapses concurrent cold reads onto one computation with a single-flight group keyed by the cache entry key alone. /api/stats, /api/facets, /api/components, /api/tools, /api/toolfilter and /api/spend each key their entry with cacheKey(principal, request), so for one account and the same filters they have the same key. Two of them asked for together while cold ran ONE computation, and one route got the other's report. Seen when the Overview asked for /api/stats and /api/tools at the same moment: /api/stats returned the tools report.

Fix

The flight key names the cache as well as the entry (%p\x00key).

Tests

  • TestConcurrentColdReadsOfDifferentCachesDoNotShareAComputation: two caches, same key, started together; each must run its own compute (deterministic: the second compute must start while the first is held open).
  • TestStatsAndToolsRequestedTogetherEachGetTheirOwnReport: the real routes, asked together.
    Both fail without the key change (checked), the existing cache and single-flight tests pass.

Is it in the deployed build?

Read-only check: the running binary reports commit 3a1b438; git show 3a1b438:dash/api.go has a.jsonInflight.Do(key, ...) at line 266, the same single-key flight. So the deployment has it. The window is narrow (both reads cold and overlapping, then cached for 30 s), which is why it went unseen; the pairs most likely to hit it are /api/stats with /api/facets, which the old pages request together.

…answers with another route's body

The single-flight group was keyed by the entry key alone. /api/stats, /api/facets, /api/components,
/api/tools, /api/toolfilter and /api/spend all key their cache entry with cacheKey(principal, request), so
for one account and the same filters they have the SAME key; two of them cold at the same moment
collapsed onto one computation and one route answered with the other's report. The key now names the
cache as well.

Signed-off-by: Osher-Elhadad <[email protected]>

@OsherElhadad OsherElhadad left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: APPROVE at 9f74b7e (hotfix). (Posted as a comment: GitHub does not let the author account approve.)

  • The bug is real. jsonInflight was keyed by the entry key alone. Every cached route (stats, facets, components, tools, toolfilter, spend) builds its entry key with cacheKey(p, r), so the same account and filters give the same key on each of them. Two concurrent cold reads of different routes collapsed onto one computation, and one route answered with the other's body. That is a wrong-content response, not just a slow one.
  • The fix. The flight key is now %p\x00key (cache pointer plus entry key). Each cache is a distinct long-lived object, so the pointer separates routes without changing anything within a route. Same-route single-flighting is unchanged: TestServeJSONSingleFlightsStaleRefresh still passes.
  • Tests. With the old key restored, both TestConcurrentColdReadsOfDifferentCachesDoNotShareAComputation and TestStatsAndToolsRequestedTogetherEachGetTheirOwnReport fail. Both pass 5/5 under -race.
  • gofmt and go vet are clean, CI is green, and it is signed off with no AI attribution.

This approval covers 9f74b7e.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 9f74b7e3abcd approve

Verdict: approve

Findings

None. The fix is correct and well-tested.

Non-blocking

None.

What I checked

  • Read the full diff: one production change in dash/api.go (line 340) and one new test file dash/jsoncache_flight_test.go
  • Verified the bug: jsonInflight.Do(key, ...) used only the entry key, so two different caches (statsCache, toolsCache) asking for the same entry key collapsed onto one computation
  • Verified the fix: fmt.Sprintf("%p\x00%s", c, key) prefixes the flight key with the cache pointer, making each cache's group distinct. The \x00 separator is safe (cannot appear in a cache key)
  • Checked consistency with other uses of singleflight.Group in the codebase:
    • components/offload/extract_llm.go:666 uses extractInflight with a content-derived key (no cache pointer needed; one global group)
    • proxy/proxy.go:289 uses metricsInflight with a constant key "metrics" (one global group, one cache)
    • This is the only place where multiple caches share one singleflight.Group, so the pointer prefix is the right fix
  • Ran the new tests on the eval box: both pass
  • Ran the full dash package test suite on the eval box: all 268 tests pass, no regressions
  • Verified test coverage:
    • TestConcurrentColdReadsOfDifferentCachesDoNotShareAComputation: unit test proving two caches with the same key each run their own compute
    • TestStatsAndToolsRequestedTogetherEachGetTheirOwnReport: integration test through real routes proving /api/stats and /api/tools each return their own report
  • The fix is minimal, targeted, and preserves all existing behavior for single-cache uses

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (bob, user of @amiddavid) IBM Bob Shell 1.0.3 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 9f74b7e3abcd approve

Verdict: approve

Findings

None. The fix is correct and complete.

Non-blocking

None.

What I checked

  • The bug and its fix. The singleflight group was keyed by cacheKey(principal, request) alone. Multiple routes (/api/stats, /api/facets, /api/components, /api/tools, /api/toolfilter, /api/spend) use the same principal-scoped key for their cache entries. Two routes requested concurrently with the same principal and filters collapsed onto one computation, and one route answered with the other's report. The fix adds the cache pointer to the key: fmt.Sprintf("%p\x00%s", c, key). Each route has its own jsonCache field (statsCache, facetsCache, etc.), so the pointer disambiguates them.

  • The fix is minimal and correct. One line changed in dash/api.go:340. The cache pointer is stable for the lifetime of the API struct, so the key is consistent across requests to the same route. The \x00 separator prevents collisions between cache pointer and entry key.

  • Test coverage. Two new tests in dash/jsoncache_flight_test.go:

    • TestConcurrentColdReadsOfDifferentCachesDoNotShareAComputation: unit test that directly calls serveJSON with two different jsonCache instances and the same entry key. Verifies both computations run and each returns its own result.
    • TestStatsAndToolsRequestedTogetherEachGetTheirOwnReport: integration test through real routes. Requests /api/stats and /api/tools concurrently with the same account and filters. Verifies each response contains its own report by checking for route-specific keys ("tokens_before" for stats, "servers" or "coverage" for tools).
  • Tests pass. Ran both new tests on the eval box. Both pass. Also ran related tests (TestServeJSONSingleFlightsStaleRefresh, TestConcurrentCaptureIsRaceFree, TestConcurrentAnalysesAreBounded). All pass.

  • No other singleflight uses affected. Searched for other singleflight.Group uses in the codebase. Found extractInflight in components/offload/extract_llm.go and metricsInflight in proxy/proxy.go. Both are correctly keyed for their use cases and unaffected by this change.

  • Fail-open preserved. The change is inside serveJSON, which already has error handling. A panic in the key formatting would be caught by the existing recovery. The cache pointer is never nil (it is a field of the API struct), so %p cannot fail.

  • No data loss. The fix changes only the singleflight key, not the cache key. Cache entries remain scoped to principal and query. No existing cache entries are invalidated.

  • Commit follows conventions. DCO sign-off present. Conventional commit title. Author is repo owner. Commit message explains the bug and the fix clearly.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer: review-574-claude (Claude Code subagent)
Kind: AI agent (Claude Code, Sonnet 5.5)
Started by: integrator (session integrator-053), as a comparison with the Bob reviews
Context: fresh
Review: 3rd, comparison (not 1 of 2 or 2 of 2)
Head: 9f74b7e
Verdict: approve

Findings

None that block. The fix is correct. One test gap is listed below as non-blocking.

What I checked, with the result:

  • Every caller of serveJSON passes a distinct *jsonCache. Callers: cachedRoute (routeCache, api.go:404), stats (two calls, statsCache, api.go:1241 and 1250), components, facets, promptCache (promptapi.go:119), spendCache, toolFilterCache, toolsCache. No route is missing.
  • Two routes that share one cache are separated by the entry key. routeCache and promptCache put the path in the entry key (api.go:403, promptapi.go:119). The two statsCache calls (lean and full) have the same cache and the same key. See Non-blocking 1.
  • The flight key cannot collide across caches. %p prints a distinct address for each live cache. The \x00 follows the address, and %p output has no \x00. So (c1,k1) equals (c2,k2) only if c1==c2 and k1==k2.
  • The stale refresh path does not use jsonInflight. refreshJSON (api.go:421) is gated by c.refreshing[key], which is a per-cache map. The bug cannot happen there, and no fix is needed.
  • The cache pointer is stable. The caches are fields of API, and API is used by pointer.

Non-blocking

  1. Test gap: the entry key half of the flight key has no test. If a later change drops key and keeps only %p, no new test fails. Then two tenants asking the same route at once would share one flight, and one tenant would get the other's report. I ran this mutation (see below). The new tests and the other cache tests I selected still pass. A test with one cache, two different keys, and a blocked compute would close the gap. I did not run the whole suite for this mutation, so another test may catch it.
  2. Stale comment. dash/api.go:84-86 says jsonInflight is "Keyed by the same principal-scoped cacheKey as the caches". It now has the cache pointer too. Update the comment.
  3. Test helper. containsKey rewrites strings.Contains. The body read in the second test is one Read call, so it can return a partial body. Use io.ReadAll and strings.Contains.
  4. Weak condition. In the second test, (!isStats || isTools && !isStats) is the same as !isStats. Simplify it.
  5. Old behaviour kept. A cold flight and a stale refresh for the same key can still run at once. This is not new, and no wrong content results.

Tests I ran

All on the eval box (cgssh2), in a fresh copy of the PR head.

  1. go test -race -count=5 -run 'TestConcurrentColdReadsOfDifferentCachesDoNotShareAComputation|TestStatsAndToolsRequestedTogetherEachGetTheirOwnReport' ./dash/: ok, 5.0s.
  2. Fails on main. I reverted only the one-line fix (Do(key, ...)) in a copy. Same command, -count=5: FAIL, 10 of 10 runs. Messages:
    • the second cache's compute never started: it joined the first one's flight
    • /api/tools answered with the stats report: {"since":0,...,"tokens_before":100...
    • /api/stats answered with the wrong report: {"coverage":...
      So both tests fail without the fix, and they do not pass by luck. The second test hit both directions of the swap.
  3. My mutation: flight key is fmt.Sprintf("%p", c) only (entry key dropped). Ran -race -count=1 -run 'TestConcurrent|Test.*Json|Test.*Cache|Test.*Inflight|Test.*Flight|TestStatsAndTools' ./dash/: ok, 62s. No test failed. This is Non-blocking 1.
  4. Full go test -race ./dash/... on the PR head: ok, 411s. I did not run the two known box-only failures, which are in another package.

Compared with the Bob reviews

I read them after my findings.

  • Agree: approve, no blocking issue. The bug is real, the one-line fix is right, and the stale refresh path needs no change.
  • Bob did not run the test on main. Reviewer 2 did not prove the tests fail without the fix. I did: 10 of 10 runs fail.
  • Bob missed the test gap. Both say "Non-blocking: None". Mutation 3 shows the entry-key half of the flight key is untested. Bob also missed the stale comment at api.go:84.
  • One Bob claim I did not verify: "268 tests pass" in the dash package. I only saw ok.

@amiddavid
amiddavid merged commit 7037b35 into main Oct 20, 2026
5 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants