Skip to content

Reject an array whose elements were not read outside the MergeTree readers - #115528

Merged
alexey-milovidov merged 17 commits into
masterfrom
fix-array-empty-elements-outside-mergetree
Sep 12, 2026
Merged

alexey-milovidov merged 17 commits into
masterfrom
fix-array-empty-elements-outside-mergetree

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

Reading a Log table whose array sizes stream is there while its array elements stream is not returned a ColumnArray that reports rows whose elements are not present. Every consumer then indexes the elements column out of bounds. On the BuzzHouse (arm_asan_ubsan) master run below, SELECT * FROM d0.t37 LIMIT 100 over a Map(Map(Enum8, Date), Int32) column tripped the PODArray assertion in ColumnArray::sizeAt while sortBlock was permuting that column; in a release build the same read silently returns garbage (the Map reads back as {'':0,'':0}).

SerializationArray::deserializeBinaryBulkWithMultipleStreams allowed that state for the sizes encoding. It is legitimate in one place only: a column of a Nested type that was added by ALTER reads from the parts written before that ALTER with its shared sizes stream present and its elements stream missing. The MergeTree readers record such a column in partially_read_columns, discard it and fill it with defaults in IMergeTreeReader::fillMissingColumns, so nothing downstream ever sees it. Log and TinyLog have no such step and hand the column straight to the query pipeline.

Deserialization now rejects an empty elements column with a non-zero last offset with INCORRECT_DATA, naming the column and the path, unless the caller sets the new partially_read_columns_are_refilled flag - which only MergeTreeReaderWide and MergeTreeReaderCompact do.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8d087c3c23fb6c25532270957bdb5eddb1947872&name_0=MasterCI&name_1=BuzzHouse%20%28arm_asan_ubsan%29

Related: #109212

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):

Fix reading a Log or TinyLog table whose array or map elements are missing while their sizes are present: such a table returned rows with elements that are not there and made the server read out of bounds. It is now reported as INCORRECT_DATA.


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

…aders

`SerializationArray::deserializeBinaryBulkWithMultipleStreams` accepted an empty
elements column with a non-zero last offset for the sizes encoding. The resulting
`ColumnArray` reports rows whose elements are not there, so every consumer indexes
the elements column out of bounds - `ColumnArray::sizeAt` tripped the `PODArray`
assertion while `sortBlock` permuted a `Map(Map(Enum8, Date), Int32)` column read
from a `Log` table:

    Logical error: '(n >= (static_cast<ssize_t>(pad_left_) ? -1 : 0)) && (n <= static_cast<ssize_t>(this->size()))'
    DB::ColumnArray::sizeAt(long) const
    DB::ColumnArray::indexImpl<unsigned long>(...) const
    DB::ColumnMap::index(DB::IColumn const&, unsigned long) const
    DB::ColumnTuple::index(DB::IColumn const&, unsigned long) const
    DB::ColumnArray::indexImpl<unsigned long>(...) const
    DB::ColumnMap::permute(...) const
    DB::sortBlock(...)

That state is legitimate in one place only: a column of a `Nested` type that was
added by `ALTER` reads from the parts written before that `ALTER` with its shared
sizes stream present and its elements stream missing. The MergeTree readers mark
such a column in `partially_read_columns`, throw it away and fill it with defaults
in `IMergeTreeReader::fillMissingColumns`, so nothing else ever sees it. Everyone
else - `Log`, `TinyLog` - hands the column straight to the query pipeline.

Deserialization now rejects it with `INCORRECT_DATA` unless the caller sets the new
`partially_read_columns_are_refilled` flag, which the two MergeTree readers do. The
`Log` engine reported plausible garbage before the fix (a `Map` read back as
`{'':0,'':0}`) and now names the column and the path it could not read.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=8d087c3c23fb6c25532270957bdb5eddb1947872&name_0=MasterCI&name_1=BuzzHouse%20%28arm_asan_ubsan%29

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [21b3e47]

Summary: ✅


AI Review

Summary

This PR tightens SerializationArray so a sizes-encoded array whose last offset is non-zero but whose elements were not read is rejected unless the caller is a MergeTree reader that will discard and refill that column, and it threads that allowance through the wide/compact MergeTree readers with focused regression coverage. I did not find a remaining correctness, compatibility, or evidence gap on the current head.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit 21b3e47.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 20/20 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 20, 2026
@tiandiwonder tiandiwonder self-assigned this Aug 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

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

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

Compile time of recompiled translation units

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

Job report

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Shorten the comments.

`MergeTreeReaderWide` and `MergeTreeReaderCompact` set
`partially_read_columns_are_refilled` for every column they read, while
`IMergeTreeReader::fillMissingColumns` only replaces the columns recorded
in `partially_read_columns`. A column whose elements file is present but
holds no data is not recorded there, so its `ColumnArray` with offsets
past the end of its elements still reached the query pipeline. Each
reader now sets the flag only for the columns it will actually refill.

The gtest for the accepted case is replaced by
`05024_mergetree_array_missing_elements`, which drives the real MergeTree
readers: a `Nested` column added by `ALTER` still reads as defaults from
the older parts, while an emptied elements file is now reported as
`INCORRECT_DATA`. Keeping it as a unit test also broke
`Bugfix validation (unit tests)`, whose before-binary is compiled with
the fix reverted and therefore without the new flag.

Add the `log-engine` tag to `05023_log_array_missing_elements`, which
otherwise breaks under `--replace-log-memory-with-mergetree`, and trim
the comments that repeated the flag's declaration.
…es are missing

Both tests located the files to corrupt with an unguarded `find | head -n 1`: when `find`
matched nothing, `dirname ''` collapsed to `.` and the tests passed vacuously without
corrupting anything, which is how `05024_mergetree_array_missing_elements` failed on
`Fast test (arm_darwin)` - the part has no `a.bin` there for a reason not yet known.

`05024` now asks `system.parts` for the active part path instead of searching, and exits
with a listing of the parts and files when `a.bin` is not where it must be, so the next
darwin run shows the actual part layout. `05023` requires exactly the three element files
of the `Log` table and the `sizes.json` next to them.

#115528
alexey-milovidov and others added 4 commits August 27, 2026 03:54
…tive filesystem

`Fast test (arm_darwin)` failed on this test because on a case-insensitive
filesystem every stream file of a MergeTree part is stored under the hash of
its name (`replaceFileNameToHashIfNeeded`), so there is no `a.bin` to
truncate - the diagnostics added earlier showed the part holding
`1fa2c35cbbcd93388960cb3c765e3171.bin`, which is
`lower(hex(reverse(sipHash128('a'))))`. The test now resolves the elements
file by trying both the plain and the hashed name, and still exits with an
error listing the part layout when neither is there.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115528&sha=46bd9a99cf4bfdd9a62211d2dda98a20a919f501&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29

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

@tiandiwonder tiandiwonder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving. All six findings from rounds 1-3 are closed, and this round closed the last open question too.

The arm_darwin failure turned out not to be the fix at all — it was the test looking for a.bin where MergeTree stores every stream under sipHash128 of its name on a case-insensitive filesystem, independently of replace_long_file_name_to_hash. I checked the new formula against real on-disk names rather than reading it: forcing the same layout with replace_long_file_name_to_hash = 1, max_file_name_length = 0 gives 1fa2c35cbbcd93388960cb3c765e3171.bin, exactly what lower(hex(reverse(sipHash128('a')))) returns, and sipHash128('k') is a different one of the three files so the probe can't land on the key column. Deriving the digest from the server instead of hard-coding it is the right call — it can't rot. 05024 no longer appears in the arm_darwin failures.

