Skip to content

Deliver one sorted run per stream reading object storage in order - #113095

Merged
murphy-4o merged 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112981-object-storage-read-in-order
Nov 12, 2026
Merged

murphy-4o merged 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112981-object-storage-read-in-order

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #112981
Closes: #130439
Closes: #130440
Closes: #127435
Closes: #127434
Related: #100394

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed wrong row order for ORDER BY (and GROUP BY with optimize_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 ... DESC on such tables no longer returns ascending rows.

Description

image

When every file carries the table's sort order, optimize_read_in_order drops 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 and max_threads = 1, ORDER BY id returned 2 4 1 3.

Now requestReadingInOrder accepts only when the pipeline can deliver one sorted run per file:

  • one source per file, as ReadFromMergeTree does per part; no resize; Parquet preserve_order;
  • declined (the sort stays) for DESC, distributed plans, non-Parquet files, GLOBAL IN filters, or more than read_in_order_two_level_merge_threshold * max_threads files;
  • the files listed for this check are handed back to the iterator, so a declined read still reads every file;
  • above the threshold, files are merged in groups first.

Performance: ORDER BY ... LIMIT is at parity with a full sort; a full ORDER BY over 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_log medians)

SELECT id, data FROM t ORDER BY id FORMAT Null, 30 files, 7 runs. Master skips the sort
without delivering sorted data, so its 47 ms is the price of the wrong answer:

variant master p50 fixed p50 peak mem (fixed)
one source per file 47 ms (wrong results) 152 ms 85.9 MiB
preliminary merge 43 ms (wrong results) 89 ms 131.5 MiB
full sort 106 ms 108 ms 115.6 MiB

At the default cap (read_in_order_two_level_merge_threshold * max_threads = 800 files),
9 runs, variants measured in separate blocks:

files variant p50 min peak mem
200 one source per file 581 ms 233 ms 38.4 MiB
200 full sort 197 ms 170 ms 21.3 MiB
800 one source per file 2485 ms 1214 ms 52.0 MiB
800 preliminary merge 655 ms 582 ms 25.4 MiB
800 full sort 586 ms 552 ms 25.2 MiB

ORDER BY id LIMIT 10 at 200 files: 434 ms in-order vs 463 ms full sort. The not-in-order
path is unchanged. Sorted output verified at the cap (0 inversions over all 600k rows).


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

Version info

  • Merged into: 26.11.1.2104-master (included in 26.11 and later)
  • Backported to: 26.10.5.17

groeneai and others added 2 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 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]>
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, click to expand)

Before publishing I reviewed this change with an independent model, cold (no access to the
implementation notes), and adjudicated every finding against the source. Round 1 found four real
defects and bounced the change back; round 2 found none.

Round 1 - 6 findings, all AGREED and fixed

❌ Blocker: read_in_order_two_level_merge_threshold = 0 divided by zero.
The gate only skipped the preliminary merge for num_files <= threshold || num_files <= 2, so
three or more files with the setting at 0 reached (num_files + threshold - 1) / threshold.
The cap normalized the zero separately, so the request path accepted rather than declined.
tests/clickhouse-test randomizes this setting over 0..100. Reproduced as
Received signal 8 / Integer divide by zero at that exact line, killing the server. Fixed with a
single normalized value used by the gate, the division and the cap; (6, 0) is now in the
regression matrix.

❌ Blocker: the grouping path leaked a column its declared header did not contain.
The preliminary merge materializes the sorting key into the pipe, and the identity projection
meant to remove it again cannot: ActionsDAG::updateHeader re-emits header columns that match no
DAG input, so icebergBucket(16, id) survived and the step emitted [id, icebergBucket(16, id)]
while declaring [id]. Confirmed with EXPLAIN PIPELINE header = 1 before and after. Fixed with
a blocksHaveEqualStructure + makeConvertingActions bracket, which also corrects column order.

⚠️ Major: no test distinguished the new pipeline shape from a correct fallback.
All five (max_threads, threshold) cases passed with the entire grouping block deleted, because
one sorted run per port plus the downstream merge already sorts correctly. Result assertions
alone could not tell the two topologies apart. Fixed with EXPLAIN PIPELINE subquery assertions,
each with a recorded mutation arm that reddens it. That exercise caught a vacuous oracle: the
first header assertion read only the first line of a multi-line header block, so it was
structurally blind to the leaked column it existed to catch; rewritten, it then failed 2/2
against the mutated binary.

⚠️ Major: the source count at the cap was ~26x what the performance A/B measured.
Re-measured at the default cap (800 files): 52.0 MiB peak against 25.2 MiB for the full sort, so
memory does not scale badly and no ceiling was added; the cost is latency, and since a decline
falls back to the full sort, a cap could not beat it. The numbers are in the PR body.

