Skip to content

Fix rusage race in executable UDF metering with check_exit_code=false - #109667

Merged
alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-udf-nonzero-exit-rusage-race
Jul 11, 2026
Merged

alexey-milovidov merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-udf-nonzero-exit-rusage-race

Conversation

@groeneai

@groeneai groeneai commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Description

Fixes a race that made test_executable_udf_profile_events::test_check_exit_code_false_succeeds_and_meters flaky (assert cpu > 0).

Failing check: Integration tests (arm_binary, distributed plan, 3/4).
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=9d5fd8abfb763217edb76704dba9fb9453a6992d&name_0=MasterCI&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%203%2F4%29

Root cause. With check_exit_code=false, ShellCommandSource::cleanup waits the child via ShellCommand::tryWaitWithoutStatusCheck, which did a single wait4(WNOHANG). A child that has closed stdout but only just reached _exit is not yet a zombie, so WNOHANG returns 0, no rusage is collected, and ExecutableUserDefinedFunctionUserTimeMicroseconds reads 0.

Fix. tryWaitWithoutStatusCheck polls wait4(WNOHANG) within the configured command_termination_timeout window (wait_for_normal_exit_before_termination_seconds), so a child exiting in that window has its usage collected here instead of by the destructor's waitForPid, which collects none. Timeout 0 means a single non-blocking attempt, so a query is never stalled beyond the configuration. A child lingering past the budget still falls through to the bounded command_termination_timeout + SIGTERM teardown (the ..._lingering_child_is_bounded_and_flushes_bytes invariant is preserved).

Reproducing test. udf_nonzero_exit.py closes stdout then sleeps 2s (inside the 5s command_termination_timeout, above a 1s window) before exiting non-zero, making the lost-usage window deterministic. Verified on a local debug build: without the fix test_check_exit_code_false_succeeds_and_meters fails (UserTime == 0); with the fix it and the lingering-child test pass, and CHILD_WAS_NOT_EXITED_NORMALLY is never logged.

Version info

  • Merged into: 26.7.1.800 (included in 26.7 and later)

With check_exit_code=false the ShellCommandSource cleanup reaped the child
with a single non-blocking wait4(WNOHANG) via tryReapWithoutStatusCheck. A
child that has closed stdout (pipeline complete) but has only just reached
_exit is not yet a reapable zombie, so the single WNOHANG returns 0, the
child's rusage is lost, and ExecutableUserDefinedFunctionUserTimeMicroseconds
reads zero. On loaded arm CI this intermittently failed
test_executable_udf_profile_events::test_check_exit_code_false_succeeds_and_meters
(assert cpu > 0).

Make tryReapWithoutStatusCheck poll wait4(WNOHANG) for a bounded budget (1s,
5ms steps) so a promptly-exiting child is reaped and its usage captured. A
child that lingers past the budget still falls through to ~ShellCommand's
bounded command_termination_timeout + SIGTERM teardown, so cleanup never
hangs. The regression test's UDF now closes stdout then sleeps 0.6s before
exiting: above the single-shot failure threshold (deterministic UserTime=0
without the fix) yet within the poll budget and termination timeout.

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

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Local debug build: without the fix UserTime == 0 in 8/8 runs when the UDF sleeps >= 0.5s after closing stdout (0/8 below 0.2s); the failure is deterministic in that window.
b Root cause explained? Yes. check_exit_code=false cleanup reaps via tryReapWithoutStatusCheck, a single wait4(WNOHANG). A child that closed stdout (pipeline done -> cleanup runs) but has only just reached _exit is not yet a reapable zombie -> WNOHANG returns 0 -> rusage never collected -> ExecutableUserDefinedFunctionUserTimeMicroseconds = 0.
c Fix matches root cause? Yes. The reap now polls wait4(WNOHANG) for a bounded budget (1s, 5ms steps), directly closing the "child not yet a zombie at reap time" window instead of masking it.
d Test intent preserved / new tests? Yes. The existing sub-test still asserts cpu > 0; the regression UDF is strengthened (sleep 0.6s after closing stdout) so it now fails deterministically without the fix instead of only ~1% of the time. No assertion weakened.
e Demonstrated both directions? Yes. Without fix: 8/8 fail at 0.6s. With fix: 15/15 pass at 0.6s; 0/8 fail at 0.2/0.5/0.8/0.95s. CHILD_WAS_NOT_EXITED_NORMALLY never logged.
f Fix is general, not a narrow patch? Yes. The fix is in the shared reap primitive ShellCommand::tryReapWithoutStatusCheck, covering every check_exit_code=false executable-UDF/table caller, not just this one test. The lingering-child no-hang path is unchanged.
g Generalizes across inputs? Yes. The reap is child-exit-timing driven, independent of UDF argument types/values; the bounded poll handles any promptly-exiting child, and any child lingering past the budget takes the unchanged SIGTERM teardown.
h Backward compatible? Yes. No setting/format/protocol change. Adds only a bounded internal poll delay (<= 1s) on the check_exit_code=false cleanup path; no user-visible behavior change.
i Invariants and contracts preserved? Yes. The no-hang guarantee holds: a child past the 1s budget still falls through to ~ShellCommand's bounded command_termination_timeout + SIGTERM (existing ..._lingering_child_is_bounded... test invariant preserved). wait_called/reap semantics unchanged.

