Repository navigation
Conversation
…n read CREATE TABLE dl AS loop(t) creates a persistent StorageTableFunctionProxy. The first read of dl materialises the proxy's nested storage, and from then on DROP TABLE t SYNC never returns and has to be KILL QUERYed. t leaves system.tables but stays in system.dropped_tables until the server restarts, so its data is not reclaimed before then, and SELECT * FROM dl keeps returning the dropped table's rows. TableFunctionLoop::executeImpl resolves the named source and hands the StoragePtr to StorageLoop, which stored it as a data member. For a persisted table StorageTableFunctionProxy::getNestedImpl memoises that StorageLoop and clears get_nested, so the strong reference to the source's storage object lives for the whole server lifetime. DatabaseCatalog's background drop task only takes an entry whose pointer is unique (!isSharedPtrUnique(it->table)), so in_use stays true and the UUID never leaves tables_marked_dropped_ids, so waitTableFinallyDropped keeps waiting: it returns only on shutdown, or throws out of its throw_if_cancelled callback (QUERY_WAS_CANCELLED on a KILL, TIMEOUT_EXCEEDED under max_execution_time). StorageLoop now keeps a StorageID and resolves it per read, the settled convention for a storage that references another table: StorageBuffer holds destination_id, StorageMaterializedView holds target_table_id, StorageAlias holds target_database and target_table. The UUID is cleared so the source is followed by name, which is also what lets dl pick up a source that was dropped and recreated. ReadFromLoopStep and LoopSource still take the resolved StoragePtr and pin it for the duration of their own query, exactly as ReadFromMerge::selected_tables does; only retention on the storage is removed. LoopSource::initLoop now tests inner_table_function_ast first. That is required rather than cosmetic: master's first branch dereferenced inner_storage, which is null for the inner-table-function form. The two forms are mutually exclusive by construction, since executeImpl sets the AST exactly for the inner-table-function form and leaves it null for the named form. The branch that read inner_storage directly is deleted. It is where the stale rows came from: it served a named source that had already been dropped. processed_stage, max_block_size and num_streams go with it, since that branch was their only consumer and on both surviving paths the inner SELECT is built by the interpreter, which derives those from its own context. The metadata snapshot is deliberately still taken in the constructor with CurrentThread::tryGetQueryContext(). InterpreterCreateQuery calls executeImpl with use_global_context = true, so resolving it from executeImpl's context instead would silently change which context reads the schema. The mergeTree* introspection table functions retain their parent the same way and still pin it, but they read its parts through that handle, so they need a different remedy than per-read resolution and are left alone here. Co-Authored-By: Claude Opus 5 <[email protected]>
…ertises Resolving the source per read makes its schema mutable behind an already-created loop table, and LoopSource still advertised the header cached at CREATE: storage_snapshot->getSampleBlockForColumns() in the ISource constructor and in ReadFromLoopStep. A source whose column type had changed therefore sent its columns unconverted under the cached header. A port compares only the column count (InputPort::pullData and OutputPort::pushData test chunk.getNumColumns() != header->columns() and nothing else), and StorageTableFunctionProxy::read's own "Converting columns" step is an identity here because query_plan.getCurrentHeader() is already the cached header by the time it runs. The mismatched column travelled to the wire, where SerializationNumber typeid_casts it and abortOnFailedAssertion fires: Logical error: 'Bad cast from type DB::ColumnString to DB::ColumnVector<char8_t>' Received signal Aborted (6) Measured on a debug server, both directions. Reaching it by dropping and recreating the source with a different type is new to this change: on bd4f088 that sequence returns the pre-drop rows instead, because the source's storage object is still pinned. Reaching it by ALTER TABLE ... MODIFY COLUMN on a non-key column is not new - it aborts identically on bd4f088 - and the same conversion step fixes that route too. A key column cannot be retyped at all (ALTER of key column ... is not safe), so the non-key form is the only ALTER route. LoopSource::initLoop now appends an ExpressionStep built by ActionsDAG::makeConvertingActions when the built plan's header is not structurally equal to the header this source advertises, which is the same shape StorageTableFunction.h:193-210 uses and which 04653_table_function_proxy_prewhere_type_drift pins for the sibling case. It is placed after the plan is built, so it covers the named-source form and the inner-table-function form (loop(file(...)) rebuilds from the current external schema and can drift the same way). A conversion that is not possible throws out of makeConvertingActions, which is the wanted outcome: CANNOT_PARSE_TEXT rather than an abort. 05137 gains one drift arm, recreating the source as String holding '3' and asserting the read returns 3. The test also now pins ignore_drop_queries_probability = 0, because the stress runner passes 0.2 to every client (ci/jobs/scripts/stress/stress.py) and InterpreterDropQuery turns a DROP of a table with data on disk into a silent no-op when it fires, which would make the UNKNOWN_TABLE arm return a row about one Stress run in five. And it asserts system.dropped_tables no longer holds the source once the SYNC drop returns, an oracle for the retained reference that does not depend on the statement's timeout. Co-Authored-By: Claude Opus 5 <[email protected]>
SELECT * FROM loop(<database>, '<table>') over a table-function-backed database threw Code: 81 UNKNOWN_DATABASE. That is a regression of the first commit on this branch: a plain query, no persisted table and no drop anywhere. StorageLoop derived the id it resolves per read from the resolved StoragePtr, and for a table-function-backed database that object's id is not the name the user wrote. DatabaseFilesystem::getTableImpl, DatabaseS3::getTableImpl and DatabaseHDFS::getTableImpl each return the storage their table function built, unrenamed, so its id carries ITableFunction::getDatabaseName()'s synthetic _table_function database. That is not a database in DatabaseCatalog, so resolving the id threw. DatabaseURL is not affected: DatabaseURL::getTableImpl wraps its delegate in a StorageURLDatabaseTable carrying StorageID(getDatabaseName(), name). The deleted direct-read branch had served this population as well. Its gate was DatabaseCatalog::isTableExist, which returns false for an unknown database instead of throwing, so _table_function.<file> fell through to it and read fine. TableFunctionLoop::executeImpl now hands StorageLoop the logical StorageID it already computes for the named form, and ReadFromLoopStep and LoopSource carry that id and build the synthetic FROM from it. Both sites are needed: initLoop used to re-derive the id from the resolved storage, which would have re-broken it. So the source is resolved exactly the way SELECT ... FROM <database>.<table> resolves it, for every database engine, and nothing has to clear a UUID off the id any more, because it is a name a user typed. The resolved handle is no longer a member of anything. StorageLoop::read pins it for the duration of the query with QueryPlan::addStorageHolder, as Planner.cpp and InterpreterSelectQuery.cpp do for a plan's source. Keeping it as a member instead would be a field nothing reads, which -Wunused-private-field rejects. 02722_database_filesystem gains one arm that reads such a table through loop(). Measured on a debug server: it passes on bd4f088, fails with Code: 81 DB::Exception: Database _table_function does not exist on this branch's previous commit, and passes here; 50 randomised runs of the file pass. The argument-form matrix and the sibling carriers are unchanged. Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model reviewAn independent model reviewed this change against the code across three rounds, and I adjudicated every
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20260908-210300 |
|
cc @kssenii @davenger, could you review this? A persisted |
|
Workflow [PR], commit [7951c7c] Summary: ❌
AI ReviewSummaryThe PR fixes persisted Missing context / blind spots
Final Verdict✅ Approve — no code changes requested. Current-head CI remains pending. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes6 object files changed (+12.58 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units9 translation units recompiled, 21 s compile time in total, 9 of them have a recent master baseline. |
CI finish ledger - 70f3caeEvery failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
Two notes on the rest of the red surface, so the table is not read as incomplete:
Session id: cron:our-pr-ci-monitor:20260909-083055 |
|
Fixing PR for the I confirmed the shape from that job's server log rather than assuming it. The aborting query is |
Only ReadFromLoopStep.cpp conflicted. Master removed the pre-analyzer interpreter branch and added a RepeatedPipelineBuildScope so the joins a `loop` rebuilds are counted once per pipeline rather than once per pass; this branch replaces the cached `StoragePtr inner_storage` with a `StorageID` resolved by name on every read, which orphaned processed_stage, max_block_size and num_streams. Both sides are kept: the scope name is threaded through the LoopSource constructor, member list and makePipe() alongside the StorageID, and the scope guard stays adjacent to buildQueryPipeline so it still covers exactly the region master marked. The converting ExpressionStep is added to the plan before that region, since addStep builds no joins. The merged tree differs from master by this branch's nine files only, so no submodule pin and no part of the scope work is reverted.
CI finish ledger - 2117022Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
Two notes, so the rest of the red surface is not read as unowned:
Session id: cron:our-pr-ci-monitor:20260923-233131 |
Conflict in `TableFunctionLoop::executeImpl`: master's `refreshExternalMetadata` call and this branch's `source_table_id` assignment were both added right after the `Alias` access check. Both are kept, the refresh first; they are independent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 7951c7cEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261021-170005 |
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
DROP TABLE t SYNCnever returning whentis the source of a persistent table created asCREATE TABLE ... AS loop(t)and that table has been read at least once. Such a table now resolves its source by name on every read instead of holding on to the source's storage object, so the source can be dropped, and reading the persistent table afterwards raisesUNKNOWN_TABLEinstead of returning rows from the dropped table. Reading it after the source's column types changed now converts the values instead of reinterpreting them under the cached type, which aborted a debug or sanitizer build and was also reachable withALTER TABLE t MODIFY COLUMN.Description
Related: #116629 (found while probing its read path). Closes #119765.
CREATE TABLE dl AS loop(t)creates a persistentStorageTableFunctionProxy. The first read ofdlmaterialises the proxy's nested storage, and from then onDROP TABLE t SYNCnever returns and must beKILL QUERYed.tleavessystem.tablesbut stays insystem.dropped_tablesuntil restart, so its data is not reclaimed.Root cause:
StorageLoopstored the source as aStoragePtrmember, and the persisted proxy memoises thatStorageLoopfor the server's lifetime (StorageTableFunctionProxy::getNestedImpl). The background drop task only takes a table whose pointer is unique (DatabaseCatalog::getTablesToDrop), sowaitTableFinallyDroppedwaits forever.Fix:
StorageLoopkeeps aStorageIDand resolves it per read, the settled convention for a storage referencing another table (StorageBuffer,StorageMaterializedView,StorageAlias); the query plan pins the resolved table for its own query. TheLoopSourcebranch that read the retained storage, the source of the stale rows, is deleted. The id is the name the user wrote, so the source resolves as it does forSELECT ... FROM db.tbl, covering table-function-backed databases (Filesystem,S3,HDFS) whose storages are not registered under their own id;02722_database_filesystemgains an arm.Resolving live leaves the source's schema mutable behind the header cached at
CREATE, so the read now converts to it; that also fixes aBad castlogical error pre-existing on master viaALTER TABLE t MODIFY COLUMN.Validation:
05137_loop_table_function_drop_source_tablefails on pristine master (Code: 159, 31 s) and passes with the fix; the 50/50 and theloopfamily are green, and persistedloop()tables still attach.Not fixed here:
mergeTreeIndexand fourmergeTree*siblings pin their parent the same way, but read its parts through that handle, so the remedy differs.Workflow [PR]
Sync PR [sync-upstream/pr/118947]