Repository navigation
fix(query-orchestrator): key refresh key cache entries consistently - #11607
Conversation
|
Claude finished @ovr's task in 3m 57s —— View job Review complete — solid fix; 2 medium notes, 2 low, posted inlineFull review
VerdictThe diagnosis holds up. Two things deserve a mention in the description before merge; neither is a blocker. Findings
Nit (not worth a thread): TestsGood coverage, and the "verified load-bearing" claim checks out by inspection:
Missing scenario worth adding: The note about Security / performanceNo 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 — |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
38c23dd to
5e3f19c
Compare
|
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
What changed in this pushNothing in the code. The push was a rebase onto the new
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: Standing findings — re-affirmed, not re-postedBoth 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.
The core verdict is unchanged: the diagnosis is right ( Still the only substantive ask before merge: a test pinning Security / performanceUnchanged 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 |
5e3f19c to
18666ad
Compare
|
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
What changed in this pushUnlike 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:
The core verdict is unchanged and still holds: Standing findings — re-affirmed, not re-postedBoth inline threads are still unresolved and still land on the exact current lines, so per the dedup rule I did not post copies.
Nothing to resolve — neither thread is stale. Asks before merge (unchanged)
TestsStill good, still load-bearing by inspection. Reminder from the last pass, still true: Security / performanceNo 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. |
18666ad to
5843f0b
Compare
|
Claude finished @ovr's task in 3m 42s —— View job Re-review after synchronize — new
|
| 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:
- Adding
externalto the identity is an independent correctness fix.cacheQueryResultroutes onexternal: 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 bothfalseand absent, andJSON.stringifywould otherwise hash those tofalsevsnull.a refresh key resolved against each engine gets its own cache entrypins exactly this. - 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 policyis the sharpest addition — it asserts the positive (differingoptionsstill hit), the normalization (externalabsent ≡external: false), and the negative (external: trueis 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 entryasserts through the drivers (executedQuerieson 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— theLocalCacheDriver.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 synchronouslydiscriminates onrefreshKeyValues.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.
5843f0b to
0d864c4
Compare
|
Claude finished @ovr's task in 3m 3s —— View job Re-review after synchronize — the fix is now enforced by construction (
|
| 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)
- A test pinning
invalidateKeyQueries: []+externalRefresh— finding MUTEX for requests #2 is the one case where the guard changes behavior that exists today. Fix this → - 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).
- Either fold
dataSourceintorefreshKeyIdentityor 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.
`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>
0d864c4 to
ebf4e9c
Compare
|
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 nitFull review
What changed in this pushEssentially nothing behavioral. Compared with the revision I reviewed at 11:06 UTC, The design still holds up and is the strongest shape this PR has had:
Original diagnosis unchanged: the memo branch has been unreachable since the third tuple element appeared in #3061, excluding the policy element is right because Naming nit (not worth an inline thread)In this file's vocabulary the unhashed tuple is the Standing findings — re-affirmed, not re-postedBoth 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.
Asks before merge (unchanged)
TestsUnchanged from the last revision apart from
The Security / performanceNo 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: |
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 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 nitsFull review
What changed in this pushThree real edits on top of the revision I reviewed at 11:12 UTC, none of which change behavior:
The regrouped condition is equivalent, and better. I walked the combos: The thunk is a genuine (if small) win too: hashing now happens only on the one path that consults it, so
The Key-space re-check after
|
| # | 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)
- A test pinning
invalidateKeyQueries: []+externalRefresh— finding MUTEX for requests #2 is the one case where the guard changes behavior that exists today. Fix this → - 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).
- Either fold
dataSourceintorefreshKeyIdentityor 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 policyremains the sharpest: positive (differingoptionsstill hit), normalization (externalabsent ≡false), negative (external: truediffers) in one place.a refresh key resolved against each engine gets its own cache entryasserts throughexecutedQuerieson each driver rather than through the key — the right level.both refresh key paths store the same renewal keyno longer discriminates the way it once did, since one code path now writes the entry; keep it as a divergence guard, butRefreshKeyCacheOptionsis the real protection.mockExternalDriverFactoryhas acreateTableside effect per invocation, somockExternalDriver.tablesis non-empty in tests touching the external queue — harmless here, but don't assert on it the way theexternalRefreshtest asserts onmockDriver.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.
`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 finished @ovr's task in 3m 31s —— View job Re-review after synchronize —
|
| 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.
keyQueryResultandhasKeyQueryResultboth passthis.dataSource(PreAggregationLoadCache.ts:194,:212), and that field is already the normalized value —PreAggregations.ts:528-541keys load caches bydataSourceand 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 thatrefreshKeyIdentitynow collapses.loadRefreshKeypassesoptions.dataSource, whichloadRefreshKeysFromQueryforwards raw fromquery.dataSource(QueryCache.ts:928-936) — precisely the absent case the|| 'default'normalization and thean absent data source hashes as defaulttest exist for. - Build-range write/read stay symmetric. Both sides read the parent descriptor — write at
PreAggregationPartitionRangeLoader.ts:89(this.preAggregation), read atPreAggregations.ts:635(queryBody.preAggregations[]) — so they see the samedataSource, and the partition descriptor spreads...this.preAggregation(PreAggregationPartitionRangeLoader.ts:200) so nothing rewrites it mid-flight. Same reasoning asexternallast pass. - No external callers.
refreshKeyIdentity/refreshKeyCacheKey/cacheRefreshKeyResult/buildRangeInvalidateKeyare grep-clean outside this package, so the signature changes are internal. @AsyncDebouncedoesn'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:asyncDebounceFnhashesargs.map(JSON.stringify).join(',')(packages/cubejs-backend-shared/src/promises.ts:284-287), which includes the whole options object, sodataSourceparticipates.external: cacheKey[2]replacingqueryOptions?.externalis a safe tightening —undefinedandfalseare both falsy at theexternal ? externalQueue : queuefork, 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 entryasserts throughmockDriver.executedQueries(two executions of the same SQL) rather than through the key — same right-level choice as theexternaltest, and it would survive a rewrite of the key derivation.an absent data source hashes as defaultis the one that pins the|| 'default'normalization, which is the subtle half of this commit — without it,loadRefreshKeysFromQueryforwarding an absentdataSourceand 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 eithercovers boththrowOnMissingPartitionpolarities and assertsmockDriver.tables === []. ThepreAggOverridesparameter added tocreatePreAggLoaderis the minimal way to get there.refresh key identity covers sql, params and engine, but not policyremains the sharpest of the set — positive, normalization, and negative in one place.- Trap noted before, still true:
mockExternalDriverFactorycallscreateTableon every invocation, somockExternalDriver.tablesis non-empty in tests touching the external queue — don't assert on it the way theexternalRefreshtests assert onmockDriver.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.
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 finished @ovr's task in 1m 50s —— View job Re-review after synchronize — comment trimming plus a
|
| 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
invalidateKeyQuerieswhilegetPartitionInvalidationKeyValuesresolvespartitionInvalidateKeyQuerieswhen set (ksqlDB), so awaitForRenew: falserequest can enter the inline path on warm keys and then block on cold ones. - The warm path returns real
refreshKeyValueswhere the deferred path returned[], which changes whatusedPreAggregationsmetadata exposes on non-waitForRenewresponses. 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
buildRangeInvalidateKeyitself — 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.jsis still not matched bytestMatch: ['<rootDir>/test/**/*.test.ts'], so its edits in this PR are correct but unexecuted. A follow-up issue to widentestMatchor 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.
| } | ||
|
|
||
| public queryRedisKey(cacheKey: CacheKey): string { | ||
| public queryCacheKey(cacheKey: CacheKey): string { |
There was a problem hiding this comment.
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)); // hashIt 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).
…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>
…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>
Check List
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
PreAggregationLoadCachecould never hit, so everywaitForRenew: falserequest took the deferred path; the refresh scheduler and the pre-aggregationloader marked each other's entry stale whenever a cube
refreshKeyand a pre-aggregationinvalidateKeyQueryresolved to the same SQL; and the same SQL run against different engines ordifferent 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 oneplace (
QueryCache.refreshKeyIdentity) and applied by one helper (cacheRefreshKeyResult) thatowns 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
Bug 1 — the load cache memo could never hit
PreAggregationLoadCachelives for one request and memoizes resolved refresh key values so thatseveral partitions or pre-aggregations do not each re-run the same SQL.
Both sides now go through
refreshKeyCacheKey()->refreshKeyIdentity(), so they agree onH.Bug 1, consequence — a dead branch in
loadPreAggregationOn a live request against a partitioned rollup:
Re-enabling that branch needed a guard, which also closes a hole that exists on master today:
Bug 2 — renewal key ping-pong between the scheduler and the loader
When a cube level
refreshKeyand a pre-aggregationinvalidateKeyQueryresolve to the same SQL,both paths write the same cache entry with a different
renewalKey, anddecideCacheActiontreats
entry.renewalKey !== renewalKeyas a reason to re-fetch.The same mismatch also disqualifies the in-memory entry (
isMemoryEntryUsablerequires equalitytoo), so the miss was doubled.
Bug 3 — entries collided across engines and across data sources
cacheQueryResultroutes a refresh key query on two dimensions —externalpicks the engine,dataSourcepicks the queue and the driver — and the cache prefix separates tenants, not datasources. Neither dimension was in the key.
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 tokeep it identical to the other. There is now one definition.
Also in this series:
QueryCache.queryRedisKeyis renamed toqueryCacheKey— the cache driver hasnot been Redis-specific since the driver abstraction landed. Mechanical, byte-identical output, no
entry moves.
LocalQueueDriverConnection.queryRedisKeykeeps its name: it builds queue keys, notcache keys.
Verification
Confirmed end to end against a live Cube instance over Postgres with a partitioned rollup
(
orders_by_status, three monthly partitions, refresh keyevery: 1 day):usedPreAggregations[].refreshKeyValues[[],[],[]]must-revalidate[[{refresh_key:20685}]]x3[[{refresh_key:20685}]]x3Eight new tests in
PreAggregations.test.ts, each verified load-bearing against the branch with itsown fix reverted — including the two
externalRefreshguard tests, which fail if the cache key isfixed without the guard.
Notes for the reviewer: this is rebased on #11608, which removed the now-dead
Array.isArraynormalization in the same functions but left
hasKeyQueryResultuntyped and still hashing the wholetuple, so the two changes are complementary rather than overlapping. Tests live in
PreAggregations.test.tsbecauseQueryOrchestrator.test.jsis not matched bytestMatch: ['<rootDir>/test/**/*.test.ts']and never runs; its call sites are updated anyway, andrun 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[*].refreshKeyValuesserializes raw nativeResultWrapperinternals(
isWrapper,cache,rootResultObject) instead of plain rows — it reproduces on master viacache: 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
@AsyncDebounceand the in-memory cache;old entries age out on their own (1h / 24h TTLs).