Skip to content

fix(query-orchestrator): key refresh key cache entries consistently - #11607

Merged
ovr merged 5 commits into
masterfrom
fix-haskeyqueryresult-tuple-hash
Aug 28, 2026
Merged

ovr merged 5 commits into
masterfrom
fix-haskeyqueryresult-tuple-hash

Conversation

@ovr

@ovr ovr commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Check List

  • Tests have been run in packages where changes have been made if available
  • Linter has been run for changed code
  • Tests for the changes have been added if not covered yet
  • Docs have been added / updated if required

Description of Changes Made

Refresh key queries were stored under one cache key and looked up under another. Three things
followed from that: the per-request memo in PreAggregationLoadCache could never hit, so every
waitForRenew: false request took the deferred path; the refresh scheduler and the pre-aggregation
loader marked each other's entry stale whenever a cube refreshKey and a pre-aggregation
invalidateKeyQuery resolved to the same SQL; and the same SQL run against different engines or
different data sources shared a single entry and served each other's rows.

This PR gives a refresh key one identity — [sql, params, external, dataSource] — computed in one
place (QueryCache.refreshKeyIdentity) and applied by one helper (cacheRefreshKeyResult) that
owns the cache key, the renewal key and the renewal threshold, so a caller can no longer store an
entry under a key it will later look up by a different one.


How it broke, and how it is fixed

One entity, three different hashes

                       ONE refresh key query
   [ "SELECT FLOOR(EXTRACT(EPOCH FROM NOW())/86400) refresh_key",  [],
     { renewalThreshold: 86400, external: false, incremental: false } ]     dataSource: "default"
        └──── sql ────┘                          └──── options ────┘

  BEFORE                                              AFTER
  ─────────────────────────────────────────────       ────────────────────────────────────
  H2 = md5([sql, params])           <- cacheKey       H = md5([sql, params,
  H2                    <- renewalKey (loader)                  !!external,
  H3 = md5([sql, params, options])                              dataSource || 'default'])
                        <- renewalKey (scheduler)         ^
  H3                    <- memo lookup                    |  refreshKeyIdentity()
                                                          |  one hash everywhere
  H2 != H3  =>  the bugs below                            +-- cacheKey = renewalKey = memo key

Bug 1 — the load cache memo could never hit

PreAggregationLoadCache lives for one request and memoizes resolved refresh key values so that
several partitions or pre-aggregations do not each re-run the same SQL.

   PreAggregationLoadCache.queryResults  (in memory, one per request)
   +--------------------------------------------------------------+
   |  { "H2": Promise<[{refresh_key: 20685}]> }                    |
   +--------------------------------------------------------------+
        ^ WRITE                                    READ ^
        | keyQueryResult()                              | hasKeyQueryResult()
        | queryCacheKey([query, values])                | queryCacheKey(keyQuery)
        |            = H2                               |      = H3  <- the whole 3-tuple
        |                                               |
   -----+-----------------------------------------------+-----
                          H2 != H3  ->  miss, 100% of the time, for four years
                     (regression from #3061: `options` moved into the tuple,
                      only the store side was updated)

Both sides now go through refreshKeyCacheKey() -> refreshKeyIdentity(), so they agree on H.

Bug 1, consequence — a dead branch in loadPreAggregation

BEFORE                                     AFTER
────────────────────────────────────       ──────────────────────────────────────
notLoadedKey = keys.find(k => !warm(k))    allWarm = keys.every(k => warm(k))
       warm() === false  ----+                    warm() actually works
       => always truthy      |
                             v
if (isJob || !(notLoadedKey && !waitForRenew))   if (isJob || (!externalRefresh &&
                                                      (waitForRenew || allWarm)))
     collapses to:
     isJob || waitForRenew        <- "keys are warm" never contributed

On a live request against a partitioned rollup:

POST /v1/load  (default cache mode => waitForRenew = false)
   |
   +- PartitionRangeLoader.loadRangeQuery()
   |     +- getInvalidationKeyValues() --> keyQueryResult(q) --> queryResults{ H: 20685 }
   |                                                              ^ memo warmed here
   +- partition 2025-06 -+
   +- partition 2025-07 -+--> loadPreAggregation()
   +- partition 2025-08 -+        |
                                  +-- BEFORE: hasKeyQueryResult -> H3 -> miss
                                  |        => Case 3: serve what exists, refresh in background
                                  |        => refreshKeyValues: []
                                  |
                                  +-- AFTER:  hasKeyQueryResult -> H  -> hit
                                           => Case 1: confirm freshness inline
                                           => refreshKeyValues: [{refresh_key: 20685}]

Re-enabling that branch needed a guard, which also closes a hole that exists on master today:

externalRefresh:
  BEFORE     warm-key path unreachable (always a miss)          => Case 3            [ok]
             but invalidateKeyQueries: [] left notLoadedKey undefined,
             so !(undefined && ...) was true                    => Case 1, BUILDS    [bug]
  naive fix  warm keys now route those requests into            => Case 1, BUILDS    [bug]
  THIS PR    !externalRefresh guard: both cases report the partition as missing      [ok]

Bug 2 — renewal key ping-pong between the scheduler and the loader

When a cube level refreshKey and a pre-aggregation invalidateKeyQuery resolve to the same SQL,
both paths write the same cache entry with a different renewalKey, and decideCacheAction
treats entry.renewalKey !== renewalKey as a reason to re-fetch.

 t0  refresh scheduler - loadRefreshKey(q) ------> entry{ value: 20685, renewalKey: H3 }
                                                                                  |
 t1  /v1/load - keyQueryResult(q) -> reads entry                                  |
        expects H2, finds H3 --> isKeyMismatch --> SQL --> entry{ 20685, H2 } -----+
                                                                                  |
 t2  refresh scheduler - loadRefreshKey(q) -> reads entry                         |
        expects H3, finds H2 --> isKeyMismatch --> SQL --> entry{ 20685, H3 } -----+
                                                     ^
 t3  ... on every touch, while the value never changed

 AFTER:  both paths -> cacheRefreshKeyResult() -> renewalKey = cacheKey = H
         +----------------------------------------------------------+
         |  entry{ value: 20685, renewalKey: H }   <- both read, hit |
         +----------------------------------------------------------+

The same mismatch also disqualifies the in-memory entry (isMemoryEntryUsable requires equality
too), so the miss was doubled.

Bug 3 — entries collided across engines and across data sources

cacheQueryResult routes a refresh key query on two dimensions — external picks the engine,
dataSource picks the queue and the driver — and the cache prefix separates tenants, not data
sources. Neither dimension was in the key.

 BEFORE:  identity = [sql, params]
          "SELECT MAX(updated_at) FROM orders"
             +-- prod    / source DB  --+
             +-- staging / source DB  --+--> md5([sql, params]) = H2 --> ONE entry
             +-- prod    / Cube Store --+     whoever ran first served everyone

 AFTER:   identity = [sql, params, !!external, dataSource || 'default']
             prod    / source DB  --> Hp  -+
             staging / source DB  --> Hs  -+-> three distinct entries
             prod    / Cube Store --> Hx  -+

          both defaults normalized:  external: undefined | false          -> false
                                     dataSource: undefined | 'default'    -> 'default'
          (JSON.stringify renders undefined as null, so the spellings had to collapse;
           `getQueue` already resolves an absent dataSource to `default`)

Not a bug, just deduplicated

invalidateKeyQueries[0].slice(0, 2) was spelled out twice — on the write side (loadRangeQuery)
and on the read side (checkPartitionsBuildRangeCache), each with a comment telling the reader to
keep it identical to the other. There is now one definition.

 loadRangeQuery()      -+                          -+
                        +- buildRangeInvalidateKey -+  one call, nothing left to drift
 checkPartitionsBuild… -+                          -+

Also in this series: QueryCache.queryRedisKey is renamed to queryCacheKey — the cache driver has
not been Redis-specific since the driver abstraction landed. Mechanical, byte-identical output, no
entry moves. LocalQueueDriverConnection.queryRedisKey keeps its name: it builds queue keys, not
cache keys.


Verification

Confirmed end to end against a live Cube instance over Postgres with a partitioned rollup
(orders_by_status, three monthly partitions, refresh key every: 1 day):

build cache mode rows usedPreAggregations[].refreshKeyValues
master default 4 [[],[],[]]
master must-revalidate 4 [[{refresh_key:20685}]] x3
this PR default 4 [[{refresh_key:20685}]] x3

Eight new tests in PreAggregations.test.ts, each verified load-bearing against the branch with its
own fix reverted — including the two externalRefresh guard tests, which fail if the cache key is
fixed without the guard.

Notes for the reviewer: this is rebased on #11608, which removed the now-dead Array.isArray
normalization in the same functions but left hasKeyQueryResult untyped and still hashing the whole
tuple, so the two changes are complementary rather than overlapping. Tests live in
PreAggregations.test.ts because QueryOrchestrator.test.js is not matched by
testMatch: ['<rootDir>/test/**/*.test.ts'] and never runs; its call sites are updated anyway, and
run manually against the compiled copy its failure set is 5, a subset of master's 7. Separately,
while testing I found a pre-existing bug worth its own issue: on a cold refresh key cache,
usedPreAggregations[*].refreshKeyValues serializes raw native ResultWrapper internals
(isWrapper, cache, rootResultObject) instead of plain rows — it reproduces on master via
cache: must-revalidate, and this PR widens the exposure to the default path without introducing it.

Upgrade note: the refresh key cache keys and the partition build range cache keys move, so both
are cold once on the first start after the upgrade — refresh keys and build ranges are re-resolved,
pre-aggregation data itself is not rebuilt. Bounded by @AsyncDebounce and the in-memory cache;
old entries age out on their own (1h / 24h TTLs).

@ovr
ovr requested a review from a team as a code owner August 20, 2026 17:34
@github-actions github-actions Bot added the javascript Pull requests that update Javascript code label Aug 20, 2026
@claude

claude Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 57s —— View job


Review complete — solid fix; 2 medium notes, 2 low, posted inline

Full review
  • Read PR diff (git diff origin/master...HEAD)
  • Review PreAggregationLoadCache key derivation
  • Review PreAggregationLoader branch change
  • Review QueryCache.loadRefreshKey renewalKey change
  • Review tests
  • Post review

Verdict

The diagnosis holds up. keyQueryResult stores under queryRedisKey([query, values]) while hasKeyQueryResult hashed the whole tuple, so since the third options element appeared the lookup could never hit — the notLoadedKey/Case 2 branch has been unreachable for waitForRenew: false. Routing both through one private helper is the right shape, the "exclude options because renewalThreshold is clock-derived" rationale is correct and well documented in the code, and the find → every swap incidentally fixes a falsy-key edge (a falsy keyQuery used to read as "loaded"). The QueryCache.loadRefreshKey renewalKey asymmetry is a genuine twin bug — writing a renewal key that can never match what the other producer writes for the same redisKey means guaranteed mutual invalidation whenever a cube cacheKeyQuery and a pre-agg invalidateKeyQuery share SQL.

Two things deserve a mention in the description before merge; neither is a blocker.

Findings

# Severity Where Issue
1 Medium QueryCache.ts:878 renewalKey shape change invalidates every persisted refresh-key entry once on upgrade, and old/new instances thrash each other's entries through a shared Redis for the length of a rolling deploy. Operational note, not a code defect.
2 Medium PreAggregationLoader.ts:136-141 The !externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes Case 2 and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. Probably the intended semantics, but it's a user-visible error-surface change that the description doesn't mention, and no test pins it.
3 Low PreAggregationLoader.ts:136 The warm check reads invalidateKeyQueries while loadPreAggregationWithKeys() resolves partitionInvalidateKeyQueries when set (ksqlDB) — so a warm check can send a waitForRenew: false request into Case 2 where the keys that actually gate the blocking work are cold. Acknowledged by the TODO; suggested a one-line gate on the set that will actually be resolved.
4 Low PreAggregationLoader.ts:147-150 The warm path now returns real refreshKeyValues where Case 3 returned []. These surface in usedPreAggregations response metadata (QueryOrchestrator.ts:233) — behavior improvement, but it does change what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

Nit (not worth a thread): keyQueryResult and queryResultCacheKey both run the Array.isArray(sqlQuery) ? … : [sqlQuery, [], {}] normalization. Having the helper take the already-normalized [query, values], or return the normalized triple alongside the key, would remove the duplication — though the current shape does keep hasKeyQueryResult a clean one-liner, so this is taste.

Tests

Good coverage, and the "verified load-bearing" claim checks out by inspection:

  • hasKeyQueryResult ignores the options element fails on master (lookup never hits).
  • both refresh key paths store the same renewal key — the LocalCacheDriver.reset() between the two writes is the load-bearing detail; without it the second path would just read the first's entry and the disagreement would stay invisible. Nice.
  • warm invalidation keys are confirmed synchronously — on master Case 3 with no structure version returns loadPreAggregationWithKeys() directly, whose refreshKeyValues is [], so length === 1 does discriminate.
  • externalRefresh guard test asserts both the throw and mockDriver.tables === [], which is the assertion that actually catches an unwanted build.

Missing scenario worth adding: invalidateKeyQueries: [] + externalRefresh (finding #2) — that's the case where the guard changes behavior that exists today rather than behavior that's been dead since #3061.

The note about QueryOrchestrator.test.js not being matched by testMatch: ['<rootDir>/test/**/*.test.ts'] is a real trap and a good catch — that file is silently dead. Might be worth a follow-up issue to either rename it or widen testMatch, rather than leaving four pre-existing failures parked in a file nobody runs.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is the whole point of the change and is net positive; the two costs are #1 (transient, upgrade-scoped) and #3 (ksqlDB-only).

Caveat: I could not execute the test suite — npx jest was blocked by this environment's command permissions. All analysis above is by inspection of the diff and surrounding code; CI results should be treated as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

@codecov

codecov Bot commented Aug 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.81818% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.77%. Comparing base (8b3d6fb) to head (0f53b8a).

Files with missing lines Patch % Lines
...-query-orchestrator/src/orchestrator/QueryCache.ts 84.61% 2 Missing ⚠️
...hestrator/src/orchestrator/PreAggregationLoader.ts 66.66% 0 Missing and 1 partial ⚠️
...orchestrator/PreAggregationPartitionRangeLoader.ts 0.00% 1 Missing ⚠️

❗ There is a different number of reports uploaded between BASE (8b3d6fb) and HEAD (0f53b8a). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (8b3d6fb) HEAD (0f53b8a)
cubesql 1 0
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #11607       +/-   ##
===========================================
- Coverage   84.52%   58.77%   -25.75%     
===========================================
  Files         261      237       -24     
  Lines       85440    18932    -66508     
  Branches        0     3841     +3841     
===========================================
- Hits        72217    11128    -61089     
+ Misses      13223     7243     -5980     
- Partials        0      561      +561     
Flag Coverage Δ
cube-backend 58.77% <81.81%> (?)
cubesql ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ovr
ovr force-pushed the fix-haskeyqueryresult-tuple-hash branch from 38c23dd to 5e3f19c Compare August 20, 2026 20:18
@claude

claude Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 28s —— View job


Re-review after synchronize — rebase only, no code changes; both prior threads still stand (2 medium, 2 low)

Full review
  • Read current diff vs origin/master
  • Compare against previously reviewed revision
  • Check existing review threads (resolve stale / dedupe)
  • Post review

What changed in this push

Nothing in the code. The push was a rebase onto the new origin/master (c290698, refactor(query-orchestrator): normalize pre-aggregation SQL to tuples #11608). All four blobs are byte-identical to the revision I reviewed at 38c23dd:

File SHA (then / now)
PreAggregationLoadCache.ts bc26430 / bc26430
PreAggregationLoader.ts 36719a1 / 36719a1
QueryCache.ts 3172b43 / 3172b43
test/unit/PreAggregations.test.ts 975c3be / 975c3be

I re-checked the interaction with the new base, since #11608 touches the same package and normalizes pre-agg SQL to tuples. It's compatible: queryRedisKey(cacheKey: CacheKey) is unchanged (QueryCache.ts:1079), QueryWithParams is still the 3-element tuple (QueryCache.ts:55), and PreAggregationLoadCache.ts:202 is the only remaining caller outside QueryCache. If anything the tuple normalization strengthens the premise of this PR — the hasKeyQueryResult(keyQuery: QueryWithParams) type annotation is now accurate for every producer rather than aspirational.

Standing findings — re-affirmed, not re-posted

Both inline threads from the previous review are still unresolved and still apply verbatim to the current lines; per the dedup rule I did not post copies.

# Severity Where Issue
1 Medium QueryCache.ts:876 renewalKey shape change invalidates every persisted refresh-key entry once on upgrade, and old/new instances thrash each other's entries through a shared Redis for the length of a rolling deploy. Operational note for the release notes, not a code defect.
2 Medium PreAggregationLoader.ts:141 The !externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes Case 2 and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. Probably intended, but it's a user-visible error-surface change the description doesn't mention, and no test pins it.
3 Low PreAggregationLoader.ts:136 Warm check reads invalidateKeyQueries while loadPreAggregationWithKeys() resolves partitionInvalidateKeyQueries when set (ksqlDB) — a waitForRenew: false request can enter Case 2 with the keys that actually gate the blocking work still cold. Acknowledged by the in-code TODO; a suggested one-line gate is in the thread.
4 Low PreAggregationLoader.ts:147-150 The warm path returns real refreshKeyValues where Case 3 returned []; these surface in usedPreAggregations response metadata (QueryOrchestrator.ts:233). Behavior improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

The core verdict is unchanged: the diagnosis is right (keyQueryResult stored under [query, values] while hasKeyQueryResult hashed the whole tuple, so the memo branch has been unreachable since the third element appeared), routing both through one private helper is the right shape, the "exclude options because renewalThreshold is clock-derived" rationale is correct and documented in the code, the find → every swap incidentally fixes a falsy-keyQuery edge, and the loadRefreshKey renewalKey asymmetry is a genuine twin bug.

Still the only substantive ask before merge: a test pinning invalidateKeyQueries: [] + externalRefresh (finding #2) — that's the case where the guard changes behavior that exists today, rather than behavior dead since #3061 — plus a release-note line for #1.

Security / performance

Unchanged from the previous pass. No security surface touched. Performance is net positive; the costs are #1 (transient, upgrade-scoped) and #3 (ksqlDB-only).

Caveat: I again could not execute the suite — both npx jest and yarn jest were rejected by this environment's command permissions. Everything above is by inspection; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

@claude

claude Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 27s —— View job


Re-review after synchronize — code simplified onto the new base; verdict unchanged, both prior threads still stand (2 medium, 2 low)

Full review
  • Read current diff vs origin/master
  • Diff against the previously reviewed revision
  • Re-check both standing findings against current lines
  • Check existing review threads (resolve stale / dedupe)
  • Post review

What changed in this push

Unlike the last synchronize (pure rebase), this one does carry code edits — but they are simplifications enabled by the new base (#11608 normalized pre-agg SQL to tuples), not new behavior:

File Change since last reviewed revision
PreAggregationLoadCache.ts The private key-derivation helper is gone; hasKeyQueryResult now destructures [query, values] inline, mirroring keyQueryResult (PreAggregationLoadCache.ts:194) which already destructures on master. Net effect identical, and it removes the duplicate Array.isArray(...) normalization I nitpicked last time — good.
PreAggregationLoader.ts Condition is byte-identical (PreAggregationLoader.ts:139). The TODO about partitionInvalidateKeyQueries was removed; the externalRefresh comment stays.
QueryCache.ts Unchanged (renewalKey: [query, values] at QueryCache.ts:876).
test/unit/PreAggregations.test.ts Same four tests.

The core verdict is unchanged and still holds: keyQueryResult stores under queryRedisKey([query, values]) while hasKeyQueryResult hashed the whole tuple, so the memo branch has been unreachable since the third element appeared; routing both through the same 2-element derivation is right; excluding options because renewalThreshold is clock-derived is correct and documented in the code; find → every incidentally fixes a falsy-keyQuery edge; and the loadRefreshKey renewalKey asymmetry is a genuine twin bug — loadRefreshKey writes to redisKey([query, values]) (QueryCache.ts:867) while stamping a 3-tuple renewal key, so it could never match what the other producer writes for the same entry.

Standing findings — re-affirmed, not re-posted

Both inline threads are still unresolved and still land on the exact current lines, so per the dedup rule I did not post copies.

# Severity Where Issue
1 Medium QueryCache.ts:876 renewalKey shape change invalidates every persisted refresh-key entry once on upgrade, and old/new instances thrash each other's entries through a shared Redis for the length of a rolling deploy. Operational note for the release notes, not a code defect.
2 Medium PreAggregationLoader.ts:139 The !externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes Case 2 and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. Almost certainly intended, but it is a user-visible error-surface change the description doesn't mention, and no test pins it.
3 Low PreAggregationLoader.ts:139 Warm check reads invalidateKeyQueries, while the blocking work in loadPreAggregationWithKeys() resolves partitionInvalidateKeyQueries when set (getPartitionInvalidationKeyValues, PreAggregationLoader.ts:402) — so a waitForRenew: false request can enter Case 2 with the keys that actually gate the blocking work still cold. This push removed the TODO that acknowledged it, so the gap is now undocumented as well as unaddressed. A one-line gate on the set that will actually be resolved is in the existing thread.
4 Low PreAggregationLoader.ts:143-150 The warm path returns real refreshKeyValues where Case 3 returned []; these surface in usedPreAggregations response metadata. Behavior improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

Nothing to resolve — neither thread is stale.

Asks before merge (unchanged)

  1. A test pinning invalidateKeyQueries: [] + externalRefresh — finding MUTEX for requests #2 is the one case where the guard changes behavior that exists today, rather than behavior dead since feat: Execute refreshKeys in externalDb (only for every) v2 #3061. Fix this →
  2. A release-note line for ReferenceError: self is not defined - Issue with whatwg-fetch when using the core lib with Node.js #1 (one-time refresh-key refetch storm on upgrade for shared-cache deployments).
  3. Optional: restore the partitionInvalidateKeyQueries TODO if you don't want to take the gate change in this PR — it was the only in-code record of ResultSet pivot methods documentation  #3.

Tests

Still good, still load-bearing by inspection. both refresh key paths store the same renewal key remains the sharpest one — the LocalCacheDriver.reset() between the two writes is what makes the disagreement observable rather than masked by the first path's entry.

Reminder from the last pass, still true: QueryOrchestrator.test.js is not matched by testMatch: ['<rootDir>/test/**/*.test.ts'] and never runs. Worth a follow-up issue rather than leaving four pre-existing failures parked in a file nobody executes.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is the point of the change and is net positive; the costs are #1 (transient, upgrade-scoped) and #3 (ksqlDB-only).

Caveat: I could not execute the suite in this environment (jest invocations are blocked by command permissions). Everything above is by inspection of the diff and surrounding code; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

@claude

claude Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 42s —— View job


Re-review after synchronize — new refreshKeyIdentity fixes a real source/external key collision; verdict positive. 1 new medium (posted inline), 1 medium + 2 low re-affirmed, 1 stale thread resolved

Full review
  • Read current diff (git diff HEAD~1 — origin/master is c290698, the PR's parent)
  • Review new QueryCache.refreshKeyIdentity and all four call sites
  • Check cache/queue key shape impact of the added boolean element
  • Re-check standing findings against current lines
  • Dedupe against prior threads / resolve stale ones
  • Post review

What changed in this push

This is a real revision, not a rebase. The ad-hoc [query, values] derivation is replaced by a single QueryCache.refreshKeyIdentity() (QueryCache.ts:406) returning [query, values, !!options?.external], and every producer and consumer of a refresh-key cache key now routes through it:

Site Before After
PreAggregationLoadCache.keyQueryResult queryRedisKey([query, values]) (x3, inline) one memoKey from refreshKeyIdentity
PreAggregationLoadCache.hasKeyQueryResult hashed the whole tuple → never hit same identity as the store side
QueryCache.loadRefreshKey cacheKey: [query, values], renewalKey: q both identity
PreAggregationPartitionRangeLoader.loadRangeQuery / PreAggregations.checkPartitionsBuildRangeCache invalidateKeyQueries[0].slice(0, 2) on both sides refreshKeyIdentity on both sides

Two things this buys beyond the original fix, both worth calling out as good:

  1. Adding external to the identity is an independent correctness fix. cacheQueryResult routes on external: queryOptions?.external, but the old key was engine-blind — the same refresh-key SQL resolved against the source DB and against Cube Store shared one cache entry, so one engine's value could be served for the other. The !! normalization is the right detail too: producers spell "source" as both false and absent, and JSON.stringify would otherwise hash those to false vs null. a refresh key resolved against each engine gets its own cache entry pins exactly this.
  2. The .slice(0, 2) duplication is gone. Those two sites had to agree by convention and nothing enforced it; the paired "must stay identical to the other side" comments plus a shared function is a strict improvement.

The original diagnosis still holds and the fix is still right: keyQueryResult stored under a 2-element key while hasKeyQueryResult hashed the full tuple, so the memo branch has been unreachable since the third element appeared in #3061; excluding the policy element because replacePartitionSqlAndParams recomputes renewalThreshold from new Date() is correct and now documented on the function itself; and find → every incidentally fixes a falsy-keyQuery edge.

New finding (posted inline)

# Severity Where Issue
5 Medium QueryCache.ts:406 dataSource is the other routing dimension cacheQueryResult dispatches on, and it is in neither the identity nor the getKey() prefix — identical refresh-key SQL across two data sources collides in the persisted cache (the per-instance queryResults memo hides it in-process). Pre-existing, not introduced here, but the new doc comment reads as if the routing dimensions are covered. Document the omission or thread dataSource through. The same thread carries the updated upgrade-churn note.

Standing findings — re-affirmed, not re-posted

The PreAggregationLoader.ts:139 thread is still unresolved and still lands on the current line, so per the dedup rule I did not post a copy.

# Severity Where Issue
2 Medium PreAggregationLoader.ts:139 The && !this.externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes Case 2 and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. Almost certainly intended, but it is a user-visible error-surface change the description doesn't mention, and still no test pins it. The new externalRefresh test covers the warm-keys case, not the empty-keys case.
3 Low PreAggregationLoader.ts:135 Warm check reads invalidateKeyQueries, while getPartitionInvalidationKeyValues (PreAggregationLoader.ts:402) resolves partitionInvalidateKeyQueries when set (ksqlDB) — a waitForRenew: false request can enter Case 2 with the keys that actually gate the blocking work still cold. The TODO that used to record this is still gone, so the gap remains undocumented; suggested one-line gate is in the existing thread.
4 Low PreAggregationLoader.ts:143-150 The warm path returns real refreshKeyValues where Case 3 returned []; these surface in usedPreAggregations response metadata. Improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

Resolved

PRRT_kwDOCOH19M6a5wrL (the earlier renewalKey rolling-deploy note) — resolved as stale. Its point 2 described old and new instances writing different renewalKeys for the same redisKey; now the redisKey moves too, so the versions write disjoint entries and there's no mutual invalidation. The surviving (and slightly widened) one-time-cold-cache point is folded into the new inline thread.

Tests

The four new tests plus the two QueryOrchestrator.test.js updates track the change well.

  • refresh key identity covers sql, params and engine, but not policy is the sharpest addition — it asserts the positive (differing options still hit), the normalization (external absent ≡ external: false), and the negative (external: true is a different key) in one place. That's the whole contract of the new function.
  • a refresh key resolved against each engine gets its own cache entry asserts through the drivers (executedQueries on each) rather than through the key, which is the right level — it would still catch a regression if the key derivation were rewritten.
  • both refresh key paths store the same renewal key — the LocalCacheDriver.reset() between the two writes is still the load-bearing detail; without it the second path would just read the first's entry and any disagreement would stay invisible.
  • warm invalidation keys are confirmed synchronously discriminates on refreshKeyValues.length === 1 (Case 3 returns []), which does distinguish the branches.

Gap, unchanged from the last pass: invalidateKeyQueries: [] + externalRefresh (finding #2). Fix this →

Also still true: QueryOrchestrator.test.js is not matched by testMatch: ['<rootDir>/test/**/*.test.ts'], so the two updates to it in this diff are correct but unexecuted. Worth a follow-up issue to widen testMatch or rename the file.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is net positive and is the point of the change; the costs are the one-time cold cache on upgrade (new inline thread) and finding #3 (ksqlDB-only).

Caveat: I could not run anything this time — node_modules is absent in this checkout and git fetch / package installs are blocked by command permissions, so I could not run jest or tsc. Everything above is by inspection of the diff and the surrounding source; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

@ovr
ovr force-pushed the fix-haskeyqueryresult-tuple-hash branch from 5843f0b to 0d864c4 Compare August 28, 2026 11:06
@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 3s —— View job


Re-review after synchronize — the fix is now enforced by construction (cacheRefreshKeyResult); verdict positive, no new findings. 1 medium + 2 low re-affirmed, 0 new, 0 stale threads to resolve

Full review
  • Read current diff vs origin/master
  • Diff against the previously reviewed revision
  • Trace the new cacheRefreshKeyResult / refreshKeyRedisKey against every prior call site for behavior drift
  • Check the widened CacheKeyItem for key-space collisions with other cacheQueryResult producers
  • Re-check standing findings against current lines
  • Dedupe against prior threads / resolve stale ones
  • Post review

What changed in this push

This revision goes one step further than the last one and it's the right step. Previously refreshKeyIdentity centralized the key but each caller still assembled the policy (renewalThreshold, renewalKey, useInMemory, external) by hand — two copies that had to agree. Now there is a single QueryCache.cacheRefreshKeyResult(sqlQuery, expiration, options) (QueryCache.ts:444) that derives all of it from the tuple, plus refreshKeyRedisKey() (QueryCache.ts:464) for the lookup side:

Site Before this push Now
PreAggregationLoadCache.keyQueryResult own renewalThreshold / renewalKey / useInMemory / external block, queryRedisKey(...) x3 cacheRefreshKeyResult(sqlQuery, ...), one memoKey
PreAggregationLoadCache.hasKeyQueryResult queryRedisKey(refreshKeyIdentity(...)) refreshKeyRedisKey(...) — same derivation as the store side, by construction
QueryCache.loadRefreshKey own policy block cacheRefreshKeyResult, 3 call-site options left

The RefreshKeyCacheOptions = Pick<CacheQueryResultOptions, 'priority' | 'requestId' | 'waitForRenew' | 'dataSource'> type is the part I like most — it makes the invariant a type rather than a comment. A caller can no longer pass its own renewalKey, so the class of bug this PR fixes (store under one key, look up by another) is now unrepresentable rather than merely fixed. The doc comment on it says exactly that. This also dissolves the duplication nit I raised two passes ago.

I checked each derived value against what master computed, per path, and they match: renewalThreshold = options.refreshKeyRenewalThreshold || queryOptions?.renewalThreshold || 2 * 60 (identical in both old blocks), useInMemory: true (both), external: queryOptions?.external (both), waitForRenew still per-caller (!options.skipRefreshKeyWaitForRenew vs the passed flag), priority still only from keyQueryResult. The only intended deltas are the ones the PR is about: the key/renewal key shape. Types line up too — dataSource is non-optional in CacheQueryResultOptions and both callers supply it (LoadRefreshKeyOptions.dataSource, PreAggregationLoadCacheOptions.dataSource).

The original diagnosis and the external addition still hold and are still right: the memo branch has been unreachable since the third tuple element appeared in #3061, and the old engine-blind key conflated a refresh key resolved against the source DB with the same SQL resolved against Cube Store.

Collision check on the widened key space — clean

CacheKeyItem gained boolean and refresh-key entries went from 2 to 3 elements, so I checked whether [query, values, false] can now collide with another producer's 3-element cacheKey under getCacheHash/JSON.stringify (utils.ts:15, queryRedisKey at QueryCache.ts:1207). The near miss is PreAggregationPartitionRangeLoader.loadRangeQuery, whose invalidate is false when a pre-agg has no invalidateKeyQueries — a build-range query and a cube cacheKeyQuery can easily be the same SELECT MAX(created_at) FROM orders. It does not collide: that site goes through QueryCache.queryCacheKey (QueryCache.ts:416), which always emits [query, values, preAggLoadSqls] and only appends invalidate when truthy — so a falsy invalidate yields [query, values, []], which stringifies distinctly from [query, values, false]. Worth recording that this is load-bearing: if queryCacheKey were ever changed to push a falsy invalidate, the two key spaces would overlap.

Also checked renewQuery's queryRedisKey([query, values]) (QueryCache.ts:890) — that's the main query's identity inside its own renewalKey, not a refresh key, so it correctly stays out of this migration.

One observation on the shape (not a defect)

For refresh-key entries renewalKey is now literally cacheKey, so renewalKey === redisKey after hashing (QueryCache.ts:1020-1021) and isKeyMismatch (QueryCache.ts:958) is structurally always false. That is correct — a refresh key is a leaf and has nothing to invalidate against — and the truthy renewalKey is still required, because decideCacheAction returns ServeCached unconditionally when renewalKey is falsy (QueryCache.ts:975), which would stop refresh keys from ever renewing. Fine as is; just noting that the invariant now rests on cacheRefreshKeyResult continuing to pass something truthy.

Side effect on one test: both refresh key paths store the same renewal key no longer discriminates the way it did, since there is now literally one code path writing the entry — it can't observe a disagreement that can no longer exist. It's still worth keeping as a guard against the two paths diverging again, but the real protection is now RefreshKeyCacheOptions.

Standing findings — re-affirmed, not re-posted

Both unresolved threads still land on the exact current lines, so per the dedup rule I did not post copies. Nothing became stale in this push, so nothing to resolve.

# Severity Where Issue
2 Medium PreAggregationLoader.ts:140 The && !this.externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes Case 2 and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. Almost certainly intended, but it's a user-visible error-surface change the description doesn't mention, and still no test pins it — the new externalRefresh test covers the warm-keys case, not the empty-keys case.
5 Medium QueryCache.ts:436 dataSource is the other dimension cacheQueryResult routes on, and it's in neither the identity nor the getKey() prefix, so identical refresh-key SQL across two data sources shares one persisted entry (the per-instance queryResults memo hides it in-process). Pre-existing, but the new doc comment reads as if the routing dimensions are covered. Same thread carries the upgrade-churn note.
3 Low PreAggregationLoader.ts:135 Warm check reads invalidateKeyQueries, while getPartitionInvalidationKeyValues resolves partitionInvalidateKeyQueries when set (ksqlDB) — a waitForRenew: false request can enter Case 2 with the keys that actually gate the blocking work still cold. The TODO that recorded this is still gone.
4 Low PreAggregationLoader.ts:143-150 The warm path returns real refreshKeyValues where Case 3 returned []; these surface in usedPreAggregations response metadata. Improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

PRRT_kwDOCOH19M6a5wrL (the old rolling-deploy renewalKey note) remains resolved — correctly, since the redisKey itself moves now, so versions write disjoint entries instead of fighting over one.

Asks before merge (unchanged from last pass)

  1. A test pinning invalidateKeyQueries: [] + externalRefresh — finding MUTEX for requests #2 is the one case where the guard changes behavior that exists today. Fix this →
  2. A release-note line for the one-time cold refresh-key + build-range cache on upgrade (finding Add support for AWS Athena in JDBC driver #5, part 2).
  3. Either fold dataSource into refreshKeyIdentity or say in the doc comment why it's omitted, plus a follow-up issue.

Tests

The four new tests are unchanged from the last revision and still track the behavior well. refresh key identity covers sql, params and engine, but not policy remains the sharpest — positive, normalization (external absent ≡ false), and negative in one place. a refresh key resolved against each engine gets its own cache entry asserting through executedQueries on each driver rather than through the key is the right level.

The externalDriverFactory: mockExternalDriverFactory addition is correctly placed on the shared queryCache (not preAggregations), which is what the external: true refresh key actually routes through. Minor note: mockExternalDriverFactory has a createTable side effect on every invocation, so mockExternalDriver.tables is now non-empty in tests that touch the external queue — harmless for the assertions here, but a trap for anyone later asserting on external tables the way the externalRefresh test asserts on mockDriver.tables.

The QueryOrchestrator.test.js updates (.slice(0, 2) → refreshKeyIdentity, and the two queryKey fixtures gaining false / true) are the correct mechanical follow-through. Still true that this file isn't matched by testMatch: ['<rootDir>/test/**/*.test.ts'], so those edits are correct but unexecuted — worth a follow-up issue to widen testMatch or rename the file rather than leaving four pre-existing failures parked in a file nobody runs.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is the point of the change and is net positive; the costs are the one-time cold cache on upgrade and finding #3 (ksqlDB-only).

Caveat: node_modules is absent in this checkout and installs are blocked by this environment's command permissions, so I could not run jest or tsc. Everything above is by inspection of the diff and the surrounding source; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

`PreAggregationLoadCache` writes resolved refresh key values under
`queryRedisKey([query, values])` but `hasKeyQueryResult` looked them up under
`queryRedisKey(keyQuery)` — the full `[sql, params, options]` tuple every producer
emits. `getCacheHash` md5s `JSON.stringify`, so array length is part of the hash and
the lookup could never hit.

Regression from #3061, which moved refresh key metadata from a parallel
`refreshKeyRenewalThresholds` array into a third tuple element and updated only the
store side. Consequence: `notLoadedKey` was truthy whenever a pre-aggregation had any
invalidate key query, so `waitForRenew: false` requests always took the deferred path
and the "keys are already warm in this load cache, confirm freshness inline" branch has
been dead for four years. It failed safe — data was never stale, we just skipped a free
freshness win.

Both sides now go through one `QueryCache.refreshKeyIdentity` helper, which defines a
refresh key as `[sql, params, external]` — what identifies the result, as opposed to the
policy applied to it. `renewalThreshold` and friends stay out because
`replacePartitionSqlAndParams` recomputes `renewalThreshold` from `new Date()` for
incremental keys; measured, a key covering it drifts within 1.5s (10 -> 12) and would
miss nondeterministically for the whole 24h after a partition's update window closes.
`external` is in because it selects the engine the query runs against, so it is identity
rather than policy. It is normalized with `!!`: producers spell "source database" as both
`false` and an absent option, and `JSON.stringify` renders the latter as `null`.

Rather than have each caller apply that definition, both refresh key paths now hand the whole
tuple to `QueryCache.cacheRefreshKeyResult`, which derives the cache key, the renewal key and
the renewal threshold from it. Its options type is a `Pick` that deliberately excludes all
three, so a caller storing an entry under a key it would later look up by a different one is
now a compile error rather than a convention to remember. That also folds away the
`refreshKeyRenewalThreshold || queryOptions?.renewalThreshold || 2 * 60` chain and the
`useInMemory` / `external` defaults, which were duplicated verbatim across the two files --
the same drift hazard one level up. `refreshKeyIdentity` stays public because
`loadRangeQuery` and `checkPartitionsBuildRangeCache` need it as the `invalidate` component
of a larger key, not as the key itself.

The same helper replaces the `invalidateKeyQueries[0].slice(0, 2)` expression duplicated
across `PreAggregationPartitionRangeLoader.loadRangeQuery` (which writes the range query
cache entry) and `PreAggregations.checkPartitionsBuildRangeCache` (which reads it back) —
the same drift hazard, one definition now.

Re-enabling that branch needed a guard. The `externalRefresh` handling
(`throwOnMissingPartition` / `return null`) lives only in the deferred branch, and the
constructor forces `waitForRenew = false` when it is set, so those requests always
landed there. With the hash fixed and warm keys they would fall through to
`loadPreAggregationWithKeys()` -> `executeInQueue`, building pre-aggregations on an
instance explicitly told not to. The branch condition now excludes `externalRefresh`,
keeping its behaviour identical to today.

Also fixes the twin asymmetry from the same commit: `QueryCache.loadRefreshKey` still
passed `renewalKey: q` (3-tuple) while writing to `queryRedisKey([query, values])`,
whereas `keyQueryResult` stores `renewalKey: [query, values]` for the same entry. When a
cube level `cacheKeyQuery` and a pre-aggregation `invalidateKeyQuery` resolve to the same
SQL, the refresh scheduler and the pre-aggregation loader made each other look stale and
re-fetched on every touch.

Each new test was verified load-bearing across three configurations:

| test | no fixes | load cache fix only | full fix |
| --- | --- | --- | --- |
| `hasKeyQueryResult` ignores options element | fail | pass | pass |
| both refresh key paths store the same renewal key | fail | pass | pass |
| warm invalidation keys confirmed synchronously | fail | pass | pass |
| warm keys do not let `externalRefresh` build | pass | **fail** | pass |
| identity covers sql, params and engine, not policy | fail | - | pass |
| each engine gets its own cache entry | fail | - | pass |

Tests went into `PreAggregations.test.ts` because `QueryOrchestrator.test.js` is not
matched by `testMatch: ['<rootDir>/test/**/*.test.ts']` and never runs. Its call sites were
updated anyway so they stop encoding the old convention. Run manually against the compiled
`dist/test` copy — which is what jest picks up, since `allowJs` makes tsc emit it — master
fails 7 of 51 and this branch fails 5. The two that start passing, `lambda partitions week`
and `real-time sealing partitions`, assert on `queryRedisKey(...slice(0, 2))` and can only
hold once the store and lookup sides agree, so they are the fix showing up. The other 5 fail
on master too.

Upgrade note: this changes `cacheKey`, so every existing refresh key cache entry (and the
range query cache) becomes unreachable on deploy — one re-execution per distinct key,
bounded by `@AsyncDebounce` and the in-memory cache, and old entries age out on their own
(1h / 24h TTLs).

Verified against a live Cube instance (test-postgres, partitioned `orders_by_status`
rollup over Postgres, three monthly partitions unioned, refresh key `every: 1 day`).
The default cache mode never reported refresh keys before; it does now, and the data is
byte-identical:

| build | cache mode | rows | `usedPreAggregations[].refreshKeyValues` |
| --- | --- | --- | --- |
| master | default | 4 | `[[],[],[]]` |
| master | `must-revalidate` | 4 | `[[{refresh_key:20685}]]` x3 |
| this fix | default | 4 | `[[{refresh_key:20685}]]` x3 |

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 1s —— View job


Re-review after synchronize — this push is a rename/polish of the previously reviewed revision; verdict unchanged and positive. 0 new findings, 2 medium + 2 low re-affirmed, 1 naming nit

Full review
  • Read current diff vs origin/master
  • Compare against the previously reviewed revision
  • Verify every value cacheRefreshKeyResult derives against what master computed per path
  • Check the build-range key sites (loadRangeQuery / checkPartitionsBuildRangeCache) for write/read symmetry
  • Re-check standing findings against current lines
  • Dedupe against prior threads / resolve stale ones
  • Post review

What changed in this push

Essentially nothing behavioral. Compared with the revision I reviewed at 11:06 UTC, refreshKeyRedisKey() is now named refreshKeyCacheKey() (QueryCache.ts:464) and the surrounding doc comments were tightened; refreshKeyIdentity (QueryCache.ts:436), cacheRefreshKeyResult (QueryCache.ts:446), RefreshKeyCacheOptions (QueryCache.ts:52), the PreAggregationLoader condition (PreAggregationLoader.ts:140) and all four tests are unchanged in substance.

The design still holds up and is the strongest shape this PR has had:

  • The bug is now unrepresentable, not just fixed. RefreshKeyCacheOptions = Pick<CacheQueryResultOptions, 'priority' | 'requestId' | 'waitForRenew' | 'dataSource'> means a caller cannot supply its own renewalKey/cacheKey, so "store under one key, look it up by another" — the original defect — can't recur by construction. hasKeyQueryResult and keyQueryResult both route through refreshKeyCacheKey, so the store and lookup sides are the same expression.
  • Derived values match master per path. I re-checked each: renewalThreshold = this.options.refreshKeyRenewalThreshold || queryOptions?.renewalThreshold || 2 * 60 (identical in both old inline blocks), useInMemory: true (both), external: queryOptions?.external (both), waitForRenew still per-caller (!options.skipRefreshKeyWaitForRenew vs the passed flag), priority still only from keyQueryResult. The only intended deltas are the key and renewal-key shape.
  • Folding external into the identity remains an independent correctness fix. The old [query, values] key was engine-blind, so the same refresh-key SQL resolved against the source DB and against Cube Store shared one entry. The !! normalization matters because producers spell "source" as both false and absent and JSON.stringify would hash those to false vs null.
  • The .slice(0, 2) duplication is gone and the two build-range sites now carry paired "must stay identical to the other side" comments plus a shared function. I checked the new third element is stable across those two sites: replacePartitionSqlAndParams spreads ...options (PreAggregationPartitionRangeLoader.ts:176) and only rewrites renewalThreshold, so external survives partition rewriting and the write/read sides agree.

Original diagnosis unchanged: the memo branch has been unreachable since the third tuple element appeared in #3061, excluding the policy element is right because renewalThreshold is clock-derived, and find → every incidentally fixes a falsy-keyQuery edge.

Naming nit (not worth an inline thread)

In this file's vocabulary the unhashed tuple is the cacheKey (cacheQueryResult(query, values, cacheKey, …)) and the hashed string is the redisKey (redisKey = this.queryRedisKey(cacheKey), QueryCache.ts:915). refreshKeyCacheKey() returns the hashed string, so the rename in this push moved away from the local convention — refreshKeyRedisKey (the previous name) read correctly against refreshKeyIdentity returning the tuple. Cosmetic only; flagging because the pair refreshKeyIdentity (tuple) / refreshKeyCacheKey (string) invites someone to pass the wrong one.

Standing findings — re-affirmed, not re-posted

Both unresolved threads still land on the exact current lines, so per the dedup rule I did not post copies. Nothing became stale, so nothing to resolve.

# Severity Where Issue
2 Medium PreAggregationLoader.ts:140 The && !this.externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes Case 2 and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. Almost certainly intended, but it's a user-visible error-surface change the description doesn't mention, and still no test pins it — the new externalRefresh test covers the warm-keys case, not the empty-keys case.
5 Medium QueryCache.ts:436 dataSource is the other dimension cacheQueryResult routes on, and it's in neither the identity nor the getKey() prefix, so identical refresh-key SQL across two data sources shares one persisted entry (the per-instance queryResults memo hides it in-process). Pre-existing, but the doc comment reads as if the routing dimensions are covered. Same thread carries the upgrade-churn note.
3 Low PreAggregationLoader.ts:135 Warm check reads invalidateKeyQueries, while getPartitionInvalidationKeyValues resolves partitionInvalidateKeyQueries when set (ksqlDB) — a waitForRenew: false request can enter Case 2 with the keys that actually gate the blocking work still cold. The TODO that recorded this is still gone.
4 Low PreAggregationLoader.ts:143-150 The warm path returns real refreshKeyValues where Case 3 returned []; these surface in usedPreAggregations response metadata. Improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

PRRT_kwDOCOH19M6a5wrL (the old rolling-deploy renewalKey note) stays resolved — correctly, since the redisKey itself moves now, so old and new instances write disjoint entries instead of fighting over one.

Asks before merge (unchanged)

  1. A test pinning invalidateKeyQueries: [] + externalRefresh — finding MUTEX for requests #2 is the one case where the guard changes behavior that exists today. Fix this →
  2. A release-note line for the one-time cold refresh-key + build-range cache on upgrade (finding Add support for AWS Athena in JDBC driver #5, part 2).
  3. Either fold dataSource into refreshKeyIdentity or state in the doc comment why it's omitted, plus a follow-up issue.

Tests

Unchanged from the last revision apart from refreshKeyCacheKey in the renewal-key test, and still tracking the behavior well.

  • refresh key identity covers sql, params and engine, but not policy is the sharpest — positive (differing options still hit), normalization (external absent ≡ false), and negative (external: true differs) in one place.
  • a refresh key resolved against each engine gets its own cache entry asserts through executedQueries on each driver rather than through the key, which is the right level.
  • both refresh key paths store the same renewal key no longer discriminates the way it once did — there is now literally one code path writing the entry, so it can't observe a disagreement that can no longer exist. Still worth keeping as a divergence guard, but RefreshKeyCacheOptions is the real protection.
  • Minor trap noted before, still true: mockExternalDriverFactory has a createTable side effect per invocation, so mockExternalDriver.tables is non-empty in tests touching the external queue — harmless here, but don't assert on it the way the externalRefresh test asserts on mockDriver.tables.

The QueryOrchestrator.test.js updates (.slice(0, 2) → refreshKeyIdentity, queryKey fixtures gaining false / true) are the correct mechanical follow-through, but that file still isn't matched by testMatch: ['<rootDir>/test/**/*.test.ts'], so those edits are unexecuted. Worth a follow-up issue to widen testMatch or rename the file rather than leaving four pre-existing failures parked in a file nobody runs.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is the point of the change and is net positive; the costs are the one-time cold cache on upgrade and finding #3 (ksqlDB-only).

Caveat: node_modules is absent in this checkout and installs are blocked by this environment's command permissions, so I could not run jest or tsc. Everything above is by inspection of the diff and surrounding source; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

Follow-up cleanups on top of the refresh key memoization fix.

Share the build range `invalidate` derivation. The previous commit extracted
only the inner half and left the surrounding expression copied into both
`PreAggregationPartitionRangeLoader.loadRangeQuery` and
`PreAggregations.checkPartitionsBuildRangeCache`, each carrying a comment
telling the reader it must stay identical to the other. Both sites now call
`QueryCache.buildRangeInvalidateKey`, so the coupling is a call rather than
prose, and the two copies no longer disagree on optional chaining.

Stop computing `invalidationKeysLoaded` when it cannot change the outcome. It
is unused whenever `isJob`, `waitForRenew` or `externalRefresh` holds, and
`externalRefresh` defaults to true on every API instance in a split
API/refresh-worker deployment — so on that topology the previous commit added
one stringify+md5 per invalidation key per partition, all discarded. It is now
a thunk, and the condition gates `externalRefresh` structurally instead of
leaning on the constructor's `externalRefresh => waitForRenew = false`
invariant to make the comment true.

Stop hashing the same array twice per refresh key access.
`cacheRefreshKeyResult` passes one reference as both `cacheKey` and
`renewalKey`; before this series those differed on the `loadRefreshKey` path,
so the second `queryRedisKey` earned its keep. It no longer can.

Also: read `external` once off the identity tuple; correct the
`RefreshKeyCacheOptions` doc, which called `renewalThreshold` part of the
entry's identity while `refreshKeyIdentity` argues the opposite; drop the
orphaned `Case 3` label left behind when Cases 1 and 2 were removed; use the
new `refreshKeyCacheKey` in `QueryOrchestrator.test.js` instead of
re-composing it by hand, which would have let the wrapper drift unnoticed; and
replace the tenth verbatim `new PreAggregations(...)` copy in the test file
with a factory.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 40s —— View job


Re-review after synchronize — condition restructure is behaviorally equivalent and now self-sufficient; verdict positive. 0 new findings, 2 medium + 2 low re-affirmed, 2 nits

Full review
  • Read current diff vs origin/master
  • Diff against the previously reviewed revision (11:12 UTC)
  • Verify the restructured loadPreAggregation condition against the old one, combo by combo
  • Trace the new buildRangeInvalidateKey across both build-range sites
  • Check the renewalKey === cacheKey shortcut for correctness
  • Re-check key-space collisions after CacheKey grew a 4th element
  • Re-check standing findings against current lines
  • Dedupe against prior threads / resolve stale ones
  • Post review

What changed in this push

Three real edits on top of the revision I reviewed at 11:12 UTC, none of which change behavior:

File Change
PreAggregationLoader.ts:135-142 Condition regrouped: isJob || this.waitForRenew || (loaded && !externalRefresh) → isJob || (!externalRefresh && (waitForRenew || loaded())), and invalidationKeysLoaded became a thunk. The Case 1/2/3 comments were replaced with prose.
QueryCache.ts:443-455 New static buildRangeInvalidateKey(preAggregation), replacing the derivation that loadRangeQuery and checkPartitionsBuildRangeCache each spelled out.
QueryCache.ts:1028-1036 redisKey hoisted in cacheOperationContext; renewalKey reuses it when options.renewalKey === cacheKey by reference.

The regrouped condition is equivalent, and better. I walked the combos: isJob still wins first in both. When externalRefresh is set, the constructor coerces waitForRenew = false (PreAggregationLoader.ts:127-129), so the old form collapsed to (loaded && !externalRefresh) = false, i.e. the same Case-3 outcome the new form reaches by short-circuit. The difference is that the new form no longer depends on that coercion — if the constructor line were ever dropped, the old expression would silently route externalRefresh instances onto the building path while the new one wouldn't. Worth having.

The thunk is a genuine (if small) win too: hashing now happens only on the one path that consults it, so isJob, externalRefresh and waitForRenew requests skip refreshKeyCacheKey per invalidation key entirely.

buildRangeInvalidateKey is the right last piece. Those two sites had to agree by convention and nothing enforced it — the read side is PreAggregations.checkPartitionsBuildRangeCache (PreAggregations.ts:635) and the write side is PreAggregationPartitionRangeLoader.loadRangeQuery (PreAggregationPartitionRangeLoader.ts:89), and a shared static is what makes divergence impossible rather than merely unlikely. It also incidentally hardens the read side: preAggregation?.invalidateKeyQueries[0] would throw on a pre-agg with no invalidateKeyQueries (the ?. was on the wrong link); invalidateKeyQueries?.[0] doesn't.

The renewalKey shortcut is correct. Reference equality implies value equality, so reusing redisKey can't produce a different hash than queryRedisKey(options.renewalKey) would. cacheQueryResult passes its cacheKey argument to cacheOperationContext untouched (QueryCache.ts:1154), so the identity holds for cacheRefreshKeyResult (which passes the same array as both) and every other caller falls through to hashing as before. Non-index properties like the persistent flag queryCacheKey attaches aren't visible to JSON.stringify either way.

Key-space re-check after CacheKey grew a 4th element — clean

buildRangeInvalidateKey now returns a 3-element tuple where the old .slice(0, 2) returned two, so build-range keys with a truthy invalidate are 4 elements: [query, values, [], [sql, params, external]]. Refresh-key entries are 3 elements [query, values, external]. Distinct lengths, distinct JSON — no overlap. The falsy-invalidate case is still the near miss and still safe: queryCacheKey only appends invalidate when truthy (QueryCache.ts:422), so it yields [query, values, []], which stringifies distinctly from [query, values, false]. That remains load-bearing — pushing a falsy invalidate would make the two key spaces overlap.

The earlier verdict is unchanged: the memo branch has been unreachable since the third tuple element appeared in #3061; RefreshKeyCacheOptions makes "store under one key, look up by another" unrepresentable rather than merely fixed; folding external into the identity is an independent correctness fix (the old key was engine-blind, and the !! normalization collapses false and absent, which JSON.stringify would otherwise hash to false vs null); and find → every incidentally fixes a falsy-keyQuery edge.

Nits (not worth inline threads)

  1. The new thunk comment is hard to parse. "Hashes a cache key per invalidation key, so it stays a thunk — the branches above it decide the outcome on their own for every request an externalRefresh instance serves." There are no branches above it; the referents are the other operands of the same if. Something like "kept lazy: hashes one cache key per invalidation key, and isJob / externalRefresh / waitForRenew all decide without it" would say it in one read.
  2. refreshKeyIdentity (tuple) vs refreshKeyCacheKey (hashed string). Still flagging from the last pass: this file's vocabulary is cacheKey = unhashed tuple, redisKey = hashed string (redisKey = this.queryRedisKey(cacheKey)), so refreshKeyCacheKey() returning the hash reads against the local convention. Cosmetic, but the pair invites passing the wrong one.

Standing findings — re-affirmed, not re-posted

Both unresolved threads still land on the current lines, so per the dedup rule I did not post copies. Neither became stale in this push, so nothing to resolve.

# Severity Where Issue
2 Medium PreAggregationLoader.ts:142 The !this.externalRefresh guard also changes a path that is live on master: invalidateKeyQueries: [] + externalRefresh currently takes the build path and builds locally; it now throws noPreAggregationPartitionsBuiltMessage / returns null. I re-verified this against the regrouped condition — externalRefresh now short-circuits before invalidationKeysLoaded() is even called, so the empty-array case is affected exactly as before. Almost certainly intended, but it's a user-visible error-surface change the description doesn't mention, and still no test pins it — the externalRefresh test covers the warm-keys case, not the empty-keys case.
5 Medium QueryCache.ts:433 dataSource is the other dimension cacheQueryResult routes on, and it's in neither the identity nor the getKey() prefix, so identical refresh-key SQL across two data sources shares one persisted entry (the per-instance queryResults memo hides it in-process). Pre-existing, but the doc comment reads as if the routing dimensions are covered. Same thread carries the upgrade-churn note, which this push slightly widens again — buildRangeInvalidateKey moves the build-range key for every partitioned pre-agg too.
3 Low PreAggregationLoader.ts:137 Warm check reads invalidateKeyQueries, while getPartitionInvalidationKeyValues resolves partitionInvalidateKeyQueries when set (ksqlDB) — a waitForRenew: false request can enter the inline path with the keys that actually gate the blocking work still cold. The TODO that recorded this is still gone.
4 Low PreAggregationLoader.ts:144-152 The warm path returns real refreshKeyValues where the deferred path returned []; these surface in usedPreAggregations response metadata. Improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

PRRT_kwDOCOH19M6a5wrL (the old rolling-deploy renewalKey note) stays resolved — correctly, since the redisKey itself moves now, so old and new instances write disjoint entries instead of fighting over one.

Minor loss worth noting: dropping the Case 1 / Case 2 / Case 3 labels is fine for the code (nothing else in the package referenced them — I grepped), but it does cost the shared vocabulary that this PR's own description and every review thread on it use. Not asking for them back.

Asks before merge (unchanged)

  1. A test pinning invalidateKeyQueries: [] + externalRefresh — finding MUTEX for requests #2 is the one case where the guard changes behavior that exists today. Fix this →
  2. A release-note line for the one-time cold refresh-key and partition build-range cache on upgrade (finding Add support for AWS Athena in JDBC driver #5, part 2).
  3. Either fold dataSource into refreshKeyIdentity or state in the doc comment why it's omitted, plus a follow-up issue.

Tests

Byte-identical to the last revision — the four new PreAggregations.test.ts tests and the two QueryOrchestrator.test.js fixture updates. Still tracking the behavior well:

  • refresh key identity covers sql, params and engine, but not policy remains the sharpest: positive (differing options still hit), normalization (external absent ≡ false), negative (external: true differs) in one place.
  • a refresh key resolved against each engine gets its own cache entry asserts through executedQueries on each driver rather than through the key — the right level.
  • both refresh key paths store the same renewal key no longer discriminates the way it once did, since one code path now writes the entry; keep it as a divergence guard, but RefreshKeyCacheOptions is the real protection.
  • mockExternalDriverFactory has a createTable side effect per invocation, so mockExternalDriver.tables is non-empty in tests touching the external queue — harmless here, but don't assert on it the way the externalRefresh test asserts on mockDriver.tables.

No test covers buildRangeInvalidateKey. It's the newest code in the diff and it's the piece whose whole purpose is write/read symmetry across two files — exactly the class of bug this PR exists to fix. A small test that writes a build-range entry via PreAggregationPartitionRangeLoader and then finds it via checkPartitionsBuildRangeCache would pin the invariant the doc comment asserts. Low priority given the shared derivation makes divergence hard, but the same was true of the original bug before someone edited one side.

QueryOrchestrator.test.js is still not matched by testMatch: ['<rootDir>/test/**/*.test.ts'], so its edits here are correct but unexecuted — worth a follow-up issue to widen testMatch or rename the file rather than leaving four pre-existing failures parked in a file nobody runs.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is net positive and is the point: the memo branch works again, the thunk removes per-key hashing on three of four paths, and the renewalKey shortcut saves one md5 per refresh-key cache operation. The costs are the one-time cold cache on upgrade and finding #3 (ksqlDB-only).

Caveat: node_modules is absent in this checkout and installs are blocked by this environment's command permissions, so I could not run jest or tsc. Everything above is by inspection of the diff and surrounding source; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

`cacheQueryResult` routes a refresh key query on two dimensions — `external`
picks the engine, `dataSource` picks the queue and the driver — but only
`external` was part of `refreshKeyIdentity`, and the cache prefix
(`${cachePrefix}#SQL_QUERY_RESULT:`) separates tenants rather than data sources.
Two data sources inside one orchestrator with identical refresh key SQL, say
`SELECT MAX(updated_at) FROM orders` against prod and against staging, therefore
shared one persisted entry and each served the other's row; the per-request
`PreAggregationLoadCache.queryResults` memo hid it in process. `dataSource` now
joins the identity, normalized to `default` the way `getQueue` already resolves
an absent one, so the two spellings that reach the same driver reach the same
entry. `buildRangeInvalidateKey` picks it up from the pre-aggregation
descriptor, which both the write side (`loadRangeQuery`) and the read side
(`checkPartitionsBuildRangeCache`) already hold.

Also pins the one behaviour the new `!this.externalRefresh` guard changes for a
path that exists on master: a pre-aggregation with `invalidateKeyQueries: []`
left `notLoadedKey` undefined, so `!(notLoadedKey && !waitForRenew)` was true and
even an `externalRefresh` instance took the building path and built locally. It
now reports the partition as missing like every other `externalRefresh` request.
The existing test covered the warm-keys case only.

| test | fails without |
| --- | --- |
| `a refresh key resolved against each data source gets its own cache entry` | `dataSource` in the identity |
| `an absent data source hashes as default` | the `\|\| 'default'` normalization |
| `a pre-aggregation with no invalidation keys does not let externalRefresh build either` | the `!this.externalRefresh` guard |

Upgrade note: this moves the persisted refresh key cache keys and the partition
build range cache keys, so both are cold once on the first start after the
upgrade — refresh keys and build ranges are re-resolved, pre-aggregation data
itself is not rebuilt.

`test/unit/PreAggregations.test.ts` is 44 green. The `refreshKeyCacheKey` and
`queryKey` updates in `QueryOrchestrator.test.js` are correct but unexecuted —
`testMatch` is `test/**/*.test.ts`; run manually against the compiled copy its
failure set is 5, identical to this branch before the change and a subset of
master's 7.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 31s —— View job


Re-review after synchronize — dataSource folded into the identity and the externalRefresh empty-keys case now pinned; both of my medium findings are addressed. Verdict positive. 1 typing nit posted inline, 1 low re-affirmed, 1 stale thread resolved

Full review
  • Read current diff vs origin/master
  • Diff against the previously reviewed revision (11:29 UTC)
  • Verify the dataSource addition at every producer and consumer
  • Check write/read symmetry of buildRangeInvalidateKey after the 4th element
  • Re-check key-space collisions with other cacheQueryResult producers
  • Check @AsyncDebounce on loadRefreshKey for cross-dataSource sharing
  • Re-check standing findings against current lines
  • Dedupe against prior threads / resolve stale ones
  • Post review

What changed in this push

One new commit, 0f53b8a fix(query-orchestrator): key refresh key entries by data source, and it lands both of the medium findings that had been standing since the first pass:

Finding Status
#5 — dataSource missing from the identity Fixed. refreshKeyIdentity(sqlQuery, dataSource) now returns [query, values, !!external, dataSource || 'default'] (QueryCache.ts:438-448), threaded through refreshKeyCacheKey, cacheRefreshKeyResult (options.dataSource), buildRangeInvalidateKey (preAggregation.dataSource) and both PreAggregationLoadCache sites. Doc comment updated to claim exactly what it now covers.
#2 — invalidateKeyQueries: [] + externalRefresh unpinned Fixed. a pre-aggregation with no invalidation keys does not let externalRefresh build either asserts both the throwOnMissingPartition throw and the null return, plus mockDriver.tables === [] — which is the assertion that actually catches an unwanted build.
#5 part 2 — release note Addressed in the commit message ("moves the persisted refresh key cache keys and the partition build range cache keys, so both are cold once… pre-aggregation data itself is not rebuilt"). Worth mirroring the current key shape into the PR description's Upgrade note, which still describes the earlier H2 -> H revision.

Verification of the dataSource change

I traced the new element through every path rather than taking the commit message for it:

  • Producers and consumers agree. keyQueryResult and hasKeyQueryResult both pass this.dataSource (PreAggregationLoadCache.ts:194, :212), and that field is already the normalized value — PreAggregations.ts:528-541 keys load caches by dataSource and filters pre-aggs with (p.dataSource || 'default') === dataSource, so the load cache's value and the descriptor's value can only differ by the absent/'default' spelling that refreshKeyIdentity now collapses. loadRefreshKey passes options.dataSource, which loadRefreshKeysFromQuery forwards raw from query.dataSource (QueryCache.ts:928-936) — precisely the absent case the || 'default' normalization and the an absent data source hashes as default test exist for.
  • Build-range write/read stay symmetric. Both sides read the parent descriptor — write at PreAggregationPartitionRangeLoader.ts:89 (this.preAggregation), read at PreAggregations.ts:635 (queryBody.preAggregations[]) — so they see the same dataSource, and the partition descriptor spreads ...this.preAggregation (PreAggregationPartitionRangeLoader.ts:200) so nothing rewrites it mid-flight. Same reasoning as external last pass.
  • No external callers. refreshKeyIdentity / refreshKeyCacheKey / cacheRefreshKeyResult / buildRangeInvalidateKey are grep-clean outside this package, so the signature changes are internal.
  • @AsyncDebounce doesn't reintroduce the collision. Worth checking, since a debounce that keyed only on the SQL would let two data sources share an in-flight promise no matter what the cache key says. It doesn't: asyncDebounceFn hashes args.map(JSON.stringify).join(',') (packages/cubejs-backend-shared/src/promises.ts:284-287), which includes the whole options object, so dataSource participates.
  • external: cacheKey[2] replacing queryOptions?.external is a safe tightening — undefined and false are both falsy at the external ? externalQueue : queue fork, so queue selection is unchanged, and it removes the last place the two could drift.

Key-space re-check after the 4th element — still clean

Refresh-key entries are now 4-element [query, values, boolean, string]; build-range keys with a truthy invalidate are 4-element [query, values, preAggLoadSqls, [sql, params, boolean, string]]. Same arity, but element 3 is a boolean vs an array, so the JSON is disjoint. The falsy-invalidate case remains the near miss and remains safe for the same reason as before: queryCacheKey only appends invalidate when truthy (QueryCache.ts:422), yielding [query, values, []]. That's still load-bearing — pushing a falsy invalidate would overlap the two key spaces.

Everything from the earlier passes still holds: the memo branch has been unreachable since the third tuple element appeared in #3061; RefreshKeyCacheOptions makes "store under one key, look it up by another" unrepresentable rather than merely fixed; find → every incidentally fixes a falsy-keyQuery edge; and the regrouped loadPreAggregation condition no longer depends on the constructor's waitForRenew = false coercion to keep externalRefresh off the building path.

New finding (posted inline)

# Severity Where Issue
6 Nit QueryCache.ts:441 dataSource is typed non-optional string, but buildRangeInvalidateKey forwards a dataSource?: string and the new test passes undefined positionally — it compiles only because this package sets strictNullChecks: false. Since the || 'default' normalization is deliberate, string | undefined documents it and survives the package being tightened.

Standing findings

# Severity Where Issue
3 Low PreAggregationLoader.ts:138 Still open, and the only substantive thing left. The warm check reads invalidateKeyQueries, while the blocking work in loadPreAggregationWithKeys() resolves partitionInvalidateKeyQueries when set (getPartitionInvalidationKeyValues, PreAggregationLoader.ts:404-413; those are a separate per-partition set, rewritten at PreAggregationPartitionRangeLoader.ts:210). So a waitForRenew: false ksqlDB request can enter the inline path on warm keys and then block on cold ones. The suggestion in the existing thread gates on the set that will actually be resolved.
4 Low PreAggregationLoader.ts:143-152 The warm path returns real refreshKeyValues where the deferred path returned []; these surface in usedPreAggregations response metadata. Improvement, but it changes what non-waitForRenew responses expose. Not part of any cache key, so no invalidation impact.

Thread bookkeeping: I resolved PRRT_kwDOCOH19M6b0FDm (the dataSource-in-identity + upgrade-churn note) — this push implements exactly what it asked for. I left PRRT_kwDOCOH19M6a5w6l unresolved because only its first half (the missing empty-keys test) is addressed; the partitionInvalidateKeyQueries suggestion in its second half is finding #3 and still applies. No copies re-posted.

Tests

The three new tests are well chosen and each is falsifiable in a different place:

  • a refresh key resolved against each data source gets its own cache entry asserts through mockDriver.executedQueries (two executions of the same SQL) rather than through the key — same right-level choice as the external test, and it would survive a rewrite of the key derivation.
  • an absent data source hashes as default is the one that pins the || 'default' normalization, which is the subtle half of this commit — without it, loadRefreshKeysFromQuery forwarding an absent dataSource and a load cache spelling it 'default' would write two entries for one driver, i.e. the same class of split the PR exists to remove.
  • a pre-aggregation with no invalidation keys does not let externalRefresh build either covers both throwOnMissingPartition polarities and asserts mockDriver.tables === []. The preAggOverrides parameter added to createPreAggLoader is the minimal way to get there.
  • refresh key identity covers sql, params and engine, but not policy remains the sharpest of the set — positive, normalization, and negative in one place.
  • Trap noted before, still true: mockExternalDriverFactory calls createTable on every invocation, so mockExternalDriver.tables is non-empty in tests touching the external queue — don't assert on it the way the externalRefresh tests assert on mockDriver.tables.

Still no test on buildRangeInvalidateKey itself — the piece whose whole purpose is write/read symmetry across two files, which is exactly the class of bug this PR exists to fix. A test that writes a build-range entry via PreAggregationPartitionRangeLoader and then finds it via checkPartitionsBuildRangeCache would pin the invariant its doc comment asserts. Low priority now that the derivation is shared, but the same was true of the original bug before someone edited one side. Fix this →

The QueryOrchestrator.test.js updates (refreshKeyCacheKey(..., 'default') and the two queryKey fixtures gaining 'default') are the correct mechanical follow-through, but that file still isn't matched by testMatch: ['<rootDir>/test/**/*.test.ts'], so those edits are unexecuted. The commit message's manual run (5 failures, identical to this branch before the change, a subset of master's 7) is the right diligence; a follow-up issue to widen testMatch or rename the file would stop this recurring.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is net positive and is the point: the memo branch works again, the thunk skips per-key hashing on the isJob / externalRefresh / waitForRenew paths, and the renewalKey === cacheKey shortcut saves one md5 per refresh-key cache operation. The dataSource element adds no per-request cost; its only cost is the one-time cold cache on upgrade.

Caveat: node_modules is absent in this checkout and installs are blocked by this environment's command permissions, so I could not run jest or tsc — including the typing nit above, which I reasoned about from the package's tsconfig.json rather than from a compiler run. Everything here is by inspection of the diff and surrounding source; treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

ovr and others added 2 commits August 28, 2026 15:07
Follow-up comment pass over the three commits in this series. Comments that
restated what the next line or two already says are gone; the ones that carry a
reason are kept and shortened.

Removed outright: `// Renew synchronously so the current request returns the
most current data.` above `await this.loadPreAggregationWithKeys()`, and
`// Warm refresh keys must not promote an externalRefresh instance onto the
building path.` above an assertion that spells out the same thing in its
`rejects.toThrowError`.

Condensed, keeping the why: the `RefreshKeyCacheOptions` doc now leads with the
constraint it exists to enforce rather than enumerating the `Pick` members
below it; `refreshKeyIdentity` no longer re-explains what `external` and
`dataSource` select two lines above the tuple that returns them; and the
normalization comment states the invariant (both spellings of each default
collapse to one key) instead of walking through each producer.

No behaviour change -- comments only. `yarn tsc` clean,
`test/unit/PreAggregations.test.ts` 44 green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`QueryCache.queryRedisKey` hashes a `CacheKey` into the namespaced key handed to
`this.cacheDriver`. That driver has not been Redis-specific since the cache
driver abstraction landed -- it is `LocalCacheDriver` or the Cube Store backed
driver depending on `CUBEJS_CACHE_AND_QUEUE_DRIVER` -- so the name pointed at an
implementation the method no longer knows about.

Mechanical rename of the method and its 6 call sites, plus 2 call sites and a
comment in `test/unit/QueryCache.abstract.ts`. No behaviour change: the returned
string is byte-identical, so no cache entry moves.

Two deliberate non-changes:

`LocalQueueDriverConnection.queryRedisKey(queryKey, suffix)` keeps its name. It
builds queue keys (`${prefix}_${hash}_${suffix}`) against the queue driver, not
cache keys, so `queryCacheKey` would be actively wrong there.

The `redisKey` field on `CacheOperationContext` and the `tablesUsedRedisKey` /
`tablesTouchRedisKey` / `preAggBackoffRedisKey` helpers in `PreAggregations.ts`
also still carry the old naming. They are the same cleanup but a wider diff;
left for a dedicated pass.

Worth flagging for review: `QueryCache` now has both a static and an instance
member named `queryCacheKey`, doing different halves of the same job --
`static queryCacheKey(queryBody): CacheKey` builds the tuple, `queryCacheKey(cacheKey):
string` hashes it. TypeScript keeps static and instance members in separate
namespaces so this compiles, but `resultFromCacheIfExists` now reads:

    const cacheKey = QueryCache.queryCacheKey(queryBody);
    const cachedValue = await this.cacheDriver.get(this.queryCacheKey(cacheKey));

If that overload reads as too subtle, `queryCacheKeyHash` for the instance
method disambiguates it.

`yarn tsc` clean. `QueryCache.test.ts` + `PreAggregations.test.ts` 84 green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 50s —— View job


Re-review after synchronize — comment trimming plus a queryRedisKey → queryCacheKey rename; no behavior change. Verdict positive. 1 naming nit posted inline, 0 open findings

Full review
  • Read the two new commits (b421b56, 6110b46) against the previously reviewed revision
  • Verify the queryRedisKey → queryCacheKey rename is complete and mechanical
  • Re-check standing findings against current lines
  • Dedupe / resolve stale threads
  • Post review

What changed in this push

Two commits on top of 0f53b8a, and neither touches behavior:

Commit Change
b421b56 trim narration from refresh key comments Prose only — doc comments on RefreshKeyCacheOptions, refreshKeyIdentity, buildRangeInvalidateKey, the PreAggregationLoader thunk comment, and four test comments. One comment I flagged last pass as hard to parse ("the branches above it decide the outcome…") is now "A thunk: hashing a cache key per invalidation key is wasted whenever the cheaper terms of the condition below already decide it" — that reads in one pass. Nit closed.
6110b46 rename queryRedisKey to queryCacheKey Mechanical rename of the instance method plus its 7 call sites and 3 test references. No logic touched.

I diffed 0f53b8a..HEAD line by line: every hunk is either a comment or the identifier swap. refreshKeyIdentity's return, cacheRefreshKeyResult's derivation, buildRangeInvalidateKey, the loadPreAggregation condition, and all key shapes are byte-identical to the revision I reviewed at 12:14 UTC. One incidental deletion worth confirming as harmless: the // Renew synchronously so the current request returns the most current data. line above loadPreAggregationWithKeys() is gone; the surrounding externalRefresh comment still carries the load-bearing part.

Rename completeness: I grepped the whole packages/ tree — no queryRedisKey references remain except the unrelated LocalQueueDriverConnection.queryRedisKey(queryKey, suffix) (different class, different signature, correctly untouched). The QueryCache.abstract.ts seeding helper was updated in step, which matters because it replicates the hashing that fetchNew does.

The substantive verdict from the earlier passes is unchanged and still holds: the memo branch has been unreachable since the third tuple element appeared in #3061; RefreshKeyCacheOptions makes "store under one key, look it up by another" unrepresentable rather than merely fixed; external + dataSource in the identity are two independent correctness fixes (engine-blind and data-source-blind keys respectively), with !! / || 'default' collapsing the two spellings of each default; buildRangeInvalidateKey removes the last write/read pair that had to agree by convention; and the regrouped condition no longer depends on the constructor's waitForRenew = false coercion to keep externalRefresh off the building path.

New finding (posted inline)

# Severity Where Issue
7 Nit QueryCache.ts:1225 The rename lands two members named queryCacheKey on the same class meaning opposite things: the static returns the unhashed CacheKey tuple from a query body (QueryCache.ts:415), the new instance method hashes a tuple into the storage key. They appear on adjacent lines at QueryCache.ts:1214-1215. It also inverts the vocabulary the rest of the file still uses (cacheKey = tuple, redisKey = hash — including const redisKey = this.queryCacheKey(cacheKey) three lines from the call site). Getting "redis" out of the name is a fine goal; a non-colliding name like cacheKeyHash() would get there without the homonym. Also a small breaking change for external callers, since queryRedisKey was public.

Thread bookkeeping

All four of my prior threads are now resolved, so there is nothing to re-affirm and nothing stale to resolve. For the record, three of them were addressed by code in earlier pushes (the dataSource identity, the empty-keys externalRefresh test, the old rolling-deploy note). The fourth — PRRT_kwDOCOH19M6dKb9V, the dataSource: string vs string | undefined typing nit at QueryCache.ts:437 — was resolved without the type changing; it still compiles only because this package sets strictNullChecks: false, and the test still passes undefined positionally. Taking that as a deliberate call rather than an oversight, so I have not re-posted it.

Two low findings from earlier passes were also resolved rather than fixed, which I'll likewise treat as decided:

  • Warm check reads invalidateKeyQueries while getPartitionInvalidationKeyValues resolves partitionInvalidateKeyQueries when set (ksqlDB), so a waitForRenew: false request can enter the inline path on warm keys and then block on cold ones.
  • The warm path returns real refreshKeyValues where the deferred path returned [], which changes what usedPreAggregations metadata exposes on non-waitForRenew responses. Not part of any cache key, so no invalidation impact.

Tests

Unchanged apart from comment edits. Still tracking the behavior well; refresh key identity covers sql, params and engine, but not policy (positive / normalization / negative in one place), an absent data source hashes as default (pins the || 'default' half), and a pre-aggregation with no invalidation keys does not let externalRefresh build either (both throwOnMissingPartition polarities plus mockDriver.tables === []) are the load-bearing three.

Two carry-overs, both low and both unchanged:

  • Still no test on buildRangeInvalidateKey itself — the newest piece, and the one whose whole purpose is write/read symmetry across two files, which is exactly the class of bug this PR exists to fix. Fix this →
  • QueryOrchestrator.test.js is still not matched by testMatch: ['<rootDir>/test/**/*.test.ts'], so its edits in this PR are correct but unexecuted. A follow-up issue to widen testMatch or rename the file would stop this recurring.

Also still worth a pass over the PR description before merge: the Upgrade note and the ASCII diagrams still describe the H2 -> H = md5([sql, params, !!external]) revision, while the shipped identity is [sql, params, !!external, dataSource || 'default'] and the build-range key moved too. The body text further down does mention dataSource, so it's an internal inconsistency rather than a wrong claim — but the release-note line should say both the refresh key cache and the partition build range cache go cold once, with pre-aggregation data itself not rebuilt.

Security / performance

No security surface touched — no user input, no auth, no query construction. Performance is net positive and unchanged from the last pass: the memo branch works again, the thunk skips per-key hashing on the isJob / externalRefresh / waitForRenew paths, and the renewalKey === cacheKey shortcut saves one hash per refresh-key cache operation. The only cost is the one-time cold cache on upgrade.

Caveat: node_modules is absent in this checkout and installs are blocked by this environment's command permissions, so I could not run jest, tsc, or the linter — the rename in particular is the kind of change a compiler run would confirm outright, and I verified it by grepping instead. Treat CI as the source of truth for the pass/fail claims in the description.

· branch `fix-haskeyqueryresult-tuple-hash`

}

public queryRedisKey(cacheKey: CacheKey): string {
public queryCacheKey(cacheKey: CacheKey): string {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This rename lands QueryCache with two members named queryCacheKey that mean opposite things:

  • public static queryCacheKey(queryBody: QueryBody): CacheKey (QueryCache.ts:415) — builds the unhashed tuple from a query body.
  • public queryCacheKey(cacheKey: CacheKey): string (here) — hashes a tuple into the prefixed storage key.

It compiles (static and instance namespaces are separate), but the two are adjacent in real code, and the pairing is now hard to read:

const cacheKey = QueryCache.queryCacheKey(queryBody);            // tuple
const cachedValue = await this.cacheDriver.get(this.queryCacheKey(cacheKey)); // hash

It also inverts the vocabulary the rest of the file still uses — the unhashed tuple is the cacheKey and the hash is the redisKey, including three lines down from the call site (const redisKey = this.queryCacheKey(cacheKey), QueryCache.ts:1031) and in the returned { cacheKey, redisKey }. I raised the same shape on refreshKeyCacheKey last pass; this commit generalizes it rather than resolving it.

If the goal is to get "redis" out of the name (reasonable — the driver is cacheDriver, not Redis), something that doesn't collide with the static and reads as "hash it" would do the job, e.g. cacheKeyHash() / storageKey(), with the redisKey locals and the CacheKeyItem.renewalKey field renamed alongside so the file speaks one vocabulary. Purely naming — no behavior at stake. Fix this →

Also worth noting queryRedisKey was public, so this is a (small) breaking change for anything outside this repo that calls it. Inside the monorepo the rename is complete — I grepped, and the only remaining queryRedisKey is the unrelated LocalQueueDriverConnection.queryRedisKey(queryKey, suffix).

@ovr ovr changed the title fix(query-orchestrator): make refresh key memo lookups hit again fix(query-orchestrator): key refresh key cache entries consistently Aug 28, 2026
@ovr
ovr merged commit 5bc6308 into master Aug 28, 2026
91 of 94 checks passed
@ovr
ovr deleted the fix-haskeyqueryresult-tuple-hash branch August 28, 2026 14:50
ovr added a commit that referenced this pull request Aug 29, 2026
…ime behind a flag

Interval and cron based `refreshKey` values can now be computed from the API
instance clock instead of via `SELECT FLOOR(...) as refresh_key`, gated by
`CUBEJS_REFRESH_KEY_LOCAL_TIME` (default `false`).

The compiler already derived every input in JS — `interval`, `dayOffset` and
`utcOffset` come from `parseSecondDuration`/`calcIntervalForCronString`. SQL only
contributed `now()`. So `BaseQuery.everyRefreshKeyParts()` is extracted as the
single source of truth that both the rendered SQL and a serializable descriptor
derive from, and when the flag is on that descriptor rides in the refresh-key
tuple's options element.

The orchestrator short-circuits it in exactly one place,
`QueryCache.cacheRefreshKeyResult`. #11607 had just made that the sole owner of a
refresh key's cache key, renewal key and threshold, so both consumers — the
scheduler's `loadRefreshKey` and the loader's `keyQueryResult` — are covered
without either being touched. `PreAggregationLoadCache` keeps its per-request
memo wrapping the call, which matters: one pre-aggregation load reads the
invalidation keys several times (`contentVersion`, the returned
`refreshKeyValues`, the refresh queue key), and re-reading the clock could
straddle an interval boundary and have the load look a table up under one content
version while enqueueing it under another. A test pins that by stubbing
`Date.now` across a boundary.

Why: the default `{ every: '10 seconds' }` cube refresh key has
`renewalThreshold: 10`, so it is re-issued to Cube Store on essentially every
request. That query has no `TableScan`, so `is_data_select_query` is false and it
takes the `QueryPlan::Meta` path — correctly bypassing `SqlResultCache`, but still
paying parser + plan + optimize + `collect`, plus
`MetaStoreSchemaProvider::new(get_tables_with_path(false))` on every call, plus a
WebSocket round trip. All to learn the wall clock.

Scope: cube-level `cacheKeyQueries` and pre-aggregation `invalidateKeyQueries`,
including the `10 seconds` and `1 hour` defaults. Excluded are `refreshKey.sql`
and `incremental` keys — the latter are wrapped in
`CASE WHEN NOW() < <dateTo + updateWindow>` against an allocated partition-range
param, and their options drive `renewalThresholdOutsideUpdateWindow` shortening
for freshly sealed partitions.

Flag off is byte-identical. The gate is applied at emit time as well as consume
time, so the tuples and every hash derived from them are unchanged and no
persisted cache is invalidated on upgrade. The existing `everyRefreshKeySql`
assertions pass unedited, which is what proves the emitted SQL did not move.

Clock skew is why this is flagged. Two nodes straddling an interval boundary
produce different `contentVersion`s, so the same pre-aggregation gets built twice,
recurring at each boundary. `externalRefresh` bounds the blast radius — non-builder
API instances never run these queries — so a single refresh worker is safe;
multiple workers or `CUBEJS_PRE_AGGREGATIONS_BUILDER=true` API instances are not.
Flipping the flag also forces one pre-aggregation rebuild each way, since `pg`
returns `numeric` as a string and Cube Store as a number. Table names are
unaffected; `getStructureVersion` excludes invalidation keys.

One finding worth recording: `preAggregationInvalidateKeyQueries` is memoized
against a `queryCache` whose key did not include the flag, so a flag-on query's
compiled refresh keys leaked to a flag-off query. Fixed by adding
`localRefreshKey` to the key list next to the analogous
`convertTzForRawTimeDimension`. A test caught this, not review.

| Suite | Result |
| --- | --- |
| `cubejs-backend-shared` `test/env.test.ts` | 25/25 |
| `cubejs-query-orchestrator` `test/unit` | 129/129, 6 suites |
| `cubejs-schema-compiler` `dist/test/unit` | 826/831, 39/42 suites |

The five schema-compiler failures are `error-reporter`, `FILTER_PARAMS` and
`pre-agg-interpolated-cube-refs`; all five reproduce on an unmodified master,
verified by reverting this branch's two schema-compiler files and re-running.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
ovr added a commit that referenced this pull request Aug 31, 2026
…ime behind a flag

Interval and cron based `refreshKey` values can now be computed from the API
instance clock instead of via `SELECT FLOOR(...) as refresh_key`, gated by
`CUBEJS_REFRESH_KEY_LOCAL_TIME` (default `false`).

The compiler already derived every input in JS — `interval`, `dayOffset` and
`utcOffset` come from `parseSecondDuration`/`calcIntervalForCronString`. SQL only
contributed `now()`. So `BaseQuery.everyRefreshKeyParts()` is extracted as the
single source of truth that both the rendered SQL and a serializable descriptor
derive from, and when the flag is on that descriptor rides in the refresh-key
tuple's options element.

The orchestrator short-circuits it in exactly one place,
`QueryCache.cacheRefreshKeyResult`. #11607 had just made that the sole owner of a
refresh key's cache key, renewal key and threshold, so both consumers — the
scheduler's `loadRefreshKey` and the loader's `keyQueryResult` — are covered
without either being touched. `PreAggregationLoadCache` keeps its per-request memo
wrapping the call, which matters: one pre-aggregation load reads the invalidation
keys several times (`contentVersion`, the returned `refreshKeyValues`, the refresh
queue key), and re-reading the clock could straddle an interval boundary and have
the load look a table up under one content version while enqueueing it under
another. A test pins that by stubbing `Date.now` across a boundary.

Why: the default `{ every: '10 seconds' }` cube refresh key has
`renewalThreshold: 10`, so it is re-issued to Cube Store on essentially every
request. That query has no `TableScan`, so `is_data_select_query` is false and it
takes the `QueryPlan::Meta` path — correctly bypassing `SqlResultCache`, but still
paying parser + plan + optimize + `collect`, plus
`MetaStoreSchemaProvider::new(get_tables_with_path(false))` on every call, plus a
WebSocket round trip. All to learn the wall clock.

Scope: cube-level `cacheKeyQueries` and pre-aggregation `invalidateKeyQueries`,
including the `10 seconds` and `1 hour` defaults. Excluded are `refreshKey.sql`
and `incremental` keys — the latter are wrapped in
`CASE WHEN NOW() < <dateTo + updateWindow>` against an allocated partition-range
param, and their options drive `renewalThresholdOutsideUpdateWindow` shortening
for freshly sealed partitions.

Flag off is byte-identical. The gate is applied at emit time as well as consume
time, so the tuples and every hash derived from them are unchanged and no
persisted cache is invalidated on upgrade. The existing `everyRefreshKeySql`
assertions pass unedited, which is what proves the emitted SQL did not move.

Clock skew is why this is flagged. Two nodes straddling an interval boundary
produce different `contentVersion`s, so the same pre-aggregation gets built twice,
recurring at each boundary. `externalRefresh` bounds the blast radius — non-builder
API instances never run these queries — so a single refresh worker is safe;
multiple workers or `CUBEJS_PRE_AGGREGATIONS_BUILDER=true` API instances are not.
Flipping the flag also forces one pre-aggregation rebuild each way, since `pg`
returns `numeric` as a string and Cube Store as a number. Table names are
unaffected; `getStructureVersion` excludes invalidation keys.

Three things review caught, all fixed here:

- `refreshKeyRenewalThreshold` would have stopped working. On the SQL path that
  option throttles how often the result is re-read, and that is also what bounds
  how often the key advances — a value cached for a day advances daily, whatever
  `every` says. A locally evaluated key has no cache entry to age out, so
  `refreshKeyRenewalThreshold: 86400` with `every: '1 hour'` would have gone from
  ~daily to hourly advancement, roughly 24x the pre-aggregation rebuilds. Local
  evaluation now declines when the override is set, and says so once in the log
  rather than silently doing nothing.
- The flag was wired in two halves. `QueryCache` accepted a `localRefreshKey`
  option while the emitting half read only the environment, and
  `QueryOrchestrator.queryCacheOptions` is typed `any`, so
  `queryCacheOptions.localRefreshKey = true` type-checked and enabled the consumer
  while no descriptor was ever emitted — a silent no-op. The consumer now reads
  the environment only, which makes the half-enabled state unrepresentable. Tests
  toggle `process.env.CUBEJS_REFRESH_KEY_LOCAL_TIME` around construction instead.
- `RefreshScheduler.refreshCubesRefreshKey` exists only to warm the shared
  refresh-key cache, so with the flag on it spent a `getSql` plus an
  `executeQuery` per cube per timezone on a result that is computed locally and
  thrown away. It now skips a cube whose key is locally evaluable. Note it skips
  per cube rather than wholesale: the flag does not make every key local, and a
  cube with a `sql` refresh key still needs warming.

`EvaluatedCube` gained the `refreshKey` field it already carried at runtime, so
the scheduler can narrow on it without a cast.

| Suite | Result |
| --- | --- |
| `cubejs-backend-shared` `test/env.test.ts` | 25/25 |
| `cubejs-query-orchestrator` `test/unit` | 130/130, 6 suites |
| `cubejs-schema-compiler` `dist/test/unit` | 826/831, 39/42 suites |

`server-core` passes `tsc --noEmit`. The five schema-compiler failures are
`error-reporter`, `FILTER_PARAMS` and `pre-agg-interpolated-cube-refs`; all five
reproduce on an unmodified master, verified by reverting this branch's two
schema-compiler files and re-running.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

javascript Pull requests that update Javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants