Skip to content

Fix huge OSIOWaitTime and other OS metric deltas when a kernel counter goes backwards - #134097

Open
groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/asyncmetrics-kernel-counter-backwards
Open

groeneai wants to merge 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/asyncmetrics-kernel-counter-backwards

Conversation

@groeneai

@groeneai groeneai commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #120906

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed asynchronous metrics such as OSIOWaitTime reporting a value around 1e16 for one sample when the kernel counter they are computed from decreased between two updates (the iowait field of /proc/stat can go backwards). Such a delta is now 0. This covers every /proc/stat, block device and network interface counter.

Description

On 26.10 and 26.3, when the iowait counter in /proc/stat steps backwards between two samples (proc(5): it may decrease), system.asynchronous_metrics reports OSIOWaitTime of about 2.4e16 for that sample (measured on 26.10.5.57 and 26.3.63.123 with a faked /proc/stat). Since #120906 enabled the UBSan check for unsigned overflow, the same subtraction aborts sanitizer builds:

src/Common/AsynchronousMetrics.cpp:854:25: runtime error: unsigned integer overflow: 9363 - 9364 cannot be represented in type 'uint64_t'

It kills servers and keepers at random in *_asan_ubsan integration jobs, e.g. master Integration tests (amd_asan_ubsan, db disk, 3/8) (test_convert_ordinary_to_atomic: all 3 keepers died).

The four operator- that compute kernel counter deltas (/proc/stat CPU and other lines, also used for cgroup cpu.stat; /sys/block/*/stat; /proc/net/dev) now use the existing safeDiff (ThreadProfileEvents.h), so a counter that went backwards contributes 0. The other deltas in the file (/proc/pressure/* totals, in-process profile events) are monotonic and unchanged.

Test: test_system_reload_async_metrics gets a case that bind-mounts a fake /proc/stat while the server starts, lowers iowait and ctxt, and runs SYSTEM RELOAD ASYNCHRONOUS METRICS. It fails on master (debug: OSIOWaitTime 2.6e16; asan_ubsan: the abort above) and passes with the fix (10/10 debug, 5/5 asan_ubsan). The block device and network operators get the same change but are not exercised by the test.


Workflow [PR]
Sync PR [sync-upstream/pr/134097]

…ronousMetrics

The `iowait` field of `/proc/stat` is not monotonic (proc(5): "This value
is not reliable ... may decrease"). `AsynchronousMetrics` computed every
delta of a kernel counter with a plain unsigned subtraction, so a counter
that stepped back wrapped to about 2^64: `system.asynchronous_metrics`
reported `OSIOWaitTime` of about 2.4e16 and `OSContextSwitches` of 1.8e19
for that sample (measured on 26.10.5.57 and 26.3.63.123), and since ClickHouse#120906
enabled `-fsanitize=unsigned-integer-overflow` the same subtraction aborts
`*_asan_ubsan` servers and keepers:

  AsynchronousMetrics.cpp:854:25: runtime error: unsigned integer overflow:
  9363 - 9364 cannot be represented in type 'uint64_t'

Use the existing `safeDiff` (ThreadProfileEvents.h) in all four kernel
counter `operator-`: `/proc/stat` CPU and other lines, `/sys/block/*/stat`
(32-bit tick fields wrap, a re-created device restarts its counters) and
`/proc/net/dev` (a re-created interface restarts its counters). A counter
that went backwards contributes 0 for that interval; the true delta is
unknown, and 0 never produces an impossible value. `in_flight_ios` is a
gauge and stays as is. The other deltas in the file (`/proc/pressure/*`
totals, in-process profile events) are monotonic.

The test bind-mounts a fake `/proc/stat` while the server starts (the file
is opened once and sampled synchronously in `start()`), detaches the mount,
lowers `iowait` and `ctxt`, and runs `SYSTEM RELOAD ASYNCHRONOUS METRICS`
(the module's update period is 60000 s). `OSProcessesBlocked` (a gauge read
from the fake file) proves the server reads it; `OSProcessesCreated` and
`OSUserTime` prove an advancing counter keeps its delta.

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

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 1 finding; bounded: 1 full pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ⚠️ The test does not exercise the block-device and network operator- (AsynchronousMetrics.cpp:914-946) DISAGREE Same one-token safeDiff(other.x, x) change as the two tested operators; the test pins the helper and its argument order both ways (backwards -> 0, advancing -> exact delta) and fails with inverted arguments or an unfixed ProcStatValuesOther. Faking them needs runner-specific rigs: /proc/net/dev is read through /proc/self and opened once in the constructor, /sys/block/* names differ per runner. The body says they are not exercised.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal per finding. Findings on hunks unchanged by the fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20261124-110201

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @pamarcos, could you review this? The four kernel-counter operator- in AsynchronousMetrics.cpp (/proc/stat CPU and other lines, block devices, network interfaces) now use the existing safeDiff, so a counter that steps backwards (iowait in /proc/stat) gives a 0 delta instead of wrapping to about 2^64; since #120906 that wrap aborts asan_ubsan servers and keepers in integration jobs.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes: test_system_reload_async_metrics/test.py::test_counter_going_backwards (fake /proc/stat, iowait 5000 -> 4000, one synchronous SYSTEM RELOAD ASYNCHRONOUS METRICS, update period 60000 s). Fails on every master run.
b Root cause explained? iowait in /proc/stat may decrease (proc(5)); the four kernel counter operator- in AsynchronousMetrics.cpp subtract unsigned values, so the delta wraps to about 2^64: a garbage metric on release builds, a UBSan abort since #120906.
c Fix matches root cause? Yes: the subtraction now clamps a backwards step to 0 with the existing safeDiff; no sanitizer annotation, the detector stays.
d Test intent preserved / new tests added? New case in the existing test_system_reload_async_metrics module; existing tests untouched.
e Both directions demonstrated? Master debug: OSIOWaitTime 2.6e16, OSContextSwitches 1.8e19, FAIL. Master asan_ubsan: AsynchronousMetrics.cpp:858:25: runtime error: unsigned integer overflow: 4000 - 5000, FAIL. Fix: 10/10 debug, 5/5 asan_ubsan with no sanitizer report. Mutants with inverted safeDiff arguments or an unfixed ProcStatValuesOther both fail the test.
f Fix is general across code paths? All four kernel counter delta operators (/proc/stat CPU and other lines, block devices, network interfaces). The /proc/pressure totals and the in-process profile event deltas are monotonic, unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Every field of the four structs; the per-CPU lines and the aggregate line share the operator. A counter that advances keeps its exact delta (OSUserTime, OSProcessesCreated checked).
h Backward compatible? (maintainer-approved exception only) Yes: no setting, format or protocol change; only the one-sample value of a decreased counter changes from about 2^64 to 0.
i Invariants and contracts preserved? operator- stays a pure function of two samples; the in_flight_ios gauge is untouched; the previous/current bookkeeping in update() is unchanged.

Session id: cron:clickhouse-impl-slot-7:20261124-094400

@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [78c21ab]

Summary: ✅


AI Review

Summary

Reviewed #134097 at 78c21ab45076. The change clamps decreasing kernel-counter deltas to zero in AsynchronousMetrics, preventing invalid OS metrics and unsigned-overflow sanitizer failures. The focused regression test covers decreasing counters and preserves checks for advancing counters. No actionable findings.

Missing context / blind spots
  • ⚠️ Builds are still running, and the published targeted integration report contains no test results yet. The author reports successful debug and ASan/UBSan regression runs; independent CI confirmation remains pending. No local tests were run in this CI review job.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default can be tested Allows running workflows for external contributors comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). labels Nov 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 78c21ab45 with master 0f38da1d6 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

7 translation units recompiled, 9 s compile time in total, 7 of them have a recent master baseline.

Job report

@Algunenano Algunenano self-assigned this Nov 24, 2026

@Algunenano Algunenano 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.

Not sure if we need a test like this, but it's all good. Let's merge and go on

@Algunenano
Algunenano enabled auto-merge November 24, 2026 13:08

This branch has not been deployed

No deployments
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 comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants