Skip to content

Stop the parts cleanup in three transaction tests that read a rolled back part - #118377

Merged
alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:stop-cleanup-in-rolled-back-part-transaction-tests
Sep 20, 2026
Merged

alexey-milovidov merged 3 commits into
ClickHouse:masterfrom
groeneai:stop-cleanup-in-rolled-back-part-transaction-tests

Conversation

@groeneai

@groeneai groeneai commented Sep 6, 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):

Fixed a flaky failure of three transaction tests that read a rolled back part from system.parts.

Description

01172_transaction_counters, 04057_transaction_version_metadata_lifecycle and 04060_transaction_snapshot_visibility assert that a part created by a rolled back transaction is still listed in system.parts with creation_csn = 18446744073709551615. The background parts cleanup can delete it first, and the run loses that line:

 4	all_1_1_0	1	(0,0,'00000000-0000-0000-0000-000000000000')	0
-4	all_2_2_0	18446744073709551615	(0,0,'00000000-0000-0000-0000-000000000000')	0
 4	all_3_3_0	0	(0,0,'00000000-0000-0000-0000-000000000000')	0

MergeTreeTransaction::rollback removes the part with clear_without_timeout = true, so remove_time = 0 and grabOldParts may take it at any old_parts_lifetime; canBeRemoved is true outright for RolledBackCSN. SYSTEM STOP MERGES does not stop that remover: MergeTreeCleanupThread has its own blocker, taken only by SYSTEM STOP CLEANUP, so 01172's -- stop background cleanup comment was wrong and is repaired here. One public sighting, with the query below; 04057 and 04060 carry the identical assertion.

Fix, per test: SYSTEM STOP CLEANUP <table> beside SYSTEM STOP MERGES, plus merge_tree_clear_old_parts_interval_seconds = 100000 in the CREATE TABLE (precedents 04338_replace_partition_no_resurrect_after_restart.sql, 04813_merge_over_rolled_back_gap_part.sh). The statement alone is not a barrier: run checks the blocker once, before iterate, so the iteration queued at CREATE TABLE can still run its parts pass; the pinned interval shuts that pass. No assertion or .reference byte changes. A suite-wide remove_rolled_back_parts_immediately = 0 is ruled out by 01173_transaction_control_queries.sql:83, and the arm below shows it does not help anyway.

All three also take no-shared-merge-tree: IStorage::getActionLock returns an empty lock by default and ActionLocksManager::add keeps it only if (!action_lock.expired()), so on an engine without ActionLocks::Cleanup the statement blocks nothing, and 02491_part_log_has_table_uuid.sh records that StorageSharedMergeTree removes parts from PartsKillerThread on the server-wide parts_kill_delay_period instead, which a .sql test cannot pin. The tag is honored under --cloud and --replace-replicated-with-shared; a lane setting only --replace-non-replicated-with-shared rewrites the engine without honoring it, which I left to the harness rather than change a predicate 111 other tests share. Public CI sets none of the three flags.

The public sighting, the measured arms, and why not remove_rolled_back_parts_immediately = 0

The sentinel row has to be removed and not replaced, otherwise the needle also matches the
unrelated non-transactional-insert shape:

SELECT check_start_time, pull_request_number, check_name FROM default.checks
WHERE test_name = '01172_transaction_counters' AND test_status IN ('FAIL','ERROR')
  AND base_repo = 'ClickHouse/ClickHouse' AND position(test_context_raw,'result differs') > 0
  AND position(test_context_raw, concat(' -4', char(9), 'all_2_2_0')) > 0
  AND position(test_context_raw, concat(' +4', char(9), 'all_2_2_0')) = 0

2026-06-15 01:02:23   62614   Stateless tests (arm_asan_ubsan, azure, parallel)

04057's and 04060's older AsyncInsert-lane failures are that different, already-blacklisted
mechanism. The forcing below is merge_tree_clear_old_parts_interval_seconds = 0,
cleanup_delay_period = 1 and a 2 s delay before the assertions; 5 runs per test per arm, plus 50
randomized runs per test on the final tree (150/150).

tree under test 01172 04057 04060
unchanged 0/5 pass 0/5 pass 0/5 pass
+ SYSTEM STOP CLEANUP only 5/5 5/5 5/5
+ the pinned interval only 5/5 5/5 5/5
+ remove_rolled_back_parts_immediately = 0 0/5 pass 0/5 pass 0/5 pass
+ the 2 s delay only, no cleanup settings 5/5 5/5 5/5
this PR, forcing minus the pinned setting 5/5 5/5 5/5

The statement-only arm is green because this forcing cannot land inside the startup window; that
window is closed by reading run and iterate, not by an arm. remove_rolled_back_parts_immediately = 0 does not help at all: it only disables the creation_csn == Tx::RolledBackCSN disjunct in
grabOldParts while reached_removal_time stays true through remove_time = 0. The delay-only arm
shows the failure comes from the cleanup.


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

Version info

  • Merged into: 26.10.1.244-master (included in 26.10 and later)

…back part

`01172_transaction_counters`, `04057_transaction_version_metadata_lifecycle` and
`04060_transaction_snapshot_visibility` assert that a part created by a rolled back transaction is
still listed in `system.parts` with `creation_csn = RolledBackCSN`. Nothing keeps it there.

`MergeTreeTransaction::rollback` marks the part `RolledBackCSN` and then removes it from the
working set with `clear_without_timeout = true`, which stores `remove_time = 0`. In `grabOldParts`
the subtraction is therefore from 0, not from the rollback time, so
`time_now - remove_time >= old_parts_lifetime` holds for any lifetime below the current Unix time and
the `old_parts_lifetime=3600` these tests set does not hold the part; `VersionMetadata::canBeRemoved`
returns true outright for `RolledBackCSN`.

The remover is `MergeTreeCleanupThread`, a dedicated `BackgroundSchedulePool` task, and two timers
gate it. Its first iteration cannot remove a part, because `start` restarts the parts stopwatch
just before scheduling it and the `merge_tree_clear_old_parts_interval_seconds` gate (1 second) is
therefore still shut. The next iteration lands `cleanup_delay_period` plus up to
`cleanup_delay_period_random_add` later, 30-40 s with defaults, so a run slow enough to still be
inside the assertions by then loses the row.

`SYSTEM STOP MERGES` does not stop it: merges are gated by `merges_blocker`, the cleanup thread by
`IMergeTreeCleanupThread::cleanup_blocker`, which only `ActionLocks::Cleanup` takes. 01172's
"stop background cleanup" comment above `system stop merges` was therefore describing something that
statement does not do, and is repaired here.

`SYSTEM STOP CLEANUP` on its own would leave a narrower version of the same race. `run` tests the
blocker once, before `iterate`, and taking the lock only increments an atomic counter, so an
iteration that started while the table was being created and is then delayed past the one-second
gate still runs its parts pass and still takes the part. `merge_tree_clear_old_parts_interval_seconds`
is therefore pinned in each `CREATE TABLE` as well: the stopwatch is restarted inside `start`, so no
iteration can reach the pinned interval during the test, in flight or not.
`04813_merge_over_rolled_back_gap_part.sh` pins the same setting for the same reason.

Pinning `remove_rolled_back_parts_immediately = 0` instead does not work, because it only disables
the third disjunct in `grabOldParts` while `reached_removal_time` stays true through
`remove_time = 0`. Measured with the cleanup forced: that arm still fails 5/5 on all three tests,
while `SYSTEM STOP CLEANUP` passes 5/5.

No assertion and no `.reference` byte changes.

