Skip to content

Do not read part sizes while committing under the parts lock - #112691

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-3563-40df-noexcept-scope-async-read
Aug 29, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-3563-40df-noexcept-scope-async-read

Conversation

@groeneai

Copy link
Copy Markdown
Collaborator

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

Fixes a server abort while committing a mutated part. Accounting for a part whose column and secondary index sizes were not computed yet read them from the part storage inside a critical section documented as non-throwing, so a failure to start a thread for that read terminated the server instead of being reported.

Description

MergeTreeData::Transaction::commit updates the table-level column and secondary index size aggregates from inside a NOEXCEPT_SCOPE, whose catch-all calls std::terminate. Accounting for a part whose own sizes were not computed yet called the part's size getters, which compute them from the part storage; on packed storage that reads the skip-indices archive. Under the default local_filesystem_read_method = 'pread_threadpool' that read is submitted to a thread pool, so a failure to schedule it raises CANNOT_SCHEDULE_TASK. That is not a memory-tracker exception, so LockMemoryExceptionInThread does not hold it back and it escapes the scope.

Such a part now invalidates the table aggregates instead of having its sizes read, and the next reader rebuilds them from the active parts. That is already the state before the first size query on the default columns_and_secondary_indices_sizes_lazy_calculation = 1, and the consumers are advisory statistics. A part whose sizes are known keeps the existing arithmetic. This also drops a hasSecondaryIndex check that resolved an index file through the part storage, while getSecondaryIndexSize already returns an empty size for an absent index. Separately, both recompute paths cleared only the two size maps, so primary_index_size was double counted on every rebuild; it is now cleared too. The change is in MergeTreeData, so it covers plain and replicated tables and every Transaction::commit call site.

Observed on master (Stress test (amd_msan), commit 27b5773, Received signal 6 (internal) (STID: 3563-40df), CI report).

The new test measures the extra storage access itself, through the MutatePart row of system.part_log, against a warm control; the scheduling step is established by the stack above rather than by the test. It pins the lazy size calculation. A sweep of related stateless tests found no failure that is unique to the fixed build.

groeneai and others added 4 commits July 30, 2026 02:55
`MergeTreeData::Transaction::commit` updates the table-level column and
secondary index size aggregates from inside a `NOEXCEPT_SCOPE`, whose
catch-all calls `std::terminate`. Accounting for a part whose own sizes
were not computed yet called the part's size getters, which compute them
from the part storage; on packed storage that reads the skip-indices
archive through the thread-pool reader. When scheduling that read fails,
the resulting `CANNOT_SCHEDULE_TASK` is not a memory-tracker exception,
so `LockMemoryExceptionInThread` does not hold it back: it escapes the
scope and aborts the server.

A part arrives with its sizes uncomputed whenever it was produced by a
path that calls neither warm site, which on the default
`columns_and_secondary_indices_sizes_lazy_calculation = 1` includes the
untouched-part mutation shortcut and ordinary part load.

Account for such a part by dropping the table aggregates instead of
reading its sizes, and let the next reader rebuild them from the active
parts, which is already the state before the first size query on that
default. A part whose sizes are known keeps the existing arithmetic and
answers from its cached maps, so it performs no IO either.

Also drop the `hasSecondaryIndex` check in the subtract path: it
resolves an index file through the part storage, which reads on packed
storage, while `getSecondaryIndexSize` already returns an empty size for
an index the part does not have.

Clear `primary_index_size` in both recompute paths alongside the two
size maps. It has a single writer and neither path cleared it, so a
recompute double-counted the primary index; this change makes recompute
reachable on a new path.

Verified with probes at the scope boundary and at every storage entry
point below it: before this change one mutation performs 1 lazy size
calculation, 2 index-existence resolutions, 12 storage overlay probes,
1 archive read and 1 thread-pool submit inside the scope; after it, zero
of each, with identical query results and identical size aggregates.
The fix removes a part-storage read from MergeTreeData::Transaction::commit's
NOEXCEPT_SCOPE. On packed storage that read resolves the skip-index archive
index, and on object storage it is handed to a thread pool; a pool that cannot
schedule throws CANNOT_SCHEDULE_TASK, which is not a memory-tracker exception,
so it escapes the scope and terminates the server.

