Skip to content

Revert "Revert "Support real hard links for plain_rewritable metadata."" - #119304

Merged
alexey-milovidov merged 21 commits into
masterfrom
revert-119276-revert-110939-plain-rewritable-explicit-prefix-path
Oct 5, 2026
Merged

alexey-milovidov merged 21 commits into
masterfrom
revert-119276-revert-110939-plain-rewritable-explicit-prefix-path

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

Reverts #119276, i.e. re-lands #110939 (real hard links for plain_rewritable metadata via explicit file lists in prefix.path, opt-in with enable_hard_links), with the fixes below on top.

Closes: #91611
Related: #119154

Changelog category (leave one):

  • New Feature

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

Disks with the plain_rewritable metadata (s3_plain_rewritable, and azure/local object storages with metadata_type = plain_rewritable) support hard links if configured with the new enable_hard_links setting, which enables ALTER operations and mutations on MergeTree tables stored on them. Mutations and partition operations share the unchanged blobs between parts instead of copying them. The setting is off by default, because a disk that has hard links cannot be read by older servers.

Details

The original change was reverted because the stress test kills random mutations, and a readonly table_disk reader over a live table's directory (the new test 05104) then failed to load with a raw S3_ERROR The specified key does not exist for a mutation_*.txt entry that the owner removed between the listing and the read (report). Compared to #110939:

  • loadMutations of a readonly table reports a concurrently removed entry as FILE_DOESNT_EXIST with the reason and the way to retry (SYSTEM DROP DISK METADATA CACHE and attach again), instead of a missing object. The table still refuses to load without the entry: a reader cannot tell a killed mutation from a finished one (see Tolerate a concurrently removed mutation entry on a readonly shared directory #119154 (comment)). Test 05227 reproduces the race with a pauseable failpoint.
  • With enable_hard_links = 0, the copy that stands in for a hard link is replayed in the uncommitted state, and a rewrite of its target in the same transaction supersedes it (the copy would otherwise overwrite the new bytes at commit).
  • The table_disk cleanup of mutation_* entries and the deduplication log on DROP TABLE runs after the parts are removed, so a failed drop can still be retried or undone with them. Test 05228 checks it with a pauseable failpoint.
  • The prefix.path undo rewrites go through undoWithRetries, like every other undo stage since Retry every stage of a plain-rewritable undo until it succeeds #119235.
  • ReadOnlyDiskWrapper forwards supportsHardLinks to the disk it wraps, instead of falling back to IDisk::supportsHardLinks, which is true. Without it a read-only attachment of a disk that cannot share blobs offers the operations that need hard links while the disk it wraps refuses them. This is older than enable_hard_links - the same was true of a read-only attachment of a plain or write-once disk - but the new setting widens the set of disks it is wrong about. Test 05234.
  • The downgrade note of enable_hard_links states the boundary as "a server that does not have the setting" instead of naming a release, which this change cannot pin down.

🤖 Generated with Claude Code


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

Version info

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

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ffb4b6d]

Summary: ✅


AI Review

Summary

This PR re-lands plain_rewritable hard-link support behind enable_hard_links, adds the explicit prefix.path file-list form needed to preserve shared blobs safely, and folds in the follow-up fixes around readonly mutation-entry loading, table_disk drop ordering, and wrapper capability reporting. I re-read the current diff and all prior PR discussion/review threads; the earlier concerns raised on-thread are addressed in the current head or intentionally constrained with behavior that matches the remaining callers, and I do not see a remaining correctness, compatibility, or safety issue in the current code.

Final Verdict
  • Status: ✅ Approve
  • The current head addresses the prior review issues, includes focused regression coverage for the new hard-link and fallback-copy cases, and I did not find a remaining blocker or major concern.

LLVM Coverage Report

Measured on commit ffb4b6d.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 742/816 (90.93%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Sep 10, 2026
@mintlify

mintlify Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Oct 3, 2026, 6:09 AM

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage-disks Object-storage disk layer: DiskObjectStorage, metadata storage adapters, transaction support for ... label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ffb4b6df9 with master 7cbb8ad28 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 796d29517; 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

36 object files changed (+409.59 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFro… 365.91 KiB 492.41 KiB +126.51 KiB (+34.57%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/PrefixPat… new 89.36 KiB +89.36 KiB
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFro… 473.73 KiB 529.01 KiB +55.27 KiB (+11.67%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/BlobLinkC… new 47.92 KiB +47.92 KiB
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/FsSnapsho… 157.63 KiB 182.54 KiB +24.91 KiB (+15.80%)
src/CMakeFiles/dbms.dir/Storages/StorageMergeTree.cpp.o 1.54 MiB 1.57 MiB +24.20 KiB (+1.53%)
src/CMakeFiles/dbms.dir/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/Metadata/FsMetadat… 24.37 KiB 42.43 KiB +18.06 KiB (+74.13%)

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

295 translation units recompiled, 2938 s compile time in total, 293 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×0.94 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost -190.4 s (-6%) in total before that adjustment.

Job report

CheSema added a commit that referenced this pull request Sep 11, 2026
Master reverted "Support real hard links for plain_rewritable metadata"
(#110939) in 79745e1, so the operations this branch touches lost their
explicit file lists. The reversal work is re-applied on the simpler code:

- `MetadataStorageFromPlainObjectStorageHardLinkOperation` is gone, because
  `createHardLink` copies the blob again, which the copy operation covers.
- `MetadataStorageFromPlainObjectStorageWriteFileOperation` no longer writes to
  object storage, so it has nothing to reverse and does not take `UndoRetries`.
- The move of a file has a single form again, so its reversal no longer has a
  branch for a move that only rewrites file lists.
- `prefix.path` holds a logical path again, so the tests read it directly.

Everything the branch claims is unchanged: every stage of an `undo` repeats
until object storage accepts it, each stage converges on the state recorded
before the first write rather than on what `execute` saw succeed, and a blob
that exists under neither its own key nor its temporary key is reported as a
logical error.

When #119304 restores the hard links, the reversals of the hard link operation,
of `WriteFileOperation` and of the file move that only rewrites file lists need
the same treatment again.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 5 commits September 18, 2026 03:25
…t-110939-plain-rewritable-explicit-prefix-path

# Conflicts:
#	src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp
#	src/Disks/tests/gtest_metadata_plain_rewritable_disk.cpp
Master (#119235) made every stage of a plain-rewritable undo repeat until
object storage accepts it, because an undo that stops halfway leaves object
storage describing a filesystem this process does not have. The undo stages
that this branch adds - restoring the `prefix.path` of a directory whose
explicit file list an operation rewrote - now go through `undoWithRetries`
as well.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… state

With `enable_hard_links = 0` a hard link is a copy that runs at commit, and
the transaction did not replay it: a later rewrite of the target in the same
transaction planned as the creation of a missing file, chose the same default
key, and the copy overwrote the new bytes at commit.

The copy is now recorded in the uncommitted state like any created file, and
a rewrite of its target in the same transaction supersedes the copy: the
target directory keeps the implicit form, where a file has exactly one key,
so the copy cannot go anywhere else and has nothing to contribute once the
target is rewritten. Covered by the new `HardLinksDisabledRewriteLinkInTheSameTransaction`
test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ts parts

`StorageMergeTree::drop` removed the `mutation_*` entries and the deduplication
log of a `table_disk` table before `dropAllData` started. A drop that fails
while removing the parts is retried by `DatabaseCatalog`, and `UNDROP TABLE`
can still restore the table until then, so a failed drop could resurrect the
table with all of its parts and without its mutation queue or deduplication
history.

The cleanup now runs from the late root-cleanup phase of `dropAllData`, after
the parts are gone, through a `MergeTreeData` hook that the engines override
for the files they keep in the root of the disk. The new test pauses a drop
before it removes the parts and checks that a readonly table over the same
directory still loads the mutation and the deduplication log.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…while a readonly table loaded

A readonly `MergeTree` table over the directory of a live table (`table_disk`
on the same `plain_rewritable` endpoint) does not own the `mutation_*.txt`
entries there: the live table removes one at any moment (`KILL MUTATION`,
`clearOldMutations`), also between the listing and the read in
`loadMutations`. The read then failed with a raw `S3_ERROR` (`The specified
key does not exist`), which is what reverted #110939: the stress test kills
random mutations and treats every such error as a bug, see
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3b3489bfd27660683f874666359fc92f58ca46b8&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29

The table still cannot load without the entry - a part below its version
would miss the commands, and no reader-side rule can tell a killed mutation
from a finished one (see the analysis in #119154) - so the load still fails,
but with `FILE_DOESNT_EXIST` and the reason: the entry was removed
concurrently, and the attach can be retried after `SYSTEM DROP DISK METADATA
CACHE` reloads the metadata of the readonly disk, which still lists the entry.
The check probes the backend, because the cached metadata of the disk is
exactly what is stale. Only a readonly disk takes this path.

Related: #119154

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

alexey-milovidov commented Sep 18, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Merged master (3881 commits behind, conflicts with #119235 in the operations file and the gtest resolved: the undo flags renamed there are kept, and the prefix.path undo rewrites this branch adds now also go through undoWithRetries), and addressed the three review threads (two adopted, one declined with reasoning on the thread).

The original #110939 was reverted because of the stress test: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=3b3489bfd27660683f874666359fc92f58ca46b8&name_0=MasterCI&name_1=Stress%20test%20%28amd_debug%29 - the harness kills random mutations, and a readonly table_disk reader over the live table's directory (the new test 05104) then failed in loadMutations with a raw S3_ERROR The specified key does not exist, which the No such key check treats as a bug. A plain revert of the revert would bring that back (15 stress reds in 13 hours per the analysis in #119154), so 0e12a4d changes the failure, not the outcome: the table still refuses to load without the entry (no reader-side rule can tell a killed mutation from a finished one, see #119154 (comment)), but it reports FILE_DOESNT_EXIST with the reason - the entry was removed by the owner of the shared directory while loading, and the attach can be retried after SYSTEM DROP DISK METADATA CACHE reloads the readonly disk's metadata, which still lists the entry. The check probes the backend and applies only to readonly disks. Test 05227 reproduces the race deterministically with a new pauseable failpoint.

@groeneai: this overlaps the same lines of loadMutations as your #119154; the CSN/temporary-entry writes to a disk the table does not own are not touched here, so that part still stands on its own. Once this lands, a merge of master into #119154 will conflict in loadMutations; the natural resolution is to keep your write-skipping and rebase the tolerance on loadMutationEntry.

@groeneai

Copy link
Copy Markdown
Collaborator

Confirmed, and that is the resolution I will take on #119154. loadMutationEntry is the right seam for the probe; the only thing my change needs at the loadMutations call site is the decision, which depends on the part set the table has just loaded.

At merge time:

  • the three writes to a directory the table does not own stay as they are (writeCSN becomes an in-memory entry.csn, an entry of an uncommitted transaction is ignored instead of unlinked, tmp_mutation_* is left alone);
  • loadMutationEntry reports "the entry is provably gone" to the caller instead of only throwing, so loadMutations can apply the minimum-part-version test and either skip the entry or let your FILE_DOESNT_EXIST out. No catching by error code at the call site;
  • your probe picks up the two guards mine has around it: an empty unique id, and a probe that throws, both leave the original read failure in force rather than reporting a removal that did not happen. Neither is reachable on plain_rewritable (one object or a throw), but the new message is specific enough that I would rather it not be wrong on another metadata type.

On the tolerance itself, since the comment cites my "no reader-side rule" note: that note is about telling a killed mutation from a finished one, which I still believe is undecidable on the reader side, and the guard does not try. It asks only whether any active part of this table is below the entry's version, that is, whether this table would ever apply that entry's commands as an on-the-fly conversion. If nothing is below it, the entry is irrelevant to every part in the set, killed or finished. If something is below it (mutation 15 over a part left at version 12, in the job I analysed) it refuses, which is exactly what the reland now reports with a reason. The two compose rather than compete.

One measurement in favour of the reland, over the 20 Stress jobs this signature reddened from 3b3489bf (2026-09-09 23:14Z) onwards: in every one of them that log scan was the only non-OK row, with no Test script failed and nothing else, so 05104 failing under the disruptor does not by itself red the job. The scan is Code: 499.*The specified key does not exist (clickhouse_proc.py:1215 and stress_tests.lib:414), and all 79 matched lines over those runs split 39 executeQuery / 40 TCPHandler, with no intermediate logger emitting the raw exception, and Exception::message() is the text without the Code: N. prefix. So the rewrap takes all of those lines out of the scan, and no other scan in the job matches FILE_DOESNT_EXIST.

The tests do not overlap: 05227 covers the reported reason, 05161 on my branch covers the skip and the must-not-skip arms. Once the failpoint is on master I will drive the removal there with storage_merge_tree_load_mutations_pause_before_read instead of the stale metadata cache.

alexey-milovidov and others added 3 commits September 21, 2026 17:56
…t-110939-plain-rewritable-explicit-prefix-path
…per`

`ReadOnlyDiskWrapper` forwards the capabilities of the disk it wraps
(`isWriteOnce`, `supportZeroCopyReplication`, `supportsCache`, ...), but not
`supportsHardLinks`, so it fell back to `IDisk::supportsHardLinks`, which is
`true`. A read-only attachment of a disk that cannot share blobs - a
`plain_rewritable` disk without `enable_hard_links`, and before this pull
request also any `plain` or write-once disk - therefore reported that the
operations needing hard links are possible, while the disk it wraps reported
the opposite.

`ALTER` and mutations do not reach the capability check on such a table:
`InterpreterAlterQuery` rejects it earlier with
`TABLE_IS_PERMANENTLY_READ_ONLY`. The reachable caller is
`InterpreterHypotheticalObjectQuery`, which mirrors the `ALTER` rule because a
hypothetical index is only worth estimating on a table that could really get
one. The new test `05234_read_only_disk_hard_links_capability` creates a
read-only attachment of a `plain_rewritable` disk over the directory of a live
table and checks that `CREATE HYPOTHETICAL INDEX` on it is refused with the
same reason as on the writable table, and that with `enable_hard_links` both
accept it - so the wrapper is not answering `false` unconditionally either.
Without the fix the first arm accepts the index that the very same disk
refuses.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e_hard_links`

The note said that servers older than `26.9` cannot read a directory with an
explicit file list, which is a number this pull request cannot back: `26.9` is
already branched off and master is `26.10`, so the boundary would be wrong even
if the re-land lands today, and wrong downgrade guidance either blocks a safe
downgrade or invites an unsupported mixed-version setup.

The boundary is stated in terms of the feature instead - a server that does not
have the `enable_hard_links` setting is exactly a server that cannot read the
form, because reading it was added together with the setting. This is the
wording already used next to the code, in
`MetadataStorageFromPlainRewritableObjectStorage.h`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Sep 21, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master (1890 commits, no conflicts) and addressed both remaining review threads.

  • ReadOnlyDiskWrapper now forwards supportsHardLinks (405472b). The bug predates this pull request - the wrapper always fell back to IDisk::supportsHardLinks (true), so a read-only attachment of any plain or write-once disk answered wrongly too; enable_hard_links only widens the set of disks it is wrong about. Of the three callers, only InterpreterHypotheticalObjectQuery can observe it: checkAlterIsPossible and checkMutationIsPossible sit behind InterpreterAlterQuery, which rejects a read-only table with TABLE_IS_PERMANENTLY_READ_ONLY first. New test 05234_read_only_disk_hard_links_capability covers both arms and was verified to fail without the fix.
  • The 26.9 in the downgrade note is gone (f1cd2ee). v26.9.1.1-new is already tagged and master is 26.10, so no concrete number this pull request could write would stay right; the note now states the boundary as "a server that does not have the enable_hard_links setting", which is what the comment next to the code already says.

The CI reds on 0e12a4d0 were not from this branch. 03174_exact_rows_before_aggregation, 01414_push_predicate_when_contains_with_clause and 03262_filter_push_down_view failed together in Stateless tests (amd_llvm_coverage, ParallelReplicas, s3 storage, parallel) on master itself on 2026-09-17 (11 runs) and 2026-09-18 (4 runs), and have 0 failures on master from 2026-09-19 through 2026-09-21 - the master merge picks up the fix. The amd_tsan selected-tests job died in find_tests.py with Failed to get previously failed tests required for test selection, a fail-closed CIDB query error that a re-run clears.

Locally against a build of the merged branch: 05104, 05137, 05227, 05228 and the new 05234 all pass, as do 04545_read_only_disk_refresh_parts, 04223_hypothetical_index_lifecycle, 05024_hypothetical_projection_ddl and the 03008_*_plain_rewritable tests that do not need the CI disk configuration.

alexey-milovidov and others added 4 commits October 3, 2026 05:22
…y probe fails

The probe in `loadMutationEntry` (`getUniqueId` and `checkUniqueId`) can itself fail
for reasons other than a removed object. It was outside of any `try`, so its
exception replaced both the original read failure and the explanatory
`FILE_DOESNT_EXIST`. Now the error is converted only when the probe proves that
the object is gone; otherwise the original read failure is rethrown.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `enable_hard_links = 0`, a later rewrite of the target of a copy that stands
in for a hard link supersedes the copy. The bookkeeping in `fallback_copies` was
keyed by the original target path and was not updated by `moveFile`,
`replaceFile` and `moveDirectory`, so a new file written at the old path after
the target was moved away superseded the copy that the move needs as its source.
Drop the entries whose target is moved or replaced.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commit dropped the entry of `fallback_copies` when its target was
moved. That turned a rewrite at the old path into a silent overwrite: the copy
then ran at commit over the bytes the caller had written to the same default
key. A moved copy cannot be superseded either, because the move needs it as the
source, and the blob the move produces would overwrite the bytes of a rewrite at
the new path.

Now `moveFile`, `replaceFile` and `moveDirectory` mark the copy as moved under
both the old and the new path, and `generateObjectKeyForPath` refuses to write
such a path with `NOT_IMPLEMENTED` before any bytes are written. A moved copy
without a rewrite still commits as before.

Also pass `hard_links_enabled` in the `RefreshSkipsUnchangedDirectoryReads`
test that came from master, which still used the two-argument constructor of
`MetadataStorageFromPlainRewritableObjectStorage`.

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/praktika.html?PR=119304&sha=770425c6e0c802344e0e5c1dd64c8718765104f0&name_0=PR&name_1=Stress%20test%20%28arm_debug%29 (Logical error: Got read request from replica A for unknown stream B, tracked in #110518) and provide a fix in a separate PR. If the fix is already in progress, link it here.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Investigated. The job's fatal log names the aborting query, SELECT id, department FROM t_mt_index_rp ORDER BY id, and the stress runner reports that the server died during 04891_mergetree_index_respects_row_policy, with serialize_query_plan = 1 and parallel replicas over a non-replicated MergeTree drawn for that run.

This is the row-policy route of #110518: the serialized plan shipped to the replicas loses the row policy that the initiator pushed into the MergeTree read. The policy fixes the first sorting key column, so the initiator reads ORDER BY id in order and registers per-split streams, while the replicas, planning without it, use default reading and request the bare stream t_mt_index_rp, which the coordinator never created.

The fix is in progress: #114955 (mine, open, CI green on its current head). It applies the policy on the executing server, so all replicas plan the same read, and its test 04908_row_policy_serialized_plan_parallel_replicas reproduces this abort on master with a failpoint. It is not merged, so this run's tree could not contain it.

alexey-milovidov and others added 4 commits October 4, 2026 21:20
…it directory

With `enable_hard_links = 0`, `createHardLink` copies the blob to the default key
`<remote dir>/<file name>` of the target directory. That key is not free in a
directory in the explicit form, written while hard links were enabled: a file
removed there may leave its blob alive for a hard link elsewhere, and the copy
would overwrite the bytes that link sees (and its undo would remove them).

Now the copy into such a directory gets a fresh random key, chosen at planning
time like a new file of the directory in `generateObjectKeyForPath`, and the key
is listed in `prefix.path`. An implicit target directory keeps the default key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e `FsSnapshot` of this branch

The test came from master with the merge. On this branch `FsSnapshot` takes the
shared `BlobLinkCounts`, and `FileRemoteInfo` has the `blob_key` field.

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

Copy link
Copy Markdown
Member Author

🕵 Pushed ffb4b6d:

  • Fixed the Build (arm_tidy) failure (cppcoreguidelines-pro-type-member-init on FallbackCopy::copy).
  • Addressed the review thread: when hard links are disabled, the copy that stands in for a hard link into a directory in the explicit form now gets a fresh random blob key listed in prefix.path, not the default key. The default key may still hold a blob linked from elsewhere. Covered by the new gtest HardLinksDisabledCopyIntoExplicitDirectory.
  • Merged master and adapted the new gtest_metadata_plain_rewritable_fs_snapshot from master to the FsSnapshot constructor of this branch. All 82 MetadataPlainRewritableDiskTest / FsSnapshot / PlainRewritable* gtests pass locally.

@groeneai, thanks for the analysis of the Stress test (arm_debug) abort; we will wait for #114955.

@alexey-milovidov alexey-milovidov self-assigned this Oct 5, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 5, 2026
Merged via the queue into master with commit 8cffe60 Oct 5, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the revert-119276-revert-110939-plain-rewritable-explicit-prefix-path branch October 5, 2026 19:36
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 5, 2026
@iskakaushik

Copy link
Copy Markdown
Contributor

A use case for enable_hard_links, from chDB. pg_chdb, PostgreSQL extensions whose full-text and
vector indexes keep MergeTree tables in an embedded ClickHouse (chDB's libchdb), stores parts on
chDB's callback object storage (chdb-io/chdb-core#256), which sits under plain_rewritable metadata
and offers flat keys only. At 26.9.2.1, as on master, every mutation there stops in
MergeTreeData::checkMutationIsPossible with Code 344 (Mutations are not supported for immutable disk), since DiskObjectStorage::supportsHardLinks() is false for plain metadata:
DELETE FROM in the default and alter_update modes, ALTER TABLE ... DELETE and UPDATE,
APPLY PATCHES, APPLY DELETED MASK and REWRITE PARTS. Only lightweight_update_force works,
and its patch parts then turn off text index direct reads until a merge (#124085): on
28,737,557 Hacker News rows (16-vCPU i4i.4xlarge, local NVMe), a rare-term search went from 112 ms
to 4,045 ms end to end with three patch parts. With hard links we would delete in the default
mode, whose _row_exists mask keeps the direct read, or run APPLY PATCHES at VACUUM. It
reproduces with clickhouse local on disk(type = 'object_storage', object_storage_type = 'local', metadata_type = 'plain_rewritable', ...). This half of chdb-io/chdb#657 comes here on a
maintainer's advice. One question: does enable_hard_links need anything from the object
storage beyond reading, writing, removing and listing flat keys?

groeneai added a commit to groeneai/ClickHouse that referenced this pull request Oct 5, 2026
Resolve the conflict with ClickHouse#119304 in `loadMutations` as agreed there:

- keep the three writes this branch skips on a readonly disk (CSN kept
  in memory, an uncommitted entry ignored instead of removed,
  `tmp_mutation_*` left alone);
- drop this branch's own backend probe, and let `loadMutationEntry`
  return nothing for an entry the owner removed when the caller allows
  it; the caller allows it only when no active part of the table is
  below the entry's version, otherwise `FILE_DOESNT_EXIST` from
  ClickHouse#119304 is thrown as before;
- an empty unique id is not taken as proof that the entry is gone (a
  file without a backing object, e.g. with inline content), so the
  original read failure stays in force.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov added a commit that referenced this pull request Oct 5, 2026
…rrow-metadata-lock

Reconcile with real hard links for `plain_rewritable` (#119304),
which conflicted with the per-path locks, the replayed journal and the tombstone markers of this PR:

- The journal of `FsSnapshot` also records `markDirectoryExplicit`, `addBlobLink` and `removeBlobLink`, and
  `FsMetadata::applyJournal` folds the replayed blob link deltas into the committed `BlobLinkCounts`.
- A file operation that may rewrite the `prefix.path` of its directory (the directory has the explicit file list,
  the blob of the file is shared, or hard links are enabled) also locks the directory: the explicit file list lists
  all files of the directory, so two concurrent rewrites for different files would otherwise lose one of them.
- `UnlinkMetadataFileOperation` and `MoveFileOperation` keep the metadata-only paths of master and use the
  tombstone markers on the paths that move blobs. `RemoveRecursiveOperation` chooses the blobs to delete in
  `execute`, keeping the shared ones, and deletes them before the `prefix.path` objects in `finalize`.
- The initial load does not reclaim a blob of an orphaned directory that a live file still links to, rolls a
  pending removal back without losing the explicit file list, and lists `__root` for the leftovers of file
  removals even when the root has the explicit file list.
- `getStorageObjectsIfExist` of a read-only disk maps the blob key of the target of a pending replacement to
  its backup.
- Remove a no-op `std::move` of a const object flagged by clang-tidy.
moleus pushed a commit to moleus/ClickHouse that referenced this pull request Nov 2, 2026
…g arrayJoin

allOutputsDependsOnlyOnAllowedNodes asks whether a key-expression node is
determined by the query's reduced key nodes. Its ARRAY_JOIN arm was
UNREACHABLE(), which encoded its original caller's precondition: until
6fe760d the only caller was isPartitionKeyFunctionOfKeys, walking a
MergeTree partition key, and MergeTreeData::checkKeyExpression throws
ILLEGAL_COLUMN "... key cannot contain array joins" for such a key, so the arm
was genuinely dead.

That commit gave the walker a second caller,
StorageDistributed::isShardingKeySuitsQueryTreeNodeExpression, and nothing
validates a Distributed sharding key the same way:
checkShardingKeyExistsAndIsNumeric only requires one integer-representable
output column, which cityHash64(k1, arrayJoin([1, 2]), k2) satisfies. The check
moved but the precondition that justified it did not, so the arm became
reachable from SQL. The pre-existing expression_dag.hasArrayJoin() early return
does not cover it: that guards the query DAG, while the walk which reaches the
arm starts at the sharding-key output and descends its children. matchTrees has
no ARRAY_JOIN branch, so the node stays unmatched and the switch is always
reached.

I answer false instead of aborting. res is already false on entry to the switch,
so break is the answer, and the arm previously carried no break at all. false is
also the semantically correct answer, not just the safe one: an exploded array
element is not a per-row function of its source row, so equal values may come
from unrelated source rows lying on different shards, and the initiator's merge
step is required. Claiming true would drop that step and return unmerged
per-shard results. The sibling walker in this file already treats an ARRAY_JOIN
result as irreducible for the same reason, and useDataParallelAggregation.cpp
spells out the consequence for the walker's other caller.

With false, isShardingKeySuitsQueryTreeNodeExpression returns false,
getOptimizedQueryProcessingStageAnalyzer returns {}, and getQueryProcessingStage
returns WithMergeableState, which is the path taken when
optimize_distributed_group_by_sharding_key is off. No sharding key that works
today changes behaviour, which the unchanged plan for cityHash64(k1, k2)
confirms.

This was the only aborting ARRAY_JOIN switch arm in src/. In an official release
build the arm was __builtin_unreachable() carrying no break, so behaviour there
was undefined; a 26.10.1.394 amd_release binary was measured to produce the same
declining plan as this change, so release output is unchanged and what goes away
is the debug and sanitizer build abort.

The regression test drives a stored table definition rather than remote(...).
An arrayJoin in a sharding key reaches the planner whenever a definition is
replayed instead of stated (a short ATTACH, the tables of an ATTACH DATABASE, a
Replicated database's DDL replay, a RESTORE, server startup), and that route
keeps loading such a key regardless of whether stating one freshly is accepted,
so it is the surface the fix has to hold on. Each assertion asks whether the
initiator kept a merge step of its own, as SELECT count() > 0 FROM (EXPLAIN ...)
WHERE explain ILIKE '%Distinct (DISTINCT)%' and the same over MergingAggregated.
That is where the decision shows: taking the shortcut leaves nothing above the
remote read, while declining it keeps the initiator's Distinct or
MergingAggregated step. An ordinary key is asserted in the same file as the
control, pinning the zero side, so the reference also fails if the optimization
stops firing.

Found by the AST fuzzer on Stress test (amd_tsan), PR ClickHouse#119304, commit
f1cd2ee.

Co-Authored-By: Claude Opus 5 <[email protected]>
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-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support hard links in the disks with plain_rewritable metadata

4 participants