Skip to content

Fix spurious CANNOT_OPEN_FILE when writing to an hdfs disk - #118654

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-hdfs-prefix-directory-race
Sep 8, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:fix-hdfs-prefix-directory-race

Conversation

@groeneai

@groeneai groeneai commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

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

Fixed a spurious Code: 76 CANNOT_OPEN_FILE error (Parent directory doesn't exist) on any write to an hdfs disk. 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/101708096214

Root cause. HDFSObjectStorage::writeObject creates the key's prefix directory and opens the object in two NameNode requests, with a createHDFSFS connect between them, while removeEmptiedParentDirectories deletes 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 makes hdfsOpenFile fail verifyParentDir. Any write to an hdfs disk can hit it, not just REPLACE 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, since allow_remote_fs_zero_copy_replication makes multi-server access to one root first-class. A retry would only lower the probability.

Cost. Emptied prefix directories are retained. For the hdfs disk that set saturates at 17576 per root regardless of volume, and /-rooted HDFS storages already retain them forever; listObjects recurses into them. With a plain or plain_rewritable layout it would instead be unbounded, but neither is usable on hdfs: measured on master, plain fails at CREATE TABLE (Code: 660) and plain_rewritable throws NOT_IMPLEMENTED at disk construction. LocalObjectStorage has 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 createParent would 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 hdfs disk, 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_reclaimed fails on master, passes here. test_log_family_hdfs --count 20: 100/100.


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

Version info

  • Merged into: 26.9.1.1004 (included in 26.9 and later)

`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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Reviewed cold against the code, then adjudicated with the implementation evidence. Three rounds; the
last cold re-review returned no findings.

❌ Blockers: none.

⚠️ Majors, fixed before publication. The change deletes the reclamation at two sites
(HDFSObjectStorage::removeObject and WriteBufferFromHDFS::removeFileOnCancel). The first draft's
regression assertion compared a global directory count under /clickhouse against > 0, which a
directory retained by an earlier test in the same module already satisfies; both tests now compare
the directory set across the removal, and the removal test fails on a binary that still reclaims.
A later draft described the canceled-write assertion as covering the cancel site, which it does not.
I corrected the description rather than strengthening the assertion, for the reason below.

💡 Noted, not blocking.

  • removeFileOnCancel has no test oracle, and I could not build one worth shipping. Only one
    predicate separates this change from reverting that hunk alone: the prefix directory of the blob
    the canceled write itself created must exist and be empty afterwards. Telling that directory apart
    from the ones the module has already retained depends on its three-letter prefix not colliding
    with any of them, so the assertion would fail on a correct binary in roughly 0.2% of runs, which
    is the same birthday collision this change exists to make harmless. A collision-free form needs
    the blob key, which the test cannot obtain, or failure injection. Measured rather than argued: a
    binary with only the removeObject reclamation deleted leaves the module green. The mutation is
    also not reachable by accident, since the helper, its declaration, its plumbing parameter and both
    call sites are deleted together.
  • test_truncate_table_keeps_user_directories can no longer fail, because nothing prunes
    directories now. I kept it: it states a user-facing invariant rather than the absence of the
    deleted code, and it is the guard the createParent route below would need. Its comment, which
    still described the deleted cleanup, is corrected.
  • Two claims were reworded to match what I could verify. The documentation calls the hdfs disk
    unsupported, not specifically the metadata_type = plain combination. And plain_rewritable
    retains an unbounded set for the same reason plain does, since it maps each logical directory to
    its own prefix, so the description now names both layouts; I measured only plain already failing
    at CREATE TABLE.

Residuals are disclosed in the description rather than fixed here: LocalObjectStorage has the same
create-then-reap shape (a local root has one writing process, so it can be coordinated, and I have
no observed failure there), and listObjects now recurses into retained empty directories, bounded
by the same 17576 per root. Exposing libhdfs3's createParent would make the create atomic and
allow the cleanup back with one request fewer; that needs a submodule bump, so it is your call.

@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [05ba5bc]

Summary: ✅


AI Review

Summary

This PR removes HDFS parent-directory reclamation so a concurrent delete can no longer remove the generated prefix directory between hdfsCreateDirectory and hdfsOpenFile. The default metadata_type = local path looks mechanically covered, but the blanket removal also creates a new operational regression for HDFS metadata_type = plain_rewritable.

Findings

⚠️ Majors

  • [src/Disks/DiskObjectStorage/ObjectStorages/HDFS/HDFSObjectStorage.cpp:219, src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorage.cpp:94-138, src/Disks/DiskObjectStorage/MetadataStorages/PlainRewritable/MetadataStorageFromPlainRewritableObjectStorageOperations.cpp:295-297] The new contract is "never prune HDFS directories", but plain_rewritable still stores one remote directory per logical directory and still reloads by recursively iterating __meta/ on startup. Deleting prefix.path now leaves __meta/<remote_path>/ behind forever, so a long-lived HDFS plain_rewritable disk accumulates an unbounded set of empty directories and restart cost grows with historical dropped parts instead of live metadata.
    Suggested fix: either reject HDFS metadata_type = plain_rewritable/plain explicitly, or keep the no-prune behavior scoped to the hashed-key local metadata layout that motivated the race fix.
Final Verdict

Request changes until the HDFS plain_rewritable/plain regression is handled or the unsupported configurations are explicitly rejected.

LLVM Coverage Report

Measured on commit 05ba5bc.

Metric Baseline Current Δ
Lines 88.80% 88.80% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.20% 81.20% +0.00%

Changed lines: Changed C/C++ lines covered: 18/23 (78.26%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @alesapin, could you review this? writeObject creates the object key's prefix directory and opens the object in two NameNode requests, so the emptied-prefix-directory reclamation from #113396 can delete that directory in between and fail any hdfs disk write with Parent directory doesn't exist. I removed the reclamation rather than retrying, since the pair cannot be made atomic (libhdfs3 hardcodes createParent = false) and one HDFS root is legitimately written by several servers under zero-copy replication.

@clickhouse-gh clickhouse-gh Bot added the comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. label Sep 7, 2026
@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Build (arm_tidy) duplicate-include master break: #118661 (external, open).

The break is not caused by this PR: master itself has been red on Build (arm_tidy) since the merge of #117314 at 2026-09-07T20:27:29Z, which added a second #include <DataTypes/DataTypeLowCardinality.h> to src/Storages/MergeTree/MergeTreeIndexConditionText.cpp, so readability-duplicate-include errors under WarningsAsErrors. Every pull request built against that master inherits it. I will pick the fix up here with a master merge once #118661 is merged.

@groeneai

groeneai commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - c822417

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Build (arm_tidy) / Build ClickHouse trunk regression: master 2be1edf87853 left a duplicate #include <DataTypes/DataTypeLowCardinality.h> in src/Storages/MergeTree/MergeTreeIndexConditionText.cpp:36, and readability-duplicate-include is -Werror #118680 (external, open); same one-line fix in #118661
Finish Workflow / new_tests_check.py cascade of the same gate: Bugfix validation reports DROPPED (Dropped due to previous failure [Build (arm_tidy)]) #118680 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260908-013052

@@ -241,12 +238,6 @@ void HDFSObjectStorage::removeObject(const StoredObject & object)

if (res == -1)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@clickhouse-gh

clickhouse-gh Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 05ba5bc76 with master 55c256363 (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.

Compile time of recompiled translation units

17 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.
The matched translation units cost +7.1 s (+12%) in total before that adjustment.

Job report

@alexey-milovidov alexey-milovidov self-assigned this Sep 8, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 8, 2026
Merged via the queue into ClickHouse:master with commit 7dead72 Sep 8, 2026
175 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 8, 2026
save-my-heart pushed a commit to save-my-heart/ClickHouse that referenced this pull request Oct 1, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-object-storage Object storage connectivity (S3/GCS/Azure) including credentials, retries, multipart, etc. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default 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.

3 participants