Skip to content

Fix DeltaLake read hanging forever when the scan thread reports an error - #119345

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-deltalake-iterator-lost-wakeup
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-deltalake-iterator-lost-wakeup

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117434
Related: #110975 (comment)

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 DeltaLake / deltaLakeLocal read that could hang forever instead of reporting an error when the delta-kernel scan thread fails, for example on a table whose _delta_log points a data file outside the table directory. The read waited with no timeout and no cancellation point, so it could only be ended by killing the process.

Description

In TableSnapshot::Iterator, the reading pipeline waits in next() on an untimed data_files_cv.wait(lock, pred) whose predicate reads data_files, iterator_finished and shutdown, holding next_mutex. Normal completion sets iterator_finished under that mutex, which is correct. setScanException() and ~Iterator() set shutdown (and scan_exception) without it.

That is a lost wakeup, and wait(lock, pred)'s re-check does not close it: the unprotected window is inside wait, between its last pred() call and the atomic register-and-unlock. If the scan thread throws there, notify_all finds no registered waiter and the notification is dropped. The scan thread then leaves its while (!shutdown.load()) loop without setting iterator_finished and without a second notify, so nothing can satisfy the predicate again: next() sleeps forever and the stored exception is never rethrown, so the error never reaches the client.

The fix publishes both fields under next_mutex and notifies after releasing it, matching the normal-completion path above. allow_delta_kernel_rs is on by default, so this is the default read path.

Validated with a REGULAR failpoint that widens the window, on two binaries differing by exactly this change:

Arm matrix, 8 runs each
arm build failpoint result
A base ON hangs 8/8, killed at 30 s, no error on stderr
B base OFF passes 8/8, 0.42-0.79 s
C fixed ON passes 8/8, 6.41-8.72 s, error reported
D fixed OFF passes 8/8, 0.41-0.50 s

The new 04299_deltalake_local_iterator_lost_wakeup fails on unfixed code in 61.63 s and passes in 7.55 s with the fix. 50/50 randomized runs of it and of 04299_deltalake_local_path_traversal: 100 OK, 0 failures, no hung queries.

04299_deltalake_local_path_traversal hit the 600 s harness timeout three times in five weeks, most recently on 2026-09-10, always on the kernel-rs arm. I fix a proven lost wakeup on the path those runs took; I could not reproduce that occurrence itself (its only surviving stack is truncated), so I do not claim it is proven to be this.

Separate defect from #117434 (kernel FFI waits lacking a cancellation point), which I do not address; this wait stays untimed. #117434 says shutdown is only ever set by ~Iterator, but setScanException sets it too, and that is the losing path. ~Iterator carries the same defect on schedule_next_batch_cv; the same mutex fixes it, without a separate reproducer. This diff and #117431 do not overlap.


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

TableSnapshot::Iterator is a producer/consumer pair: a scan thread pushes data
files into `data_files`, and the reading pipeline pulls them in `next()` by
waiting on an untimed `data_files_cv.wait(lock, pred)` while holding
`next_mutex`. The predicate reads `data_files`, `iterator_finished` and
`shutdown`.

The scan thread published its terminal state on two different disciplines.
Normal completion set `iterator_finished` under `next_mutex`, which is correct.
`setScanException()` set `scan_exception` and `shutdown`, and `~Iterator()` set
`shutdown`, without holding it.

Mutating a predicate input without owning the mutex is a lost wakeup, and
`wait(lock, pred)`'s re-check does not close it: the unprotected window is
inside `wait`, between its last `pred()` call and the atomic
register-and-unlock. If the scan thread threw in that window, its `notify_all`
found no registered waiter and the notification was dropped. The scan thread
then left `while (!shutdown.load())` without setting `iterator_finished` and
without a second notify, so nothing could satisfy the predicate again: `next()`
waited forever, the pipeline never finished, and the stored exception was never
rethrown, so the error never reached the client. Since the wait has no timeout
and no cancellation point, neither `KILL QUERY` nor `max_execution_time` ended
it. `scan_exception` is also read under the lock, so the unlocked write was a
data race in its own right.

