Repository navigation
Add asynchronous metrics for executable UDF memory usage - #107300
Conversation
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.
|
Workflow [PR], commit [297af55] Summary: ✅
AI ReviewSummaryThis PR adds instance-wide asynchronous metrics for Final VerdictStatus: ✅ Approve |
The suite verified return-to-baseline only after a successful query (reap path) or an externally killed pool worker. This covers the failure path: the script allocates ~128 MiB and hangs, `command_read_timeout` fails the query, and the error-path teardown must SIGTERM the stuck process and release its registry entry, returning both metrics to baseline. A leaked wrapper on the error path would keep the gauge stuck high; no other test would catch that.
- Remove the per-root registry membership re-check from `UDFProcessRegistry::sample`: it only narrowed an already negligible pid-reuse window (a full pid-space wraparound within a sub-millisecond span, self-correcting on the next sweep) at the cost of extra locking every reader had to reason about. The global dedup across subtrees stays. - Fix two comments: `sampleExecutablePeak` is also a try/catch caller of `UDFProcfs`; the registry tracks pids rather than live processes (a killed pool worker stays registered as an unreaped zombie until its wrapper is destroyed, and is excluded from the metrics by having no VmRSS line). - Harden `test_timed_out_executable_is_killed_and_leaves_metrics`: widen the observation window to 25 s for slow sanitizer runners, check both metric deltas in one predicate so a separate count snapshot cannot land after the timeout kill, and assert the query thread finished.
Address review comments: - Remove the registry entry in `tryWaitProcessWithTimeout` only when `waitForPid` actually reaped the child. An unreaped child keeps its pid un-reusable (alive, then zombie), so the retained entry can never alias another process, and a process that outlives `command_termination_timeout` or ignores SIGTERM stays counted instead of vanishing from the metrics while it still holds memory. Once it dies, the zombie has no VmRSS line and drops out of both metrics; the stale set entry costs tens of bytes alongside the pre-existing leaked zombie. ClickHouse#107300 (comment) - Wait in the test fixture until the metrics are published before any test takes numeric baselines. ClickHouse#107300 (comment)
| bool process_terminated_normally = waitForPid(pid, timeout_in_seconds); | ||
|
|
||
| if (process_terminated_normally && config.register_in_udf_process_registry) | ||
| UDFProcessRegistry::instance().remove(pid); |
- Remove the cross-subtree dedup from `UDFProcessRegistry::sample`: registered roots are direct children of this server, so their subtrees are disjoint, and `walkSubtree` already dedups within one subtree. - Tests: restart the server at the top of every pool test, making the suite order- and repeat-independent; fork two generations in the descendant test so the ballast lives in the grandchild and the assertion pins recursive subtree walking; add a two-UDF test asserting the gauge reports the sum of both workers; assert memory deltas as bands of `BALLAST +/- TOLERANCE` (25 MiB, ~3x the measured 7-9 MiB interpreter overhead) instead of one-sided thresholds, and process count deltas as exact equalities, so overcounting fails the suite as loudly as undercounting.
The registry entry is removed only when the child is reaped; a child that survives the bounded wait in `tryWaitProcessWithTimeout` stays registered (alive, then a zero-RSS zombie that contributes nothing to the metrics). The class doc and the `ShellCommand::Config` flag comment still claimed removal at wrapper destruction. ClickHouse#107300 (comment)
- Wrap the registry sweep and metric emission in try/catch: an allocation failure under memory pressure now costs only the two UDF metrics for that cycle instead of discarding the whole asynchronous metrics snapshot. Memory pressure is exactly when these metrics are read, so blanking every metric for the cycle was the worst failure mode. - Pin `asynchronous_metrics_update_period_s` to 1 in the test config: the suite's polling windows are calibrated to a 1 second sweep and previously relied on the server default. - Fix the `sample` comment: on non-Linux the metrics are absent, not 0 (the call site gates emission).
|
|
||
| The number of uncorrectable ECC memory errors. A non-zero number of this value indicates bad RAM which has to be immediately replaced, because it indicates potential data corruption. Source: `/sys/devices/system/edac/mc/` | ||
|
|
||
| ### ExecutableUserDefinedFunctionMemoryResident {#executableuserdefinedfunctionmemoryresident} |
There was a problem hiding this comment.
I'm not a fan of the name. What is "memory resident" (compare this with "memory resident size")? What are the units? Maybe ExecutableUserDefinedFunctionVmRSSBytes?
There was a problem hiding this comment.
For regular MemoryResident bytes suffix is also missing, so for me either works
There was a problem hiding this comment.
Added the Bytes suffix. I kept the MemoryResident because it parallels the server's async memory metrics using VmRSS
Lmk if we still prefer to change MemoryResident into VmRSS
| /// When true, the child pid is tracked in the global `UDFProcessRegistry` | ||
| /// from spawn until the child is reaped. Set for both executable and | ||
| /// executable_pool UDFs. | ||
| bool register_in_udf_process_registry = false; |
There was a problem hiding this comment.
ShellCommand is not UDF-specific, right? So what does this do for non-UDF callers? As per comment, a non-UDF process would also be tracked?
There was a problem hiding this comment.
Right, ShellCommand is not UDF-specific. Non-UDF callers will have register_in_udf_process_registry to false, so the pid is not tracked. register_in_udf_process_registry is only set to true if is_user_defined_function = true here. Updated comments to be more clear.
| if (pid <= 0) | ||
| return; | ||
|
|
||
| std::lock_guard lock(mutex); |
There was a problem hiding this comment.
There's no need to unlock? Does it unlock itself at the end of scope?
There was a problem hiding this comment.
Right. It acquires the mutex in its constructor and releases it in its destructor, when it's out of scope
| * | ||
| * `ShellCommand` adds the pid at spawn and removes it when the child is | ||
| * reaped, so idle pool workers stay registered for as long as they live. | ||
| * A never-reaped child stays registered: its pid stays pinned, and a zombie |
There was a problem hiding this comment.
I'm not sure I understand why how a zombie, if it's registered, is not contributing to the metrics?
There was a problem hiding this comment.
@andreev-io @vdimir Yeah this is guaranteed by the procfs implementation, although I couldn't find an official documentation. Also did some experiments to validate it.
Procfs only emits the Vm lines in /proc/<pid>/status when mm != NULL, mm is set to NULL when the task is terminating. And our implementation guarantees that if the Vm line is missing, we don't attribute the pid to the metrics.
I added some comments in commit
|
|
||
|
|
||
| def _wait_for(predicate, timeout=30, interval=0.5): | ||
| """Poll until predicate() is truthy; async metrics update once per second, |
There was a problem hiding this comment.
async metrics update once per second
Is this strictly true?
There was a problem hiding this comment.
It is defined via asynchronous_metrics_update_period_s, with a default of 1s. The test config pins it to 1s with <asynchronous_metrics_update_period_s>1</asynchronous_metrics_update_period_s>
…to hanzi/udf-memory-async-metrics
The flag is assigned in `ShellCommandSource` from `is_user_defined_function`, not directly by the executable-UDF loader. State only that it is enabled for executable and executable_pool UDFs.
Two reviewers asked why a registered-but-zombie child contributes to neither `ExecutableUserDefinedFunctionMemoryResidentBytes` nor `ExecutableUserDefinedFunctionProcesses`. State the mechanism in the `UDFProcessRegistry` comment: a zombie has released its address space, so `/proc/<pid>/status` has no `VmRSS` line and `sample` skips it.
|
@groeneai check out CI failures, if they all are known and fixed, merge master otherwise prepare fixes in separate PRs |
|
@vdimir Triaged both failures on the latest run (56a087f). Neither is caused by this PR (it only touches UDF async metrics / ShellCommand; both failures are unrelated code paths).
Recommendation: merge master into the branch and re-run. No code change is needed in this PR for either failure. |
|
@groeneai why do we see many 'Hung check failed' error in PRs? Should we find a root cause and fix? |
|
@vdimir Short answer: "Hung check failed" is not one bug. It is the Stress test's single catch-all: after the test suite finishes, if ANY query is still in the processlist after the 90s drain, the whole stress job is failed with this one generic name. So it is an umbrella over several independent server-hang signatures, surfaced heavily because Stress runs the server/AST fuzzer under sanitizers (5-10x slower), which exposes timing-sensitive hangs. Each PR's stress run trips one of them roughly once, at random, so it shows up on many unrelated PRs without being caused by any of them. Quantifying "many" (CIDB, last 30d, exact test names "Hung check failed..." + "Possible deadlock on shutdown..."):
Yes, it is being root-caused, per-signature (the generic name itself cannot be "fixed" as one thing). Known signatures and status:
Infra unblocker already merged: #103551 stopped the stress script from deleting hung_check.log and embeds its tail into CIDB test_context_raw, so every new hit now ships the stuck-thread stacks for per-signature triage. Recommendation: keep attacking it per-signature. Highest-leverage next step is landing #105905 to pin the shutdown-leak subsystem; the distributed-plan fixes above should already pull down the recent spike. For this PR specifically, the single hung-check hit is one of these chronic instances and is unrelated to the UDF async-metrics change, so it is safe to merge master and proceed. Happy to break any specific signature into its own fix PR if you want one prioritized. |
Stamp each registered pid with a generation so a stale reap cannot evict a successor that reused the pid, and prune zombie roots during sampling.
ccdb1a7 to
afb8a5c
Compare
@groeneai please check out this failures |
|
@vdimir Checked both. Neither is caused by this PR (diff touches only the executable-UDF async metrics path: 1. 2. Stress test (arm_debug) "Unknown error" - benign lost-connection, not a crash. Recommendation: both are flaky/benign and unrelated to the PR. Just re-run the two jobs; no code change needed here. |
@groeneai we still need to figure out how to fix it separately |
|
@vdimir Will pursue separately. Key point: 30d CIDB: 3 hits / 3 unrelated PRs, 0 on master, ~3 in 90k runs, all with the identical signature: after The Stress (arm_debug) "Unknown error" was a single benign lost-connection (no crash signature anywhere in the full log, 1 occurrence in 30d, 0 master); nothing to fix there beyond a re-run unless it recurs. |
|
@vdimir Root-caused it, and it turned out bigger than a flaky test: Deterministic repro (any column type, any part type): -- table with a few unmerged parts that contain column d, then:
OPTIMIZE TABLE t FINAL SETTINGS mutations_sync=0; -- async, in background pool
ALTER TABLE t RENAME COLUMN d TO d1 SETTINGS mutations_sync=1; -- concurrently
-- ~15-30% of races: d1 reads back entirely empty/None. Data is gone.Confirmed on v2 and v3, packed/compact/wide, String and Dynamic. Control: Mechanism: the merge captures So the metadata snapshot (selection time) and the mutations snapshot (execute time) are captured inconsistently and the rename falls into the gap. Fixing it cleanly means making the merge's mutation snapshot consistent with the parts/metadata version it selected (and likely mirroring to ReplicatedMergeTree). That is a core merge/mutation coordination change with real trade-offs, so before I open a PR: do you want the snapshot pinned at selection time, the metadata_snapshot pinned to the selected parts, or another approach? No GH issue exists yet; I can file one with this repro. |
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered by tests: 141/155 (90.97%) | Lost baseline coverage: none · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: This PR only adds two asynchronous metrics that track memory and process counts for executable user-defined functions; it touches the UDF process registry, the shell-command wrapper (behind a flag that is off for normal queries), and the periodic async-metrics sweep. None of these are on the query-execution path that ClickBench Q4, Q15, or Q28 exercise, and with no UDFs registered the new sampling does no work. The three flagged improvements (-19.6%, -12.5%, -5.7%) cannot plausibly come from this change, so they are downgraded as run-to-run variance rather than a real PR effect. clickbenchFlagged queries (3 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
@Algunenano Correct, and already handled. Those two subtests ( Fixed in #108275 (merged 2026-06-23 17:24 UTC): restart + wait for a clean 0/0 baseline before the snapshot, matching the 6 sibling subtests that already did this. 0 FAIL/ERROR in ~24.8k runs since merge (last failure was 06-23 09:06, before the merge). For the record, the other failure originally flagged on this PR, the Stateless |
Adds asynchronous metrics for executable and executable_pool UDFs:
ExecutableUserDefinedFunctionMemoryResidentBytesis the sum of VmRSS over all live executable and executable_pool UDF processes and their descendant processes, in bytes.ExecutableUserDefinedFunctionProcessesis the number of processes the sum was taken over.Live UDF pids are tracked in a new
UDFProcessRegistry.ShellCommandregisters each pid at spawn with a generation stamp and removes only its own entry at reap, so a stale reap can't evict a later process that reused the pid. Zombies have no VmRSS line, so they are not counted towards the metrics, and sampling prunes their registry entries.Summing
VmRSScounts shared pages once per process.PSSwas measured and rejected because its cost scales with resident memory.The metrics are instance-wide aggregates instead of per-function dynamic names because metric names built from user-defined identifiers have unbounded cardinality, as users can define arbitrarily many functions. Dynamic name suffixes are reserved for small bounded sets.
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added asynchronous metrics
ExecutableUserDefinedFunctionMemoryResidentBytesandExecutableUserDefinedFunctionProcesses, reporting the resident memory (VmRSS) and number of live processes ofexecutableandexecutable_pooluser-defined functions, including descendant processes and idle pool workers.Documentation entry for user-facing changes
Version info
26.6.1.1125