Skip to content

Report the missing named collection in remote()/Remote instead of reparsing the call positionally - #113510

Merged
PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-remote-missing-named-collection
Aug 6, 2026
Merged

PedroTadim merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-remote-missing-named-collection

Conversation

@groeneai

@groeneai groeneai commented Aug 5, 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 the error reported when the remote/remoteSecure table functions or the Remote/RemoteSecure table engines are given a named collection that does not exist together with a key = value override. Such a call was silently reparsed as a positional call, so the override was analyzed as a data expression and the reported error named something unrelated (for example Function with name `merge` does not exist for remote(collection, database = merge(...))). The missing named collection is now reported.

Description

parseRemoteFunctionArguments looked the collection up with throw_unknown_collection = false, so a missing collection returned nullptr, the named-collection branch was skipped, and parsing fell through to the positional branch. There the override is analyzed as an ordinary expression, so database = merge(...) resolves merge against FunctionFactory instead of TableFunctionFactory (46), database = 'd' folds to a UInt8 where a String is read (170), and sharding_key = rand() has no resolvable identifier (47). ATTACH TABLE replays on-disk metadata through this parser, so an operator whose collection went missing sees the misleading error while the server refuses to start.

The first argument may also be a cluster name, and that form needs the positional branch, so the lookup cannot simply be made fatal. The two shapes are distinguishable without resolving anything: a key = value second argument is an equals ASTFunction, and no positional signature accepts one there (the second argument is consumed as the database/table before any sharding key). The lookup is made fatal exactly for that shape, and NamedCollectionFactory::get raises the existing NAMED_COLLECTION_DOESNT_EXIST.

Only the error changes: every affected call already failed, with 170 BAD_GET, 46 UNKNOWN_FUNCTION or 47 UNKNOWN_IDENTIFIER depending on the override. A positional sharding key that is an equality expression (remote(cluster, db, table, x = 1)) keeps working because it is not the second argument.

This fixes the parse and the error, not startup survival: #110529 is doing that for the URL engine, and StorageURL.cpp is deliberately left alone here.

Validated on a debug build: 4 arms report 669 with the fix and 46/47 without it (170 for a plain literal); the cluster-name form, the positional-equality-sharding-key form, an unknown cluster (CLUSTER_DOESNT_EXIST) and a live collection are unchanged. Three mutants each redden a different arm. 100/100 randomized runs of the new test plus 04511.

Version info

  • Merged into: 26.8.1.908 (included in 26.8 and later)

…positionally

parseRemoteFunctionArguments looked the named collection up with
throw_unknown_collection = false, so a missing collection returned nullptr, the
named-collection branch was skipped, and parsing fell through to the positional
branch. There an override argument such as `database = merge('d', '^t$')` is not
a table function, so it is analyzed as an ordinary data expression and `merge` is
resolved against FunctionFactory instead of TableFunctionFactory, giving
``Code: 46 UNKNOWN_FUNCTION: Function with name `merge` does not exist``. A
`sharding_key = rand()` override fails in the same place with `Code: 47
UNKNOWN_IDENTIFIER`. Since ATTACH TABLE replays on-disk metadata through this
parser, an operator whose collection went missing sees the misleading error while
the server refuses to start (722 <- 695 <- 46).

The first argument of remote() may also be a cluster name, and that form
legitimately needs the positional branch, so the lookup cannot simply be made
fatal: before this change 11 files under tests/queries/0_stateless already used
`remote(<cluster name>, ...)`, and test_shard_localhost is a cluster rather than a
named collection. The two shapes are distinguishable without resolving anything,
because a `key = value` argument is an `equals` ASTFunction and no positional
signature accepts one as the second argument: args[1] is consumed by the
database/table arm before the credentials and sharding-key block, which only runs
with arg_num >= 2. The lookup is therefore made fatal exactly for that shape and
NamedCollectionFactory::get raises the existing NAMED_COLLECTION_DOESNT_EXIST.

