Skip to content

fix(cubesql): Preserve lastRefreshTime with post-processing and SQL pushdown - #11394

Merged
MazterQyou merged 1 commit into
masterfrom
cubesql/preserve-lastrefreshtime
Aug 3, 2026
Merged

MazterQyou merged 1 commit into
masterfrom
cubesql/preserve-lastrefreshtime

Conversation

@MazterQyou

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

This PR makes the SQL API return lastRefreshTime for queries whose plan has post-processing nodes over the cube scan (calculated projections over MEASURE(), sorts, filters) and for SQL pushdown queries, both of which silently dropped it. Related test is included.

@MazterQyou
MazterQyou requested review from a team as code owners July 28, 2026 11:41
@github-actions github-actions Bot added rust Pull requests that update Rust code javascript Pull requests that update Javascript code labels Jul 28, 2026
@claude

claude Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MazterQyou's task in 4m 54s —— View job


Review complete — approach is sound; 1 medium (external aggregation direction), 3 low/nits, posted as 4 inline comments

Full review — traced the plumbing end to end, findings and verification notes
  • Gather context (read diff + surrounding code)
  • Trace the freshness plumbing end to end (gateway → transport → scan → span → JSONL header)
  • Review Rust changes (scan.rs, service.rs, node_export.rs)
  • Review TS change (gateway.ts)
  • Review tests
  • Post inline comments + summary

Verification

I traced both halves of the fix rather than taking the description at face value:

SQL pushdown path. scan.rs → transport.load(sql_query: Some(..)) → JS sqlApiLoad → gateway's request.sqlQuery branch. Because that branch resolves a plain object (not a ResultWrapper), wrapNativeFunctionWithStream takes the JSON.stringify path (js/index.ts:335), so it lands in ValueFromJs::String → TransportLoadResponseColumnar → convert_transport_response → build_response_schema (transport.rs:478-527, scan.rs:1307). V1LoadResult already has lastRefreshTime/external (v1_load_result.rs:31-38) — they were simply never populated on the pushdown side. Confirms the gateway.ts two-liner is the correct and complete fix for that path.

Post-processing path. Confirmed the mechanism: CubeScanExecutionPlan::execute returns a router whose schema is the batch schema (scan.rs:588-596), so the metadata only reached stream.schema() when the scan was the plan root. A ProjectionExec/SortExec on top rebuilds the schema and drops it. Routing through the span is the right fix, and it also improves the pg-wire path (shim.rs:390, 1878) for free.

Format. Span round-trips through DateTime::parse_from_rfc3339 → to_rfc3339_opts(Millis, true). Since the value originates from JS toISOString(), output is byte-identical to the old schema-metadata path — no observable change for existing consumers. Unparseable values fall back to the schema metadata via or_else, which is correct.

Findings

# Severity Where Issue
1 Medium service.rs:128-140 external aggregates "any wins" while last_refresh_time right above aggregates "oldest wins". A join where one scan hits CubeStore and one hits the source DB reports external: true on a partially-live result. Elsewhere the flag is computed with .all(...) (base_query.rs:84, top_level_planner.rs:56). Needs a tri-state to be conservative — or an explicit note that "any" is deliberate.
2 Low node_export.rs:377-386 The span read happens before the first stream.next(), so it works only because execute is async in this DataFusion fork and parents await children eagerly. Undocumented load-bearing assumption for a header that must be written first. Also, the comment's "every cube scan that ran" isn't true in stream mode (scan.rs:554 never calls load_data) — not a regression, but the comment overstates coverage.
3 Low gateway.ts:2228-2233 disableExternalPreAggregations is set for pushdown queries, so response.external should always be falsy here. Harmless to mirror, but worth a note — the two new tests read as if both true and false are live cases.
4 Nit sql-api-load.test.ts:64-78 No case for a response without lastRefreshTime — the common path, and the one that exercises the ?. and the undefined-is-dropped serialization contract. Plus a stray import * as console.

Also minor, not worth an inline: span_id_for_schema (node_export.rs:306) is a second Arc clone alongside span_id_clone; one clone reused would do.

What's good

  • Test design is deliberate: the plain measure projection case in the parameterized native test is a real control that passed before the fix, so the pair actually isolates the regression rather than just asserting the happy path.
  • The SpanId doc comments explain the aggregation semantics, not just the mechanics — that's what made finding ReferenceError: self is not defined - Issue with whatwg-fetch when using the core lib with Node.js #1 reviewable at all.
  • Fallback ordering (span.or_else(schema)) is the right precedence and keeps plans without a span working.

Not verified

I could not execute either test suite — node_modules is not installed in this checkout and a Rust build wasn't attempted. All findings are from reading code; the ordering analysis in #2 is from tracing execute() call sites, not from running the plans.

· branch `cubesql/preserve-lastrefreshtime`

@codecov

codecov Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.46%. Comparing base (5a47e08) to head (2d70972).

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #11394      +/-   ##
==========================================
+ Coverage   79.43%   79.46%   +0.02%     
==========================================
  Files         480      480              
  Lines       98778    98810      +32     
  Branches     3636     3636              
==========================================
+ Hits        78460    78515      +55     
+ Misses      19800    19774      -26     
- Partials      518      521       +3     
Flag Coverage Δ
cube-backend 59.10% <ø> (+0.10%) ⬆️
cubesql 83.96% <100.00%> (+0.01%) ⬆️

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.

@MazterQyou
MazterQyou force-pushed the cubesql/preserve-lastrefreshtime branch from 5e3ae90 to 34e7db2 Compare July 28, 2026 13:48
@claude

claude Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MazterQyou's task in 1m 59s —— View job


Re-review of the update — all 4 prior findings addressed; 1 new low (external fallback uses || instead of span-precedence)

Full re-review — what changed, verification, and the one new finding
  • Diff the current head against my previous review
  • Check which prior threads are now addressed
  • Re-review the changed code
  • Resolve stale threads / post new finding

Prior findings — all resolved

# Prior finding Status
1 external aggregated "any wins" vs last_refresh_time's "oldest wins" Fixed. SpanId::external is now RWLockAsync<Option<bool>> with *write = Some(write.unwrap_or(true) && external) — the conservative tri-state. span_id_external_only_when_every_load_is_external covers the sticky-false case (true → false → true stays false), which is the part that's easy to get wrong. Doc comment now states the semantics and cross-references usages.iter().all(..).
2 Undocumented eager-child-execution assumption + comment overstated coverage Fixed. The comment in node_export.rs:381-392 now spells out both the async execute dependency ("a node that deferred child execution to first poll would silently empty this header again, and the tests would not catch it") and the stream-mode gap.
3 external unreachable-as-true on the pushdown branch Fixed. gateway.ts:2233-2238 explains the disableExternalPreAggregations chain and that the mirror is for shape parity. The test mock carries the same note.
4 Missing negative test case + stray import * as console Fixed. omits lastRefreshTime when absent added, with a comment tying it to JSON.stringify dropping undefined → Option<String> on the Rust side. Import removed.

Resolved all four threads.

New finding

Low — node_export.rs:412-420: the external schema fallback uses ||, which can undo the aggregation that was just made conservative.

Two blocks up, last_refresh_time uses or_else: span wins outright, schema is consulted only when the span is silent. external ORs them instead, so a span that deliberately folded to false can be overridden by leftover schema metadata.

Reachable case: a UNION of two cube scans, first from a CubeStore pre-aggregation, second live. UnionExec delegates to child streams rather than rebuilding a batch schema, so stream.schema() is the first child's batch schema and still carries external=true. The span correctly says false; the || re-reports external: true alongside lastRefreshTime = min(A, B) — precisely the disagreement the new set_external doc comment argues against.

Fix needs the tri-state to leak out (external() -> Option<bool>, .unwrap_or_else(schema), with shim.rs callers taking .unwrap_or(false)). Details in the inline comment. Narrow in practice, but the two adjacent blocks reading differently is the kind of thing that gets copied.

Fix this →

Also checked, no issue

  • set_external read-modify-write happens under a single write guard, so concurrent loads can't interleave the fold.
  • response.lastRefreshTime?.toISOString() — QueryOrchestrator.ts:262/287 produces a Date, and this matches the existing prepareResultTransformData call at gateway.ts:1935.
  • set_last_refresh_time still only fires on a parseable RFC3339 value while set_external fires on every load; asymmetric but correct — a missing timestamp shouldn't make the span look fresher.
  • span_id_for_schema is still a second Arc clone alongside span_id_clone; cosmetic, not worth a thread.

Not verified

Could not execute either suite — no node_modules in this checkout and no Rust build attempted. The UnionExec schema-delegation claim is from reading the operator's stream handling, not from running a union plan.

· branch `cubesql/preserve-lastrefreshtime`

@claude

claude Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MazterQyou's task in 2m 38s —— View job


Re-review: all 5 prior findings resolved — no new blocking issues; 2 cosmetic nits

Full re-review — what changed, verification notes, and the two nits
  • Diff current head vs. prior review
  • List existing review threads / dedupe
  • Review changed Rust + TS code
  • Resolve stale threads
  • Post findings

Prior findings — status

# Finding Status
1 external aggregated "any wins" vs last_refresh_time's "oldest wins" Fixed — RWLockAsync<Option<bool>> + Some(write.unwrap_or(true) && external), with two unit tests including the sticky-false case
2 Undocumented eager-child-execution assumption; comment overstated coverage Fixed — node_export.rs:381-396 now spells out both the async execute dependency and the stream-mode gap
3 external unreachable-as-true on the pushdown branch Fixed — gateway.ts:2234-2239 explains the disableExternalPreAggregations chain; test mock carries the same note
4 Missing negative test case + stray import * as console Fixed — omits lastRefreshTime when absent added; import removed
5 external schema fallback used ||, undoing the conservative fold Fixed — SpanId::external() now returns Option<bool>; node_export.rs:415 uses .unwrap_or_else(…), matching the or_else precedence used for lastRefreshTime two blocks up