Session id: cron:clickhouse-worker-slot-5:20260707-142800

@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @rschu1ze — could you review? Small fix: the executable-UDF reap on the check_exit_code=false path did a single wait4(WNOHANG) and lost the child rusage when the child had closed stdout but not yet exited, making test_check_exit_code_false_succeeds_and_meters flaky. The reap now polls with a 1s bounded budget; the no-hang teardown path is unchanged.

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

clickhouse-gh Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4e73d27]

Summary: ✅


AI Review

Summary

This PR fixes the executable-UDF check_exit_code=false accounting race by polling wait4(WNOHANG) until a shared command_termination_timeout deadline, so wait4 resource usage is captured when the child exits shortly after closing stdout, while cleanup and destructor now share one timeout budget instead of double-charging it. The current code addresses the two earlier timeout-accounting issues raised in review, and I do not see a remaining code blocker in the diff; the only issue left is PR metadata.

PR Metadata
  • ⚠️ Changelog category should be Bug Fix, not CI Fix or Improvement. This change fixes a user-visible production bug: executable UDF profile events can report ExecutableUserDefinedFunctionUserTimeMicroseconds = 0 for check_exit_code=false commands that exit shortly after closing stdout.
  • ⚠️ Because this is a Bug Fix, Changelog entry is required. Suggested replacement: Fixes executable UDF profile-event accounting where ExecutableUserDefinedFunctionUserTimeMicroseconds could be reported as 0 for check_exit_code=false commands that exit shortly after closing stdout.
Final Verdict

⚠️ Needs PR metadata fix before merge. No new inline code findings on the current diff.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Jul 7, 2026
Comment thread src/Common/ShellCommand.cpp Resolved
The cleanup reap in tryReapWithoutStatusCheck used a hardcoded 1s poll
budget, which did not follow the command_termination_timeout contract.
With command_termination_timeout=0 that path could still spin ~1s before
~ShellCommand sends SIGTERM, stalling the query beyond the configured
teardown; and when the timeout is larger than 1s, a child that exits
naturally after the 1s budget was reaped by the destructor's waitForPid,
which does not collect wait4 rusage, so
ExecutableUserDefinedFunctionUserTimeMicroseconds stayed 0.

Derive the reap poll budget from
config.terminate_in_destructor_strategy.wait_for_normal_exit_before_termination_seconds
(the same value the destructor waits). A configured 0 means a single
non-blocking reap (no stall); a larger timeout lets the cleanup reap the
child, with its rusage, anywhere inside the configured teardown window
instead of losing usage to the destructor's waitForPid.

The regression UDF now sleeps 2s (inside the 5s command_termination_timeout
but past a 1s window) so the test deterministically distinguishes the
config-derived budget from the old fixed 1s budget.

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

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up to the review comment on reap_poll_budget_ms (commit b258943: reap poll budget now derives from command_termination_timeout).

Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. test_check_exit_code_false_succeeds_and_meters with the UDF sleeping 2s (inside the 5s command_termination_timeout, past a 1s window): fails deterministically on the old hardcoded 1s budget, passes with the config-derived budget.
b Root cause explained? The cleanup reap (tryReapWithoutStatusCheck) used a fixed 1s poll budget. A child that exits between 1s and command_termination_timeout is not reaped in cleanup, so it is reaped by the destructor's waitForPid, which does not collect wait4 rusage -> ExecutableUserDefinedFunctionUserTimeMicroseconds stays 0. And with command_termination_timeout=0 the fixed budget still spins ~1s before SIGTERM, stalling the query beyond the configured teardown.
c Fix matches root cause? Yes. The budget is now config.terminate_in_destructor_strategy.wait_for_normal_exit_before_termination_seconds (== command_termination_timeout): 0 -> single non-blocking reap (no stall); >0 -> cleanup reaps within the configured teardown window, capturing rusage.
d Test intent preserved / new tests added? Preserved. Existing assertions unchanged; the linger test's command_termination_timeout bound (<25s) still holds. The UDF sleep bumped 0.6s -> 2.0s so the regression test now discriminates the config-derived budget from a fixed 1s budget (proven: fails without fix, passes with).
e Both directions demonstrated? Yes, locally on Integration tests (amd). Without fix: got 0 assertion failure. With fix: both ..._succeeds_and_meters and ..._lingering_child_is_bounded_and_flushes_bytes pass.
f Fix is general across code paths? Yes. tryReapWithoutStatusCheck is the single cleanup-reap entry point for check_exit_code=false executable UDFs; no sibling reap path hardcodes a budget. The destructor already uses the same config value.
g Fix generalizes across inputs? Yes. Budget scales with any configured command_termination_timeout; the 0 case is handled (single non-blocking reap, std::min guards the final sleep step so it never overshoots the budget).
h Backward compatible? Yes. No setting default, wire/disk format, or validation change. Behavior now honours the existing command_termination_timeout contract more faithfully than the previous fixed 1s.
i Invariants and contracts preserved? Yes. Cleanup stays non-blocking-bounded; a reaped child sets wait_called, so ~ShellCommand returns immediately (a genuinely lingering child is still bounded by command_termination_timeout + SIGTERM). The "cleanup never turns into a query hang" invariant (linger test) holds.

Session id: cron:clickhouse-worker-slot-7:20260707-160700

Comment thread src/Common/ShellCommand.cpp Resolved
@rschu1ze

rschu1ze commented Jul 7, 2026

Copy link
Copy Markdown
Member

@groeneai 1. Do not use the term "reap" in this PR. 2. Be only half as verbose. 3. Make a test that reproduces the problem.

…omments

Drop the term reap and cut comment verbosity per review. No logic change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai groeneai changed the title Fix rusage race in executable UDF reap with check_exit_code=false Fix rusage race in executable UDF metering with check_exit_code=false Jul 7, 2026
@groeneai

groeneai commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Done (1070f64):

  1. "reap" removed. Method renamed tryReapWithoutStatusCheck -> tryWaitWithoutStatusCheck; the word is gone from the diff, comments, PR title and description.
  2. Comments and description trimmed (net -20 lines in this commit).
  3. The reproducing test is test_check_exit_code_false_succeeds_and_meters with udf_nonzero_exit.py: it closes stdout then sleeps 2s (inside the 5s command_termination_timeout, above a 1s window) so the lost-usage window is deterministic. Locally it fails (UserTime == 0) without the fix and passes with it.

…or waits

