Skip to content

Fix alias-keyed additional_table_filters being ignored for *Cluster table functions - #122579

Open
groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:cluster-table-function-additional-table-filters
Open

groeneai wants to merge 13 commits into
ClickHouse:masterfrom
groeneai:cluster-table-function-additional-table-filters

Conversation

@groeneai

@groeneai groeneai commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #122544

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

Fix additional_table_filters for reads through *Cluster table functions (urlCluster, s3Cluster, fileCluster and the others): an entry keyed by the alias of the table function was silently ignored, so the query returned unfiltered rows. Closes #122544.

Description

On 26.8.10.6-lts and 26.9.1.1629-stable, SELECT sum(n) FROM urlCluster('test_cluster_one_shard_three_replicas_localhost', '<url returning 0..3>', TSV, 'n UInt64') AS t SETTINGS additional_table_filters = {'t': 'n > 1'} returns the unfiltered 6 instead of 5.

Root cause. The initiator matches the entry by the alias t, but reads the cluster storage at WithMergeableState, leaving the filter to the replicas. They receive the query rendered from the analyzed tree, where the table expression is __table1, so the alias entry matches nothing. A full-name key (_table_function.urlCluster) worked only because the replica resolves that name itself.

Change. One site, IStorageCluster::read, used by every cluster storage. Above FetchColumns, the initiator forwards its resolved filter as the first additional_table_filters entry, keyed by the full name the replica resolves for the forwarded table function (_table_function.urlCluster), and removes the setting from the text's top-level SETTINGS, which would override it. The replica applies it below the query's WHERE, as for a plain read. A replica has its own current database, so the filter's table names are qualified and currentDatabase(), also written without parentheses, is replaced with the session's database; its aliases, lambda parameters and columns, including subcolumns, virtual columns and Nested columns, stay as written, as does the right side of IN in a subquery.

Not covered (pre-existing, as for the full-name key): an alias-keyed entry for a table read in an IN subquery, which the replicas plan themselves; data-lake catalog tables; a table on the right of IN in a subquery or with an alias, read from the replica's database; a temporary table in the filter, never sent to the replicas; the current database in a SQL function body, or written without parentheses in a subquery of the filter.

Validation. The new test fails on the base build and passes with the fix, 50 randomized + 50 plain runs.

Measured matrix, base -> fix

Filter n > 1 over the numbers 0..3 (correct sum: 5).

  • urlCluster, fileCluster, s3Cluster, alias key: 6 -> 5; alias + full-name keys (n > 2): 3 -> 5; full-name key: 5 -> 5
  • urlCluster in a JOIN, left or right, every join_algorithm, with and without the table swap: 6 -> 5
  • enable_parallel_replicas 0/1 x serialize_query_plan 0/1, and the setting given at session level: 6 -> 5
  • toString(n) filter: base ignored it (6), now ILLEGAL_TYPE_OF_COLUMN_FOR_FILTER, as for a plain url read
  • an entry for another table read in an IN subquery keeps applying (fix 2, base 3)
  • a filter reading a table of the current database (IN subquery, IN <table>, dictGet, joinGet) after USE other_db: 6 -> 5
  • after USE other_db, currentDatabase() / current_schema() in the filter: 6 -> 5; full-name key: 0 -> 5
  • the same, CURRENT_DATABASE / DATABASE / SCHEMA / CURRENT_SCHEMA without parentheses, unless the name is a column, an alias or a lambda parameter: 6 -> 5; full-name key: 0 -> 5
  • n IN arr (an array column), arrayExists(x -> n IN x, [[2, 3]]): 6 -> 5; full-name key: 5 -> 5
  • a column of a subquery, n IN (SELECT id FROM ids WHERE id IN allowed): 6 -> 5; full-name key: 5 -> 5
  • a SQL function threshold -> arrayExists(n -> n > threshold, [3]) applied to n (correct sum: 3): 6 -> 3; full-name key: 3 -> 3
  • a filter using its own alias, n IN ([2, 3] AS allowed) AND n IN allowed: 6 -> 5; full-name key: 5 -> 5
  • a subcolumn, virtual column or Nested column on the right of IN (n IN `tup.arr` , 'x' NOT IN _tags, tuple(n) IN nest): 6 -> 5; full-name key: 5 -> 5
  • the query's own WHERE throwIf(n = 0) = 0, with default settings and with short-circuit evaluation off and filters unmerged: base error -> 5; full-name key: 5 -> 5

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

