Repository navigation
Fix spurious CANNOT_OPEN_FILE when writing to an hdfs disk - #118654
Conversation
`HDFSObjectStorage::writeObject` creates the object key's prefix directory
(`hdfsCreateDirectory`) and opens the object (`hdfsOpenFile`) in two separate
NameNode requests, with a `createHDFSFS` connect in between, while
`removeEmptiedParentDirectories` deleted that directory as soon as it became
empty: from `removeObject`, from `WriteBufferFromHDFS::removeFileOnCancel`, and
transitively from `BlobKillerThread::removeBlobsBatch`. Object keys are a
hardcoded `[a-z]{3}/[a-z]{29}`, so two unrelated blobs sharing a prefix
directory is a birthday collision among 17576 buckets rather than an exotic
case. A removal that emptied the directory inside that window made
`hdfsOpenFile` fail `verifyParentDir`, so any write to an `hdfs` disk could
fail with `Code: 76. DB::Exception: Unable to open HDFS file: ... error: Parent
directory doesn't exist`. `REPLACE PARTITION` is where CI saw it, because it is
the one step that writes a new blob per cloned part while the parts it replaced
out are being removed.
The two requests cannot be collapsed into one: libhdfs3's C entry point
hardcodes `createParent = false`
(`contrib/libhdfs3/src/client/Hdfs.cpp:698`), so there is no atomic
create-with-parents to call. And no in-process coordination can help, because
one `hdfs` root is legitimately written and reclaimed by several servers:
`allow_remote_fs_zero_copy_replication` makes multi-server access to a single
root a first-class configuration, and blob removal for such a root runs on any
replica. A bounded retry would only lower the probability, not establish the
invariant. So remove the reclamation and keep the parent-directory creation:
with nothing deleting a prefix directory, a write that has created its parent
can always open its object, in every configuration, with no new state, no lock
and no retry. This also drops one NameNode request per object deletion.
The reclamation was added to keep the NameNode namespace from growing without
bound. For the `hdfs` disk that premise does not hold: keys come from
`createObjectStorageKeyGeneratorByPrefix`, so the retained set saturates at
17576 directories per root and does not grow with data volume, roughly 2.6 MB
of NameNode heap at 150 bytes per inode, and a disk holding many blobs already
has that many live directories. ClickHouse also already retains those
directories forever for `/`-rooted HDFS storages. The one residual cost is that
`listObjects` recurses into retained empty directories, bounded by the same
17576 per root.
Two consequences that are disclosed rather than fixed here. An `hdfs` object
storage with `metadata_type = plain` takes keys from
`MetadataStorageFromPlainObjectStorage` instead, where they are logical paths of
unbounded count and the object storage is the only directory manager, so this
change does leak empty directories there; the `hdfs` disk is itself documented
unsupported (`storing-data.mdx:48`), the combination has no test configuration
anywhere under `tests/`, and I measured it already failing before this change,
at `CREATE TABLE` with `Code: 660. DB::Exception: Cannot get file info for:
.../format_version.txt`, so nothing that works today regresses.
`LocalObjectStorage` has the same create-then-reap shape, but a local root has a
single writing process, so its reclamation can be made safe by coordination; I
have no observed failure of it and left it alone.
`test_no_leftover_directories_after_removal` becomes
`test_prefix_directories_are_not_reclaimed`: it records the set of directories
present and asserts that `TRUNCATE` removes the objects and none of those
directories. `test_no_leftover_directories_after_canceled_write` becomes
`test_no_leftover_files_after_canceled_write`: it keeps every assertion about
files, which is still correct behaviour, and makes the same set comparison
across the canceled insert. Comparing sets rather than counts is what keeps both
specific, since a directory retained by an earlier test in the module cannot
satisfy either assertion. Both fail on a binary that still reclaims, with no
failpoint and no timing: the first is left with an empty directory set, and the
second loses the prefix directory of the `sizes.json` blob that `LogSink`
rewrites upfront on every insert to be able to roll back (`FileChecker::save`
writes a new blob and `replaceFile`s over the old one). The file's one
`time.sleep` poll is gone.
Both of those assertions bite on the `removeObject` site. I measured that the
`removeFileOnCancel` site has no test oracle: a binary with only the
`removeObject` reclamation deleted leaves the whole module green. That site can
only ever reclaim the prefix directory of the file the canceled write itself
created, which is never a member of a set captured before that write, so no
before/after comparison in this test can see it. It is covered by the argument
that a canceled write and a concurrent write can collide on a prefix exactly as
a removal and a write can, not by a test.
Validated with a concurrent write/remove workload on an `hdfs` disk, with the
object-key space temporarily narrowed so the prefix collision is frequent
instead of once per few hundred CI runs: 4 client failures and 10 server-log
occurrences per 640 queries with the reclamation present, 0 with it deleted,
the two arms differing only by that mechanism. Both files were run on both
binaries: `test_log_family_hdfs` is 2 failed / 3 passed before the change and 5
passed after, the two failures being exactly the two adapted tests, and
`test_merge_tree_hdfs` is 7 passed on both, including the
`test_move_replace_partition_to_another_table` that CI reported.
`test_log_family_hdfs --count 20` is 100/100.
CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=118526&sha=051fe4723d3ee9e1f6145a87924182005b690534&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%205%2F6%29
Carrier pull request whose CI produced that report (unrelated to the cause): ClickHouse#118526
Related: ClickHouse#113396
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewReviewed cold against the code, then adjudicated with the implementation evidence. Three rounds; the ❌ Blockers: none.
💡 Noted, not blocking.
Residuals are disclosed in the description rather than fixed here: |
|
Workflow [PR], commit [05ba5bc] Summary: ✅
AI ReviewSummaryThis PR removes HDFS parent-directory reclamation so a concurrent delete can no longer remove the generated prefix directory between Findings
Final VerdictRequest changes until the HDFS LLVM Coverage ReportMeasured on commit 05ba5bc.
Changed lines: Changed C/C++ lines covered: 18/23 (78.26%) · Uncovered code |
|
cc @alexey-milovidov @alesapin, could you review this? |
|
Fixing PR for the The break is not caused by this PR: master itself has been red on |
CI finish ledger - c822417Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260908-013052 |
| @@ -241,12 +238,6 @@ void HDFSObjectStorage::removeObject(const StoredObject & object) | |||
|
|
|||
| if (res == -1) | |||
There was a problem hiding this comment.
This fixes the hashed-prefix race for the default metadata_type = local, but removing directory cleanup unconditionally also regresses HDFS metadata_type = plain_rewritable. That layout deletes __meta/<remote_path>/prefix.path through removeObjectIfExists (MetadataStorageFromPlainRewritableObjectStorageOperations.cpp:295-297) and reloads by recursively iterating layout->constructMetadataDirectoryKey() on startup (MetadataStorageFromPlainRewritableObjectStorage.cpp:94-138). With this cleanup gone, every dropped part leaves __meta/<remote_path>/ behind forever, so restart cost grows with historical directories rather than live metadata.
If we cannot make pruning safe for that layout, we should reject HDFS plain_rewritable/plain explicitly or scope the no-prune behavior to the hashed-key local metadata path instead of changing all HDFS-backed disks.
There was a problem hiding this comment.
Verified every path cited, and the reading of them is accurate. The configuration it applies to cannot be instantiated, though, so there is nothing there to regress.
MetadataStorageFromPlainRewritableObjectStorage's constructor initialises metrics(createPlainRewritableMetrics(object_storage->getType())) (MetadataStorageFromPlainRewritableObjectStorage.cpp:255-257), and that function throws for ObjectStorageType::HDFS, next to None/Web/Max (PlainRewritableMetrics.cpp:63-68). So an object_storage_type = hdfs + metadata_type = plain_rewritable disk fails when the disk is constructed, before any metadata object is written. Measured on a master debug build (26.9.1.1), with that disk in storage_configuration:
<Error> Application: Code: 48. DB::Exception: Not Implemented. (NOT_IMPLEMENTED)
5. .../MetadataStorages/PlainRewritable/PlainRewritableMetrics.cpp:68: DB::createPlainRewritableMetrics(DB::ObjectStorageType)
6. .../MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.cpp:257: DB::MetadataStorageFromPlainRewritableObjectStorage::MetadataStorageFromPlainRewritableObjectStorage(...)
13. .../Disks/DiskSelector.cpp:120: DB::DiskSelector::initialize(...)
The server does not finish starting. __meta/<remote_path>/prefix.path is therefore never written on HDFS, so removing the reclamation cannot leave those directories behind. This is pre-existing master behaviour, unrelated to this PR, which changes nothing under MetadataStorages/. plain is unusable too, for a different reason measured earlier: CREATE TABLE fails with Code: 660 ... InvalidPathException on format_version.txt. No integration test pairs hdfs with either layout.
That also answers the scoping request: local is the only constructible metadata layout for an hdfs disk, so scoping the no-prune behaviour to it is what this change already does. I corrected the Cost. paragraph in the description to state both measurements instead of leaving plain_rewritable open.
On the counterfactual, in case the layout is made to work later: the race is layout-independent, because it lives in writeObject's create-then-open pair (HDFSObjectStorage.cpp:185, then hdfsOpenFile at WriteBufferFromHDFS.cpp:53) rather than in the key derivation. Keeping the reclamation for a plain layout would keep the Code: 76 write failure there, not avoid a cost. Making the create atomic (libhdfs3's createParent) is what would allow pruning back for every layout, and that is the follow-up the description offers.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units17 translation units recompiled, 69 s compile time in total, 17 of them have a recent master baseline. Median compile-time ratio to the baselines is ×1.11 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio. |
…log_family_hdfs
test_merge_tree_hdfs counted objects with fs.walk("/clickhouse"): one
WebHDFS LISTSTATUS per directory. pyhdfs without a requests session opens
a new connection per request and the client closes it, so every request
leaves a client-side TIME_WAIT for 60 s. Since ClickHouse#118654 the hdfs disk keeps
emptied [a-z]{3}/ prefix directories, so every walk lists every prefix used
since the module started (0 to 474 directories over the module's 72 walks).
In master WeeklyCFI "Integration tests (amd_cfi, 3/4)" (sha 424a061)
the module sent 14,908 LISTSTATUS over 14,931 new NameNode connections,
10,528 of them within 60 s, against the runner's 10,536-port ephemeral
range (55000-65535). Its own connects failed with EADDRNOTAVAIL from
05:17:22 to 05:17:47, and test_postgresql_kill_query, running on another
xdist worker in the same network namespace, failed three tests with
EADDRINUSE on bind(("", 0)) at 05:17:32. pyhdfs walk also swallows a failed
listing, so the two listings that failed both attempts (/clickhouse/lvx,
/clickhouse/lws) silently dropped their subtrees from the count.
Count with one GETCONTENTSUMMARY instead: fileCount is the NameNode's
recursive file count of the subtree. List paths only where the names are
needed: the failure message of a count assertion, and drop_table's leftover
cleanup when the count is non-zero. Remove the three unconditional debug
listings of test_move_replace_partition_to_another_table.
test_log_family_hdfs counts the same way; its hdfs_directories stays a walk
because its callers compare directory names.
A full pass of test_merge_tree_hdfs now makes 86 NameNode connections (peak
83 TIME_WAITs) instead of 14,931, and a failed request raises instead of
shrinking the count.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed a spurious
Code: 76 CANNOT_OPEN_FILEerror (Parent directory doesn't exist) on any write to anhdfsdisk. Removing a blob deleted its emptied object-key prefix directory, which could race a concurrent write that had just created the same directory and not yet opened its object. Emptied prefix directories are now kept.Description
Related: #113396
Seen in CI on
test_merge_tree_hdfs::test_move_replace_partition_to_another_table: https://github.com/ClickHouse/ClickHouse/actions/runs/34107856098/job/101708096214Root cause.
HDFSObjectStorage::writeObjectcreates the key's prefix directory and opens the object in two NameNode requests, with acreateHDFSFSconnect between them, whileremoveEmptiedParentDirectoriesdeletes that directory as soon as it is empty (removeObject,WriteBufferFromHDFS::removeFileOnCancel,BlobKillerThread). Keys are a hardcoded[a-z]{3}/[a-z]{29}, so two blobs sharing a prefix is a birthday collision among 17576 buckets. A removal emptying the directory inside that window makeshdfsOpenFilefailverifyParentDir. Any write to anhdfsdisk can hit it, not justREPLACE PARTITION. Present in 26.8 and master, not 26.7.Why removal. The pair cannot be made atomic (libhdfs3 hardcodes
createParent = false,Hdfs.cpp:698), and no in-process lock can own an HDFS root, sinceallow_remote_fs_zero_copy_replicationmakes multi-server access to one root first-class. A retry would only lower the probability.Cost. Emptied prefix directories are retained. For the
hdfsdisk that set saturates at 17576 per root regardless of volume, and/-rooted HDFS storages already retain them forever;listObjectsrecurses into them. With aplainorplain_rewritablelayout it would instead be unbounded, but neither is usable onhdfs: measured on master,plainfails atCREATE TABLE(Code: 660) andplain_rewritablethrowsNOT_IMPLEMENTEDat disk construction.LocalObjectStoragehas the same shape, but a local root has one writer, so its reclamation can be coordinated; I have no observed failure there.Exposing libhdfs3's
createParentwould make the create atomic and allow the cleanup back with one RPC fewer; that needs a submodule bump, so it is your call.Validation. A concurrent write/remove workload on an
hdfsdisk, key space narrowed so collisions are frequent: 4 client failures and 10 log hits per 640 queries with the reclamation, 0 without it; the arms differ only by that mechanism.test_prefix_directories_are_not_reclaimedfails on master, passes here.test_log_family_hdfs --count 20: 100/100.Workflow [PR]
Sync PR [sync-upstream/pr/118654]
Version info
26.9.1.1004(included in26.9and later)