Repository navigation
Conversation
Pre-PR validation gatea) Deterministic repro? Yes. b) Root cause explained? Yes. c) Fix matches root cause? Yes. The fix re-checks the file state UNDER the d) Test intent preserved? New tests added? Yes. No existing test was modified. New regression test e) Demonstrated in both directions? Yes. Verified the test FAILS on master HEAD (commit 56b7c4e) with the exact server-side stack trace ending at f) Fix is general, not a narrow patch? Yes. The pre-lock-TOCTOU + empty-file fix is in Session: cron:clickhouse-ci-task-worker:20260526-104500 |
|
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. |
b047279 to
00d5c1f
Compare
|
Workflow [PR], commit [5809d9a] Summary: ✅
AI ReviewSummaryThis PR materially improves Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 5809d9a.
Changed lines: Changed C/C++ lines covered: 156/165 (94.55%) · Uncovered code |
00d5c1f to
248182a
Compare
Pre-PR validation gateRe-run after adding Scenario C (unnamed FREEZE over a numeric
Session id: cron:clickhouse-worker-slot-4:20260610-200800 |
248182a to
1040089
Compare
Pre-PR validation gateRe-run for HEAD
Session id: cron:clickhouse-worker-slot-3:20260610-225430 |
1040089 to
bf18141
Compare
Pre-PR validation gate (HEAD bf18141)This update addresses the numeric
Session id: cron:clickhouse-worker-slot-24:20260611-001421 |
bf18141 to
aebc131
Compare
| /// 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
aebc131 to
e9ba16f
Compare
Pre-PR validation gate (HEAD e9ba16f)This update addresses the signed-range concern on
Session id: cron:clickhouse-worker-slot-2:20260611-065400 |
e9ba16f to
5b9177e
Compare
Pre-PR validation gate (HEAD 5b9177e)This update addresses the two clickhouse-gh[bot] review comments on
Session id: cron:clickhouse-worker-slot-5:20260611-081700 |
5b9177e to
a9eeacc
Compare
Pre-PR validation gate (HEAD a9eeacc, broken-disk recovery fix)
Session id: cron:clickhouse-worker-slot-19:20260611-110800 |
a9eeacc to
5183975
Compare
Pre-PR validation gate (HEAD 5183975)This round fixes the two PR-caused CI failures on the previous head (a9eeacc): a Fast test failure (
Session id: cron:clickhouse-worker-slot-0:20260611-135000 |
5183975 to
f0c38bf
Compare
CI finish ledger — e6ed506Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
None of these is caused by this PR, whose diff only touches the FREEZE/ Session id: cron:our-pr-ci-monitor:20260727-110000 |
|
Fixing PR for the It raises the test's own I had a branch ready that lowered |
e6ed506 to
da39726
Compare
| throw DB::Exception(e.code(), "File {} is empty. You must fill it manually with appropriate value.", path); | ||
| throw; | ||
| } | ||
| DB::readIntText(res, rb); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) | ||
| { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
5abc37b to
c06700f
Compare
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
c06700f to
1a8d774
Compare
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 304/373 (81.50%) · Uncovered code |
CI finish ledger - 1a8d774Every failure below has an owner: a fixing PR, or a full-effort fix task whose
Session id: cron:our-pr-ci-monitor:20260729-083000 |
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes4 object files changed (+35.96 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units7 translation units recompiled, 41 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - ede68fdEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Neither row is attributable to this diff. The The Session id: cron:our-pr-ci-monitor:20260810-023000 |
…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]>
…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]>
Closes: #105719
Motivation
A concurrent
ALTER TABLE ... FREEZE WITH NAMEandALTER TABLE ... UNFREEZE WITH NAMErace, or a writer killed betweentruncate(0)and the subsequentwriteIntTextinsideCounterInFile::add, could leave the server-globalshadow/increment.txtat size 0. Every subsequent FREEZE on the server then failed permanently withATTEMPT_TO_READ_AFTER_EOFuntil 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):
Fix
CounterInFile::adddrops the TOCTOU-unsafe pre-lockfs::existscheck, takes the exclusiveflock, then usesfstatunder the lock to determine state. A size-0 file is treated the same as a missing file: withcreate_if_needthe counter is repaired in place; without it the call throws, a missing file is not created, and an existing empty file is left untouched.MergeTreeData::freezePartitionsByMatcherwalksshadow/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 withoutWITH NAMEdoes not collide with an already-allocatedshadow/<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:webdisk 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.
DiskLocalbecomes read-only whenever write access is lost while staying fully readable and not broken, so such a disk can still holdshadow/<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 NAMEdoes with the counterA 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/0is 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 UNFREEZEremoves 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
shadowlookup 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 withcreate_if_need = false, which keeps the one property it needs and drops the one it does not: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 existingshadow/<N>/;A genuinely broken counter still fails the query: an unreadable one, a short read, content
readIntTextrejects outright, or any errno other thanENOENT. Content thatreadIntTextaccepts as a prefix (abc,12x, a value wider thanInt64) 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:
09223372036854775807is a different path from9223372036854775807and onlyFREEZE WITH NAMEcan 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, becauseshadow/<Int64 max>is reachable (recovery frommax - 1adds one) and must therefore be accounted for. That makes exhaustion reachable, where no next id exists at all, and recovery then fails withLIMIT_EXCEEDEDnaming the directory instead of overflowing the counter and reusing it.Regression tests
tests/integration/test_freeze_recover_broken_disk/test.pycovers:09223372036854775807, and a numeric plain file; a numericFREEZE WITH NAMEreserving 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;DiskEncryptedstill counting toward the bound;Int64boundary, where a backup namedmax - 1must still allowmaxto be allocated while a backup occupyingmaxitself is refused withLIMIT_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 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.cpppins theCounterInFile::addcontract directly: missing and empty files with and withoutcreate_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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix
ALTER TABLE ... FREEZEfailing permanently withATTEMPT_TO_READ_AFTER_EOFaftershadow/increment.txtwas left empty by a concurrent FREEZE/UNFREEZE race or an interrupted writer. The counter is now repaired in place from the maximum existingshadow/<N>/directory rather than requiring manual operator intervention.Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/105844]