💡 Two nits folded in: the replaying iterator's estimatedKeysCount ignored its un-replayed
prefix (latent, but a drained delegate reporting 0 would collapse the read to one stream), and
the comment budget.

The review also corrected a claim of mine

Round 1 asked how the tests distinguish the mechanisms, and the answer was that two of them do
not: distinct-in-order never reaches this step (canImproveOrderForDistinct only fires where
it can improve on the order the step advertises, and this step advertises the full sorting key),
and optimize_aggregation_in_order defaults to false, so the earlier DISTINCT and GROUP BY
result assertions were evidence for neither. Both are now pinned explicitly: aggregation-in-order
present at = 1 and absent at = 0, distinct-in-order asserted as zero with the reason. The
description and changelog were corrected to match.

Round 2 - 0 findings

Re-reviewed the fixes cold, then adjudicated: all four items closed, verified from the source
rather than from the implementation notes. I also raised and refuted a hazard of my own - clone()
copy-constructs, so a clone would share the file iterator and copy the enumerated file list, which
would be a wrong-results bug if any site cloned an already-enumerated step. Every reachable
QueryPlan clone site either gates on MergeTree-family steps, clones before optimization runs, or
is the distributed path, which this step declines outright.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. max_threads = 1 on the issue's own fixture: SELECT id FROM t ORDER BY id returns 2 4 1 3 in 3/3 runs. max_threads >= 2 happens to look correct, which is why the pre-existing test was green. Command: sg docker -c "python3 -m ci.praktika run 'integration' --test 'test_storage_iceberg_with_spark/test_read_in_order.py::test_read_in_order'".
b Root cause explained? Yes. optimize_read_in_order drops the sorting step via convertToFinishSorting, whose contract is that every input port of the merge already carries a run sorted by sort_description_for_merging. ReadFromObjectStorageStep never established that, so the merge received unsorted inputs. At num_streams = 1 one source reads both files serially and concatenates them, and SortingStep::mergingSorted installs no merge for a single port while need_finish_sorting is false for a full key match, so nothing sorts and nothing merges.
c Fix matches root cause? Yes. It establishes the missing per-port guarantee (one source per file, no pipe.resize, preserve_order pinned) instead of widening a bound or masking a symptom. No assertion was relaxed and no no-random-* tag was added.
d Test intent preserved / new tests added? Yes. The one modified pre-existing assertion became STRICTER: get_array sorts its input, so every ordering assertion in that file was blind to ordering; it now compares the rows as returned. Four new tests cover the grouping path, expression sorting keys, the ORC decline and duplicate keys, and each new plan-shape assertion has a recorded arm in which it fails. 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.
e Both directions demonstrated? Yes. Same test file, same command, only src/ differing: pristine master (Build ID 12f2fdde50966da24c1dde83aba42a144e96e989) 10 failed / 7 passed; with the fix (Build ID 0b336165d7e724d2505ab7f21374da8b70154560) 17 passed. Every baseline failure is a wrong-results assertion ([2, 4, 1, 3], [1, 2, 1, 3], unsorted buckets, ORC wrongly accepted). Repeated 3 more times: 17 passed each.
f Fix is general across code paths? Yes. Read-in-order and aggregation-in-order both reach the same requestReadingInOrder, so one change fixes both, and both are asserted at the plan level (MergingSortedTransform counts; AggregatingInOrderTransform present with optimize_aggregation_in_order = 1 and absent with = 0). Distinct-in-order does NOT reach this step: 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 explicitly rather than assumed. Limit-by is still not enabled for this step upstream and is deliberately left alone. The cluster iterator and the distributed_processing read task are untouched, and a distributed plan declines.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Direction (ASC accepted, DESC declined); per-file format including mixed-format tables, since the predicate runs over the enumerated object list rather than the table format; ORC declines and is tested; archives decline; expression sorting keys (bucket(16, id)) go through the materialize-merge-project bracket and are tested; file counts 1, 2, 3, 6, 30, 200, 800; thresholds 0, 1, 2, 3, 10, 25, 100, including 0 with a file count inside the cap, which is where the group count used to divide by zero; max_threads 1, 2, 4, 8, 96; duplicate keys across files; the zero-file case keeps the NullSource and the one-file case adds no merge.
h Backward compatible? (maintainer-approved exception only) Yes. No setting default changed and no serialization format changed, so no SettingsChangesHistory.cpp entry. The new members are not serialized: the step declines when a distributed plan is being built, so no cached file list can reach serialize. Every decline keeps the sorting step, so results stay correct on all paths.
i Invariants and contracts preserved? Yes. The StorageObjectStorage::read() snapshot pin is intact: enumeration reuses the same pinned snapshot and each single-file iterator forwards getSnapshotVersion(), so the schema-cache key is unchanged. clone() copy-constructs, so the new members survive cloning. The step's output header is unchanged, asserted directly against the step's own pipe header (EXPLAIN PIPELINE header = 1) on the grouping path: an identity projection cannot drop the materialized sorting key, because unmatched header columns are re-emitted, so converting actions are used instead. Enumeration consumes the iterator, so a replaying iterator is installed unconditionally before any rejection can return, and row-count parity is asserted on every declined path. The shared reader pool changes a destructor contract: an in-flight reader task captures this, so a source with a shared pool waits on its own future rather than on the whole pool, and the pool is created with an unlimited queue so scheduling cannot be refused.

Session id: cron:clickhouse-review-slot-48:20260803-115500

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @antaljanosbenjamin @kssenii, could you review this? optimize_read_in_order drops the sorting step for a sorted object storage table, but ReadFromObjectStorageStep never delivered one sorted run per output port, so the merge above it interleaved unsorted inputs and returned unsorted rows; this builds one source per file, skips the output resize, and pins the Parquet preserve_order the guarantee depends on.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a5b16cf]

Summary: ✅


AI Review

Summary

The PR fixes ordering of sorted object storage reads by delivering one sorted run per output port, preserving Parquet row-group order, and retaining the full sort when those guarantees cannot be established. Reviewed head a5b16cf043e5a38d9d3e3e4f0d5fb478b56e0f1c, including all prior discussion and the current implementations. The earlier findings are addressed; no remaining actionable findings were identified.

Missing context / blind spots
  • ⚠️ No local ClickHouse build was available, so runtime tests were not rerun. The latest head's integration and sanitizer results were not available at review time; completed CI runs of test_read_in_order.py would close this validation gap. Earlier reported regression runs and the current test coverage support the fix.
  • ⚠️ Cloud-only distributed-read implementations and the private sync failures were unavailable in this checkout; this review covers the public implementation.
Final Verdict

✅ Approve — no code changes requested. Integration and sanitizer validation of the latest head remains pending.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
… 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]>
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6a0cca6

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'globalNullIn' (STID 0250-41a5) Trunk bug, not caused by this branch: a fuzzer query reaches a set-dependent function before its FutureSet is built. This diff touches read-in-order and object-storage sources only, not set resolution. Breadth over 30 d: 207 rows / 160 PRs / 14 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Build (arm_release) / Post Hooks CI harness: build_profile_hook.py telemetry upload fails in prepare-time-trace.sh (LogCluster warning). Job-level check_status = success (the hook carries allow_failure), so the build itself is green. Breadth over 7 d: 1712 rows / 368 PRs / 1193 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Bugfix validation (integration tests, amd64 + aarch64) / 7 x test_storage_iceberg_with_spark/test_read_in_order.py Not a failure to own: this is the bugfix-validation contract working as designed. The check runs this PR's new tests against the previous-release binary, which must fail to prove they catch the bug. Both jobs report check_status = success not a failure - bugfix-validation contract (job-level success on both arches)

153 success, 21 skipped, 1 failure out of 175 check-runs. Finish Workflow succeeded.

Session id: cron:our-pr-ci-monitor:20260803-200000

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
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.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Wrong results for a nullable sorting key that contains NULLs

I measured this while checking the change above. It is a wrong-results defect that this PR does
not fix, so it is worth settling before merge.

Iceberg specifies null-order per sort field, independently of direction. Spark writes
"null-order": "nulls-first" for WRITE ORDERED BY id, but
getSortingKeyDescriptionFromMetadata reads only direction and transform, so the imported key
carries ClickHouse's default null placement instead. Measured on a two-file table with NULLs in
both files (id BIGINT, WRITE ORDERED BY id):

SELECT id FROM t ORDER BY id SETTINGS max_threads = 1
  -> \N, 3, \N, 2      (sorting step dropped)
SELECT id FROM t ORDER BY id SETTINGS max_threads = 1, optimize_read_in_order = 0
  -> 2, 3, \N, \N      (correct)

Neither cheap containment works. Declining on "nullable key column" disables the optimization for
every table here, since id BIGINT is nullable in Iceberg. Declining on "null order differs from
the ClickHouse default" disables it for ordinary Spark-written tables, because nulls-first is
Spark's default and nulls-last is ClickHouse's. Carrying the null order properly needs a field
KeyDescription does not have today: it has reverse_flags and no null flags. So this is a design
choice rather than a patch, either extending KeyDescription, or keeping the null order on the
Iceberg side and applying it where the sort descriptions are built.

