Skip to content

Fix ReadBuffer-canceled abort in GraceHashJoin spilled-block reader - #111056

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-grace-hash-read-after-cancel
Aug 18, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:fix-grace-hash-read-after-cancel

Conversation

@groeneai

@groeneai groeneai commented Jul 20, 2026 •

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

Fixed a LOGICAL_ERROR: ReadBuffer is canceled. Can't read from it. that could occur in a grace_hash join when reading spilled blocks failed mid-read while multiple threads shared the reader.

Description

GraceHashJoin shares one AccumulatedBlockReader between concurrent DelayedJoinedBlocksWorkerTransform threads. If reader->read throws while reading a spilled block, ReadBuffer::next cancels the underlying buffer and rethrows. Previously the shared reader was not marked finished, so a sibling worker could re-enter read on the canceled buffer and throw LOGICAL_ERROR: ReadBuffer is canceled. Can't read from it. The query should instead preserve and report the original read exception.

The fix marks AccumulatedBlockReader finished on every read exception while holding its existing mutex. Subsequent workers return an empty block and cannot re-read the canceled buffer. This covers both the left delayed reader and the right reader that use the same read implementation.

The new stateless regression deterministically forces a failure only in the shared left delayed reader: it cancels the underlying buffer, throws FAULT_INJECTED, verifies the query reports that original exception, and then verifies that the server remains alive. Without the eof assignment, a sibling worker re-enters the canceled buffer and triggers the original logical exception.


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

Version info

  • Merged into: 26.8.1.1598 (included in 26.8 and later)

One AccumulatedBlockReader is shared between concurrent
DelayedJoinedBlocksWorkerTransform threads. When reader->read() threw
mid-read (e.g. a MEMORY_LIMIT_EXCEEDED that cancels the underlying
ReadBuffer via ReadBuffer::next()'s catch), read() propagated the
exception without marking the reader finished. A sibling worker then
re-entered read() on the now-canceled buffer and tripped
chassert(!isCanceled()) ("ReadBuffer is canceled. Can't read from it."),
aborting the server in debug/sanitizer builds.

Set eof on any read failure so subsequent reads on the shared reader
return an empty block instead of re-reading the canceled buffer. The
query still fails with the original exception.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 3 findings across 1 full pass + 1 delta recheck; bounded).

# Sev Finding Verdict Evidence / action
1 ⚠️ Test doesn't deterministically fail without the fix (accepts the first MEMORY_LIMIT_EXCEEDED; the defect needs a sibling worker to re-read) AGREE Confirmed: an injected cancel+throw failpoint did NOT abort the unfixed binary (0/10) — single-query teardown outruns the sibling re-read; this is a true cross-thread race. Proving baseline-fail deterministically would need a spin-barrier in the production hot path (rejected as scaffolding) or a PAUSEABLE failpoint + test coordination. Kept a memory-limit stress guard over the exact spill+concurrency path (asserts graceful failure, never abort; precedent 03277). The fix itself was verified BOTH directions by faithful fault injection: unfixed → SIGABRT with the exact CI stack; fixed → clean propagated exception (see PR description + a–i gate).
2 ⚠️ no-asan/no-tsan removes the builds where the chassert aborts DISAGREE (evidence) The sibling memory-limit spill test 03277_join_adaptive_spill_oom carries exactly no-asan, no-tsan; its git history (fb6a31ad "fix flakiness") shows sanitizer memory overhead shifts the OOM point and makes the exact limit flaky. Debug builds (NOT excluded) still fire the guarded chassert, and both-directions fault-injection proof covers the abort path directly.
3 ⚠️ no-msan removed while the comment says sanitizer overhead makes the limit flaky (internal inconsistency) AGREE — fixed @ 37cbb1c Restored no-msan; the test now excludes all three sanitizers, consistent with its own rationale and with 03277.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding.

Session id: cron:clickhouse-author-slot-3:20260720-094200

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Injecting a mid-read cancel in the shared AccumulatedBlockReader reproduces the abort on demand: unfixed build → SIGABRT (RC=134), "Logical error: 'ReadBuffer is canceled. Can't read from it.'".
b Root cause explained? Yes. One DelayedBlocks (one AccumulatedBlockReader) is shared by all DelayedJoinedBlocksWorkerTransform workers. Worker A's reader->read() throws mid-read → ReadBuffer::next() cancels the buffer + rethrows. read() propagated without setting eof, and IBlocksStream::finished only flips on a normal empty return, so worker B re-entered read() → reader->read() on the canceled buffer → chassert(!isCanceled()).
c Fix matches root cause? Yes. Set eof on any read failure so the shared reader is terminal-on-error; a later read() returns {} instead of re-reading the canceled buffer. Uses the reader's existing mutex+eof invariant. Not a band-aid (does not touch the chassert or reset cancellation).
d Test intent preserved / new test added? New test 04545_grace_hash_join_read_after_cancel added: a grace_hash join that spills then fails mid-read under a tight max_memory_usage with many threads, asserting a clean MEMORY_LIMIT_EXCEEDED rather than an abort. No existing test weakened.
e Both directions demonstrated? Yes (faithful fault injection, instrumentation NOT committed): unfixed → SIGABRT with the exact CI stack (ReadBuffer::next ← NativeReader::read ← AccumulatedBlockReader::read ← DelayedBlocks/getDelayedBlocks ← ...WorkerTransform::work); fixed → clean propagated exception, 0 aborts. New test: 50/50 graceful MEMORY_LIMIT_EXCEEDED, 0 crashes.
f Fix is general across code paths? Yes. The single AccumulatedBlockReader::read() is the only reader->read() in GraceHashJoin and is used by BOTH the left reader (DelayedBlocks::getLeftTableReader) and the right reader (startJoining/getDelayedBlocks), so one fix covers the whole class.
g Fix generalizes across inputs? Yes. The catch (...) is exception-type-agnostic (memory limit, query cancellation, IO error all set eof). Verified correct results across INNER/LEFT/RIGHT/FULL/LIMIT grace_hash joins with spilling.
h Backward compatible? Yes. No setting/format/protocol change. Pure internal error-path robustness; behavior changes only on the failure path (graceful exception instead of abort), the query still fails with the original exception.
i Invariants and contracts preserved? Yes. eof is still only written under the held mutex (same as the normal empty-block path); success-path semantics of eof/finished unchanged; no new lock, no lock-order change.

Session id: cron:clickhouse-author-slot-3:20260720-094200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @nickitat @vdimir — could you review this? It fixes the chronic ReadBuffer is canceled stress abort in GraceHashJoin: when a spilled-block read fails mid-read (canceling the buffer), the shared AccumulatedBlockReader was left non-eof, so a sibling worker re-read the canceled buffer and hit chassert(!isCanceled()). The fix marks the reader finished on any read failure.

Comment thread src/Interpreters/GraceHashJoin.cpp Resolved
@vdimir vdimir self-assigned this Jul 20, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 20, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [170ad21]

Summary: ✅


AI Review

Summary

The PR fixes the shared AccumulatedBlockReader error path in GraceHashJoin so a failed spilled-block read becomes terminal instead of letting a sibling worker re-enter a canceled ReadBuffer. The current diff and discussion are consistent with that contract, and I did not find a remaining correctness, concurrency, or test-coverage issue that warrants a new inline review comment.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.80% 86.80% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 79.20% 79.20% +0.00%

Changed lines: Changed C/C++ lines covered: 34/34 (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 Jul 20, 2026
count() lets the analyzer prune the wide l.s column (confirmed via EXPLAIN
under enable_analyzer=0), so the spilled left payload need not be materialized
and the shared delayed-reader path this PR fixes could go uncovered. Selecting
l.s post-join makes it a required output column under both analyzers, so the
mid-read failure on the shared AccumulatedBlockReader is exercised.

Addresses the automated-review finding on the regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 79a46c7

Every failure below has an owner (a fixing PR). Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_msan, 7/8) / test_replicated_database::test_replicated_table_structure_alter flaky, unrelated to this GraceHashJoin change (105 master failures in 30d across 91 commits and 20+ unrelated PRs) #111029 (external, open)

Notes: Bugfix validation (functional tests, amd64/aarch64) rolled up SUCCESS; the 04545_grace_hash_join_read_after_cancel row failing on the master binary is the expected must-fail-on-master baseline. Finish Workflow / Mergeable Check / PR are aggregators reflecting the single integration red above.

Session id: cron:our-pr-ci-monitor:20260720-210000

groeneai and others added 2 commits July 29, 2026 13:33
… reader

The existing stateless regression 04545_grace_hash_join_read_after_cancel is
probabilistic: it relies on a tight max_memory_usage failing a spilled read at the
right moment. Measured on a debug build with the branch instrumented, that query
never reaches AccumulatedBlockReader::read at all - the memory limit fires earlier,
in MergeTreeSelect while reading the source table (10/10 runs: zero entries into the
reader, zero DelayedBlocks constructions). So the branch this PR adds was not covered.

Add failpoint grace_hash_join_fail_in_delayed_block_read, armed only for the left
(delayed) reader, which cancels the underlying buffer and then throws - the same post
state ReadBuffer::next leaves on a real mid-read failure. DelayedJoinedBlocksTransform
hands the same delayed stream to every worker port before any worker runs, so the
reader is already shared when the failure is injected.

With the fix the new test passes (50/50 under randomization); with the eof assignment
removed it aborts 5/5 with "ReadBuffer is canceled. Can't read from it.", which is the
signature this PR exists to prevent.

