Skip to content

Enable read_in_order_use_virtual_row by default - #106215

Merged
alexey-milovidov merged 65 commits into
masterfrom
fix-52624-read-in-order-virtual-row-default
Aug 18, 2026
Merged

alexey-milovidov merged 65 commits into
masterfrom
fix-52624-read-in-order-virtual-row-default

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #52624

When reading in order of the primary key over many parts (the optimize_read_in_order optimization), the merging pipeline opens one reader per part to feed the MergingSortedTransform, and keeps a CompressedReadBuffer per column resident for every one of them. With a large number of parts this makes even ORDER BY pk LIMIT n consume memory proportional to the number of parts, even though only a few of them can contribute to the result. The original report describes a query needing ~42 GB for this reason (1803 parts × 3 columns × 8 MB compress blocks).

The read_in_order_use_virtual_row optimization lets MergingSortedTransform reprioritize sources using primary key values taken from the sparse index, so the parts that cannot contribute to the answer are never read and their readers are never created. The optimization already existed but was disabled by default; this change enables it.

Measured on a table with 300 parts and an 8 MB compress block size, the peak memory of SELECT * FROM t ORDER BY k LIMIT 10 drops from ~700 MB to a few MB.

Related issues: #53101, #53287, #7413 (closed), and #89638 (open) describe the same underlying behavior.

Note: the more aggressive read_in_order_use_virtual_row_per_block (which also disables read_in_order_use_buffering and the preliminary merge) is intentionally left disabled by default, since it trades some parallelism for the extra memory savings.

Update. The first CI run showed consistent 1.3x–5x slowdowns in read-in-order perf tests (distinct_in_order, optimize_sorting_for_input_stream, read_in_order_many_parts, monotonous_order_by, redundant_functions_in_order_by) on both architectures. The cause: a source that starts with a virtual row is not read until the merge reaches its key, so the merge requests deferred sources strictly one by one and reading degrades to a single thread (locally, SELECT DISTINCT over 100M rows ran at the same speed with max_threads=1 and max_threads=16). This was addressed by letting deferred sources read ahead: without a LIMIT a window of number of threads deferred sources, and with a LIMIT only sources provably needed soon (those whose virtual row is not greater than the key at which the merge must stop within an already-read chunk).

Update 2. The second perf run and review showed that the "provably needed" rule for the LIMIT case was wrong in both directions:

  • it was unbounded: with many overlapping parts, every deferred source whose virtual row preceded the merge stop row was scheduled at once, which could re-create the O(parts) resident-reader memory issue this PR fixes;
  • it was still too conservative: with a selective filter (SELECT * FROM hits WHERE UserID = ... ORDER BY pk LIMIT 100), filtered chunks rarely reach the merge, the proof never arrives, and reading degrades to a single stream again — order_by_read_in_order showed 3.3x–4.7x and lazyMaterialization 1.9x–2.5x slowdowns on both architectures.

Both are fixed by making the read-ahead window unconditional: the merge always keeps the next number of threads deferred sources (in the order it will need them) reading ahead, with or without a LIMIT. Under a LIMIT the read-ahead is speculative — the merge may finish before reaching a prefetched source — but the number of speculative readers is bounded by O(threads). A released source can additionally retain chunks under the pre-existing BufferChunksTransform limits; peak reader memory nevertheless stays bounded by the window instead of the number of parts: the 300-part LIMIT 10 query above runs with ~7 MB peak memory and reads only the window's first chunks, vs ~1.3 GB and a full read without the optimization. Pending read-ahead is dropped as soon as the merge finishes, so a query that already produced its LIMIT does not start new reads.

Changelog category (leave one):

  • Performance Improvement

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

Enable read_in_order_use_virtual_row by default. When reading in order of the primary key (e.g. ORDER BY primary_key LIMIT n) over a table with many parts, only the parts that can actually contribute to the result are read (plus a read-ahead window of at most max_threads parts that keeps reading parallel), which significantly reduces peak memory consumption.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.8.1.1592 (included in 26.8 and later)

Fixes #52624.

