Repository navigation
Conversation
optimize_read_in_order accepts an object storage table whose data is sorted by the sorting key and drops the sorting step. That is only valid if every input port of the merge above it already carries a run sorted by sort_description_for_merging. ReadFromObjectStorageStep never established that, so the merge was fed unsorted inputs and returned unsorted rows. With max_threads = 1 the failure is deterministic: over two overlapping files SELECT id FROM t ORDER BY id returns 2 4 1 3, because the single source reads both files serially and concatenates them, SortingStep::mergingSorted installs no merge for a single port, and finishSorting does not run on a full sorting-key match, so nothing sorts and nothing merges. Five independent causes, all on this path: - every stream pulled from the same shared file iterator, so file-to-stream assignment was a race and one stream could take two files; - pipe.resize under parallelize_output_from_storages redistributed chunks across ports; - requestReadingInOrder was const and recorded nothing, so initializePipeline could not know an order had been promised; - input_format_parquet_preserve_order defaults to false and the Parquet reader then delivers row groups in completion order, so even one file per port was not a sorted run. Iceberg pins that setting today only as a side effect of its positional-delete path, so the ordering happened to be correct by coincidence; - a descending order was accepted although there is no reverse file walk and no ReverseTransform here, so ORDER BY id DESC was answered with ascending data. requestReadingInOrder now takes the direction and the optimization settings and decides everything during optimization, which is the only point where declining is still possible: it rejects a non-ascending direction, enumerates the files, checks each file's own format (the format is per file, so a mixed-format table is judged on its actual files), caps the file count at read_in_order_two_level_merge_threshold * max_threads, requires the sorting-key expression to be computable from the step's header, and declines when a distributed plan is being built, since bucket assignment happens later. On success it pins Parquet's preserve_order and caches the file list. Enumeration consumes the iterator, and createIterator early-returns on an existing iterator while next() is destructive, so a naive drain would leave an exhausted iterator and every declined path would read zero rows. A replaying iterator that first hands back the consumed prefix and then delegates is therefore installed unconditionally, before any rejection can return. initializePipeline then builds one source per file, mirroring one source per part in ReadFromMergeTree, sharing a single reader pool rather than a private single-thread pool per source, which is what makes per-file sources affordable at scale. It skips the resize, and above read_in_order_two_level_merge_threshold files it adds a preliminary merge per group of files exactly as ReadFromMergeTree does, materializing the sorting-key expression first and projecting it away afterwards so the step's output header is unchanged. No second merging transform is added: the one the issue asks for is already installed by the existing FinishSorting path. The missing half was only the per-stream guarantee. Read-in-order, aggregation-in-order and distinct-in-order all go through requestReadingInOrder, so all three are fixed. Limit-by is still not enabled for this step and is left alone. The regression tests assert the rows as returned rather than through get_array, which sorts its input and made every existing ordering assertion in that file blind to ordering. They also cover the preliminary-merge grouping, an expression sorting key, an ORC table declining, duplicate keys across files, and row-count parity on every declined path. patch_metadata now patches the newest metadata version instead of a hardcoded v4.metadata.json, which is required for any fixture with more than two inserts: patching a stale version leaves the table unsorted and silently measures the declined path. Closes ClickHouse#112981.
…ge pipe read_in_order_two_level_merge_threshold = 0 means "always preliminary-merge", but buildInOrderPipe used the raw setting as the group-count divisor while requestReadingInOrder normalized it for the cap. The two disagreed, so a file count inside the cap (3 <= files <= max_threads) reached the division and the server took SIGFPE during pipeline construction. tests/clickhouse-test randomizes this setting over 0..100, so it was reachable in CI. Both sites now read one normalized value. The grouping merge materializes the storage sorting key into the pipe and projected it away with an identity ActionsDAG. That cannot remove a column: ActionsDAG:: updateHeader re-emits every header column not matched to a DAG input, and ExpressionActions defaults to project_inputs = false, so with an expression sorting key the step emitted a column absent from its declared output header, and out of position. ReadFromMergeTree uses the same helper safely only because it follows it with makeConvertingActions; do the same here. Also count the un-replayed prefix in ObjectIteratorReplayThenDelegate:: estimatedKeysCount. A drained delegate can report 0 and a consumer seeing <= 1 key collapses to a single stream. Latent today, since no current iterator reports 0 after a full drain. Tests: assert the pipeline SHAPE, not only the results. One sorted run per port plus the downstream FinishSorting merge sorts correctly on its own, so every result assertion was equally satisfied with the grouping branch deleted, and the previous SELECT * check could not see the leaked column. Now the grouped configuration is required to contain more preliminary merges than the ungrouped one, the read step is required to emit exactly its declared columns, and aggregation-in-order is required to be the operator producing the aggregated results. Distinct-in-order cannot engage on this step at all, because canImproveOrderForDistinct only fires where it can improve on the order the step advertises and this step advertises the full sorting key; that decline is asserted rather than assumed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Internal second-model review (2 rounds, click to expand)Before publishing I reviewed this change with an independent model, cold (no access to the Round 1 - 6 findings, all AGREED and fixed❌ Blocker: ❌ Blocker: the grouping path leaked a column its declared header did not contain.
💡 Two nits folded in: the replaying iterator's The review also corrected a claim of mineRound 1 asked how the tests distinguish the mechanisms, and the answer was that two of them do Round 2 - 0 findingsRe-reviewed the fixes cold, then adjudicated: all four items closed, verified from the source |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-48:20260803-115500 |
|
cc @antaljanosbenjamin @kssenii, could you review this? |
|
Workflow [PR], commit [a5b16cf] Summary: ✅
AI ReviewSummaryThe PR fixes ordering of sorted object storage reads by delivering one sorted run per output port, preserving Missing context / blind spots
Final Verdict✅ Approve — no code changes requested. Integration and sanitizer validation of the latest head remains pending. |
… probe The Style check's catch_all sub-check flagged the catch (...) in sortingKeyIsComputableFromSourceHeader as silently swallowing exceptions. Swallowing is the intended behaviour there: the try block only probes whether the storage sorting key expression can be built against the header this step emits, so any failure is the answer to the question rather than an error to report. The caller declines read-in-order and the query is answered by the full sort it would have used before this change, so results stay correct and nothing is lost by not logging. The same shape is already used for the domain-narrowing probes in TTLDescription.cpp. Verified by extracting check_catch_all from ci/jobs/check_style.py and running it over the changed files: clean with the comment, and reproducing the exact CI violation at ReadFromObjectStorageStep.cpp:422 with the comment removed. Co-Authored-By: Claude Fable 5 <[email protected]>
CI finish ledger - 6a0cca6Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
153 success, 21 skipped, 1 failure out of 175 check-runs. Session id: cron:our-pr-ci-monitor:20260803-200000 |
…-order Co-Authored-By: Claude Fable 5 <[email protected]>
The read-in-order request phase asked "is the storage sorting key computable from this step's header" by re-running TreeRewriter and ExpressionAnalyzer over the key AST and reading any throw as "no". That turned failures which say nothing about computability into a silent fallback to a full sort: TOO_DEEP_RECURSION from the checkStackSize calls on that path (TreeRewriter.cpp:792, ActionsVisitor.cpp:823, thrown at checkStackSize.cpp:134), an allocation failure under the query's memory tracker, or a LOGICAL_ERROR raised inside the analyzer, which a release build would then hide. The probe was redundant as well. KeyDescription::getKeyFromAST already performs that exact analysis once, against every storage column, and keeps the result in sorting_key.expression (KeyDescription.cpp:180). Its existence is what proves function resolution, arity and types already succeeded, so the only variable left at plan time is which of those columns the query still reads. Absent columns are also the only thing the old probe could newly discover: it fails on this header by throwing UNKNOWN_IDENTIFIER for an unresolved name (TreeRewriter.cpp:1349). getColumnsRequiredForSortingKey() reports exactly that column set, the header this step emits is built from the same storage snapshot, and ReadFromMergeTree asks the same question through the same accessor on its own read-in-order path (ReadFromMergeTree.cpp:1176). The predicate is therefore a presence check over the key's required columns, and no exception handling is left to be too broad. Errors raised where the pipe is actually built propagate exactly as before. Verified with test_storage_iceberg_with_spark/test_read_in_order.py: 17 passed. Inverting the presence test fails 15 of the 17 with the sorting step no longer dropped, so the suite is sensitive to this predicate; the two survivors are the ORC decline test and a test that asserts no pipeline topology.
Wrong results for a nullable sorting key that contains NULLsI measured this while checking the change above. It is a wrong-results defect that this PR does Iceberg specifies Neither cheap containment works. Declining on "nullable key column" disables the optimization for @alexey-milovidov which would you prefer, and would you like it here or separately given #100394? |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Processors/QueryPlan/ReadFromObjectStorageStep.cpp.o |
480.57 KiB | 971.52 KiB | +490.95 KiB (+102.16%) |
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.64, programs/clickhouse-keeper ×0.70 (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 | 13.3 s | +9.6 s (+254%) |
programs/clickhouse |
_ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… |
3.4 s | 7.3 s | +5.2 s (+239%) |
Compile time of recompiled translation units
117 translation units recompiled, 1192 s compile time in total, 117 of them have a recent master baseline.
| Translation unit | Master | PR | Δ vs median |
|---|---|---|---|
src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp |
14.6 s | 19.3 s | +5.2 s (+37%) |
Slowest changed entities of src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp:
- ParseClass
DB::SortQueueVariants: +1.0 s
CI finish ledger - 7f67ed3Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
The owner is merged but absent from the tree that ran: the lock the fix introduces in The two |
…-order Resolve conflicts with the TopK query condition cache, the data lake read estimate and the Spark 4.0 test adaptation on master: - The in-order pipe reuses master's FormatFilterInfo (format filter, schema mapper, row numbers, TopK filter) and passes the TopK query condition cache key to every per-file source; a source ignores a key without a hash, which happens only for plain object storage, which is never read in order. - StorageObjectStorageSource takes the shared reader pool after the new TopK key argument; its destructor waits for its own reader task when the pool is shared, then writes the pending TopK cache entries as on master. - Drop patch_metadata from the new tests: Iceberg 1.11 Spark writers record the write order in sort_order_id (92653a5), so the tables take the in-order path without patching. Co-Authored-By: Claude Opus 5.5 <[email protected]>
With more files than read_in_order_two_level_merge_threshold * max_threads, requestReadingInOrder declines and the sorting step stays. The (4, 0) and (4, 1) cases only checked the returned rows, which a kept sort and an in-order read both get right; assert the plan for them and for the accepted (6, 0) case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… built yet requestReadingInOrder enumerates the files during plan optimization, and the iterator evaluates the filter: the _path / _file filter and the key condition of the data lake build a set in place, which runs its subquery. applyFilters leaves GLOBAL IN sets for the pipeline to build, so planning alone ran such a subquery: EXPLAIN SELECT ... WHERE _path GLOBAL IN (SELECT toString(throwIf(1))) ORDER BY id threw on a sorted Iceberg table, while master does not run it. Decline instead and keep the full sort. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - ee2bf8aEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
CIDB has no other Session id: cron:our-pr-ci-monitor:20261110-230008 |
…torage read Reading fills in the file objects listed during planning, so accepted copies of a cloned step (e.g. both sides of a `full_sorting_merge` join over one sealed view) wrote to the same objects. A copy now keeps only the in-order decision and lists its own files from the same table state. The cloned-read test now enables aggregation in order on the outer query, so both copies read in order. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp
|
Public CI on
I checked the fuzzer query both ways: the CI One more thing: the |
Resolve the conflicts in ReadFromObjectStorageStep.cpp/.h and StorageObjectStorageSource.cpp/.h: keep the 26.10 side and take only the lines of #113095. The conflicting master context is the TopK query condition cache for object storage (#124808, #124813) and the declarations next to it, none of which is in 26.10. So the in-order sources are built without a TopK query condition cache key, and createIterator keeps its 26.10 form, which has no iterator_metadata to preserve. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #113095 to 26.10: Deliver one sorted run per stream reading object storage in order
…object storage in order
Backport #113095 to 26.10: Deliver one sorted run per stream reading object storage in order
Closes: #112981
Closes: #130439
Closes: #130440
Closes: #127435
Closes: #127434
Related: #100394
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong row order for
ORDER BY(andGROUP BYwithoptimize_aggregation_in_order) when reading in order from a sorted object storage table, e.g. an Iceberg table whose files carry its sort order.ORDER BY ... DESCon such tables no longer returns ascending rows.Description
When every file carries the table's sort order,
optimize_read_in_orderdrops the sort and only merges the read streams, assuming each stream is sorted. It wasn't: a stream could read several files back to back, and its rows could also be reordered (resize after reading, Parquet row groups in completion order). With two overlapping files andmax_threads = 1,ORDER BY idreturned2 4 1 3.Now
requestReadingInOrderaccepts only when the pipeline can deliver one sorted run per file:ReadFromMergeTreedoes per part; no resize; Parquetpreserve_order;DESC, distributed plans, non-Parquet files,GLOBAL INfilters, or more thanread_in_order_two_level_merge_threshold * max_threadsfiles;Performance:
ORDER BY ... LIMITis at parity with a full sort; a fullORDER BYover many files costs about what the sort costs with the group merge, and up to ~4x more without it.Measurements (600k rows,
max_threads=8,system.query_logmedians)SELECT id, data FROM t ORDER BY id FORMAT Null, 30 files, 7 runs. Master skips the sortwithout delivering sorted data, so its 47 ms is the price of the wrong answer:
At the default cap (
read_in_order_two_level_merge_threshold * max_threads= 800 files),9 runs, variants measured in separate blocks:
ORDER BY id LIMIT 10at 200 files: 434 ms in-order vs 463 ms full sort. The not-in-orderpath is unchanged. Sorted output verified at the cap (0 inversions over all 600k rows).
Workflow [PR]
Sync PR [sync-upstream/pr/113095]
Version info
26.11.1.2104-master(included in26.11and later)26.10.5.17