Repository navigation
Forbid to create a table as a MergeTree introspection table function - #118969
Conversation
CREATE TABLE p AS mergeTreeIndex('db', 's') was accepted, and once p had
been read it made s undroppable: DROP TABLE s SYNC never returned, s stayed
in system.dropped_tables forever, and its data was never reclaimed from
disk. The same persisted form is wrong two further ways that were measured
alongside: reads of p keep describing the dropped table (count(p) stayed at
2 after the source was dropped and re-created with 3 rows), and p stops
seeing new parts of a live source, because the parts vector is captured in
the storage's constructor.
A persisted table function is wrapped in a StorageTableFunctionProxy, whose
getNestedImpl memoises the storage it built in nested and clears
get_nested, so the storage lives for the whole server lifetime after the
first read. Each of these five storages keeps the source table's StoragePtr
as a data member: StorageMergeTreeIndex::source_table,
StorageFromMergeTreeProjection::parent_storage,
StorageMergeTreeAnalyzeIndexes::source_table,
StorageMergeTreeTextIndex::source_table and
StorageMergeTreeCodecBlockCounts::source_table. DROP TABLE s SYNC detaches
s, pushes it onto tables_marked_dropped and waits in
DatabaseCatalog::waitTableFinallyDropped, but the background drop task only
takes an entry whose pointer is unique (DatabaseCatalog::getTablesToDrop,
bool in_use = it->table && !isSharedPtrUnique(it->table)). The memoised
member is a permanent second reference, so in_use stays true, the entry is
never selected, and the wait loop exits only on is_shutting_down. The gate
is an ordinary shared_ptr use-count test rather than an assertion, so
release builds hang identically.
Removing the member is not the fix. Four of the five storages also cache
MergeTreeData::DataPartsVector data_parts in their constructor, and
IMergeTreeDataPart references its storage by raw reference (const
MergeTreeData & storage), so the cached parts do not keep the source alive
and would dangle. The tree states this in two places:
MergeTreeData::SnapshotData carries a ConstStoragePtr storage to
compensate, and StorageMergeTreeCodecBlockCounts says "The parts reference
the source table's MergeTreeData without owning it" before calling
addStorageHolder. Resolving the source per read instead would be a redesign
rather than a mechanical change, above all for
StorageFromMergeTreeProjection, whose const MergeTreeData & member cannot
be rebound, whose projection is a raw interior pointer into the parent
metadata, and whose constructor derives the storage's own schema from the
source's projection.
So the defect is not that the storage holds a pointer, which it must, but
that this storage is allowed to outlive its query.
canBeUsedToCreateTable() is the mechanism that already expresses exactly
that, used by eval, viewIfPermitted and the cluster functions, so give the
five table functions the same override. Five class bodies cover six
registered names, because mergeTreeAnalyzeIndexes and
mergeTreeAnalyzeIndexesUUID are the same class registered twice. Nothing on
the drop path changes, no bound is relaxed, and the transient
SELECT ... FROM mergeTreeIndex(...) form, the only documented and only
in-tree-exercised usage, is untouched.
The veto inspects only the outermost function, so nested carriers were
measured rather than assumed: remote(self, view(SELECT * FROM
mergeTreeIndex(...))), merge() over a database holding the proxy, and
ENGINE = Remote(..., mergeTreeIndex(...)) each materialise the inner
storage and still release it, because the outer storage keeps the AST and
rebuilds the inner one per query. The direct persisted form is therefore
the only pinning carrier.
canBeUsedToCreateTable() is consulted at two sites and only one is reached
by metadata replay, since the inferred column list is itself persisted. A
server that already holds such a table therefore keeps loading it at
startup and on ATTACH DATABASE, which route through
DatabaseOnDisk::createTableFromAST and do not consult the veto, while an
explicit ATTACH TABLE, a RESTORE, a replica recovery and
CREATE TABLE x AS p are refused. That asymmetry is the same one the
existing vetoes already carry, and it applies to a form with no uses
anywhere in the tree.
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Three rounds of independent pre-publication review (engine: codex) against the same diff. Nothing was
My own cold review of the tree found no blocker and no major. Session id: cron:clickhouse-review-self-slot-58:20260909-060300 |
|
Workflow [PR], commit [e5ae260] Summary: ✅
AI ReviewSummaryThis PR forbids Final Verdict✅ No new inline findings to post on this PR. LLVM Coverage ReportMeasured on commit e5ae260.
Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code |
|
cc @nikitamikhaylov @vitlibar, could you review this? A persisted |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units11 translation units recompiled, 37 s compile time in total, 11 of them have a recent master baseline. |
alexey-milovidov
left a comment
There was a problem hiding this comment.
This is clear, thank you!
1757957
|
@groeneai @alexey-milovidov — ClickGap found the following in this PR:
Close anything that's wrong or already addressed. |
Related: #118947
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
CREATE TABLE ... AS mergeTreeIndex(...)is no longer accepted, nor the same form overmergeTreeProjection,mergeTreeAnalyzeIndexes,mergeTreeAnalyzeIndexesUUID,mergeTreeTextIndexandmergeTreeCodecBlockCounts. The storage these functions return holds its source table's storage object, so once such a persisted table had been read,DROP TABLE <source> SYNCnever returned, the source stayed insystem.dropped_tablesforever and its data was never reclaimed from disk. Reading these functions directly, as inSELECT ... FROM mergeTreeIndex(...), is unaffected. An existing table of this shape keeps loading at server startup, butATTACH TABLE,RESTOREandReplicateddatabase replica recovery now refuse it: list them withSELECT database, name FROM system.tables WHERE engine = 'Proxy', drop the ones over these six functions, and read the functions directly instead.Description
CREATE TABLE p AS mergeTreeIndex('db', 's')was accepted, and oncephad been readDROP TABLE s SYNCnever returned. Reads ofpalso kept describing the dropped table.A persisted table function is wrapped in a
StorageTableFunctionProxy, whose first read memoises the storage it built and never releases it. That storage keeps its source table'sStoragePtras a data member, andDatabaseCatalog::getTablesToDroponly takes a table whose pointer is unique, sowaitTableFinallyDroppednever returns. The member cannot just be removed: four of the five storages also cachedata_parts, which reference their storage by raw reference. The defect is that the storage may outlive its query, so the fix is the persistence vetoeval,viewIfPermittedand the cluster functions already carry. Six registered names over five classes, all measured to pin, all now refused; the transient form is untouched and the test asserts that.The veto also refuses replay of a definition created before it, which is why this is filed as a backward incompatible change. Gating the hook on
LoadingStrictnessLevelwould preserve replay, but the hook is shared withviewIfPermitted, whose veto is a security control, so I did not relax it. Say the word if you would rather have a per-function replay hook.Blast radius of that asymmetry, what the test does not cover, and one more residual
The veto reads only the outermost function; the nested carriers (
remote(self, view(... mergeTreeIndex ...)),merge(),ENGINE = Remote(..., mergeTreeIndex(...))) were measured too and each releases the inner storage after materialising it, so the direct persisted form is the only pinning carrier.Reaching the affected state needs a hand-written
CREATE TABLE ... AS mergeTreeIndex(...): the form is undocumented,grepfinds no use of it anywhere in the repository, and any such table already hangs its own source'sDROP ... SYNC. AReplicateddatabase accepts the form today becausecheckQueryValidonly inspectscreate->storage, which is null for a table function.The new test asserts the six refusals and the untouched transient form, but not the replay paths: reaching those from a stateless test would mean writing legacy metadata by hand, outside the API surface, so lifecycle coverage belongs in an integration test rather than here.
A persisted
view(SELECT * FROM mergeTreeIndex(...))orloop(mergeTreeIndex(...))is also accepted and then unreadable. Neither pins its source, so both are left alone.timeSeriesSamples/Tags/Metricsneed the same veto for a worse reason, their storage being the target table itself; #116629 adds it there.Found while enumerating the invariant carriers of the sibling
loopfix, #118947.Workflow [PR]
Sync PR [sync-upstream/pr/118969]