When reading in order of the primary key over many parts (the
`optimize_read_in_order` optimization), the merging pipeline opens one
reader per part for the `MergingSortedTransform` and keeps a
`CompressedReadBuffer` per column resident for each of them. With a large
number of parts this makes even `ORDER BY pk LIMIT n` consume memory
proportional to the number of parts, although only a few of them can
contribute to the answer.

`read_in_order_use_virtual_row` lets `MergingSortedTransform` reprioritize
sources using primary key values taken from the sparse index, so the parts
that cannot contribute are never read and their readers are never created.
The optimization already existed but was disabled by default; this commit
enables it.

On a table with 300 parts and an 8 MB compress block size, the peak memory
of `SELECT * FROM t ORDER BY k LIMIT 10` drops from ~700 MB to a few MB.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8244319]

Summary: ✅


AI Review

Summary

This PR flips read_in_order_use_virtual_row on by default and adds a bounded read-ahead window so read-in-order queries over many parts stop opening every reader eagerly while still avoiding the single-stream slowdown that the first revision introduced. I re-read the current diff and all prior PR discussion threads against the current head, and I did not find any surviving correctness, safety, or performance-contract issues that still warrant an inline review comment.

Final Verdict

✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.10% 79.20% +0.10%

Changed lines: Changed C/C++ lines covered: 160/167 (95.81%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label May 31, 2026
alexey-milovidov and others added 3 commits June 2, 2026 14:13
…ests

Enabling `read_in_order_use_virtual_row` by default adds `VirtualRowTransform`
nodes to the `EXPLAIN PIPELINE` output of in-order reads over multiple parts.
The tests `04105_limit_by_into_sort_explain` and `04052_explain_pipeline_distributed`
inspect the pipeline shape of other optimizations (the `LIMIT BY` into sort
optimization and distributed pipeline explain), where the virtual row transform is
incidental noise. Pin `read_in_order_use_virtual_row = 0` in these tests so their
references stay focused and deterministic, matching the existing precedent in
`03257_reverse_sorting_key`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master into the branch (it was 573 commits behind).

The only CI failure was the Build (arm_tidy) job, which failed on an unrelated pre-existing issue in src/Processors/Formats/Impl/BinaryRowInputFormat.cpp:177 (variable 'is_default' is not initialized [cppcoreguidelines-init-variables]). That was already fixed in master by b533bbfa52904 ("Fix tidy build in master"), so the merge picks it up.

The merge produced no conflicts; the read_in_order_use_virtual_row default flip and the SettingsChangesHistory entry (in the 26.6 block) are intact.

Verified locally on a freshly built binary:

  • 04303_read_in_order_memory_issue_52624 — PASS (only a small number of rows is read with the optimization enabled by default).
  • 04105_limit_by_into_sort_explain — PASS.
  • 04052_explain_pipeline_distributed — the PR-modified portion matches; the only divergence is the parallel-replicas section that needs the predefined test_cluster_one_shard_two_replicas cluster from the full test harness (an environment artifact of my minimal local server, not a test problem).

alexey-milovidov and others added 2 commits June 7, 2026 02:20
The merge with master pulled in two `SettingsChangesHistory` entries for
`query_plan_min_columns_for_join_lazy_indexing` and
`query_plan_max_limit_for_join_lazy_indexing`. These came from the
"Lazily apply selector and replication indexes in join" change that was
later reverted on master, so the corresponding settings no longer exist.
Applying `compatibility` walks the history and tries to restore old
values for every listed setting; entries for non-existent settings make
the `compatibility`-related stateless tests fail. Drop the orphans.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master (was 451 commits behind and red) and fixed the Fast test failures.

Root cause of the 14 Fast test failures (all compatibility-related: 02324_compatibility_setting, 02325_compatibility_setting_2, 03243_compatibility_setting_with_alias, 03916_check_settings_constraints_erases_with_compatibility, 04078_settings_constraints_compatibility_const, 02933_replicated_database_forbid_create_as_select, etc.): a previous merge of master left two orphaned SettingsChangesHistory entries — query_plan_min_columns_for_join_lazy_indexing and query_plan_max_limit_for_join_lazy_indexing. Those settings came from "Lazily apply selector and replication indexes in join", which was reverted on master, so the settings no longer exist. applyCompatibilitySetting walks the history and calls resolveName/get/set for every listed setting, so any query with compatibility < 26.6 threw Unknown setting. Removed the two orphan entries.

Verified locally against a freshly built binary: the formerly-failing compatibility tests (02324, 02325, 03243, 04234, 02970, 03274, 04209) now pass, along with 04303_read_in_order_memory_issue_52624 and 04105_limit_by_into_sort_explain. (04052 only diverged locally because my standalone server lacks the test_cluster_one_shard_two_replicas cluster used by its parallel-replicas query; it passes in CI.)

No unresolved review threads.

@clickhouse-gh

clickhouse-gh Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 34 analysed

This PR enables read_in_order_use_virtual_row by default and adds a bounded read-ahead window to MergingSortedTransform, which only affects ORDER BY primary-key reads with LIMIT over many parts. ClickBench Q23 (SELECT ... ORDER BY EventTime LIMIT 10) is ×2.2 faster — a clean on-path win from reading only the relevant parts. The uniform ~15% shifts across the GROUP BY aggregation queries (Q13, Q15-Q18, Q30, Q31) and the Q28 regression are off the changed code path and were downgraded to not-sure as variance. TPC-H Q7 (×8.6 faster) and Q8 (×2.2 faster) show large, consistent deltas the math locks in, but they are join/aggregation queries with no obvious read-in-order LIMIT path, so those wins are worth an independent sanity check.

clickbench

🟢 1 improved · ⚠️ 8 inconclusive

Flagged queries (9 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 167 75 ×2.2 faster <0.0001 io: Q23 is a filtered ORDER BY EventTime LIMIT 10 across many parts — exactly the read-in-order path this PR accelerates, so ×2.2 faster is a plausible on-path win from reading only relevant parts.
⚠️ 13 not_sure 426 348 -18.5% <0.0001 aggregation: Q13 is a GROUP BY aggregation (ORDER BY count() DESC), not an ORDER BY primary-key read, so this PR's read-in-order change cannot cause the -18.5% shift; off-path variance.
⚠️ 15 not_sure 193 164 -15.0% <0.0001 aggregation: Q15 is a GROUP BY UserID aggregation, not a merging-sorted read-in-order path, so the -15.0% delta cannot come from this PR; treating it as run-to-run variance.
⚠️ 16 not_sure 793 634 -20.0% <0.0001 aggregation: Q16 is a GROUP BY aggregation; the changed code only affects ORDER BY primary-key LIMIT reads, so -20.0% here is off-path and not attributable to this PR.
⚠️ 17 not_sure 556 461 -17.1% <0.0001 aggregation: Q17 is a GROUP BY aggregation with no primary-key ordered read, so the -17.1% shift is off the changed path; downgrading to not-sure.
⚠️ 18 not_sure 1298 1092 -15.8% <0.0001 aggregation: Q18 is a GROUP BY aggregation; this PR's read-in-order optimization cannot touch it, so -15.8% is off-path variance.
⚠️ 28 not_sure 1048 1144 +9.2% <0.0001 aggregation: Q28 is a GROUP BY aggregation with a regex, not a read-in-order path, so the +9.2% regression is off-path; the source samples were also noisy. Downgrading to not-sure.
⚠️ 30 not_sure 279 238 -14.5% <0.0001 aggregation: Q30 is a GROUP BY aggregation; the merging-sorted change cannot affect it, so -14.5% is off-path variance.
⚠️ 31 not_sure 395 335 -15.2% <0.0001 aggregation: Q31 is a GROUP BY aggregation with no primary-key ordered read, so -15.2% is off the changed path; downgrading to not-sure.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 574 67 ×8.6 faster <0.0001 ×8.6 faster is a large delta the math locks in, but Q7 is a join/aggregation query with no ORDER BY primary-key LIMIT read, so attribution to this PR is unclear and worth a sanity check.
🟢 8 improvement 175 78 ×2.2 faster <0.0001 ×2.2 faster and consistent across both tests, but Q8 is a join/aggregation query without a read-in-order LIMIT path; the large delta locks the verdict though attribution to this PR is unclear.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: c51f64e7-86f0-4b8f-9ceb-4bd65aae8506
  • MIRAI run: 83a0afbb-7a75-46e6-8260-66c9ff8d1917
  • PR check IDs:
    • clickbench_1715875_1786953802
    • clickbench_1715994_1786953820
    • clickbench_1716232_1786954051
    • tpch_adapted_1_official_1716261_1786954053
    • tpch_adapted_1_official_1716489_1786954102
    • tpch_adapted_1_official_1716591_1786954108

alexey-milovidov and others added 2 commits June 8, 2026 16:22
…rallel

Enabling `read_in_order_use_virtual_row` by default caused consistent
1.3x-5x slowdowns in read-in-order perf tests (`distinct_in_order`,
`optimize_sorting_for_input_stream`, `read_in_order_many_parts`,
`monotonous_order_by`, `redundant_functions_in_order_by`) on both amd
and arm. The cause: a source that starts with a virtual row is not read
until `MergingSortedTransform` reaches its key, so the merge requests
the sources strictly one by one and reading becomes single-threaded.
Locally, `SELECT DISTINCT low, medium FROM distinct_cardinality_low
ORDER BY low` ran at the same speed with `max_threads=1` and
`max_threads=16` (0.25s), while with the optimization disabled it
scaled to 0.06s.

Fix: `MergingSortedAlgorithm` now reports deferred sources that are
worth reading ahead (`Status::sources_to_prefetch`), and
`IMergingTransform` asks those inputs for data without waiting for it:

- without a limit, every source is read in full anyway, so the first
  `virtual_row_prefetch_window` deferred sources (in the order the
  merge will need them) read ahead immediately, and the window is
  topped up as their data arrives;
- with a limit, only sources that are provably needed soon read ahead:
  those whose virtual row is not greater than the key at which the
  merge must stop within an already-read chunk (bounded by the
  remaining limit), so sources that cannot contribute are still never
  read and the memory savings are preserved exactly.

The window is the number of pipeline threads, so peak reader memory is
O(threads), not O(parts). On a 300-part table, `SELECT * FROM t ORDER
BY k LIMIT 10` still reads only 8192 rows with 3 MB peak memory
(vs 6.8M rows and 1.3 GB with the optimization disabled), while
`DISTINCT ... ORDER BY` over 100M rows scales with threads again
(0.26s -> 0.07s at 16 threads).

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=30b53cd589f189d928654bf816406e4afca9ce9d&name_0=PR&name_1=Performance%20Comparison%20%28amd_release%2C%20master_head%2C%203%2F6%29

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Investigated the CI failures of the last run (sha 30b53cd589f):

Performance Comparison (slower queries) — real, caused by this PR, now fixed. Enabling read_in_order_use_virtual_row serialized reads: a source that starts with a virtual row is not read until the merge reaches its key, so MergingSortedTransform requested the deferred sources strictly one by one. Locally, SELECT DISTINCT low, medium FROM distinct_cardinality_low ORDER BY low (100M rows) ran in 0.25 s regardless of max_threads, while with the setting off it scaled to 0.06 s at 16 threads — exactly the +130%…+415% seen in distinct_in_order, optimize_sorting_for_input_stream, read_in_order_many_parts, monotonous_order_by, and redundant_functions_in_order_by on both amd and arm.

Pushed 45c2bf7746c: deferred sources now read ahead in parallel when it is safe (immediately up to number of threads sources when there is no LIMIT; only provably-needed-soon sources when there is one). The memory property is preserved exactly — the 300-part ORDER BY k LIMIT 10 query reads 8192 rows with ~3 MB peak (vs 6.8M rows / ~1.3 GB without the optimization) — and the read-minimization tests (03581_read_in_order_use_virtual_row_WHERE, 04201_read_in_order_limit_with_filter, 03711_read_in_order_through_join, 04303_read_in_order_memory_issue_52624) pass. A residual slowdown may remain for selective-filter + LIMIT shapes over non-overlapping sources (order_by_read_in_order #4, lazyMaterialization), where read-ahead is inherently speculative; let's see the next perf run.

Stress test (arm_ubsan), Cannot start clickhouse-server — unrelated. The server failed to restart after the stress run: leftover remote databases from 04210_show_remote_databases_in_system_tables (MySQL/PostgreSQL engines pointing at the TEST-NET address 192.0.2.1) made metadata loading hang on connection timeouts while the previous instance still held the ports (Address already in use). The same Cannot start clickhouse-server stress failure occurs on master without this PR (2026-06-05, 06-06, 06-07, 06-09 in CIDB) with various leftover-state causes. Nothing in this PR touches server startup or DatabaseMySQL.

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=30b53cd589f189d928654bf816406e4afca9ce9d&name_0=PR&name_1=Stress%20test%20%28arm_ubsan%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated the Stress test (arm_ubsan) Cannot start clickhouse-server failure. Fix in a separate PR: #107055.

Root cause confirmed (code + the arm_ubsan clickhouse-server.err.log startup stack + a local A/B repro): DatabaseMySQL's constructor connects to the MySQL host synchronously (empty() -> fetchTablesIntoLocalCache() -> PoolWithFailover::get()). The constructor runs during startup metadata loading, before the listen ports are bound, so a MySQL database pointing at an unreachable host blocks startup for connect_timeout * connection_max_tries per database.

In stress this compounds exactly as you diagnosed: when the server is killed mid-test the trailing DROP in 04210_show_remote_databases_in_system_tables is skipped, the leaked 192.0.2.1 databases accumulate across restarts, each startup blocks cumulatively, the previous instance still holds the ports, and the restart cascade ends in Address already in use.

DatabasePostgreSQL already defers the connect (its constructor does not connect), which is why the PostgreSQL database in 04210 never blocks startup. #107055 makes DatabaseMySQL match: skip the constructor connect on attach (startup / ATTACH DATABASE), fetch tables lazily on access. A/B with one unreachable MySQL database at the default timeout: 30.7s -> 0.6s startup; three databases go from "fails to start within the start window" to 0.66s.

Agreed this is unrelated to your PR.

alexey-milovidov and others added 2 commits June 12, 2026 02:36
Review and the perf run found three flaws in the previous read-ahead:

- With a `LIMIT`, the number of read-ahead sources was unbounded: every
  deferred source whose virtual row preceded the merge stop row was
  scheduled at once, so many overlapping parts could re-create the
  O(parts) resident-reader memory issue this PR fixes.
- Read-ahead was issued only for sources provably needed by the merge,
  so shapes where the proof never arrives still degraded to a single
  thread. With a selective filter (`WHERE UserID = ...` or
  `WHERE URL LIKE '%google%'` with `ORDER BY pk LIMIT n`), filtered
  chunks rarely reach the merge, so nothing ever became provably needed:
  `order_by_read_in_order` showed 3.3x-4.7x and `lazyMaterialization`
  1.9x-2.5x slowdowns on both architectures.
- `sources_to_prefetch` was forwarded even on a finished status, and
  `IMergingTransformBase::prepare` processes prefetches before checking
  `state.is_finished`, so a query that already reached its `LIMIT`
  could still start reads that are never consumed.

Now `MergingSortedAlgorithm` always keeps the next
`virtual_row_prefetch_window` deferred sources (in the order the merge
will need them) reading ahead, with or without a `LIMIT`. Under a
`LIMIT` the read-ahead is speculative - the merge may finish before
reaching a prefetched source - but the waste is bounded by O(threads)
chunks (a source past its virtual row only buffers one chunk in its
port until the merge consumes it), and peak reader memory stays bounded
by the window instead of the number of parts. Pending read-ahead is
dropped when the merge finishes, both in `merge` and in
`IMergingTransformBase::prepare`.

Test `04201_read_in_order_limit_with_filter` encoded the strict
on-demand behavior (3 granules); with the window all 4 parts contribute
one granule each, which is the documented O(threads) trade-off.

Perf report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=45c2bf7746c88ff92a9c46a5f6dfb41dc46b8519&name_0=PR

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed 5d11e85846e: merged master (clean) and reworked the virtual-row read-ahead after the perf run and review — the window is now unconditional and bounded by max_threads in both the limit and no-limit cases (see Update 2 in the description). Both review threads are addressed and resolved.

The two red checks on the previous run are unrelated to this PR:

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov investigated STID 3440-2ddb. It is the same root cause as STID 3440-3393, which is already fixed by #105433 (merged into master 2026-06-11 19:20 UTC by @ azat). No separate PR is needed; this is covered.

Root cause. Both STIDs crash at AddDefaultDatabaseVisitor.h:130:

if (select.recursive_with)
    for (const auto & child : select.with()->children)  // with() is null

IStorageCluster::read runs AddDefaultDatabaseVisitor over the AST that the analyzer regenerates from the query tree (QueryNode::toASTImpl). When the recursive CTE has already been consumed, that AST has recursive_with = true but a null WITH clause, so select.with()->children dereferences a null intrusive_ptr<IAST>. The 2026-05-31 hit on #106184 is literally Assertion 'px != 0' failed in intrusive_ptr<IAST>::operator->(), the same null deref.

#105433 fixes this at the source in QueryNode::toASTImpl, restoring the parser invariant recursive_with -> with() != nullptr:

select_query->recursive_with = is_recursive_with && hasWith();

Evidence it is the same bug and is fixed:

Report for reference: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=45c2bf7746c88ff92a9c46a5f6dfb41dc46b8519&name_0=PR&name_1=BuzzHouse%20%28amd_msan%29

So the two red checks are indeed unrelated to this PR, and the segfault is resolved on current master by #105433.

(session cron:clickhouse-worker-slot-2:20260612-034800)

alexey-milovidov and others added 2 commits June 13, 2026 06:16
With the bounded read-ahead window for sources deferred behind virtual rows,
a deferred source within the window may be speculatively prefetched and read
one block ahead of the merge. For this test (two parts, `ORDER BY x LIMIT 10`),
the second part is not needed to answer the query, but whether its one
prefetched block is actually read before the merge finishes is timing
dependent: the test passed locally (second part read `0` rows) but failed in
CI (second part read `65536` rows).

Assert the deterministic invariants instead of the exact per-part read count:
both parts have their own `MergeTreeSelect` and `VirtualRowTransform` (so the
virtual-row path is engaged) and neither reads more than one block. This
mirrors the bounded-read assertion already used in
`04201_read_in_order_limit_with_filter`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=5d11e85846e1f09b165fa2ec58ce8eb582ca33b0&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 <[email protected]>
A source deferred behind a virtual row reserves a read-ahead slot
(`prefetches_in_flight`) when prefetched, and the slot is released in
`MergingSortedAlgorithm::consume` once the source delivers its first real
chunk. But when a prefetched source is completely filtered out upstream it
finishes without ever delivering a real chunk: `IMergingTransformBase::prepare`
sees the input finished and sets `state.no_data` without calling `consume`. The
slot was then never released, so after `max_threads` such sources the window
stopped refilling and the merge silently degraded to reading one part at a
time, defeating the read-ahead and reproducing the very serialization the
window is meant to avoid (e.g. a selective filter that empties leading parts).

Add `IMergingAlgorithm::onSourceExhausted`, called from the transform when a
required source finishes without data, and have `MergingSortedAlgorithm`
release the deferred source there (the merge loop already drops it from the
queue via `removeTop`, so only the read-ahead bookkeeping needs updating). The
release logic is shared with `consume` through `releaseDeferredSource`.

Add `05017_virtual_row_prefetch_filtered_out` exercising the path where the
leading parts the merge walks through are all filtered out.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
alexey-milovidov and others added 2 commits June 14, 2026 04:37
The new regression test was created with prefix `05017`, far ahead of the
current maximum test number on master (`04337`), which tripped the
`test_numbers_check` style check (`Gap (4336, 5017) > 100`). The high number
was picked by `add-test` because of unrelated untracked `050xx` files left in
the shared working directory. Renumber to `04339` so the test numbers stay
contiguous. No change to the test itself; the table name does not depend on
the prefix.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=b2b7bdb327ee84f4e9485a56cb7845b11788a788&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The stateless test `04339_virtual_row_prefetch_filtered_out` only checks result
correctness, which holds with or without `MergingSortedAlgorithm::onSourceExhausted`:
when the merge walks in-order through leading parts that are entirely filtered out,
the same parts are read and the same rows are produced either way; the only
difference is scheduling. With the read-ahead slot released the filtered-out parts
are read concurrently; without it the window stalls after `max_threads` such sources
and the merge degrades to reading one part at a time. That difference is timing-only,
so it cannot be asserted deterministically in a stateless test, but it is exactly
what the performance-comparison suite measures reliably.

This test builds 64 parts with disjoint increasing key ranges where only the last
part matches the filter, so `ORDER BY a LIMIT N` has to walk through 63 fully
filtered-out leading parts, exercising the slot-release path at a scale where the
serial-vs-parallel difference is measurable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, please investigate the unrelated Stress test (arm_release) failure. It is the known FunctionIn "Not-ready Set" exception (src/Functions/in.cpp), tracked by #107619; a related fix is in progress at #102192.

@groeneai

Copy link
Copy Markdown
Collaborator

This is not caused by this PR. STID 0250-3e49, 62 failures across 55 distinct PRs plus 5 on master in the last 30 days (Stress test (arm_release) and Stress test (arm_msan), first seen 2026-07-23).

The carrier here is an AST-fuzzer mutation of 04335_packed_composite_key_set, which puts a cluster('test_unavailable_shard', ...) read inside the IN subquery:

SELECT DISTINCT (SELECT count() FROM sk_t32 WHERE (a, b) IN
    (SELECT a, b FROM cluster('test_unavailable_shard', currentDatabase(), 'sk_r32'))) = ...

The err log shows the shard failing first (Connection refused (localhost:1), then Connections to remote replicas of local shard 2 failed, will use stale local replica) and the abort following at src/Functions/in.cpp:116 under FilterTransform.

I reproduced the mechanism locally on master (8a02ec4) and it is deterministic. ReadFromRemote inherits the throwing IQueryPlanStep::clone, so a remote IN subquery takes the destructive branch of FutureSetFromSubquery::buildOrderedSetInplace, which consumes source; the set is then unbuildable and FunctionIn aborts. With the same failpoint armed, a local subquery recovers and returns the correct count, while the cluster(...) subquery gives Not-ready Set and aborts the server; without the failpoint the remote query returns the correct count, so the trigger is the swallowed in-place failure and not remoteness itself.

So neither #102192 nor #107924 covers this occurrence: #102192 adds clone for eleven steps, none of them a remote read, and it explicitly keeps ReadFromPreparedSource non-clonable.

The owner is your #114983, which names this STID and this arm_release/arm_msan pattern, and rethrows the remembered destructive-build failure so the query reports the connection error instead of the logical error. #114849 addresses the same code path by preserving non-clonable sources for the deferred build. I will track both against CIDB and follow up here if 0250-3e49 keeps firing after they merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/31941153595/job/95161801033 and provide a fix in a separate PR. The runner lost communication with GitHub while the Run step was still in progress, before any test failure was reported; the check annotation identifies a self-hosted runner/network failure. I found no matching open tracking issue or PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed as infrastructure. Job 95161801033 is Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6): the job is completed/failure while its own Run step is still in_progress with a null conclusion, the archived log is BlobNotFound, the run published 0 artifacts, and the shard published no CIDB rows at all while the other five published 1010 to 1519 rows each, all green. The amd_tsan family at this same commit has all six shards present, so the absence is one job wedging rather than a partition that never runs.

There is an open fixing PR and it is mine: #112984, which bounds the integration tests' nested containers by the job's memory limit. Its CI is now finished and clean on head ea6eb54c: 177 check-runs, 63 success, 114 skipped, 0 failed. No human review has ever been requested on it, so a review is the only step left before it can land.

One new detail. This is the first report of this wedge on a shard other than 5/6, and the breadth says the shard is incidental: of the master heads in the last three days that published only five of the six shards, the absent one was 4/6 on 18 of them, 2/6 on 11, 5/6 on 1 and 6/6 on 1. The wedge is runner-level and shard-agnostic, which fits the containment mechanism #112984 addresses rather than shard balance. This job also ran 112 minutes against 82 to 102 for the five that passed alongside it, so it is not a fixed-duration timeout.

@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.

Ok.

@alexey-milovidov alexey-milovidov self-assigned this Aug 17, 2026
@alexey-milovidov alexey-milovidov added the memory When memory usage is higher than expected label Aug 17, 2026
@vdimir vdimir self-assigned this Aug 17, 2026
Comment thread src/Core/Settings.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Thanks! So we will enable this, then enable read_in_order_use_virtual_row_per_block in the follow-up, ok?

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 18, 2026
Merged via the queue into master with commit 9c7eced Aug 18, 2026
182 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-52624-read-in-order-virtual-row-default branch August 18, 2026 01:09
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 18, 2026
Slach added a commit to Altinity/clickhouse-backup that referenced this pull request Sep 2, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The first CI run with `read_in_order_use_virtual_row` enabled by default
failed `03711_read_in_order_through_join`: `ORDER BY pk LIMIT n` read about
155k rows where the reference expects a single granule (`Fail: 155656 rows
read`), on every stateless shard.

The read-ahead window that lets sources deferred behind virtual rows read
in parallel was started eagerly — at `initialize` and on every consumed
chunk — before the merge knew whether the front source's first chunk
already satisfied the limit. When it did (e.g. `read_in_order_through_join`
with the answer in the first part, the part split into `max_threads`
streams), the window still speculatively read a block from each of the
other streams, reading parts that the optimization exists to skip.

Start the read-ahead only once the merge has finished with a source (its
real data arrived, or it was exhausted without any) and still needs
another one. The first source the merge asks for is the front source being
resolved from its virtual row; the sources deferred behind it are not
prefetched until the merge proves it must advance past the front. This
preserves the parallelism win for selective filters — where the front
chunks do not satisfy the limit, so the merge keeps requesting sources, and
the window engages (including when the leading parts are entirely filtered
out and exhausted without data) — while no longer reading parts that a
limit answered by the front source never reaches.

The `03581` and `04201` test comments are updated to describe the gated
read-ahead; both assertions (bounded read counts) still hold.

CI report: ClickHouse#106215

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The test created a query quota with `TO default`. A quota is a server-global
entity, and in stress and parallel runs all stateless tests execute
concurrently against the same server as the `default` user, so the quota on
`default` was consumed by every concurrent query, exhausted its limit, and made
the server reject subsequent queries with `QUOTA_EXCEEDED` — eventually taking
the whole server down (`Server is not responding`).

The interval is validated at CREATE time in `InterpreterCreateQuotaQuery`,
independent of the `TO` assignment, so the quota does not need to be assigned to
anyone for the test to exercise the `BAD_ARGUMENTS` rejection. Drop the
`TO default` clause so the test no longer touches the shared `default` user; the
reference output (`BAD_ARGUMENTS` / `BAD_ARGUMENTS` / `ok`) is unchanged.

Surfaced on the `Stress test (amd_msan)` job of
ClickHouse#106215
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=106215&sha=0b2a2b671abe9df2dae40253fb8fafacaf699575&name_0=PR&name_1=Stress%20test%20%28amd_msan%29

Caused by: ClickHouse#110846

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
vdimir added a commit that referenced this pull request Oct 1, 2026
The merge kept a window of sources deferred behind their virtual rows reading
ahead (`virtual_row_prefetch_window`, `Status::sources_to_prefetch`,
`onSourceExhausted`, `inputs_to_prefetch`). Reading ahead belongs to the
reading side: with `read_in_order_use_sliced_pool` the pool knows the primary
key of every unread granule and reads exactly what the merge is going to need
next, while the merge can only guess by source. The merge now only asks for
the input it needs.

On the per-part path (the setting off, descending order, parallel replicas or
a preliminary merge) the sources deferred behind virtual rows are read one
after another when the merge reaches them, as before the window was added in
#106215.

The tests that asserted the window through `processors_profile_log` keep
their assertions, which hold without read-ahead as well; only their comments
change. The generated documentation of `read_in_order_use_virtual_row` and of
`read_in_order_use_sliced_pool` is refreshed.

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

Labels

memory When memory usage is higher than expected pr-performance Pull request with some performance 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.

optimize_read_in_order may consume too much memory

4 participants