Skip to content

Stop stateless tests from leaving the shared database Replicated - #113794

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-5007-4590-shared-db-engine-leak
Aug 14, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-5007-4590-shared-db-engine-leak

Conversation

@groeneai

@groeneai groeneai commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixes a LOGICAL_ERROR: Digest does not match server abort in Stress test (arm_tsan)
(STID 5007-4590). No product code is at fault: the assertion correctly detected a divergence two
tests manufactured between them.

Root cause. In shared-database mode the stress lane points some clients at one long-lived
database (get_options, stress.py), created once and never recreated, so leftovers persist for
the whole
run. 03762_create_as_url_cluster.sql re-created it as Replicated and never restored it;
no-replicated-database cannot prevent that, because the guard reads a static CLI flag
(should_skip_test, clickhouse-test). 04545_attach_projection_part_offset_setting_disabled.sh
then ran there,
its DETACH was refused with Code: 80, and because the helper ignored that status sed -i
rewrote a live table's metadata. The next ALTER compared that file against the stale in-memory
digest and aborted.

The change, two independent halves, tests only.

  1. Fail closed in the two tests that rewrite table metadata (04545, 03001, the complete
    in-tree set): a refused DETACH now prints the server's error and exit 1s instead of letting
    the rewrite proceed.
  2. Stop the leak: the four tests that re-engined the shared database (03762, 04365,
    02483, 03224) now build their Replicated database as {CLICKHOUSE_DATABASE_2:Identifier},
    bracketed by DROP DATABASE IF EXISTS. That holds by construction rather than by cleanup,
    because the lane's killer SIGTERMs a random client on one branch of its 3 s loop
    (RandomQueryKiller._run, stress.py), skipping any cleanup-at-the-end fix. _2 because the
    scratch aliases
    are shared too (shell_config.sh) but far less contended: 3 consumers against 105, with 0
    bare creators against 19.

Validation. Under the database_replicated_force_metadata_digest_check failpoint the ALTER
aborts before the change with a stack matching the CI artifact frame-for-frame, and after it
succeeds with the database still Atomic. In shared-database mode, 02483 and 03224 previously
passed green while leaving it Replicated; now all four leave it Atomic, no scratch leftover.

Mutation matrix and scope notes

Each mutant reverts one half and reddens only its own property:

mutant result
leak restored, guard kept DETACH refused, metadata not rewritten, no abort: half 1 alone stops the corruption
leading DROP deleted, predecessor's scratch database present CREATE fails Code: 82; with the DROP it succeeds
exit 1 to return 1 at 03001's top level bash rejects return, continues into the rewrite, exits 0
03224 retarget reverted, oracle kept the engine assertion prints 1 and the test fails; with the retarget, 0

02483's reference pins the database name, so its retarget is self-checking. 03224's was not:
every renamed database is absent from its output, so reverting it still produced the full expected
result. It now asserts the invariant (engine = 'Replicated' must be false for currentDatabase())
rather than a specific engine, since the engine depends on the runner flags. Retargeting its last
phase also removed the only cleanup of its phase-3 test3, so it drops that table explicitly,
pinning ignore_drop_queries_probability = 0 as 02354_vector_search_concurrent_readers does.

A per-test database name is not available to a .sql test: the runner passes only
CLICKHOUSE_DATABASE, _1 and _2 (the --param_CLICKHOUSE_DATABASE* arguments the runner
builds), all derived from the shared
name; {CLICKHOUSE_TEST_UNIQUE_NAME} is shell-only and resolves to Code: 456.

Not addressed: 02072, 03321, 03362, 03655 and 04239 delete the shared database outright
instead of re-engining it, a different class from this digest assertion.

Version info

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

Fixes a LOGICAL_ERROR "Digest does not match" server abort in
Stress test (arm_tsan), STID 5007-4590. No product code is at fault: the
assertion in DatabaseReplicated::commitAlterTable correctly detected a real
disk-vs-memory divergence that two tests manufactured between them.

In shared-database mode the stress lane points some clients at one long-lived
database (ci/jobs/scripts/stress/stress.py:272). That database is created once
at startup and never recreated per test, so whatever a test leaves behind
persists for the whole run. 03762_create_as_url_cluster.sql re-created it as
Replicated and never restored it. The no-replicated-database tag cannot react
to that, because the guard reads a static CLI flag (tests/clickhouse-test:2928)
and the runner never re-reads the database's actual engine. Later
04545_attach_projection_part_offset_setting_disabled.sh ran in that database;
its DETACH was refused with Code: 80, its helper ignored the status, and sed -i
rewrote the metadata of a live, attached table. getMetadataHash re-reads that
file from disk (src/Databases/DatabaseReplicated.cpp:995-997) while
tables_metadata_digest still carried the pre-sed hash, so the next successful
ALTER aborted the server. On restart the replica was declared lost and one
table was moved to <db>_broken_tables.

Two independent halves, tests only:

- Fail closed in the two tests that rewrite table metadata, 04545 and 03001,
  which are the complete in-tree set of such tests: a refused DETACH now
  prints the server's own error and exits 1 instead of letting the rewrite
  proceed. exit 1 rather than return 1 is required, because 03001's DETACH is
  at script top level where bash rejects return and then continues into the
  rewrite with the script still exiting 0.
- Stop the leak at its source: 03762 and 04365 create their Replicated
  database as CLICKHOUSE_DATABASE_1 instead of re-engining the shared one,
  with DROP DATABASE IF EXISTS both before and after. The leading drop makes
  each test immune to a predecessor's leftover scratch database, the trailing
  one stops it becoming that predecessor. The shared database is never
  dropped, recreated or re-engined, so the property holds by construction
  rather than by cleanup. That distinction matters because the lane's
  background killer SIGTERMs a randomly chosen client on one branch of its
  three-second loop (ci/jobs/scripts/stress/stress.py:200-209, :755), so a
  restore-at-the-end fix is skipped on exactly the path where the leak was
  observed.

No .reference file changes: every edit is either a guard that fires only on
failure or a database identifier retarget that emits no output.

03224_invalid_alter.sql and
02483_add_engine_full_column_to_system_databases.sql still leave a Replicated
shared database behind. Neither is this failure's carrier and both need
materially more invasive rewrites, so they are deliberately out of scope here.
@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds, 3 findings adjudicated)

Before publishing I reviewed this change cold against the resulting tree, then had an independent
model re-review it. Findings and verdicts:

⚠️ Stale citation in the description (fixed) - the root-cause paragraph cited
clickhouse-test:2974 for the claim that the no-replicated-database guard reads a static CLI flag.
master has advanced 71 commits past this branch's base and that file moved, so :2974 now lands on
an unrelated comment. The guard is at :2928. Corrected in the description and in the checklist
comment. Verified with a per-line verifier carrying a negative control, at origin/master (the tree a
reviewer greps) and at the branch head; stress.py and DatabaseReplicated.cpp are byte-identical
between the two, so only this citation had rotted.

💡 Under-cited claim (fixed) - the clause about the lane's background killer asserts both the
branch it fires on and the loop interval, but cited only stress.py:200-209, which covers the branch.
The interval literal is at :54 and :755. Widened to :200-209, :755.

❌ "Six sibling tests can still leave the shared database Replicated after a mid-test SIGTERM, so
the invariant is incomplete" - disagreed, with evidence.

The mechanism is real and I concede it: a .sql test runs as one multiquery client, the killer
SIGTERMs a random client on one branch of its loop, and the workers that use a shared --database
without --replicated-database do admit no-replicated-database tests, so an interrupted sibling can
leave that database Replicated. I also checked no-ordinary-database and it is not honoured by the
runner at all (0 occurrences in tests/clickhouse-test, against positive controls of 3, 7 and 2 for
tags that are), so I am not resting this on tag exclusion.

What fails is the consequence. Reaching the abort additionally requires a test that rewrites on-disk
metadata to run there and ignore a refused DETACH. Re-censused independently at current master, the
complete set of such tests is exactly 03001 and 04545 (7 tests call sed -i; 2 of those also read
metadata_path; control: 13 tests reference metadata_path at all), and both are guarded here. The
guard is unconditional: it tests the DETACH status only, never the engine or the database name. So
with the leak restored and only the guard applied, the database does go Replicated, the DETACH is
refused with Code: 80, and yet the metadata is not rewritten, the ALTER succeeds and there is no
abort. That is the reviewer's own scenario measured against this tree.