Co-Authored-By: Claude Fable 5 <[email protected]>
The memory-limit variant added earlier in this PR passes with the fix reverted, so it
proves nothing: measured on a debug build, the injected memory limit fires in
MergeTreeSelect while reading the source table and the query never enters
AccumulatedBlockReader::read at all. Keeping both would leave a test that cannot fail
for the reason it names.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b52c6f4

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 (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit trunk regression, not caused by this diff: Code: 202 Too many simultaneous queries, and this change touches only the GraceHashJoin spilled-block reader (312 hits over 256 unrelated pull requests and 33 master runs in 30 days) #112385 (mine, merged 2026-07-29 15:37Z); this build predates it, so a rerun after the next master merge picks it up

174 check-runs on this head, all completed: 155 success, 18 skipped, 1 failure, the row above. This is the first ledger for this head; the previous one covered 79a46c7ffb33, and the four commits since are the reply to the 2026-07-29 review comment.

Session id: cron:our-pr-ci-monitor:20260729-193000

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 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: 34/34 (100.00%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2f98365

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
Stress test (amd_asan_ubsan) / Query context must be created after authentication (STID 3197-391f) trunk bug: pre-auth query context on the PostgreSQL wire port, not reachable from this diff a fix task is moved to pending (investigating at full effort, fixing-PR link to follow here)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) / test_replicated_table_attach.py::test_startup_with_small_bg_pool_partitioned flaky replica re-activation wait; 5 unrelated PRs over 7 weeks, 0 master, and it passes on every other build flavour of this same commit a fix task is created (investigating at full effort, fixing-PR link to follow here)

Session id: cron:our-pr-ci-monitor:20260801-230000

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the pre-auth Query context must be created after authentication abort in the Stress test (*) failures ledgered above: #112940.

That PR reapplies #110760 (reverted in #112935) together with the fix: PostgreSQLHandler::cancelRequest no longer builds a query context from the unauthenticated session, cancelling through the new ProcessList::sendCancelToQueryOfAnyUser instead. Verified at its head bfc13929ce68df79, where the signature no longer appears in CIDB while the same Stress flavours ran.

@groeneai

groeneai commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

Following up on the ledger above: the fixing PR for the
test_replicated_table_attach.py::test_startup_with_small_bg_pool_partitioned line is
#113733.

It is not a flaky-wait fix. The root cause is an engine bug, so no timeout would have helped: a
ReplicatedMergeTree replica whose startup goes through ReplicatedMergeTreeAttachThread can be
left with its restarting task activated but enqueued nowhere, after which nothing retries the
activation and nothing arms the periodic ZooKeeper session check. In the failing job here that
table's restarting task logged nothing for the remaining 417 seconds of the run, while the sibling
table's task logged its 60 second periodic line seven times.

@alexey-milovidov alexey-milovidov self-assigned this Aug 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 170ad21af with master c28352e98 (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
Binary Master PR Δ
programs/clickhouse-stripped 701.49 MiB 698.47 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c9b890a49e3b7c1f6cd15b0f4a5ed4d4bdb0f4ab

CI is fully finished on this head: 177 check runs, 160 success, 17 skipped, 0 failures.
Both the test-level (test_status IN ('FAIL','ERROR')) and check-level
(check_status IN ('failure','error')) CIDB enumerations for this commit return zero rows,
so there is nothing to attribute and no owner column to complete.

Check / test Reason Owner / fixing PR
(none) no failed check on this head n/a

The 17 skipped jobs are the standard non-applicable set for this PR (Performance Comparison
master_head, Bugfix validation integration tests, Docs check, Dockers/Toolchain builds).

Session id: cron:our-pr-ci-monitor:20260816-113000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - fe86a2d

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
Build (arm_tidy) / Build ClickHouse inherited master build break - gtest_merge_join_starved_totals.cpp.o, allocator_traits.h:302:5 error: no matching function for call to '__construct_at' #115087 (ours, open)
Finish Workflow / new_tests_check.py consequence of the above: all four Bugfix validation jobs are DROPPED because the build produced no binary, so the hook correctly reports that no per-arch job validated the bug #115087 (ours, open)

Not this PR's diff: the failing target is src/Processors/tests/gtest_merge_join_starved_totals.cpp,
which this PR does not touch. Master's TableJoin constructor gained a JoinAnalyzeMode parameter in
position 2 while that unit test still calls the 3-argument form, so every build of unit_tests_dbms
on a master base fails identically. #115087 supplies the missing argument. The new_tests_check.py
red has no independent cause - its inputs were all dropped by that build.

The Stress test (arm_tsan) "Not-ready Set is passed as the second argument" row visible in CIDB for
this PR is on the superseded head eeb31d668ab8, not this one, and is not part of this ledger.

Session id: cron:our-pr-ci-monitor:20260817-090000

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 18, 2026
Merged via the queue into ClickHouse:master with commit dbdd94c Aug 18, 2026
181 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 18, 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 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