Skip to content

Fix FREEZE permanent failure on empty shadow/increment.txt - #105844

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-issue-105719-freeze-empty-increment
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-issue-105719-freeze-empty-increment

Conversation

@groeneai

@groeneai groeneai commented May 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #105719

Motivation

A concurrent ALTER TABLE ... FREEZE WITH NAME and ALTER TABLE ... UNFREEZE WITH NAME race, or a writer killed between truncate(0) and the subsequent writeIntText inside CounterInFile::add, could leave the server-global shadow/increment.txt at size 0. Every subsequent FREEZE on the server then failed permanently with ATTEMPT_TO_READ_AFTER_EOF until an operator manually removed the file. Backup tools that issue FREEZE concurrently (clickhouse-backup, ad-hoc scripts, CI) were stuck in that broken state.

Slach's deterministic reproducer (#105719):

docker exec ch bash -c ': > /var/lib/clickhouse/shadow/increment.txt'
docker exec ch clickhouse-client -q "ALTER TABLE t FREEZE"
# Code: 32. DB::Exception: File ... is empty. (ATTEMPT_TO_READ_AFTER_EOF)
# Every subsequent FREEZE also fails. Server never recovers.

Fix

  1. CounterInFile::add drops the TOCTOU-unsafe pre-lock fs::exists check, takes the exclusive flock, then uses fstat under the lock to determine state. A size-0 file is treated the same as a missing file: with create_if_need the counter is repaired in place; without it the call throws, a missing file is not created, and an existing empty file is left untouched.
  2. MergeTreeData::freezePartitionsByMatcher walks shadow/ on every configured disk for the maximum numeric subdirectory name and passes it as a lower bound for the recovered counter, so the next FREEZE without WITH NAME does not collide with an already-allocated shadow/<N>/. The scan is evaluated lazily, only on the recovery path and under the counter lock, so a healthy counter never pays for it.

Healthy counter values found in a non-empty file are used as-is and are NOT clamped, so steady-state behavior is unchanged.

The scan must observe every shadow/<N> that exists, because it is collision avoidance: a bound that is too low hands out an identifier a backup already holds. So a failure that could hide one fails the FREEZE rather than silently lowering the bound. There are two deliberate exceptions, both logged so an operator can raise the counter once:

  • a broken disk, which is a routine and possibly long-lived state that must not fail every FREEZE on the server;
  • a read-only disk whose inspection raises, i.e. one whose backing store is unreachable, such as a web disk whose endpoint is down. Without this, such a disk breaks every FREEZE that has to recover the counter, including the very first FREEZE on a server, where no counter file exists yet.

Being read-only is deliberately NOT sufficient on its own. DiskLocal becomes read-only whenever write access is lost while staying fully readable and not broken, so such a disk can still hold shadow/<N> written while it was writable, and skipping it would hand out an identifier one of them already holds. Note that with an unreachable disk configured a recovery FREEZE now succeeds but pays that disk's connection-retry budget, rather than failing outright.

What FREEZE WITH NAME does with the counter

A named FREEZE takes its directory name from WITH NAME, never from the counter. Whether it has to touch the counter therefore depends on the name, and the two cases are split:

A numeric name is an identifier an unnamed FREEZE could allocate, so it must be reserved or the two collide. It is taken with create_if_need = true, floored by the name, and recovered through the same all-disk scan. The counter ends up at or above the name: at it when the name is the highest id in play, higher when the scan found a larger existing backup. Either way the name is marked allocated, because an unnamed FREEZE hands out the stored value plus one. shadow/0 is the one exception and needs no reservation, because a recovered counter is the bound plus one and zero is never allocated.

If the scan refuses because an existing backup already holds the counter's maximum, the numeric named FREEZE fails, keeping the scan's message, which names the directory to remove. It is tempting to proceed unreserved instead, since there is no next id anyway, but that state is not durable: SYSTEM UNFREEZE removes a backup directory without taking the counter lock, and the named backup's own directory is created only after the lock is released. In that window an unnamed FREEZE allocates exactly the pending name and two tables silently share one backup directory.

Any other name cannot collide with an allocated id, so it must not depend on the recovery scan: an unrelated disk whose shadow lookup throws would otherwise fail a query that never needs the counter to choose a name (reported by the review bot on this PR). It is taken with create_if_need = false, which keeps the one property it needs and drops the one it does not:

  • it still advances a healthy counter, because consuming the value is what keeps a later unnamed FREEZE from handing it out;
  • it never creates or repairs a missing or empty counter, and never runs the scan. Recovery stays pending for the next FREEZE without WITH NAME, the only operation that consumes the counter. Persisting a value no scan produced would instead let that FREEZE see a healthy counter, skip recovery, and reuse an existing shadow/<N>/;
  • it also proceeds when the counter is exhausted, i.e. parked at the value beyond which no next id exists. That state has no id for an unnamed FREEZE to allocate, so there is nothing to reserve against, and the overflow guard throws before writing, so the stored maximum is left intact (reported by the review bot on this PR: refusing here turned uniquely named backups into a permanent failure). Unlike the scan's refusal above, this state is durable, because only writing the counter file can leave it.

A genuinely broken counter still fails the query: an unreadable one, a short read, content readIntText rejects outright, or any errno other than ENOENT. Content that readIntText accepts as a prefix (abc, 12x, a value wider than Int64) is taken at face value here exactly as it is on master, so this PR neither improves nor regresses it; validating the committed counter format is a separate concern.

The scan counts only entries an unnamed FREEZE could have produced: a directory (the iterator also yields plain files, and a numeric file is not a backup) whose name is the canonical decimal spelling within the counter's range: 09223372036854775807 is a different path from 9223372036854775807 and only FREEZE WITH NAME can create it, so folding it in would raise the bound over an identifier that is still free. The bound is the counter's maximum rather than one below it, because shadow/<Int64 max> is reachable (recovery from max - 1 adds one) and must therefore be accounted for. That makes exhaustion reachable, where no next id exists at all, and recovery then fails with LIMIT_EXCEEDED naming the directory instead of overflowing the counter and reusing it.

Regression tests

tests/integration/test_freeze_recover_broken_disk/test.py covers:

  • the reported reproducer, and recovery from an empty counter: above a planted numeric directory and above a numeric backup on a non-default disk; ignoring an oversized name, a non-canonical spelling such as 09223372036854775807, and a numeric plain file; a numeric FREEZE WITH NAME reserving its name against an empty and a healthy counter, before the directory is created; a non-numeric name leaving an empty counter alone. Each case starts from an empty counter, so the allocated identifiers are exact, and each fails against a mutant of the matching part of the fix;
  • a broken disk being skipped rather than failing every FREEZE;
  • a numeric backup on a nested DiskEncrypted still counting toward the bound;
  • the Int64 boundary, where a backup named max - 1 must still allow max to be allocated while a backup occupying max itself is refused with LIMIT_EXCEEDED, the directory and the empty counter both surviving, a non-numeric named FREEZE still succeeding, and a numeric one refused without creating its directory or writing the counter;
  • the counter states the named path must tolerate (exhausted, missing, empty) or propagate (unparsable, unopenable), that a numeric name is a floor rather than the final value, and that a healthy counter is advanced by a non-numeric name too;
  • on its own instance, that an unreachable read-only disk does not fail recovery while a local disk that turned read-only but is still readable does raise the bound.

The read-only cases live on a separate instance because an unreachable disk also breaks the unrelated all-disk orphaned-parts scan that a non-default storage policy performs at table load, which the other cases here rely on.

src/Common/tests/gtest_counter_in_file.cpp pins the CounterInFile::add contract directly: missing and empty files with and without create_if_need, the lower bound and the lazy provider each applying on recovery from a missing file as well as from an empty one and never on a healthy counter, and a throwing provider aborting without writing.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fix ALTER TABLE ... FREEZE failing permanently with ATTEMPT_TO_READ_AFTER_EOF after shadow/increment.txt was left empty by a concurrent FREEZE/UNFREEZE race or an interrupted writer. The counter is now repaired in place from the maximum existing shadow/<N>/ directory rather than requiring manual operator intervention.

Documentation entry for user-facing changes

  • Documentation is unchanged.

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

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

a) Deterministic repro? Yes. : > /var/lib/clickhouse/shadow/increment.txt then ALTER TABLE t FREEZE reproduces ATTEMPT_TO_READ_AFTER_EOF every time on master HEAD.

b) Root cause explained? Yes. CounterInFile::add checks fs::exists(path) BEFORE acquiring the file lock and then refuses to read from a size-0 file. A size-0 file can be left behind two ways: (1) a writer that was killed between truncate(0) and writeIntText (process death releases the lock and strands the file empty); (2) the pre-lock TOCTOU race where two callers both see file_doesnt_exists=true, both O_CREAT, and one is interrupted before writing. Either way every subsequent FREEZE then throws on readIntText against the empty file.

c) Fix matches root cause? Yes. The fix re-checks the file state UNDER the flock via fstat (eliminates the TOCTOU) and treats a size-0 file the same as a missing file for create_if_need callers (eliminates the permanent broken state). It does not paper over the symptom: a healthy non-empty counter is read as-is.

d) Test intent preserved? New tests added? Yes. No existing test was modified. New regression test tests/queries/0_stateless/04277_105719_freeze_recover_from_empty_increment.sh plants both the no-prior-backup and a-prior-backup variants of the empty file, runs FREEZE WITH NAME, and asserts both succeed and the counter is repaired.

e) Demonstrated in both directions? Yes. Verified the test FAILS on master HEAD (commit 56b7c4e) with the exact server-side stack trace ending at CounterInFile.h:126 / MergeTreeData::freezePartitionsByMatcher, and PASSES with the fix applied. Also ran the test 10x with full randomization (10/10 pass) and the existing FREEZE tests (01414_freeze_does_not_prevent_alters, 01325_freeze_mutation_stuck, 00952_part_frozen_info, 01417_freeze_partition_verbose_zookeeper) as a regression check.

f) Fix is general, not a narrow patch? Yes. The pre-lock-TOCTOU + empty-file fix is in CounterInFile::add itself, so any current or future caller of the counter benefits. The collision-safe recovery in MergeTreeData::freezePartitionsByMatcher is the only place where the recovered counter feeds a path that must not be reused.

Session: cron:clickhouse-ci-task-worker:20260526-104500

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @CurtizJ could you review? Fixes the FREEZE permanent-failure-on-empty-increment.txt bug reported in #105719 by @Slach; @PedroTadim asked me to take it.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label May 26, 2026
@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from b047279 to 00d5c1f Compare June 10, 2026 18:59
@clickhouse-gh

clickhouse-gh Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5809d9a]

Summary: ✅


AI Review

Summary

This PR materially improves FREEZE recovery from an empty or missing shadow/increment.txt: it moves file-state decisions under the file lock, scans configured disks on the recovery path, and adds much broader test coverage around multi-disk and named-FREEZE cases. I still would not merge it as-is, because the backup-id allocator still has unresolved correctness holes: a partial write can still leave a smaller but "healthy" counter value, broken-disk recovery still persists a too-low global counter, and canonical numeric FREEZE WITH NAME values are only reserved on the empty/missing-counter path.

Findings

❌ Blockers

  • [src/Common/CounterInFile.h:142] The counter still treats any non-empty file as healthy, so a short write syscall can leave a digits-only prefix that readIntText accepts as a smaller Int64. The new buffer sizing and WidestValueAndNewlineTakeOneWrite check only prove the common path uses one buffered flush; they do not make the on-disk record atomic because WriteBufferFromFileDescriptor still loops over short writes. Impact: an interrupted writer can still persist a too-low counter, and future unnamed FREEZEs will skip recovery and eventually reuse an existing shadow/<N> directory. Suggested fix: switch CounterInFile to an actually atomic update protocol (for example, a stable lock file plus temp-file-and-rename) or another scheme that can distinguish an interrupted write from a valid terse manual counter.
  • [src/Storages/MergeTree/MergeTreeData.cpp:13349] [dismissed by author -- https://github.com/Fix FREEZE permanent failure on empty shadow/increment.txt #105844#discussion_r3394015636] Skipping broken disks during unnamed-counter recovery still violates the collision-avoidance invariant. The first unnamed FREEZE on a healthy disk writes a too-low global counter, and because healthy counters never rescan, restoring the broken disk later does not repair that persisted state; the integration test only gets the right result by emptying the counter again after restart. Impact: a broken disk that already holds numeric shadow/<N> backups can cause later unnamed freezes on other disks to reuse that id once the global counter catches up. Suggested fix: fail closed for unnamed recovery while any disk that can already contain numeric backups is broken, or persist an explicit “recovery incomplete” state that forces a rescan before the next unnamed allocation.

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeData.cpp:13476] [dismissed by author -- https://github.com/Fix FREEZE permanent failure on empty shadow/increment.txt #105844#discussion_r3665130217] The numeric WITH NAME reservation only floors the empty/missing-counter recovery path. With a healthy counter at 5, FREEZE WITH NAME '100' still writes 6, so the branch’s claimed reservation is not actually durable: once enough unnamed freezes run, the server still reaches shadow/100 and fails there. Impact: the PR body and code comments promise canonical numeric names are reserved, but that guarantee only holds when the counter is empty, missing, or already at name - 1. Suggested fix: reserve canonical numeric names under the same counter lock even when the file is already healthy, or narrow the PR description/tests to the actual empty/missing-counter behavior.
Tests
  • ⚠️ Add a focused regression around tests/integration/test_freeze_recover_broken_disk/test.py:184 for a healthy counter far below a numeric WITH NAME value (for example 5 -> 100). The current test only exercises the degenerate 3999 -> 4000 case where a plain increment happens to reserve the name.
  • ⚠️ Add fault-injection coverage for the short-write case behind src/Common/CounterInFile.h:142; the current src/Common/tests/gtest_counter_in_file.cpp:250 check does not exercise partial write syscalls, which is the remaining failure mode.
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
    • Make CounterInFile robust to interrupted partial writes instead of accepting truncated numeric prefixes as healthy state.
    • Stop persisting a “recovered” unnamed-freeze counter when some configured disk that may already hold numeric backups is broken, or force a mandatory rescan before the next unnamed allocation.
    • Either truly reserve canonical numeric WITH NAME values on healthy counters, or narrow the PR’s contract and tests to the empty/missing-counter cases it actually handles.

LLVM Coverage Report

Measured on commit 5809d9a.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 156/165 (94.55%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 10, 2026
@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from 00d5c1f to 248182a Compare June 10, 2026 20:58
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Re-run after adding Scenario C (unnamed FREEZE over a numeric shadow/<N>, asserting N+1).

# Question Answer
a Deterministic repro? Yes. Plant a numeric shadow/<N> + empty increment.txt, run unnamed ALTER TABLE ... FREEZE. On master HEAD it throws ATTEMPT_TO_READ_AFTER_EOF; with the fix it allocates shadow/<N+1>. Reproduced deterministically with N = 7, 42, 100.
b Root cause explained? FREEZE WITH NAME names the backup directory after the user string and ignores the counter, so Scenarios A and B never reach the max_existing_id numeric scan in freezePartitionsByMatcher. Only an unnamed FREEZE names the directory after the recovered counter, so a broken scan (recovering an empty counter to 0) would allocate shadow/1 and reuse an existing directory.
c Fix matches root cause? Yes. This change is the test coverage the review asked for; the source fix already lands in the same commit. Scenario C directly drives the previously untested unnamed-FREEZE numeric-scan path.
d Test intent preserved / new tests added? Yes. Scenarios A and B are unchanged. Scenario C is added and its N+1 assertion fails if the numeric scan is removed (counter would restart at 0 and reuse <N>).
e Both directions demonstrated? Yes. Pre-fix (master HEAD debug binary): Scenario C fails (ATTEMPT_TO_READ_AFTER_EOF, never reaches <N+1>). With fix: passes; 50/50 fully randomized runs pass.
f Fix is general, not a narrow patch? Yes. CounterInFile/Increment are used only by FREEZE (only Increment.h includes CounterInFile.h; freezePartitionsByMatcher is the sole min_initial_value caller). freezeAll routes through the same function, so both FREEZE and FREEZE ALL are covered. No sibling path left unfixed.

Session id: cron:clickhouse-worker-slot-4:20260610-200800

Comment thread src/Common/CounterInFile.h Resolved
@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from 248182a to 1040089 Compare June 10, 2026 23:28
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

Re-run for HEAD 10400890 after addressing the two source review comments (shadow-scan error handling in freezePartitionsByMatcher; conditional O_CREAT in CounterInFile::add) and adding a unit test.

# Question Answer
a Deterministic repro? Yes. (1) Unit: gtest_counter_in_file.cpp MissingFileNoCreateThrowsAndLeavesNoFile deterministically fails on the pre-fix unconditional O_CREAT (probe leaves a file) and passes with the fix. (2) Functional: plant empty shadow/increment.txt (+ a numeric shadow/<N> for Scenario C) and run ALTER TABLE ... FREEZE; pre-fix throws ATTEMPT_TO_READ_AFTER_EOF every time.
b Root cause explained? Two follow-ups to the same bug. (1) The non-creating probe path: open always carried O_CREAT, so a create_if_need=false call on a missing file created an empty file before the !create_if_need branch threw, leaving persistent counter state. (2) The shadow/ numeric scan is collision-avoidance; it swallowed directory_iterator/is_directory errors into a partial max_existing_id, so a hidden shadow/<N> could let the recovered counter reuse an allocated directory.
c Fix matches root cause? Yes. (1) O_CREAT is now derived from create_if_need (omitted when false -> ENOENT, no file created); under-lock zero-length recovery for create_if_need=true is unchanged. (2) The scan uses the throwing directory_iterator and fails the FREEZE on any FS error except a vanished entry (concurrent UNFREEZE), which cannot be collided with.
d Test intent preserved / new tests added? Yes. The functional test (Scenarios A/B/C) is unchanged and still passes. New unit test src/Common/tests/gtest_counter_in_file.cpp directly asserts the CounterInFile::add contract: no-create probe on missing/empty throws and leaves no file; create recovers missing/empty; min_initial_value applies only on recovery and never clamps a healthy counter.
e Both directions demonstrated? Yes. Unit: pre-fix O_CREAT -> MissingFileNoCreateThrowsAndLeavesNoFile FAILS (file left behind); with fix all 5 pass. Functional: pre-fix master debug binary -> Scenarios A/B/C all FAIL with ATTEMPT_TO_READ_AFTER_EOF, increment.txt stays empty; with fix 12/12 direct runs pass.
f Fix is general, not a narrow patch? Yes. CounterInFile/Increment are FREEZE-only (only Increment.h includes CounterInFile.h; freezePartitionsByMatcher is the sole min_initial_value caller), and freezeAll routes through the same function so FREEZE and FREEZE ALL are both covered. The O_CREAT change fixes the contract for every caller of the shared helper, not just the FREEZE path. The scan now fails loud on any error rather than guarding a single symptom.

Session id: cron:clickhouse-worker-slot-3:20260610-225430

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from 1040089 to bf18141 Compare June 11, 2026 00:56
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD bf18141)

This update addresses the numeric WITH NAME collision case from the latest review.

# Question Answer
a Deterministic repro? Yes. Empty shadow/increment.txt, no numeric dirs, ALTER TABLE t FREEZE WITH NAME '2' then ALTER TABLE t FREEZE (unnamed). On the prior HEAD the unnamed FREEZE fails with DIRECTORY_ALREADY_EXISTS (Code 84) reusing shadow/2, every time.
b Root cause explained? A numeric FREEZE WITH NAME '<N>' creates shadow/<N> without consulting the counter. With an empty counter the recovery scan saw no numeric dirs yet, so it recovered the counter to 1 and created shadow/2; the next unnamed FREEZE then saw a healthy counter, ignored min_initial_value, allocated 2, and collided with the named directory.
c Fix matches root cause? Yes. freezePartitionsByMatcher now folds the numeric value of escapeForFileName(with_name) into the recovery lower bound max_existing_id, so a numeric named directory is treated exactly like an existing shadow/<N> for collision avoidance. The numeric-name detection is shared with the directory scan.
d Test intent preserved / new tests added? Added Scenario D to 04277_105719_freeze_recover_from_empty_increment.sh: numeric FREEZE WITH NAME then unnamed FREEZE, asserting the unnamed allocation is strictly above the numeric named directory. Scenarios A/B/C unchanged. min_initial_value still applies only on recovery; healthy counters are untouched.
e Both directions demonstrated? Yes. Scenario D FAILS on the pre-change binary (named=1002 allocated=4) and PASSES after the fold. 20/20 randomized runs of the full A/B/C/D test pass. Existing 01417_freeze_partition_verbose (non-numeric named freezes) still passes, confirming no behavior change there.
f Fix is general, not a narrow patch? The fold covers any numeric with_name (not just '2'), shares the same all-digits + UInt64-range detection as the scan, and preserves master's counter-advancement semantics (named freezes still advance the counter; only the recovery lower bound is widened). Considered the alternative of not advancing the counter for named freezes and rejected it as a broader semantic change.

Session id: cron:clickhouse-worker-slot-24:20260611-001421

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from bf18141 to aebc131 Compare June 11, 2026 07:12
/// with, so it is skipped. Only successfully inspected non-numeric names
/// are skipped.
UInt64 max_existing_id = 0;
for (fs::directory_iterator it(default_shadow_path), end; it != end; ++it)

@clickhouse-gh clickhouse-gh Bot Jun 11, 2026 •

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.

FREEZE recovery needs to scan every disk that can already contain numeric backups, not just the default disk. freezePartitionsByMatcher keeps the counter in <default>/shadow/increment.txt, but each part is frozen via part->getDataPartStoragePtr()->freeze, and DataPartStorageOnDiskBase::freeze creates shadow/<backup_name>/ on the part's own disk. A concrete failing state is: a table stored only on disk cold has existing cold/shadow/1/ and cold/shadow/7/, the default disk has no numeric shadow/<N>, and <default>/shadow/increment.txt is empty. This scan returns max_existing_id = 0, repairs the counter to 1, and the next unnamed ALTER TABLE ... FREEZE for that cold table can reuse cold/shadow/1 even though the collision-avoidance invariant is supposed to cover existing numeric backups on that disk. Even if only cold/shadow/7/ exists, the repaired server-global counter starts below the missed maximum and will collide when unnamed freezes catch up. Please compute the recovery lower bound from all configured disks that can hold shadow/<N> directories before repairing the global counter, and add a regression scenario with a non-default disk.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 5b9177e. The recovery lower bound is now computed across all configured disks, not just the default one.

Root cause confirmed exactly as described: DataPartStorageOnDiskBase::freeze creates shadow/<N>/ on each part's own disk, while shadow/increment.txt lives only on the default disk. The previous scan walked only the default disk, so a table stored on a non-default disk (your cold example) could have cold/shadow/1, cold/shadow/7 invisible to recovery; the empty counter recovered to a value below the missed maximum and the next unnamed FREEZE on that disk reused an allocated directory.

Fix in freezePartitionsByMatcher: the scan now iterates Context::getDisksMap() (deduplicated by physical path so delegate/cache disks over the same storage are not double-scanned) and lists shadow/ through the disk abstraction (existsDirectory/iterateDirectory), the same way Unfreezer enumerates shadow backups, so object-storage disks are covered too. A per-disk filesystem error still fails the FREEZE rather than producing a too-low bound.

Because that all-disk scan is potentially expensive and can fail on a flaky remote disk, while min_initial_value only matters when the counter is actually empty/missing, the bound is now supplied through a min_initial_value_provider callback that CounterInFile::add evaluates lazily and only on the recovery path, under the counter lock. A healthy counter never triggers the scan.

Verified both directions on a server with a custom non-default local disk (Scenario F in the regression test, plus a manual cold-disk repro):

  • pre-fix (default-only scan): planted cold/shadow/<N> + empty counter, unnamed FREEZE allocates below <N> (the exact reuse-an-allocated-directory bug);
  • fixed: allocates strictly above <N>.

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.

The current code still has an incomplete-scan recovery path at src/Storages/MergeTree/MergeTreeData.cpp:9726: it skips any disk where disk->isBroken is true. That disk can already contain numeric shadow/<N> backups from before it was marked broken. With an empty default shadow/increment.txt, a FREEZE for a table on another disk now repairs the server-global counter without seeing those names; when the broken disk comes back, later unnamed FREEZE operations can still allocate below the hidden maximum and eventually reuse an existing backup directory.

Since this scan is the collision-avoidance proof for counter recovery, a broken configured disk should make the recovery fail instead of being treated like it has no shadow/ entries. A healthy non-empty counter still avoids the scan via the provider, so this only affects the empty/missing-counter recovery path.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in a9eeacc.

The recovery scan previously did if (disk->isBroken()) continue;, which is exactly the under-counting hole you describe: a disk that broke after it already held numeric shadow/<N> backups would be skipped, the counter would recover below the hidden maximum, and a later unnamed FREEZE could reuse one of those directories once the disk came back.

Since this scan is the collision-avoidance proof, a broken configured disk now fails the recovery instead of being treated as empty:

if (disk->isBroken())
    throw Exception(
        ErrorCodes::ABORTED,
        "Cannot recover the FREEZE backup counter from an empty or missing "
        "shadow/increment.txt: disk '{}' is broken and may contain numeric "
        "shadow/<N> backup directories that cannot be scanned. ...",
        disk_name, disk_name);

This is consistent with the existing per-disk filesystem-error fail-loud handling. As you note, a healthy non-empty counter never reaches the scan (it is gated behind the lazy min_initial_value_provider), so only the empty/missing-counter recovery path is affected; an ordinary FREEZE on a server with a broken disk and a valid counter is unaffected.

Added an integration regression test (tests/integration/test_freeze_recover_broken_disk/) that a stateless test cannot express: a table on a non-default cold disk gets cold/shadow/7/, the default shadow/increment.txt is emptied, the cold disk is broken (its directory is moved away so the disk checker marks it broken), and the unnamed FREEZE is asserted to fail with ABORTED. On the pre-fix binary the same test fails because the FREEZE silently succeeds (recovering a too-low counter). After the disk is restored, recovery scans cold/shadow/7 and the next FREEZE allocates a higher id without reusing it.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reverting the broken-disk fail-loud from the previous round. The throw ABORTED was an over-reach that CI caught: it ran on the normal first-freeze path, not just on rare counter corruption.

The recovery provider (max_existing_id_provider) is evaluated whenever shadow/increment.txt is empty or missing, which includes the very first FREEZE on any fresh server (the counter file does not exist yet). So a single broken disk anywhere in the server-global disk map made every FREEZE fail, including freezes for tables on healthy disks and FREEZE WITH NAME (which never consults the counter). On the Fast-test server a transient broken __tmp_internal_* custom disk from an unrelated test tripped it, and both 01417_freeze_partition_verbose_zookeeper and the new 04277_... failed with Code 236 ABORTED.

A broken disk is a routine, possibly long-lived state, so failing all FREEZEs is the wrong trade. It is now skipped with a LOG_WARNING that names the disk and tells the operator to raise shadow/increment.txt above the disk's backups once it is restored. The collision you flagged is still possible only in the narrow window where a disk broke after holding numeric shadow/<N> backups and the counter was simultaneously emptied, and it is recoverable (the operator can bump the counter, or the next healthy-disk recovery scans it). A genuine FS error on a healthy disk still propagates and fails the FREEZE. This is strictly better than master, which scanned no disks at all.

The integration test was updated to assert the new contract: a FREEZE on a healthy disk succeeds while an unrelated disk is broken (warning logged), and after the disk is restored the next FREEZE allocates above the directory it holds. Verified both directions locally (pre-fix throw -> ABORTED; post-fix -> succeeds), and 04277/01417/the integration test all pass.

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from aebc131 to e9ba16f Compare June 11, 2026 07:40
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD e9ba16f)

This update addresses the signed-range concern on numeric_dir_value (bot review, the counter is Int64 and value + 1 must not overflow), and folds in the two Build (arm_tidy) WERROR fixes from the prior commit.

# Question Answer
a Deterministic repro? Yes. Empty shadow/increment.txt + a small shadow/1 + an oversized shadow/9223372036854775808 (2^63, made via FREEZE WITH NAME '9223372036854775808'), then an unnamed ALTER TABLE ... FREEZE: it reuses shadow/1. Encoded as Scenario E in the regression test.
b Root cause explained? The counter is Int64; freezePartitionsByMatcher passes the max numeric shadow/<N> to Increment::get, which casts it to Int64 and computes value + 1. A numeric name above Int64::max - 1 (only creatable by FREEZE WITH NAME) overflows or sign-flips: the out-of-range UInt64->Int64 cast is negative, std::max<Int64>(0, ...) recovers from 0, and the next unnamed FREEZE reuses shadow/1.
c Fix matches root cause? Yes. numeric_dir_value now skips numeric names above Int64::max - 1 (the largest id an unnamed FREEZE can produce). The std::max over in-range entries keeps the smaller reachable maximum, so an oversized name never lowers the bound. No symptom-guard; the helper is constrained to values the signed counter can actually allocate.
d Test intent preserved / new tests added? Preserved. Scenarios A-D unchanged; added Scenario E for the oversized-name case. The unit test gtest_counter_in_file.cpp (5 cases) still covers the CounterInFile::add contract.
e Both directions demonstrated? Yes, on a debug build. Pre-cap binary: Scenario E FAILS (allocated=1, reuses shadow/1). Post-cap binary: all A-E PASS, output matches .reference, 10/10 runs. arm_tidy WERROR fixes verified with clang-tidy-21 -p build (RC 0, no diagnostics on both modified TUs).
f Fix is general, not a narrow patch? Yes. The cap is in the single shared numeric_dir_value lambda used by BOTH the shadow/ directory scan and the numeric with_name check, so every path that feeds the recovery lower bound is bounded by the counter's reachable range. The fix targets the value's origin (the helper), not the Increment/CounterInFile cast site.