Two jobs are still red and neither is this PR: Fast test (arm_darwin) fails only on 01599_multiline_input_and_singleline_comments (an expect test killed at 60 s with Operation not permitted while sending SIGKILL — macOS runner permissions), and Stateless tests (arm_binary, parallel) only on 05047_distributed_plan_finished_stages_drain with NO_SUCH_DATA_PART on a distributed read. Neither 05023 nor 05024 fails anywhere on this head.

I've replied on @clickhouse-gh's compact-coverage thread — short version, the existing compact arm already pins that reader, and the test it asks for isn't constructible. Resolving my own threads; this approval also supersedes my stale CHANGES_REQUESTED from Aug 20, whose findings are all resolved.

`MergeTreeReaderCompact::readData` gained the same
`partially_read_columns.contains(name)` gate as the wide reader, while
`05024_mergetree_array_missing_elements` only corrupted a wide part, so a
regression in the compact reader would have kept the test green.

Every column of a compact part lives in `data.bin`, and the sizes and the
elements of an array share one compressed block unless their codecs differ, so
the corrupted table gives its elements a codec of their own (`Delta`). Cutting
`data.bin` at the mark of the elements substream - read from
`mergeTreeIndex(..., with_marks = 1)` - then leaves the sizes of `a` in place
and takes its elements away, and reading the column reports `INCORRECT_DATA`.
@clickhouse-gh clickhouse-gh Bot added the comp-data-types Type system & core datatypes used across query planning/execution. label Sep 4, 2026
…ompact part is missing

If `mergeTreeIndex` returns no mark for the elements substream of `a`, `truncate -s ""` only
writes to stderr and the compact arm of the test reports a bare `0`. Print the marks and exit
instead, as the wide arm already does when it cannot find the elements file.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failures on this head — none of them touch this PR (it only changes SerializationArray and the two MergeTree readers), and please provide fixes in separate PRs (link them here if already in progress):

I have merged master (c3c86220a8a4) into the branch to pick up anything already fixed there; CI will re-run on the fresh head.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Investigated all three on 427bc813. None reaches this diff. The two stateless failures are one cascade with three open fixes, one of them yours; the BuzzHouse row is the job's own memory ceiling and has no fixing PR yet.

04648 and 04340 are one defect. In that job 04648 ran 8 minutes before 04340 (15:10:52 and 15:19:19 in the job log), same sequential bucket.

  1. 04648 expects CANNOT_SCHEDULE_TASK and got Code: 1000 ... peer closed connection, because ReadFromDistributedPlanSource::tryGenerate ran cleanupLocked before rethrowing: the cleanup closes this query's own exchange sockets, and PipelineExecutor reports the first node in graph order that holds an exception, so the socket error replaced the recorded failure. Your Report a distributed plan's root cause, not its exchange teardown error #118417 fixes exactly this.
  2. tests/clickhouse-test:3904 runs the .sql with --multiquery and no --ignore-error, and ClientBase.cpp:3722 stops the file at the unexpected error, so the next line, SYSTEM DISABLE FAILPOINT distributed_plan_record_failure_while_starting_tasks, never ran. That failpoint is REGULAR (FailPoint.cpp:360), i.e. armed process-wide until disabled.
  3. It then fired inside 04340's query, at the top of the per-task loop in DistributedPlanExecutor::startStage (:1765), so checkCancelled() threw before a single task was dispatched: no status poll, no re-enqueue, no TaskTracker::recordFailure line, hence reenqueue fault handled: 0. Failed 0 out of 3 reruns is expected here, because --diagnose-random-settings replays the failed tests alone, without 04648 in front of them.

Three open PRs, any one of which clears both rows:

PR What it removes
#118417 (yours) both halves: the rethrow ordering, and ONCE(distributed_plan_record_failure_while_starting_tasks) disarms the failpoint after its single trigger, so an aborted file cannot leak it
#118390 (mine) the same 439 to 1000 substitution from the reader side, so 04648 reaches its DISABLE
#105942 (@ Diskein, approved) the class: the runner resets enabled failpoints after each no-parallel test. 9 other stateless files can leak a REGULAR failpoint the same way

