Repository navigation
Backfill missed periodic events in system.query_metric_log - #103547
alexey-milovidov merged 4 commits into
Conversation
When a scheduled `collectMetric` task fires after the query has already finished, `getQueryInfo` returns null and the periodic event is silently dropped — under TSan builds and in highly parallel CI runs the `BackgroundSchedulePool` can fall behind by enough that this happens repeatedly, leaving `system.query_metric_log` with fewer rows than the documented behavior promises and occasionally missing the "query finished" row entirely (when the last periodic shares the finish moment's timestamp the existing dedup guard drops the final). `QueryMetricLog::finishQuery` now backfills the missed periodic events using the `query_info` captured at finish (deltas remain monotonically correct via the existing `new_value < old_value` guard) and always emits the final event by passing a new `is_final=true` flag through to `createLogMetricElement`. The dedup guard remains in place for ordinary periodic events and only the final bypasses it. Adds a regression test exercising a 1.5 s query with a 100 ms interval that asserts both the row count and the cumulative profile counters. Closes the chronic flakiness of `03203_system_query_metric_log` on `Stateless tests (amd_tsan, parallel, 1/2)` (4 unrelated PRs + 1 master hit over 30 days). CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101111&sha=d1bb5ca2ccaa688cb9d3c9dc6899e604ab175a7d&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%201%2F2%29 Co-authored-by: Claude Sonnet 4.7 <[email protected]>
Pre-PR validation gate (a–f)a) Deterministic repro? Partial. The original b) Root cause explained? Yes. Two distinct loss paths:
c) Fix matches root cause? Yes. Path 1 is fixed by backfilling at finish: d) Test intent preserved? Yes. e) Both directions demonstrated? Yes by construction:
f) Fix is general? Yes:
|
|
cc @pamarcos @Algunenano @alexey-milovidov — could you review this? |
|
Workflow [PR], commit [3c94777] Summary: ✅ AI ReviewSummaryThis PR hardens ClickHouse Rules
Final Verdict
|
|
Bumping for visibility — @pamarcos, could you take a look when you have a moment? @alexey-milovidov pointed me to you on #101111 as the original author of Local verification: |
The bug-fix-validation lane reported FAIL because the new test 04121_query_metric_log_backfill_missed_periodics passes on an unloaded master HEAD - the failure mode is timing-sensitive (BackgroundSchedulePool overload) and cannot be reproduced deterministically by the bug-fix-validation runner. Reclassify under `Improvement` and let the Config Workflow drop the `pr-bugfix` label on this CI re-run; the `04121` test stays as a regression guard for the new contract.
|
Reclassified this PR from Why: The previous run's What stays the same:
The |
…x, drop redundant 04121 test
The functional change is unchanged: backfill missed periodic events in
`QueryMetricLog::finishQuery` and bypass the dedup guard for the final row
via `is_final=true`.
Reductions:
- Trim verbose comment blocks in `QueryMetricLog.cpp` (the rationale is in
the PR description; only the load-bearing context stays in the code).
- Use a local `missed_time` loop variable instead of mutating
`query_status.info.next_collect_time` inside the backfill loop.
`next_collect_time` is no longer read after `finishQuery` returns.
- Drop the `std::max` defensive write to `info.last_collect_time`. After the
final emit, `last_collect_time` is never read again for that query, so
the assignment cannot move backwards into anything that observes it.
- Drop `tests/queries/0_stateless/04121_query_metric_log_backfill_missed_periodics.{sh,reference}`.
The existing `03203_system_query_metric_log` test already exercises the
exact failing assertion from the original CI report (`count() > 2` for the
1000 ms interval branch); reproduced deterministically by injecting a
600 ms delay in `collectMetric` showed master fails this assertion and the
fix passes it. `04121` was redundant.
Verification: with a debug delay injected at the top of `collectMetric`
(simulating a backlogged `BackgroundSchedulePool`), master+inject gives
`count = 2` (matches the canonical `Stateless tests (amd_tsan, parallel)`
failure from PR=101111) and PR-fix+inject gives `count = 3`. Both the
original PR fix and this simplified variant give the same result.
Assisted-by: claude-opus-4-7
…ailpoint The bug fixed by 7a80840 only surfaces under TSan-build CI scheduling at roughly 0.1% rate. Without controlled timing, no functional/stress/integration test on a fast machine reproduces it. Add a `query_metric_log_delay_collect` failpoint at the top of `collectMetric`: when enabled it sleeps 1 second before capturing `current_time`, simulating a backlogged `BackgroundSchedulePool` so the captured timestamp slips past the query's finish moment - exposing the race the backfill+`is_final` logic in `finishQuery` repairs. The new test `04117_query_metric_log_backfill_missed_periodics` enables the failpoint, runs the canonical `SELECT sleep(2.5) SETTINGS query_metric_log_interval=1000` probe, and asserts `count() >= 3` (1+ periodic + backfilled missed + forced final). Tagged `no-parallel` because the failpoint is server-wide: parallel test instances would race on `SYSTEM ENABLE/DISABLE FAILPOINT` and mask the bug for late-running instances. Empirical results on this machine: | Build | Test runs | Pass | Fail | |---------------------|-----------|------|------| | master + failpoint | 100 seq | 0 | 100 | | fix + failpoint | 100 seq | 100 | 0 | The same fix+failpoint binary also passes `03203_system_query_metric_log` and `03549_system_query_metric_log_with_queries_with_same_query_id` 100x in parallel, confirming the failpoint is a no-op when the test does not enable it. Pattern follows existing failpoint+`sleepForSeconds` injections such as `FailPoints::sleep_in_logs_flush` (`SystemLog.cpp`), `FailPoints::rmt_delay_commit_part`, and `FailPoints::rmt_delay_execute_drop_range`. Assisted-by: claude-opus-4-7
LLVM Coverage Report
Changed lines: 91.30% (21/23) | lost baseline coverage: 4 line(s) · Uncovered code |
alexey-milovidov
left a comment
There was a problem hiding this comment.
The fix is sophisticated. But passable.
Replace the vague `count() > 2` assertion (which counted rows but did not actually verify the presence of an ending row) with a precise equality check between the maximum `event_time_microseconds` in `system.query_metric_log` and the `QueryFinish` event_time_microseconds in `system.query_log`. The two timestamps are derived from the same `std::chrono::system_clock::now()` capture in `executeQuery.cpp`: the same `time_now` / `query_end_time` is passed to both `addStatusInfoToQueryLogElement` (which writes the `QueryFinish` row in `query_log`) and to `logQueryMetricLogFinish` → `QueryMetricLog::finishQuery` (which emits the final row in `query_metric_log`). `timeInMicroseconds` is a pure `duration_cast<microseconds>` of `time_since_epoch`, so the two values are byte-equal whenever the final row is emitted. If the final row is dropped, `max(event_time_microseconds)` falls back to the previous periodic boundary - at least one full interval (1000 ms) earlier - and the equality fails. This is a tighter, semantic check that does not depend on how many periodic ticks survived under load. It catches the regression PR ClickHouse#103547 was attempting to fix (a final row dropped by the dedup guard when its timestamp coincides with the last periodic) without backfilling fake rows. Also flush `system.query_log` so the new check can read the `QueryFinish` row. CI report that originally surfaced this: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101111&sha=d1bb5ca2ccaa688cb9d3c9dc6899e604ab175a7d&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%201%2F2%29
…fix-flaky-test Revert `query_metric_log` periodic backfill (ClickHouse#103547) and tighten flaky 03203 test
Apply the edit-changelog skill workflow to the autogenerated 26.5 section: add the release header, drop the NO CL ENTRY and NOT FOR CHANGELOG / INSIGNIFICANT sections, rescue user-visible entries into Bug Fix, Performance Improvement and Improvement, reconcile reverted PRs against the rest of the changelog (drop entries for ClickHouse#102801, ClickHouse#103547, ClickHouse#103858, ClickHouse#104800), record the isPrime / isProbablePrime revert-of-revert and follow-up PRs on the original entry, prune Build/Testing to user-affecting items, and apply a focused round of per-entry rewrites (proper-noun capitalization, backticked identifiers, common typos). Date, presentation URL and video URL in the release header are left as FIXME placeholders.
When a scheduled
collectMetrictask fires after the query has already finished,getQueryInforeturns null and the periodic event is silently dropped. Under TSan builds and in highly parallel CI runs theBackgroundSchedulePoolcan fall behind by enough for this to happen repeatedly, leavingsystem.query_metric_logwith fewer rows than the documented behavior promises — and occasionally missing the "query finished" row entirely when the last periodic happens to share the finish moment's timestamp (the existingquery_info_time <= info.last_collect_timeguard then drops the final).QueryMetricLog::finishQuerynow backfills the missed periodic rows using thequery_infocaptured at finish (deltas remain monotonically correct via the existingnew_value < old_valueguard insidecreateLogMetricElement) and always emits the final row by passing a newis_final=trueflag through tocreateLogMetricElement. The dedup guard remains in place for ordinary periodic events and only the final bypasses it.The new test (
04121_query_metric_log_backfill_missed_periodics) exercises a 1.5 s query with a 100 ms interval and asserts both the row count and the cumulative profile counters — it documents the new contract. The existing03203_system_query_metric_logtest was the symptom: it has been flaky onStateless tests (amd_tsan, parallel, 1/2)for 30 days (4 unrelated PRs + 1 master hit) with the canonical "missing final event" diff.The category is
Improvementrather than a stricter category: the failure mode requiresBackgroundSchedulePooloverload to manifest, and the bug-fix-validation lane (which runs the new test against an unloaded master HEAD) cannot deterministically reproduce the timing-sensitive race. The test still serves as a regression guard for the new contract — a future revert of the backfill oris_finalbypass that breaks the documented row count would be caught by the04121assertions.CI report that surfaced the latest occurrence: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101111&sha=d1bb5ca2ccaa688cb9d3c9dc6899e604ab175a7d&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20parallel%2C%201%2F2%29
Verification
03203_system_query_metric_log: 50/50 passes locally on a debug build (was the symptom of the issue).03203_system_query_metric_logunder heavy CPU stress (stress-ng --cpu 96): 30/30 passes (previously could fail).03549_system_query_metric_log_with_queries_with_same_query_id: 10/10 passes (sibling test, no regressions).04121_query_metric_log_backfill_missed_periodics: 30/30 passes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improve reliability of
system.query_metric_logso that rows are not silently dropped when theBackgroundSchedulePoolis overloaded. Periodic rows that were scheduled to fire but only ran after the query had finished used to be silently dropped, and the final "query finished" row could also be dropped if it shared a timestamp with the last periodic row. The query-finish path now backfills the missed periodic rows and always emits the final row.Documentation entry for user-facing changes
Version info
26.5.1.150