Skip to content

Populate ProfileEvents for executable UDFs via wait4 - #105618

Merged
vdimir merged 42 commits into
ClickHouse:masterfrom
andreev-io:ilyaandreev/udf-executable-profile-events-impl
Jun 9, 2026
Merged

vdimir merged 42 commits into
ClickHouse:masterfrom
andreev-io:ilyaandreev/udf-executable-profile-events-impl

Conversation

@andreev-io

@andreev-io andreev-io commented May 22, 2026 •

Copy link
Copy Markdown
Member

Populates the eight ExecutableUserDefinedFunction* ProfileEvents on the executable (non-pool) UDF path, so a query that calls a non-pool UDF shows up in system.query_log.ProfileEvents with per-call invocation count, wall time, child-process CPU and peak memory, and stdin/stdout bytes. ExecutableUserDefinedFunctionPoolWaitMicroseconds is N/A for this path and stays zero.

wait4 is used instead of the RFC's proposed POSIX shim to get per-child rusage atomically without an extra fork. Full rationale in #105523 (comment).

This completes the synchronous-metrics line of RFC #105523: #104998 (merged) registered the eight events; #105010 (merged) populates them for executable_pool UDFs via the shared UDFProcessSubtreeSampler; this PR populates them for executable UDFs by folding the rusage captured by wait4 in ShellCommand into the same sampler (recordExecutableFinished). The RFC's asynchronous per-UDF gauges (live process count and current RSS, landing in system.asynchronous_metrics / system.asynchronous_metric_log) are out of scope here and remain pending.

The cleanup reap is non-blocking: with check_exit_code=false the source deliberately does not wait for the child, so a WNOHANG reap harvests rusage when the child has already exited and otherwise skips accounting — profiling never adds a blocking wait. Terminating the child is left to ShellCommand's existing destructor teardown, exactly as before this change. The default check_exit_code=true path already reaps via prepare's blocking wait, so rusage is captured there.

Changelog category (leave one):

  • Improvement

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

Populate the ExecutableUserDefinedFunction* ProfileEvents counters for executable UDFs. Per-call invocation count, wall time, child-process CPU and peak memory, and stdin/stdout bytes are now visible in system.query_log.ProfileEvents.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.572

Wires the seven `ExecutableUserDefinedFunction*` ProfileEvents
(Invocations, ElapsedMicroseconds, UserTimeMicroseconds,
SystemTimeMicroseconds, PeakMemoryByteSeconds, InputBytes,
OutputBytes) for `executable`-type UDFs. The non-pool path uses
`wait4` on the UDF child for atomic per-child rusage; the existing
`UDFProcessSubtreeSampler` is extended with a `recordExecutableFinished`
method that consumes the rusage struct and fills the same accumulators
used by the procfs-based pool path.

Implements step 3 of ClickHouse#105523.
Mirrors tests/integration/test_executable_pool_udf_profile_events
for the non-pool `executable` type. Excludes the pool-wait test
(N/A for executable). Re-uses the same user-script bodies and
assertion tolerances.
- Replace blocking `tryWait` with non-blocking
  `waitIfProccesTerminated` in `ShellCommandSource::cleanup`, so
  the destructor's bounded SIGTERM path is not bypassed when a child
  is stuck (validator B1).
- Read `wasChildReaped` regardless of whether the wait threw;
  `wait4` populated rusage before any `WIFSIGNALED` throw, so
  signal-terminated children still contribute to ProfileEvents
  (validator B2).
- Gate `recordReleased` on `borrowAcquired` so the procfs path
  runs only for the pool mode (validator I1, I2).
- Hide `::rusage` behind narrow `ShellCommand` accessors
  (`wasChildReaped`, `getLastChild{User,System}TimeMicroseconds`,
  `getLastChildPeakRssBytes`) so `<sys/resource.h>` no longer leaks
  out of `ShellCommand.h` (validator I4).
- Drop a dead `SETTINGS max_block_size = 1` in the elapsed-time
  integration test (validator I5).
