Skip to content

Implement clone for the query result cache steps - #130375

Merged
alexey-milovidov merged 4 commits into
masterfrom
query-result-cache-steps-clone
Nov 14, 2026
Merged

alexey-milovidov merged 4 commits into
masterfrom
query-result-cache-steps-clone

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Related: #102192
Related: #107924

Split out of #102192 (part 3 of 6).

With query_cache_for_subqueries = 1 an IN subquery plan contains StreamInQueryResultCacheStep (write path) or is replaced by ReadFromQueryResultCacheStep (cache hit). Neither implemented clone, so FutureSetFromSubquery::buildOrderedSetInplace took the destructive fallback (see #107924), where a silent in-place build failure still leads to the "Not-ready Set is passed as the second argument" exception.

  • StreamInQueryResultCacheStep::clone gives the clone its own copy of the QueryResultCacheWriter (a shared writer would buffer the rows twice into one entry).
  • The QueryResultCacheWriter copy now carries over query_start_time. On the successful in-place build path the copy is the only writer that is finalized, so otherwise query_cache_min_query_duration would be measured from the clone point.
  • ReadFromQueryResultCacheStep keeps its SourceFromChunks and clones them with the new SourceFromChunks::clone, which shares the immutable columns.
  • Tests: 04648_not_ready_set_with_query_result_cache_subquery (write and read path), 04652_query_result_cache_subquery_clone_min_query_duration, 04653_query_result_cache_subquery_clone_skip_insert.

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

IN subqueries cached with query_cache_for_subqueries can now recover when the speculative set build for primary key analysis stops early, instead of failing with "Not-ready Set".

🤖 Generated with Claude Code


Workflow [PR]
Sync PR [sync-upstream/pr/130375]

Version info

  • Merged into: 26.11.1.2304-master (included in 26.11 and later)

Split out of #102192.

With `query_cache_for_subqueries = 1` an `IN` subquery plan contains
`StreamInQueryResultCacheStep` (write path) or is replaced by
`ReadFromQueryResultCacheStep` (cache hit). Neither implemented `clone`, so
`FutureSetFromSubquery::buildOrderedSetInplace` took the destructive fallback
(see #107924), where a silent
in-place build failure still leads to the "Not-ready Set is passed as the
second argument" exception.

- `StreamInQueryResultCacheStep::clone` gives the clone its own copy of the
  `QueryResultCacheWriter`.
- The `QueryResultCacheWriter` copy now carries over `query_start_time`, so
  `query_cache_min_query_duration` is not measured from the clone point. On the
  successful in-place build path the copy is the only writer that is finalized.
- `ReadFromQueryResultCacheStep` keeps its `SourceFromChunks` and clones them
  via the new `SourceFromChunks::clone`, which shares the immutable columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1532610]

Summary: ✅


AI Review

Summary

Adds cloning for query result cache plan steps so cached IN subqueries can retry speculative set construction without consuming their original plans. Request changes because the main recovery test also succeeds without the new cloning support, leaving the central behavior unprotected against regression.

Findings

⚠️ Majors

  • 04648_not_ready_set_with_query_result_cache_subquery.sql:36: The injected failure depends on cloning already working. CreatingSetsTransform::generate checks prepared_sets_build_ordered_set_inplace_fail only for a recoverable build, while the non-clonable fallback in FutureSetFromSubquery::buildOrderedSetInplace passes recoverable_build = false. Without the new clone overrides, both queries skip the failure injection and still satisfy the result and cache-hit assertions. Those assertions therefore do not establish recovery after a failed speculative build.
Tests
  • ⚠️ Strengthen 04648 to establish that the speculative attempt failed and a subsequent attempt successfully built the set, on both cache paths. Each case should fail when its corresponding clone override is removed. On the write path, QueryCacheWrittenRows can distinguish buffering the subquery once from buffering it in both attempts.
Missing context / blind spots
  • ⚠️ Targeted CI for head 15326105db7b55ccba08756a9d24d57cdac1ccbc is pending. The three added tests passed on preceding head f300ac3c3d6e1c240d85f100a5497f1642a0764d in the targeted ASan/UBSan distributed-plan job. Completion of the current head's jobs closes this validation gap. No local runtime tests were run.
Final Verdict

Status: ⚠️ Request changes. The minimum required change is to make the recovery regression test detect missing cloning support and prove that the failed attempt was retried.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Nov 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 15326105d with master cb1a0d516 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

10 object files changed (+43.72 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/Sources/SourceFromChunks.cpp.o 29.20 KiB 55.16 KiB +25.96 KiB (+88.93%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.60, programs/clickhouse-keeper ×0.73 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 5.8 s 9.4 s +5.9 s (+168%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.4 s 7.2 s +5.1 s (+250%)
Compile time of recompiled translation units

24 translation units recompiled, 174 s compile time in total, 24 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -16.2 s (-9%) in total before that adjustment.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The failures in Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) (Unknown query plan step: StreamInQueryResultCache in 04648, 04652, 04653) happened because the parallel-replicas remote plan serialized the IN subquery plan, which contained the query result cache step. Now that the step can be cloned, that subquery plan is no longer consumed in place, so it was still there to serialize. #130376 (merged into master) stops the Planner from adding the cache steps to plans that are shipped to replicas. I merged master into this branch. Locally, on the merged tree, all three tests match their references, both with default settings and with serialize_query_plan = 1, parallel replicas and the randomized settings from the failed CI run.

alexey-milovidov added a commit that referenced this pull request Nov 11, 2026
…in Fast test

With `use_index_for_in_with_subqueries = 1` the set for the `IN` subquery is
built speculatively during primary key analysis by
`FutureSetFromSubquery::buildOrderedSetInplace`. That build distributes only a
clone of the set source, and `StreamInQueryResultCacheStep` has no `clone` yet
(see #130375), so it fell back to
running the original source locally and wrote the cache entry, making the
"distributed" case report 1 instead of 0.

The test is about the set source conversion of the deferred build, so disable
the speculative build.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=130377&sha=latest&name_0=PR&name_1=Fast%20test
PR: #130377

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check on d877d0ff was Build profile diff, which failed with LogClusterNotReady: the endpoint never became ready — a CI logs cluster outage unrelated to this change; it is being addressed in #129675. I merged the latest master into the branch. On the merged tree the build succeeds, and 04648, 04652 and 04653 match their references against a local server.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only failure on f300ac3c, Stress test (arm_asan_ubsan), was a heap-use-after-free in DeltaLakeMetadataDeltaKernel::prepareReadingFromFormat (ColumnsDescription::rename called while iterating the same ColumnsDescription). It is unrelated to this PR and already fixed on master by 0e08178 ("Fix use-after-free on renaming Delta Lake columns to their physical names"), so I merged master (1532610) to pull the fix in.

-- analysis; the preserved (cloned) source lets the deferred build recover and produce the correct
-- result. The subquery matches k in [0, 10), so the outer count is 10.
SYSTEM ENABLE FAILPOINT prepared_sets_build_ordered_set_inplace_fail;
SELECT count() FROM t_qrc_in WHERE k IN (SELECT k FROM t_qrc_in WHERE k < 10);

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.

[Major] The failure injection is conditional on the functionality this test is meant to guard. CreatingSetsTransform::generate checks prepared_sets_build_ordered_set_inplace_fail only when recoverable_build is true, whereas the non-clonable fallback in FutureSetFromSubquery::buildOrderedSetInplace passes false. Without the two new clone overrides, both queries therefore skip the injected failure, build their sets successfully, and satisfy the existing result and cache-hit assertions. This leaves the main recovery behavior without a regression test that detects its removal.

Please assert that a speculative attempt actually failed and a subsequent attempt rebuilt the set, for both cache paths. For the write case, QueryCacheWrittenRows can distinguish buffering the subquery once from buffering it in both attempts. The relevant case should fail when its clone override is removed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The bug is already fixed, but we can keep the test just in case.

@alexey-milovidov alexey-milovidov self-assigned this Nov 14, 2026
/// writer that is ever finalized - and restarting the timer there would make cache eligibility depend
/// on the plan shape: a subquery would silently stop populating the cache just because its plan became
/// clonable.
, query_start_time(other.query_start_time)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Amazing finding!

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 14, 2026
Merged via the queue into master with commit 0c359f0 Nov 14, 2026
205 checks passed
@alexey-milovidov
alexey-milovidov deleted the query-result-cache-steps-clone branch November 14, 2026 14:01
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 14, 2026
valerypetrov pushed a commit to valerypetrov/ClickHouse that referenced this pull request Nov 16, 2026
…l replicas

The subquery query result cache is not used with plan-based parallel replicas,
ClickHouse#131463. `04648` and `04652` came with
ClickHouse#130375, after the other cache tests were pinned in
ClickHouse#131464.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants