Skip to content

Revert query_metric_log periodic backfill (#103547) and tighten flaky 03203 test - #103771

Merged
pamarcos merged 5 commits into
ClickHouse:masterfrom
pamarcos:revert-103547-and-fix-flaky-test
May 5, 2026
Merged

pamarcos merged 5 commits into
ClickHouse:masterfrom
pamarcos:revert-103547-and-fix-flaky-test

Conversation

@pamarcos

@pamarcos pamarcos commented Apr 30, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #103547, which addressed flakiness of 03203_system_query_metric_log by backfilling missed periodic rows in QueryMetricLog::finishQuery. The backfill reused the finish-time query_info for past timestamps, producing one row with the full delta stamped at a wrong past time and N-1 zero-delta rows including the final — cumulative sums stayed correct, per-row temporal accuracy did not.

Reverts that and replaces the vague count() > 2 assertion with max(event_time_microseconds) in query_metric_log equal to the QueryFinish row in query_log (both derive from the same system_clock::now() capture in executeQuery.cpp, so byte-equal whenever the final row is emitted).

Reverts #103547. Originally tracked in #71244.

Originating 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

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Version info

  • Merged into: 26.5.1.296

…metric-log-missed-periodics"

This reverts commit 3a84d78, reversing
changes made to cd197ee.
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
@clickhouse-gh

clickhouse-gh Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e2c38fb]

Summary: ✅


AI Review

Summary

This PR reverts the periodic backfill change in QueryMetricLog and replaces the flaky row-count assertion in 03203_system_query_metric_log with a timestamp-based check against QueryFinish. The revert also restores a known edge case where the final query_metric_log row can still be dropped when its timestamp equals the last periodic sample timestamp, so the change is not safe to merge as-is.

Findings

⚠️ Majors

  • [src/Interpreters/QueryMetricLog.cpp:266] The dedup guard query_info_time <= info.last_collect_time now applies to final emission as well, so finishQuery can skip the final row when finish_time == last_collect_time. This reintroduces the missing-final-row path that #103547 was attempting to address.
    Suggested fix: keep backfill reverted, but reintroduce a final-row bypass for equality (for example an allow_equal_timestamp_for_final flag or equivalent branch for the finishQuery path that uses < instead of <=).
Tests
  • ⚠️ tests/queries/0_stateless/03203_system_query_metric_log.sh still misses the equality-collision edge case (finish_time == last_collect_time): in that case the final row may be skipped while max(event_time_microseconds) still equals QueryFinish, so the test can pass despite the bug. Add a deterministic regression test that forces this collision and asserts final-row presence/semantics.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ⚠️ The dedicated regression test 04117_query_metric_log_backfill_missed_periodics was removed, while the replacement test does not cover the timestamp-collision path.
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Reintroduces an existing correctness gap in query_metric_log final emission.
Compilation time ✅
No large/binary files ✅
Performance & Safety
  • The issue is correctness in observability data rather than a performance regression: losing the final row can produce inaccurate per-interval metrics and hide end-of-query deltas in system.query_metric_log.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Restore guaranteed final emission semantics for QueryMetricLog::finishQuery when timestamp equality occurs (without reintroducing synthetic backfill rows).
    2. Add/restore deterministic test coverage for the timestamp-collision edge case.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Apr 30, 2026
@pamarcos
pamarcos marked this pull request as ready for review April 30, 2026 06:49
@pamarcos
pamarcos requested a review from Copilot April 30, 2026 06:51

Copilot AI left a comment

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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Reverts the query_metric_log periodic backfill approach introduced in #103547 and updates the existing stateless test to assert the presence of the final query_metric_log row by comparing its timestamp to the corresponding QueryFinish entry in system.query_log.

Changes:

  • Removed the backfill + “forced final row” logic from QueryMetricLog::finishQuery and deleted the failpoint/test added to exercise it.
  • Tightened 03203_system_query_metric_log to validate the final metric-log event via event_time_microseconds equality with system.query_log.
  • Removed the query_metric_log_delay_collect failpoint registration and related includes.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tests/queries/0_stateless/04117_query_metric_log_backfill_missed_periodics.sh Deletes the regression test that depended on the reverted backfill/failpoint behavior.