- Tighten the `wait4` comment in `tryWaitImpl` (validator N3) and
  normalise digit separators in the sampler (validator N1).
- Lower `test_peak_memory_uses_rusage_units` bound to 100_000
  byte-seconds (10x safety margin). The test verifies wait4
  ru_maxrss unit handling, not a minimum allocation — a loose
  bound preserves that intent on fast machines.
- `UDFProcessSubtreeSampler::recordExecutableFinished` now
  short-circuits on repeat calls, matching its "at most once"
  contract and protecting against future call-site bugs.
@clickhouse-gh

clickhouse-gh Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9683d1d]

Summary: ✅


AI Review

Summary

This PR populates the existing ExecutableUserDefinedFunction* ProfileEvents for non-pool executable UDFs by collecting child CPU through wait4, sampling executable peak RSS through /proc during I/O, and flushing invocation, elapsed, CPU, memory, and byte counters through the existing UDF execution pipeline. I reviewed the current combined diff, prior review threads and replies, PR metadata, and the current CI report; the earlier issues around unbounded check_exit_code=false cleanup, status validation, lost byte/elapsed counters, post-reap allocation, fd leaks, and unthrottled/noexcept procfs sampling are addressed in the current code.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 22, 2026
…mand.cpp`

`wait4` is only declared once `_DEFAULT_SOURCE` is defined on glibc under
`-std=c++23`, but the bare `#define` tripped `-Werror` on
`-Wreserved-macro-identifier` and `-Wunused-macros` (and the clang-tidy
`bugprone-reserved-identifier` check on the `arm_tidy` build). Wrap the define
in `#pragma clang diagnostic` and a `NOLINT`, and drop the `// namespace DB`
closing comment that the style check rejects.
When an executable UDF sets `check_exit_code=false`, `prepare` skips its
blocking `wait`, so the child was reaped with a single non-blocking `WNOHANG`
call in `cleanup`. That call usually missed the not-yet-zombie child, leaving
`last_resource_usage` unset; `~ShellCommand` then reaped via `waitpid` (no
rusage). The result was that every resource counter
(`ExecutableUserDefinedFunction{UserTime,SystemTime,PeakMemoryByteSeconds,
Elapsed}Microseconds`, `InputBytes`, `OutputBytes`) was silently zero while
`ExecutableUserDefinedFunctionInvocations` was still counted.

Block via `tryWait` on a normal finish to reap and capture rusage, matching the
`check_exit_code=true` path which already blocks in `prepare`. Keep the
non-blocking reap on an error/timeout unwind so `~ShellCommand`'s bounded
SIGTERM teardown still applies.
…ments

- Add `test_cpu_captured_when_check_exit_code_disabled` with a
  `check_exit_code=false` UDF so the `cleanup` blocking reap is actually
  exercised (it reads zero CPU without the preceding fix, non-zero with it).
- Add `test_pool_wait_is_zero_on_executable_path` so the N/A
  `ExecutableUserDefinedFunctionPoolWaitMicroseconds` is asserted to stay zero
  off the pool path.
- Pin `test_invocations` to exactly 5 via `max_block_size = 1000`, catching both
  double-counting and missing-increment regressions.
- Guard `test_elapsed_microseconds` against a future constant-folding regression.
- Correct the `getElapsedMicroseconds` doc comment and the stale "100 Hz"
  comments in the CPU/syscall scripts — the executable path reads `wait4` rusage
  (microsecond resolution), not `/proc/<pid>/stat` ticks.
…impl

`ClickHouse#105010` (executable_pool ProfileEvents) merged to master, so its sampler,
factory wiring, byte accounting and pool tests now live there — and in a more
advanced form than this branch's stale copy (procfs-failure observability). Take
master's authoritative version of every shared file
(`UDFProcessSubtreeSampler.{h,cpp}`, `UserDefinedExecutableFunctionFactory.cpp`,
`ShellCommandSource.{h,cpp}`, `ProfileEvents.cpp`, the pool test) and keep only
the executable-specific `ShellCommand.{h,cpp}` and `test_executable_udf_profile_events`.
The executable wiring on top of master's sampler/factory is re-applied next.
…5010

ClickHouse#105010 added the shared `UDFProcessSubtreeSampler` and the factory/source pool
wiring; this populates the same `ExecutableUserDefinedFunction*` `ProfileEvents`
for the `executable` (non-pool) path. `ShellCommand::tryWaitImpl` already captures
per-child `rusage` via `wait4`; `UDFProcessSubtreeSampler::recordExecutableFinished`
folds it into the accumulators and `ShellCommandSource::cleanup` calls it after the
child is reaped.

The cleanup reap is NON-BLOCKING: with `check_exit_code=false` the source must not
wait for the child, so a `WNOHANG` reap harvests `rusage` when the child has already
exited and otherwise skips accounting, leaving `~ShellCommand`'s bounded
`command_termination_timeout` + SIGTERM teardown to terminate a lingering child. The
default `check_exit_code=true` path already reaps via `prepare`'s blocking `wait`.

The factory now creates the sampler and counts `Invocations` for both paths and
flushes counters on `borrowAcquired` (pool) or `executableFinished` (executable).
The seven shared counter descriptions are broadened to "executable and
executable_pool"; `PoolWaitMicroseconds` stays pool-only.
…false cleanup

Add `test_check_exit_code_false_does_not_hang`: a `check_exit_code=0` UDF whose
script emits its rows, closes stdout, then sleeps far past
`command_termination_timeout`. The query must return promptly (bounded teardown),
not block in `cleanup` — a regression to a blocking reap would make it take ~120s.

Drop `test_cpu_captured_when_check_exit_code_disabled`: asserting non-zero CPU on
the now non-blocking reap path is racy (the child may not have exited at cleanup).
The default `check_exit_code=true` tests already cover `rusage` capture.
Comment thread src/Common/ShellCommand.cpp Resolved
`tryWaitImpl` reaped the child with `wait4` and only set `wait_called` after
`std::make_unique<LastChildResourceUsage>`. If that allocation threw, unwinding
left `wait_called` false, so `~ShellCommand` could route the already-reaped — and
possibly pid-reused — child through `waitForPid` and SIGTERM. Set `wait_called`
the instant the child is reaped, before any throwing work; on allocation failure
the rusage is simply unavailable (`wasChildReaped` stays false) and the destructor
correctly does nothing.
`waitForPid` reset a per-iteration stopwatch and subtracted only the last
`pollPid` call's duration from the budget. On the non-`pidfd` `/proc/<pid>`
fallback, `poll` on a directory fd is always immediately ready, so `pollPid`
returned in ~0 ms, the subtracted delta was ~0, the budget never shrank, and the
loop spun until the child exited on its own — `timeout_in_seconds` was silently
ignored. A `check_exit_code=false` executable UDF that closes stdout then keeps
running therefore hung the query for the child's whole lifetime instead of being
terminated after `command_termination_timeout` in `~ShellCommand`.

Bound the total wait by the stopwatch started at function entry instead. The
common path (child exits, `pollPid` blocks until exit on pidfd/kqueue) is
unchanged; the `/proc` fallback now busy-waits at most `timeout_in_seconds`
before returning false so the caller can send `SIGTERM`.
Investigating the no-hang scenario showed the residual ~120s wait for a
`check_exit_code=false` UDF that closes stdout and lingers is pre-existing,
layered `ShellCommand` teardown behaviour (the pipe close in
`tryWaitProcessWithTimeout` waits for the child to release the pipe, only at its
exit), not the single `waitForPid` timeout issue. Bounding it would need changes
to `ShellCommand`'s teardown semantics affecting every consumer (StorageExecutable,
dictionaries) — out of scope here.