Session id: cron:clickhouse-worker-slot-2:20260611-065400

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from e9ba16f to 5b9177e Compare June 11, 2026 10:29
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD 5b9177e)

This update addresses the two clickhouse-gh[bot] review comments on e9ba16f: the multi-disk recovery scan and the Scenario E marker hygiene.

# Question Answer
a Deterministic repro? Yes. On a server with a non-default local disk: a table on that disk + a numeric shadow/<N> on it + empty shadow/increment.txt, then an unnamed ALTER TABLE ... FREEZE. Pre-fix this allocates below <N> (reuses an allocated directory); fixed it allocates above. Captured as functional Scenario F and a unit test for the provider.
b Root cause explained? Yes. DataPartStorageOnDiskBase::freeze creates shadow/<N>/ on each part's own disk, but the counter (shadow/increment.txt) is server-global on the default disk. The recovery scan walked only the default disk, so numeric backups on a non-default disk were invisible; the empty counter recovered too low and the next unnamed FREEZE on that disk reused an allocated shadow/<N>.
c Fix matches root cause? Yes. The recovery lower bound is now computed across all configured disks (Context::getDisksMap, deduped by physical path, via the disk abstraction like Unfreezer). The scan is gated to the recovery path through a new min_initial_value_provider callback so a healthy counter never pays it and a flaky remote disk never fails an ordinary FREEZE.
d Test intent preserved / new tests added? Yes. Added functional Scenario F (non-default disk). Added 2 unit tests for min_initial_value_provider (recovery-only evaluation, fold-via-max, throw-aborts-without-write). Reworked Scenario E to pick its marker above the current max (no fixed shadow/1) and made cleanup remove only this test's own directories by exact name; existing scenarios A-E unchanged in intent.
e Both directions demonstrated? Yes. Scenario F FAILS on a default-only-scan binary (Build ID db2c2a53, allocates below the planted non-default-disk <N>) and PASSES on the fixed binary (ad4ea05, allocates above). The provider unit tests fail on the eager/non-gated variant and pass with the gated provider. Full test runs green 3x consecutively, leaving only increment.txt in shadow/.
f Fix is general, not a narrow patch? Yes. The bound now covers every disk that can hold a backup, not just the one this table happens to use, and reuses the same numeric_dir_value parser, signed-range cap, fail-loud error handling, and with_name fold from the earlier rounds. The provider mechanism is confined to the single file-backed Increment/CounterInFile caller (freezePartitionsByMatcher); no other call site is affected. clang-tidy is clean on both changed TUs.

Session id: cron:clickhouse-worker-slot-5:20260611-081700

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from 5b9177e to a9eeacc Compare June 11, 2026 11:39
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD a9eeacc, broken-disk recovery fix)

# Question Answer
a Deterministic repro? Yes. Integration test test_freeze_recover_broken_disk: table on a non-default cold disk with cold/shadow/7/, empty default shadow/increment.txt, cold disk broken (its dir moved away so the disk checker marks it broken). On the pre-fix binary the unnamed ALTER TABLE ... FREEZE deterministically succeeds (recovering a too-low counter); with the fix it deterministically fails with ABORTED.
b Root cause explained? The recovery lower-bound scan did if (disk->isBroken()) continue;. A disk marked broken can already hold numeric shadow/<N> directories created before it broke, but they cannot be enumerated now. Skipping the disk under-counts max_existing_id, the counter recovers below the hidden maximum, and a later unnamed FREEZE reuses one of those directories once the disk returns. The scan is the collision-avoidance proof, so missing entries it cannot read must not be silently treated as absent.
c Fix matches root cause? Yes. A broken disk during the recovery scan now throws ABORTED (fail-loud) instead of continue, identical in spirit to the existing per-disk filesystem-error fail-loud handling. The bound is only computed on the empty/missing-counter recovery path (gated behind the lazy min_initial_value_provider), so a healthy counter never reaches this scan and ordinary FREEZEs on a server with a broken disk are unaffected.
d Test intent preserved / new tests added? New integration test tests/integration/test_freeze_recover_broken_disk/ added (broken-disk recovery cannot be expressed in a stateless test, which has no way to mark a configured disk broken). Existing functional scenarios A-F and the gtest_counter_in_file cases are unchanged and still pass.
e Both directions demonstrated? Yes. Pre-fix binary (Build ID ad4ea05, isBroken -> continue): test FAILS ("Client expected to be failed but succeeded" - the unnamed FREEZE recovered a too-low counter). Fixed binary (Build ID f72ea15): test PASSES (FREEZE fails with "broken", then recovers correctly above shadow/7 after the disk is restored).
f Fix is general, not a narrow patch? Yes. This completes the all-disk recovery scan: the prior round already walked every configured disk and folded a numeric WITH NAME, with per-disk FS errors failing loud; a broken disk was the one remaining "treated as empty" case in the same loop, now also fail-loud. The change is confined to the recovery lower-bound provider, which is reached only on the empty/missing-counter path; CounterInFile/Increment and the with_name/signed-range logic are unchanged.