The test measures the read through the MutatePart row of system.part_log. That
row is usable because ProfileEventsScope is opened at function scope in
MutatePlainMergeTreeTask::executeStep, so it covers transaction.commit, and
write_part_log runs after the commit on the same thread.

An object-storage disk is required: on a local disk the same read is served
from the OS page cache and never reaches the pool, because
PackedFilesReader::patchSettings clears direct_io_threshold, so the scheduling
call short-circuits and the arms cannot be told apart.

The cold arm is compared against a warm control that computed its sizes at load
time, so the assertion needs no absolute counts. The comparison is strictly
fewer rather than no more than: the unfixed build reads exactly as much as the
control, so a no-more-than assertion would hold on both builds.

Verified against five binaries: it passes on the fix, fails on the unfixed
build, fails with only the invalidation reverted and with the predicate made to
read, and passes with only the hasSecondaryIndex probe restored, so it pins the
lazy-size carrier rather than that probe. 50 randomized runs pass with no tags
beyond no-fasttest, and a 198-test sweep shows no other verdict change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The correctness assertion in the regression test only required
data_compressed_bytes > 0 for the two secondary indices, which also passes for
a double-counted or a truncated aggregate, while the claim being sold is that
invalidate-and-rebuild is equivalent to the incremental update. It also said
nothing at all about column_sizes, the other aggregate the fix clears.

Replace it with two rows that compare the cold table against the warm control
exactly, on all three size fields, over both system.data_skipping_indices and
system.columns. The warm control never takes the invalidation branch, so it
holds the incrementally updated answer while the cold table holds the rebuilt
one. A count and a positivity guard keep the rows from passing on an empty join
or an all-zero answer.

A relative comparison rather than absolute byte counts matters more than it
looks: tests/config/install.sh draws default_compression_codec per install, so
the same fixture writes 7549 compressed bytes under LZ4, 4577 under ZSTD(1) and
3947 under ZSTD(3). Both tables are written by one server under one draw, so the
comparison is stable where absolute values would be flaky.

The fewer_pool_read comment claimed the counter measures the scheduled hand-off
to the read thread pool. It does not. ThreadpoolReaderReadBytes is incremented
inside ThreadPoolRemoteFSReader::execute, and on this path
AsynchronousBoundedReadBuffer::nextImpl has no prefetch future in flight, so it
calls readSync, which runs execute directly on the mutation thread. That is why
the counter is visible to the MutatePart scope at all: on the scheduled path the
increment happens on a pool worker under its own thread group, which the part-log
snapshot cannot collect. The assertion is a valid second read-volume signal and
is kept unchanged; only the comment is corrected.

Also backtick literal names in the test comments, per .claude/CLAUDE.md.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…comment

The guard read `MutationUntouchedParts` from `system.events`, whose counters are
process-wide and lifetime-cumulative (`StorageSystemEvents::fillData` reads
`ProfileEvents::global_counters`). The test is deliberately parallel-safe, so a
concurrent stateless test taking the same shortcut satisfied the assertion for
it, and a value produced before the test started satisfied it too. That row is
the fixture's anti-vacuity guard, so failing open would let the fixture silently
stop exercising the clone-and-keep-block-range path while still reporting OK.

Read the counter per table from the `MutatePart` row of `system.part_log`
instead, for both arms in one row. The increment happens inside
`mutate_task->execute()` under the `ProfileEventsScope` that
`MutatePlainMergeTreeTask::executeStep` opens, and `write_part_log` runs after it
on the same thread, so it lands in each table's own row. Measured: pointing the
cold arm's ALTER at a row that exists takes the value from 1 to 0 and reddens the
test, while the old row still reads 1 on that same state once another database
has taken the shortcut.

The opening comment also attributed the thread-pool scheduling to object storage,
which contradicted the comment above the read-volume assertion and did not match
the reproduced abort: those frames are the local-fs `pread_threadpool` reader
(`AsynchronousReadBufferFromFileDescriptor::asyncReadInto` ->
`ThreadPoolImpl::scheduleImpl`), and this fixture's own read runs synchronously.
State the scheduling under the default `local_filesystem_read_method`, and
explain the object-storage disk separately as what makes the extra access
measurable as read volume.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (4 review rounds, 3 fix rounds; 10 automated findings, 13 self-review findings). Click to expand.