The reviewer's actual concern is satisfied independently: the executable cleanup
reap is non-blocking (verified — it never waits for the child). Remove the
`test_udf_linger_no_exit_check` fixture and `test_check_exit_code_false_does_not_hang`
test, and revert the `waitForPid` timeout fix so this PR stays scoped to executable
UDF ProfileEvents. The `waitForPid` bug is real and can be fixed separately.
…eck_exit_code=false

The `executable` UDF cleanup reap called `waitIfProccesTerminated`, which validates
the child exit status — `tryWaitImpl` throws on `WIFSIGNALED`/`WIFSTOPPED` and
`handleProcessRetcode` throws `CHILD_WAS_NOT_EXITED_NORMALLY` on a non-zero exit. A
`check_exit_code=false` UDF that writes its rows, closes stdout and exits non-zero
(e.g. status 42) made the query succeed but the cleanup `catch` log a spurious
`CHILD_WAS_NOT_EXITED_NORMALLY`, even though that config means the exit status must
not be treated as an error.

Add a `check_exit_status` parameter to `tryWaitImpl` (default true, so `wait`,
`tryWait` and `waitIfProccesTerminated` are unchanged) that, when false, returns
right after reaping and capturing `rusage`, skipping the status decode/throws. The
cleanup reap now uses a new non-validating `tryReapWithoutStatusCheck`, so it only
captures resource usage and leaves status handling to `prepare` (which runs only
for `check_exit_code=true`). The reap stays non-blocking.
`tryWaitImpl` previously reaped every `ShellCommand` child with `wait4` to
capture `rusage`. `ShellCommand` is shared by `StorageExecutable`, executable
dictionaries, the bridge helpers and the client, none of which read the usage,
so they should keep the plain `waitpid` they have always used.

Add `ShellCommand::Config::collect_resource_usage` (default false): only when it
is set does `tryWaitImpl` use `wait4` and allocate the `rusage`; otherwise it
calls `waitpid` and allocates nothing. `ShellCommandSource` sets the flag only on
the executable (non-pool) UDF path — identified by an attached
`UDFProcessSubtreeSampler` — so `executable_pool` workers (which meter via
`/proc`) and all non-UDF consumers are byte-for-byte unchanged.
Describe what the code does rather than narrating the change: drop "keeps plain
waitpid" / "every other consumer" phrasings in favour of describing the two
branches (with the flag → `wait4` + rusage; without it → plain `waitpid`).
`collect_resource_usage`: state what each value does, without "non-UDF consumers
are unaffected". Factory invocations comment: "the other resource counters",
not "counters below".
…nches

`cleanup()` had two consecutive `if (sampler …)` blocks: the pool `recordReleased`
(a no-op on the executable path via its `borrow_acquired` early-return) and the
executable reap. Fold them into one `if (process_pool) … else if (command) …` so
the pool-vs-executable split is explicit. Behaviour is unchanged: the conditions
are the same, just made mutually exclusive.
One short comment on `recordExecutableFinished`: `wait4` rusage counts the child
plus the descendants it reaps (CPU summed, peak RSS maxed), unlike pool mode's
/proc subtree walk. Documents the distinction in one place, not in the event names.
The previous wording ("set only when a sampler is present") could read as if
pool UDFs — which also have a sampler — set the flag. Make explicit that this is
the non-pool branch; pool UDFs take the pooled branch and reap with plain waitpid.
InputBytes and OutputBytes are recorded by the pipe buffers as data
streams through, so they are valid for any executable UDF call that
performed I/O, independent of whether the child was reaped. With
check_exit_code=false a child can write all rows, close stdout, then
linger; it is never reaped, executableFinished() stays false, and the
already-observed byte counts were dropped. Flush the byte counters
unconditionally and gate only the wait4-derived time and memory counters
on a successful reap.
Cover non-pool executable paths not previously exercised:
- execute_direct=false (shell launch) still meters child rusage via wait4
- CPU and peak RSS of a reaped child roll up; an unwaited child's CPU is
  excluded
