Skip to content

Forbid to create a table as a TimeSeries target table function - #119786

Merged
nikitamikhaylov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-119648-timeseries-target-persistence-veto
Sep 13, 2026
Merged

nikitamikhaylov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-119648-timeseries-target-persistence-veto

Conversation

@groeneai

@groeneai groeneai commented Sep 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #119648
Related: #119762

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 timeSeriesSamples(...) is no longer accepted, nor over its alias timeSeriesData or over timeSeriesTags and timeSeriesMetrics. 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 threw QueryPlan was not initialized. Reading the functions directly is unaffected. Upgrading does not stop an existing table of this shape from loading, but explicit ATTACH TABLE, RESTORE and Replicated replica recovery now refuse it. To find candidates, run SELECT 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: a view(...) 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 unfiltered system.tables read returns ASYNC_LOAD_WAIT_FAILED until the metadata file is moved out of store/ and the server restarted.

Description

CREATE TABLE p AS timeSeriesData(ts) was accepted, after which DROP TABLE ts dropped p and destroyed its rows (#119648). With assertions on, the first read of p aborted 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. Every StorageTimeSeries path that resolves a target through getTargetTable(...)->getStorageID() then resolves to p.

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 in parseArguments, as #119662 does, but that call feeds checkSourceAccess, 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 restart
aborted metadata loading. The new test drops every table it creates and asserts that no Proxy row
survives, which is the regression guard for that failure mode.

Classifying every class in src/TableFunctions/ by what executeImpl returns,
TableFunctionTimeSeriesTarget is the only one that returns an already-registered catalog table. The
seven that wrap one in a fresh storage already carry the veto (#118969, #116885) except loop, which
renames the fresh StorageLoop rather than the live inner table, and whose distinct DROP ... SYNC
defect is #118947. So four registered names, one template, one line; any future ViewTarget::Kind inherits it too.

throwIfTableFunctionCannotBeUsedToCreateTable reads only the outermost function, so
CREATE TABLE pv AS view(SELECT * FROM timeSeriesData(ts)) stays accepted. I measured it: the proxy
wraps the fresh StorageView, nothing is renamed, DROP TABLE ts SYNC drops the right table and pv
survives. Reading pv returns THERE_IS_NO_QUERY, so nothing usable is kept alive there either; a
persisted view(SELECT 1) reads fine, so that error is not a property of persisting view() itself.
Left alone; #118969 measured the same asymmetry for mergeTreeIndex.

Second residual: the two-way ternary computing name falls through to "timeSeriesMetrics" for any
kind other than Samples or Tags, so a future RecentSamples or Histograms instantiation would
register 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

  • Merged into: 26.9.1.1418 (included in 26.9 and later)

`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
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR labels Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
cold read of the tree. No finding changed the diff: the tree published here is byte-identical to
the tree the first pass read. Every accepted finding was about the changelog and migration text, which
the second and third passes re-read after I corrected it.

# Sev Finding Verdict Evidence / action
1 ⚠️ The changelog promised that an existing proxy table "still loads at startup", which the loading order does not guarantee AGREE, fixed in this body The entry now claims only that the veto does not touch the loading path, and states the observed load failure and its recovery
2 ⚠️ The remediation advice could destroy data: once the proxy has been read, its drop forwards to the live target (StorageTableFunction.h:132-137) AGREE, fixed in this body The entry now says to drop on a freshly started server before anything reads it, and says what a definition already read does instead
3 ⚠️ The create_table_query ILIKE '%timeSeries%' filter I had added in response to finding 2 also matches a persisted view(...) over one of these functions, which stays accepted AGREE, fixed in this body Filter removed; candidates come from engine = 'Proxy' plus inspection of the outer call, and the view(...) shape is named as different
4 ⚠️ The stateless test does not verify the startup / ATTACH / RESTORE / replica-recovery split the changelog claims DISAGREE Measured on real servers instead: a definition written by the base binary loads on the fixed one, short ATTACH returns BAD_ARGUMENTS, and DROP leaves the TimeSeries rows intact. RESTORE and Replicated recovery both replay through InterpreterCreateQuery (DatabaseReplicated.cpp:1668-1690, :1940), which is the vetoed path. Reaching those from a stateless test means hand-writing metadata into store/, which the directive on #111922 rules out for functional tests; #118969 shipped the same split for its family
5 💡 Relationship lines used short references instead of the template's full GitHub URLs (raised in two passes) AGREE, fixed in this body Both lines are full URLs

My own cold read found 0 blockers and 0 majors: the hook has exactly one consumer, both of its call
sites are exercised by the test, and CREATE TEMPORARY TABLE ... AS <one of these> is refused or dies
in StorageFactory before a proxy exists. Its 3 nits are closed, one of them dropped because its
premise was wrong (the explicit column list in the test is the exact DESCRIBE output, and a
deliberately wrong list returns BAD_ARGUMENTS too, so that arm cannot pass for a structure reason).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are terminal
per finding.

Session id: cron:clickhouse-review-slot-8:20260913-115000

@clickhouse-gh clickhouse-gh Bot closed this Sep 13, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 13, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE ts ENGINE = TimeSeries; CREATE TABLE p AS timeSeriesData(ts); SELECT count() FROM p; on a Debug server: the CREATE is accepted (engine Proxy) and the first read aborts the server, exit 134, Logical error: '!nested_storage->getStoragePolicy()'. No randomization needed.
b Root cause explained? The class had no canBeUsedToCreateTable() override, so it inherited the permissive default and CREATE TABLE ... AS was accepted. executeImpl returns the TimeSeries table's target table, i.e. a live catalog table, and persistence wraps it in a StorageTableFunctionProxy that renames the storage in memory to the proxy's id and only then asserts it has no storage policy and stores nothing on disk. An inner target is a MergeTree, so it violates both, and after the rename every StorageTimeSeries path resolving a target through getTargetTable(...)->getStorageID() resolves to the user's table.
c Fix matches root cause? Yes. The refusal lands at the layer that decides persistability, before the proxy, the rename, the assertion or the metadata file exist. No guard at the abort site, no widened bound, no test tag. StorageTableFunction.h is shared by every table function and is deliberately untouched.
d Test intent preserved / new tests added? New stateless test 05210_forbid_timeseries_target_table_functions_as_engine; no existing test changed, because none persists these functions. It covers the four registered names, both enforcement call sites, an external target, the untouched transient form, and asserts no engine = 'Proxy' row survives.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: the test fails on the unpatched build with all six refusal arms reporting "The query succeeded but the server error '36' was expected" and the Proxy count printing 6, and passes on the patched build. A mutant that returns true from the new override reds it again identically. 50/50 with randomization on.
f Fix is general across code paths? Yes. Classifying every class in src/TableFunctions/ by what executeImpl returns, this is the only one that returns an already-registered catalog table; the wrapper classes already carry the veto (#118969, #116885), and loop renames a fresh storage instead, its own defect being #118947. The veto is on the class template, so all three instantiations, the timeSeriesData alias and any future ViewTarget::Kind inherit it. The nested view(...) form is measured and disclosed in the PR body.
g Fix generalizes across inputs (params/datatypes/wrappers)? No type surface exists here: the veto is a compile-time boolean on a table-function class, with no Nullable / LowCardinality / Array variant. I measured the argument surface instead: one-argument identifier form, two-string form, the alias, no column list, the exact column list, a deliberately wrong column list, an inner target and an external Memory target, all refused with BAD_ARGUMENTS.
h Backward compatible? (maintainer-approved exception only) Deliberately not, and filed as Backward Incompatible Change mirroring #118969. Measured: startup metadata load still accepts a definition written before this change, DETACH and DROP still work, and a DROP of an unread one leaves the TimeSeries data intact; only explicit ATTACH TABLE, RESTORE and Replicated replica recovery are refused. The changelog entry carries the state-aware removal procedure (drop it on a freshly started server before anything reads it, since a definition already read in that server lifetime is bound to the live target and forwards the drop to it) and says not to detach it instead. No setting changes, so no SettingsChangesHistory.cpp entry.
i Invariants and contracts preserved? Yes. The only contract touched is ITableFunction::canBeUsedToCreateTable, an unconditional boolean with no state, no ordering and no error path; both call sites already handle false. The transient path is unchanged: with empty cached_columns, ITableFunction::execute calls executeImpl directly, which the test asserts still returns rows. The change restores, rather than weakens, the proxy's own documented invariant that it holds no storage with a storage policy or on-disk data.

Session id: cron:clickhouse-impl-slot-7:20260913-110600

@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18ff2d8]

Summary: ✅


AI Review

Summary

This PR adds a canBeUsedToCreateTable() veto to TableFunctionTimeSeriesTarget and a stateless regression test so the direct CREATE TABLE ... AS timeSeriesData / timeSeriesSamples / timeSeriesTags / timeSeriesMetrics forms are rejected. The direct path looks correct, but the veto is still bypassable through nested table functions such as loop(...), so the persistence ban is not complete yet.

Findings

❌ Blockers

  • [src/TableFunctions/TableFunctionTimeSeries.h:27] The new veto only protects the outermost AS timeSeries... form. throwIfTableFunctionCannotBeUsedToCreateTable() still recurses only through dependsOnCurrentUserGrants(), so CREATE TABLE p AS loop(timeSeriesData(ts)) is still accepted. loop then executes the inner function and wraps its result, which means the unsupported TimeSeries target remains persistable through a one-layer wrapper and the resulting table self-recurses on read via ReadFromLoopStep. Suggested fix: reject nested table functions whose canBeUsedToCreateTable() is false, and add a regression case for loop(timeSeriesData(...)).
Tests
  • ⚠️ Not run locally. The blocker above comes from a static trace through InterpreterCreateQuery, ITableFunction::execute, TableFunctionLoop, and ReadFromLoopStep; the added stateless test covers only the direct AS timeSeries* forms.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 18ff2d8.

Metric Baseline Current Δ
Lines 89.00% 89.00% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.40% 81.40% +0.00%

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

Full report · Diff report

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; }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(...)).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@clickhouse-gh clickhouse-gh Bot added the comp-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... label Sep 13, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 18ff2d854 with master c287fac2b (stripped binary size, per-symbol sizes and ThinLTO time; 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.

Object file sizes

23 object files changed (+142.89 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Processors/QueryPlan/FillingStep.cpp.o 158.83 KiB 270.11 KiB +111.29 KiB (+70.07%)
src/CMakeFiles/dbms.dir/Core/SortDescription.cpp.o 204.89 KiB 221.96 KiB +17.07 KiB (+8.33%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@nikitamikhaylov nikitamikhaylov self-assigned this Sep 13, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Sep 13, 2026
Merged via the queue into ClickHouse:master with commit 9cee515 Sep 13, 2026
176 of 348 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 13, 2026
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-promql PromQL / time-series subsystem: TimeSeries storage engine, PromQL parser, PromQL-to-SQL converter... groeneai-origin-review-bot PR origin: review-bot finding on a groeneai PR pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

3 participants