Skip to content

Fix LOCAL in a join being taken as an implicit alias of the left table - #120222

Merged
PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-inconsistent-ast-local-join-alias
Nov 4, 2026
Merged

PedroTadim merged 4 commits into
ClickHouse:masterfrom
groeneai:fix-inconsistent-ast-local-join-alias

Conversation

@groeneai

@groeneai groeneai commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119190

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

LOCAL between a table and a join, as in SELECT * FROM a LOCAL JOIN b ON a.k = b.k, is now parsed as the join locality qualifier, like GLOBAL, instead of being silently taken as an implicit alias of a. A query that relies on such an implicit local alias, for example SELECT * FROM t local JOIN u ON local.id = u.id, now fails; write t AS local instead. Stored view and table definitions are not affected, because they are saved with an explicit AS.

Description

ParserAlias::parseImpl refuses a keyword as an implicit alias only if it is in restricted_keywords. GLOBAL is; LOCAL was not, so the alias parser consumed it before ParserTablesInSelectQueryElement could read the locality. Two consequences:

  1. The qualifier is silently ignored. SELECT * FROM ta LOCAL CROSS JOIN tb formats back as ... FROM ta AS LOCAL CROSS JOIN tb. Not cosmetic: with it EXPLAIN shows Locality: LOCAL, switches to SpillingHashJoin(ConcurrentHashJoin) and drops cost/NDV estimation.

  2. Assertions-enabled builds abort. A parenthesized join and a pipe operator desugar into a plain SELECT whose left table has no alias, re-opening the implicit-alias slot on the second parse. ASTTableJoin::updateTreeHashImpl hashes locality, so the round trip is unstable and executeQuery.cpp's debug-only check raises Inconsistent AST formatting: SELECT * FROM (ta LOCAL CROSS JOIN tb) aborts a debug server; GLOBAL there is fine.

The fix refuses LOCAL as an implicit alias only when the next token is one of the 14 keywords the join grammar admits between a locality qualifier and JOIN, unless those tokens start an ARRAY JOIN, whose optional LEFT/INNER prefix reuses two of them and carries no locality. local stays a valid alias, column name and table name wherever a join clause cannot follow it, which 04299_at_time_zone.sql pins as a contract. Where one can, FROM t local JOIN u now reads the locality instead of aliasing t, like GLOBAL; the repository has no such alias. Adding "LOCAL" to restricted_keywords would be one line, but would make SELECT 1 local a syntax error; #110372 made the same narrow choice for COMMENT. Say the word if you prefer it.

OUTER, the only other gap, is left alone: it is read only after a join kind, so no AST can carry it back into keyword text.

Tests extend 04501_format_local_join, which already stated this invariant for explicit AS.


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

Version info

  • Merged into: 26.11.1.1375-master (included in 26.11 and later)

groeneai and others added 2 commits September 15, 2026 11:56
`ParserAlias::parseImpl` refuses a keyword as an implicit alias only when the
keyword is listed in `restricted_keywords`. That array carries `GLOBAL` but not
`LOCAL`, so after a table expression the alias parser consumed `LOCAL` before
`ParserTablesInSelectQueryElement` could read it as `JoinLocality::Local`.

Two consequences. In the plain spelling the qualifier is silently dropped:
`SELECT * FROM ta LOCAL CROSS JOIN tb` formats back as
`SELECT * FROM ta AS LOCAL CROSS JOIN tb`, and the qualifier is not cosmetic,
since `EXPLAIN` shows `Locality: LOCAL`, selects
`SpillingHashJoin(ConcurrentHashJoin)` and drops cost and NDV estimation only
when it survives. And on assertions-enabled builds the query aborts: a
parenthesized join and a pipe operator each desugar into a plain `SELECT` whose
left table has no alias, which re-opens the implicit-alias slot on the second
parse, so the same text parses into a different tree.
`ASTTableJoin::updateTreeHashImpl` hashes `locality` while `getID` does not
print it, which is why the two trees the error message dumps look identical
while their hashes differ.

Refuse `LOCAL` as an implicit alias only when the next token is one of the 14
keywords the join grammar admits between a locality qualifier and `JOIN`, read
off `ParserTablesInSelectQueryElement::parseImpl` and `parseJoinStrictness`.
The peek uses `IParser::checkWithoutMoving`, which takes its position by value,
so the cursor cannot move, and a private `Expected` keeps the error-message
variants unpolluted.

`ARRAY`, the comma of a comma join, and `OUTER` are deliberately excluded so
they keep their current permissive parse. The first two are tested before the
locality keywords, so they can never follow a locality. `OUTER` is consumed only
after a join kind and every kind keyword is already restricted, so no tree can
carry a swallowed `OUTER` back into text that spells a keyword.

Adding `"LOCAL"` to `restricted_keywords` would be a single line, but it would
reserve the word for every implicit alias in the language and turn
`SELECT 1 local` into a syntax error, which this bug does not require. The same
narrow choice was made for `COMMENT` in the same function, and
`tests/queries/0_stateless/04299_at_time_zone.sql` pins the compatibility of
`local` as a column name and an alias as a contract.

Related: ClickHouse#119190

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit refuses `LOCAL` as an implicit alias whenever one of the
14 keywords the join grammar admits between a locality qualifier and `JOIN`
follows it. `ARRAY JOIN` is a sibling of the join clause, tried first in the
element parser, and it accepts an optional `LEFT` or `INNER` prefix, so a
one-token peek cannot tell `local LEFT ARRAY JOIN [1]` from
`local LEFT JOIN tb`. Both were refused, the token was then read as the
locality, and the mandatory `JOIN` never arrived: two previously valid
queries became SYNTAX_ERROR.

Skip the refusal when an `ARRAY JOIN` starts at the peek position, in any of
its three spellings. `ASTArrayJoin` carries no locality, so nothing is lost
by leaving the alias in front of it, and the collision set is exactly
`{LEFT, INNER} x ARRAY JOIN`: `LEFT OUTER ARRAY JOIN` is a syntax error
before and after this change.

Both prefixed spellings are pinned as compatibility rows, alongside a
`local LEFT JOIN ... ON` discriminator so they cannot be satisfied by
dropping `LEFT` and `INNER` from the peek set instead. Two further rows
cover the remaining join-grammar positions that no earlier row reached: a
bare `JOIN` with the kind defaulted, and a leading `NATURAL`.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-self PR origin: self-found defect (impact-bar validated) labels Sep 15, 2026
@groeneai

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

Two rounds of pre-publication review by an independent model (engine: codex; 2 findings) plus my own
cold review of the resulting tree in each round, done before reading any of the implementation notes
(3 findings). One implementation question is adjudicated here too. The round-1 blocker was fixed and
re-reviewed; round 2 found nothing to fix.

# Sev Finding Verdict Evidence / action
1 ❌ The one-token lookahead also refuses local in front of LEFT ARRAY JOIN and INNER ARRAY JOIN, turning valid queries into syntax errors (src/Parsers/ExpressionElementParsers.cpp, ParserAlias::parseImpl) AGREE, fixed @ 12d984e1fbc6a ARRAY JOIN takes an optional LEFT/INNER prefix (ParserArrayJoin::parseImpl) and is a sibling of the join clause, so both spellings were refused and the mandatory JOIN never arrived. The peek now stands down when an ARRAY JOIN starts at that position, and three rows pin the boundary, including a LOCAL LEFT JOIN discriminator so the rows cannot be satisfied by dropping LEFT/INNER from the set. The collision set is exactly {LEFT, INNER} x ARRAY JOIN: LEFT OUTER ARRAY JOIN is a syntax error before and after, so no third spelling exists
2 ⚠️ Keyword::JOIN and Keyword::NATURAL each hold their own grammar position after the locality and no test row reaches them, so either can be deleted with the suite green AGREE, fixed @ 12d984e1fbc6a Own review. Two format rows added for the bare LOCAL JOIN ... ON ... and LOCAL NATURAL JOIN spellings, each mutation-checked: deleting either keyword now reddens exactly one line. Rows were deliberately NOT added for ALL, ASOF, SEMI, ANTI, ONLY, RIGHT, FULL: each shares a grammar position with a keyword already covered
3 ⚠️ The changelog entry cited SELECT * FROM a LOCAL JOIN b, which does not parse AGREE, fixed in the PR body ON or USING is mandatory unless the join is comma, CROSS, PASTE or NATURAL, so the example a changelog reader would copy was a syntax error. The entry now reads SELECT * FROM a LOCAL JOIN b ON a.k = b.k
4 💡 The description implied no compatibility cost AGREE, fixed in the PR body It now states the one behaviour change: where a join clause can follow, FROM t local JOIN u reads the locality instead of aliasing t, exactly as GLOBAL already does, and no such alias exists in the repository
5 💡 The test comment and the description say an unstable round trip aborts the server, but the debug consistency check throws a LOGICAL_ERROR rather than terminating the process DISAGREE On a debug or sanitizer build a LOGICAL_ERROR is a termination: Exception::handleErrorCode (src/Common/Exception.cpp) routes it to abortOnFailedAssertion, which logs Logical error: '...' and then calls abort(). Measured on the base build: the server log shows <Fatal> : Logical error: 'Inconsistent AST formatting: ...' followed by <Fatal> BaseDaemon: ... Received signal Aborted (6), the test runner reports ClickHouse server died during test '04501_format_local_join', and the standalone repro exits 134. Both texts already scope the claim to assertions-enabled builds, and neither describes it as a crash; the release-build consequence is stated separately
6 ⚠️ The new rows extend 04501_format_local_join instead of going into a new test file DISAGREE That file's header already states this exact invariant, and its two statements are the explicit-AS half of the same contract, which is precisely why they never trip the implicit-alias path; a second file would be a near-duplicate of a test of the same subject. Happy to split it out if you prefer a separate file

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

@clickhouse-gh clickhouse-gh Bot closed this Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 4/4 and 100% reproducible: SELECT * FROM (ta LOCAL CROSS JOIN tb), the same with INNER/PASTE, and FROM ta |> LOCAL CROSS JOIN tb |> ORDER BY ALL each give rc=134 + Received signal 6 + Inconsistent AST formatting on a debug binary with real Memory tables. Through the test runner the base server dies outright (Reason: server died 32).
b Root cause explained? Yes. ParserAlias::parseImpl refuses a keyword as an implicit alias only via restricted_keywords, which contains GLOBAL but not LOCAL, so the alias parser consumed LOCAL before ParserTablesInSelectQueryElement could read JoinLocality::Local. ASTTableJoin::updateTreeHashImpl hashes locality while getID does not print it, which is why both dumpTree dumps in the error are identical while the hashes differ. A parenthesized join and a pipe operator each desugar into a plain SELECT whose left table has no alias, re-opening the implicit-alias slot on reformat.
c Fix matches root cause? Yes, at the alias parser's decision point, not a guard at the abort site. No widened bound, no no-random-* tag, no dataset reduction, no defensive null check.
d Test intent preserved / new tests added? Yes. The existing 04501_format_local_join already stated this invariant for the explicit-AS spelling; its two statements are kept byte-for-byte and its header extended, rather than a near-duplicate file being added. +34 reference lines covering both carriers, six implicit spellings (incl. a bare LOCAL JOIN ... ON and LOCAL NATURAL JOIN, which are separate positions in the join grammar), GLOBAL controls, OUTER non-change pins, the executed reproducers, an EXPLAIN assertion and 13 compatibility pins. Every added row is backed by a mutation check: deleting the code it covers reddens it and only it.
e Both directions demonstrated? Yes, with two servers differing only in this 26-line diff. Base: [ FAIL ] Reason: server died 32 with <Fatal> Logical error: 'Inconsistent AST formatting: ...'. Fix: [ OK ]. Every matrix row measured on both binaries; the four carriers move stable 0 to 1 with their canonical text unchanged, the four implicit spellings lose the spurious AS, and the GLOBAL, OUTER and compatibility rows are byte-identical.
f Fix is general across code paths? Yes. One change fixes both desugaring carriers. The 14-keyword peek set was read off ParserTablesInSelectQueryElement::parseImpl and parseJoinStrictness, and each enumerator verified in CommonParsers.h; ARRAY/FINAL/SAMPLE/OFFSET/STREAM/USING/ON are already restricted, , is not an identifier. OUTER is provably not a carrier (only read after a kind keyword, all of which are restricted) and is pinned unchanged. GLOBAL, the only other JoinLocality value, is already restricted. restricted_keywords has exactly one consumer and is not modified.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes, and the coverage is by grammar position rather than by keyword count. The join grammar admits four positions after the locality, and each now has a row: a kind directly (CROSS/INNER/PASTE, plus LEFT as the immediate token), a strictness first (ANY LEFT), NATURAL first, and a bare JOIN with the kind defaulted. Also upper and lower case spelling, a nested parenthesized join (exercising the join grammar's own bare ParserAlias, a different call site from ParserWithOptionalAlias), and the pipe operator. No rows for ALL/ASOF/SEMI/ANTI/ONLY/RIGHT/FULL: each shares a grammar position with a keyword already covered. Type wrappers do not apply to a parser-level keyword decision.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, so no SettingsChangesHistory.cpp entry; no serialization or format change. The behaviour delta against master is exactly one thing: a local immediately in front of a join clause is read as the locality instead of as an implicit alias of the left table, which is the bug. In particular ARRAY JOIN is excluded, so FROM t local LEFT ARRAY JOIN ... and FROM t local INNER ARRAY JOIN ... keep the alias even though LEFT and INNER also begin a join clause. local remains a valid implicit alias, column name and table name, pinned by 13 rows including all three ARRAY JOIN spellings and the deliberate exclusions (,, WHERE, ORDER BY); tests/queries/0_stateless/04299_at_time_zone.sql, which pins that compatibility as a contract, passes untouched.
i Invariants and contracts preserved? Yes. IParser::checkWithoutMoving(Pos pos, Expected &) takes Pos by value, so the peek cannot move the cursor on any path, including the early return false. A private Expected peek_expected keeps error-message variants unpolluted, matching the neighbouring COMMENT block. The block sits inside if (!has_as_word && !is_quoted), so an explicit AS LOCAL and a quoted `local` never reach it. static constexpr array, no allocation, no state.

Session id: cron:clickhouse-impl-self-slot-57:20260915-145000

@clickhouse-gh

clickhouse-gh Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7f83cf6]

Summary: ✅


AI Review

Summary

The PR preserves LOCAL as a join-locality qualifier when no explicit table alias precedes it, fixing unstable formatting for parenthesized joins and pipe operators while preserving aliases before ARRAY JOIN. No actionable findings remain. The prior persisted-metadata concern does not hold because stored aliases use explicit AS. The regression test 04501_format_local_join passed in the Fast test report for the reviewed head.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 15, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. label Sep 15, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 12d984e

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 profile diff job-level RuntimeError: CI logs cluster query failed: SELECT count() AS c FROM binary_sizes, raised in has_pr_data at ci/jobs/build_profile_diff_job.py:723: the readiness probe collapses every non-ok response into a bare False, so a transient CI logs cluster refusal is fatal and the job prints a single opaque line. Not reachable from this diff: the job only reads binary_sizes on the logs cluster. Measured 137 red heads across 123 distinct pull requests since 13:14Z today and 204 error rows in 7 days; the job runs on pull requests only, so there is no master arm #120121 (mine, open)

PR is the workflow rollup of the row above, not an independent failure. No test-level failure was
ingested for this head, and CH Inc sync is green.

Session id: cron:our-pr-ci-monitor:20260915-213215

@PedroTadim
PedroTadim enabled auto-merge November 4, 2026 16:28
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7f83cf671 with master 989ecd896 (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

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

Job report

@PedroTadim
PedroTadim added this pull request to the merge queue Nov 4, 2026
Merged via the queue into ClickHouse:master with commit 1f99913 Nov 4, 2026
185 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 4, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @PedroTadim — this PR looks backward incompatible but is categorized as Bug Fix (user-visible misbehavior in an official stable release).

Why: The new LOCAL branch in ParserAlias::parseImpl (ExpressionElementParsers.cpp:2164-2184) turns FROM x local JOIN y from an alias into a locality. SELECT count() FROM numbers(3) local JOIN numbers(3) AS r ON local.number = r.number returns 3 on 26.10 and fails with ALIAS_REQUIRED on master.

Suggested category: Backward Incompatible Change. Ignore if the change is intentionally non-breaking.

@groeneai

groeneai commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Agreed: SELECT * FROM t local JOIN u ON local.id = u.id works on 26.10.3.7 and fails on master, so I changed the category to Backward Incompatible Change and rewrote the changelog entry to name the t AS local workaround.

@PedroTadim

PedroTadim commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Yes, it is backward incompatible, but a very edge case

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-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. groeneai-origin-self PR origin: self-found defect (impact-bar validated) 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.

5 participants