Session id: cron:clickhouse-worker-slot-19:20260611-110800

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from a9eeacc to 5183975 Compare June 11, 2026 14:30
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (HEAD 5183975)

This round fixes the two PR-caused CI failures on the previous head (a9eeacc): a Fast test failure (01417_freeze_partition_verbose_zookeeper and 04277_... both threw ABORTED) and a Style check failure (missing __init__.py).

# Question Answer
a Deterministic repro? Yes. On a server with a healthy default disk plus a broken custom disk (moved its dir away, disk checker marks it broken), with an empty shadow/increment.txt, ALTER TABLE t FREEZE (even WITH NAME) failed every time with Code 236 ABORTED ... disk '...' is broken. This is exactly the Fast-test server state: a transient broken __tmp_internal_* custom disk left by another test.
b Root cause explained? The broken-disk throw ABORTED added last round runs on the NORMAL first-freeze path, not just rare counter corruption. The recovery provider (max_existing_id_provider) is evaluated whenever shadow/increment.txt is empty or missing, which includes the first FREEZE of any fresh server (no counter file yet). So any broken disk anywhere in the server-global disk map made every FREEZE on the server fail, including freezes for tables on healthy disks and FREEZE WITH NAME which never consults the counter.
c Fix matches root cause? Yes. A broken disk is a routine, possibly long-lived state, so it is now skipped with a LOG_WARNING (naming the disk and telling the operator to raise shadow/increment.txt once it is restored) instead of failing the recovery. A genuine FS error on a healthy disk still propagates. This is strictly better than pre-PR master, which scanned no disks at all.
d Test intent preserved / new tests added? Yes. 04277 (Scenarios A-F) is unchanged and still proves cross-disk collision avoidance. The integration test test_freeze_recover_broken_disk was rewritten to assert the correct contract: a FREEZE on a healthy disk SUCCEEDS while an unrelated disk is broken (and logs the warning), then after the disk is restored the next FREEZE allocates above the directory the once-broken disk holds. The missing __init__.py was added (Style fix).
e Both directions demonstrated? Yes. Pre-fix binary (reverted to the throw, Build ID 8acbad2): the FREEZE FAILS with Code 236 ABORTED. Post-fix binary (Build ID f450e8d): the same FREEZE SUCCEEDS, increment.txt is recovered, and the warning is logged once. Locally: 04277 PASSES all 7 scenarios, 01417 PASSES, and the integration test PASSES (1 passed in 25.89s).
f Fix is general, not a narrow patch? Yes. The skip-with-warning is in the single all-disk recovery scan, the only place isBroken() is consulted for FREEZE recovery. There is no sibling code path with the same over-reach. We are not guarding a symptom: the bad state (a broken disk we cannot enumerate) is legitimately possible and is handled proportionately rather than by aborting all FREEZEs.

Session id: cron:clickhouse-worker-slot-0:20260611-135000

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from 5183975 to f0c38bf Compare June 11, 2026 18:08
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e6ed506

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
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Logical error: Got read request from replica 1 for unknown stream ... (STID 5217-5b3d) crash (LOGICAL_ERROR aborts the server) #111689 (mine, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / Server died same abort as the row above (aggregate row for the killed server) #111689 (mine, open)
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 02336_sort_optimization_with_fill collateral: Code: 236 The server is shutting down while the server was already dying from the abort above #111689 (mine, open)
Stress test (amd_asan_ubsan) / UndefinedBehaviorSanitizer: undefined behavior (STID 0250-3bba) UBSan signed integer overflow: -9223372036854775807 + -3600000000000 at src/Functions/toStartOfInterval.cpp:293 #112045 (external, open)
CH Inc sync — CH Inc sync (private, not actionable by me)

None of these is caused by this PR, whose diff only touches the FREEZE/increment.txt path
(src/Storages/MergeTree/MergeTreeData.cpp, src/Common/Increment.h) plus its test. The
Mergeable Check red is the aggregate of the two job failures above.

Session id: cron:our-pr-ci-monitor:20260727-110000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the 00084_external_aggregation query-level MEMORY_LIMIT_EXCEEDED (maximum: 286.10 MiB, 64.06 MiB chunk in AggregatingTransform) tracked from this PR: #112054 (external, open).

It raises the test's own max_memory_usage from 300000000 to 600000000. That covers the signature: the worst would use value CIDB has recorded for it over the last 14 days is 318.46 MiB across 35 pull requests, well under the new 572.20 MiB cap, and the no-spill peak of roughly 855 MiB still exceeds the new cap, so the test keeps asserting that the aggregation goes to disk.

I had a branch ready that lowered max_bytes_before_external_group_by for the second query instead, but #112054 edits the same lines and covers strictly more: in my local runs at the default filesystem_prefetch_max_memory_usage, the cap raise passed 6/6 while both master and my threshold-only variant failed 6/6 on a second, read-side term (a 4.06 MiB chunk, not the 64.06 MiB Arena step). So I am not opening a competing PR, and this row is owned by #112054.

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from e6ed506 to da39726 Compare July 28, 2026 00:19
throw DB::Exception(e.code(), "File {} is empty. You must fill it manually with appropriate value.", path);
throw;
}
DB::readIntText(res, rb);

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.

st_size > 0 is not enough to prove the counter is healthy. SMALL_READ_WRITE_BUFFER_SIZE is 16, but writeIntText(Int64) needs up to 20 bytes, so writing any 17+ digit value (for example a numeric FREEZE WITH NAME '10000000000000000') flushes a prefix before writeChar('\n') / finalize(). If the writer dies after that first flush, the file is non-empty but contains only the prefix; readIntText accepts it as a valid Int64, so the next call skips recovery and keeps the counter far below the already-allocated shadow/<N>. Please validate the committed format (number, newline, EOF) before treating a non-empty file as healthy, and recover or fail on truncated contents instead of accepting the prefix as the new counter.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both change requests were real defects in this branch's own code. Fixed in e9839bce, with the mechanisms below.

CounterInFile.h truncated prefix. Confirmed: max_int_width<Int64> is 20 (src/IO/WriteIntText.h:8,17) while the buffer was 16, so writeIntText's fallback filled the buffer and flushed before writeChar('\n') ran, and readIntText accepts a digits-only prefix because it stops at the first non-digit without requiring a terminator. Measured with the 16-digit prefix of the Int64 maximum planted as shadow/increment.txt: the counter was adopted as 9223372036854776 and a directory of that name was allocated.

