Skip to content

Forbid to create a table as a MergeTree introspection table function - #118969

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:forbid-persisted-mergetree-introspection-table-functions
Sep 12, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:forbid-persisted-mergetree-introspection-table-functions

Conversation

@groeneai

@groeneai groeneai commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #118947

Changelog category (leave one):

  • Backward Incompatible Change

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 over mergeTreeProjection, mergeTreeAnalyzeIndexes, mergeTreeAnalyzeIndexesUUID, mergeTreeTextIndex and mergeTreeCodecBlockCounts. The storage these functions return holds its source table's storage object, so once such a persisted table had been read, DROP TABLE <source> SYNC never returned, the source stayed in system.dropped_tables forever and its data was never reclaimed from disk. Reading these functions directly, as in SELECT ... FROM mergeTreeIndex(...), is unaffected. An existing table of this shape keeps loading at server startup, but ATTACH TABLE, RESTORE and Replicated database replica recovery now refuse it: list them with SELECT 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 once p had been read DROP TABLE s SYNC never returned. Reads of p also 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's StoragePtr as a data member, and DatabaseCatalog::getTablesToDrop only takes a table whose pointer is unique, so waitTableFinallyDropped never returns. The member cannot just be removed: four of the five storages also cache data_parts, which reference their storage by raw reference. The defect is that the storage may outlive its query, so the fix is the persistence veto eval, viewIfPermitted and 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 LoadingStrictnessLevel would preserve replay, but the hook is shared with viewIfPermitted, 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, grep finds no use of it anywhere in the repository, and any such table already hangs its own source's DROP ... SYNC. A Replicated database accepts the form today because checkQueryValid only inspects create->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(...)) or loop(mergeTreeIndex(...)) is also accepted and then unreadable. Neither pins its source, so both are left alone.

timeSeriesSamples/Tags/Metrics need 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 loop fix, #118947.


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

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]>
@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 9, 2026
@groeneai

groeneai commented Sep 9, 2026

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

Three rounds of independent pre-publication review (engine: codex) against the same diff. Nothing was
found in the 42 added lines; every finding asked the contract to say more, and all are now in it.

  • The veto also refuses replay of a definition created before it, through ATTACH TABLE, RESTORE
    and Replicated recovery. Raised twice, so it is resolved rather than noted: the category is now
    Backward Incompatible Change and the changelog entry carries the migration. The other half of the
    prescription, gating the hook on LoadingStrictnessLevel, I did not take: the hook is shared, and
    relaxing it on those paths would let a persisted viewIfPermitted table be resolved with no user,
    which is what Forbid to create a table as viewIfPermitted #116885 closed. A per-function replay hook is offered above instead.
  • The new test asserts the six refusals but not those replay paths. Agreed. Seeding one means writing
    legacy metadata by hand, outside the API surface, so it belongs in an integration test; the gap is
    stated in the description rather than left implicit.
  • TableFunctionTimeSeriesTarget needs the same veto for a worse reason. Agreed and parked on Check access rights in the TimeSeries table functions #116629,
    which already adds that exact override to that exact class.
  • The Related link sat inside the template's HTML comment and would not have rendered. Fixed.

My own cold review of the tree found no blocker and no major.

Session id: cron:clickhouse-review-self-slot-58:20260909-060300

@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e5ae260]

Summary: ✅


AI Review

Summary

This PR forbids CREATE TABLE ... AS over the six MergeTree introspection table-function entrypoints whose persisted proxy can keep a source table alive past the query lifetime. I did not find a new blocker or major in the current code: the veto is wired in both places that matter for direct persisted creation (column inference and explicit-column creation), and the obvious persisted wrappers I checked (remote, Remote, loop, view) do not reintroduce the same long-lived StoragePtr retention.

Final Verdict

✅ No new inline findings to post on this PR.

LLVM Coverage Report

Measured on commit e5ae260.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.70% 91.80% +0.10%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 10/10 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-backward-incompatible Pull request with backwards incompatible changes label Sep 9, 2026
@groeneai

groeneai commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

cc @nikitamikhaylov @vitlibar, could you review this? A persisted CREATE TABLE ... AS mergeTreeIndex(...) keeps its source table's storage object alive through the proxy's memoised nested, so DatabaseCatalog's unique-pointer gate never passes and DROP TABLE <source> SYNC never returns; the fix is the canBeUsedToCreateTable veto rather than unpicking the retention, which four of the five storages need for their cached parts. One judgement call worth your eye: I did not gate that hook on LoadingStrictnessLevel to keep replay working, because it is shared with viewIfPermitted, so the PR is filed as a backward incompatible change instead.

@clickhouse-gh clickhouse-gh Bot added the comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). label Sep 9, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing e5ae26012 with master fe1a91eac (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 129e4b59b; 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

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

Job report

@alexey-milovidov alexey-milovidov 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.

This is clear, thank you!

@clickgapai

Copy link
Copy Markdown
Contributor

@groeneai @alexey-milovidov — ClickGap found the following in this PR:

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 comp-table-functions Table functions for temporary read/write to external systems (FROM ... tableFunction()). groeneai-origin-self PR origin: self-found defect (impact-bar validated) pr-backward-incompatible Pull request with backwards incompatible changes 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.

4 participants