`01173_transaction_control_queries` has the inverse dependency, needing the rolled back parts of its
earlier rollbacks to be gone, which is why this is fixed per test rather than with a server-level
`remove_rolled_back_parts_immediately = 0` in `tests/config`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Independent review rounds before publishing. Nothing blocking is left open.

  • ❌ The first draft guarded the race with SYSTEM STOP CLEANUP alone. That statement only
    increments an atomic counter, and run tests the blocker once, before iterate, so the cleanup
    iteration queued while the table was being created can pass that check, be delayed past the
    one-second parts gate, and still take the part. merge_tree_clear_old_parts_interval_seconds is
    now pinned in each CREATE TABLE as well, as 04813_merge_over_rolled_back_gap_part.sh does.
  • ❌ The first draft's root-cause paragraph said the parts cleanup is "gated only by
    merge_tree_clear_old_parts_interval_seconds (default 1 second)". Corrected: the cleanup task's
    wake-up is gated by cleanup_delay_period (+ cleanup_delay_period_random_add), and its first
    iteration cannot remove a part at all, because start restarts the parts stopwatch just before
    scheduling it. First possible removal is 30-40 s after CREATE TABLE, which is why this fails
    about once a quarter and only on the slowest lane.
  • ❌ "true for any finite old_parts_lifetime" was too strong: with remove_time = 0 the predicate
    is time_now >= old_parts_lifetime, and 02899_restore_parts_replicated_merge_tree.sh relies on
    a lifetime above the current Unix time to keep a rolled back part alive.
  • ⚠️ Literal SQL names in the added comments were not in backticks (AGENTS.md line 7). Fixed at all
    three sites.
  • 💡 01172's detach/attach constructs a new storage, so the table-scoped Cleanup lock stops
    applying from that point; the pinned interval, being table metadata, survives it and start
    restarts the stopwatch again. The lock is deliberately not re-issued: no assertion after the attach
    needs the rolled back part anyway, since they all filter on active or read
    system.transactions_info_log, and dropPartition locks only visible parts.
  • 💡 02421_truncate_isolation_no_merges.sh:133 guards the same remove_time = 0 fixture with
    system stop cleanup alone and keeps the default one-second parts gate, so by the finding above it
    retains the startup-window exposure that is closed here. Left alone on purpose: its assertion is a
    RemovePart row in system.part_log rather than a missing system.parts row, 2 of its 19 failures
    in 90 days carry that shape across 2 pull requests, and its fixture is a shared helper used by six
    subtests, so it is not the same one-line change. Flagging it rather than fixing it here, since I
    have not reproduced it.
  • 💡 tests/integration/test_transactions reads the same sentinel but is not affected: its
    assertions follow a restart, so the parts come from the metadata-load path and keep
    remove_time = std::numeric_limits<time_t>::max(), which fails grabOldParts' first conjunct.

On the published commit an independent read of the tree and the second-model gate both came back
clean; the last corrections were to this description, not to the tests.

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

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Forcing the race with merge_tree_clear_old_parts_interval_seconds = 0, cleanup_delay_period = 1, cleanup_delay_period_random_add = 0 plus a 2 second delay before the assertion, each of the three tests fails 5/5 with exactly the recorded shape (one line lost, neighbours intact). The unmodified tests pass 3/3 through the same harness, so the scaffold is not the oracle.
b Root cause explained? Yes. MergeTreeTransaction::rollback removes the part with clear_without_timeout = true, storing remove_time = 0; in grabOldParts the subtraction is therefore from 0, not from the rollback time, so time_now - remove_time >= old_parts_lifetime holds for any lifetime below the current Unix time and the old_parts_lifetime=3600 these tests set is inert, and VersionMetadata::canBeRemoved returns true outright for RolledBackCSN. MergeTreeCleanupThread then grabs the part, gated by two timers: its first iteration cannot remove anything, because start restarts the parts stopwatch just before scheduling it and the merge_tree_clear_old_parts_interval_seconds gate (1 second) is therefore still shut, and the next iteration lands cleanup_delay_period plus up to cleanup_delay_period_random_add later, 30-40 s with defaults. SYSTEM STOP MERGES does not stop it because cleanup has a separate blocker.
c Fix matches root cause? Yes, and the guard is deliberately two-part. SYSTEM STOP CLEANUP takes ActionLocks::Cleanup, the lock that actually gates grabOldParts, and it durably stops every cleanup iteration that starts after it. It is not a barrier, though: run tests the blocker once, before iterate, and taking the lock only increments an atomic counter, so the iteration queued while the table was being created can still reach its parts pass. merge_tree_clear_old_parts_interval_seconds = 100000 in each CREATE TABLE covers exactly that one, because the stopwatch is restarted inside start and the settings are re-read on every iteration. Not a widened bound, not a blanket no-random-* tag, not a reduced dataset. The alternative of pinning remove_rolled_back_parts_immediately = 0 was measured and does NOT fix it, because reached_removal_time stays true through remove_time = 0.
d Test intent preserved / new tests added? Preserved exactly: every assertion and every .reference byte is unchanged, and the part is still required to be present and to carry RolledBackCSN. The existing oracle becomes reachable rather than weakened. No new test: this is a test-side timing fix, no source change.
e Both directions demonstrated? Yes for the reproducible path, and stated precisely for the rest. Under identical forcing the pre-fix files fail 5/5 on all three carriers, with the diff exactly the recorded shape, and the files as shipped here pass 5/5; the pin alone, without the statement, also passes 5/5, so each half of the guard is exercised on its own. Post-fix, 50/50 randomized runs pass for each carrier (150/150), plus a control run with randomization off, and one run per carrier against the unchanged .reference. The in-flight window itself is not reddened by any arm, and it cannot be from a test-only diff: forcing it needs a stall between the blocker check in IMergeTreeCleanupThread::run and the interval gate in MergeTreeCleanupThread::iterate, and there is no failpoint on that path. Its necessity is argued from source; its remedy is measured against the reproducible path.
f Fix is general across code paths? Yes. grep -l rollback intersected with grep -l system.parts over tests/queries/0_stateless gives 8 files. The 3 that assert a rolled back part is present are all fixed in this one push; 02421_truncate_isolation_no_merges.sh already has system stop cleanup and 04813_merge_over_rolled_back_gap_part.sh already pins the settings; 04058_transaction_concurrent_removal.sh and 04310_alter_rename_column_settings_rollback.sh read only active parts, so an Outdated rolled back part cannot affect them. 01173_transaction_control_queries.sql has the inverse dependency and is disclosed in the description.
g Fix generalizes across inputs (params/datatypes/wrappers)? N/A for the type axis: no source change and no type dispatch. The setting axis that could plausibly matter was measured instead (remove_rolled_back_parts_immediately, old_parts_lifetime), and SYSTEM STOP CLEANUP is independent of both.
h Backward compatible? Yes, trivially: no setting default, no SettingsChangesHistory.cpp entry, no format change, no gate. SYSTEM STOP CLEANUP requires SYSTEM_CLEANUP on the table, which the stateless default user has.
i Invariants and contracts preserved? Yes. The action lock is per table and released at test teardown. I checked the one way this fix could redden a currently green assertion: keeping the part alive adds an Outdated row, and 04057's in_removal_txn_removal_tid_set counts non-active parts. Measured with the part held alive it still returns exactly the 2 rows its reference expects, because the rolled back part keeps removal_tid = (0,0,'00000000-0000-0000-0000-000000000000') and fails that query's predicate. 01172's detach/attach drops the lock, which is harmless because no assertion after it needs the rolled back part, so the lock is deliberately not re-issued.

Session id: cron:clickhouse-impl-slot-4:20260906-034000

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [73526cd]

Summary: ✅


AI Review

Summary

This PR stabilizes three transaction stateless tests by explicitly stopping cleanup, pinning merge_tree_clear_old_parts_interval_seconds, and skipping SharedMergeTree modes where that guard is unsupported. I re-read the current diff, the surrounding clickhouse-test skip/rewrite logic, and the existing thread discussion; I do not see a remaining correctness or coverage gap in the current tree. In particular, the previously disputed --replace-non-replicated-with-shared path does not preserve the original flaky assertion path, because transactional writes are rejected there before any rolled back part can be created.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

cc @tuanpach, could you review this? It stops the parts cleanup in 01172, 04057 and 04060, which assert a rolled back part is still listed in system.parts: rollback stores remove_time = 0, so old_parts_lifetime does not hold the part and SYSTEM STOP MERGES does not stop the remover. #117822 also touches 04057_transaction_version_metadata_lifecycle.sql, but its earliest hunk starts below my insertion and git merge-tree against master is clean.

@tuanpach tuanpach self-assigned this Sep 6, 2026
@tuanpach