Before opening this PR I put the change through repeated independent review: a cold code review by
a reviewer that had not seen the investigation, plus an automated adversarial pass per revision.
Every finding is listed with its verdict. Blockers and majors that were agreed are already fixed in
the diff; disagreements carry the measurement that settles them.

❌ Agreed and fixed

# Finding What changed
1 The size aggregates were only ever measured through the table maps, so a naive fix could pass while the underlying read still happened. The test now measures the extra storage access itself, through the MutatePart row of system.part_log, against a warm control.
2 cold <= warm is satisfied by the unfixed build, where the two are equal, so the assertion would have proved nothing. Changed to a strict cold < warm, which is the discriminator between the two builds.
3 The first shipped fix covered only the lazy size getters and left hasSecondaryIndex resolving an index file through the part storage, which reads on packed storage on a warm part too. That check is removed; getSecondaryIndexSize already returns an empty size for an index the part does not have, so the subtraction is arithmetically unchanged.
4 Both aggregate recompute paths cleared the two size maps but not primary_index_size, so it accumulated on every rebuild. Cleared in both recompute paths and in the new invalidation.
5 The anti-vacuity guard read MutationUntouchedParts from system.events, which StorageSystemEvents::fillData fills from process-wide cumulative counters, so a concurrent test taking the same shortcut satisfied it and it failed open. Replaced by a per-table read from the MutatePart row, asserted for both arms. Measured liveness: it reads 1 on the shipping fixture and 0 when the shortcut is not taken.
6 The opening test comment attributed the thread-pool scheduling to object storage, contradicting a later comment in the same file. Rewritten: the scheduling is on the default local_filesystem_read_method = 'pread_threadpool' path, which is where the observed abort came from; the object-storage disk is used only to make the extra access measurable as read volume.
7 A claim that no test could be written was too strong, and the sweep sentence in the description was not supported by what had been measured. Both corrected in the description; a test ships.

⚠️ Disagreed, with the measurement

A deferred size calculation that throws and is then retried can double count a part's total
column and secondary index sizes.
The defect is real and I verified every step of it, but it is
pre-existing, outside this diff, and this change strictly reduces its reachability.

  • Every file involved is untouched here. git diff --name-only lists only IMergeTreeDataPart.h,
    MergeTreeData.{cpp,h} and the two test files; IMergeTreeDataPart.cpp and
    MergeTreeDataPartWide.cpp are byte-identical to the merge base, and no added line mentions
    total_columns_size or total_secondary_indices_size.
  • The scenario is reachable today with none of this change: SELECT * FROM system.parts calls
    part->getTotalColumnsSize(), which enters the same computation, accumulates into the persistent
    total, and can throw in the secondary index phase while leaving the part flag false. No table
    aggregate and no Transaction::commit is involved.
  • Inside Transaction::commit this change removes throwable size calculations rather than adding
    any. Before it, a part whose sizes were not computed reached the size getters and entered that
    computation from inside the non-throwing scope. Now it takes the new branch, which reads a boolean
    and returns.
  • At that call site the retry window could not previously open at all, because the throw inside the
    non-throwing scope terminates the server before any retry. Relative to the current behaviour this
    turns a server abort into a pre-existing accounting imprecision reachable by an independent path.

Filed as a follow-up: make the per-part computation retry-idempotent by publishing both totals
atomically alongside the maps, and give resetColumnSizes the same exhaustive treatment. Both live
in the same untouched region and are a separate concern.

resetColumnSizes clears only one of the three aggregates. Pre-existing and byte-identical on
the merge base. Its only caller is dropAllData, which removes every part, so a residual value is
masked by the next rebuild starting from an empty active set. Folded into the same follow-up.

💡 Noted, not blocking

