Repository navigation
Forbid to create a table as a TimeSeries target table function - #119786
Conversation
`CREATE TABLE p AS timeSeriesData(ts)` was accepted, and then `DROP TABLE ts` dropped `p` instead of the inner samples table and destroyed its rows. On a build with assertions the first read of `p` aborted the server on `!nested_storage->getStoragePolicy()`, from analyzer identifier resolution. `TableFunctionTimeSeriesTarget::executeImpl` returns the TimeSeries table's target table, which is the catalog's own StoragePtr. Persisting a table function wraps its result in a StorageTableFunctionProxy, and that proxy may only hold a storage with no storage policy that stores nothing on disk: it renames the storage in memory to its own id and only then asserts those two properties. An inner target is a MergeTree, so it violates both, and after the rename every StorageTimeSeries path that resolves a target through getTargetTable(...)->getStorageID() - dropInnerTableIfAny, checkTableSizeBelowDropLimit, truncate - resolves to the user's table. Refuse the persistence instead, the way the MergeTree introspection functions and viewIfPermitted already do. The override sits on the class template, so all three instantiations, the timeSeriesData alias and any future ViewTarget::Kind inherit it. The transient form does not go through the proxy and is unaffected. This re-lands the veto that ClickHouse#116629 already merged and that 29d745e reverted for an unrelated reason: that PR's own test left persisted definitions behind over a dropped source, so a stress restart aborted metadata loading. The new test drops every table it creates and asserts that no Proxy row survives. Closes: ClickHouse#119648
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 3 full passes, 6 findings) plus my own
My own cold read found 0 blockers and 0 majors: the hook has exactly one consumer, both of its call Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260913-115000 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-7:20260913-110600 |
|
Workflow [PR], commit [18ff2d8] Summary: ✅
AI ReviewSummaryThis PR adds a Findings❌ Blockers
Tests
Final VerdictChanges requested. LLVM Coverage ReportMeasured on commit 18ff2d8.
Changed lines: Changed C/C++ lines covered: 1/1 (100.00%) · Uncovered code |
| void parseArguments(const ASTPtr & ast_function, ContextPtr context) override; | ||
|
|
||
| /// The returned storage is the target table itself, so a persisted table would rename a live table in memory. | ||
| bool canBeUsedToCreateTable() const override { return false; } |
There was a problem hiding this comment.
This only closes the top-level CREATE TABLE ... AS timeSeriesData(...) form. The recursive check in throwIfTableFunctionCannotBeUsedToCreateTable() still looks only at dependsOnCurrentUserGrants(), so CREATE TABLE p AS loop(timeSeriesData(ts)) is still accepted. loop then calls inner_table_function->execute(...) (TableFunctionLoop.cpp:158-165), which builds the same inner StorageTableFunctionProxy for timeSeriesData; on read, ReadFromLoopStep treats that proxy's StorageID as the outer table and recurses back into p (ReadFromLoopStep.cpp:126-132). In other words, the unsupported TimeSeries target is still persistable through a one-layer wrapper.
Please extend the nested-table-function veto to reject any nested function whose canBeUsedToCreateTable() is false, and add a regression case for loop(timeSeriesData(...)).
There was a problem hiding this comment.
I ran this on a real server before acting. The premise holds, the consequence does not, so I am not making the change.
Harness: this branch's own Debug build (Build-ID 60ee3fb18ae5..., so chassert is armed), real server, 3 rows seeded into the TimeSeries data table with values 0, 100, 200.
CREATE TABLE p AS loop(timeSeriesData(ts)) is indeed still accepted. It is also harmless, on every axis the veto exists for:
| probe | result |
|---|---|
SELECT value FROM p LIMIT 7 |
0 100 200 0 100 200 0, i.e. the inner samples table cycled |
system.query_log.tables for that read |
['d..inner_id.samples.', 'd.p'], exception_code = 0 |
| live inner table after the read | still named .inner_id.samples.<uuid>; timeSeriesData(ts) still returns its rows |
| server after the read | alive; neither StorageTableFunction.h:55 nor :56 fires |
| restart with the definition on disk | loads clean; unfiltered system.tables, SHOW TABLES, DETACH, ATTACH, DROP ... SYNC all fine |
DROP TABLE ts SYNC with p present and already read |
drops ts plus its four inner tables, returns at once, p survives, later read of p gives a clean Code: 60 UNKNOWN_TABLE ... While executing Loop |
There is no self-recursion. ReadFromLoopStep::initLoop resolves inner_storage->getStorageID(), and inner_storage is whatever TableFunctionLoop::executeImpl got from the inner function, which is the inner samples table, never the outer p. A read that recursed into p could not have returned 7 rows of the seeded data, and the query_log row names the inner table explicitly. The assertion arm is not vacuous either: the read resolves the proxy through getNested() (StorageTableFunction.h:52-58), so both assertions were evaluated with the StorageLoop as nested, and neither fired. The direct form aborts this same binary at :55.
The difference is what reaches the proxy. TableFunctionTimeSeriesTarget::executeImpl returns the catalog's own StoragePtr, so getNestedImpl renames a live MergeTree (StorageTableFunction.h:46) and then asserts two properties MergeTree violates. loop puts that pointer inside a fresh StorageLoop (TableFunctionLoop.cpp:167-171) and hands the proxy the StorageLoop, which has no storage policy and stores nothing on disk, so the rename lands on a throwaway object. Same result for every other wrapper I checked: loop(loop(timeSeriesData(ts))), remote('127.0.0.1:<port>', timeSeriesData(ts)) and view(SELECT ... FROM timeSeriesData(ts)) all leave the inner table named and the server up. The Code: 393 that the view() arm returns is the pre-existing behaviour of any persisted view() proxy, with or without a TimeSeries table.
On the suggested remedy: rejecting every nested function whose canBeUsedToCreateTable() is false would newly refuse shapes that work today. CREATE TABLE c AS loop(clusterAllReplicas('test_shard_localhost', system.one)) is accepted right now and reads correctly, and clusterAllReplicas inherits the veto from ITableFunctionCluster.h:49; the same applies to persisted view(SELECT ... FROM <any vetoed function>), which I measured accepted for both clusterAllReplicas and mergeTreeIndex. The veto is declared at nine sites today, one of them that *Cluster base class, so the widening is a backward-incompatible change across all nine with no measured defect behind it. It does not belong in this PR, and I am not filing a follow-up for it: there is nothing user-visible to fix.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes23 object files changed (+142.89 KiB total), 0 added.
716 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 units8 translation units recompiled, 10 s compile time in total, 8 of them have a recent master baseline. |
9cee515
Closes: #119648
Related: #119762
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
CREATE TABLE ... AS timeSeriesSamples(...)is no longer accepted, nor over its aliastimeSeriesDataor overtimeSeriesTagsandtimeSeriesMetrics. The persisted proxy renamed that live target table in memory on first read:DROP TABLE <ts>then dropped the user's table and destroyed its rows, and reads threwQueryPlan was not initialized. Reading the functions directly is unaffected. Upgrading does not stop an existing table of this shape from loading, but explicitATTACH TABLE,RESTOREandReplicatedreplica recovery now refuse it. To find candidates, runSELECT database, name, create_table_query FROM system.tables WHERE engine = 'Proxy', which reads metadata only, and keep the ones whose outer call is one of these four functions: aview(...)wrapping one is a different, still-accepted shape. Drop such a table on a freshly started server, before anything reads it: in that state the drop leaves the TimeSeries data intact, while a definition already read in this server lifetime is bound to the live target and forwards the drop to it. Do not detach one instead, since a detached definition can no longer be attached. Independently of this change, the metadata load of such a definition can also fail after a restart, and then every unfilteredsystem.tablesread returnsASYNC_LOAD_WAIT_FAILEDuntil the metadata file is moved out ofstore/and the server restarted.Description
CREATE TABLE p AS timeSeriesData(ts)was accepted, after whichDROP TABLE tsdroppedpand destroyed its rows (#119648). With assertions on, the first read ofpaborted the server on!nested_storage->getStoragePolicy().These functions hand back the TimeSeries table's target table itself, a live catalog table. Persisting a table function wraps it in a
StorageTableFunctionProxy, which renames that storage in memory to its own id and only then asserts it has no storage policy and no data on disk, which an inner MergeTree target has both of. EveryStorageTimeSeriespath that resolves a target throughgetTargetTable(...)->getStorageID()then resolves top.The fix is the persistence veto the MergeTree introspection functions (#118969) already carry, on the class template so all four registered names inherit it. No access check or shared proxy code is touched.
One thing I did not fix, your call: the restart wedge the changelog entry describes (observed on 2 of 3 restarts;
AS <table function>registers no loading dependency,DDLDependencyVisitor.cpp:82-84). The lever is to drop the eager target resolution inparseArguments, as #119662 does, but that call feedscheckSourceAccess, so it changes the source-access surface @ vitlibar reserved on #119282. Happy to send a follow-up, or fold it in here.Why this re-lands #116629, the carrier enumeration, the nested form, and two residuals
#116629 carried this exact veto and merged. It was reverted for an unrelated reason: its own test
left persisted
timeSeriesSelector()definitions behind over a dropped source, so a stress restartaborted metadata loading. The new test drops every table it creates and asserts that no
Proxyrowsurvives, which is the regression guard for that failure mode.
Classifying every class in
src/TableFunctions/by whatexecuteImplreturns,TableFunctionTimeSeriesTargetis the only one that returns an already-registered catalog table. Theseven that wrap one in a fresh storage already carry the veto (#118969, #116885) except
loop, whichrenames the fresh
StorageLooprather than the live inner table, and whose distinctDROP ... SYNCdefect is #118947. So four registered names, one template, one line; any future
ViewTarget::Kindinherits it too.throwIfTableFunctionCannotBeUsedToCreateTablereads only the outermost function, soCREATE TABLE pv AS view(SELECT * FROM timeSeriesData(ts))stays accepted. I measured it: the proxywraps the fresh
StorageView, nothing is renamed,DROP TABLE ts SYNCdrops the right table andpvsurvives. Reading
pvreturnsTHERE_IS_NO_QUERY, so nothing usable is kept alive there either; apersisted
view(SELECT 1)reads fine, so that error is not a property of persistingview()itself.Left alone; #118969 measured the same asymmetry for
mergeTreeIndex.Second residual: the two-way ternary computing
namefalls through to"timeSeriesMetrics"for anykind other than
SamplesorTags, so a futureRecentSamplesorHistogramsinstantiation wouldregister under a colliding name. No such instantiation is registered, so nothing is reachable today,
and #115685 rewrites those exact lines while adding
Histograms.Workflow [PR]
Sync PR [sync-upstream/pr/119786]
Version info
26.9.1.1418(included in26.9and later)