The check is deliberately restricted to args[1] rather than scanning every later
argument: sharding_key accepts an arbitrary AST, so
`remote(cluster, db, table, x = 1)` is a valid positional call whose sharding key
is an equality expression, and a broader scan would reject it. That form is
covered by a test arm.

No currently-succeeding query changes behaviour: every affected call already
failed with 46 or 47, so only the error code and message change. No explicit
check that the first argument is an identifier is needed, because
getCollectionName returns nullopt for a non-identifier before the flag is read,
which leaves the `remote('host:port', ...)` form untouched.

This fixes the parse and the error, not startup survival: a Remote table whose
collection is missing still throws at load time, now naming the right thing.
StorageURL.cpp is the only other call site passing false and is left alone, since
it belongs to separate work on tolerating a missing collection at startup.

Validated on a debug build with the collection missing: the engine and table
function, with both a table-function and a non-table-function override, report
669 and name the collection, against 46/47 before the change. The cluster-name
form, an equality expression used as a positional sharding key, an unknown
cluster (CLUSTER_DOESNT_EXIST) and a live collection are unchanged, as is
04511_remote_named_collection_complex_overrides. Three mutants each redden a
different test arm. 100 of 100 randomized runs of the new test plus 04511.
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Two review rounds by a model independent of the one that wrote the patch, plus two
independent adversarial gate passes. Source verdict on the final commit: no defect found.
Both fix rounds were test-only; src/ is byte-identical to the tree reviewed in round 1.

