Skip to content

Keep or skip five stateless tests that a Replicated database refuses to run - #112862

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/replicated-db-refused-statement-stateless-tests
Aug 1, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/replicated-db-refused-statement-stateless-tests

Conversation

@groeneai

@groeneai groeneai commented Aug 1, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #112247

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):

...

Description

On the DBReplicated coverage flavours the runner puts stateless tests on a Replicated
database, and five of them execute a statement the server refuses there by design. Those
failures were hidden: the diagnostics rerun drops the job's --replicated-database flag, so
they were labelled flaky and force-set OK (over 94,000 such rows in the last 21 days). #112247
fixes the visibility; this makes the five stop failing.

Two refusals are involved, both unconditional throws with no relaxing setting:
StorageMaterializedView.cpp rejects a refreshable materialized view with no APPEND over a
non-replicated target on a Replicated database, and InterpreterAlterQuery rejects an ALTER
mixing replicated and non-replicated actions in one statement.

The engine sanity-check block holding the first refusal is skipped when APPEND is set, so two
tests keep running on every flavour via an APPEND fixture instead of losing that coverage:
03981_refreshable_mv_retries_int64_max and
04247_attach_table_storage_clauses_without_engine_error. 04247's assertions are unchanged.
03981 also raises its retry threshold, so the wait can no longer be satisfied before the second
attempt starts, and asserts the comment that attempt formats; its reference gains one row.

The remaining three get no-replicated-database, because for them the refused statement is
the assertion: 04617_pr_plan_based_materialized_view asserts the APPEND/non-APPEND
distinction in both arms, and 04278_json_minmax_index_mixed_type_array plus
04062_table_readonly_replicated each assert a single mixed ALTER. This records a
server-enforced engine incompatibility, not a randomization silencer: no no-random-* tag is
added and randomization stays green on its own. Note the tag also skips Cloud and
shared-catalog runs, where the same refusals apply.

Validation: each rewrite verified to keep its assertion on a plain server and to newly pass with
--replicated-database; each tag verified to skip rather than fail. Reverting the APPEND or
removing a tag reddens exactly the affected tests with the refusal above. 50 randomized runs of
all five: 250 OK, 0 failures.

Version info

  • Merged into: 26.8.1.596 (included in 26.8 and later)

groeneai and others added 3 commits July 31, 2026 16:57
…to run

On the DBReplicated coverage flavours the runner puts stateless tests on a
Replicated database, where the server refuses two statement shapes by design:

  * StorageMaterializedView rejects a refreshable materialized view with no
    APPEND over a non-replicated target ("This combination doesn't work ...
    Refusing to create", BAD_ARGUMENTS), because the refresh would run on one
    replica while the table was replaced on the others.
  * InterpreterAlterQuery's validateReplicatedDatabaseSegments rejects an ALTER
    mixing replicated and non-replicated actions in one statement
    (QUERY_IS_PROHIBITED).

Five tests execute one of those, so they failed on every such run. The failures
were hidden rather than absent: the functional-test diagnostics rerun builds its
command without the job's own --replicated-database flag, so the failure could
not reproduce in the rerun, was labelled flaky, and was force-set OK on the
coverage jobs. That accounts for 89977 whitewashed-OK rows over 21 days.

The engine sanity-check block holding the first refusal is gated on !fixed_uuid,
and fixed_uuid is the APPEND flag, so APPEND skips the refusal outright. Two
tests therefore keep running on every flavour via an APPEND fixture instead of
losing that coverage:

  * 03981_refreshable_mv_retries_int64_max: its subject is the signed-overflow
    guard when refresh_retries is INT64_MAX. The retry machinery never reads the
    append flag, and the guarded site was measured to still be reached, printing
    "(attempt 4/9223372036854775808)".
  * 04247_attach_table_storage_clauses_without_engine_error: its subject is the
    ATTACH rejection surface, decided before storage construction. EMPTY is
    added too, so no initial refresh appends a row into the target the ATTACH
    cases read.

The other three get no-replicated-database, because for them the refused
statement is the assertion: 04617_pr_plan_based_materialized_view asserts the
APPEND/non-APPEND distinction in both arms, and both
04278_json_minmax_index_mixed_type_array and 04062_table_readonly_replicated
assert a single mixed ALTER. This records a server-enforced engine
incompatibility, not a randomization silencer: no no-random-* tag is added, and
50 randomized runs of all five tests give 250 passes. The tag also skips Cloud
and shared-catalog runs, which reach the same refusals.

04062's symptom was a result-differs rather than an error, which looked like a
behavioural divergence. It is the same mixed-ALTER refusal, masked: on a plain
database the statement returns the expected NOT_IMPLEMENTED, while a Replicated
database intercepts it in segment validation first and the shell wrapper turns
that into a 0.

No reference file changed. Reverting the APPEND or removing a tag reddens
exactly the affected tests with the refusal quoted above.
The test exists to pin the signed-overflow guard in RefreshTask::executeRefresh,
which formats "(attempt N/total)" as static_cast<UInt64>(refresh_retries) + 1 so
that refresh_retries = INT64_MAX prints 9223372036854775808 rather than
overflowing. Its oracle could not observe that branch.

system.view_refreshes.retry is the internal attempt counter minus one while a
refresh is in flight, so retry == 1 has two preimages: attempt 1 has failed and
attempt 2 has not started, or attempt 2 is running. Only the second implies the
branch ran, and the first is entered first, separated from it by the retry
backoff. The poll broke on the first retry >= 1 sighting and the final assertion
re-read the same threshold, so the test could pass having executed only attempt 1.

Raise both to retry >= 2, which is reachable only once attempt 2 has entered
executeRefresh, and additionally assert the produced comment itself from
system.query_log so a regression in the guard's arithmetic changes the asserted
value rather than only the counter. The reference gains the matching row.

Measured over a matrix of fixture, threshold and the new assertion: with
refresh_retries = 0, so attempt 1 fails and no retry is ever scheduled, the
previous form still printed "ok 1" and passed, while the new form reports
ok 0 and formatted 0. Each change alone also converts that vacuous pass into a
failure, so neither is redundant. On a healthy server the test passes 20 of 20
unrandomized and 50 of 50 randomized runs, and it still runs (rather than being
skipped) with --replicated-database, where reverting the APPEND fixture keyword
restores the Code 36 refusal.
03981_refreshable_mv_retries_int64_max asserts that the retry formatting branch
in RefreshTask::executeRefresh produced '(attempt N/9223372036854775808)', by
reading system.query_log for the refresh's log_comment.

On a Replicated database an APPEND refreshable view is coordinated by default
(all_replicas defaults to false), so the refresh runs on one arbitrarily chosen
same-shard replica. The retry counter survives that, because it lives in the
shared Keeper znode, but query_log does not: it is written into the process-local
log of whichever server ran the refresh, while the test client is connected to one
server. On the coverage DBReplicated flavour two servers share a shard, so the
assertion is intermittently lost when the other replica wins the refresh lock.

Setting all_replicas = 1 keeps refresh uncoordinated, so every replica refreshes
locally and the connected one always produces both its own retry counter and its
own query_log row. The setting exists for exactly this choice: in APPEND mode both
modes are meaningful. It cannot perturb what the test measures, because the
attempt counter, the retry scheduling and the formatting branch are all
unconditional on coordination, and it is a no-op on a plain database.

Measured on two servers sharing one Keeper with the same shard macro and different
replica macros: with the setting the assertion holds in 12 of 12 runs; without it
it fails in 3 of 12 while the retry assertion passes in all runs. With the setting
no coordination znode is created at all; without it
/clickhouse/tables/<uuid>/<shard>/replicas exists and lists both replicas.

Also reword the wait comment: retry >= 2 establishes that attempt 2 entered
executeRefresh, which is weaker than the previous heading claimed.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 1, 2026

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

Before opening this PR I ran an internal review pass: an independent cold code
review plus a separate second-model gate, over three rounds. Two rounds bounced
the change back for a fix; this is the summary of what was found and what
happened to each finding.

Rounds: 3 review rounds, 2 fix rounds. 14 findings adjudicated: 1 blocker
(raised twice, independently, from both directions), 2 majors and 10 nits;
10 agreed, 1 disagreed with evidence, 3 dropped as already-verified notes.

Round Severity Finding Verdict
r1 ⚠️ major 03981's oracle could not prove the branch it exists to pin had run. system.view_refreshes.retry is attempt_number minus one while a refresh is in flight, so retry == 1 has two preimages, and the one entered first is "attempt 1 failed, attempt 2 not started". The poll broke on the first retry >= 1 sighting and the final assertion re-read the same threshold, so the test could pass having executed only attempt 1, never reaching the static_cast<UInt64>(retries) + 1 guard that is its subject. Pre-existing, but this PR newly claims the branch is reached either way, so it is in scope. ❌ Fixed: threshold raised to retry >= 2 and a row added asserting the string the branch produces. A fixture x threshold x row matrix shows the pre-round form passed vacuously with refresh_retries = 0 and that each change alone turns that into a failure.
r2 ❌ blocker The new query_log assertion is replica-local, but APPEND on a Replicated database leaves refresh coordinated, and the coverage flavour runs three servers. Two of them share {shard}, so they resolve to the same coordination znode and contest one lock; the loser executes nothing. retry reads shared Keeper state so it stays correct, but log_comment is written only by the server that ran the refresh, and the test client connects to one server. The new row would therefore fail intermittently on the exact flavour this PR exists to fix. ❌ Fixed: all_replicas = 1 keeps refresh uncoordinated. Reproduced end to end on two replicas sharing one Keeper with the same {shard}: 12 of 12 runs pass with the setting, 3 of 12 fail the new row without it, while the older assertion passes in all 24.
r3 ⚠️ major The PR's only provenance link sat inside the leading HTML comment block, so it did not render. ❌ Fixed: moved into the visible body. Convention measured rather than assumed: of 60 recently merged PRs, 16 carry a relationship line and 14 of those place it visibly.
r3 💡 nit The body quoted a precise whitewashed-row count from a sliding 21-day window; it had already drifted three times as the window moved. ❌ Fixed: re-derived live and restated as a lower bound that stays true.
r1-r3 💡 nits (8) Comment wording, the exact clause that performs the mixed-ALTER refusal, and 04247's coordinated-APPEND blast radius. Noted, not blocking. On the last one: 04247 now creates coordination znodes on that flavour for the first time, but it never waits on or reads a refresh, EMPTY suppresses the initial one, the schedule is EVERY 1 HOUR, and it has no query_log or row assertion, so nothing there is replica-sensitive.
r2 💡 nit One wording nit was disagreed with rather than applied: the mixed-ALTER comments name the enclosing validation function instead of the exact clause. The substance is correct and the refused statement is the one the comment describes. Recorded with the source citation; not changed.

Claims in the diff's own comments were treated as claims and each checked
against the source: that APPEND skips the sanity-check block holding the
refusal, that the retry and formatting paths never read the append or
coordination flags, that retry >= 2 implies the guard fired, that the
coordination decision is a no-op on a plain database, and that the mixed-ALTER
refusal is the replicated-vs-non-replicated clause rather than the
different-segments one. The tag results were re-derived by driving the runner's
own tag parser over all five files.

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. On a Replicated-database sandbox each refused statement fails on demand: Code: 36 ... refreshable materialized view, no APPEND, replicated database, non-replicated table (03981/04247/04617) and Code: 392 ... ALTERs of different types (replicated and non replicated) (04278/04062). Runner arms are deterministic, not a low-rate flake: tests/clickhouse-test --replicated-database --no-stateful gives FAIL/FAIL pre-fix and SKIPPED/SKIPPED post-tag on every run.
b Root cause explained? Yes. Two unconditional server refusals with no relaxing setting: StorageMaterializedView.cpp rejects a refreshable MV with no APPEND over a non-replicated target on a Replicated database, and InterpreterAlterQuery (validateReplicatedDatabaseSegments) rejects an ALTER mixing replicated and non-replicated actions in one statement. Both fire because the coverage DBReplicated flavours put these tests on a Replicated database. They were invisible because the diagnostics rerun drops the job's --replicated-database flag, so the failure could not reproduce in the rerun and was labelled flaky and force-set OK.
c Fix matches root cause? Yes, and it is deliberately not a silencer. The engine sanity-check block holding the first refusal is gated on !fixed_uuid, and fixed_uuid is the APPEND flag, so two tests keep running on every flavour via an APPEND fixture rather than losing that coverage. Only the three whose refused statement is the assertion get no-replicated-database, which records a server-enforced engine incompatibility. No no-random-* tag is added anywhere and no assertion bound was widened, no dataset reduced.
d Test intent preserved / new tests added? Preserved, and for 03981 strengthened. 04247 keeps its assertions and its .reference byte-identical. 03981 gains a stronger oracle: its poll and final assertion move from retry >= 1 to retry >= 2, and a new row asserts the string the guarded branch produces (log_comment like 'refresh of %rmv (attempt %/9223372036854775808)', where 9223372036854775808 is static_cast<UInt64>(INT64_MAX) + 1). system.view_refreshes.retry is attempt_number minus one while a refresh is in flight, so retry >= 1 was also satisfied before the second attempt started, i.e. before the overflow guard the test exists for had run. Its .reference therefore gains one row (formatted 1), the only reference edit in this PR. The view also sets all_replicas = 1, which keeps refresh uncoordinated so the replica the test client is connected to runs its own refresh: retry reads shared Keeper state and is replica-agnostic, but query_log is replica-local, so without it a coordinated refresh on another same-shard replica would make the new row read 0. Nothing weakened or removed; no new test file.
e Both directions demonstrated? Yes. Positive: 2 rewrites OK on a plain server and newly OK with --replicated-database; 3 tagged tests SKIPPED (REPLICATED_DB) rather than failing; all 5 OK on a plain server; 03981 20/20 unrandomized and 50/50 randomized. Negative: reverting APPEND/EMPTY reddens both rewritten tests with the refusal text, and removing each tag reddens that test with its class's exact error (Code 36 for 04617, Code 392 for 04278, and for 04062 the masked form, a result differs whose fourth assertion reads 0 instead of 1). For 03981's strengthened oracle, a matrix over fixture x threshold x new row shows each change is independently load-bearing: with refresh_retries = 0, so attempt 1 fails and no retry is ever scheduled, the pre-strengthening form still printed ok 1 and passed, whereas the shipped form reports ok 0 and formatted 0, and each change alone also turns that vacuous pass into a failure. all_replicas = 1 is load-bearing on two independent arms: with it no coordination znode is created at all, without it /clickhouse/tables/<uuid>/<shard>/replicas exists; and on two replicas sharing one Keeper with the same {shard} and different {replica} (the topology of the coverage flavour's 9000/19000 pair), replaying the test against one replica gives formatted 1 in 12 of 12 runs with the setting and formatted 0 in 3 of 12 without it, while the ok row passes in all 24.
f Fix is general across code paths? Yes. Both refusal sites were enumerated, then every other candidate checked repo-wide: the four untagged refreshable-MV tests named as possible latent carriers are all non-carriers (measured: 4 OK on --replicated-database), and a scan of all 0_stateless .sql/.sh/.sql.j2 for a single ALTER mixing a replicated action with MODIFY/RESET SETTING in untagged tests returned 9 candidates, all non-carriers (6 are deliberate error-case assertions of the column-level form, which is a syntax error on any engine; 1 only formats the text via formatQuery; 3 are single-action ALTERs). DBReplicated exists only on the two coverage job definitions, so there is no symmetric non-coverage job to fix.
g Fix generalizes across inputs? The relevant axis is the database engine rather than type wrappers, and both arms were measured for all five tests (plain and Replicated). The tag's real scope is stated in the PR body: it also skips Cloud and shared-catalog runs, where the same refusals apply. The APPEND/EMPTY interaction was measured rather than assumed: EMPTY is load-bearing because APPEND alone lets an initial refresh append a row into the target the ATTACH cases read.
h Backward compatible? (maintainer-approved exception only) N/A. Test-only change: no source file touched, no setting default moved, no SettingsChangesHistory.cpp entry, no serialization or format change.
i Invariants and contracts preserved? Yes. No source change, so no server pre/postcondition, data-structure invariant or locking contract moves. On the test side each fixture still cleans up (03981 drops its view, 04247 restores then drops its tables), and the runner's leftover-table check passed on every arm including the 50-run randomized batch.

Session id: cron:clickhouse-review-slot-9:20260801-050002

@groeneai

groeneai commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach, could you review this? Five stateless tests execute a statement a Replicated database refuses, so they fail deterministically on the DBReplicated coverage flavours; two keep running there via an APPEND fixture, because the engine sanity-check block holding the refusal is skipped when APPEND is set, and the three whose refused statement is the assertion get no-replicated-database.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 1, 2026
@PedroTadim
PedroTadim enabled auto-merge August 1, 2026 11:00
@PedroTadim PedroTadim self-assigned this Aug 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8107172]

Summary: ✅


AI Review

Summary

This PR fixes five stateless tests that deterministically fail on DBReplicated coverage jobs because a Replicated database rejects the statement shape under test. I reviewed the current diff, the current code in the touched tests and cited server paths, the existing PR discussion, and the current all-green CI reports; I did not find a surviving correctness, determinism, or coverage issue that warrants a new inline review comment.

Final Verdict

✅ No new findings.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 1, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 1, 2026
Merged via the queue into ClickHouse:master with commit cd6fd72 Aug 1, 2026
179 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 1, 2026
github-merge-queue Bot pushed a commit that referenced this pull request Aug 2, 2026
These five tests fail deterministically (Failed 3 of 3 reruns) on the
DBReplicated flavours and are then force-set to OK by the llvm-coverage
whitewash, so today they assert a deny path that silently allows and catch
nothing at all on those configurations.

Two distinct causes.

Four access tests (04318_remote_storage_engine_access,
04401_remote_storage_engine_restore_access, 04401_url_engine_s3_dispatch,
04489_remote_storage_engine_restore_tf_access) assert checks implemented
inside storage construction (StorageDistributed.cpp, StorageURL.cpp). On a
Replicated database InterpreterCreateQuery returns tryEnqueueReplicatedDDL,
which performs no checkAccess, and the entry is executed by a worker whose
context has no user: DDLTask::makeQueryContext only calls setUser when
distributed_ddl_use_initial_user_and_roles is enabled and initiator_user is
set, and only the ON CLUSTER path populates initiator_user. Context::getAccess
then computes full_access = !user_id, so those in-storage checks short-circuit
to allow. Observed in the server log: the RESTORE arrives as the restricted
user, but the CREATE TABLE ... ENGINE = Remote(...) it produces executes as
(from 0.0.0.0:0, user: , initial_query_id: ...) and succeeds where the test
requires rejection. The signature that this is one cause and not three: in
04401_url_engine_s3_dispatch the table-function source check still passes,
because a table function is analyzed on the initiator, while both engine
checks flip to NOT DENIED. This is open issue #111561, so each of these four
comments names it and git grep 111561 tests/ finds every pin when it is
resolved.

02440_mutations_finalization pauses the merge-selecting task with a failpoint,
but SYSTEM ENABLE FAILPOINT is a process-local call and the helper macro
appends auto_{shard}, so the table is created once per shard and the untouched
shard's scheduler finishes the mutation the test expects to stay pending. That
is a harness assumption rather than a defect, so its comment cites no issue.

No assertion is weakened, inverted or removed and no reference file changes.
The tag reaches three configurations (replicated-database, cloud,
shared-catalog), all of which are replicated or shared-catalog database
environments subject to the same gap. Coverage is retained everywhere else:
250/250 green over 50 randomized runs on the default flavour, 250/250 skipped
on the affected one.

The engine fix is deliberately not attempted here. #111561 is parked on an
owner-level decision, since the authorization channel is either one host
(rights-dependent results then diverge per replica), or all hosts (which is
distributed_ddl_use_initial_user_and_roles, off by default), or refusing to
execute. A write-up with three options is already posted there.
04541_create_as_select_table_scoped_insert_grant and
04418_create_table_as_select_subquery_access are left failing on purpose as
that issue's live evidence and are untouched. Same instrument as #112862.
alexey-milovidov pushed a commit to filimonov/ClickHouse that referenced this pull request Aug 5, 2026
Both fail on every run of the
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 1/3)
job. They read as flaky only because the llvm-coverage diagnostics rerun drops
--replicated-database, so the failure reruns green, is labelled flaky, and is
force-set to OK in the CI database. Requested by alexey-milovidov on ClickHouse#112052.

