Skip to content

Fix a view over a temporary table failing with UNKNOWN_TABLE after a restart - #129485

Closed
groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-view-temporary-table-after-reload
Closed

groeneai wants to merge 6 commits into
ClickHouse:masterfrom
groeneai:fix-view-temporary-table-after-reload

Conversation

@groeneai

@groeneai groeneai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Fix a view over a temporary table failing with UNKNOWN_TABLE after a restart

Closes: #129449
Related: #114923

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed a view that reads a temporary table by its unqualified name failing with UNKNOWN_TABLE (or reading a table of the same name in the view's database) after a server restart or ATTACH DATABASE, because the name was qualified with the view's database when the view was loaded. Closes #129449.

Description

On 26.10.2.103-stable, a view that reads a session temporary table by its unqualified name fails with UNKNOWN_TABLE after a server restart (#129449), or reads a table of that name in the view's database.

Caused by #114923 (CI build of its merge 659cc1c2 fails, of its first parent f75df105 passes): qualifyNamesFromLegacyMetadata, which repairs names that SQL UDF expansion left bare in older metadata, also qualified an ordinary view's SELECT with the view's database on load, where no session exists. CREATE VIEW leaves a temporary table's name unqualified on purpose.

StorageView now does that repair itself and keeps the SELECT as stored. When the reading query has temporary tables, the stored SELECT is re-qualified under that query, so a temporary table of the session takes precedence, as at CREATE. Otherwise the name resolves to the view's database, as on 26.10, also in another table's CONSTRAINT evaluated at attach. SQL SECURITY DEFINER and NONE views always use the repaired SELECT, since they run without the reader's temporary tables. Materialized views, column defaults, constraints and the dependency graphs are unchanged.

Validation: the test reloads views with DETACH/ATTACH DATABASE. Eight read temporary objects (FROM, JOIN, IN, scalar subquery, dictGet, a temporary view, a view over a view, a temporary table named like a table of the view's database): each fails on master and passes with the fix, also with randomized settings, as does the issue's repro across a real restart. Passing on both: six controls (materialized views, dictionary, ReplicatedMergeTree, Replicated database), a table whose CONSTRAINT reads such a view attaching (it failed on the previous head of this PR), and DEFINER/NONE views and a reader without the temporary table reading the view's database, also after an ALTER from a session that has it.


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

groeneai and others added 2 commits November 5, 2026 11:26
…rom metadata

`CREATE VIEW` leaves a table name unqualified on purpose when it resolves
to a temporary table of the creating session, so that every reading
session resolves it to its own temporary table. Since ClickHouse#114923,
`qualifyNamesFromLegacyMetadata` qualified every name of a view's SELECT
with the view's database when the definition was loaded from metadata,
under a session-less context. After a restart or `ATTACH DATABASE`, the
view then read `<view db>.<name>`: `UNKNOWN_TABLE` / `UNKNOWN_IDENTIFIER`,
or a permanent table of the same name in the view's database instead of
the session's temporary table.

Nothing reads an ordinary view's SELECT at attach time; it is resolved
only under the reading query, as on 26.9. So the load-time repair now
covers the SELECT of materialized views only, and the column defaults and
constraints of every table, which are analyzed at attach. The dependency
graphs are unchanged, because they resolve a bare name against the
owning database anyway.

Closes ClickHouse#129449

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a reload, the view must read the session's temporary table, not the
permanent table of the same name in the view's database. Each view's whole
result is now checked as one `groupArray` row.

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

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (2 rounds): 1 issue fixed, 1 out of scope
  • ❌ Fixed: the body claims a reloaded view can read a same-named table of its database (wrong rows), but no test case covered it. The test now has a fifth view shadowed by a MergeTree table of the same name, and every view's whole result is asserted.
  • ⚠️ Out of scope (older than Make a table read by a scalar subquery in a CONSTRAINT a loading dependency #114923, different path): a Replicated database qualifies the temporary-table name when it replays CREATE VIEW, so the stored SELECT is already qualified at CREATE (v26.9 InterpreterCreateQuery.cpp:2051, replay at DatabaseReplicatedWorker.cpp:470). Stated in the PR body as not changed.
  • 💡 The behaviour-change sentence also names the table of joinGet, which pre-26.10 CREATE left unqualified too.

Round 2 (test-only delta): no findings.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 05508_view_temporary_table_after_reload fails on every run on master (1/1 fixed settings, 10/10 randomized), on each of its five lines; the issue's repro fails across a real server restart.
b Root cause explained? CREATE VIEW keeps a name that resolves to a session temporary table unqualified. Since #114923, qualifyNamesFromLegacyMetadata qualified every name of a view's SELECT with the view's database on load, under a context without a session, so the view read <db>.<name>.
c Fix matches root cause? Yes. The load-time repair of the SELECT is limited to materialized views; an ordinary view's SELECT is resolved only under the reading query, as before #114923.
d Test intent preserved / new tests added? New SQL-driven test with three sessions and five shapes (FROM, JOIN, IN, scalar subquery, a same-named table in the view's database); each view's whole result is asserted. No existing test changed.
e Both directions demonstrated? Master: all five lines red (UNKNOWN_TABLE x3, UNKNOWN_IDENTIFIER for IN, and the same-named table's row [2] instead of [1]). Fix: OK, 50/50 randomized. CI builds of the #114923 merge and its first parent split the same way.
f Fix is general across code paths? The function is the single place, shared by the attach path and the dependency-graph build, so both stay consistent; graph edges do not change.
g Fix generalizes across inputs (params/datatypes/wrappers)? FROM, JOIN, IN, scalar subquery, and a same-named permanent table in the view's database (master read it, the fix reads the temporary table), in the test; a parameterized view, by probe. Materialized views are unchanged (measured: they never kept such a name across a reload); refreshable ones take the same unchanged branch.
h Backward compatible? (maintainer-approved exception only) No setting or format change; metadata files are not rewritten. Ordinary views from pre-26.10 metadata with a UDF-expanded bare name resolve it as on 26.9 again (described in the PR).
i Invariants and contracts preserved? The attached storage and both dependency graphs are still built from one definition by one function; column default and constraint repair is unchanged for every table; dictionaries are still skipped.

Session id: cron:clickhouse-impl-slot-4:20261105-122300

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alexey-milovidov @tavplubix, could you review this and add the can be tested label so CI runs? Since #114923 the load-time qualifyNamesFromLegacyMetadata also qualified an ordinary view's SELECT with the view's database, so a bare temporary-table name became <db>.<name>; it now applies to materialized views only, and the trade-off for pre-26.10 views with UDF-expanded bare names is described in the PR (review requested by @ PedroTadim on #129449).

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

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [93d9ee2]

Summary: ❌

job_name test_name status info comment
Build profile diff ERROR

AI Review

Summary

This PR restores session temporary-table resolution through ordinary views after metadata reload, while preserving owning-database resolution for legacy definitions and SQL SECURITY DEFINER/NONE execution. Reviewed the current diff, surrounding code, and every prior discussion thread at PR head 93d9ee243be1d25c551784343ae555e732ac5fca. The earlier constraint-attachment blocker is fixed and covered by the regression test. No remaining findings.

Consumers traced for the query-dependent metadata:

  • StorageView::readImpl, analyzer view inlining, the legacy interpreter, and parameterized-view construction consume the query's snapshot and retain the existing SQL security context handling.
  • DESCRIBE, EXPLAIN SYNTAX, system.tables, StorageMerge, and parallel-replica discovery consume query-local metadata without installing it as the view's stored definition.
  • StorageView::alter explicitly uses the base metadata; comment updates use the stored metadata directly. Persistence and backups retain the stored view definition.
Missing context / blind spots
  • ⚠️ The current CI finish report reports runtime jobs skipped because a review thread was unresolved when the run started; a full CI rerun remains necessary. Runtime evidence verified for implementation commit 61167d7dc8aa1f4c80adeae5fc44a642d69be900: the byte-identical regression script passed 50 targeted ASan runs, and amd64 bugfix validation passed. No local build or runtime tests were performed.
Final Verdict

Status: ✅ Approve. No new inline findings or thread changes. The normal CI gate still needs its full rerun.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-view Logical (non-materialized) views. labels Nov 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 93d9ee243be1d25c551784343ae555e732ac5fca with master failed: LogClusterNotReady: the endpoint never became ready.

See the job log for details.

@groeneai

groeneai commented Nov 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5f077f9

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
Upgrade check (amd_release) / Error message in clickhouse-server.log (see upgrade_error_messages.txt) not from this PR (it changes only how a view's stored SELECT is qualified at load): every line is ILLEGAL_DIVISION intDiv(100, x) While executing TTL from a background merge of t_column_ttl_materialized_undefined, the intentionally failing case of 05073_column_ttl_recompute_materialized; seen on 59 PRs in 14 days #127731 (mine, open)
Mergeable Check, PR praktika rollups of the row above #127731 (same as above)

Session id: cron:our-pr-ci-monitor:20261105-190008

@PedroTadim PedroTadim self-assigned this Nov 6, 2026
Comment thread src/Databases/DatabaseOnDisk.cpp Resolved
groeneai and others added 2 commits November 6, 2026 17:38
Three more views read the session's temporary objects by an unqualified
name: one over a temporary view, one over another view of the database
that reads the temporary table, and one calling `dictGet` on the
temporary table. On master each fails with `UNKNOWN_TABLE` after the
reload; with the fix each reads the new session's objects.

Six controls cover views over a materialized view, a refreshable
materialized view, a dictionary, a `ReplicatedMergeTree` table, a table
of a `Replicated` database, and a view inside a `Replicated` database.
They pass both on master and with the fix. A view inside a `Replicated`
database over a temporary table is not covered: `CREATE VIEW` there
stores the name qualified with the database, so the creating session
cannot read it either, before any reload, on master and with the fix.

Requested in ClickHouse#129485 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The previous commits stopped qualifying the SELECT of an ordinary view loaded
from metadata, so that a name left unqualified at CREATE because it was a
temporary table keeps resolving to the temporary table of the reading session.
That also dropped the 26.10 repair of legacy metadata (names introduced by SQL
UDF expansion before they were qualified at CREATE): such a view resolved the
name against the current database of the reader again, and a table whose
CONSTRAINT reads it failed to attach (UNKNOWN_TABLE, ASYNC_LOAD_WAIT_FAILED).

Now `StorageView` repairs the stored SELECT itself when the definition is read
back from metadata, as `qualifyNamesFromLegacyMetadata` did, and keeps the
stored one. `getInMemoryMetadataPtr` re-qualifies the stored SELECT under the
reading context when that context has temporary tables, so a temporary table of
the session takes precedence, as it does at CREATE. A `DEFINER` or `NONE`
view keeps the qualified SELECT: its body runs in a context without the
temporary tables of the reader, so a bare name would resolve against the
current database of the reader. `alter` keeps using the stored metadata.

The test gains a table with a CONSTRAINT that reads such a view (it attaches
after DETACH/ATTACH DATABASE), the same view read without the temporary table,
`SQL SECURITY DEFINER` and `NONE` views, and an `ALTER` from a session with
the temporary table.

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

groeneai commented Nov 7, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 61167d7

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 (arm_binary, ParallelReplicas, s3 storage, parallel) / 05515_global_subquery_projection_where not from this PR (the test is not in its diff): Code: 47 UNKNOWN_IDENTIFIER on a _data_<hash> name at the INSERT, deterministic on master in this lane since the test was added #129836 (mine, open)
Mergeable Check, PR praktika rollups of the row above #129836 (the owner of the row above)

No job was dropped, and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261107-023005

Comment thread src/Storages/StorageView.cpp Resolved
@PedroTadim
PedroTadim enabled auto-merge November 9, 2026 10:29

@tavplubix tavplubix left a comment

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.

I'm not sure if we needed #114923 in the first place

A scalar subquery in CHECK never works for inserts. Its only effect is that it runs at CREATE and at every attach. 
That's what makes the table fragile at startup, and it's the case #114923 and its load-time repair were built around. 
So #114923 hardened loading for a construct that can't accept an insert, and the "legacy repair" it added to support that caused #129449 and the joinGet regressions. 
Rejecting scalar subqueries in CHECK/ASSUME at CREATE and ALTER ADD CONSTRAINT, as #85575 suggested, would be the simpler fix. 
Tables that already have one would still need to load, so it couldn't be an error on attach. 
If you want, I can draft an issue proposing it, with links to #85575, #114923 and #129449.

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

@tavplubix I measured the premise:

  • CHECK: right. With CONSTRAINT c CHECK x <= (SELECT max(id) FROM src) every INSERT fails on master with Code: 47 ... Unknown identifier: __subquery_... (the same on 26.9.25.15 and 26.10.2.103 when the subquery reads a view), while x IN (SELECT id FROM src) works. ASSUME is not checked on INSERT, so there the INSERT succeeds.
  • Rejecting them at CREATE / ALTER ADD CONSTRAINT does not fix View that reads a session temporary table by bare name breaks after restart on 26.10 #129449 by itself: the view in the issue has no constraint, it breaks because the load-time repair qualifies the view's own SELECT. So that would be a separate PR (I can send it). It only changes how much of the repair this PR has to keep for ordinary views:
  1. The first version of this PR: one line, qualifyNamesFromLegacyMetadata skips ordinary views, no StorageView change. The price, both as on 26.9: a view created before 26.10 whose SQL UDF left a bare name reads it from the reader's current database again (measured: 26.9.25.15 returns default.source, 26.10.2.103 returns db.source), and a table whose CHECK reads such a view can fail to attach (the case from the bot review above).
  2. The current version: keeps the 26.10 repair, and a temporary table of the session takes precedence (about 40 lines in StorageView).

Reverting the whole load-time repair of #114923 would also return materialized views, column defaults and constraints written before 26.10 to 26.9 resolution, and the dependency graphs are built from the repaired names, so I would not do that here. I did not find a reported joinGet regression from #114923; with a link I can check it against both versions.

Which one do you prefer, 1 or 2?

@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 93d9ee2

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 infra, not from this PR (no ci/ file in the diff): all 8 readiness probes to the CI logs cluster hit Read timed out. (read timeout=3), so has_pr_data raised LogClusterNotReady: the endpoint never became ready #129675 (mine, open)
PR praktika rollup of the row above #129675 (the owner above)

Session id: cron:our-pr-ci-monitor:20261109-133006

@tavplubix

Copy link
Copy Markdown
Member

Rejecting them at CREATE / ALTER ADD CONSTRAINT does not fix #129449

Reverting #114923 does. @PedroTadim please double-check. Also please check what happens if I pass a temporary table to the scalar subquery in CHECK in #114923 description

Which one do you prefer, 1 or 2?

None of them, both are wrong.

@PedroTadim

Copy link
Copy Markdown
Member

I prefer to revert #114923 too. #114918 needs a better solution

@PedroTadim
PedroTadim disabled auto-merge November 9, 2026 16:22
@groeneai

groeneai commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

Also please check what happens if I pass a temporary table to the scalar subquery in CHECK in #114923 description

Measured with t1 a temporary table of the creating session, on 26.9.25.15, 26.10.2.103 and master (26.11.1.211):

  • CREATE TABLE t2 (conversation UInt64, CONSTRAINT c CHECK (SELECT id FROM t1 LIMIT 15) IN (conversation)) ... succeeds on all three and stores the bare t1.
  • Every INSERT into t2 fails, also in the creating session: Table default.t1 does not exist on 26.9, Unknown table expression identifier 't1' on 26.10 and master.
  • 26.10 and master record a loading dependency of t2 on default.t1, which does not exist. If such a table is created later, it cannot be dropped (HAVE_DEPENDENT_OBJECTS).
  • After a restart t2 fails to load on all three (UNKNOWN_TABLE for default.t1), and every query that touches it returns ASYNC_LOAD_WAIT_FAILED. The server itself starts.

So #114923 does not help here, and it adds a wrong dependency.

The revert does fix #129449: the reproducer returns 1 at the first parent of #114923 (f75df105) and fails with UNKNOWN_TABLE at its merge commit (659cc1c2). Two things the revert has to handle:

I'll open the full revert and link it here. If you want the SQL UDF part kept, say so. With the revert, this PR is not needed.

@PedroTadim

Copy link
Copy Markdown
Member

Closing this PR in favor of the revert

@groeneai

Copy link
Copy Markdown
Collaborator Author

The revert is #130531.

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-view Logical (non-materialized) views. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

View that reads a session temporary table by bare name breaks after restart on 26.10

3 participants