groeneai and others added 3 commits September 27, 2026 20:27
…function read

An `additional_table_filters` entry keyed by the alias of a `*Cluster` table function
(`urlCluster`, `s3Cluster`, `fileCluster`, ..., and `url`/`s3` converted automatically by
`parallel_replicas_for_cluster_engines`) was silently ignored: the query returned
unfiltered rows.

The initiator matches the entry by the original alias and builds the filter, but it reads
the cluster storage at `WithMergeableState`, where the planner adds the filter steps only
for `FetchColumns`, so the filter is left to the replicas. They receive the query rendered
from the analyzed tree, in which the table expression is renamed `__table1`, together with
the unchanged setting (in the settings packet and in the text's own `SETTINGS` clause), and
resolve it against that text: the alias matches nothing. A key naming the table function by
its full name (`_table_function.urlCluster`) worked only because the replica resolves that
name itself, and with both kinds of entries the replica applied the full-name one instead
of the first match.

`IStorageCluster::read` now ANDs the filter the initiator resolved into the `WHERE` of the
forwarded query when the read is shipped above `FetchColumns` and reads a table function,
so the replica evaluates it before any partial aggregation, like a user-written `WHERE`. It
also removes the entries keyed by the full name of the forwarded table function from the
forwarded settings (the packet and the text's top-level `SETTINGS`), so a replica cannot
apply a second entry to the same read. Entries naming other tables of the forwarded query
are forwarded unchanged, and a read at `FetchColumns`, where the initiator applies the
filter itself, and data-lake catalog table reads are unchanged.

Closes ClickHouse#122544

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e function read

The filter the initiator resolved now reaches the replica as the first
`additional_table_filters` entry, keyed by the full name of the forwarded table
function, so the replica applies it as its own filter step below the query's
`WHERE`, as for a plain read. Folding it into the forwarded `WHERE` let the query's
own condition see the removed rows (`throwIf`) and changed the full-name key,
which already worked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep only the invariants in the IStorageCluster::read comment: first-match resolution of additional_table_filters on the replicas, the generated table alias in the forwarded query, and that the initiator applies the filter itself at FetchColumns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 27, 2026
@groeneai

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

Pre-publication review by an independent model (3 findings over two rounds) plus my own review (nits only).

# Sev Finding Verdict Evidence / action
1 ❌ Folding the filter into the forwarded WHERE let the query's own condition (throwIf(n = 0)) see rows the filter removes, unlike a plain read, and regressed the full-name key AGREE, fixed @ cef85a0 the resolved entry is forwarded first in additional_table_filters, so the replica applies it as its own filter step; test line added
2 ⚠️ The test covered neither the automatic url -> urlCluster conversion nor an entry for another table AGREE, fixed @ cef85a0 two test lines added, each red on the base build and under a mutation of the fix
3 ⚠️ The automatic-conversion line also returns 5 on a plain url read, so it would pass if the conversion stopped DISAGREE every input of the conversion condition (TableFunctionURL.cpp:347-353) is pinned in the line's SETTINGS; EXPLAIN shows ReadFromCluster, base returns 6; only a code change stops the conversion (#122306, whose test asserts ReadFromURL 5 for this query, which this line keeps passing)
4 💡 A __table1 key and an alias defined inside the filter behaved differently from a plain read AGREE, fixed @ cef85a0 resolved by the change for 1

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-9:20260927-215900

@clickhouse-gh

clickhouse-gh Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [28460ff]

Summary: ✅


AI Review

Summary

This PR forwards the initiator-matched additional_table_filters predicate to workers of *Cluster table functions and preserves database-dependent expressions. At head 28460ff161a8f276ddf3f931d4988056f4763b95, two existing scope defects still allow workers to evaluate a different predicate and silently return incorrect results. ❌ Block pending those fixes.

Findings

❌ Blockers

  • src/Interpreters/AddDefaultDatabaseVisitor.h:137: Lambda-local expression aliases still affect outer table resolution. The synthetic select invokes collectAliases, which descends into lambda bodies and adds their aliases to the enclosing expression_aliases. The lambda branch only saves/restores with_expression_aliases, so it does not undo that leakage. For the predicate n IN ids AND arrayExists(x -> (x AS ids) > 0, [1]), the local alias prevents qualification of the unrelated outer IN ids. With the session database review_other, review_other.ids containing 2,3, and the worker's default.ids containing 3, reading n = 0..3 yields sum(n) = 3 instead of 5. Both the alias and full-name filter keys are affected. Collect expression aliases separately for each lambda scope, while retaining visibility inside the owning lambda. Existing thread.

  • src/Interpreters/AddDefaultDatabaseVisitor.h:141: A nested lambda declaration suppresses substitution of unrelated built-in calls. collectLambdaAliases collects names across all subqueries and lambdas; substituteCurrentDatabase then uses that same set throughout the predicate. After USE review_other, the predicate n > 1 AND currentDatabase() = 'review_other' AND (WITH (() -> 'shadow') AS currentDatabase SELECT currentDatabase()) = 'shadow' must preserve the outer built-in and the subquery-local lambda independently. Instead, both calls remain unchanged: a worker using default evaluates the outer comparison as false, producing sum(n) = 0 instead of 5 over 0..3. Both filter keys are affected. Track function-alias bindings at their query/lambda scope boundaries and substitute only calls that resolve to the built-in. Existing thread.

Tests
  • ⚠️ Add focused stateless coverage for both predicates above, with both filter keys and different initiator/worker databases. The existing lambda-alias case exercises the separate niladic-identifier substitution pass; the shadowing-lambda case never combines the nested declaration with an outer built-in call, so neither protects these invariants.
Missing context / blind spots
  • ⚠️ No local ClickHouse binary or build is available. The remaining findings were verified by tracing the current source against the concrete reproductions in their existing threads; rerunning those cases would provide runtime confirmation.
Final Verdict

❌ Block. Preserve expression-alias and function-alias scope during filter qualification/substitution, and add the focused regressions above. Both findings already have inline threads; no duplicate review comments were posted. The fixed quoted-subcolumn thread was resolved.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 27, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 27, 2026
Comment thread src/Storages/IStorageCluster.cpp Resolved
Comment thread src/Storages/IStorageCluster.cpp Resolved
… a cluster table function read

A replica resolves an unqualified table name in the forwarded filter against its own
current database, which is the default database of the user, not the current database of
the initiator's session. After `USE other_db`, a filter such as
`{'t': 'n IN (SELECT id FROM probe)'}` failed on every replica with `UNKNOWN_TABLE`,
which `skip_unavailable_shards` (always on for cluster table functions) turned into an
empty result. A plain `url` read resolves the filter on the initiator and returns the
filtered rows.

The forwarded filter now carries the tables qualified with the initiator's current
database (table expressions, the right argument of `IN`, `dictGet`/`joinGet`), like the
tables of the forwarded query itself. Common table expression names stay unqualified.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 28460ff16 with master f83293657 (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.

Object file sizes

12 object files changed (+92.01 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/IStorageCluster.cpp.o 392.75 KiB 472.31 KiB +79.57 KiB (+20.26%)

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

19 translation units recompiled, 169 s compile time in total, 19 of them have a recent master baseline.

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

Job report

@clickhouse-gh

clickhouse-gh Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 36 queries analysed

This PR only changes IStorageCluster::read, and the new block runs only when a *Cluster table function is combined with additional_table_filters. Neither ClickBench nor TPC-H runs that path. The one flagged row, clickbench Q34 at +5.4%, was already held at not_sure because it falls inside master's normal variance band. CPU time for that query is flat and the PR's measurements were noisier than the baseline, so the suppression matches the diff and no query shows a performance change from this PR.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1118 1178 +5.4% <0.0001 The +5.4% change is inside master's current variance band and CPU time is flat (16331 vs 16340 ms). ClickBench Q34 reads a local MergeTree table and never reaches IStorageCluster::read, so the new code cannot explain it.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 3e205c1e-ca16-4e82-b63d-1ed45fbb7e61
  • MIRAI run: 113d7797-1cae-4ef0-8fb4-7e1cafe4935b
  • PR check IDs:
    • clickbench_2603829_1790810978
    • clickbench_2603835_1790810978
    • clickbench_2603847_1790810978
    • tpch_adapted_1_official_2603858_1790810978
    • tpch_adapted_1_official_2603885_1790810978
    • tpch_adapted_1_official_2603899_1790810978

…le function name

A replica names the storage of a table function after `ITableFunction::getName()` of the
function `TableFunctionFactory` resolves (`Context::executeTableFunction`), so the entry the
initiator forwards for a cluster table function read is now keyed by that name instead of
by the spelling in the forwarded query. Every `*Cluster` table function is currently
registered case-sensitively and without aliases, so the key is unchanged today; this keeps
it matching if a case-insensitive name or an alias is added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/IStorageCluster.cpp Resolved
groeneai and others added 2 commits November 1, 2026 12:54
…ion-additional-table-filters

Resolve the conflict in src/Storages/IStorageCluster.cpp includes: keep both sets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master no longer converts a url or s3 read to its cluster variant when
additional_table_filters is set (Context::canReplaceClusterEngineWithClusterVariant,
since ClickHouse#122306), so that line read through a plain url and passed without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/IStorageCluster.cpp Resolved
Comment thread src/Storages/IStorageCluster.cpp Resolved
The filter forwarded to the replicas of a cluster table function was qualified
with `visitTableExpressions` directly on the expression, which collects aliases
only inside a select query. So in `n IN ([2, 3] AS allowed) AND n IN allowed`
the second `allowed` became `<db>.allowed`, and the replica failed with
UNKNOWN_IDENTIFIER. This also broke the full-name key, which worked before
because the replica parsed the original text.

`currentDatabase()` in the filter, and the body of a SQL function used in it,
were interpreted on the replica, whose current database is its own (the
`database` setting is not forwarded), unlike for a plain `url` read or for the
query's own `WHERE`, where it is the initiator's.

The SQL functions of the filter are now expanded on the initiator, and
`AddDefaultDatabaseVisitor::visitStandaloneExpression` qualifies the expression
as a select list, so its aliases are collected, and replaces `currentDatabase()`
(and its aliases, now including `current_schema`) with the database, keeping the
alias of the replaced call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Storages/IStorageCluster.cpp Resolved
…er filter

The initiator expanded the SQL functions of the filter forwarded to the replicas
of a cluster table function with `UserDefinedSQLFunctionVisitor`, which
substitutes the arguments by name, so a lambda parameter of the body captured
them: with `threshold -> arrayExists(n -> n > threshold, [3])`, the filter `f(n)`
became `arrayExists(n -> n > n, [3])`. This also broke the full-name key, which
worked before. The replicas expand the SQL functions themselves again.

An identifier on the right of `IN` was qualified with the database even when it
names a column or a lambda parameter, which the analyzer resolves before a
table, so `n IN arr` and `arrayExists(x -> n IN x, [[2, 3]])` failed with
UNKNOWN_IDENTIFIER with either key. The columns of the table are now listed
next to the filter, like its aliases, and a lambda parameter is not qualified
inside its lambda (this also holds for the metadata load path, which shares the
pass). A lambda parameter does not hide a table of the same name outside it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`visitStandaloneExpression` qualified a plain name on the right of `IN`
inside a subquery of the filter as a table, but there it may be a column
of the subquery's tables, which the analyzer resolves before a table.
`n IN (SELECT id FROM ids WHERE id IN allowed)`, with `allowed` an array
column of `ids`, became `... IN <db>.allowed` and failed with
UNKNOWN_IDENTIFIER for the alias key and for the full-name key
`_table_function.urlCluster`, which returns 5 on master.

The columns of a nested select query are not known to the visitor, so
the right argument of `IN` is left as written there, as master forwards
it. Table expressions of the subquery are still qualified.

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

groeneai commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9def424

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
Stateless tests (amd_debug, parallel) / 05474_parquet_corpus_writers not from this PR (it changes only AddDefaultDatabaseVisitor.h, IStorageCluster.cpp and test 05261): master since the merge of #128336 reads the polars 0.20 u64 rows as ok while the reference expected INCORRECT_DATA; true master failed the same way on every head until ca92d3a, which passes. The fix merged at 20:53Z, after this run was created (18:11Z), so the tested merge commit predates it #128494 (ours, merged)
Stateless tests (arm_binary, parallel) / 05474_parquet_corpus_writers same as the row above #128494 (ours, merged)
Stateless tests (arm_asan_ubsan, targeted) / 05474_parquet_corpus_writers, Too many test failures same as the row above; the targeted run stopped at --max-failures on these repeats #128494 (ours, merged)
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) / 05474_parquet_corpus_writers, Too many test failures same as the row above #128494 (ours, merged)
Finish Workflow / Post Hooks new_tests_check.py: both functional Bugfix validation jobs were DROPPED behind the Stateless tests (amd_debug, parallel) failure above, so none reported OK #128494 (ours, merged)
Mergeable Check, PR praktika rollups of the rows above #128494 (ours, merged)
CH Inc sync - CH Inc sync (private, not actionable by me)

CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261101-213002

Comment thread src/Storages/IStorageCluster.cpp Resolved
expression_list.children.push_back(std::move(column));
}
standalone_expression_select = select.get();
visitTableExpressions(*select);

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.

[P1] Keep lambda-local aliases out of the enclosing filter scope

The synthetic select makes collectAliases descend into lambda bodies and collect their expression aliases into the enclosing expression_aliases. For n IN ids AND arrayExists(x -> (x AS ids) > 0, [1]), the alias ids belongs only to the lambda, but it now prevents the outer IN ids table reference from being qualified. The new lambda handling saves and restores parameter names in with_expression_aliases; it does not isolate these expression aliases.

Reproduced with session database review_other, review_other.ids containing 2,3, and the worker's default.ids containing only 3: over the test's 0..3 source, a plain url read returns 5, whereas urlCluster returns 3 with either filter key. Removing the lambda's AS ids restores 5, so a local alias silently changes which table an unrelated part of the filter reads.

Please collect and restore expression aliases at lambda scope boundaries, preserving aliases inside their own lambda without exposing them to the enclosing expression. Cover this predicate after switching databases.

…uster filter

`CURRENT_DATABASE`, `DATABASE`, `SCHEMA`, `CURRENT_SCHEMA` (and the other
spellings of `currentDatabase`) without parentheses stay identifiers in the
AST until the analyzer resolves them as niladic functions, so the filter
forwarded to the replicas was evaluated in the replica's database: after
`USE other_db`, `{'t': 'n > 1 AND CURRENT_DATABASE = ''other_db''}` returned
0 instead of 5, with either key.

The standalone-expression path now replaces such an identifier with the
database too, but only where the analyzer would resolve it as the function:
not when it is a column of the table, or an alias or a lambda parameter of
its scope (a lambda has its own aliases), and not inside a subquery of the
filter, whose columns are not known there. `x AS x` is not taken for an
alias, as in the analyzer. A call `currentDatabase()` is also left as
written when the filter defines a lambda with the alias of that name, e.g.
in a `WITH` clause of a subquery: the analyzer calls the lambda. The query's
own WHERE is a separate path (it is rendered from the initiator's query
tree) and is not changed here.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +135 to +137
NameSet lambda_aliases;
collectLambdaAliases(*expression_list.children.at(0), lambda_aliases);
substituteCurrentDatabase(expression_list.children.at(0), expression_list, lambda_aliases);

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.

[P1] Keep lambda function aliases scoped during database substitution

collectLambdaAliases descends into every subquery and lambda, then substituteCurrentDatabase uses that one name set for the entire predicate. Consequently, a lambda named currentDatabase in one subquery suppresses substitution of unrelated built-in calls outside that subquery.

For example, after USE review_other, add this predicate to the test's 0..3 source:

n > 1
AND currentDatabase() = 'review_other'
AND (WITH (() -> 'shadow') AS currentDatabase SELECT currentDatabase()) = 'shadow'

The outer call must resolve to the session database and the subquery call must invoke its local lambda, giving sum(n) = 5. Here both calls remain in the forwarded AST; the worker evaluates the outer built-in in default, so the predicate rejects every row and returns 0. This affects both the alias key and the previously working full-name key.

Please track lambda bindings per query/lambda scope while substituting calls, so a local declaration protects only calls that actually bind to it. Cover the combination of an outer built-in call and a shadowing lambda in a nested subquery with both keys.

The filter forwarded to the replicas of a cluster table function has its
table names qualified with the initiator's database. The right side of `IN`
is taken for a table unless it is a column, but only the top-level physical
columns were known. So ``n IN `tup.arr` ``, `'x' NOT IN _tags` and
`tuple(n) IN nest` (for the `Nested` columns `nest.*`) had the column
qualified as a table, and the replicas failed with UNKNOWN_IDENTIFIER. That
broke the full-name key too, which works on master.

The virtual columns are now known as well. A name also counts as a column
when the analyzer would resolve it as one: a subcolumn (some split into a
column and a subcolumn its type has, static or dynamic, e.g. `Map`, `JSON`
paths) or the prefix of `Nested` `Array` columns. A table whose name merely
starts with a column name and a dot is still qualified. The same check keeps a
`Nested` prefix named `database` from being replaced with the database name.

A table name with an alias on the right of `IN` is left as written: once
`ids` was qualified, `n IN (ids AS allowed) AND n IN allowed` no longer
resolved `allowed`, while the full-name key works on master.

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

Copy link
Copy Markdown
Collaborator Author

@nickitat master's #130531 (the revert of #114923) removed the table-name qualification pass in AddDefaultDatabaseVisitor.h that this PR uses for the forwarded filter, so the conflict cannot be resolved by a plain merge. The bug is still there: on master 9b10750, an alias-keyed entry on urlCluster returns 6 instead of 5. Which way should I take?

  • A. Bring the removed pass back in this PR, used only for the forwarded filter. The behaviour stays as it is now, but the PR grows to about +400 lines in AddDefaultDatabaseVisitor.h (plus +59 in IStorageCluster.cpp).
  • B. Drop the qualification and only forward the alias-keyed entry under the canonical _table_function.<name> key: about +35 lines in IStorageCluster.cpp, no visitor change. The entry then behaves like the full-name key does on master, where a bare table name or currentDatabase() in the filter resolves in the replica's database: after USE other_db, {'_table_function.urlCluster': 'n IN (SELECT id FROM ids)'} returns no rows, while the same filter on a plain url read returns 5. This also drops the CURRENT_DATABASE handling that you asked for in Fix alias-keyed additional_table_filters being ignored for *Cluster table functions #122579 (comment).

I would take B: it is the smaller fix for the reported bug, and the database case is not specific to alias keys.

This branch has not been deployed

No deployments
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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrong result: an alias-keyed additional_table_filters entry is dropped for cluster table functions (urlCluster, s3Cluster)

2 participants