Skip to content

Reclaim objects left by a DROP interrupted on a plain_rewritable disk - #118465

Open
alexey-milovidov wants to merge 61 commits into
masterfrom
fix-plain-rewritable-drop-orphans
Open

alexey-milovidov wants to merge 61 commits into
masterfrom
fix-plain-rewritable-drop-orphans

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Closes: #114051
Related: #111804
Related: #118490

On a plain_rewritable disk, operations commit a change in the metadata first and delete the objects in finalize. If the server is killed in between, the objects must not stay in the bucket forever. The main part of the fix is already on master. It came in through #118490, which was based on an earlier version of this branch: reserved removed names, tombstone markers, rollback of pending removals and replacements, and reclamation on the initial load.

This PR adds the remaining pieces on top of master:

  • Metadata-only operations on a directory with an explicit file list (unlinkFile, the metadata-only moveFile/replaceFile, and a rewrite of a file to a new blob) drop the last link to a blob by rewriting prefix.path, and delete the blob only in finalize. Nothing under the prefix of an explicit directory is listed on load, so a kill in between leaked the blob forever. Such an operation now writes a marker with the key of the blob first (PlainRewritableLayout::BLOB_REMOVAL_TOMBSTONE_PREFIX). finalize deletes the marker after the blob, and undo deletes it after restoring prefix.path. On the writable initial load, the blob is deleted if no live directory links it anymore and kept otherwise. Then the marker is deleted.
  • If some directory object has no logical path (it may be a directory of a pending removal whose prefix.path was being rewritten), or the metadata object of the root is empty (an interrupted rewrite of the root's explicit file list), the markers of pending removals and blob removals are kept instead of being deleted.
  • The reclamation of orphaned objects on load is best-effort, so a failure there does not prevent the disk from loading. The markers are removed last, so the cleanup is retried on the next start.
  • The temporary names of the operations are generated until they are absent from the filesystem, because copyObject would overwrite an existing look-alike name created by an older version.
  • RemoveRecursiveOperation::undo removes its marker through undoWithRetries.
  • The marker of a pending replacement escapes the name of the target if it contains a line feed (PlainRewritableLayout::PENDING_REPLACE_ESCAPED_TOMBSTONE_PREFIX), so an existing file with such a name can be replaced by replaceFile. The content of the marker for any other name is not changed.
  • Transactions that remove different links to the same shared blob are serialized by locks on the keys of the shared blobs (KeyLocks). This way the transaction that removes the last link sees it in its own snapshot and removes the blob through the marker, instead of the blob losing its last link only when the changes are published. A path that an earlier operation of the same transaction moved a file or directory to is resolved back through the moves, so a removal after a move takes the same locks.

A new case is added to test_s3_plain_rewritable_crash_recovery: test_unlinked_blob_of_explicit_directory_is_reclaimed.
The serialization by KeyLocks is covered by the new unit tests ConcurrentUnlinkOfDifferentLinksToSharedBlob and ParallelUnlinkOfDifferentLinksToSharedBlob (also with a move followed by an unlink). BlobRemovalMarkersOfInterruptedCleanup runs a real unlink, replacement, and rewrite in an explicit directory with failing deletions in finalize, and checks that the markers name the old blobs and that the next load reclaims them. EmptyRootMetadataKeepsBlobRemovalMarkers covers the empty root metadata object. ReplaceOfFileWithLineFeedInName covers the replacement of a file with a line feed in its name, including the rollback of an interrupted replacement on the next load.

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

Fixes a permanent leak of objects in object storage on plain_rewritable disks (such as s3_plain_rewritable) when the server is killed after removing or replacing a file in a directory with an explicit file list (hard links) but before the blob is deleted. Such blobs are now deleted when the server loads the disk metadata on the next start.

🤖 Generated with Claude Code


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

@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1af106a]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 2/6) FAIL Performance dashboard
h3_polygon_to_cells #0 FAIL dashboard
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Reviewed head 1af106a49bdb976470771c8a96859d468f0831b9. The PR adds recoverable blob removals, serialization of shared-blob removals, atomic local metadata writes, and startup cleanup for plain_rewritable disks. The latest change preserves newline-bearing replacement targets through a separate escaped marker format. Two object-key containment gaps remain; block pending their resolution. New marker forms were traced through parseTombstoneMarkerContent, loadRemoteLayout, findTargetsToReadFromBackups, and the snapshot reader's backup overlay. Prior discussion was rechecked against current code; addressed points and accepted tradeoffs are omitted.

