Skip to content

Do not record the async-metrics readonly checks in system.errors - #119448

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:no-record-async-metrics-readonly-race
Nov 5, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:no-record-async-metrics-readonly-race

Conversation

@groeneai

@groeneai groeneai commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118928, #111845

Changelog category (leave one):

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

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

Do not count a ReplicatedMergeTree replica's read-only state as an error in system.errors and system.error_log when the asynchronous metrics thread reads its replication delay. Previously a dropped or restarted replica recorded TABLE_IS_READ_ONLY, and a replica on static storage recorded TABLE_IS_PERMANENTLY_READ_ONLY and logged an error once per asynchronous_metrics_update_period_s, with no query having failed.

Description

Requested by @ alexey-milovidov in #93111. Seen as test_cancel_backup.py::test_cancel_restore at :547 (report); test_different_versions.py:105 has the same producer. No open issue exists.

ServerAsynchronousMetrics::updateImpl guards getReplicaDelays with status.is_readonly, but the callee starts with assertNotReadonly(), which rejects more than that flag, so it throws before doing any work in two ways:

  1. a concurrent DROP TABLE or SYSTEM RESTART REPLICA flips is_readonly after the check: TABLE_IS_READ_ONLY;
  2. assertNotReadonly() also checks static storage, which that flag does not reflect, so a replica on a read-only or write-once disk gets TABLE_IS_PERMANENTLY_READ_ONLY. That one is not a race and never stops: the restarting thread clears is_readonly after startup while the disk stays static, so it fired on every tick, at error level, only the transient code having been demoted.

The counter is incremented in the exception constructor, before any catch runs, and is cumulative.

#104981 named case 1 but only demoted its log level. This completes it: the call is wrapped in Exception::SuppressErrorCodesScope, the guard now uses isTableReadOnly() (is_readonly || isStaticStorage(), what assertNotReadonly() enforces and what ReplicasStatusHandler already uses), and the handler re-records every code except the two readonly ones, so Keeper failures stay visible.

No test ships. Case 1 has no failpoint; case 2 is deterministic, but its fixture needs a static-storage ReplicatedMergeTree, which in a stateless test means a deprecated Ordinary database plus s3_plain, as in 02980_s3_plain_DROP_TABLE_ReplicatedMergeTree.sh. I could not validate that locally and would rather not add an unvalidated test here; happy to add one if wanted.

Validation, both directions on a debug build

Case 1, a probe widening the window identically on both binaries, 12 forced flips:
system.errors[TABLE_IS_READ_ONLY] moves by +12 before the fix and by 0 after, while the
Cannot get replica delay line for this call site appears 12 times on both, so the race still
happens and is still reported. With Keeper's port blocked, KEEPER_EXCEPTION rises by +8 on both.

Case 2, a ReplicatedMergeTree restarted onto a read_only disk so the policy is static,
sampled over 20 s with system.replicas.is_readonly = 0, i.e. with the branch reachable:
the Cannot get replica delay line for that table appears 21 times at error level before the fix
and 0 times after. system.errors[TABLE_IS_PERMANENTLY_READ_ONLY] moves by +61 and +40, the
21 difference being this call site; the rest is the replica's own queueUpdatingTask,
mutationsFinalizingTask and mergeSelectingTask, a separate producer not touched here.

Not over-suppressed: after the fix, a healthy replica with min_relative_delay_to_measure = 0
and Keeper unreachable still logs this call site and still adds +11 to
KEEPER_EXCEPTION/NO_ZOOKEEPER, so tables that should be measured still are.

test_different_versions passes 50/50.


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

Version info

  • Merged into: 26.11.1.1428-master (included in 26.11 and later)

ServerAsynchronousMetrics::updateImpl reads `status.is_readonly` and then calls
`getReplicaDelays`, whose first statement is `assertNotReadonly()`. A concurrent
DROP/RESTART flips `is_readonly` in between (ReplicatedMergeTreeRestartingThread::
setReadonly), so the call throws TABLE_IS_READ_ONLY before doing any work. The
Exception constructor increments the error counter, so the code lands in
system.errors and system.error_log even though no user action caused it and the
background thread simply skips the table.

PR ClickHouse#104981 identified the same race but only demoted the log level from error to
debug, leaving the system.errors accounting in place. This completes that change
by wrapping the speculative call in Exception::SuppressErrorCodesScope, which
exists for exactly this shape.

The scope suppresses every code constructed on the thread, and getReplicaDelays
also does Keeper I/O after the readonly check (getZooKeeper, getChildren,
tryGet), whose Coordination::Exception is a DB::Exception. Those failures are
real and must stay visible, so the handler re-records every code except
TABLE_IS_READ_ONLY via recordToSystemErrors(). Log-level selection from ClickHouse#104981
is unchanged.

The other getReplicaDelays caller, ReplicasStatusHandler, has the same window and
is deliberately left alone: it serves an explicit /replicas_status request, so its
errors belong in system.errors.

Verified with a temporary probe widening the window, over 12 forced flips per
binary: the TABLE_IS_READ_ONLY counter moves by 12 on the pre-fix binary and
stays 0 on the fixed one, while the debug line naming this call site appears 12
times on both, so the race still happens and is still reported. With Keeper
blocked, KEEPER_EXCEPTION rises by 8 on both binaries.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 11, 2026
@groeneai

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

Two independent reviews of this change (a cold read plus a separate model pass) agreed on one
substantive point, which was fixed before publishing.

❌ A unit test that could not fail without the fix was removed. An earlier revision added
Exception.SuppressOnlyTheSelectedErrorCode to src/Common/tests/gtest_exception.cpp. It asserted
the caller's rule as a lambda defined inside the test, so reverting the change in
ServerAsynchronousMetrics.cpp left it green, and the part of the primitive's contract it did
exercise is already covered by Exception.RecordToSystemErrorsOnlyRecordsSuppressedExceptions.
Production-path coverage would need a pause failpoint in the metrics loop, which parks a
server-global background thread and forces no-parallel; that trade did not look like mine to make
unasked.

⚠️ Residual, deliberately not changed. The same window can still record KEEPER_EXCEPTION:
getAbsoluteDelay() returns current_time while the replication queue has never been updated,
which clears min_relative_delay_to_measure, so the Keeper part of getReplicaDelays is reachable
in the racy window and a ZNONODE on <zookeeper_path>/replicas during a concurrent DROP is
re-recorded on purpose. Keeping real Keeper failures visible is the point of the selective handler
rather than a blanket scope; measured at +8 on both binaries with Keeper's port blocked.

💡 ReplicasStatusHandler has the same window and is deliberately untouched, as noted in the
description.

Session id: cron:clickhouse-review-slot-8:20260911-121300

@clickhouse-gh clickhouse-gh Bot closed this Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 11, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @antonio2368 @pamarcos, could you review this? The async-metrics thread reads status.is_readonly, then getReplicaDelays throws TABLE_IS_READ_ONLY when a concurrent DROP or SYSTEM RESTART REPLICA flipped the replica in between, and the DB::Exception constructor counts it in system.errors before the existing catch runs; this suppresses that one code at the call and re-records every other, so Keeper failures from the same call stay visible. #111845 carries the same hunk repo-wide and is credited in the description.

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3319b06]

Summary: ✅


AI Review

Summary

The change suppresses expected readonly exceptions from asynchronous replication-delay collection, skips static-storage replicas, and preserves accounting and error logging for other exceptions, including Keeper failures. No remaining findings at 3319b067c7dcb5786dd7bc1db3f93e90b4741fd5. The previous static-storage issue is fixed. The remaining readonly-status concern is withdrawn: system.replicas.is_readonly retains its documented transient Keeper-state meaning, and the collector now uses the broader isTableReadOnly predicate. The PR reports focused before/after debug-build measurements for both readonly cases and Keeper failures, with the fixture limitations explaining the absence of an automated regression test.

Missing context / blind spots
  • ⚠️ CI for the current head is still running. No local build or tests were run during this review; runtime evidence comes from the experiments reported in the PR.
Final Verdict

✅ Approve. No additional changes requested.

@clickhouse-gh clickhouse-gh Bot added the comp-logging Logging/monitoring/observability (logs, metrics, tracing, instrumentation). label Sep 11, 2026
`status.is_readonly` mirrors only the transient atomic flag, but the callee's
`assertNotReadonly()` checks static storage first and throws
TABLE_IS_PERMANENTLY_READ_ONLY for a replica attached on a read-only or
write-once disk. So the previous guard let that replica into the branch on every
tick.

Unlike the DROP/RESTART flip this is not a race and it never stops: the
restarting thread clears `is_readonly` after a successful startup, while
`isStaticStorage()` stays true for the table's lifetime. The result on any server
at the default 1 s metrics period is a TABLE_IS_PERMANENTLY_READ_ONLY row in
system.errors plus an error-level "Cannot get replica delay" line every second,
with nothing having failed. Only TABLE_IS_READ_ONLY was demoted and excluded, so
the permanent code was both counted and logged at error level.

Ask for both states up front instead: `isTableReadOnly()` is
`is_readonly || isStaticStorage()`, which is exactly what `assertNotReadonly()`
enforces, and is what the only other `getReplicaDelays` caller,
ReplicasStatusHandler, already guards with. The handler now also treats the
permanent code as benign, so the narrow window between the check and the call is
covered for both codes; Keeper failures from the same call are still recorded and
still logged at error level.

Reported by clickhouse-gh[bot] in
ClickHouse#119448 (comment)

Verified on a debug build, both directions. Fixture: a ReplicatedMergeTree on a
local_blob_storage disk, restarted with read_only=true so the disk reports
isReadOnly() and the policy becomes static; sampled over 20 s with
system.replicas.is_readonly = 0, i.e. with the branch reachable.

  before  "Cannot get replica delay" for that table: 21 lines, level Error
          system.errors[TABLE_IS_PERMANENTLY_READ_ONLY]: +61
  after   "Cannot get replica delay" for that table: 0 lines
          system.errors[TABLE_IS_PERMANENTLY_READ_ONLY]: +40

The 21-line difference is this call site, and 61 - 40 = 21 accounts for it
exactly. The remaining 40 come from the replica's own queueUpdatingTask,
mutationsFinalizingTask and mergeSelectingTask, which are a separate producer and
are not touched here.

Non-target check on the fixed binary, so the new predicate is not over-broad: a
healthy replica with min_relative_delay_to_measure = 0 and Keeper's port blocked
still logs this call site and still adds 11 to KEEPER_EXCEPTION/NO_ZOOKEEPER.
Tables that should be measured are still measured, and real failures stay
counted.
@groeneai groeneai changed the title Do not record the async-metrics readonly race in system.errors Do not record the async-metrics readonly checks in system.errors Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 3319b067c with master 6a59c7376 (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, 21 s compile time in total, 7 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e555dbc

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose
fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_release, oracle) / TLP Aggregate oracle mismatch! on SELECT count() ... FROM test_has_idx_simple STREAM BOUNDED UNORDERED CURSOR {...} oracle mismatch: QueryOracleChecker compares a reference query against a metamorphic rewrite as two separate executeQuery calls, and a STREAM BOUNDED ... CURSOR row set is a function of physical layout rather than contents, so the two sides do not read the same relation. This PR changes one file, src/Interpreters/ServerAsynchronousMetrics.cpp, which is not on that path; the same oracle-mismatch signature hit 108 other pull requests and 3 master runs in the last 14 days. #119465 (mine, open)

Mergeable Check and PR are the praktika aggregators reporting that one job, not separate failures.

Session id: cron:our-pr-ci-monitor:20260911-210037

@alexey-milovidov alexey-milovidov self-assigned this Nov 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 5, 2026
Merged via the queue into ClickHouse:master with commit 2bfb3be Nov 5, 2026
185 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 5, 2026
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). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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.

3 participants