`~Iterator()` carried the same defect on the other condition variable: the scan
thread waits on `schedule_next_batch_cv` while holding `next_mutex` whenever the
batch queue is full, so an early-terminating read could lose the destructor's
wakeup and hang in `thread.join()`.

Publish both fields under `next_mutex` and notify after releasing it. There is
no self-deadlock risk: none of the three `setScanException` call sites holds
`next_mutex` when it runs, and the scan thread only ever holds it briefly or
inside a `wait` that releases it.

`grep -rn condition_variable src/Storages/ObjectStorage/DataLakes/` returns
exactly two condition variables, both in this file, so the affected set is
closed. `allow_delta_kernel_rs` is enabled by default, so the affected path is
the default one for every DeltaLake and deltaLakeLocal read.

Add a REGULAR failpoint with two sites that together order the scan thread
against the pipeline, plus a stateless regression test built on it. A single
site is not enough: `scanCallbackImpl` acquires `next_mutex` before the throw
and releases it after, so a delay inside the predicate (which holds the mutex)
either blocks the scan thread or arrives too late, and the ordering has to be
forced from both sides.

Related: ClickHouse#117434
Related: ClickHouse#110975 (comment)

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 10, 2026
@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; 2 findings, plus 1 from my own
cold review; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The regression test can pass with the locking fix reverted, because the failpoint neither forces nor verifies the target interleaving, and it cannot cover the ~Iterator half (04299_deltalake_local_iterator_lost_wakeup.sh) DISAGREE, in part An inactive failpoint cannot yield a silent pass: a build without libfiu throws SUPPORT_IS_DISABLED (InterpreterSystemQuery.cpp:1220) and an unknown name throws Code: 36 BAD_ARGUMENTS Cannot find fail point, either of which aborts the -q batch before the SELECT, so the test fails. The suggested explicit synchronization is not available: the failpoint is process-global, so this has to be a single-process, single-query clickhouse-local test, and a pauseable handshake needs a second channel to release it. Ordering margin is a forced 1000 ms producer sleep against a millisecond-scale pipeline build; base-side redness was observed 9/9. The ~Iterator half is genuinely uncovered, and structurally so: Local/Configuration.cpp:111 sets list_object_keys_size = 0 and both schedule_next_batch_cv waits are gated on list_batch_size > 0, so that condition variable is unreachable from deltaLakeLocal. Stated as a limitation in the description rather than papered over.
2 💡 The new concurrency comment calls scan_exception an input of the data_files_cv predicate (TableSnapshot.cpp:180-182) AGREE, fixed before publication Correct: the predicate reads only data_files, iterator_finished and shutdown; scan_exception is read after the wait, under the same lock. Both fields need next_mutex, for two different reasons. Comment reworded to say that.
3 ⚠️ The issue link and the originating comment link sat inside the template's HTML comment block, so the provenance would not have rendered AGREE, fixed before publication Found in my own cold review of the draft description. Both links moved above the changelog category, where the project's own tooling puts them (ci/jobs/revert_ci_regressions.py:1774-1778).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260910-195700

@clickhouse-gh clickhouse-gh Bot closed this Sep 10, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. A REGULAR failpoint holds the delta-kernel scan thread until the reading pipeline is inside its data_files_cv wait, then holds the pipeline while the scan thread publishes its error. On unfixed code the read hangs 8/8 (killed at 30 s, no error on stderr); the shipped test fails in 61.63 s.
b Root cause explained? Yes. next() waits on an untimed data_files_cv.wait(lock, pred) holding next_mutex. setScanException() and ~Iterator() publish shutdown / scan_exception without that mutex, so if the scan thread throws inside the window between the predicate's last evaluation and the atomic register-and-unlock, notify_all finds no waiter and is dropped. The scan thread then exits its while (!shutdown.load()) loop without setting iterator_finished and without a second notify, so the predicate can never be satisfied: the read waits forever and the stored exception is never rethrown.
c Fix matches root cause? Yes. Both fields are published under next_mutex, with the notify after release, which is the discipline the normal-completion path already uses three lines above (iterator_finished under lock_guard). No bound widened, no no-random-* tag, no data reduction, no guard at the waiting site; the wait is left untimed and un-cancellable exactly as before.
d Test intent preserved / new tests added? Yes. No existing test changed. Added 04299_deltalake_local_iterator_lost_wakeup, which fails on unfixed code within its timeout and passes with the fix. It asserts the containment message, not just PATH_ACCESS_DENIED, because the table function's outer user_files_path guard raises the same error code without reaching the delta reader (measured).
e Both directions demonstrated? Yes, on two binaries differing by exactly this change (saved the fixed file, reverted only the two hunks, rebuilt, restored, rebuilt). Base + failpoint: hangs 8/8. Base, failpoint off: passes 8/8 in 0.42-0.79 s. Fixed + failpoint: passes 8/8 in 6.41-8.72 s with the error reported. Fixed, failpoint off: passes 8/8 in 0.41-0.50 s. Plus 50/50 randomized runs of the new and the existing 04299 test: 100 OK, 0 failures, no hung queries.
f Fix is general across code paths? Yes. grep -rn condition_variable src/Storages/ObjectStorage/DataLakes/ returns exactly two condition variables, both in this file, so the affected set is closed. Both unlocked publication sites are fixed (setScanException, ~Iterator); the correct site and the atomic reads are left alone. TableChanges.cpp, DeltaLakeMetadata.cpp and WriteTransaction.cpp have no condition variable and no worker thread. Fixed at the publisher, not guarded at the waiter.
g Fix generalizes across inputs (params/datatypes/wrappers)? Type wrappers do not apply: this is a thread-handoff path with no column types and no format or engine matrix. The axis that matters is which producer exit runs, enumerated in (f): normal end, exception end, destruction. The ~Iterator path is fixed by the same mutex but is not separately reproduced (that would need a third hook inside schedule_next_batch_cv's wait), and the PR body says so rather than claiming it as measured.
h Backward compatible? (maintainer-approved exception only) Yes, vacuously. No setting, no format, no protocol and no persisted state, so no SettingsChangesHistory.cpp entry is required. The diff is FailPoint.cpp +1 and TableSnapshot.cpp +26/-3, touching no setting.
i Invariants and contracts preserved? Yes. The invariant is now explicit: every mutation of a data_files_cv or schedule_next_batch_cv predicate input happens while holding next_mutex, and the notify stays outside the lock. No self-deadlock: none of the three setScanException call sites holds next_mutex when it runs, since scanCallbackImpl's unique_lock scope closes before resolvePathInsideTable, tryRefreshAndRetryScanState closes its own lock scope before anything that can throw, and unwinding releases either lock in any case. The destructor's new lock_guard cannot deadlock against the scan thread, which only holds next_mutex briefly or inside schedule_next_batch_cv.wait, which releases it. Nothing is persisted, so there is no restart re-entry path.

Session id: cron:clickhouse-impl-slot-41:20260910-180900

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7ce9594]

Summary: ❌

job_name test_name status info comment
Upgrade check (amd_release) FAIL
Logical error: Virtual row has different type for A. Expected B, got C (STID: 1637-309b) FAIL cidb

AI Review

Summary

This PR fixes a real lost-wakeup in TableSnapshot::Iterator: shutdown and scan_exception now follow the same next_mutex discipline as the data_files_cv predicate they unblock, and the new stateless regression test exercises that error-reporting path through the shared Delta kernel iterator. I did not find a remaining correctness, concurrency, or PR-metadata issue in the current diff, so there was nothing new to post inline.

Final Verdict

Status: ✅ Approve

LLVM Coverage Report

