Skip to content

Populate ProfileEvents for executable_pool UDFs - #105010

Merged
vdimir merged 37 commits into
ClickHouse:masterfrom
XuJia0210:xujia/udf-pool-profile-events-impl
Jun 4, 2026
Merged

vdimir merged 37 commits into
ClickHouse:masterfrom
XuJia0210:xujia/udf-pool-profile-events-impl

Conversation

@XuJia0210

@XuJia0210 XuJia0210 commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Stacks on top of #104998. Adds the eighth ExecutableUserDefinedFunction* ProfileEvent (PoolWaitMicroseconds) and populates all eight on the executable_pool UDF path, so a query that calls a pool UDF shows up in system.query_log.ProfileEvents with per-call invocation count, wall and pool-wait time, child-process CPU and peak memory, and stdin/stdout bytes.

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_pool UDFs. Per-call invocation count, wall and pool-wait 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.377

Adds the eighth ProfileEvent
`ExecutableUserDefinedFunctionPoolWaitMicroseconds` (the other seven
were registered by PR ClickHouse#104998) and populates all eight on the
`executable_pool` UDF path.

A new `UDFProcessSubtreeSampler` walks
`/proc/<pid>/task/<tid>/children` at borrow and again at release. The
pre-snapshot writes `5` to `/proc/<pid>/clear_refs` to reset `VmHWM`,
the post-snapshot reads `VmHWM` and sums `utime`/`stime` deltas for
pids seen in both walks. CPU is only attributed for pids present at
both snapshots, avoiding the over-attribution that would happen if a
pre-walk `readStat` failed on a warm pool worker (its lifetime
`utime` would land in the post sum with no baseline to subtract).

The sampler is wired into the borrow lifecycle via a `shared_ptr` in
`ShellCommandSourceConfiguration`. Other consumers (executable
dictionaries, `StorageExecutable`) leave it null, so they remain
strict no-ops. The increment block runs from `SCOPE_EXIT` so failed
UDF queries still report whatever resource was consumed before the
failure.

Procfs failures (ENOENT, EACCES, parse errors) are silently skipped:
CPU/memory increments may be dropped but the other six events keep
firing.
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9df4bc4]

Summary: ✅


AI Review

Summary

This PR adds executable_pool UDF resource accounting through new ExecutableUserDefinedFunction* ProfileEvents, a /proc-based UDFProcessSubtreeSampler, lifecycle wiring in ShellCommandSource, and focused integration coverage. The main design is in place, but there are still correctness gaps in the best-effort sampler failure paths and one test that does not prove the PoolWaitMicroseconds contract it is meant to cover.

Findings