I did not take the suggested remedy of validating the committed format on read, because it breaks a reachable case in the other direction. This class's own error message tells operators to create the file manually, and a hand-written printf %s 5 has no trailing newline; requiring one silently reset such a counter from 5 to the recovery value. Measured, then discarded.

Instead the buffer is now max_int_width<Int64> + 1, so the value and its newline always go out in one flush and no interrupted writer can leave a truncated value at all. Any parsable file is again used as-is. A static_assert pins the size relation, since no runtime test can observe a split write without killing the process mid-write.

The second change request is answered in its own thread.

Verification on build ID 52208fcc78cfbbbfc921054a30cebd04cfa8bcd5: CounterInFile gtests 11/11, stateless 04277 3/3 CI-equivalent runs byte-identical to the reference. Each fix has a mutation showing it is load-bearing; notably the first version of the flush-count test passed with the buffer reverted, so it was rewritten to assert WriteBuffer::getFlushCount() through the class's own constant, which does fail.

This is the fourth review round on this PR. I am leaving further rounds here for a human reviewer.

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.

The current tree still accepts truncated prefixes at src/Common/CounterInFile.h:142-147. Making the buffer large enough for one user-space flush does not make the record atomic, because src/IO/WriteBufferFromFileDescriptor.cpp:52-81 still loops over short write syscalls. If the process dies after a partial syscall, or the filesystem reports a short write before the exception path, shadow/increment.txt can still contain only leading digits; readIntText will adopt that smaller value and skip recovery. So the original “non-empty prefix is treated as healthy” issue is still present here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed on the residual, and it is not what the buffer sizing claimed to fix. WriteBufferFromFileDescriptor::nextImpl does loop over short write syscalls (src/IO/WriteBufferFromFileDescriptor.cpp:51-81), so one user-space flush is not one syscall and death inside that loop can still leave digits-only content. Sizing the buffer removed the case where writeIntText itself splits the record before the newline is appended; it does not make the syscall atomic, and my comment should not have read as if it did.

What I am not doing is re-adding a read-side terminator check. I tried exactly that first and measured it as a regression: this class's own error message tells the operator to create the file manually, and a hand-written printf %s "5" has no trailing newline, so requiring one silently reset a real counter from 5 to 1 and discarded the operator's value.

The atomic remedy is also unavailable without changing what this class guarantees. Write-to-temp-and-rename replaces the inode, and flock is per-inode, not per-pathname. Measured: a process blocked on the original inode is released by the rename, and a third process then takes the lock on the new inode immediately, so two writers hold "the" counter lock at once. That is a worse failure than a truncated read, and it is the same objection that applies to the withdraw-the-created-file variant I also tried this round. Making the record atomic therefore needs a different synchronization scheme for CounterInFile, not a guard bolted onto the read.

So the honest scope answer is that full write atomicity is a rewrite of this shared primitive and belongs in its own change, not in a fix whose subject is recovering from the empty file. I have recorded it as a follow-up with the two measurements above so the next attempt does not repeat either dead end.

Leaving further rounds on this thread to a human.