None is merged, so c3c86220a8a4 carries none of them and the pair can fail again on the fresh head. #118417 and #118390 overlap on the 04648 signature; I would rather not land two PRs on that path, so say the word if you want mine reduced to the exchange-source reporting path and its gtests, or closed.

BuzzHouse (arm_asan_ubsan) is the job's memory ceiling. The container runs with --memory=57608769536 (53.65 GiB) and run-fuzzer.sh sets max_server_memory_usage_to_ram_ratio to 0.75, so the server's cap was 40.24 GiB. The first rejection in server.log reads current RSS: 40.26 GiB, maximum: 40.24 GiB; RSS then kept growing to 52.76 GiB while the tracker rejected 48,585 allocations over the next five minutes. Rejecting new allocations cannot release what is already resident, so the liveness probe never got SELECT 1 through (its MEMORY_LIMIT_EXCEEDED branch, 100 retries) and the job force-stopped the server: server exit 137, fuzzer exit 143 from its own 30 minute SIGTERM. No product failure in it: no sanitizer report (only the makecontext/swapcontext ASan warning), no core dump, no logical error, and zero hits in the 4.17 GiB server log for this PR's elements column is empty while the last offset or Cannot read all array values. BuzzHouse generates its own SQL and never ran the two new .sh tests.

That descriptor has no fixing PR yet: a fix task owns it and I will post the link here when it opens. Since it may recur on the fresh head, the rate: 33 rows in 30 days, at most 2 on any day before 09-03 and 4 to 7 per day since, almost all AST fuzzer (amd_debug*); this is the only BuzzHouse (arm_asan_ubsan) occurrence in the window.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thank you for the analysis — the failpoint-leak cascade explains both rows, and it matches what the head shows.

On the overlap: let's land #118417 as the fix for this red. It is two files, and it removes both halves at once — the rethrow ordering in ReadFromDistributedPlanSource::tryGenerate, and the ONCE(distributed_plan_record_failure_while_starting_tasks) change that makes an aborted .sql file unable to leak the failpoint into the next test. That is the minimum needed to stop 04648 from turning into an 04340 failure eight minutes later.

#118390 should not land the same 439-to-1000 substitution a second time. Please reduce it to the part #118417 does not touch — the exchange-source reporting path itself (StreamingExchangeSource / StreamingExchangeLookup ownership) and the gtest_exchange_server_handshake coverage — and rebase it on top of #118417 once that merges. If, after removing the overlapping half, nothing substantial remains beyond the gtests, move the gtests into #118417 and close #118390.

#105942 is the one I want independently of the above: resetting enabled failpoints after each no-parallel test fixes the class, not this instance, and the nine other files that can leak a REGULAR failpoint are a real hazard. It is approved already.

On BuzzHouse (arm_asan_ubsan): agreed it is the job's own memory ceiling with no product signal in it — no sanitizer report, no core, and no hit for this PR's elements column is empty while the last offset or Cannot read all array values in the server log. Please link the fix PR here when it opens.

This branch has now been merged with master again (d7e88825), so the fresh run is on current master; none of the three fixes above is merged yet, so the pair may still fire.

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator

Agreed on landing #118417 as the fix for this red.

On reducing #118390: there is no overlapping code to remove. #118417 is src/Common/FailPoint.cpp (the ONCE flip) and src/Processors/Sources/ReadFromDistributedPlanSource.cpp (the rethrow ordering, plus dropping the cleanup from the catch). #118390 touches neither. Its only contact with that class is the header, so the source takes the query's DistributedQueryCancellation instead of creating its own; everything else is the ownership chain that carries that object out to the exchange sources (QueryPlan::convertToDistributed -> createExchangeLookup -> createStreamingExchangeLookup -> StreamingExchangeSource), the readFromSocket reporting path itself, and the gtest_exchange_server_handshake cases. What the two PRs share is the outcome for this signature, not any lines.