tests/queries/0_stateless/04117_query_metric_log_backfill_missed_periodics.reference Deletes the expected output for the removed test.
tests/queries/0_stateless/03203_system_query_metric_log.sh Replaces a vague row-count assertion with a timestamp-equality check against QueryFinish.
src/Interpreters/QueryMetricLog.h Removes the is_final parameter from createLogMetricElement.
src/Interpreters/QueryMetricLog.cpp Reverts backfill logic and removes the “final row bypasses dedup” behavior + failpoint hook.
src/Common/FailPoint.cpp Unregisters query_metric_log_delay_collect.

Comment thread src/Interpreters/QueryMetricLog.cpp Resolved
Comment thread src/Interpreters/QueryMetricLog.cpp Resolved
The style check (ci/jobs/scripts/check_style/various_checks.sh) requires
queries against `system.query_log` and `system.query_thread_log` to
filter by `current_database = currentDatabase()`. The new cross-check
against `system.query_log` introduced in the previous commit was missing
that filter.

Adding it is also a defensive improvement: the test query_id contains
$CLICKHOUSE_DATABASE, but the explicit database filter prevents matching
should the same query_id ever surface from a different database via
`system.query_log`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=103771&sha=48c992d853e2f0e9bf2905f86b892534cb1889b6&name_0=PR&name_1=Style%20check
Comment thread src/Interpreters/QueryMetricLog.cpp Resolved
(SELECT event_time_microseconds
FROM system.query_log
WHERE event_date >= yesterday() AND event_time >= now() - 600 AND current_database = currentDatabase() AND query_id = '${query_prefix}_1000' AND type = 'QueryFinish'
LIMIT 1)

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.

LIMIT 1 without ORDER BY makes this assertion nondeterministic if multiple QueryFinish rows exist for the same query_id in the 600-second window (e.g., retries/re-runs). In that case this subquery can pick an older finish row and compare it to the latest query_metric_log row, causing flakiness unrelated to the regression under test.

Please either make the query_id unique per test run (for example append $$) or add ORDER BY event_time_microseconds DESC before LIMIT 1 so this always compares against the latest QueryFinish row.

pamarcos added 2 commits May 1, 2026 03:04
…IT 1

Address review feedback on PR ClickHouse#103771: `LIMIT 1` without `ORDER BY` is
nondeterministic if multiple `QueryFinish` rows match the same query_id
in the 10-minute time window (e.g. flake-detection re-runs of the same
test in the same database). `$CLICKHOUSE_DATABASE` is supposed to be
unique per test invocation so this is unlikely in practice, but ordering
by `event_time_microseconds DESC` and taking the first row is a one-line
defensive fix that removes the failure mode entirely.

The same pattern is used elsewhere in the test suite, e.g.
`01903_correct_block_size_prediction_with_default.sh`.
Address review comment on PR ClickHouse#103771: the format string reads
"Query {} has a more recent metrics collected at {}. This metrics are
from {}. Skipping this one", which expects query_id, last_collect_time,
query_info_time - but the arguments were passed as last_collect_time,
query_info_time, query_id, producing nonsensical log lines such as
"Query 2024.10.26 05:05:12.500 has a more recent metrics collected at
2024.10.26 05:05:11.000. This metrics are from test_xxx_1000".

Pre-existing since the original `QueryMetricLog` introduction; only
visible when LOG_TEST is enabled. Reorder the arguments to match the
format string.
SELECT '--Check that there is a final event when queries finish';
SELECT count() > 2 FROM system.query_metric_log WHERE event_date >= yesterday() AND event_time >= now() - 600 AND query_id = '${query_prefix}_1000'
SELECT
(SELECT max(event_time_microseconds)

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.

This check can still miss the regression it is trying to detect. If QueryMetricLog::finishQuery skips the final row because finish_time == last_collect_time, max(event_time_microseconds) from system.query_metric_log can still equal QueryFinish from system.query_log, so this assertion passes even though the final row was not emitted.

Please add a deterministic coverage path for the timestamp-collision case (or assert a property that distinguishes a true final emission from a periodic row with the same timestamp).

@clickhouse-gh

clickhouse-gh Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 100.00% (18/18) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this May 1, 2026
@pamarcos
pamarcos added this pull request to the merge queue May 5, 2026
Merged via the queue into ClickHouse:master with commit adfa623 May 5, 2026
165 checks passed
@pamarcos
pamarcos deleted the revert-103547-and-fix-flaky-test branch May 5, 2026 15:05
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label May 5, 2026
@pamarcos pamarcos mentioned this pull request May 14, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-ci 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.

4 participants