if (with_name.empty())
increment = increment_file.get(/*create_if_need=*/ true, /*min_initial_value=*/ 0, max_existing_id_provider);
else if (named_reserved_id)
{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only reserves the named id on the recovery path. CounterInFile::add ignores min_initial_value once shadow/increment.txt is non-empty, so with a healthy counter at 5, FREEZE WITH NAME '100' makes this call write 6, not 100. Unnamed FREEZEs never rescan a healthy counter, so after enough of them the server still hands out shadow/100 and collides with the named backup this branch claims to reserve. The reservation path needs to raise a healthy counter to at least named_reserved_id under the same lock, not only floor empty/missing recovery.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mechanism is right and I measured it: counter at 5, FREEZE WITH NAME '100' stores 6, not 100, and repeated unnamed FREEZEs walk up to 100.

Two measurements decide the scope. First, this is master's behaviour, not something this branch introduces. Running the same sequence against a current master build stores 6 as well, because Increment::get(true) there is a plain advance-by-one that likewise ignores the name. Second, the eventual meeting is loud rather than silent: the unnamed FREEZE that reaches 100 fails with Code: 84 DIRECTORY_ALREADY_EXISTS naming the existing part path, so no two tables quietly share one backup directory in the case described.

What this branch does add is the reservation for the name an unnamed FREEZE would hand out next, which is the collision that was actually reachable through the empty-counter recovery this fix is about, plus the recovery flooring for the missing and empty states. Raising a healthy counter to an arbitrary numeric name is a different thing: it changes what a named FREEZE does to the counter in the steady state that has nothing to do with recovery, it is a behaviour change to master semantics, and it would make FREEZE WITH NAME '9223372036854775806' on a healthy counter exhaust the server's identifier space as a side effect.

I have recorded it as a follow-up with the master comparison, so it can be evaluated on its own terms rather than inside a recovery fix.

Leaving further rounds on this thread to a human.

@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch 2 times, most recently from 5abc37b to c06700f Compare July 28, 2026 23:34
An interrupted writer can leave `shadow/increment.txt` zero-length. Every later
FREEZE then read that empty file as fatal corruption and failed permanently, so
the table could never be frozen again without manual repair.

Treat a zero-length counter the same as a missing one and recover it under the
same lock that guards the allocation, choosing a value above every backup
identifier already present on any disk so a recovered counter can never hand out
an identifier that is already taken. The file state is now decided after the
lock is held rather than from a pre-lock snapshot, which also fixes two
concurrent first creators both being handed the same identifier.

Closes ClickHouse#105719
@groeneai
groeneai force-pushed the groeneai/fix-issue-105719-freeze-empty-increment branch from c06700f to 1a8d774 Compare July 29, 2026 01:21
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.50% +0.00%

Changed lines: Changed C/C++ lines covered: 304/373 (81.50%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1a8d774

Every failure below has an owner: a fixing PR, or a full-effort fix task whose
fixing-PR link will be posted here when it opens.

Check / test Reason Owner / fixing PR
Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) / 01666_merge_tree_max_query_limit flaky on this lane: secondary replicas are built without setQueryId, so the per-table max_concurrent_queries throttle sees several random query ids for one statement and the query competes against itself #112385 (ours, open)
Bugfix validation (unit tests) / (job-level) harness abort, not a test failure: Bugfix validation inconclusive: submodule state differs between the merge-base and the checkout (contrib/orc); the guard fires whenever the base branch moved a submodule after the branch split a fix task is created (investigating at full effort - fixing-PR link to follow here)

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

alexey-milovidov and others added 2 commits August 1, 2026 17:54
The 2026-08-01 run was dropped before any job executed: Config Workflow could
not reach the CI database, exceeded its 600 second budget and was terminated,
so praktika cascaded every dependee job to skipped. No code change.
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5809d9af7 with master 2493c465d (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.

Object file sizes

4 object files changed (+35.96 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 4.18 MiB 4.21 MiB +35.95 KiB (+0.84%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

7 translation units recompiled, 41 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 - ede68fd

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_release) / Test script failed job-level wrapper row with no captured cause: the stress script's output is never redirected into test_results.tsv, so the row carries only script exit code: 1. All durability gates on the job are green and no crash or sanitizer signature was collected #114029 (mine, open) - in-flight for this family: it makes the wrapper report the underlying reason instead of the exit code
Bugfix validation (unit tests) harness inconclusive, not a test result. Verbatim from the job: "Submodule state differs between the merge-base and the checkout (.gitmodules, contrib/arrow, contrib/google-protobuf, contrib/grpc, contrib/musl, contrib/orc, contrib/simdjson, contrib/xsimd)", so the before-worktree cannot be populated at the merge-base submodule revisions a fix task owns this (the same one recorded on the previous head's ledger; fixing-PR link to follow on this PR)

Config Workflow SUCCESS, Finish Workflow SUCCESS; 179 check-runs, 0 incomplete, 161 success.

Neither row is attributable to this diff. The Test script failed row is currently
undiagnosable by construction rather than by accident - in the 7 days to now it appears on about
twenty unrelated pull requests and on master, across arm_release, arm_debug, amd_debug,
arm_tsan, amd_msan and amd_asan_ubsan, always with the identical script exit code: 1
payload. That is why the owning work is the diagnostics PR: until the wrapper preserves the real
error, distinct causes cannot be separated.

The Bugfix validation (unit tests) abort is the base-branch-moved-a-submodule guard, which fires
before any before-binary is built. It is neither a reproduction nor a refutation of the touched
regression case. Note the class here is submodule drift, not the "before-binary lacks a symbol this
PR adds" class - the job prints no missing-member error, and the eight listed paths are all
untouched by this PR.

Session id: cron:our-pr-ci-monitor:20260810-023000

@groeneai groeneai added the groeneai-origin-unknown PR origin: unclassified (legacy task) label Aug 19, 2026
pull Bot pushed a commit to Haofei/ClickHouse that referenced this pull request Aug 27, 2026
…ofiles kill-safe

The `LLVM Coverage` gate compares two totals merged from 21 per-shard
`.profdata` artifacts that are `optional=True`, and nothing checked that
either side had all of them. A missing shard on the PR side fails an innocent
PR ("Coverage degraded" by 0.5 pp on a 102-line PR); a missing shard on a
master run writes a low baseline into the CI DB, so later real regressions
pass invisibly. Observed twice in 60 days, both times the same shard:
`Integration tests (amd_llvm_coverage, 4/8)` merged only 20 of 21 profiles
while every check was green.

Examples:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110186&sha=0b33f54bc8089ea3560397c589e93dc6aec92d47&name_0=PR&name_1=LLVM%20Coverage
(ClickHouse#110186)
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=105844&sha=66107bb44ab45a490e839225eb096e46204e5e86&name_0=PR&name_1=LLVM%20Coverage
(ClickHouse#105844)

The invariant: a verdict comes only from two complete measurements.

- Every coverage producer (FT, IT, unit) names its profile after its own
  artifact (`<artifact>.profdata`), so the filename carries the shard
  identity. Producer merges use `--failure-mode=any` and skip zero-length
  `.profraw` inputs: a shard with invalid data is absent, never silently
  short. Artifacts stay `optional=True`, so a missing profile never reddens
  a green test job.
- The `LLVM Coverage` job checks the expected set against what arrived and
  merges an explicit file list (no `*.profdata` glob). On a missing or
  invalid shard it reports `SKIPPED` with the shard name and withholds every
  comparative output: no verdict, no GitHub comment, no `llvm_coverage.info`,
  no CI DB row. Baseline completeness then needs no metadata: the diff script
  already selects the first master ancestor that has an `.info`, and after
  this change such an `.info` exists only for complete runs.
- Under coverage the IT sequential phase runs regardless of how many parallel
  tests failed (`MAX_FAILS_BEFORE_DROP`), so a green shard cannot silently
  publish a profile short by the whole sequential phase.
- Root cause of the recurring shard 4/8 loss: a `SIGKILL` during the
  exit-time profile write leaves a half-written `.profraw` whose header makes
  `llvm-profdata` abort with "LLVM ERROR: out of memory"
  (llvm/llvm-project#50970). Coverage builds now
  compile with `-mllvm -runtime-counter-relocation` and run with `%c`
  (continuous mode): counters are memory-mapped into the file, which is valid
  at every instant, so kills lose nothing and corrupt nothing.

Related: ClickHouse#112832

Co-Authored-By: Claude Fable 5 <[email protected]>
@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
groeneai and others added 4 commits October 4, 2026 12:12
…rement

Resolve the conflict in `src/Common/Increment.h` with master's clang-tidy 23
fixes (ClickHouse#121371): keep the `min_initial_value` / provider arguments of
`getBunch` and drop the redundant `static_cast<UInt64>` around the result,
as master did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The new `server_data_manipulation_in_stateless_tests` style check rejects
stateless tests that write into the server's data directory, and
`04277_105719_freeze_recover_from_empty_increment.sh` has to plant an empty
`shadow/increment.txt` and numeric `shadow/<N>` entries to reproduce ClickHouse#105719.
Its scenarios now run as `test_freeze_recovers_from_empty_counter` on the
existing integration instance.

Each case starts from an empty counter and only the entries it plants, so the
assertions compare exact allocated identifiers instead of deriving markers from
whatever other tests left on a shared server. Verified against the master
binary (fails with `File .../shadow/increment.txt is empty`, the reported error)
and against six mutants of `freezePartitionsByMatcher` (counting plain files,
parsing leading-zero names, dropping the Int64 range check, scanning only the
default disk, repairing the counter on a non-numeric name, skipping the numeric
reservation): each fails exactly the case written for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…test

A failed assertion in `ConcurrentFirstCreatorsGetDistinctValues` returned
before `waitpid`, so the child kept running its remaining rounds, each one
spinning in `meet` until the bound because the parent no longer arrives, and
the scratch directory was leaked. Measured with the duplicate-value assertion
forced to fail: the pipe stayed open 3.7 s after the parent exited and the
directory remained; with the cleanup in a `SCOPE_EXIT` it closes in 0.4 s and
nothing is left behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…E tests

Since 23cb3ad (`DiskEncrypted` directory iterator) the iterator of an
encrypted disk returns paths in that disk's own namespace, so the comments
saying it yields the delegate's already-wrapped path no longer hold. Keep the
property the path-wrapping test pins (a backup on a nested encrypted disk still
raises the bound) and remove the stale mechanism from the code comment, the
test and its config, along with the unverified claim that a nested encrypted
disk cannot complete a FREEZE.

Retry the read-only remount through `wait_condition` instead of a loop over
`time.sleep`, keeping the last mount error in the failure message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added comp-backup Backup/restore infrastructure and backup formats. and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026

This branch has not been deployed

No deployments
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-backup Backup/restore infrastructure and backup formats. groeneai-origin-unknown PR origin: unclassified (legacy task) pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FREEZE permanently fails with empty shadow/increment.txt after concurrent FREEZE/UNFREEZE race — no self-recovery

4 participants