⚠️ Majors

  • [src/Common/UDFProcessSubtreeSampler.cpp:66] walkSubtree is best-effort and its callers catch allocation exceptions, but the raw DIR * opened here is only closed at line 105. If children_path construction, std::ifstream, or result.push_back throws before closedir, the sampler leaks a file descriptor while the query continues.
    Suggested fix: wrap the handle immediately, for example with std::unique_ptr<DIR, decltype(&::closedir)> dir(::opendir(...), &::closedir), and call readdir(dir.get()).

  • [src/Common/UDFProcessSubtreeSampler.cpp:276] A pre-snapshot readStat failure still lets CPU attribution proceed with an incomplete baseline. If a helper PID is seen during the pre-walk, readStat fails, and the parent reaps that helper during the borrow, the parent's later cutime / cstime includes the helper's lifetime CPU while pre_utime_sum / pre_stime_sum has no matching baseline to subtract. That can charge pre-borrow CPU to the current query.
    Suggested fix: mark the CPU baseline invalid when any pre-snapshot readStat fails, and skip UserTimeMicroseconds / SystemTimeMicroseconds for that borrow.

  • [src/Common/UDFProcessSubtreeSampler.cpp:61] [dismissed by author -- https://github.com/Populate ProfileEvents for executable_pool UDFs #105010#discussion_r3338769567] The MAX_PIDS warning still misses cap-hit cases because the outer loop stops once result.size() == MAX_PIDS. If the root contributes exactly enough direct children to fill the vector, queued children are never walked, their descendants are silently dropped, and truncated remains false unless one more child was seen in the same children file. I still consider this real because the current loop condition is unchanged.
    Suggested fix: either continue walking already-collected PIDs and set truncated when a new unique child is seen at the cap, or mark truncation whenever the cap is reached before the queue is drained.

Tests
  • ⚠️ [tests/integration/test_executable_pool_udf_profile_events/test.py:145] The PoolWaitMicroseconds test still asserts only max(waits) > 0, which can pass from ordinary non-contended tryBorrowObject overhead or sequential thread scheduling. It does not prove one query waited behind another while the single pool slot was held. Add synchronization so the second query starts after the first has borrowed the slot, then assert the wait is a meaningful fraction of the 0.5 second sleep.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Close the DIR * exception leak in walkSubtree.
  2. Fail closed for CPU attribution when the pre-snapshot readStat baseline is incomplete.
  3. Fix or explicitly accept the remaining silent MAX_PIDS truncation case.
  4. Strengthen the PoolWaitMicroseconds contention test.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 15, 2026
XuJia0210 and others added 2 commits May 18, 2026 09:36
Match the convention already used by the top-level `UserTimeMicroseconds`
and `SystemTimeMicroseconds` events, replacing the awkward
`CPU{User,System}Microseconds` naming. Propagates the rename through the
pool sampler call sites and the integration test.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Clarify that the memory byte-seconds counter is computed from per-process
peak memory (max `VmHWM` across the subtree) integrated over wall time,
not from an integrated memory sample. Rename the event to
`ExecutableUserDefinedFunctionPeakMemoryByteSeconds` and propagate the
rename through the pool sampler call sites and the integration test.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
XuJia0210 and others added 3 commits May 18, 2026 09:43
Rename the sampler's CPU/memory getters and backing fields to match the
ProfileEvent names introduced in the preceding two commits:
`getCPUUserMicroseconds` → `getUserTimeMicroseconds`,
`getCPUSystemMicroseconds` → `getSystemTimeMicroseconds`, and
`getMemoryUsageByteSeconds` → `getPeakMemoryByteSeconds` (plus the
corresponding `_us` / `_byte_seconds` fields and one comment). Update
the helper-script docstrings that referenced the old names.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
`readStat` and `readPeakRss` are `noexcept` and the `std::ifstream` /
`std::istringstream` parsing they do reports failures via stream state,
not exceptions. The surrounding `try { ... } catch (...) { return false; }`
arms were unreachable — drop them.

Header doc had two stale references that confused reviewers:
- a lifecycle entry for `recordExecuteImplStart` which never existed
  (the constructor implicitly starts the wall clock for pool wait);
- a "Free helpers exposed for unit testing" rationale on the `UDFProcfs`
  namespace, even though no unit test ships with this stack yet.
…executeImpl`

C++ destroys local objects in reverse declaration order, so `pipe` /
`pipeline` / `executor` — declared after the `SCOPE_EXIT` that flushes
the resource counters — destruct first; `~ShellCommandSource` runs
`recordReleased` on the sampler during that destruction, and by the
time the `SCOPE_EXIT` guard fires the sampler holds the final counters.

The earlier inner `{ ... }` made this dependency structurally explicit
but reindented every line of the existing pipeline boilerplate, showing
up as diff noise that obscured the real change. Drop the inner scope
and document the stack-order guarantee in the comment above
`SCOPE_EXIT` instead. Smoke test still reports all eight events
populated on a 500k-row workload.
When this stack still wrapped the pipeline in an inner scope,
`result_column` had to be hoisted ahead of the inner block so it
outlived the scope and could be returned. The inner scope was dropped
in the previous commit, so the hoist is no longer load-bearing; move
the declaration back next to its first use, where master had it.
Comment thread src/Common/ProfileEvents.cpp Resolved
XuJia0210 added 5 commits May 18, 2026 17:48
Bot review: ClickHouse#105010 (comment)

`~ShellCommandSource::cleanup` nulled `command` (which terminates the
worker process) before calling `sampler->recordReleased`, so any
exception path lost CPU and `PeakMemoryByteSeconds` to a now-gone
`/proc/<pid>`. Move the sampler call ahead of the worker tear-down so
the resident set and CPU counters are observed before either the worker
dies or the slot is returned to the pool.
Bot reviews:
- ClickHouse#105010 (comment) (re-checked: r3255919213)
- ClickHouse#105010 (comment)

`recordBorrowAcquired` ran after `buildCommand`, so on a cold borrow the
child-spawn time leaked into `PoolWaitMicroseconds` — contradicting the
event description. And when `tryBorrowObject` timed out, `createPipe`
threw before the sampler was notified, so the factory's `SCOPE_EXIT`
saw `borrowAcquired == false` and skipped every increment, losing the
pool wait that did happen.

Split the sampler API into two phases:
- `recordPoolWaitDone` freezes `pool_wait_us` and restarts the borrow
  clock. Called immediately after `tryBorrowObject` returns, on both
  the success and the timeout-failure paths.
- `recordPidAcquired` assigns `root_pid`, takes the pre-snapshot, and
  flags `borrow_acquired = true`. Called after `buildCommand` on the
  success path only.

The factory's `SCOPE_EXIT` now flushes in two stages: gate
`PoolWaitMicroseconds` on `poolWaitDone` (fires even on timeout), gate
the remaining six counters on `borrowAcquired`.

Outcome:
- timeout failure: only `PoolWaitMicroseconds` fires;
- cold borrow: `buildCommand` time falls into `ElapsedMicroseconds`;
- successful borrow: all 8 events fire as before.
Bot review: ClickHouse#105010 (comment)

The integration test exercised `UserTimeMicroseconds` via the existing
CPU spin UDF but never asserted
`ExecutableUserDefinedFunctionSystemTimeMicroseconds`. Add a
syscall-heavy UDF, `test_pool_udf_syscall`, that issues many zero-byte
`write(2)` calls per row to accumulate kernel-mode CPU above the 10 ms
clock-tick granularity. Zero-byte writes still cost a real syscall but
emit no bytes, so the TabSeparated UInt64 row written at the end of
the loop stays well-formed.

Add `test_system_time_microseconds`, which runs the new UDF across a
64-row block and asserts `SystemTimeMicroseconds > 0`.
CI: Style check `cpp` sub-check on
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105010&sha=e00518c21c51b44f3ac7342f327d621de8374f6c&name_0=PR&name_1=Style%20check

The `check_cpp.sh` cpp gate forbids `std::stringstream` (prefer
`ReadBufferFromString` / `WriteBufferFromOwnString`) and refuses
unassigned `::close(fd)` calls (the return value must at least be
bound to a variable).

- Switch the two `std::istringstream` parsers in `readStat` and
  `readPeakRss` to `ReadBufferFromString` plus
  `skipWhitespaceIfAny` / `skipStringUntilWhitespace` /
  `tryReadIntText` from `IO/ReadHelpers.h`.
- Bind `::close(fd)` in `clearRefs` to a `[[maybe_unused]]` int,
  matching the pattern used by `WriteBufferFromFile` and
  `KeeperStateMachine`.
- Drop the now-unused `<sstream>` include.
CI: Build (arm_tidy) on
https://s3.amazonaws.com/clickhouse-test-reports/PRs/105010/e00518c21c51b44f3ac7342f327d621de8374f6c/build_arm_tidy/build_clickhouse/build_clickhouse.log

Three `-warnings-as-errors` reported on
`src/Common/UDFProcessSubtreeSampler.cpp`:

- `google-runtime-int` on `long t = ::sysconf(_SC_CLK_TCK)`: switch
  to `Int64`, which is the fixed-width type the project already uses.
- `concurrency-mt-unsafe` on `::readdir(dir)` inside `walkSubtree`:
  the `DIR *` is a local allocated and destroyed inside one stack
  frame and never shared across threads, so the warning is a false
  positive. Apply `NOLINTNEXTLINE(concurrency-mt-unsafe)` with a
  justification comment.
- `modernize-use-starts-ends-with` on
  `line.compare(0, 6, "VmHWM:") != 0`: replace with
  `!line.starts_with("VmHWM:")`.
@XuJia0210
XuJia0210 marked this pull request as ready for review May 19, 2026 08:58
@vdimir vdimir self-assigned this May 19, 2026
The five integration-test shards on PR ClickHouse#105010 head b10b87b
(arm_binary distributed plan 2/4, amd_tsan 4/6, amd_asan_ubsan db
disk old analyzer 4/6, amd_llvm_coverage 5/5, amd_asan_ubsan flaky)
all reported the same six failures in
`test_executable_pool_udf_profile_events`: `test_invocations`,
`test_cpu_user_microseconds`, `test_system_time_microseconds`,
`test_memory_usage_byte_seconds`, `test_input_bytes`,
`test_output_bytes` — every assertion saw `got 0`.

Local repro showed that
`SELECT count() FROM (SELECT udf(number) FROM numbers(N))` is rewritten
by the optimizer to `SELECT count() FROM numbers(N)` because the outer
`count` does not reference the UDF column, so the UDF never runs and
no `ProfileEvents` fire. The two tests that passed in CI
(`test_elapsed_microseconds`, `test_pool_wait_microseconds`) already
invoked the UDF at the top level, which is why they were unaffected.

Switch the six failing tests to
`SELECT sum(udf(number)) FROM numbers(N)`. `sum` keeps the UDF column
live and forces evaluation; the row counts and per-row sizes are
unchanged, so the existing thresholds still hold.
@clickhouse-gh

clickhouse-gh Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

AI Review

Summary

This PR wires ExecutableUserDefinedFunction* ProfileEvents for the executable_pool UDF path (including the new PoolWaitMicroseconds) and adds integration coverage for pool UDF counters. The main remaining contract issue is that event descriptions claim coverage for both executable and executable_pool, while the current increments are still only on the pool path, so the user-visible metric contract is overstated.

Findings

⚠️ Majors

  • [src/Common/ProfileEvents.cpp:1351] The descriptions for ExecutableUserDefinedFunctionInvocations, ExecutableUserDefinedFunctionElapsedMicroseconds, ExecutableUserDefinedFunction{User,System}TimeMicroseconds, ExecutableUserDefinedFunctionPeakMemoryByteSeconds, ExecutableUserDefinedFunctionInputBytes, and ExecutableUserDefinedFunctionOutputBytes say "executable and executable_pool", but the current wiring in UserDefinedExecutableFunctionFactory::executeImpl increments them only when coordinator_configuration.is_executable_pool is true. This violates the published metric contract for plain executable UDFs.
    Suggested fix: either scope the descriptions to executable_pool for now, or add the corresponding executable instrumentation in the same change.
Final Verdict

Status: ⚠️ Request changes
Minimum required actions:

  1. Align the public ProfileEvents contract with actual behavior by either updating descriptions to executable_pool-only wording or implementing the missing executable-path increments.

Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
@andreev-io

Copy link
Copy Markdown
Member

@groeneai Can you review this PR?

@groeneai

Copy link
Copy Markdown
Collaborator

@andreev-io thanks for the ping. I went through the code and the procfs semantics. Here are answers to your two inline comments plus a few other things I noticed.

1. UDFProcessSubtreeSampler.cpp ~line 256, "kernel's lifetime peak"

You are right to push on this. The wording is imprecise.

clear_refs mode 5 (CLEAR_REFS_MM_HIWATER_RSS, since Linux 4.0) does not zero VmHWM. It snaps the high-water mark to the process's current RSS:

// fs/proc/task_mmu.c
if (type == CLEAR_REFS_MM_HIWATER_RSS) {
    // Writing 5 to /proc/pid/clear_refs resets the peak
    // resident set size to this mm's current rss value.
    reset_mm_hiwater_rss(mm);
    ...
}

// include/linux/mm.h
static inline void reset_mm_hiwater_rss(struct mm_struct *mm)
{
    mm->hiwater_rss = get_mm_rss(mm);
}

So when clearRefs fails (open returns -1, or the write itself fails: typical on procfs hidepid, on uid mismatches between server and worker, on the race where the worker died), VmHWM is unchanged. What you read back at release depends on the borrow history:

  • Brand-new pool worker, first borrow: VmHWM = peak RSS since process start. That happens to equal "lifetime peak", so the current comment is true.
  • Long-lived pool worker, clearRefs succeeded on a previous borrow: VmHWM = peak RSS since that previous successful clear. Not lifetime peak.
  • Long-lived worker, clearRefs has never succeeded: VmHWM = peak since process start, again lifetime peak.

The "over-counts slightly" framing also understates the bad case. If a previous borrow hit a 4 GiB peak and clearRefs has been failing every borrow since, a 100 MiB borrow will report ~4 GiB. The inflation is bounded by the worst peak across all prior un-cleared borrows, which can be arbitrarily large depending on workload, not "slight".

Concrete suggestion for the block:

/// Pre-snapshot: walk subtree, reset VmHWM per pid via clear_refs(5), and
/// capture utime/stime baselines. clear_refs(5) does not touch utime/stime,
/// only VmHWM, so the order of the two reads is fine.
///
/// clearRefs failure is silent. When it fails, VmHWM is left at whatever it
/// was on entry: the peak RSS since process start (if no successful clear
/// has ever run) or since the most recent successful clear_refs(5). The
/// borrow-attributed peak is then an upper bound, but the over-count is
/// bounded by the worst peak across all prior borrows since the last
/// successful clear, which can be arbitrarily large depending on workload.

Optional follow-up: a log-once on first clearRefs failure per pool worker would let operators distinguish trustworthy samples from inflated ones. Out of scope for this PR.

2. UDFProcessSubtreeSampler.cpp ~line 50, "execute.sh -> nsjail -> python"

Agreed, that example leaks a private-side topology that does not exist in OSS. The MAX_PIDS guard is independent of any sandbox, so keep the guard, drop the example.

The same concern repeats at ~line 309 in recordReleased:

/// because pids run mostly serially inside one borrow (nsjail+exec
/// chain) so peak resident set per pid is a better estimate than a sum.

Suggested replacements:

/// UDF process subtrees are shallow in practice (typically a launcher shell
/// or runtime wrapper plus the interpreter), but MAX_PIDS guards against
/// pathological /proc states.
/// For peak memory we take the max VmHWM observed across the subtree:
/// processes in a UDF subtree typically run serially in an exec chain, so
/// peak resident set per pid is a better estimate than a sum, which would
/// double-count the launcher and the interpreter.

3. ProfileEvent description vs. wiring contract

The AI Review bot flagged this and it is real. The event descriptions in ProfileEvents.cpp (introduced in #104998) say "executable and executable pool", but the increments in UserDefinedExecutableFunctionFactory::executeImpl only fire inside the if (coordinator_configuration.is_executable_pool) branch.

Two paths forward:

a. Tighten the descriptions to executable_pool-only wording in this PR. Minimal, lets it ship.

b. Also instrument the non-pool executable path here. Doable but more invasive: that path uses the same ShellCommandSource machinery without the borrow boundary, so you would skip recordPoolWaitDone and call recordPidAcquired right after ShellCommand::execute() returns the pid.

I would do (a) in this PR and track (b) as a follow-up. The descriptions are part of the documented metric contract for system.events, and a future rewording costs more than getting the labels right now.

4. Minor

  • peak_memory_byte_seconds = peak_rss * elapsed_us / 1000000ULL: the comment's overflow boundary (~1.8e13 byte-seconds) is accurate. Fine.
  • Atomic input_bytes/output_bytes with memory_order_relaxed: safe because recordReleased runs after send_data_threads are joined in cleanup(). Fine.
  • readStat skips 11 tokens to land on utime. The procfs field layout (man 5 proc, /proc/[pid]/stat) has been stable since 2.6, but a one-line comment citing the man page would help future readers.
  • walkSubtree uses std::find over a vector for dedup, O(N^2) with N capped at MAX_PIDS = 1024. Fine.

Verdict

The design is sound. The sampler is scoped per borrow, lifecycle hooks are placed correctly (recordPoolWaitDone before the timeout check, recordPidAcquired right after buildCommand, recordReleased before the worker is returned or torn down), the SCOPE_EXIT in the factory drains on both success and exception paths, and the integration test covers each ProfileEvent independently.

My recommendation is to block on:

  1. The two comment rewrites above (kernel-peak semantics and OSS-relevance).
  2. Aligning the ProfileEvents.cpp descriptions with what the code actually populates (either narrow to executable_pool or instrument both paths).

Everything else is a nit or a follow-up. Once those land I would be happy to re-review.

Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
Comment thread src/Common/UDFProcessSubtreeSampler.cpp Resolved
`UDFProcfs::walkSubtree` silently broke out of the inner read loop
once the running descendant count reached `MAX_PIDS=1024`. For a UDF
that genuinely spawns more than 1024 descendants the sampler then
reported a strict under-count of CPU and `PeakMemoryByteSeconds` with
no operator-visible signal.

Add a `truncated` out-parameter to `walkSubtree`. The size check now
runs BEFORE `push_back`, so `truncated` is set precisely when a
unique pid candidate is seen with the result already at the cap — a
borrow whose subtree fills to exactly 1024 without further candidates
is left untouched. The sampler ORs the result of both walks (pre and
post) into a new `subtree_truncated_any` bit, surfaced via the new
`subtreeWalkTruncated()` accessor.

The factory's `SCOPE_EXIT` picks the new bit up alongside the three
procfs-failure bits and raises a single `LOG_WARNING` the first time
the cap is reached for a given UDF, reusing the per-UDF flag map
introduced in commit 82712a1.

Addresses ClickHouse#105010 (comment)
@XuJia0210 XuJia0210 added the can be tested Allows running workflows for external contributors label Jun 2, 2026
XuJia0210 added 3 commits June 2, 2026 12:12
The existing five reaping-scenario tests assert only on
`UserTimeMicroseconds`, and `test_memory_usage_byte_seconds` drives a
single-pid UDF, so the cross-pid `peak_rss = std::max(peak_rss,
hwm_bytes)` line in `recordReleased` had no coverage that could
distinguish `max` aggregation from `sum`.

Add `pool_udf_multi_mem.py`: spawns three helper subprocesses at
script startup, each allocates and touches a ~50 MiB `bytearray` and
sleeps indefinitely (`daemon=True` keeps them tied to the parent's
lifetime in the pool slot). A `multiprocessing.Event` barrier blocks
the parent until every helper has finished touching its allocation,
so all three are guaranteed to be at peak RSS by the time the borrow
starts. Memory has no `cutime`/`cstime` analogue, so the helpers MUST
be alive when `recordReleased` runs the post-walk; an indefinite
sleep handles that.

`test_peak_rss_max_across_live_descendants` runs ten rows and inverts
the encoding `byte_seconds = peak_bytes × elapsed_us / 1e6` to recover
the effective `peak_rss`. With `max` the derived peak lands around
the per-helper RSS (~60 MiB, parent footprint inherited at fork plus
the 50 MiB allocation); with `sum` it would land near ~180 MiB. The
assertion `40 MiB ≤ derived_peak ≤ 100 MiB` falsifies `sum`
aggregation while leaving room for normal helper-RSS variance.

Verified locally:

  pytest test_executable_pool_udf_profile_events/test.py::\
    test_peak_rss_max_across_live_descendants
  ============================== 1 passed in 21.88s ==============================
`recordPidAcquired` is called in `ShellCommandSourceCoordinator::createPipe`
right after `process_holder->buildCommand()` returns. At that point
`process_holder` is still a local `unique_ptr<ShellCommandHolder>`;
ownership is not handed off to `ShellCommandSource` until further down.

`recordPidAcquired` is not `noexcept` — it constructs the `vector<pid_t>`
returned by `UDFProcfs::walkSubtree` and does `unordered_set::insert` /
`unordered_map::operator[]` writes, all of which can throw `bad_alloc`.
If it threw here, stack unwinding would destroy the local
`process_holder` without ever calling `process_pool->returnObject`, so
`BorrowedObjectPool::borrowed_objects_size` would keep climbing. After
`pool_size` borrows the UDF's pool would be effectively at zero
capacity and the next `tryBorrowObject` would deadlock on the timeout.

Mirror the try/catch pattern from commit 7368078 (the post-side
`recordReleased` guard in `ShellCommandSource::cleanup`): wrap the
`recordPidAcquired` call, swallow any exception, and `tryLogCurrentException`
under the `ShellCommandSource` tag. Sampling is best-effort — losing
one pre baseline drops the borrow's CPU/memory delta but keeps the
worker hand-off, the borrow lifecycle, and the pool slot intact.

`Common/Exception.h` is already included from commit 7368078.

Addresses ClickHouse#105010 (comment)
Two unrelated lint failures on CI:

1. **Style check `cpp`**: `check_cpp.sh`'s no-bare-std-container rule
   was broadened upstream to cover `src/Functions`, which now catches
   `static std::unordered_map<String, std::unique_ptr<...>> flags_by_udf;`
   in the per-UDF warning-flag map introduced by commit 82712a1.
   The map is process-level state (lives for the server's lifetime,
   keyed by UDF name, not query memory), so the `*WithMemoryTracking`
   alternatives do not actually apply. Mark the line with a trailing
   `// STYLE_CHECK_ALLOW_STD_CONTAINERS` and add a short comment
   explaining why memory tracking is the wrong tool here.

2. **Build (arm_tidy) `cppcoreguidelines-init-variables` (WERROR)**:
   the `struct dirent *entry` in `UDFProcfs::walkSubtree` was
   declared uninitialised. Initialise to `nullptr`. The value is
   overwritten on every loop iteration so this is a tidy-satisfaction
   fix, not a behavioural one.

Verified locally that the std-container regex from master's
`check_cpp.sh` no longer hits my line after the suppression comment;
the three remaining `std::vector` hits on lines 374 / 456 / 461 are
pre-existing and were not flagged on CI.
@XuJia0210

Copy link
Copy Markdown
Contributor Author

@andreev-io All five deltas are in, plus the MAX_PIDS warning, the pre-snapshot exception guard, and child-reaping tests. PTAL.

_profile_event_value(qid, "ExecutableUserDefinedFunctionPoolWaitMicroseconds")
for qid in qids
]
assert max(waits) > 0, f"Expected PoolWait > 0 on at least one query, got {waits}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

PoolWaitMicroseconds is supposed to prove real pool contention here, but > 0 does not distinguish that from normal non-contended tryBorrowObject call overhead.

With this assertion the test would still pass if both queries ran sequentially, or if the code recorded only a few microseconds around an immediate borrow. Please assert that one query waited for a meaningful fraction of the 0.5 second sleep, after synchronizing the two runners so the second borrow starts while the first holds the only slot.

@andreev-io andreev-io 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. Please test it.

…e-walk completes

`UDFProcfs::clearRefs`, `readStat`, and `readPeakRss` allocate
internally — the `/proc/<pid>/...` path strings, the `std::ifstream`
line buffer, `std::string::substr` over the parsed line — and they
were declared `noexcept`. A memory-limit `exception` raised by any
of those allocations would have hit `std::terminate` at the
`noexcept` boundary, because the existing internal try/catch on the
sampler call sites (commit 7368078, mirrored by commit 6e65ace)
sits at the call site in `ShellCommandSource`, not inside the
helpers themselves.

Drop `noexcept` from the three declarations and definitions. The
`return false` channel still covers expected procfs failures —
`open` or `stat` failing because the pid vanished or seccomp denied
the read, malformed contents — but a `bad_alloc` now propagates
instead of being silently mapped onto `false`. Both callers
(`recordPidAcquired` in this file, `recordReleased` via the
`ShellCommandSource::cleanup` guard) already swallow exceptions via
`tryLogCurrentException("ShellCommandSource")`, so the exception is
logged and sampling is skipped for that borrow rather than masquerading
as "metric unavailable". This matches the repo's avoid-fallback
guidance from `.claude/CLAUDE.md`.

Move `borrow_acquired = true` in `recordPidAcquired` to after the
pre-walk loop. If `walkSubtree`, `clearRefs`, or `readStat` throws
mid-iteration the function exits with `borrow_acquired == false`,
so `recordReleased`'s `if (!borrow_acquired) return;` short-circuit
keeps the partially-built `pre_snapshot` out of the post-walk delta
— a borrow only contributes its resource counters if its
pre-snapshot was fully built.

Update the `UDFProcfs` namespace doc to spell out the expected-vs-
unexpected failure split.

Verified locally:

  python -m ci.praktika run "integration" \
    --test "test_executable_pool_udf_profile_events"
  ============================= 14 passed in 34.36s ==============================
const pid_t pid = result[i];
const std::string task_dir = "/proc/" + std::to_string(pid) + "/task";

DIR * dir = ::opendir(task_dir.c_str());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

walkSubtree is meant to tolerate allocation exceptions from the sampler, but this raw DIR * leaks if anything throws before line 105 calls closedir.

A concrete path is: opendir succeeds, then children_path construction or result.push_back throws while the caller catches the exception and lets the query continue. That turns best-effort metrics into a per-failure fd leak. Please wrap the handle immediately, e.g. std::unique_ptr<DIR, decltype(&::closedir)> dir(::opendir(...), &::closedir), and use dir.get() for readdir.

if (UDFProcfs::readStat(pid, utime_us, stime_us))
pre_snapshot[pid] = PreSnapshot{utime_us, stime_us};
else
read_stat_failed_any = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

readStat failing during the pre-snapshot should invalidate CPU attribution for this borrow, not just set the warning bit.

Concrete race: the pre-walk sees a helper pid from a previous borrow, readStat(helper) returns false because the helper exits before this line, and the parent reaps it during the current borrow. The post-walk no longer sees the helper, but the parent's cutime/cstime now include the helper's lifetime CPU, while pre_utime_sum/pre_stime_sum have no helper baseline to subtract. That charges the helper's pre-borrow CPU to this query.

Please fail closed for UserTimeMicroseconds/SystemTimeMicroseconds when any pre-snapshot readStat fails, for example by marking the CPU baseline invalid and skipping CPU increments for the borrow.

@clickhouse-gh

clickhouse-gh Bot commented Jun 3, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 92.40% 92.40% +0.00%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 98/325 (30.15%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@vdimir
vdimir added this pull request to the merge queue Jun 4, 2026
Merged via the queue into ClickHouse:master with commit bcac3d7 Jun 4, 2026
166 checks passed
@robot-ch-test-poll1 robot-ch-test-poll1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 4, 2026
andreev-io added a commit to andreev-io/ClickHouse that referenced this pull request Jun 4, 2026
…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.
andreev-io added a commit to andreev-io/ClickHouse that referenced this pull request Jun 4, 2026
…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.
Maoyao233 pushed a commit to Maoyao233/ClickHouse that referenced this pull request Jun 8, 2026
`test_hedged_requests/test.py::test_stuck_replica` is chronically flaky
on heavily overcommitted ASan/UBSan integration shards. The failure shape
in CIDB is identical across 9 unrelated PRs in the past 30 days:

    pause_container('node_1') did not become observably effective within
    90.0s ... still succeed after ~890 probe iterations; last outcome:
    server replied (4 bytes)

The probe in `_wait_for_pause_effective` keeps receiving live ClickHouse
exception packets from `node_1` for the entire 90s budget, which proves
that `docker compose pause` returned success while the cgroup freezer
never actually froze the user-space tasks. The existing SIGSTOP fallback
in `ClickHouseCluster.pause_container` only fires when `docker compose
pause` raises an exception, not when it lies about success, so the
escalation path was never taken.

Switch this test to `cluster.pause_container_using_signal`, which uses
`SIGSTOP`/`SIGCONT` from the start. A signal cannot be silently lost the
way the cgroup freezer can, so the pause becomes observable on the very
first probe iteration. Same helper is already used by
`test_postgresql_replica_database_engine` for the same reason.

The change is local to one call site. The chronic flake hit
`Integration tests (amd_asan_ubsan, db disk, old analyzer, 1/6)` in the
following PRs (CIDB, last 30 days): ClickHouse#103404, ClickHouse#106311, ClickHouse#105010, ClickHouse#105056,
ClickHouse#104830, ClickHouse#106025, ClickHouse#100391, ClickHouse#106571, ClickHouse#103229. All show the same
`server replied (4 bytes)` outcome, distinguishing this from generic
flakiness.

Related: ClickHouse#106571
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-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.

6 participants