Findings

❌ Blockers

  • PlainRewritableLayout.cpp:158: isValidBlobKey accepts s3://other-bucket/victim.bin. With a supported empty disk prefix, object-key construction preserves it, and the S3 deletion path interprets it as another bucket. A blob-removal marker or an explicit file list under a committed recursive removal can therefore delete outside the disk's namespace using its credentials. Reject qualified object paths before accepting these keys. A standalone source-extracted C++ probe confirmed validation succeeds and routes deletion to bucket other-bucket, key victim.bin.

  • PrefixPath.cpp:92: The containment check does not cover snapshot.bin. The existing readPlainRewritableSnapshot reads blob keys without validation, and read-only disks apply the layout directly. A snapshot entry with /other-prefix/victim.bin reaches constructBlobObjectKey, discards the configured prefix, and is read by S3 without a containment check. Snapshot-supplied remote directory paths also affect default blob keys. Validate the effective key returned by getBlobKey for every snapshot entry, or enforce containment centrally before object-key construction. This alternate path is pre-existing and remains uncovered by the new invariant.

Missing context / blind spots
  • ⚠️ The current head's full unit and integration CI results were not available at review time; builds and the workflow remained in progress. Fast test and Style check passed. See the current-head Praktika report. No ClickHouse server tests were run locally; the standalone probe validates key construction and routing, not a complete server exploit.
Tests
  • ⚠️ Add an empty-prefix S3 recovery case with a qualified key and a sentinel in another bucket; startup must leave the sentinel untouched. Cover blob-removal markers and committed-subtree file lists.
  • ⚠️ Add a read-only snapshot case with an outside-prefix sentinel. Cover explicit blob keys and default keys derived from remote directory paths; neither may initiate an outside-namespace read.
Final Verdict

Status: ❌ Block

Close both key-containment gaps and add the focused regressions above. Two new inline findings were submitted together in one review; no existing threads were reopened or replied to.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... labels Sep 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1af106a49 with master 1506a9e15 (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

13 object files changed (+137.21 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFro… 923.59 KiB 960.99 KiB +37.40 KiB (+4.05%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/PlainRewritableLay… 99.80 KiB 127.69 KiB +27.89 KiB (+27.94%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Transactions/KeyLo… new 25.59 KiB +25.59 KiB
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/ObjectStorages/Local/LocalObjectStorage.cpp.o 335.06 KiB 353.02 KiB +17.96 KiB (+5.36%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFro… 587.40 KiB 605.12 KiB +17.72 KiB (+3.02%)

716 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

34 translation units recompiled, 239 s compile time in total, 33 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The single red check on b9314ae4 — Stateless tests (arm_asan_ubsan, azure, sequential) — is a known master-wide flake, unrelated to this pull request.

Both failures are distributed-plan tests, in a subsystem this pull request does not touch (it changes plain_rewritable recursive removal):

  • 04648_distributed_plan_task_error_propagation — Expected server error code: 439 but got: 1000
  • 04340_distributed_plan_status_reenqueue_fault — result differs with reference

The harness re-ran both in isolation and each passed 3/3 (Failed 0 out of 3 reruns), which is the signature of cross-test contamination rather than a regression.

This exact pair is tracked in #118626: failing fleet-wide since 2026-09-06 on master itself (pull_request_number = 0) as well as dozens of unrelated pull requests — 49 failures across 31 distinct pull requests for 04648, 44 across 25 for 04340 — and most of those hits are in this same arm_asan_ubsan, azure, sequential job. Per-test issues: #118831, #118832.

Root cause and fixes are already in progress: a fail point armed with SYSTEM ENABLE FAILPOINT is server-wide, so a test that never reaches its own SYSTEM DISABLE FAILPOINT leaves it armed for every later test in the sequential batch.

I have not re-run the job: the leak comes from a neighbouring test in the same batch, so a re-run is a coin flip until #118863 lands, at which point merging master will clear it. LLVM Coverage, CH Inc sync and the PR rollup are still running.

@clickhouse-gh

clickhouse-gh Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 1 query(s) improved out of 31 analysed

This PR only changes plain_rewritable disk metadata: blob-removal markers, locks on blobs shared between files, writing metadata in a single write, and cleanup when the disk loads. None of that runs in ClickBench or TPC-H SELECTs, so no flagged change can reasonably be traced to it. The 7-17% slowdowns in the GROUP BY queries (Q16, Q18, Q31-Q34) all fall inside master's normal range, and two clickbench runs shared a host. Q20's -41.4% stays an improvement because it meets the hard trust thresholds and CPU dropped with it, but nothing in the diff explains it; a baseline or build difference is more likely, so do not credit it to this PR.

clickbench

🟢 1 improved · ⚠️ 7 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 20 improvement 220 129 -41.4% <0.0001 The -41.4% is large and backed by a CPU drop, so the hard trust rule locks it. The diff only touches plain_rewritable metadata writes and recovery, so a baseline or build difference is the likelier cause than this PR.
⚠️ 16 not_sure 530 601 +13.4% <0.0001 aggregation: This is a GROUP BY query that stays inside master's normal range. The PR only changes plain_rewritable disk metadata transactions, which this read path never runs.
⚠️ 18 not_sure 848 992 +17.0% 0.0005 aggregation: The +17.0% sits inside master's normal range and the query's history is noisy. No changed code runs during this SELECT.
⚠️ 28 not_sure 1058 1133 +7.0% 0.0020 Borderline +7.0%, the two tests disagree, and the measurements were noisy. The query does not run any code this PR changes.
⚠️ 31 not_sure 257 283 +10.1% <0.0001 aggregation: The +10.1% is inside master's normal range. Nothing in the plain_rewritable metadata changes runs during this aggregation.
⚠️ 32 not_sure 742 871 +17.3% 0.0003 aggregation: The +17.3% is inside master's normal range and the measurements were very noisy. This SELECT does not touch any changed code path.
⚠️ 33 not_sure 1049 1125 +7.2% 0.0003 aggregation: The +7.2% is inside master's normal range and the query's history is noisy. The PR does not touch this code path.
⚠️ 34 not_sure 1046 1126 +7.5% 0.0002 aggregation: The +7.5% is inside master's normal range and the query's history is noisy. The PR does not touch this code path.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: b089d848-8a89-41b4-b46a-58da4fb29c18
  • MIRAI run: a34b7aaa-cf92-40c7-be9c-49fead30c487
  • PR check IDs:
    • clickbench_71100_1791935163
    • clickbench_71106_1791935163
    • clickbench_71120_1791935163
    • tpch_adapted_1_official_71160_1791935163
    • tpch_adapted_1_official_71183_1791935163
    • tpch_adapted_1_official_71205_1791935163

alexey-milovidov added a commit that referenced this pull request Sep 26, 2026
…e-narrow-metadata-lock

Pull in #118465: the leftovers of a committed removal live under
reserved `__removed.` names with a marker object, so `load` never ingests them and the initial load reclaims them.
This addresses the review finding that a failed post-commit cleanup could leave scratch objects that a later
`SYSTEM DROP DISK METADATA CACHE` would load as metadata.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 This change is now merged into #118490 (commit e0b51af), where it resolves a review blocker about leftovers of a failed post-commit cleanup being loaded back. Keeping this PR open until #118490 lands; it can be closed then.

alexey-milovidov and others added 4 commits October 3, 2026 04:05
…etry the marker cleanup in `undo`

On a read-only disk, a refresh or a `SYSTEM DROP DISK METADATA CACHE` reload no longer drops the subtree of
a pending removal: nothing can be removing it in this process, so it keeps being shown under its original
path, as on the initial load. Only a writable non-initial load skips it.

`RemoveRecursiveOperation::undo` now removes the tombstone marker through `undoWithRetries`, like the other
marker cleanups, so that a transient object storage error does not stop the rollback of the transaction.

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

Master added a fast path in `MetadataStorageFromPlainRewritableObjectStorage::load` that reuses the known
`DirectoryRemoteInfo` of an unchanged directory without reading its `prefix.path`. This PR added the
`is_orphaned` and `object_path` fields to `DirectoryLoadResult`, so the new initializer has to fill them.
A directory found in the snapshot is never an orphaned removal: those are never put into the layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits October 5, 2026 21:55
…-effort

The deletion of objects left by unfinished removals runs after the layout is
already installed. A failure there must not prevent the disk from loading:
the leftovers stay hidden while their markers exist, and the markers are
removed last, so the cleanup is retried on the next start.

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

Names of the shape of `generateRemovedName` created by older versions are
ordinary data, and `copyObject` overwrites the destination. Generate the
temporary names of `UnlinkMetadataFileOperation`, `MoveFileOperation`
(`replaceFile`) and `RemoveRecursiveOperation` until they are absent from the
filesystem snapshot and distinct from each other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e-drop-orphans

Master added real hard links and the explicit file lists to `plain_rewritable`.
Conflict resolution:
- `RemoveRecursiveOperation`: the blobs to delete are collected in `execute` (as on master,
  keeping the blobs shared with files outside of the removed subtree), but the data objects
  and the `prefix.path` objects are kept apart and deleted in `finalize` in two passes
  before the tombstone marker, as in this PR.
- `UnlinkMetadataFileOperation` and `MoveFileOperation`: the metadata-only paths of master
  need no temporary copies; the blob-copy paths use the reserved, marked temporary names.
- `checkNotReservedPath` is kept for `createHardLink`, `moveFile`, `replaceFile`.
- The reclamation on load deletes the blobs of an orphaned directory by their blob keys,
  and skips the blobs that are still referenced by a live directory with an explicit
  file list (hard links). The root files directory is listed for the leftovers of committed
  removals even when the root has an explicit file list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (8eea585) and resolved the conflicts with the real hard links / explicit file lists of plain_rewritable:

  • RemoveRecursiveOperation collects the blobs to delete in execute like master (keeping blobs shared with files outside the subtree), and finalize still deletes data objects, then prefix.path objects, then the marker.
  • The metadata-only paths of unlink/move need no temporary copies; the blob-copy paths keep the reserved, marked temporary names.
  • The reclamation on load now deletes an orphaned directory's blobs by their blob keys and skips blobs still referenced by a live directory with an explicit file list. The root files directory is listed for committed-removal leftovers even when the root has an explicit file list.

test_s3_plain_rewritable_crash_recovery and test_s3_plain_rewritable pass locally (12/12).

alexey-milovidov and others added 2 commits October 7, 2026 04:08
…s of implicit directories

The startup rollback of a pending `RemoveRecursive` rewrote only the logical path
of the `prefix.path` object, dropping the explicit file list and the blob keys of
a directory with hard links. Serialize the full contents with `serializePrefixPath`.

The cleanup of orphaned blobs subtracted only the keys referenced by live explicit
directories, but the source side of a hard link stays in an implicit directory under
its default key. Subtract the keys of all live directories, including the root,
whose files are listed only after the other directories.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…kers if a directory is unreadable

`LocalObjectStorage` writes to the final key directly, so a process that dies
while writing a tombstone marker can leave it empty or truncated. Previously
any content that did not start with `pending\n` was taken as a committed
removal, and a truncated pending marker rolled the subtree back to a truncated
path. Now both forms end with the removed name (committed: exactly the removed
name; pending: `pending\n<path>\n<removed name>`), and any other content is
malformed: nothing under that name is loaded, moved back, or deleted, and the
marker stays.

Also, a directory object without a logical path may be a directory of a
pending removal whose `prefix.path` was being rewritten when the process died.
It cannot be moved back, so in that case the pending markers are kept instead
of being deleted after the rollback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/118465/802f6cede412a36d459a9cddb9f71312c9a14523/pr/ast_fuzzer_amd_release_oracle/job.log (AST fuzzer (amd_release, oracle): TLP Aggregate oracle mismatch for count() with message LIKE '%pa%' OR message LIKE '%pb%' on a text-indexed table, with use_text_index_pattern_bypass_cache and text_index_like_max_postings_to_read = 5). This is unrelated to this PR, which only touches plain_rewritable disk metadata. Please provide a fix in a separate PR. If a fix is already in progress, link it here.

alexey-milovidov and others added 3 commits November 5, 2026 14:18
…not be read

When reading the metadata object of a listed directory failed with `NO_SUCH_KEY`,
Azure `NotFound`, or `ENOENT`, the directory was silently skipped, so it contributed
no references to the reconciliation of the blob-removal markers. A transient `404`
on a directory that still links a blob named by a marker would then delete the live
blob permanently. Treat such a skipped read as an incomplete inventory, the same as
an empty directory object: keep the pending markers and the blobs until a later load
reads every directory.

Add `UnreadableDirectoryKeepsBlobRemovalMarkers`, which injects `ENOENT` on the read
of the directory that links the blob; it fails without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (25a5566, clean merge; the only overlap is unrelated new code in FailPoint.cpp, ObjectStorageFactory.cpp, and gtest_disk_object_storage.cpp). The changed translation units compile. The only red check on 731a98e was CH Inc sync (the sync PR conflicted with private master). I fixed it by overlaying the PR files onto private master, so the sync PR is MERGEABLE again. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (e4670fd, clean merge; the only overlap is unrelated new code in FailPoint.cpp and ObjectStorageFactory.cpp). The changed translation units compile. There are no unresolved review threads.

The only red check on 026f4b0 is Build profile diff, which is unrelated to this PR: the readiness probe of the CI logs cluster timed out (Read timed out. (read timeout=3), then LogClusterNotReady: the endpoint never became ready), see https://s3.amazonaws.com/clickhouse-test-reports/PRs/118465/026f4b05dceec54d033acade2a59db59ad82442c/pr/build_profile_diff/job.log. The fix for this classification is in progress in #129675.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (f0ebe7e, clean merge; the only overlap is an unrelated new failpoint in src/Common/FailPoint.cpp). The changed translation units compile. There are no unresolved review threads.

The only red check on e4670fd is Build profile diff, which is unrelated to this PR: the CI logs cluster never became ready (LogClusterNotReady: the endpoint never became ready), see https://s3.amazonaws.com/clickhouse-test-reports/PRs/118465/e4670fd19969d108914b5ff3453a24fe55e6a149/pr/build_profile_diff/job.log. A fix that classifies this as a CI logs cluster outage is in progress in #129675.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (a62d3fd, clean merge; it overlaps this PR only in src/Common/FailPoint.cpp (an unrelated new failpoint) and an added include in gtest_metadata_plain_rewritable_disk.cpp). The changed translation units compile. There are no unresolved review threads.

The only red check on f0ebe7e was CH Inc sync (tests failed). The private sync PR's failures are unrelated to this PR:

  • 05345_hash_join_row_store_strings and 05483_smt_condemned_part_removal_by_storage hit max_rows_to_read (TOO_MANY_ROWS) on queries over system.text_log.
  • 05497_s3_concurrent_insert_new_file reported acknowledged writers: 2 instead of 1 with the s3 table engine. This PR changes only plain_rewritable metadata and the local object storage.
  • 01079_parallel_alter_modify_zookeeper_long timed out after 600 seconds.

The new push re-runs the sync.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (1e2fc59, clean merge). The changed translation units compile against it. The only CI failure on d57ab6c, AST fuzzer (amd_debug) (Inconsistent AST formatting for a fuzzed CREATE TABLE ... CODEC(FirstApplicable(..., toTypeName | indexHint(_), ...))), is unrelated to this PR: the f | g composition operator was formatted wrongly inside CODEC arguments. The same failure hit about 15 other PRs and master on 2026-11-11. The fix is #125567, which was already on master and was not yet in this branch; this merge brings it in. A remaining (NOT x) | f variant is tracked in #130934. There are no unresolved review threads.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (cb1a0d5, clean merge). The only CI failure on 92c30d1, Build (arm_tidy, 4/4), was a compile error in gtest_s3_object_storage_explicit_settings.cpp, which this PR does not touch. It came from a master-side createClientConfiguration signature change, and the test is already fixed on master, so the merge brings in that fix. Finish Workflow failed only as a consequence, because the bugfix-validation jobs were dropped after the build failure. The changed translation units and that gtest compile locally. There are no unresolved review threads.

…is incomplete, validate keys of markers

When a directory object could not be read on startup, its references are
unknown. The blob-removal markers were already kept in that case, but the
objects of committed recursive removals were still deleted: a blob shared
with a file of the unreadable directory looked unreferenced and was deleted
with the subtree and its marker. Now nothing is reclaimed on such a load;
the leftovers stay hidden behind their markers and the next start retries.

The key of a blob is taken from the content of a blob-removal marker and
the blob is deleted, so an absolute key, `.`/`..` components, NULs, or a key
under `__meta` could name an object outside of the blobs of the disk. Such
markers are now `Malformed` and cause no deletion. The target of a pending
replacement, which is overwritten from its backup, is checked the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits November 19, 2026 00:37
…oved blob referenced during rollback

The keys of the blobs of a directory in the explicit form are read from its
`prefix.path`, and the blobs of an orphaned subtree are deleted on load. Only
the keys of blob-removal markers were checked with `isValidBlobKey`, so an
absolute key (or one with `..`, or under `__meta`) in a damaged or forged
file list could name an object outside of the disk. `parsePrefixPath` now
rejects such keys with `INCORRECT_DATA`, which makes the load fail and
deletes nothing.

The metadata-only branch of `MoveFileOperation::undo` restored the target
directory before the source one. After a cross-directory replacement only
the target references the moved blob, so a process that died between the
two rollback writes (or a rewrite of the source that failed for good) left
the blob linked from nowhere, and no marker named it. The rewrites are now
reversed in the reverse order of `execute`.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits November 21, 2026 16:48
… disk

The name of a file may contain a line feed, and then the key of its blob
contains it too. A hard link writes this key to the explicit file list of
the target directory (`prefix.path`), where it is escaped with
`writeEscapedString`. `isValidBlobKey` rejected a line feed, so
`parsePrefixPath` threw `INCORRECT_DATA` for such a file list on the next
load, and the disk could not be loaded.

`isValidBlobKey` no longer rejects a line feed: it only keeps the
containment checks. The marker of a blob removal now escapes the key the
same way as the file list instead of refusing a key with a line feed, so
the last link to such a blob in an explicit directory can be removed. The
content of the marker still ends with a line feed that is not escaped, so a
torn content is never taken for a complete one.

The new unit test `HardLinkOfFileWithLineFeedInName` covers the round trip
of the marker, the reload of the metadata, and the removal of the last link.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@stresshouse

stresshouse Bot commented Nov 21, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

No performance change can be attributed to this PR. It only changes how plain_rewritable object-storage disks write and recover their metadata: blob-removal markers, locks on shared blobs, atomic metadata writes and cleanup at startup. The only flagged row, clickbench Q10 (+20.7%, 111 ms vs 92 ms), was held at not_sure automatically because it falls inside master's recent 83–115 ms range and this query is noisy on master. That call is consistent with the diff: Q10 is a read-only COUNT(DISTINCT) aggregation that never runs the changed metadata transaction or startup-loading code, so there is no reason to contest it.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 10 not_sure 92 111 +20.7% <0.0001 aggregation: The +20.7% delta (111 ms vs 92 ms) sits inside master's recent 83–115 ms range, and this query is noisy on master. The PR only changes plain_rewritable disk metadata writes and startup recovery, which this query does not run.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: fb54667f-448b-4cd6-adfa-386dc060768f
  • MIRAI run: a6a51600-b7fb-43b6-9cd1-1f9cde948025
  • PR check IDs:
    • clickbench_697115_1795291139
    • clickbench_697121_1795291139
    • tpch_adapted_1_official_697154_1795291139
    • tpch_adapted_1_official_697176_1795291140

alexey-milovidov and others added 2 commits November 24, 2026 15:42
…cement

`makePendingReplaceTombstoneContent` rejected a target whose name contains
a line feed, because a line feed separates the fields of the marker. So an
existing file with such a name, which is a valid name on a
`plain_rewritable` disk, could not be replaced by `replaceFile`.

Such a name is now written escaped (like in the file list of `prefix.path`)
under a separate prefix, `PENDING_REPLACE_ESCAPED_TOMBSTONE_PREFIX`, and
parsed symmetrically. The content for a name without a line feed is not
changed, so the markers stay readable by the versions that know only
`PENDING_REPLACE_TOMBSTONE_PREFIX`, and an old marker with a backslash in
the name is not misread as an escaped one.

The new unit test `ReplaceOfFileWithLineFeedInName` covers the round trip
of the content, torn contents, a replacement that fails and is undone, a
rollback of an interrupted replacement on the next load, and a successful
replacement.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (7157203, clean merge) and addressed the review thread about the marker of a pending replacement in 1af106a (see the reply there). The PlainRewritable, LocalObjectStorage, and DiskObjectStorage unit tests pass locally on the merged tree (167 tests).

The only CI failure on d5acb7c, 05299_promql_offset_sample_timestamps in Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel), is unrelated to this PR: the test is flaky with plan-based parallel replicas (it passed 92 of 92 reruns) and was added to the plan-based blacklist by #133730, which is already on master, so this merge brings the fix in.

return out.str();
}

bool PlainRewritableLayout::isValidBlobKey(std::string_view blob_key)

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.

[Blocker] Reject qualified object paths before accepting a blob key

isValidBlobKey accepts s3://other-bucket/victim.bin: it is relative to std::filesystem, contains no NUL or traversal component, and does not start with __meta. An empty common key prefix is supported by getS3URI; in that configuration constructBlobObjectKey preserves this string. S3ObjectStorage::groupByBucket then calls splitBucketAndKey, which interprets it as bucket other-bucket, key victim.bin.

Consequently, a supplied blob-removal marker, or an explicit file list of a committed recursive removal, can make startup delete an object in another bucket using the disk's credentials. A standalone probe using this validator and the repository's trySplitFullyQualifiedObjectPath confirmed the accepted key and cross-bucket routing; this was not a full server reproduction.

Please reject qualified paths as well as filesystem traversal, and add a recovery regression with an empty disk prefix and a sentinel in another bucket. Check the namespace interpretation used by the S3 consumer, not only filesystem relativity.

/// The blobs of a directory are deleted with it (also by the reclamation on the initial load), so a key that
/// would name an object outside of the blobs of this disk (in another prefix, or in `__meta`) is never taken
/// from a damaged or forged file list.
if (!PlainRewritableLayout::isValidBlobKey(file.blob_key))

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.

[Blocker] Apply blob-key containment to snapshot-loaded entries too

This check protects prefix.path, but the existing snapshot.bin load path bypasses it. readPlainRewritableSnapshot reads FileRemoteInfo::blob_key without validation (Metadata/PlainRewritableSnapshotFile.cpp:190), and a read-only disk applies that layout directly (MetadataStorageFromPlainRewritableObjectStorage.cpp:1279). A well-formed snapshot can therefore give a file the key /other-prefix/victim.bin; getStorageObjectsIfExist passes it to constructBlobObjectKey, whose filesystem join discards the configured prefix, and S3ObjectStorage::readObject reads that key without a containment check. The same gap exists for a default key derived from a snapshot-supplied DirectoryRemoteInfo::remote_path.

Thus the relative-key invariant being enforced here still does not hold across the persisted representations, and supplied snapshot metadata can redirect reads outside the disk's namespace. This alternate path is pre-existing, but remains uncovered by the containment fix.

Please validate the effective key from getBlobKey for snapshot entries as well, or enforce containment centrally before constructing an object key. Add a read-only snapshot regression with an outside-prefix sentinel and cover both explicit and default blob keys.

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

comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

2 participants