So the question is not what to strip, but whether that reporting path still changes anything once your ordering is in. By the reasoning in your catch comment, onCancel performs the cleanup after the task queue is finished, so no source of that pipeline runs again to observe the teardown close. I have not measured whether a path remains where an exchange read fails while a failure is already recorded. Plan: rebase #118390 on #118417 once that merges, measure the reporting path there with and without the readFromSocket translation, and report the result on #118390. If nothing beyond the gtests changes an outcome, I will close #118390 as you describe; since I cannot push to your branch, I will post the gtest cases on #118417 for you to pick up.

#105942: nothing from me, and I will not touch it.

BuzzHouse (arm_asan_ubsan): no fixing PR for the memory ceiling exists yet. I will post the link here when it opens.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (30c98e714f85) into the branch — it was 2424 commits behind. Clean merge, no conflicts, and no API drift: SerializationArray.cpp, MergeTreeReaderWide.cpp, MergeTreeReaderCompact.cpp and gtest_serialization_array_offsets.cpp all recompile as-is, and both 05099_log_array_missing_elements and 05099_mergetree_array_missing_elements pass locally against the freshly linked binary.

On the two reds of d7e88825:

No unresolved review threads; the AI Review reports no remaining inline findings, and the description and changelog entry still match the diff exactly (SerializationArray rejects an empty elements column with a non-zero last offset unless the caller sets partially_read_columns_are_refilled). Awaiting the fresh CI run on the new head; the merge is for a human.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Status on 21b3e47e: the only red left is CH Inc sync, and it is not caused by this PR.

The sync status reads tests failed (1 new, 3 known). The private sync PR is clickhouse-private#69863; it merges cleanly and builds, and the single failing job is Stress test (arm_asan_ubsan, SharedCatalog, meta in keeper). Its four failure rows are one cascade:

  • Cannot start clickhouse-server — the server process did not come up after 31 start attempts, every attempt ending in Code: 999. Coordination::Exception: All connection tries failed while connecting to ZooKeeper. nodes: [::1]:9181, [::1]:19181, [::1]:29181. That is the job's Keeper not being reachable, i.e. environment, not code.
  • Logical error: 'false' in ObjectStorageQueueMetadata::unregisterNonActive (src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp:986), reached from StorageObjectStorageQueue::shutdown → IStorage::flushAndShutdown → InterpreterDropQuery::executeToTableImpl while dropping a database through SharedDatabaseCatalog::tryExecuteDDLQuery. This is the known Shared Catalog defect tracked in clickhouse-private#38454 ("Logical error in ObjectStorageQueueMetadata::unregisterNonActive with Shared Catalog"), and the same job is failing on other open sync-upstream/pr/* PRs.
  • Test script failed and Check failed are just the script and job roll-ups of the two above.

Neither path touches this diff: the PR only changes SerializationArray and MergeTreeReaderWide / MergeTreeReaderCompact, and nothing in the stack trace goes through array deserialization or a MergeTree reader. I re-ran the failed job (private run 34670626166); it is queued now.

Everything else is settled on this head: all public checks green, 0 unresolved review threads, AI Review ✅ No new findings, approved by @tiandiwonder, and the branch merged master (30c98e714f85) earlier today with both 05099_log_array_missing_elements and 05099_mergetree_array_missing_elements passing locally. Nothing to push — awaiting the sync rerun and a human merge.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 12, 2026
Merged via the queue into master with commit 5fb1471 Sep 12, 2026
175 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-array-empty-elements-outside-mergetree branch September 12, 2026 19:04
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 12, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@alexey-milovidov @tiandiwonder — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-data-types Type system & core datatypes used across query planning/execution. pr-bugfix Pull request with bugfix, not backported by default 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.

5 participants