The change replaces an incremental update with an invalidation plus a rebuild from the active parts
on the next aggregate read. That read happens in query planning
(PlannerJoinTree, TreeRewriter, SubstituteColumnOptimizer, ConvertQueryToCNFPass) and in the
system.columns and system.data_skipping_indices tables. The branch only fires for a part whose
own sizes are not computed, and on the default
columns_and_secondary_indices_sizes_lazy_calculation = 1 the aggregates are already absent until
the first size query, so this is the state the table starts in. Three successive cold-clone commits
were measured to produce aggregates byte-identical to a full recompute with no observable slowdown.

Two test comment wordings did not follow the repository convention for function names. Fixed in the
same round.

Session id: cron:clickhouse-review-slot-10:20260730-232100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, for the read the fix removes. The shipped test 04653_packed_part_size_accounting_no_read_in_commit measures it on an object-storage disk through the MutatePart row of system.part_log: FileOpen 12 vs 13 and ThreadpoolReaderReadBytes 32825 vs 33215 against a warm control, where the unfixed build measures 13/13 and 33201/33201. Probes at the scope boundary agree: on the unfixed build one mutation performs, between the scope's entry and exit, 1 lazy size calculation, 2 index-existence resolutions, 12 storage overlay probes, 1 packed-archive read and 1 ThreadPoolReader::submit. The abort itself is not reproducible from SQL, because it needs the pool's scheduling to fail; with the injector armed at probability 1.0 and confirmed live, the mutation still succeeded.
b Root cause explained? Yes. Transaction::commit accounts for the committing part inside a NOEXCEPT_SCOPE; for a part whose sizes are not computed yet that reached the size getters, which compute them from the part storage; on packed storage the skip-indices archive is read through the thread-pool reader; a scheduling failure raises CANNOT_SCHEDULE_TASK, which LockMemoryExceptionInThread does not suppress, so it reaches the catch-all and calls std::terminate.
c Fix matches root cause? Yes. It removes the reason to read (a cold part invalidates instead of calling any getter, and the redundant storage-backed hasSecondaryIndex probe is deleted) rather than guarding the throw. No catch, no widening of LockMemoryExceptionInThread, no change to the scope boundary.
d Test intent preserved / new tests added? Yes, both. No test weakened, and 198 related stateless tests give identical failure sets on both builds. A new stateless test ships: tests/queries/0_stateless/04653_packed_part_size_accounting_no_read_in_commit.sql, on an object-storage disk not because the scheduling happens there, but because that makes the extra storage access deterministically measurable as read volume; on that disk the read runs synchronously, so the test observes the access and the scheduling step is established by the observed stack instead. It asserts strictly fewer file opens and fewer pool-read bytes than a warm control, which is the form that separates the arms: a <= assertion holds on the unfixed build too. It reddens on the unfixed build and on a build with only the invalidation reverted, and the tag-free 50/50 run is 50 OK / 0 FAIL. It pins the lazy size calculation; the hasSecondaryIndex deletion is covered by the boundary probe instead, because with the aggregates invalidated that resolution is answered from the already-probed archive overlay and neither counter can see it. An earlier unit test was written and discarded after it was confirmed to pass on the unfixed build.
e Both directions demonstrated? Yes. Two binaries from one worktree, identical probes, differing only by the fix, each with buildId() asserted equal to its ELF Build ID: unfixed 1/2/12/1/1 in-scope events, fixed 0/0/0/0/0, with identical query results and identical size aggregates. Three separate mutations each restore only their own carrier: reverting the invalidation restores the size calculation and the thread-pool submit; restoring the hasSecondaryIndex probe restores only the index-existence resolutions; making the new predicate call a getter restores the read entirely.
f Fix is general across code paths? Yes. The change is in MergeTreeData and IMergeTreeDataPart, so it covers StorageMergeTree, StorageReplicatedMergeTree and every Transaction::commit call site. Both in-scope carriers are addressed. The six non-commit callers of the two helpers were checked: three call the untouched Unlocked variant, and the other three hold the parts lock exactly as commit does, where invalidation is the same rebuild-on-demand state the lazy default already uses before the first size query.
g Fix generalizes across inputs? Yes. The new predicate reads a bool, so it is type-independent. Both storage kinds are covered by construction because the fix sits above the storage layer; only packed storage has an asynchronous reader, which is what narrows the abort rather than the fix. All four ways a part can reach the commit with uncomputed sizes reach the same two helpers.
h Backward compatible? Yes. No setting added or default changed, no serialization or on-disk format change, so no SettingsChangesHistory.cpp entry. Only the timing of in-memory advisory statistics changes, and the aggregates were measured identical to a full recompute on both builds.
i Invariants and contracts preserved? Yes. The cold branch performs strictly less than before: two map clears and a bool store, all in memory, under the mutex the function already holds, so there is no new ownership, no new failure mode and nothing to unwind on an error path. The new predicate takes the part's own sizes mutex while the caller holds the table's sizes mutex and the parts lock, which is the identical nesting the previous getColumnSize call used from the same sites, so no lock order is introduced and neither critical section widened. primary_index_size is now cleared wherever the other two maps are, which is what makes the newly reachable recompute path correct.