@alexey-milovidov which would you prefer, and would you like it here or separately given #100394?

@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

⚠️ Significant changes: object file sizes.

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 ⚠️

11 object files changed (+502.86 KiB total), 0 added.

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7f67ed3

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) not caused by this diff: a CI-harness resource defect on master. docker compose stop signals every container of a cluster at once, so each node that outlives the 60s shutdown deadline attaches gdb to dump thread stacks at the same moment, and gdb has to read the whole binary's debug info. The concurrent copies exhaust the /docker cgroup leaf that parents the nested containers (CI_DIND_NESTED_BUDGET), the kernel kills them, and the shard reports this leaf breach instead of a test result. Signature is two days old and fleet-wide: 298 rows over 108 distinct pull requests and 32 true-master commits, Integration tests only #117202 (external, merged 2026-08-31T11:05Z) - this build predates it
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) same defect, sibling shard of the same job. Shards 1/6 to 4/6 of this run are green #117202 (external, merged 2026-08-31T11:05Z) - this build predates it

The owner is merged but absent from the tree that ran: the lock the fix introduces in
tests/integration/integration-tests-entrypoint.sh is present at its merge commit, absent at this
head, and absent at the pre-fix control. I am not pushing a master merge only to pick it up, since
the next push on this branch collects it anyway.

The two Bugfix validation (integration tests, *) jobs are green. Their FAIL rows in the CI
database are the expected inversion for that check: the new test_read_in_order.py cases must fail
on master for the validation to pass, which is what they did on both arches.

groeneai and others added 3 commits November 10, 2026 18:09
…-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]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ee2bf8a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) / 05019_cascades_replicated_total_rows flaky, not from this PR: the distributed-plan JOIN ... USING (k) count came out 4x (800000 instead of 200000) with 4 workers; it reproduces only with the randomized query_plan_optimize_join_order_randomize and index_granularity = 103 and passes 49/49 without randomization. It also failed on master and on 4 other PRs in the last 30 days #129420 (mine, open)
Mergeable Check, PR praktika rollups of the row above #129420 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

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]>
@murphy-4o

Copy link
Copy Markdown
Member

@groeneai, please investigate the CI failures in this PR (commit 2519c50) and fix them, or link existing fixes.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113095&sha=2519c501dfd6335ab4bba44beb9c71f2cc1252bd&name_0=PR

Also, 6 failures in the private sync PR.

@murphy-4o
murphy-4o added this pull request to the merge queue Nov 12, 2026
@murphy-4o
murphy-4o removed this pull request from the merge queue due to a manual request Nov 12, 2026
# Conflicts:
#	src/Processors/QueryPlan/ReadFromObjectStorageStep.cpp
@murphy-4o
murphy-4o enabled auto-merge November 12, 2026 09:56
@murphy-4o
murphy-4o added this pull request to the merge queue Nov 12, 2026
Merged via the queue into ClickHouse:master with commit 161b258 Nov 12, 2026
203 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 12, 2026
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Nov 12, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Public CI on 2519c501 had one real failure, and it is not caused by this PR:

Check / test Reason Owner / fixing PR
AST fuzzer (arm_asan_ubsan) / Logical error: 'IAggregateFunction::merge called with the same source and destination state' (STID: 2508-4ac1) window -State self-merge of a zero-size state in AggregateWindowFunctionRecalculate::evaluate; the retry passed #130678 (merged)
Bugfix validation (integration tests, amd64 / aarch64) / test_read_in_order.py::* expected: the new tests fail without the fix, the check itself is green -
CH Inc sync (6 failures) - CH Inc sync (private, not actionable by me)

I checked the fuzzer query both ways: the CI amd_debug build of 2519c501 aborts at IAggregateFunction.h:263, current master 7a987ba2 (includes #130678) returns the 10 rows.

One more thing: the Closes: lines of this PR sit inside the template's HTML comment, so GitHub did not link #112981, #130439, #130440, #127434 and #127435, and all five are still open. I don't have the permission to close them.

murphy-4o pushed a commit that referenced this pull request Nov 15, 2026
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]>
robot-ch-test-poll3 added a commit that referenced this pull request Nov 15, 2026
Cherry pick #113095 to 26.10: Deliver one sorted run per stream reading object storage in order
robot-clickhouse added a commit that referenced this pull request Nov 15, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 15, 2026
clickhouse-gh Bot added a commit that referenced this pull request Nov 15, 2026
Backport #113095 to 26.10: Deliver one sorted run per stream reading object storage in order
@fm4v fm4v removed the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 16, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Nov 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

8 participants