- peak memory is max-of-per-process-peaks, not a concurrent sum
- check_exit_code=false: a non-zero exit does not raise and does not log
  CHILD_WAS_NOT_EXITED_NORMALLY, and a child that closes stdout then
  lingers keeps cleanup non-blocking while its byte counters still flush
`pollPid` closed the `pidfd` / `/proc` fd (Linux) and the `kqueue` fd
(macOS, FreeBSD) only on the success path. A `poll`/`kevent` timeout or a
filter-add error returned without closing it, leaking one descriptor per call.
With the teardown timeout now honoured, a lingering `check_exit_code=false`
child hits this on every `command_termination_timeout`, so repeated calls can
exhaust server file descriptors. Release the handle via `SCOPE_EXIT` so it is
closed on every return path.
`pollPid` wrapped its `poll`/`kevent` wait in `HANDLE_EINTR`, which restarts the
syscall with the full timeout on every `EINTR`. When the query profiler is active
its `SIGPROF` interrupts the wait periodically, so it never completes its timeout
and `waitForPid` blocks until the child exits — a `check_exit_code=false` UDF whose
child closes stdout and lingers then holds the query for the child's whole lifetime.
Return `RESTART` on `EINTR` instead, so `waitForPid`'s outer loop re-evaluates the
remaining budget (bounded by the stopwatch started at function entry) and the total
wait stays within `command_termination_timeout`.
}

ShellCommand::tryWaitResult ShellCommand::tryWaitImpl(bool blocking)
ShellCommand::tryWaitResult ShellCommand::tryWaitImpl(bool blocking, bool check_exit_status)

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.

Is it that we now call tryWaitImpl multiple times with different flags - first as a regular wait with check_exit_status, and later from cleanup just to collect statistics? If the process has already terminated, does wait4 handle that correctly?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Is it that we now call tryWaitImpl multiple times with different flags - first as a regular wait with check_exit_status, and later from cleanup just to collect statistics?

I added this because a UDF can be launched with check_exit_code=false but we still want to reap to collect resource usage. Previously, if check_exit_code was false, we wouldn't have reaped.

multiple times with different flags

If the first time we called we have check_exit_status true, we don't call again. Otherwise, we call again in cleanup to reap. This is guarded by checking command->isWaitCalled(). In any case, we reap at most once (we reap zero times if check_exit_code is false and then the process keeps running for longer than we wait in tryWaitProcessWithTimeout).

If the process has already terminated, does wait4 handle that correctly?

Yes, it should be OK to reap on a terminated process. The only problem would be if reaped twice, but we don't do that.

@andreev-io andreev-io Jun 9, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I added this because a UDF can be launched with check_exit_code=false but we still want to reap to collect resource usage.

Sorry, this isn't exactly accurate. Without this parameter, the reap would validate the exit status and throw CHILD_WAS_NOT_EXITED_NORMALLY on a non-zero exit. check_exit_code=false UDFs are allowed to fail, so we need to reap for rusage without checking the status. That's what this parameter makes possible.

Comment thread src/Common/ShellCommand.cpp Resolved
Comment thread src/Common/waitForPid.cpp
watch.restart();

PollPidResult result = pollPid(pid, timeout_in_ms);
const Int64 remaining_ms = total_timeout_ms - static_cast<Int64>(watch.elapsedMilliseconds());

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.

Was it a bug that we waited more then remaning timeout in pollPid? Does it affect only executable udfs?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, there was a bug. Previously, every signal restarted the timeout from zero.

No, this change actually isn't specific to executable UDFs. It affects every user of ShellCommand (executable dictionaries, table functions, the pool, executable UDFs). Apparently any of them could over-wait, for example when query profiler was enabled and returned SIGPROF.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Checked every caller for blast radius. waitForPid is reached only from ShellCommand's destructor teardown (tryWaitProcessWithTimeout), and the changed poll loop runs only when the timeout is positive — a 0 timeout takes a single non-blocking waitpid fast path that this diff doesn't touch.

  • The odbc/library bridges (IBridgeHelper) and the client's pager/editor (ClientBase) pass timeout 0, so they hit that fast path and never reach the changed code.
  • Only ShellCommandSource — executable UDFs and executable table functions, default command_termination_timeout=10s — passes a positive timeout and reaches the loop.
  • Everything else uses terminate_in_destructor=false and doesn't call waitForPid at all.

So it's not UDF-specific (it also covers executable table functions), but the only behavioral change is that those teardowns now honor command_termination_timeout instead of over-waiting. The overshoot only happened under signals (the profiler's SIGPROF) and contradicted the timeout's documented meaning, so nothing relied on it.

…u_maxrss

For a `vfork`+`exec` child the kernel folds the pre-`exec` mm's RSS into
`signal->maxrss` at `exec`, so `wait4`'s `ru_maxrss` reports the parent
(ClickHouse server) RSS rather than the child's. `PeakMemoryByteSeconds`
therefore shipped the server footprint (~hundreds of MiB) identically for
every executable UDF, independent of its real allocation.

Sample `/proc/<pid>/VmHWM` across the child subtree during IO instead, while
the child is provably alive (it just produced output or is consuming stdin).
`VmHWM` is the current mm's high-water mark: parent-independent and monotonic,
so it captures transient and pre-output peaks even after the child frees them.
`recordExecutableElapsed` now derives `peak_memory_byte_seconds` from the
sampled peak and is independent of the reap; `wait4` is kept for CPU only.

`sampleExecutablePeak` is gated on a dedicated `executable_root_pid`, so the
pool path and non-UDF `ShellCommand` consumers are untouched. A descendant pid
that vanishes between the subtree walk and the per-pid read is treated as
having exited (benign); only a failed read of the root pid signals degradation.

Add `test_peak_memory_reflects_udf_not_server`: a high-allocation UDF must
report a meaningfully higher implied peak than a near-zero-allocation one, which
is impossible if the metric is pinned to the shared server RSS. The previous
lower-bound floors passed under the contaminated value and could not catch this.
The memory fork scripts keep their children alive until the parent has written
output so the subtree sample observes them.
…le check

The style check flags `catch (...)` blocks that swallow exceptions unless the
block carries a comment noting the suppression is intentional.
Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
`sampleExecutablePeak` ran a full `/proc` subtree walk plus per-pid `VmHWM`
read on every IO buffer fill, so a UDF streaming large output performed tens of
thousands of walks. Throttle it to at most one walk per ~5 ms; `VmHWM` is a
monotonic high-water mark, so a process observed at least once after reaching
its peak is still captured exactly. The first call always samples (start) and a
best-effort final call is issued at stdout EOF (finish) for a child that lingers
after closing stdout. Measured cost of one walk is ~34 us for a single-process
UDF and ~104 us for a three-process subtree (100% CPU, mostly kernel time), so
the throttled worst case is well under one tenth of a core and is flat in data
volume.

Harden the `noexcept` boundary: the per-pid `readPeakRss` loop builds a path
string and opens an `ifstream`, so a `std::bad_alloc` under a memory limit could
have crossed `noexcept` and called `std::terminate`. The whole walk-and-read
body now runs inside one try/catch. A failed root read on the final call is not
treated as degradation, since the child has usually already exited by then.

The forked-child memory tests previously raced: they sampled the child before it
finished allocating, or after it was reaped, so they measured the ~10 MiB parent
and passed only because of a loose lower-bound floor. The child UDFs now allocate,
signal readiness, and stay alive at their peak while the parent emits output, and
the assertions require the child's real resident set (>= 40 MiB for the 64 MiB
child; >= 60 MiB for the 100 MiB children) so they fail if only the parent is
seen. A short-lived child reaped between samples remains best-effort; this is
documented on `sampleExecutablePeak`.
@andreev-io

Copy link
Copy Markdown
Member Author

Memory-sampling overhead, measurements, and mitigations

Concern. The executable-UDF peak-memory metric samples /proc/<pid>/VmHWM across the child subtree during IO. Initially this ran a full subtree walk plus a per-pid VmHWM read on every IO buffer fill, so a UDF streaming large output performed tens of thousands of walks (≈25k for 100 MiB of output), and the sampler is installed for every executable UDF.

Measurements (on the target hardware, 100k iterations replicating walkSubtree + readPeakRss):

Subtree Per walk Nature
Single-process UDF ~34 µs ~100% CPU (thread_cpu ≈ wall), ~90% kernel time generating /proc
UDF + 2 children (3 pids) ~104 µs same

The cost is genuine CPU on the IO thread (confirmed with CLOCK_THREAD_CPUTIME_ID), almost entirely kernel time synthesising /proc/<pid>/{status,task} — there is no device IO to block on.

Mitigations.

  • Throttle to at most one walk per ~5 ms. VmHWM is a monotonic high-water mark, so sparse sampling still captures each process's true peak; tightening the interval does not improve accuracy for the processes that matter (the UDF and any long-lived helper are observed across many samples regardless).
  • Bounded boundary samples: the first call always samples (start) and one best-effort sample is taken at stdout EOF (finish).
  • Result: a worst case — a UDF streaming continuously for the whole query — of ~0.7% of one core (single-process) to ~2% (forking), and the cost no longer scales with input/output volume.

Known limitation. Because /proc is observed only at these throttled sample points, a short-lived child that allocates and is reaped between two samples is best-effort and may be under-counted. A process alive at least once after reaching its peak is captured exactly (monotonic VmHWM). This is documented on sampleExecutablePeak.

A UDF that writes all expected rows, closes stdout, then allocates and holds
~256 MiB before exiting 0 (default `check_exit_code=true`) has that post-output
allocation reflected in `ExecutableUserDefinedFunctionPeakMemoryByteSeconds`: the
peak sampler keeps sampling the child subtree at its end-of-stream cadence while
the child lingers through the blocking reap, so the peak stays consistent with the
CPU and elapsed that `wait4` and `recordExecutableElapsed` attribute to the same
post-EOF interval. The child holds the buffer for ~2 s, far longer than the sample
cadence, so the assertion is deterministic rather than racy (verified over repeated
runs).
Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
`walkSubtree` opened a `/proc/<pid>/task` directory and closed it manually at the
end of the loop body, but built `children_path` and opened an `ifstream` after
`opendir` succeeded. Under a memory limit one of those allocations can throw; the
exception propagates out and `sampleExecutablePeak` swallows it, so `closedir`
was skipped and a directory fd leaked per failed sample. Guard the handle with
`SCOPE_EXIT` so it is released on every path, including the exceptional one.
The executable peak sampler took a one-shot sample at stdout EOF that could
incidentally re-fire during the post-EOF blocking reap, leaving it unclear
whether `ExecutableUserDefinedFunctionPeakMemoryByteSeconds` covered the
post-output interval. Define the contract explicitly: drop the EOF sample so
peak RSS is sampled only during the input/output phase (the throttled
stdout-read and stdin-write samples). Memory the child allocates after closing
stdout is not included in the peak, although elapsed time and the `wait4` CPU
events still cover that interval; this is documented in the event description
and the sampler header.

`test_peak_memory_excludes_post_eof_allocation` locks the contract: a UDF that
writes every row, closes stdout, then allocates 256 MiB must report a peak that
excludes it. The forked-child memory tests are unaffected — they capture during
the output phase via the IO-loop samples.
Comment thread src/Common/ShellCommand.cpp Resolved
…cutable UDFs

Peak memory: take one best-effort concluding sample when the stdout read reaches
EOF (fired once via a guard in the read buffer), so a peak reached just before
the function closes stdout is captured. This is not continuous coverage of the
post-output reap — it is documented as a single best-effort tail reading. A
short-lived UDF that writes small output and exits before ClickHouse drains
stdout may still report a near-zero peak; this is documented in the event
description and on the sampler.

ShellCommand: capture the reaped child's CPU times by value at reap time instead
of heap-allocating after the child has exited, so a memory-limit `exception` can
no longer fail a query whose child already finished successfully.

UDFProcessSubtreeSampler: the executable path no longer raises the
"PeakMemoryByteSeconds will under-count" degradation flag on a `readPeakRss`
failure — the child's lifetime is not under our control, so a failed read is
usually a legitimately-exited child rather than a sandbox denial. The pool path,
where the borrowed worker is provably alive during sampling, still flags it.

Also correct stale doc comments (the sampler lifecycle bullet and
`recordExecutableFinished` idempotency), clarify the `pollPid` timeout-vs-error
return, and remove the post-EOF exclusion test whose assertion no longer matches
the best-effort tail contract.
The best-effort and short-lived-UDF caveats live in the sampler comments and the
PR description; the ProfileEvents entry stays a concise one-liner like its peers.
…sed]]

The amd_darwin, arm_darwin and amd_freebsd builds failed with
-Werror,-Wunused-parameter: `is_final` is referenced only inside the
`#if defined(OS_LINUX)` block (the throttle gate), since the `/proc VmHWM`
sampling is Linux-only. On other platforms that block is compiled out and the
parameter is unused. Mark it `[[maybe_unused]]` on the declaration and
definition; it stays genuinely used on Linux.
Reading res > 0 means the child produced that output and it sits in the pipe
buffer; it does not prove the child is still alive when we sample. A short-lived
UDF can write a small result and exit before we drain stdout, in which case the
sample finds no VmHWM and is a harmless no-op. Reword the comment accordingly;
no behavior change.
A successful write means the child's stdin is open (it was running), not that it
is actively consuming the bytes — they enter the pipe buffer and the child reads
them later, or exits first (then the sample is a harmless no-op). Reword to match;
no behavior change.
@clickhouse-gh

clickhouse-gh Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.60% 84.60% +0.00%
Functions 92.30% 92.30% +0.00%
Branches 77.20% 77.20% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 170/212 (80.19%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 1 line(s) · Uncovered code

Full report · Diff report

@vdimir
vdimir added this pull request to the merge queue Jun 9, 2026
Merged via the queue into ClickHouse:master with commit 784958f Jun 9, 2026
166 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 9, 2026
fkastrati pushed a commit to fkastrati/ClickHouse that referenced this pull request Jun 22, 2026
Two new server asynchronous metrics, sampled every
`asynchronous_metrics_update_period_s`:

- `ExecutableUserDefinedFunctionMemoryResident`: sum of VmRSS over all
  live executable and executable_pool UDF processes and their descendant
  processes, in bytes.
- `ExecutableUserDefinedFunctionProcesses`: number of processes the sum
  was taken over.

Unlike the per-invocation ProfileEvents (ClickHouse#105618), this is a
point-in-time view that includes idle executable_pool workers, which
hold their memory between invocations.

Live UDF child pids are tracked in a new `UDFProcessRegistry`:
`ShellCommand` registers the pid at spawn (a new Config flag set only
by the executable UDF path) and removes it at the two points where the
pid stops being ours: at reap in `tryWaitImpl`, and before
`waitForPid` in `tryWaitProcessWithTimeout` on destructor teardown.
A reused pid can therefore never be sampled or unregistered by a stale
wrapper. The sweep reuses `UDFProcfs::walkSubtree` plus a new
`readCurrentRss` (VmRSS from /proc/<pid>/status), deduplicating pids
across subtrees; a zombie has no VmRSS line and drops out of both
metrics.

Summing VmRSS counts shared pages once per process, so the metric is an
upper bound on the unique physical footprint; the limitation is
documented in the metric description. PSS from smaps_rollup was measured
and rejected: its page-table walk cost scales with resident size, which
is unacceptable inside the once-per-second update loop.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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