Session id: cron:clickhouse-review-slot-10:20260730-232100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @Avogar @CheSema, could you review this? Transaction::commit accounts for the committing part inside a NOEXCEPT_SCOPE, and for a part whose sizes were not computed yet that called the size getters, which read the part storage, so a failure to schedule that read terminated the server; such a part now invalidates the table aggregates instead and the next reader rebuilds them.

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

clickhouse-gh Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [af3a507]

Summary: ✅


AI Review

Summary

This PR moves column and secondary-index size I/O out of MergeTreeData::Transaction::commit by invalidating the table-level aggregates when a committing part still has lazy size state, then rebuilding those aggregates on demand later. I traced the changed MergeTreeData accounting paths, the per-part size-cache flag in IMergeTreeDataPart, and the new stateless regression test, and I did not find a remaining correctness, concurrency, compatibility, or coverage issue in the current code.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 33/35 (94.29%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - af3a507

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
(none) 174 check-runs, 0 failures nothing to own

Config Workflow and Finish Workflow both completed successfully; no check queued or in progress.

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

@Avogar Avogar self-assigned this Aug 5, 2026
@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

While verifying the ordering hazard around this change I also noticed that locked_parts_to_cleanup in MergeTreeData::Transaction::commit (MergeTreeData.cpp:9878, appended at :9912) is written and never read, so the cleanup its comment promises does not exist. I am not raising it: the !txn path it tracks now goes through VersionMetadataOnDisk::setAndStoreNonTransactionalRemovalTID, which acquires and releases the removal lock inline via SCOPE_EXIT (VersionMetadataOnDisk.cpp:101-103), so no lock outlives the call and there is nothing left to undo; the LOGICAL_ERROR the tracking originally guarded against is additionally excluded for non-transactional TIDs at VersionMetadataOnDisk.cpp:128, and CIDB shows zero occurrences of that message in the last 400 days apart from two rows that both predate its 2026-02-17 fix. The residue is a leftover of that fix, whose caller-side try/catch reader was removed when the version-metadata refactor moved the same guarantee into the callee. Adding the unlock back would in fact throw Cannot unlock removal_tid, it's a bug. (VersionMetadataOnDisk.cpp:153-165), since the SCOPE_EXIT has already zeroed the lock hash, so the only defensible change is deleting the two dead lines and the stale comment, which has no user-reachable consequence.

@alexey-milovidov alexey-milovidov self-assigned this Aug 29, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 29, 2026
Merged via the queue into ClickHouse:master with commit b8fdc06 Aug 29, 2026
180 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 29, 2026
@groeneai

groeneai commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

This fix is not in 26.8, and the abort it fixes now shows up there. Stress test (amd_tsan) on a 26.8 backport PR (version 26.8.35.1) hit std::terminate in Transaction::commit: CANNOT_SCHEDULE_TASK from the packed skip-index read under addPartContributionToColumnAndSecondaryIndexSizes, inside the NOEXCEPT_SCOPE (report).

  • 26.8 was cut five days before this merged and still has the pre-fix code. The diff applies to it cleanly.
  • 26.9 and 26.10 already contain the fix. 26.3 has no packed part storage (DataPartStorageOnDiskPacked), so it does not have this read.

Could this PR get v26.8-must-backport? The backport would also bring 04653_packed_part_size_accounting_no_read_in_commit, which is flaky on master (3 master and 29 PR failures in 30 days). My fix for that is #118234, still open.

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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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