Two further points: none of the six named tests is touched here, so any exposure is pre-existing
rather than introduced; and all six end by dropping the shared database, so on the ordinary path they
leave it absent rather than Replicated, which is a weaker class than the two residuals already named
in the description. Retargeting them is a wider cleanup and a separate change.

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. One debug server, no stress infra, no sanitizer: leak the shared database with 03762's body, run 04545's attach_with_gate_disabled helper on a table in it, then ALTER TABLE ... ADD COLUMN IF NOT EXISTS c Array(LowCardinality(UInt64)) under SYSTEM ENABLE FAILPOINT database_replicated_force_metadata_digest_check. Aborts every time. allow_suspicious_low_cardinality_types = 1 is required, or the ALTER is rejected with Code: 455 and never reaches the digest assertion.
b Root cause explained? Yes. In shared-database mode the lane points some clients at one long-lived database (stress.py:272) that is created once and never recreated. 03762_create_as_url_cluster.sql re-created it as Replicated; no-replicated-database cannot react because the guard reads a static CLI flag (clickhouse-test:2928). 04545's helper then had its DETACH refused with Code: 80, ignored that status, and sed -i rewrote the metadata of a live table. getMetadataHash (DatabaseReplicated.cpp:995-997) re-reads that file from disk while tables_metadata_digest still held the pre-sed hash, so commitAlterTable's assertDigest (:2663) aborted.
c Fix matches root cause? Yes. The tests that break the isolation contract are fixed. No defensive check was added to the product code and the assertion that caught this is untouched: masking it would hide exactly the corruption it exists to detect.
d Test intent preserved / new tests added? Yes. No assertion weakened, no dataset reduced, no bound widened, no tag added or removed, and no .reference file changed. 03762 still creates its table through url() inside a Replicated database, 04365 still returns 5 10 from both fileCluster reads, and 04545/03001 still edit metadata and exercise their own scenarios. The guards turn a previously silent corruption into a loud failure, which strengthens both tests.
e Both directions demonstrated? Yes, on one Build-ID-verified binary. Pre-fix: shared database Atomic to Replicated, DETACH refused, metadata rewritten, ALTER aborts with Digest does not match on the local-vs-in-memory branch (1 occurrence, 0 for the Keeper branch), stack matching the CI artifact frame-for-frame. Post-fix: database still Atomic with an unchanged UUID, DETACH succeeds, ALTER returns 0.
f Fix is general across code paths? Yes, and the carrier set is closed by census: exactly two stateless .sh tests rewrite a metadata file after a DETACH (04545, 03001), and both are fixed. A first, wider census also matched 01114_database_atomic.sh; inspected and rejected, since it uses sed as a stdout pipe filter to normalise UUIDs for its reference and never writes a metadata file. Control: 7 .sh tests use sed -i at all.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A (test-isolation fix, not a data-path change). The axis that matters is the shared database's engine, covered by the leak/no-leak and kill-path arms plus the guard-alone mutant.
h Backward compatible? Yes. Tests only, no src/ change. No SettingsChangesHistory.cpp entry, no serialization or format change, no new setting, no experimental gate.
i Invariants and contracts preserved? Yes. Invariant: a stateless test must not drop, recreate or re-engine the shared CLICKHOUSE_DATABASE; a test needing a differently-engined database uses a scratch database. The guards additionally uphold the helpers' own precondition, never rewrite the metadata of an attached table, on every path including the refused-DETACH one. ZooKeeper lifecycle checked: the {database} macro now resolves to the scratch name, DROP DATABASE removes the znode, and an immediate re-CREATE on the same path succeeds.

Session id: cron:clickhouse-impl-self-slot-57:20260807-051400

@groeneai

groeneai commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach, could you review this? It is test-only: in shared-database mode the stress lane reuses one long-lived database, 03762 re-created it as Replicated and never restored it, and a later test that rewrites on-disk metadata had its DETACH refused yet ignored the status, so sed -i edited a live attached table and the next ALTER hit the digest assertion.

@PedroTadim

Copy link
Copy Markdown
Member

@tuanpach I think the logical error is not expected?

@clickhouse-gh

clickhouse-gh Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9060bee]

Summary: ✅


AI Review

Summary

This PR hardens the two metadata-rewrite tests and moves the four current-database Replicated recreators onto {CLICKHOUSE_DATABASE_2} so they stop leaving the shared stress database Replicated. That closes the original digest-assertion path, but 03224_invalid_alter.sql still drops and recreates the shared current database earlier in the file, so the shared-database isolation contract is still incomplete under the same random-SIGTERM stress model.

PR Metadata

Changelog category: CI Fix or Improvement matches a test-only stress-lane fix.

Changelog entry: not required for this category; leaving ... is acceptable.

Findings
⚠️ Majors
  • [tests/queries/0_stateless/03224_invalid_alter.sql:68] 03224 still runs DROP DATABASE {CLICKHOUSE_DATABASE} / CREATE DATABASE {CLICKHOUSE_DATABASE} ON CLUSTER ... ENGINE = Atomic on the worker's long-lived current database earlier in the file. In the odd stress workers that database is created once at startup and never recreated per test, while stress.py can SIGTERM the client mid-file. A kill after the DROP but before the CREATE leaves the shared database missing for later tests, so the file still violates the same shared-database isolation invariant this PR is trying to enforce. Move that Atomic phase onto a scratch database as well, or otherwise stop dropping/recreating {CLICKHOUSE_DATABASE} here.
Final Verdict

Status: ⚠️ Request changes

  • Stop mutating the shared current database in 03224_invalid_alter.sql; the new {CLICKHOUSE_DATABASE_2} scratch database only covers the later Replicated phase, not the earlier DROP DATABASE {CLICKHOUSE_DATABASE} kill path.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Aug 13, 2026
Review feedback: {CLICKHOUSE_DATABASE_1} is not a per-test name. shell_config.sh:9 derives
it as ${CLICKHOUSE_DATABASE}_1 and clickhouse-test:3685-3695 passes that same value to every
.sql test in the client, so with --database (stress workers i%2==1) it is shared and, per
clickhouse-test:4046, never recreated. A run interrupted between the CREATE and the trailing
DROP therefore leaves the scratch database behind for later tests.

Measured on a leaked Replicated test_1_1: a bare CREATE DATABASE fails Code: 82
DATABASE_ALREADY_EXISTS, an IF NOT EXISTS one silently inherits the Replicated engine, and a
later DETACH TABLE is refused Code: 80. 19 of the 86 in-tree tests that create _1 have no
leading DROP, so the exposure is real.

A genuinely per-test name is not constructible in a .sql test: the runner passes only
CLICKHOUSE_DATABASE, _1 and _2, all derived from the shared name, and
{CLICKHOUSE_TEST_UNIQUE_NAME} resolves to Code: 456 UNKNOWN_QUERY_PARAMETER because it is a
shell-only export. That is why every in-tree Replicated-database-with-unique-name test is a
.sh test. Converting both tests to .sh would be a much larger diff for a narrower gain.

Move to _2 instead, which is a strict improvement on the same one-line shape: contended
consumers drop from 105 files to 3, hard-failing bare creators from 19 to 0, and all three
remaining _2 consumers already bracket with DROP DATABASE IF EXISTS. The bracketing DROPs are
kept, so an interrupted run self-heals on the next run of the test.

Verified: both tests pass in per-test and in shared-database mode; after the shared-database
run the shared database is still Atomic with no leftover; with a Replicated _2 injected
beforehand the test still passes and cleans up. Negative control: the pre-change 03762 passes
green while leaving the shared database Replicated, which is the defect this PR fixes.

The digest LOGICAL_ERROR does not relocate: the only two tests that rewrite on-disk metadata
(03001, 04545 -- the 2 of 7 sed -i users that also read metadata_path) operate in
currentDatabase() and reference neither _1 nor _2.
@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9060bee96 with master 0eb658995 (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
Binary Master PR Δ
programs/clickhouse-stripped 692.32 MiB 689.30 MiB -3.01 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

groeneai and others added 2 commits August 14, 2026 03:05
…tch database

02483 and 03224 recreated {CLICKHOUSE_DATABASE} itself as Replicated. With
--database=test_N that name is shared by every test in the client, so both left
the shared database Replicated for whatever ran next, which is the same defect
this PR closes for 03762 and 04365.

Measured in shared-database mode against a plain shared database (26.8.1.1
debug): 02483 passed green and left test_1 Replicated; 03224 likewise. After the
move both leave the shared database Atomic with no scratch leftover, and 03224's
stdout is byte-identical to the pre-change run, so the assertions are unchanged.

02483 pinned its path and its predicate to currentDatabase(); both now name the
scratch database explicitly, and its reference gains the _2 suffix because the
runner only normalizes the base name.

Not touched: 02072, 03321, 03362, 03655 and 04239 delete the shared database
outright rather than re-engining it. That is a separate class from the digest
assertion this PR is about.

Co-Authored-By: Claude Fable 5 <[email protected]>
…cated

Retargeting the last phase to the scratch database removed the only cleanup of
phase 3's test3: the old DROP DATABASE deleted it. With --database the harness
skips per-test cleanup, so test3 survived the run and 03266_with_fill_staleness_cases
does a bare CREATE TABLE test3. Verified in shared-database mode: the table was
still there afterwards, and is gone now.

The DROP pins ignore_drop_queries_probability = 0 because the stress runner sets
it to 0.2, which would make the DROP a no-op; 02354_vector_search_concurrent_readers
pins it the same way.

The retarget itself had no oracle: every renamed database is absent from the
output, so reverting it still produced the full expected result while leaking.
Assert the invariant instead of a specific engine, since the engine depends on
the runner flags. Verified by mutation: with the retarget reverted the new line
prints 1 and the test fails; with it in place it prints 0.

Co-Authored-By: Claude Fable 5 <[email protected]>
-- ignore_drop_queries_probability = 0: the stress runner sets it to 0.2, which makes a DROP a no-op.
DROP TABLE test3 SETTINGS ignore_drop_queries_probability = 0;

-- {CLICKHOUSE_DATABASE} must not be re-engined: with --database it is shared by every test in

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.

03224 still mutates the worker's shared current database earlier in the file: lines 44-46 do DROP DATABASE {CLICKHOUSE_DATABASE} followed by CREATE DATABASE {CLICKHOUSE_DATABASE} ON CLUSTER ... ENGINE = Atomic.

In the odd stress workers, clickhouse-test creates that --database=test_i only once at startup and never recreates it per test, while stress.py can SIGTERM the client mid-file. A kill after the DROP but before the CREATE leaves the shared database missing for later tests in the same worker, so this file still violates the same shared-database isolation invariant that motivated moving the later Replicated phase onto {CLICKHOUSE_DATABASE_2}.

Please move the Atomic phase onto a scratch database as well, or otherwise stop dropping/recreating {CLICKHOUSE_DATABASE} here.

@tuanpach

Copy link
Copy Markdown
Member

@tuanpach I think the logical error is not expected?

@PedroTadim Do you mean throwing LOGICAL_ERROR when the digests are mismatched?
I think we should, and it is under the DEBUG build. But I am happy to hear your reason for not throwing LOGICAL_ERROR.

@groeneai

Copy link
Copy Markdown
Collaborator Author

As the author of the PR this thread is on, the concrete instance that prompted it was test-induced, so the assertion was reporting a real divergence rather than a false one.

STID 5007-4590, Stress test (arm_tsan): in shared-database mode the lane reuses one long-lived database, 03762_create_as_url_cluster.sql re-created it as Replicated and never restored it, and 04545's helper then had its DETACH refused with Code: 80, ignored that status, and sed -i rewrote the metadata of a live attached table. getMetadataHash re-reads that file from disk (DatabaseReplicated.cpp:995-997) while tables_metadata_digest still held the pre-sed hash, so commitAlterTable's assertDigest (:2663) took the local-vs-in-memory branch (:1369-1371; the Keeper branch has 0 occurrences in the artifact). I reproduced it on a plain debug server under SYSTEM ENABLE FAILPOINT database_replicated_force_metadata_digest_check, with a stack matching the artifact frame-for-frame, and it stops reproducing once the two tests are fixed. That is why this PR is test-only and does not touch the assertion.

One scope detail, since it is what made this instance hard to diagnose: the throw is guarded by DEBUG_OR_SANITIZER_BUILD (:1295), which is !NDEBUG or any of ASan/TSan/MSan/UBSan (base/base/sanitizer_defs.h:61-66), so it also fires in sanitizer builds. Those define NDEBUG, while the diff dump next to the check is #ifndef NDEBUG (:1373, :1393), so in this artifact the assertion fired with its diagnostic compiled out and the offending table unnamed. #113009 fixes that half.

The design call is yours. Whichever way it goes, the failure it caught here was real.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9060bee

CI finished with no failing checks at this head: 177 leaves, 53 OK, 124 skipped, 0 dropped,
praktika top-level OK, Config Workflow and Finish Workflow both success.

Check / test Reason Owner / fixing PR
(none) no failures at this head -
CH Inc sync - CH Inc sync (private, not actionable)

The two earlier Stress test logical errors (STID 2508-2e0c / 2508-30f6) and
04340_autopr_input_bytes_estimation_join belong to the previous head 6b702f010cd4 and are
absent here.

Session id: cron:our-pr-ci-monitor:20260814-083000

@PedroTadim

Copy link
Copy Markdown
Member

@tuanpach I think the logical error is not expected?

@PedroTadim Do you mean throwing LOGICAL_ERROR when the digests are mismatched? I think we should, and it is under the DEBUG build. But I am happy to hear your reason for not throwing LOGICAL_ERROR.

I didn't check well. This PR is fixing tests, thanks.

@PedroTadim PedroTadim self-assigned this Aug 14, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 14, 2026
Merged via the queue into ClickHouse:master with commit fdba33b Aug 14, 2026
182 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 14, 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 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.

5 participants