03990_alter_rename_column_swap_different_types

One assertion issues RENAME COLUMN ..., RENAME COLUMN ..., UPDATE ... WHERE 1 as
a single ALTER. InterpreterAlterQuery groups an ALTER's commands into segments by
kind, and validateReplicatedDatabaseSegments rejects any multi-segment ALTER on a
DatabaseReplicated, so the server refuses the statement with
Code: 392 QUERY_IS_PROHIBITED before any storage code runs.

The combined form is the assertion: the non-key UPDATE is what forces the part to
be rewritten by the mutation, so getColumnsForNewDataPart processes the part while
the renamed-from column holds no data. Splitting it into two ALTERs would make the
mutation observe a different part state and stop exercising the issue ClickHouse#103247 code
path, so the honest fix is the tag. This matches the disposition already merged for
the sibling test 04278 in ClickHouse#112862. The other twelve ALTERs in the file are
single-kind and execute normally on a Replicated database, verified individually.

The tag also suppresses Cloud and shared-catalog runs, which is a real coverage
cost, accepted because the statement is unsupported there.

04510_s3_explicit_url_named_secret_mask

The closing oracle compares a byte-exact system.query_log transcript scoped only by
current_database. On a Replicated database the DDL replay worker logs each DDL a
second time, so the transcript gains 7 replayed entries and 7 rewritten CREATE
statements with a materialized UUID: 14 extra lines.

Every secret is still [HIDDEN] in those extra rows, so masking is intact and this
is not a security failure; the oracle simply over-specifies which rows exist. A
skip tag would delete real coverage of 47 tagged secrets across roughly 60
carriers, so the oracle is scoped to the initiating query instead.

DDLTaskBase::makeQueryContext calls setCurrentQueryId(""), giving the replay
context a fresh random query_id, and DDLWorker then calls
setInitialQueryId(task.entry.initial_query_id), inheriting the initiator's id. For
a directly issued query Context::setCurrentQueryId sets initial_query_id equal to
current_query_id. So query_id = initial_query_id selects exactly the statements the
test issued, on both Atomic and Replicated databases, and the reference needs no
change. Filtering on the text of the ddl_entry comment was rejected as a fragile
match on the very column under assertion; is_replicated_database_internal is
semantically exact but is not exposed in query_log.

Validation: both reproduce deterministically with --replicated-database and pass
after the fix, both still pass without it, and each survives 50 randomized runs per
flavour. The 04510 filter was checked for vacuity in both directions: injecting a
statement that logs a plaintext secret as an initiating row still makes the filtered
oracle fail, and on a non-Replicated database the added clause changes nothing.
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 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