Skip to content

Cherry pick #113095 to 26.10: Deliver one sorted run per stream reading object storage in order - #131083

Merged
robot-ch-test-poll3 merged 15 commits into
backport/26.10/113095from
cherrypick/26.10/113095
Nov 15, 2026
Merged

robot-ch-test-poll3 merged 15 commits into
backport/26.10/113095from
cherrypick/26.10/113095

Conversation

@robot-ch-test-poll2

Copy link
Copy Markdown
Contributor

Original pull-request #113095

Do not merge this PR manually

This pull-request is a first step of an automated backporting.
It contains changes similar to calling git cherry-pick locally.
If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.

The check results does not matter at this step - you can safely ignore them.

Before you resolve anything

Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.

Troubleshooting

If the conflicts were resolved in a wrong way

If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:

  • delete the pr-cherrypick label from the PR
  • delete this branch from the repository

You also need to check the Original pull-request for pr-backports-created label, and delete if it's presented there

The PR source

The PR is created in the CI job

groeneai and others added 14 commits August 3, 2026 06:19
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 #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]>
… 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]>
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.
…-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]>
… NULLs may be present

The in-order merge places NULLs last for ASC keys and first for DESC. Files sorted with the
other null order (Spark's default `asc nulls-first`) are only in that order if they have no
NULLs, so keep the sort unless every data file's manifest shows a zero null count for those
sort columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… row groups

Listing files during planning consumes the iterator, so a clone of a planned step (a sealed
view under a correlated subquery) shared the cursor and both reads lost each other's files.
A clone now lists its own files from the same table state. Also test reading in order over a
file with several row groups, which only the Parquet `preserve_order` pin keeps in order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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
…torage-read-in-order

Deliver one sorted run per stream reading object storage in order
@robot-ch-test-poll2 robot-ch-test-poll2 added pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only! do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default labels Nov 12, 2026
@murphy-4o

This comment was marked as resolved.

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]>
@groeneai

This comment was marked as resolved.

@robot-ch-test-poll3
robot-ch-test-poll3 merged commit 4c7b58a into backport/26.10/113095 Nov 15, 2026
2 checks passed
@robot-ch-test-poll3
robot-ch-test-poll3 deleted the cherrypick/26.10/113095 branch November 15, 2026 04:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do not test disable testing on pull request pr-bugfix Pull request with bugfix, not backported by default pr-cherrypick Cherry-pick of merge-commit before backporting. Do not use manually - automated use only!

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants