Repository navigation
Fix a hang in the parallel Parquet encoder when it cannot start an extra thread - #112959
PedroTadim merged 5 commits into
Conversation
ParquetBlockOutputFormat::startMoreThreadsIfNeeded keeps threads_running as a census of encoder threads that have started and not yet exited. It incremented the counter in the scheduleOrThrowOnError branch, but the trySchedule branch scheduled a job without counting it, while every job decrements on exit. The counter is a size_t, so each such job underflowed it. Once underflowed, threads_running == 0 is never true again, so scheduleOrThrowOnError becomes unreachable. That call exists to guarantee a first thread. Every later attempt goes through trySchedule, which is allowed to fail, and when it does the encoder is left with a non-empty task queue and no thread to drain it: tasks_in_flight never reaches zero, finalizeImpl never sees row_groups empty, and it waits on its condition variable indefinitely. That is the "stuck with tasks but no threads" state the comment in threadFunction exists to prevent. No cancellation is involved; the surfaced artifact showed about 30 ms of CPU across 954 s inside pthread_cond_wait. This is not limited to fault injection. The encoder pool is constructed with queue_size == max_threads, so a zero-wait trySchedule legitimately fails on queue saturation. With fault injection disabled entirely, a small-row-group write produced 9981 failed trySchedule calls and 3206 underflow events across 10 runs, and 6 failures on default row group settings. Fault injection only raises the rate at which the resulting hang is observable. Correcting the count also removes work: an underflowed counter stopped to_add from clamping to max_threads and produced spurious scheduling attempts. Introduced by 8184a28. The new test drives the encoder in clickhouse local, where the process-global thread allocation fault injector cannot disturb the server or a concurrent copy of the test, and uses timeout as the oracle: completion is asserted, the hang is never asserted. It hangs on unpatched master in 5 of 5 attempts and passes with this change; reverting the added line makes it fail again. Co-Authored-By: Claude Fable 5 <[email protected]>
The test asserted only that the write did not hang. A run that never reached the parallel encoder was therefore indistinguishable from a successful one: a renamed setting, a bad option, or a future default flip that leaves the encoder pool null would make finalizeImpl skip the waiting loop entirely and the test would pass while testing nothing. It also sent stderr to /dev/null and rejected only timeout's own status, so any unexpected failure counted as a pass. Add a positive control iteration that runs with nothing injected: it asserts the parallel encoding setting and max_threads are in effect, requires the write to succeed, reads the file back, and checks the data spans more than one row group. That establishes a real, completed, parallel Parquet write on this binary and configuration before the injected loop draws any conclusion. In the loop, keep accepting CANNOT_SCHEDULE_TASK, which is the correct outcome of an allocation that genuinely failed, but fail on anything else and print the captured stderr. The status is matched through the message because the shell truncates 439 to 183. Raise the per-iteration timeout from 6s to 120s. The budget is only ever spent on a real hang, so a generous cap costs nothing when the fix is present, while 6s was close enough to the loaded per-iteration time that contention alone could be misread as the unbounded wait: 50 repeats of the previous version reported seven false hangs on a fixed binary. With the larger cap 50 repeats pass and the slowest takes 23s. Tag the test long. It performs thirty serial writes, and the flaky check runs many copies of a test at once. Co-Authored-By: Claude Fable 5 <[email protected]>
…oder Two ways the test could print OK while testing nothing. A high injection probability fails the write's first schedule attempt, so it short circuits before the thread counter can underflow. The loop accepted every such iteration and counted nothing, so a run where all 30 failed early still passed. It now requires at least one iteration to complete, which is the state the defect corrupts. Anyone raising the probability, or changing the injector so first attempts fail more often, gets a failure instead of a silent no-op. The injector is armed by an option after an empty `--`. Those tokens skip the unrecognized-option check and an unknown key is dropped without a diagnostic, so a typo or a rename of the server setting would leave the injector off with exit status 0. The test now asserts through `system.server_settings` that the exact spelling the loop passes is set and non-zero. Correcting the previous commit message: it said the per-iteration timeout went from 6s to 120s. The committed value was 30s, so the change is 30 -> 120. The argument is unchanged, since 30s was only about 1.3x the loaded per-iteration wall time and produced 7 measured false positives on a correct binary.
The starvation test could pass without ever exercising the defect. It needs a trySchedule that actually failed, and none of its guards observed one: the positive control runs with nothing injected by design, the completed-iteration floor is satisfied by clean writes, and the arming assertion only shows that the config layer accepted the option spelling. That assertion runs in a separate clickhouse local process and reads system.server_settings, so it says nothing about the processes that perform the writes. It also cannot notice a future change in how the probability is scaled, since the setting stays both enabled and changed while the draw stops producing failures. The loop now counts iterations whose stderr carries the injector's own reason and fails when none did. That string is unique to the injector, unlike CANNOT_SCHEDULE_TASK, which five other reasons raise and which the loop already tolerates. Co-Authored-By: Claude Opus <[email protected]>
Internal second-model review (4 rounds, all findings resolved)An independent model reviewed this change cold in four rounds before it was opened, plus my own Resolved in the branch
Raised and not accepted❌ "The fired-injector counter does not prove Parquet's extra-thread
Detection power is measured rather than argued: unpatched, the test hangs on 3 of 3 and 5 of 5 💡 No memory cap on the test's Session id: cron:clickhouse-review-slot-49:20260801-222700 |
Pre-PR validation gate (click to expand)Repro and root cause. Both directions. Unpatched master hangs 3 of 3 on the final file; with the fix it passes 3 of 3 and once more through the real runner at 21.8 s. Reverting only the added line and rebuilding to a distinct Build ID makes it hang again, and restoring the line rebuilds bit-identically to the fixed binary, so that line is the only variable. Every arm's served build id was asserted equal to its own Test oracle. No existing test is modified. The oracle is Generality and compatibility. One note on scope, since the reported artifact came from a stress run: this is not specific to fault injection. The encoder's pool is constructed with Also worth recording: 50 randomized runs of the new test pass, slowest 23.0 s, and a 29-test Parquet-output sweep shows no regressions, with the new test failing only on the unpatched arm. Session id: cron:clickhouse-impl-slot-41:20260801-214600 |
|
cc @al13n321 @vitlibar, could you review this? The parallel Parquet encoder counted a thread started through scheduleOrThrowOnError but not one started through trySchedule, while every encoder thread decrements the count on exit, so the size_t census underflowed and the guaranteed-first-thread branch became unreachable; a later trySchedule failure then left a non-empty task queue with no thread to drain it and finalizeImpl waited on its condition variable forever. |
|
Workflow [PR], commit [c575401] Summary: ❌
AI ReviewSummaryThis PR fixes the Final VerdictStatus: ✅ Approve |
The test pinned one thread allocation fault probability, and on arm_asan_ubsan every iteration was refused its very first encoder thread, so no iteration ever completed and the anti-vacuity floor reddened. All amd arms stayed green, including four flaky-check 50x arms. The hit rate is not monotonic in that probability. A hang needs a refused thread to land after the live-thread count has already underflowed, while raising the probability also raises the chance of refusing the first thread and ending the write early. The peak therefore sits at a different probability on each platform: measured on amd, 20 iterations of the pristine binary hung 1/20 at p=0.10, 1/20 at p=0.05, 7/20 at p=0.03 and 0/20 at or below p=0.02, with the earlier 28% figure at p=0.05 not reproducing under different machine load. So sweep a ladder instead of pinning a value, and prove the injector is armed in a separate deterministic step at probability 1, where the first schedule attempt is certain to be refused. That check is stronger than the previous loop-level counter, which could only ever observe refusals of the first thread and so was in direct tension with the completion floor it sat next to. Both floors remain non-vacuous: mistyping the probability as a percentage leaves the injector disabled and the arming step fails, and a ladder made entirely of high rungs completes nothing and the completion floor fails. Verified on the final file with the real runner: the pristine binary hangs 4/4, the fixed binary passes 4/4, and 50 randomized runs pass with a 44.76s maximum against the 180s limit.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 3/3 (100.00%) · Uncovered code |
CI finish ledger — c575401Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not attributable to this change: The shape is a shared-budget capacity issue, not a crash and not a hang: 0 The Session id: cron:our-pr-ci-monitor:20260802-103000 |
bf681dd
|
Fixing PR for the |
|
The one line fixed here is absent from three active release branches. Measured two independent ways: the
On 26.3, 26.6 and 26.7 the @alexey-milovidov, could you apply
I found no public CI failure on those branches in 90 days whose context names the encoder, and a hang would not necessarily name it, so the case rests on the missing fix rather than on an observed failure there. |
…lled in teardown `Stateless tests (amd_msan, WasmEdge, parallel, 2/2)` on PR ClickHouse#112959 reported `error` with zero test failures: all 6174 tests passed and `All tests have finished` printed at t=8893s, then the job was killed at the 9000s budget, 122s into teardown. `main` holds the complete per-test result in memory from the moment the suite finishes until `Result.complete_job` at the very end, and everything in between is teardown: `SYSTEM FLUSH LOGS`, log-export shutdown against a remote staging cluster, coverage export, log collection. The single job timeout covers setup, suite and teardown together, and praktika's watchdog SIGKILLs the process group with no knowledge of which phase is running, so a total overrun discards results that were already finished. Measured against the sibling shard that passed at the same sha: the killed shard inserted 1 CIDB row and uploaded 1 artifact, the passing one 6178 and 5. The run becomes invisible to every flaky-detection query, and an unrelated PR gets a red check with nothing to inspect. Write the collected results into the job's existing result file as soon as they exist, before any teardown, and leave the status non-terminal. `Runner._get_result_object` then patches a killed job with `add_error` + `set_status(ERROR)`, neither of which touches `result.results`, so the job still reports `ERROR` (it was killed) but carries all 6174 rows. Keeping the status non-terminal is what makes this safe by construction rather than by careful placement: a terminal status here could publish green over a fatal that teardown had not yet discovered, and would publish the bugfix-validation verdict before `invert_bugfix_validation_status` runs. Published by rename rather than `Result.dump`, which is `open(..., "w")` + `json.dump` and so truncates before serializing: a kill mid-write would leave JSON `Result.from_fs` refuses to parse, turning a lost result into a harder failure. The bugfix-validation loop gets its own call site because it replaces `test_result.results` per build type and then stops the server and re-prepares the environment, so a single post-loop call loses the rows of every build type but the last. This does not fix the overrun itself, and does not make teardown reliable: logs gathered later can still be lost. It makes the run attributable. Nothing under `ci/praktika/` is touched. All eight `common_ft_job_config` derivations and `bugfix_validation_ft_pr_jobs` run this same `main` and inherit the checkpoint.
Port the shared Parquet encoder pool to 26.3: - 26.3 declares the static thread pools one by one, without APPLY_FOR_STATIC_THREAD_POOLS, so getParquetEncoderThreadPool() and its metrics are added by hand to SharedThreadPools.h/.cpp. - 26.3 still has the Arrow writer, and the encoder pool is created only for the custom encoder: switch that creation to the shared pool. - Also take the one-line fix of #112959, which is not on 26.3: count the job started via trySchedule(). stopThreads() waits for threads_running to reach 0, so without it the counter underflows and the writer never finishes (the test hangs). The test keeps only its file() part on 26.3. A partitioned Iceberg INSERT with max_insert_threads = 8 loses rows or a metadata file in most runs on 26.3 even without this change and with a large thread pool, so the Iceberg part cannot pass there. 26.3 also has no max_threads_min_free_memory_per_thread and max_insert_threads_min_free_memory_per_thread, and its background schedule pool starts all 512 threads when clickhouse-local starts, more than the test's 500-thread global pool: drop the two settings and set background_schedule_pool_size = 16. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #110084
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixes a hang when writing Parquet with
output_format_parquet_parallel_encodingenabled (the default) andmax_threadsgreater than 1. If the encoder failed to schedule an additional thread, its live thread counter underflowed and the write could stop making progress permanently instead of finishing or reporting an error.Description
ParquetBlockOutputFormat::startMoreThreadsIfNeededkeepsthreads_runningas a census of encoder threads that have started and not yet exited. It incremented the counter in thescheduleOrThrowOnErrorbranch, but thetrySchedulebranch scheduled a job without counting it, while every job decrements on exit. The counter is asize_t, so each such job underflowed it.Once underflowed,
threads_running == 0is never true again, soscheduleOrThrowOnErrorbecomes unreachable. That is the one branch with a guarantee ("we need it to succeed; otherwise we may get stuck"). Every later attempt goes throughtrySchedule, which is allowed to fail, and when it does the encoder is left with a non-empty task queue and no thread to drain it:tasks_in_flightnever reaches zero,finalizeImplnever seesrow_groupsempty, and it waits on its condition variable indefinitely. This is the "stuck with tasks but no threads" state the comment inthreadFunctionexists to prevent. No cancellation is involved.The fix counts the thread started through
trySchedule. Both mutation sites already run under the format's mutex, so no locking changes.This is not limited to fault injection. The encoder's pool is constructed with
queue_size == max_threads, so a zero-waittrySchedulelegitimately fails on queue saturation. With fault injection disabled I measured 9981 failedtrySchedulecalls and 3206 underflow events across 10 runs of a small-row-group write. Fault injection only makes the resulting hang frequent enough to test.The bug dates back to
8184a289e5441208110bcd2f8f63b57e31ccde33(2023, parallel encoder reimplementation).Performance: one increment under an already-held lock. It also removes work, since an underflowed counter stopped
to_addfrom clamping and produced spurious scheduling attempts.Validation: the new test
04690_parquet_parallel_encoder_thread_starvationhangs on unpatched master and passes with the fix; reverting only the added line makes it fail again. 50 randomized runs pass, and a 29-test Parquet-output sweep shows no regressions.Version info
26.8.1.634(included in26.8and later)