The cleanup-side wait and ~ShellCommand each waited the full
command_termination_timeout, so a lingering check_exit_code=false child was
charged the grace period twice (~6s for a 3s config) before SIGTERM. Both waits
now draw from a single monotonic deadline, so the timeout bounds their sum.

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

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. SELECT sum(test_udf_stdout_close_linger(number)) FROM numbers(50) with command_termination_timeout=3: teardown ~6.5s without the fix (repeatable), <5s with it.
b Root cause explained? The cleanup-side tryWaitWithoutStatusCheck polled the full command_termination_timeout, then ~ShellCommand's tryWaitProcessWithTimeout waited the same window again before SIGTERM, so a lingering child was charged the grace period twice (~6s for a 3s config).
c Fix matches root cause? Yes. A single monotonic deadline (remainingTerminationTimeoutMs) is armed by the first waiter and consumed by both, so the timeout bounds their sum, not each. No band-aid to the bound.
d Test intent preserved / new tests added? Yes. The linger test bound was 25s (could not detect the doubling); tightened to 5s so it now reproduces the problem: fails at ~6s, passes at ~3s. Other assertions unchanged.
e Both directions demonstrated? Yes. Without fix: linger test FAILS assert 6.48 < 5. With fix: linger + ..._succeeds_and_meters both PASS (27.6s). Build IDs differ across the two runs.
f Fix is general across code paths? Yes. Both wait paths through ShellCommand teardown now use the shared deadline; the single tryWaitProcessWithTimeout caller and the single tryWaitWithoutStatusCheck caller are covered.
g Fix generalizes across inputs? Yes. command_termination_timeout=0 -> single non-blocking attempt (no stall); >0 -> shared window regardless of when the child exits or lingers.
h Backward compatible? Yes. No setting/format/API change. Teardown is now closer to the configured timeout than before (previously it could be up to 2x).
i Invariants and contracts preserved? Yes. Reaping still sets wait_called (destructor early-returns after cleanup reap); rusage still captured only via cleanup wait4; deadline armed once, monotonic, never resets.

Session id: cron:clickhouse-worker-slot-1:20260708-003900

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 26/27 (96.30%) · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 4e73d27

Every failure below has an owner. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (arm_tsan) / "Possible deadlock on shutdown" (test row; the check itself passed) chronic hung-check-on-shutdown family #108212 (ours, merged) / #105905 (ours, merged)

All checks are green (Mergeable Check SUCCESS, Finish Workflow COMPLETED).

Session id: cron:our-pr-ci-monitor:20260708-050000

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good.

@alexey-milovidov alexey-milovidov self-assigned this Jul 11, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 11, 2026
Merged via the queue into ClickHouse:master with commit cb49e25 Jul 11, 2026
175 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 11, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix rusage race in executable UDF metering with check_exit_code=false

ClickGap verified: reproduced it with the script below on 26.6; tested 2 version(s) — 1 affected, 1 clean (see Affects); bisected to a candidate range — a single introducing PR could not be pinned (see Bisect).

Reproduction

Shell reproducer — run against a local ClickHouse build (bash <script> <clickhouse-binary>); requires the referenced test fixtures from the repo.

# Executable UDF with check_exit_code=false whose script closes stdout, sleeps
# 2s (inside command_termination_timeout=5s), then exits non-zero:
#   functions/udf.xml: test_udf_nonzero_exit -> udf_nonzero_exit.py
#     <check_exit_code>false</check_exit_code>
#     <command_termination_timeout>5</command_termination_timeout>
#   udf_nonzero_exit.py: after emitting rows -> os.close(1); time.sleep(2.0); os._exit(3)
clickhouse local --print-profile-events \
  --query "SELECT sum(test_udf_nonzero_exit(number)) FROM numbers(20)"
# Observed (pre-fix): ExecutableUserDefinedFunctionUserTimeMicroseconds == 0 (rusage lost:
# tryWaitWithoutStatusCheck did a single wait4(WNOHANG) and the child was alive-but-not-zombie);
# expected > 0. Integration test: test_executable_udf_profile_events::test_check_exit_code_false_succeeds_and_meters

Bisect

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.6
  • Does NOT reproduce on: master
  • Could not test (binary unavailable): 26.5, 26.4, 26.3, 26.2, 26.1
  • Backport needed: 26.6

Suggested next step

The bug reproduces as far back as the oldest tested release (26.6) and the only converged boundary is topically unrelated — this is a long-standing / pre-existing bug in comp-udf, not a recent regression; no introducing PR exists within the tested range.

Component: comp-udf
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @alexey-milovidov


ClickGap · Finding: phase_d_pr109667

Triage metadata

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…it-rusage-race

Fix rusage race in executable UDF metering with check_exit_code=false
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-ci 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.

6 participants