Resolved the one remaining stale thread (#5).

Verification of the #5 fix

Checked that leaking the tri-state didn't strand any caller: SpanId::external() has exactly one non-test consumer (node_export.rs:401). The shim.rs sites (390, 1878) only read last_refresh_time(), so no .unwrap_or(false) was needed there — the earlier suggestion overestimated the blast radius. set_external's read-modify-write is still under a single write guard, so concurrent loads can't interleave the fold.

Re-confirmed the two paths behave as documented:

  • Single scan — span reports the same value the batch schema would have, so the header is byte-identical to before.
  • Multi-scan (join/union) — span folds to false and now wins outright over stale first-child schema metadata. lastRefreshTime = min(A, B) and external = false agree.
  • No load at all (SELECT 1) — span silent → None → schema fallback → false. Unchanged.

Nits (not worth inline threads)

  1. node_export.rs:378 — "The stream schema is only a fallback for plans with no span" is slightly off for this call site: span_id is unconditionally Some(...) at line 247, so the fallback is reached only when the span is silent, never when it's absent. The comment says the accurate thing 15 lines later ("consulted only when the span was silent"); the earlier sentence just contradicts it.
  2. node_export.rs:504 — the query-completed event logs lastRefreshTime but not external. Now that the span carries both, including it would make the log line match the JSONL header. Optional.

Also still true from the first pass: span_id_for_schema is a second Arc clone alongside span_id_clone; both are moved into the same closure so both are needed as written — cosmetic only.

What's good

  • The tri-state now reads consistently in all three places it matters (fold, accessor, fallback), and the doc comments explain why rather than what, which is what made Add support for AWS Athena in JDBC driver #5 findable in the first place.
  • span_id_external_only_when_every_load_is_external tests the true → false → true sequence, which is the part a naive && on a bool field would get wrong.
  • The negative gateway test pins the undefined-is-dropped serialization contract against the Rust Option<String>, not just the happy path.

Not verified

Neither suite was executed — node_modules is absent in this checkout and no Rust build was attempted. All conclusions are from reading code. The multi-scan behaviour described above is traced from the operators' schema handling, not from running a join or union plan.

· branch `cubesql/preserve-lastrefreshtime`

… pushdown

Signed-off-by: Alex Qyoun-ae <4062971+MazterQyou@users.noreply.github.com>
@MazterQyou
MazterQyou force-pushed the cubesql/preserve-lastrefreshtime branch from 4340f76 to 2d70972 Compare August 3, 2026 15:00
@claude

claude Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MazterQyou's task in 1m 17s —— View job


Re-review after rebase: no code changes since the last pass — all 5 findings still resolved, nothing new blocking

Full re-review — what changed, verification notes, remaining nits
  • Diff current head vs. prior review
  • List existing review threads / dedupe
  • Review changed Rust + TS code
  • Resolve stale threads
  • Post findings

What changed

The branch was rebased onto current master (head is now 2d70972, previously 4340f76). Diffing origin/master...HEAD across all six files, the content is byte-identical to what I reviewed at 14:19 — no new commits touching the fix. All five prior findings remain fixed:

# Finding Status
1 external aggregated "any wins" vs last_refresh_time's "oldest wins" Fixed — RWLockAsync<Option<bool>> + Some(write.unwrap_or(true) && external)
2 Undocumented eager-child-execution assumption; comment overstated coverage Fixed — node_export.rs:377-396
3 external unreachable-as-true on the pushdown branch Fixed — gateway.ts:2233-2238
4 Missing negative test case + stray import * as console Fixed — omits lastRefreshTime when absent
5 external schema fallback used || Fixed — SpanId::external() -> Option<bool> + .unwrap_or_else(…)

All five review threads are already resolved (checked via gh list-review-threads); nothing stale left to close, and no new inline comments — the two items below are cosmetic and don't warrant threads.

New verification this pass

I checked the one claim in the new native test I hadn't traced before — that LIMIT 10 pins both queries to the buffered path even under CUBESQL_STREAM_MODE=true. scan.rs:528-532 computes stream_mode as (true, None) => true, (true, Some(limit)) if limit > query_limit => true, _ => false. With non_streaming_query_max_row_limit well above 10, both parameterized queries fall to false and go through load_data, which is what populates the span. The test comment's reasoning holds, and the explicit LIMIT is load-bearing rather than incidental — worth keeping if anyone edits those SQL strings later.

Also re-confirmed, unchanged from before:

  • set_external's read-modify-write is under a single write guard, so concurrent loads can't interleave the fold.
  • SpanId::external() has exactly one non-test consumer (node_export.rs:401); the shim.rs sites only read last_refresh_time(), so leaking the tri-state stranded no caller.
  • Single scan → span reports what the batch schema would have, header byte-identical to before. Multi-scan → span folds to false and wins outright. No load at all → None → schema fallback → false.

Remaining nits (carried over, still not worth threads)

  1. node_export.rs:378 — "The stream schema is only a fallback for plans with no span" is slightly off for this call site: span_id is unconditionally Some(..) at line 247, so the fallback is reached only when the span is silent, never absent. The comment says the accurate thing 15 lines later.
  2. node_export.rs:501 — the query-completed log event carries lastRefreshTime but not external. Now that the span holds both, including it would make the log line match the JSONL header.

Not verified

Neither suite was executed — no node_modules in this checkout and no Rust build attempted. All conclusions are from reading code; the multi-scan behaviour is traced from the operators' schema handling, not from running a join or union plan.

· branch `cubesql/preserve-lastrefreshtime`

@MazterQyou
MazterQyou merged commit 3728d62 into master Aug 3, 2026
193 of 197 checks passed
@MazterQyou
MazterQyou deleted the cubesql/preserve-lastrefreshtime branch August 3, 2026 16:41

This branch was successfully deployed

1 active deployment
Preview — 2d70972d Deployed Aug 3, 2026 by vercel[bot]
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 rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants