Skip to content

Fix crash on REFRESH ... DEPENDS ON shadowed by a temporary table - #107156

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-refresh-depends-on-empty-database-106737
Jun 20, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-refresh-depends-on-empty-database-106737

Conversation

@groeneai

@groeneai groeneai commented Jun 11, 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 a server crash (LOGICAL_ERROR "Unexpected exception in refresh scheduling", followed by a crash-loop on restart) when a refreshable materialized view has a REFRESH ... DEPENDS ON <name> dependency whose unqualified name matches a temporary table or a CTE name.

Description

Closes: #106737

REFRESH ... DEPENDS ON <name> dependencies are built into StorageIDs directly from the AST in RefreshTask::create / RefreshTask::alterRefreshParams. AddDefaultDatabaseVisitor skips qualifying a bare name that matches a temporary table or a CTE, so such a dependency kept an empty database. On the first scheduling pass StorageID::getFullTableName() threw UNKNOWN_DATABASE "Database name is empty", the catch-all in RefreshTask::doScheduling re-raised it as a LOGICAL_ERROR and the server aborted; the bad definition was persisted, so the server then crash-looped on restart.

Fix: resolve any still-unqualified dependency against the view's database in RefreshTask::create / alterRefreshParams. This is the correct database for the no-session paths (attach-from-metadata on restart, background scheduling) and matches the database AddDefaultDatabaseVisitor would have used for a non-shadowed name.

The change is limited to the empty-database dependency. It does not change how a refreshable MV's SELECT or DEPENDS ON clause resolves unqualified names in the normal (non-shadowed) case: both still resolve in the session database at CREATE time, as before.

The regression test 04329_refreshable_mv_depends_on_database_qualification.sh reproduces the original crash via a temporary table shadowing the dependency name, and asserts system.view_refreshes settles at MissingDependencies with an empty exception (instead of Disabled with an exception), so it catches the regression in non-sanitizer functional CI as well as in debug/sanitizer builds where the catch-all aborts. It also covers the detach/attach (attach-from-metadata) path.

CI report for the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107156&sha=d1c5d0ef9aad5b1c5c71acda4fb8e98495cf0ab7&name_0=PR

Found by issue #106737 (STID 2508-3e7b).

Version info

  • Merged into: 26.6.1.1076

@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

# Question Answer
a Deterministic repro? Yes. CREATE TEMPORARY TABLE t (a UInt64) ENGINE = Memory; CREATE MATERIALIZED VIEW db.v REFRESH EVERY 1 SECOND DEPENDS ON t TO db.dst AS SELECT a FROM db.t; aborts the server every time on a debug build (and crash-loops on restart).
b Root cause explained? Yes. RefreshTask::create/alterRefreshParams build dependency StorageIDs straight from the AST. AddDefaultDatabaseVisitor skips qualifying a bare DEPENDS ON name when it matches a temporary table (correct for SELECT refs, wrong for a dependency), so the dependency keeps an empty database. On the first scheduling pass StorageID::getFullTableName() throws UNKNOWN_DATABASE "Database name is empty"; the catch(...) in doScheduling re-raises it as LOGICAL_ERROR -> abort. Separately, unqualified deps were resolved against the session database (current_database) instead of the view's database.
c Fix matches root cause? Yes. The interpreter now qualifies the refresh strategy against the view's database (create.getDatabase()), and RefreshTask::create/alterRefreshParams resolve any still-unqualified dependency against the view's database when building the StorageIDs. No widened bounds, no no-random-* tags, no defensive guard at the throw site.
d Test intent preserved / new tests added? New regression test 04329_refreshable_mv_depends_on_database_qualification.sh covers both the temporary-table-shadow crash and the cross-database qualification. Existing 02932_refreshable_materialized_views_{1,2,3} still pass.
e Both directions demonstrated? Yes. Without the fix: server aborts (Logical error: 'Unexpected exception in refresh scheduling', build id 42cba66d, Exit 134, crash-loop on restart). With the fix (build id a9d2c949, fresh master 1d9ac68): new test passes 8/8, server stays alive, 0 crash markers, persisted bad metadata self-heals on restart.
f Fix is general, not a narrow patch? Yes. Both dependency-building sites (create and alterRefreshParams) go through one parseRefreshDependencies helper. The RefreshTask layer also covers the ATTACH-from-metadata path (which does not run the interpreter visitor), so already-persisted unqualified definitions no longer crash on restart. The fix resolves the bad database at its origin (where the dependency StorageID is constructed), not at the getFullTableName() throw site.

Session id: cron:clickhouse-worker-slot-3:20260611-063900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @al13n321 @tuanpach — could you review this? It fixes the Unexpected exception in refresh scheduling crash (issue #106737): REFRESH ... DEPENDS ON dependencies were built from the AST without resolving the database, so a bare name matching a temporary table kept an empty database and aborted the scheduler (and crash-looped on restart). The fix resolves dependencies against the view's database in both the interpreter and RefreshTask.

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

clickhouse-gh Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8d85c5e]

Summary: ✅


AI Review

Summary

This PR fixes the REFRESH ... DEPENDS ON temp-table shadowing exception by qualifying still-empty refresh dependency StorageIDs before they enter RefreshSet, and adds regression coverage for the scheduling state plus detach/attach metadata replay path. I did not find a current correctness or test-coverage issue that needs an inline review comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 11, 2026
@PedroTadim

PedroTadim commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

@groeneai I am not sure if we should allow materialized views to/with temporary tables. Is that going to work at the moment?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim good question. I dug into the current behavior on the fixed build. Short version: this PR does not make MV depend on a temporary table. With the fix a DEPENDS ON name always resolves in the view's database, so a temp table can never become a refresh dependency, and the crash is gone.

Details, all tested locally on this branch:

  1. The crash is the actual bug and must be fixed regardless of the scope question. Before the fix, a bare DEPENDS ON t that happened to match a temporary table was left with an empty database; the first scheduling pass threw UNKNOWN_DATABASE from getFullTableName(), the catch-all re-raised it as a LOGICAL_ERROR, the server aborted, and because the bad definition is persisted it crash-looped on restart. Server abort on user DDL is never acceptable, independent of whether MV+temp is a supported combination.

  2. With the fix, DEPENDS ON resolves against the view's database (like the view's SELECT does), so it does not bind to the temp table:

    • DEPENDS ON t where a same-named temp table t AND a view_db.t both exist: binds to view_db.t, not the temp table. Proven by making view_db.t a refreshable MV: the dependent MV then reaches Scheduled / succeeds, i.e. it is waiting on view_db.t, not the session temp table.
    • DEPENDS ON only_tmp where the name exists ONLY as a temp table (no view_db.only_tmp): resolves to the (non-existent) view_db.only_tmp and sits at MissingDependencies. No crash, refresh just never fires, exactly like any DEPENDS ON pointing at a missing or non-refreshable table.
  3. So MV-depending-on-a-temp-table effectively cannot happen by design after this fix. The temp table is never wired in as a dependency; it only ever mattered because the old code left the database empty and crashed. I did not add a dedicated rejection for a dependency that only matches a temp table because the resulting behavior is already the same harmless MissingDependencies that DEPENDS ON gives for any not-yet-existing or non-refreshable target. Adding a special-case error there would be a broader policy change on DEPENDS ON validation, separate from this crash fix. Happy to do it as a follow-up if you prefer the stricter contract.

Regression test 04329_refreshable_mv_depends_on_database_qualification.sh covers the temp-table-shadow crash and the cross-database qualification, and the persisted-bad-metadata restart now self-heals instead of crash-looping (verified: server restarts clean, all MVs attach).

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finished on HEAD fee14ca0f702 (Mergeable Check + Finish Workflow pass; AI Review approved). The single failure — 04027_system_start_replicated_view in Stateless tests (arm_asan_ubsan, azure, parallel) — is a pre-existing flaky test, NOT caused by this PR: it self-healed in the run's own reproducibility check (failed 0 out of 3 reruns), CIDB shows it across 3 unrelated PRs / 0 master in 30d, and it exercises SYSTEM START REPLICATED VIEW which is unrelated to this REFRESH DEPENDS ON database-qualification fix. Tracked separately. No PR-caused failures. Moving to review.

Session id: cron:our-pr-ci-monitor:20260611-160000

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix the pre-existing flaky test, 04027_system_start_replicated_view

@groeneai
groeneai force-pushed the groeneai/fix-refresh-depends-on-empty-database-106737 branch from fee14ca to 0b7d352 Compare June 19, 2026 22:18
@groeneai

groeneai commented Jun 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov This one is already fixed and merged: #107254 "Fix flaky test 04027_system_start_replicated_view" (merged 2026-06-12, approved by nikitamikhaylov).

Root cause was an asymmetric wait budget in the test, not an engine bug: the post-resume <4: new rows> wait was seq 1 30 (15s) while the initial-refresh and stop waits are seq 1 60 (30s). Under arm_asan_ubsan/azure/parallel load the resumed refresh's scheduler wake + Keeper round-trip to APPEND occasionally exceeded the shorter 15s window. The fix extends that loop to seq 1 120 (60s), parity with the initial-refresh wait; assertions and .reference unchanged.

Verification: master HEAD 04027_system_start_replicated_view.sh now has seq 1 120, and CIDB shows 0 failures on master or any branch in the ~7 days since the merge (the only 30-day hit is the 2026-06-11 sighting on this PR, which predated the fix).

That 06-11 sighting flaked here because this branch was ~3360 commits behind master and still carried the old 15s test. I've just rebased #107156 onto current master, so its CI now runs the fixed version. Sorry for the stale ledger comment above — by the time it was posted the fix PR had not landed yet.

@groeneai
groeneai force-pushed the groeneai/fix-refresh-depends-on-empty-database-106737 branch from 0b7d352 to 253a3d5 Compare June 19, 2026 22:59
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (test-strengthening update, 253a3d5)

# Question Answer
a Deterministic repro? Yes. Stub parseRefreshDependencies (keep only the InterpreterCreateQuery change) and compile out the debug abort to mimic a release build: mv_tmp deterministically reports Disabled with a non-empty exception.
b Root cause explained? A bare DEPENDS ON t that shadows a temporary table is left unqualified by AddDefaultDatabaseVisitor, so the StorageID has an empty database. collectDependencyStates -> StorageID::getFullTableName() throws UNKNOWN_DATABASE; the catch-all in doScheduling records unexpected_error and stops scheduling. It aborts only under DEBUG_OR_SANITIZER_BUILD; in release it is swallowed, so SELECT 1 keeps succeeding.
c Fix matches root cause? This change is to the test only. It asserts the settled system.view_refreshes state (status + exception = ''), which is precisely the state corrupted by the bug, so the assertion fails on the exact mechanism from (b) rather than relying on the abort.
d Test intent preserved / new tests added? Preserved and strengthened. All original checks remain (creation, cross-DB qualification, server-alive); added a polling report_refresh_state assertion for both the temp-shadow (mv_tmp) and cross-DB (mv_cross) views.
e Both directions demonstrated? Yes. Full fix: 10/10 PASS with randomization. Without parseRefreshDependencies + abort compiled out: FAIL (mv_tmp = Disabled/non-empty exception) while SELECT 1 still returns 1.
f Fix is general, not a narrow patch? The underlying code fix (unchanged here) already covers create, alterRefreshParams, and the ATTACH-from-metadata path. The test now covers both the temp-table-shadow path (guarded by parseRefreshDependencies) and the cross-database path (guarded by the InterpreterCreateQuery change).

Session id: cron:clickhouse-worker-slot-0:20260619-223800

@groeneai
groeneai force-pushed the groeneai/fix-refresh-depends-on-empty-database-106737 branch from 253a3d5 to d1c5d0e Compare June 20, 2026 00:02
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(For the SELECT/DEPENDS ON database-divergence fix raised in the InterpreterCreateQuery.cpp review.)

# Question Answer
a Deterministic repro? Yes. From session db s: CREATE MATERIALIZED VIEW db.mv REFRESH EVERY 1 SECOND DEPENDS ON t TO db.dst AS SELECT a FROM t (with s.t and db.t holding different data) persists ... FROM s.t while DEPENDS ON db.t; the refresh reads s.t. Reproduces every time.
b Root cause explained? A refreshable MV runs its SELECT as a background query with no session, so unqualified refs must resolve in the view's db. Only column inference did (setCurrentDatabaseUnchecked, #87082); the persisted SELECT AST and DEPENDS ON were qualified with current_database. getSelectQueryFromASTForMatView early-returns for refreshable views, so the metadata-time setCurrentDatabase(view_db) never re-qualifies the persisted SELECT. Result: schedule off db.t, read from s.t.
c Fix matches root cause? Yes. InterpreterCreateQuery::createTable qualifies BOTH the SELECT and the refresh strategy against the view's db for a refreshable MV (view_default_database = create.refresh_strategy ? create.getDatabase() : current_database). Converges SELECT, DEPENDS ON, inference, and the no-session refresh execution context on one database.
d Test intent preserved / new tests added? Yes. 04329 keeps the crash/state assertions (cases 1, 2, 2b) and adds case 3/3b: session db and view db both hold t with different data; asserts the persisted SELECT resolves to the view db and the refresh writes the view-db rows (111,222), not the session-db row (777).
e Both directions demonstrated? Yes. Fixed build: 5/5 PASS. Reverting only the SELECT change (DEPENDS ON fix kept): case 3 → 0, case 3b → 777, and SELECT 1 still succeeds — so it fails in plain functional CI, not only sanitizer/debug.
f Fix is general, not a narrow patch? Yes. The qualification is fixed at the single source where the persisted AST is built (createTable), covering SELECT and DEPENDS ON together. Non-refreshable views keep session-db resolution (verified unchanged). Restart/ATTACH path verified: persisted def is view-qualified, ATTACH succeeds, no crash-loop.

Session id: cron:clickhouse-worker-slot-1:20260619-233900

@alexey-milovidov

Copy link
Copy Markdown
Member

@groeneai, fix fast test and address review.

Fixes a server crash (issue ClickHouse#106737, STID 2508-3e7b) when a refreshable
materialized view has a `REFRESH ... DEPENDS ON <name>` dependency whose
unqualified name matches a temporary table (or a CTE name).

RefreshTask::create and RefreshTask::alterRefreshParams turned the DEPENDS ON
entries into StorageIDs straight from the AST. AddDefaultDatabaseVisitor skips
qualifying a bare name that matches a temporary table or CTE, so such a
dependency kept an empty database. On the first scheduling pass
StorageID::getFullTableName() threw UNKNOWN_DATABASE "Database name is empty",
the catch-all in RefreshTask::doScheduling re-raised it as a LOGICAL_ERROR and
the server aborted. The bad definition was persisted, so the server then
crash-looped on restart.

Resolve any still-unqualified dependency against the view's database in
RefreshTask::create / alterRefreshParams. This is the right database for the
no-session paths (attach-from-metadata on restart, background scheduling) and
matches the database the AddDefaultDatabaseVisitor would have used for a
non-shadowed name.

This change is limited to the empty-database dependency. It does not change how
a refreshable MV's SELECT or DEPENDS ON clause resolves unqualified names in
the normal (non-shadowed) case: both still resolve in the session database at
CREATE time, exactly as before.

Closes: ClickHouse#106737

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai
groeneai force-pushed the groeneai/fix-refresh-depends-on-empty-database-106737 branch from d1c5d0e to 8d85c5e Compare June 20, 2026 01:51
@groeneai groeneai changed the title Resolve REFRESH ... DEPENDS ON dependencies in the view's database Fix crash on REFRESH ... DEPENDS ON shadowed by a temporary table Jun 20, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate

(For the pivot to the minimal crash fix after the previous push broke the pre-existing master test 03258_refreshable_mv_misc.)

# Question Answer
a Deterministic repro? Yes. 03258_refreshable_mv_misc FAILs deterministically on the previous head (d1c5d0ef9aa): expected ACCESS_DENIED error, got: ... v doesn't exist (the SELECT * FROM a resolved a in the view DB, where it does not exist, instead of the session DB). And 04329 FAILs on a bug-demo binary that disables the RefreshTask empty-DB guard: case 1 reports Disabled 0 instead of MissingDependencies 1.
b Root cause explained? Two distinct issues. (1) Crash (#106737): AddDefaultDatabaseVisitor skips qualifying a bare DEPENDS ON t that shadows a temporary table/CTE, so the dependency kept an empty DB; getFullTableName() threw UNKNOWN_DATABASE, the doScheduling catch-all re-raised LOGICAL_ERROR, server aborted + crash-looped. (2) Regression I introduced: the previous push changed a refreshable MV's SELECT to resolve unqualified names in the view DB; 03258 relies on the long-standing behavior that the SELECT resolves in the session DB (table a is in the session DB, MV is elsewhere), so it broke.
c Fix matches root cause? Yes. (1) is fixed by resolving any still-unqualified dependency against the view DB in RefreshTask::create/alterRefreshParams (the only no-session paths). (2) is fixed by reverting the InterpreterCreateQuery visitor change back to master: both SELECT and DEPENDS ON resolve in the session DB at CREATE, as before. No band-aid: the guard targets exactly the empty-DB dependency.
d Test intent preserved / new tests added? Yes. 03258 (pre-existing master test) passes again. 04329 is the new regression test: it asserts system.view_refreshes settles at MissingDependencies with empty exception for the temp-shadow case (fails as Disabled + exception without the fix, even in non-sanitizer builds) and covers the detach/attach (attach-from-metadata) path. No assertions weakened; no no-parallel; ${CLICKHOUSE_DATABASE}-scoped.
e Both directions demonstrated? Yes. 04329: FAILs on the bug-demo binary (guard disabled) with Disabled 0, PASSes 10/10 with full randomization on the fix. 03258: FAILs on d1c5d0ef9aa, PASSes 10/10 with randomization on the fix. The full refreshable-MV suite (02932_1/2/3, 03221, 03258, 03327, 03760, 04201, 04218, 04227, 04329) passes on the fix (03221 only fails locally on a --database client-arg artifact of my ad-hoc server, unrelated to the change and not in the diff).
f Fix is general, not a narrow patch? Yes. The empty-DB guard is applied at all three dependency-building sites: RefreshTask::create (CREATE), alterRefreshParams (ALTER MODIFY REFRESH), and the attach-from-metadata path that replays create with no session. Traced the bad value to its origin: the empty DB comes from the visitor's deliberate temp/CTE skip, so the guard fills it at the point the StorageID is built, where the correct default (the view DB) is known.

Session id: cron:clickhouse-worker-slot-4:20260620-004100

@clickhouse-gh

clickhouse-gh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.20% 85.20% +0.00%
Functions 92.50% 92.50% +0.00%
Branches 77.50% 77.40% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 17/17 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov self-assigned this Jun 20, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 20, 2026
Merged via the queue into ClickHouse:master with commit 480b7d9 Jun 20, 2026
166 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 20, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @groeneai @alexey-milovidov — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Unexpected exception in refresh scheduling' (STID: 2508-3e7b)

5 participants