tuanpach commented Sep 6, 2026

Copy link
Copy Markdown
Member

@groeneai Check the CI failure.

@clickhouse-gh clickhouse-gh Bot added the comp-testing Test content only (no production code). label Sep 6, 2026
@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

The red on the PR page is a cancelled duplicate workflow run, not a test failure. I re-measured before answering:

Two PR workflow runs exist for 5e8c8a92735870cfac48bbd9fe2ec39dab2749eb: 34012052935, cancelled at 04:40:24Z, and 34012047343, still in progress. clickhouse-gh[bot] closed and reopened the PR at 04:39:28Z and 04:39:29Z, one second apart, which is where the second run comes from.

All 117 fail rows in gh pr checks belong to the cancelled run, each with duration 0. The only failure on this PR with a non-zero duration is that same cancelled run's own Finish Workflow (41s). Every pass, pending and skipping row belongs to the live run, which has 16 successful jobs, 31 skipped, 6 in progress and zero failed.

CIDB records no test-level failure:

SELECT check_name, test_name, test_status FROM checks
WHERE pull_request_number = 118377 AND test_status IN ('FAIL', 'ERROR')

0 rows, against 14976 ingested rows for the same commit (14589 of them Fast test, plus 5 successful builds).

For a test-only change the flaky check is the signal that matters here, and it has passed on the two arms that have finished: all three changed tests ran 50 times each on amd_msan and amd_tsan, 300/300 OK. The amd_debug, amd_binary and amd_asan_ubsan flaky checks are still running.

CI is not finished, so I am not calling it green yet. I will post the finish ledger here when it completes, and follow up if a real failure appears.

@groeneai

groeneai commented Sep 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5e8c8a9

CI is fully finished at this commit and no check failed, so no ledger row is owed.

The reading in my previous comment holds. Run 34012047343 concluded success, and every one of the 170 cancelled/failure check rows on this commit belongs to the cancelled duplicate run 34012052935, not to the live one. Deduplicated by name, the commit has 170 check runs: 42 success, 128 skipped, nothing else. Config Workflow, Style check, Fast test and Finish Workflow are all green, the last of them at 07:16:40Z.

CIDB agrees at test level: 0 rows with test_status IN ('FAIL', 'ERROR') and 0 with a failed check_status, against 70040 ingested rows for this commit across 43 checks, 66054 of them OK.

For a test-only change the flaky check is the signal that matters, and it is now green on all five arms (amd_debug, amd_binary, amd_asan_ubsan, amd_msan, amd_tsan): each of the three changed tests ran 50 times per arm, 150/150 OK on every arm, 750/750 in total.

Session id: cron:our-pr-ci-monitor:20260906-080115

@tuanpach tuanpach closed this Sep 7, 2026
@tuanpach tuanpach reopened this Sep 7, 2026
`SYSTEM STOP CLEANUP` installs a blocker only when the storage hands back a
non-empty lock. `IStorage::getActionLock` returns `{}` by default
(`IStorage.h:651`) and `ActionLocksManager::add` keeps the lock only
`if (!action_lock.expired())` (`ActionLocksManager.cpp:44`), so on an engine that
does not implement `ActionLocks::Cleanup` the statement succeeds and blocks
nothing. `StorageMergeTree` is the only public engine that implements it
(`StorageMergeTree.cpp:3652`).

`02491_part_log_has_table_uuid.sh` and `02950_part_log_bytes_uncompressed.sh`
already record that `StorageSharedMergeTree` does not implement
`ActionLocks::Cleanup` and removes parts from `PartsKillerThread` on the
server-wide `parts_kill_delay_period` (`ServerSettings.cpp:1379`, "Only available
in ClickHouse Cloud"), which a stateless test cannot pin. Neither guard this PR
adds therefore holds the rolled back part once `--cloud` or
`--replace-non-replicated-with-shared` rewrites `ENGINE = MergeTree` to
`SharedMergeTree` (`clickhouse-test:283` and `:4109-4119`), and the assertions
keep the race they were meant to close.

The tag is enforced at `clickhouse-test:3053` (`--cloud`) and `:3176`
(`--replace-replicated-with-shared`); a lane that sets only
`--replace-non-replicated-with-shared` substitutes the engine without honoring
the tag. Public CI sets none of the three flags, so the public `MergeTree` lanes
run all three tests unchanged: every executed line is byte-identical to the
previous commit, only comments and the `Tags` line move.
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 58f7c10

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
Stress test (arm_tsan) / Cannot start clickhouse-server Not this PR's diff. The restart fails metadata load with Code: 36 ... Path does not exist: /var/lib/clickhouse/user_files/05057_file_rename_after_processing_write_grant_test_<uniq> ... while loading database fsdb_05057_... on all 11 start attempts: the Filesystem database that test 05057_file_rename_after_processing_write_grant creates over its own user_files directory outlives that directory when the stress kill interleaves with the test's teardown. First sighting of this signature in 30 days of CIDB (1 row, 0 master SHAs; the rocksdb Cannot start clickhouse-server family is a separate 22-row bucket). a fix task is created (investigating at full effort, fixing-PR link to follow here)
Stress test (arm_tsan) / Check failed Job-level fallout of the startup failure above (Check failed with exit code 1), not an independent failure. a fix task is created for the startup failure it reports (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika aggregators, red only because they report Failed: Stress test (arm_tsan). No independent failure. a fix task is created for the Stress test (arm_tsan) startup failure they report (investigating at full effort, fixing-PR link to follow here)

Control for the rest of the run, so the single red check is stated against a non-empty baseline: 70416 CIDB
rows on this commit across 37 checks report check_status = success, 8 skipped, and the only failure rows
are the 4 belonging to Stress test (arm_tsan).

Session id: cron:our-pr-ci-monitor:20260907-150153

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the three Stress test (arm_tsan) rows in the ledger above: #118684.

DatabaseFilesystem validated its backing directory in the constructor, so once the user_files directory that 05057_file_rename_after_processing_write_grant creates a Filesystem database over is gone, startup metadata replay throws Code: 36 and the server cannot boot at all. #118684 tolerates a missing path only while the server replays its own stored metadata, logging a warning; a user CREATE/ATTACH DATABASE over a missing path still fails.

Not merged yet, so the row can reappear on a re-run until it lands. Still not caused by this PR's diff.

huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 12, 2026
…the comment

`05136_database_filesystem_missing_path_on_load` sent the second
`clickhouse local` invocation's stderr to `/dev/null`, which discarded the only
text that identifies the defect: without it a base-build failure is a bare
missing-lines stdout diff, on the sole regression test for a "server cannot
start" fix. The redirect suppressed nothing that a green run emits. A bare
`clickhouse local` sets `logger.level` to `fatal` unless one of
`logger.console`, `logger.level`, `log-level` or `logger.log` is given, so the
tolerated path's `LOG_WARNING` never reaches stderr; `shell_config.sh` builds
`--send_logs_level` into `CLICKHOUSE_CLIENT` only, never into
`CLICKHOUSE_LOCAL`; and the first invocation in the same test already ran
unredirected. Measured after removing it: stderr is empty on the fix build and
50 randomized runs stay green, while the base build now reports
`Code: 36 ... Path does not exist: ... while loading database ... from file
metadata/fsdb.sql. (BAD_ARGUMENTS)`.

Also reword the second sentence of the `is_internal_metadata_replay` comment.
It justified the exclusion by who supplies the path, which is false for the
short `ATTACH DATABASE db` form: that reads `metadata/<db>.sql`, replays the
stored definition and supplies no path of its own, yet still throws, because
`args.internal` is false. Name the discriminator that actually decides it.
`RESTORE` is internal too and is excluded by the mode term instead, so the
wording claims only what the guard does.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#118377

Co-Authored-By: Claude Opus 5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 12, 2026
…ssing path

The previous commit's guard was `args.internal && args.mode >= ATTACH`, on the
assumption that `internal` means the server generated the statement. It does
not. `InterpreterParallelWithQuery::executeSubquery` runs every `PARALLEL WITH`
child through `executeQuery(..., QueryFlags{ .internal = true })`, and
`InterpreterExecuteAsQuery::execute` does the same for `EXECUTE AS`, so a
statement a user writes arrives at `DatabaseFactory` with `internal` set.
`PARALLEL WITH` is gated by no setting and DDL children are its canonical use.

Measured on a server: `ATTACH DATABASE d ENGINE = Filesystem('<missing>')` is
rejected with `Code: 36`, while the same statement followed by
`PARALLEL WITH DROP TABLE IF EXISTS <absent>` was accepted, wrote
`metadata/d.sql`, and survived a restart. Both plain forms already threw, so
only the wrapped form reached the tolerant branch.

Add a third conjunct, `args.replays_stored_definition`, computed by the
interpreter one line above the factory call as `create.attach &&
!need_write_metadata`. That expression already means "the definition being
attached is the one stored in `metadata/`", so this reuses the interpreter's own
answer instead of inventing a second notion of replay. A definition supplied
with the query is never a stored one, wrapper or not. The change moves in one
direction only: strictly fewer statements reach the tolerant branch, and a
genuine startup replay still evaluates all three terms true, which
`05136_database_filesystem_missing_path_on_load` continues to assert.

`02921_database_filesystem_path_check` gains the wrapped `ATTACH` arm. Its
sibling is `DROP TABLE IF EXISTS`, whose pipeline is empty, so the assertion
does not depend on the order the children run in or on what `max_threads`
randomizes to. Dropping the new conjunct while keeping the plumbing reddens
that arm with `The query succeeded but the server error '36' was expected`.

The sibling engines that share the two-term predicate are left alone: the same
laundering reaches them, but that belongs with the wrapper rather than with each
engine.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#118377

Co-Authored-By: Claude Opus 5 <[email protected]>
huldarchen pushed a commit to huldarchen/ClickHouse that referenced this pull request Sep 12, 2026
The previous commit's third conjunct was `create.attach && !need_write_metadata`,
which it described as "the definition being attached is the one stored in
`metadata/`". It does not test that. `need_write_metadata` is
`!create.attach || !existsFile(metadata/<name>.sql)`, so the conjunct only tests
whether the NAME already has a stored definition; whether the definition being
executed came from that file is never checked. The file is read solely in the
short-syntax branch (`!create.storage && create.attach`), which a long-syntax
`ATTACH DATABASE ... ENGINE = ...` skips. `DETACH DATABASE` leaves the metadata
file in place (`DatabaseCatalog` removes it only when dropping, and
`DatabaseFilesystem::shouldBeEmptyOnDetach()` is false), so two ordinary
statements arrange the precondition.

Measured on a server, twice, with `buildId()` asserted against the binary:

    CREATE DATABASE d;
    DETACH DATABASE d;
    ATTACH DATABASE d ENGINE = Filesystem('<missing>')
      PARALLEL WITH DROP TABLE IF EXISTS <absent>;

was accepted, and `system.databases` then reported `d` with engine `Filesystem`
over a path that does not exist, while `metadata/d.sql` still held the original
`ENGINE = Atomic` definition. The same shape via short syntax, after removing
the directory of a real `Filesystem` database, was likewise accepted. Both plain
forms threw `Code: 36`, so `internal`, laundered by the wrapper, was again the
term being defeated.

Feed the decision from the loader instead of deriving it from the statement.
`InterpreterCreateQuery` gains `setIsMetadataReplay`, called only from
`executeCreateQuery` in `loadMetadata.cpp`, beside the `setInternal(true)` that
startup metadata replay already performs. Nothing else can reach it: `QueryFlags`
has no route to an interpreter member, so no SQL sets it. A dedicated flag rather
than the adjacent `setLoadDatabaseWithoutTables` because that one means "defer
table loading", not "this is a replay".

With the loader answering directly, `args.internal` leaves the predicate: the
same call site sets both, so it decided nothing. `args.mode >= ATTACH` is kept as
the idiom the sibling engines use; it is not independently provable by mutation
here, because a replayed `Filesystem` definition is always an `ATTACH DATABASE`
statement and therefore always that mode.

`isLoadingFromExistingMetadata` remains unusable for this: a database is replayed
under plain `ATTACH`, unlike tables, which use `FORCE_ATTACH`, so the helper never
matches a database load.

`02921_database_filesystem_path_check` gains the name-aliasing arm in pure SQL,
and re-attaches before dropping, since a database left detached keeps a metadata
file that every later start replays. `05136_database_filesystem_missing_path_on_load`
gains the sharper arm: the definition a start has just replayed is refused to a
user who replays it by hand, plainly and wrapped, and the start after each
rejection attaches the database again. Restoring the previous predicate reddens
both arms, the wrapped `05136` line flipping while its plain line stays green,
which is exactly the statement class that was reachable before.

The sibling engines that share the two-term predicate are still left alone: the
laundering reaches them too, and belongs with the wrapper rather than with each
engine.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118377&sha=58f7c10d1c3a06e4661e9b38aa3d45dc6b268a96&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29
ClickHouse#118377

Co-Authored-By: Claude Opus 5 <[email protected]>
@tuanpach

Copy link
Copy Markdown
Member

@groeneai Check the CI failure.
Any PR fixing them?

@groeneai

Copy link
Copy Markdown
Collaborator Author

Yes, both of them, and both are already merged.

The only red at 58f7c10d was Stress test (arm_tsan): the stress restart could not bring the server back up, failing every one of its 11 start attempts with

Code: 36. DB::Exception: Path does not exist: /var/lib/clickhouse/user_files/05057_file_rename_after_processing_write_grant_...
  while loading database fsdb_05057_...

Mergeable Check and PR were red only as fallout of that one job (1 failure, 45 success, 124 skipped at that commit). The carrier is 05057_file_rename_after_processing_write_grant, which this PR does not touch: the diff here is three transaction test files.

Fixing PRs, both merged after that run:

I merged master into the branch (73526cd) to pick both up, so CI is re-running now.

@tuanpach

Copy link
Copy Markdown
Member

@groeneai, any CI jobs or issues linked to this fix?

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI jobs yes, issues none. The provenance here is CI evidence only.

The public witness. The exact shape (the rolled back part's row removed and not re-added) has one public row in the last 180 days, and none in the last 90:

Stateless tests (arm_asan_ubsan, azure, parallel), PR 62614, 2026-06-15 01:02:23, report.

Re-measured on default.checks today over 180 days with base_repo = 'ClickHouse/ClickHouse': 01172_transaction_counters has 286 FAIL/ERROR rows, of which only 2 are result differs with reference and exactly 1 is this shape (the row above); the equivalent predicate for 04057_transaction_version_metadata_lifecycle and 04060_transaction_snapshot_visibility returns 0. No row of this shape on public master. The shape itself reached me from a private mirror master run that I cannot link here. 04057 and 04060 are in the fix because they carry the identical assertion, and the failure reproduces on all three locally (0/5 before, 5/5 after; arms table in the description).

The other red rows on these tests are different mechanisms. 67 of 04057's and 67 of 04060's 180-day rows are on Stateless tests (amd_llvm_coverage, AsyncInsert, s3 storage, parallel), where whole assertion blocks go missing and values change: that is the async insert flush race, already handled by tests/async_insert_blacklist.txt:28,35,36. 01172's other result differs row drops the transactions_info_log block instead of the part row.

Issues. Nothing open. The closed ones on these test names are those other shapes, not this one: #103152, #102932 (04057) and #103151 (04060) are the auto-generated flaky test issues for the AsyncInsert shape; #68165 (01172, 2024) is the transactions_info_log shape, which I checked against its CIDB row rather than assuming.

If you want an issue tracking this one, say so and I will open it.

@alexey-milovidov alexey-milovidov self-assigned this Sep 19, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 19, 2026
Merged via the queue into ClickHouse:master with commit d3977b5 Sep 20, 2026
177 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 20, 2026
@clickhouse-gh clickhouse-gh Bot added comp-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... and removed comp-testing Test content only (no production code). labels Nov 22, 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-transactions MergeTree transactions (MVCC): BEGIN / COMMIT / ROLLBACK, the transaction log and manager, part v... groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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