Measured on commit 7ce9594.

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: 29/29 (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 Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @SmitaRKulkarni @arsenmuk, could you review this? TableSnapshot::Iterator publishes shutdown and scan_exception without holding next_mutex, even though shutdown is an input of the untimed data_files_cv predicate that next() waits on, so an error raised by the delta-kernel scan thread inside the window between the predicate evaluation and the cv registration drops the notification and the read waits forever instead of reporting the error. The fix publishes both under that mutex, matching what the normal-completion path already does.

@clickhouse-gh clickhouse-gh Bot added the comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7ce959496 with master cebe81e85 (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

8 translation units recompiled, 14 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 - 7ce9594

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
Upgrade check (amd_release) / Logical error: Virtual row has different type for A. Expected B, got C (STID 1637-309b) server abort, not PR-caused #119385 (mine, open)
Mergeable Check aggregator over the row above #119385 (mine, open)
PR aggregator over the row above #119385 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

The abort is a type divergence in the read-in-order virtual row: the merging transform is planned with
CAST(json.b, 'String') as Nullable(String) while the chunk delivers a bare String, and
setVirtualRow asserts the two agree. This branch is a DeltaLake read-cancellation fix and touches
nothing on that path; the same signature first appeared on true master at ad8622edd0fb
(Stress test (amd_tsan), 2026-09-10 16:22Z) and has since fired on two other carriers. #119385
requires the mapped pair's result types to agree in matchTrees, which is the producing site.

Finish Workflow reported a red post-hook at 2026-09-10 20:18Z on this same commit while
Bugfix validation was still pending; it re-ran at 02:42:51Z and reported OK, so it is not a
failure on this head.

Session id: cron:our-pr-ci-monitor:20260911-030120

@zlareb1

zlareb1 commented Sep 17, 2026

Copy link
Copy Markdown
Member

@groeneai will this fix #117434?

@groeneai

Copy link
Copy Markdown
Collaborator Author

No, not as asked. #119345 fixes a lost wakeup on the ClickHouse side; #117434 asks for a cancellation point and an overall timeout on the kernel FFI waits, and this PR adds neither.

What it fixes is a dropped notification, not a kernel-side block: terminal state (scan_exception, shutdown) was published without holding next_mutex, so a notify landing while the consumer sat inside data_files_cv.wait(lock, pred), between the last predicate evaluation and registering on the cv, was lost, and next() then waited forever with the scan thread already gone. ~Iterator carried the same defect on schedule_next_batch_cv, so an early-terminating read could hang in thread.join() when the batch queue was full. Both hangs occur while the kernel is behaving normally, which is the opposite of #117434's premise.

What stays broken on master after it: the wait at TableSnapshot.cpp:380 is still untimed with no checkTimeLimit, and TableChanges.cpp and WriteTransaction.cpp contain no cancellation or timeout check at all. If scan_metadata_next, table_changes_* or commit blocks inside the kernel, next() still has nothing to interrupt and the destructor still joins a stuck thread. #117431 covers the snapshot load only, and is still open.

One correction for whoever scopes #117434: it states that shutdown is only ever set by ~Iterator. setScanException sets it too (TableSnapshot.cpp:176), and that unlocked write is the path that was losing the notification.

If you want item 1 of that issue handled here, the query-side half is cheap: poll data_files_cv.wait_for() and call process_list_element->checkTimeLimit() on each tick, which is what #117431 does for the snapshot load in this same file (waitForSnapshotLoad). The destructor half is not cheap: not joining a scan thread that is stuck in the kernel needs that PR's markAbandoned treatment, so doing it before #117431 lands would duplicate its mechanism. I can add the query-side half here, or send it separately once #117431 is in, whichever you prefer.

@clickhouse-gh clickhouse-gh Bot added comp-delta-lake Delta Lake tables: reading Delta metadata through delta-kernel-rs (table snapshots, schema and ty... and removed comp-datalake Data lake table formats (Iceberg/Delta/Hudi) integration. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-delta-lake Delta Lake tables: reading Delta metadata through delta-kernel-rs (table snapshots, schema and ty... groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants