Repository navigation
Populate ProfileEvents for executable_pool UDFs - #105010
Conversation
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.
|
Workflow [PR], commit [9df4bc4] Summary: ✅
AI ReviewSummaryThis PR adds Findings
Tests
Final VerdictStatus:
|
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]>
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.
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:")`.
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.
AI ReviewSummaryThis PR wires Findings
Final VerdictStatus:
|
|
@groeneai Can you review this PR? |
|
@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.
|
`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)
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.
|
@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}" |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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()); |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 98/325 (30.15%) | Lost baseline coverage: none · Uncovered code |
…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.
`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
Stacks on top of #104998. Adds the eighth
ExecutableUserDefinedFunction*ProfileEvent (PoolWaitMicroseconds) and populates all eight on theexecutable_poolUDF path, so a query that calls a pool UDF shows up insystem.query_log.ProfileEventswith per-call invocation count, wall and pool-wait time, child-process CPU and peak memory, and stdin/stdout bytes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Populate the
ExecutableUserDefinedFunction*ProfileEventscounters forexecutable_poolUDFs. Per-call invocation count, wall and pool-wait time, child-process CPU and peak memory, and stdin/stdout bytes are now visible insystem.query_log.ProfileEvents.Documentation entry for user-facing changes
Version info
26.6.1.377