Skip to content

Report a too long async distributed INSERT directory name as a user error - #113083

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112719-distributed-async-insert-long-dir-name
Aug 4, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-112719-distributed-async-insert-long-dir-name

Conversation

@groeneai

@groeneai groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Closes: #112719

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 the error reported when an asynchronous INSERT into a Distributed table needs a queue directory whose name exceeds the 255-byte filesystem limit (reachable with use_compact_format_in_distributed_parts_names = 0). It was a LOGICAL_ERROR for a shard with internal_replication and an unattributed Code: 1001. std::exception otherwise; both now report ARGUMENT_OUT_OF_BOUND naming the table, the cluster and the limit.

Description

With use_compact_format_in_distributed_parts_names = 0 an async INSERT spools blocks into one directory per destination, named user[:password]@host:port[#default_database]. For a shard with internal_replication that name is comma-joined across all replicas, so ~10 replicas exceed NAME_MAX (255) with no single long field.

The condition is purely input-driven, so neither failure mode was an invariant violation:

  • internal_replication = true: Cluster::ShardInfo::insertPathForInternalReplication threw LOGICAL_ERROR, which aborts the server in assert builds.
  • internal_replication = false: no check at all. mkdir failed with ENAMETOOLONG, surfacing as Code: 1001. DB::Exception: std::exception, naming neither the cluster nor the limit.

The fix adds one length check at the top of DistributedSink::writeToShard, the sole creator of these directories (including the hardlink loop over the later destinations) and reached by both shard shapes. It throws ARGUMENT_OUT_OF_BOUND, mirroring DatabaseOnDisk::checkTableNameLength, before any disk reservation. The now-redundant LOGICAL_ERROR in Cluster.cpp is removed, leaving insertPathForInternalReplication a pure accessor. The message omits the name itself, which embeds the password system.distribution_queue masks out.

Names of 255 bytes or less behave exactly as before, and the compact format is unaffected (shard<N>_replica<M> is bounded by construction). The check is on the write path only, so a too long directory already on disk stays tolerated and table loading cannot start failing.

Rejecting the combination at CREATE TABLE or config parse time, as the issue suggests, is not possible: use_compact_format_in_distributed_parts_names is a per-query setting, so at that point it is unknown whether such a name is ever built.

Validated by a new stateless test (the unguarded branch, the exactly-255 boundary, a multi-destination shard whose first address is short, and the password not being disclosed) plus a new test_distributed_format case for the internal_replication half. Both fail on master.

…rror

With use_compact_format_in_distributed_parts_names = 0 an async INSERT into a
Distributed table spools blocks into one on-disk directory per destination,
named user[:password]@host:port[#default_database]. For a shard with
internal_replication that name is additionally comma-joined across every
replica of the shard, so around ten ordinary replicas already exceed NAME_MAX
(255 bytes) without any single field being long.

The resulting failure was misreported on both shard shapes, even though the
condition is purely input-driven (cluster configuration plus a per-query
setting) and therefore not an invariant violation:

  - internal_replication = true: Cluster::ShardInfo::insertPathForInternalReplication
    threw LOGICAL_ERROR, which aborts the server in assert builds.
  - internal_replication = false: there was no check at all, so mkdir failed
    with ENAMETOOLONG and surfaced as Code: 1001 DB::Exception: std::exception,
    naming neither the cluster nor the limit.

Add a single length check at the top of DistributedSink::writeToShard, which is
the sole creator of these directories (including the hardlink loop over the
later destinations) and is reached by both shard shapes, and throw
ARGUMENT_OUT_OF_BOUND mirroring DatabaseOnDisk::checkTableNameLength. Placing
it above the storage-policy reservation means nothing is reserved and no
partial directories are left behind on the failing path. The now redundant
LOGICAL_ERROR in Cluster.cpp is removed, leaving insertPathForInternalReplication
a pure accessor; its !has_internal_replication check is unchanged.

The message deliberately reports the length rather than the name, because the
name embeds the password that system.distribution_queue masks out.

Names of 255 bytes or less are unaffected, and the compact format stays
unaffected because shard<N>_replica<M> is bounded by construction. The check
covers the write path only: an over-long directory already present on disk is
still tolerated when directory queues are initialized, so table loading cannot
start failing after an upgrade.

Rejecting the combination earlier, at CREATE TABLE or at config parse time as
the issue suggests, is not possible, because
use_compact_format_in_distributed_parts_names is a per-query setting and at that
point it is unknown whether such a name is ever built. A config-time check would
reject clusters used only for SELECT or only with the compact format.

Closes: ClickHouse#112719
The tests pinned only the error code, so shrinking the message would have
left them green while the fix's stated contract (name the table, the
cluster and the limit) went untested. That contract is the second half of
issue ClickHouse#112719, whose complaint is that the old failure named "neither the
cluster, nor the directory, nor the limit".

The stateless test asserts the table name and the limit; the cluster is
asserted in the integration case, which is the only place a real named
cluster exists (the Remote engine reports the <remote> fallback). The new
positive row also makes the adjacent password_not_leaked zero
self-evidencing: it previously held vacuously on a reverted fix, where the
exception code is 1001 and its predicate selects no rows.

Verified by shrinking the format string to just the length: exactly the new
assertion reddens, every other arm stays green.
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

An independent model reviewed this change cold, without access to the reasoning behind it.
Verdicts below; findings marked fixed were addressed before this PR was opened.

# Finding Verdict
❌ The tests pin the error code but not the diagnostic. Dropping the table, cluster or limit from the message at DistributedSink.cpp:856 would leave every assertion green, even though naming the scope is the second half of what the issue asks for. Agreed, fixed. 04725 now asserts, over the same system.query_log rows it already flushes, that a code-69 exception for the offending table carries both the table name and is 255; the integration case additionally pins the cluster name, which only exists there. A mutation that shrinks the format string reddens exactly the new assertion.
⚠️ The password_not_leaked row asserts a countIf(...) = 0 filtered by exception_code = 69, so with the fix reverted it holds because the predicate selects no rows at all, not because nothing leaked. Agreed, fixed by the same change: the new positive row proves a code-69 exception for that table exists, so the adjacent zero-assertion is now self-evidencing.
💡 The integration case's assert "distr_long_path" in error can be satisfied by the query text that clickhouse-client echoes to stderr for a non-interactive session, rather than by the server diagnostic. Noted, not changed. The other two lines of that group carry the check: the cluster name is not in the query text, so test_cluster_internal_replication_long_path and is 255 can only come from the message's own fields. The table name is pinned unambiguously in the stateless test, where system.query_log.exception never contains the query.
💡 #include <climits> was added for NAME_MAX, which is POSIX rather than a <climits> guarantee. Not changed. The tree is already inconsistent here: computeMaxTableNameLength.cpp obtains NAME_MAX via <unistd.h> and base/glibc-compatibility uses it with no include. Editing this would change no behavior.

Verified during review and deliberately left alone: the deleted LOGICAL_ERROR had exactly one
caller, which immediately hands the path to writeToShard, so nothing else relied on it, and
insertPathForInternalReplication's !has_internal_replication invariant check is unchanged.
shouldSkipShardOnInsert special-cases LOGICAL_ERROR so that a local invariant violation is
never swallowed by skip_unavailable_shards; reclassifying to ARGUMENT_OUT_OF_BOUND cannot
open that hole, because its only caller sits on the synchronous insert path while this guard is
on the asynchronous one. initializeDirectoryQueuesForDisk still tolerates an over-long
directory already on disk, so no table can start failing to load after an upgrade.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Check Answer
a Deterministic repro? Yes, on demand, both shard shapes. internal_replication = false: CREATE TABLE t (x UInt64) ENGINE = Remote('<243-char host>:9000', currentDatabase(), tgt) then INSERT ... SETTINGS distributed_foreground_insert = 0, prefer_localhost_replica = 0, use_compact_format_in_distributed_parts_names = 0 gives Code: 1001 ... STD_EXCEPTION on master. internal_replication = true: a config cluster with 10 replicas gives Logical error: 'Path '...' for async distributed INSERT is too long (exceed 255 limit)' and aborts the debug binary. Not a rate, a certainty.
b Root cause explained? The directory name is built from unvalidated configuration (Cluster::Address::toFullString) and, for internal replication, grown further by an unbounded comma concatenation (concatInsertPath). The only length check in the tree sat on the read side of the cached path and was written as an internal assertion (LOGICAL_ERROR) rather than input validation, while the sibling branch that builds its names on the fly in DistributedSink::writeAsyncImpl never got a check at all. So one user error surfaced as a server abort on one shard shape and an unattributed std::exception on the other.
c Fix matches root cause? Yes. The invariant belongs to "a directory with this name is about to be created", so the check lives at the sole creator, DistributedSink::writeToShard, and the misclassified LOGICAL_ERROR in Cluster.cpp is deleted rather than merely reclassified. No bound was widened, no name hashed, no test weakened.
d Tests added? Yes. New stateless test 04725_distributed_async_insert_long_directory_name (unguarded branch, exactly-255 boundary, multi-destination shard with a short first address, password not disclosed, compact format still working) plus a new case in tests/integration/test_distributed_format for the internal_replication half, which is not reachable from a stateless cluster.
e Both directions demonstrated? Yes. Stateless test: FAIL on master (Code: 1001), 50/50 PASS with the fix. Integration case: FAIL on master (server abort / LOGICAL_ERROR), PASS with the fix. Three mutations were each built and run: deleting the loop reddens both cases; narrowing it to the first element reddens exactly the multi-destination arm; changing > to >= reddens exactly the 255-byte arm. Every arm therefore has a mutation that kills it.
f General across code paths? Yes. All three producers of such a name were enumerated: toFullString(false), concatInsertPath, and the compact shard<N>_replica<M> form (bounded by construction, so deliberately not guarded). All three directory-creation sites in writeToShard are covered, including the hardlink loop over the later destinations, because the check iterates the whole vector at the top of the function rather than trusting each caller.
g General across inputs? No column types are involved. The axes that exist are covered: both internal_replication values, both prefer_localhost_replica values (they select between two cached strings that flow through the same call site), single and multi destination, the exactly-255 boundary, one byte over, and an address carrying a password.
h Backward compatible? Yes. No setting, default, or serialization format changes, so no SettingsChangesHistory.cpp entry. Nothing that succeeds today starts failing: names of 255 bytes or less are untouched, and the two affected paths previously either aborted or threw an unattributed exception.
i Invariants preserved? Yes. The throw is above reserveAndCheck, so no disk reservation and no temporary file is taken on the failing path, and a multi-destination shard now leaves no partially created directories, which the test asserts. insertPathForInternalReplication keeps its !has_internal_replication invariant check byte for byte and becomes a pure accessor otherwise. The recovery path is untouched by design: initializeDirectoryQueuesForDisk tolerates an over-long directory already on disk, and a check there would fail table startup.

@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @alexey-milovidov, could you review this? An async INSERT into a Distributed table names its spool directory after the destination address, comma-joined across replicas for an internal_replication shard, so it can exceed the 255-byte limit; that was a LOGICAL_ERROR on one shard shape and an unattributed Code: 1001 on the other, and both now report ARGUMENT_OUT_OF_BOUND from a single check at the sole directory creator.

@PedroTadim PedroTadim self-assigned this Aug 3, 2026
@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 3, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1339110]

Summary: ❌

job_name test_name status info comment
Stress test (amd_tsan) FAIL
Logical error: Not-ready Set is passed as the second argument for function 'A (STID: 0250-41a5) FAIL cidb, issue ISSUE EXISTS
Stress test (arm_asan_ubsan, s3) FAIL
Hung check failed, possible deadlock found FAIL cidb IGNORED

AI Review

Summary

This PR moves the async distributed-insert directory-name validation to the actual queue-directory creation boundary, reclassifies the overlong-name failures as user-facing ARGUMENT_OUT_OF_BOUND, and the follow-up change correctly hoists the same validation ahead of the local write for mixed local/remote shards. I did not find any remaining correctness, compatibility, or test-evidence issues on the current head; the new stateless and integration coverage matches the fixed behaviors, and the current Praktika run is all green.

Final Verdict

✅ No blocking findings.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 3, 2026
A shard without internal replication that contains this server plus a remote
destination whose directory name exceeds NAME_MAX inserted into the local table
first and only then hit the length check, so the INSERT reported
ARGUMENT_OUT_OF_BOUND after it had already changed local state, and a retry
duplicated rows on the local replica.

Move the check ahead of writeToLocal by assembling the destination list first and
validating it there. The check is extracted into checkDirectoryNameLengths and is
still called from writeToShard, which is the only creator of these directories, so
both callers remain covered structurally.