Finding Verdict
❌ Round 1: the two assertion arms drop a named collection while a dependent table is DETACHED. That succeeds today only because the dependency guard filters a detached table as stale via isTableExist; a tightening of that filter would let the drop be refused, the following ATTACH would then succeed, and the arms would stop witnessing the fix while blame landed on the test. AGREE, fixed. SET check_named_collection_dependencies = 0 pinned in both arms. Verified non-vacuous: the pinned test still fails on pristine master and on a rebuilt revert mutant, with all four arms flipping back to 46/47. Positive control that the guard is live: with the table attached the drop fails NAMED_COLLECTION_IS_USED, and the identical drop after the SET succeeds. That code differs from the asserted one, so a guard throw cannot be mistaken for a pass.
⚠️ Round 1: untagged, so the test runs in the Replicated-database job where database_replicated_always_detach_permanently = 1 turns DETACH into DETACH PERMANENTLY. The resulting .sql.detached flag is skipped by metadata iteration, so the later ATTACH would not be the startup-replay path the arm documents, and every DDL becomes a three-host replicated DDL whose timeout can replace the asserted error. AGREE, fixed. # Tags: no-replicated-database added. Verified by executing the runner's own tag parser: tag set is {no-replicated-database}, and three negative controls (broken colon, wrong comment sign, line deleted) each return empty, so the tag is live rather than a silent comment. no-fasttest deliberately not added: it would drop coverage for a non-constraint.
⚠️ Round 1: the changelog entry wrapped a nested backtick with a backslash escape. CommonMark does not honour that inside a code span, so it rendered as three broken spans, and changelog.py copies the entry verbatim into CHANGELOG.md. AGREE, fixed in the PR text. Replaced with a double-backtick span. The real get_category and check_changelog_entry were then executed against the body, each with a working negative control.
⚠️ Round 2: under the stress job, ignore_drop_queries_probability can turn a DROP TABLE into a no-op or a TRUNCATE, so a cleanup DROP TABLE followed by an unpinned DROP NAMED COLLECTION could leave the collection in use and fail. DROPPED (my own finding, refuted by its own control). The mechanism is real, but 04511 has the byte-identical shape three times over and is untagged; if it materialised, 04511 would fail on roughly half the affected stress workers. Measured over 30 days: 88577 OK / 4 FAIL, and all four are unrelated DDL timeouts in one job. The two sibling tests in this family are 111840 OK / 7 FAIL and 144085 OK / 1 FAIL. Unpinned cleanup drops are the healthy established pattern here; changing them would be churn against three precedents.
💡 Round 2: this test is the slowest in its family (median 7.7 s, worst 40.1 s under 18-way concurrency, against 04511's median 1.5 s). Noted, no change. The flaky-check runtime cap is 180 s, so there is about 4.5x headroom, and a long tag would cut flaky-check repetitions to a tenth for no benefit.
✅ Both gate passes on the final commit returned no findings. The reported diff scope matched the intended change set exactly. n/a

Independently re-derived rather than taken from the patch author's notes:

  • The central safety claim. Every identifier-first remote()-family call site in the tree
    was enumerated with a parenthesis-aware argument splitter over 548 files under
    0_stateless (and 596 across all of tests/). Of the 17 identifier-first callers there, 3
    use the named-collection form and each names a collection that exists at that point; the
    other 14 use the cluster-name form and still reach the positional branch. No in-tree call
    changes from success to failure.
  • The claim that 11 files used remote(<cluster name>, ...) reproduces exactly. A naive
    grep gives 14; the three extras are .reference files, which quote the call rather than
    making it.
  • args[1] can never be a positional sharding key: it is consumed by the database/table
    arm before the credentials and sharding-key block, which only runs at a later argument index.
  • Carrier list built before comparing against the patch author's, with no divergence. The
    shared parser has exactly two callers and both are covered by test arms; after this change
    StorageURL.cpp is the only remaining call site that tolerates a missing collection, and it
    is deliberately out of scope.

Deliberately not claimed in this PR: startup survival (a Remote table whose collection is
gone still throws at load time, now naming the right thing), and any frequency figure. The
signature was measured at one CI occurrence in 30 days, which is stated as a defect class
rather than a trend.

Session id: cron:clickhouse-review-slot-9:20260805-133800

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 1/1 on a pristine master debug build (Build ID 72b3babb, asserted equal to SELECT lower(buildId()) and confirmed to lack the fix). CREATE NAMED COLLECTION nc AS host='127.0.0.1', port=P; CREATE TABLE t ENGINE = Remote(nc, database = merge(currentDatabase(), '^target$')); DETACH TABLE t; DROP NAMED COLLECTION nc; ATTACH TABLE t gives Code: 46 ... Function with name `merge` does not exist, byte-identical to the reported CI message. No fuzzer and no randomization needed.
b Root cause explained? parseRemoteFunctionArguments.cpp:91 passed throw_unknown_collection = false, so a missing collection returned nullptr and the named-collection branch was skipped. Parsing then fell through to the positional branch at :147, where args[1] = equals(database, merge(...)) is not a table function (:221), so :235 analyzes the whole node as a data expression and merge is resolved against FunctionFactory instead of TableFunctionFactory -> Code: 46. With sharding_key = rand() the same fall-through gives Code: 47. ATTACH TABLE replays on-disk metadata through this parser, so at startup the chain is 722 <- 695 <- 46.
c Fix matches root cause? Yes. It corrects the branch decision (which parse to take) rather than the downstream symptom: the unknown-collection lookup is made fatal exactly when args[1] is an equals function, so the pre-existing NAMED_COLLECTION_DOESNT_EXIST is raised instead of a misparse. One expression, one file, +8/-1. No widened bound, no no-random-* tag, no defensive check at the throw site, no new error code, no new include.
d Test intent preserved / new tests added? New 04512_remote_missing_named_collection.sh (+.reference) with 8 arms. Nothing existing weakened: 04511_remote_named_collection_complex_overrides (the nearest neighbour and the carrier's origin) is byte-identical and still passes.
e Both directions demonstrated? Yes, on two binaries whose Build IDs were each asserted against the running server. Fix bbd045b1: the four missing-collection arms report 669 and name the collection. Pristine base 72b3babb: the same four report 46/47/46/47 and name nothing, while the cluster-name form, the positional-equality-sharding-key form, an unknown cluster (701) and a live collection are identical on both. Three mutants each redden a different arm: reverting the flag reddens the four 669 arms; forcing it always-true reddens the cluster-name arm; widening it to any later argument reddens the positional-sharding-key arm.
f Fix is general across code paths? The shared parser has exactly two callers and both are covered by arms: TableFunctionRemote.cpp:30 (table function) and StorageDistributed.cpp:2519 (engine, the CI carrier). Fixed once at the shared parser rather than per carrier. cluster/clusterAllReplicas are excluded by construction (the call site is gated on !is_cluster_function) and measured unchanged. StorageURL.cpp:2163 is the other call site passing false and is deliberately left alone: it belongs to the separate startup-tolerance work in #110529.
g Fix generalizes across inputs (params/datatypes/wrappers)? Measured with the collection missing, all 669: override keys database, db, table, user, sharding_key, for both remote and remoteSecure. Boundaries measured and unchanged: the single-argument form remote(nc_missing) still gives 701 CLUSTER_DOESNT_EXIST (the flag is never reached), and a string-literal first argument with an equals second argument is unaffected because getCollectionName returns nullopt before the flag is read. cluster(...) unchanged in both shapes.
h Backward compatible? Yes, and no maintainer exception is needed. No setting, no default, no serialization or on-disk format, no header or ABI change, so no SettingsChangesHistory.cpp entry. Every affected call already failed with 46 or 47, so no query that succeeds today changes behaviour: only the error code and message change. The persisted DDL was already correct, which is why re-creating the collection makes the same metadata attach and read.
i Invariants and contracts preserved? The flag is computed before the call and read once; no lifetime, locking or ordering concern is introduced. The positional branch is entered on exactly the same conditions as before except for the newly-fatal shape, which previously always threw anyway. args[1] cannot be a positional sharding key: it is consumed by the database/table arm at :225-262, which runs before the credentials and sharding-key block at :280 (that block only runs with arg_num >= 2). The new throw comes from an existing throw site with an existing error code.

Session id: cron:clickhouse-review-slot-9:20260805-133800

@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @KochetovNicolai, could you review this? parseRemoteFunctionArguments looked a named collection up with throw_unknown_collection = false, so a missing collection silently fell through to positional parsing and the override was analyzed as a data expression, reporting something unrelated (Function with name `merge` does not exist); since the first argument may also be a cluster name, the lookup is made fatal only when the second argument is a key = value pair, which no positional signature accepts.

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

clickhouse-gh Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [93007dc]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb IGNORED
AST fuzzer (amd_debug) FAIL
Logical error: 'database_name != "_temporary_and_external_tables"' (STID: 2508-48e6) FAIL cidb IGNORED

AI Review

Summary

This PR makes remote/Remote treat a key = value second argument as unambiguously the named-collection form, so a missing collection now reports NAMED_COLLECTION_DOESNT_EXIST instead of falling through to positional parsing and surfacing unrelated UNKNOWN_FUNCTION / UNKNOWN_IDENTIFIER errors. I found no unresolved contract or evidence gaps: the new guard matches the same equals AST carrier that the named-collection override parser already consumes, keeps the valid cluster-name and positional-sharding-key cases intact, and the new stateless test covers both the table-function and engine callers.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 8/8 (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 5, 2026
@PedroTadim PedroTadim self-assigned this Aug 5, 2026
@groeneai

groeneai commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 93007dc

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
AST fuzzer (amd_debug) / Logical error: 'database_name != "_temporary_and_external_tables"' (STID 2508-48e6) pre-existing engine defect: Merge enumerates the internal temporary-tables database; 16 rows across 16 distinct pull requests in 30 days, 1 on master #113224 (external, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / Logical error: Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) pre-existing engine defect: an empty mergeable-stage header disagrees with the chunk the source produces; 14 rows across 13 distinct pull requests in 30 days a fix task is moved to pending (investigating at full effort - fixing-PR link to follow on this PR)
Build (arm_release) / Post Hooks infra: build_profile_hook.py telemetry INSERT rejected with LogCluster query failed with code 500 #113409 (external, open)

All 174 check-runs completed and Finish Workflow succeeded.

Session id: cron:our-pr-ci-monitor:20260805-230000

NamedCollectionPtr named_collection;
VectorWithMemoryTracking<std::pair<std::string, ASTPtr>> complex_args;
if (!is_cluster_function && (named_collection = tryGetNamedCollectionWithOverrides(args, context, false, &complex_args, dependent_table_id)))
/// A `key = value` second argument occurs only in the named-collection form: no positional

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@groeneai are you sure this issue doesn't exist with other table functions with key = value arguments?

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.

Fair question, and I had not measured it, so I did. No: remote/remoteSecure are the only ones. key = value support is not the discriminator -- the caller must also resolve the collection non-fatally, and only these two did.

The helper defaults to throw_unknown_collection = true (NamedCollectionsHelpers.h:31), routing to NamedCollectionFactory::get, which raises NAMED_COLLECTION_DOESNT_EXIST (NamedCollectionsFactory.cpp:54-66). Only a caller passing false gets tryGet's nullptr (:85-93), which is what makes the if fail and lets parsing continue positionally. So the census is just the flag:

git grep -n tryGetNamedCollectionWithOverrides -- src/

27 AST-form call sites on master: 25 pass true, exactly 2 pass false -- parseRemoteFunctionArguments.cpp:91 (this PR) and StorageURL.cpp:2163. The 6 dictionary sites use the config-form overload, which always calls get. :2163 is not a parsing path: it is inside overrideURLInEngineArgs, which reads the url key opportunistically; the URL engine parses at :2195 with true. After this PR :2163 is the only false left.

Not wanting to leave that as a code-reading argument, I probed every registered table function and engine on a pristine master build against a collection that does not exist. Of 93 table functions, 48 report 669 (including 17 of the 18 *Cluster variants) and 41 never attempt a lookup; the only 4 doing neither are remote, remoteSecure, cluster, clusterAllReplicas. Of 83 engines, 30 report 669 and only Remote/RemoteSecure do not.

cluster/clusterAllReplicas never reach the collection branch, which is guarded by !is_cluster_function (:91, comment at :86). Measured rather than assumed: cluster() gives the same 170 BAD_GET when the collection exists, and for a string-literal first argument, so it just means "key = value is not a cluster() argument". The nearest counterexample is mergeTreeIndex, which does take key = value arguments but whose first argument is a database name, so there is no lookup to fall through from. Both unchanged.

One behaviour change worth flagging rather than letting you find it: remote(<cluster name>, database = 'd') also moves from 170 to 669 There is no named collection `<cluster name>` . That combination has no valid reading -- no positional signature accepts key = value second, and the collection form needs the collection to exist -- so both are rejections and 669 is the accurate one. Plain positional remote(<cluster name>, db, table) is untouched, which is why the false was there originally.

Base vs this build, per shape

The symptom on master is three different errors depending on which key is overridden, all invented by the positional reparse:

shape master this PR
remote(nc_missing, database = 'd') 170 BAD_GET 669
remote(nc_missing, database = merge('x','^y$')) 46 Function with name `merge` does not exist 669
remote(nc_missing, sharding_key = rand()) 47 Unknown ... identifier `sharding_key` 669
remoteSecure(...), ENGINE = Remote(...), ENGINE = RemoteSecure(...) 170 669
url/s3/mysql/mongodb and their engines 669 669, unchanged
BACKUP ... TO S3(nc_missing, ...) 36, already names the collection 36, unchanged

Probe (*Cluster variants take the collection at argument 2):

SELECT * FROM <tf>(nc_missing, database = 'd');
CREATE TABLE t (x UInt8) ENGINE = <E>(nc_missing, database = 'd');
SELECT * FROM <tf>('some_cluster', nc_missing, database = 'd');

@PedroTadim
PedroTadim added this pull request to the merge queue Aug 6, 2026
Merged via the queue into ClickHouse:master with commit f845f92 Aug 6, 2026
177 of 180 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 6, 2026
@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai 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