Reported by the automated review on ClickHouse#113083.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

groeneai commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Automated review round 1 - adjudication

# Finding Severity Verdict
1 Validation runs after writeToLocal for mixed local/remote shards, so a rejected INSERT can partially apply and a retry duplicates local rows ⚠️ major AGREE - fixed in 1339110
2 No regression case for a shard with the local server plus a too long remote destination under prefer_localhost_replica = 1 ⚠️ major AGREE - added test_long_directory_name_rejected_before_local_write

Details are in the inline thread. Summary: the ordering claim is correct and I reproduced the
partial write (three failed INSERTs left three rows locally). The check now runs before the local
write; it is extracted into checkDirectoryNameLengths and still called from writeToShard, which
is the sole creator of these directories, so both call sites stay covered structurally. The new
test is mutation-verified: removing the hoisted call makes exactly that test fail while the
existing internal-replication case still passes.

Validation on the pushed head: test_distributed_format 10/10, stateless 04725 50/50, plus
negative controls confirming a local-only shard and a mixed shard with a short remote destination
are unaffected.

Session id: cron:clickhouse-maint-slot-18:20260803-152500

@groeneai

groeneai commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1339110

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
Stress test (amd_tsan) / Logical error: Not-ready Set is passed as the second argument for function 'notNullIn' (STID 0250-41a5) Trunk bug, not caused by this branch. A fuzzer query reaches FunctionIn::executeImpl (src/Functions/in.cpp:116) from FilterTransform::doTransform before the set's FutureSet is built. This diff touches async-insert writeToLocal handling in StorageDistributed, not set resolution. Breadth over 30 d: 211 rows / 165 pull requests / 14 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found Trunk bug, not caused by this branch. One CANCELLED query (is_cancelled = 1, elapsed 1233 s) is stuck single-threaded in ReadFromMerge::createChildrenPlans -> getModifiedQueryInfo -> QueryAnalysisPass::run, reached from applyFilters during QueryPlan::optimize: a merge(REGEXP(...)) re-analysis per underlying table with no cancellation point on that path. Read from the hung_check.log artifact. Breadth over 30 d: 483 rows / 321 pull requests / 90 master rows a fix task is moved to pending (investigating at full effort - fixing-PR link to follow here)

158 success, 15 skipped, 2 failures out of 175 check-runs. Finish Workflow succeeded.

Session id: cron:our-pr-ci-monitor:20260804-000000

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 4, 2026
Merged via the queue into ClickHouse:master with commit bb47935 Aug 4, 2026
178 of 181 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 4, 2026
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 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.

Long database name gives logical error on async insert in Distributed table

3 participants