Skip to content

Do not resolve a table function to answer a SYSTEM STOP or a system.tables size query - #116774

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/tf-proxy-no-resolve-for-locks-and-sizes
Sep 3, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:groeneai/tf-proxy-no-resolve-for-locks-and-sizes

Conversation

@groeneai

@groeneai groeneai commented Aug 27, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A table created with CREATE TABLE ... AS <table function>(...) is no longer resolved to answer a SYSTEM STOP-family lock query or a system.tables size query about it. Previously those statements contacted the endpoint of every such table, so one unreachable endpoint made them fail or stall. Until such a table is first accessed it now reports NULL sizes and an empty data_paths, and DROP TABLE ... IF EMPTY removes it instead of reporting TABLE_NOT_EMPTY.

Description

Related: #55027
Related: #112930

Requested by @ alexey-milovidov: #93067 (comment). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=93067&sha=12d25ec6e9841172f85ade039f82cd508279a94b&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

Root cause. StorageProxy forwards getActionLock and the size family through getNested, and a table-less SYSTEM STOP/PAUSE and StorageSystemTables ask them about every catalog table. For StorageTableFunctionProxy that resolves the table function: for a file-like one with no format argument, network schema inference.

Change. Six non-forcing overrides in one header: forward when the nested storage exists, otherwise return the neutral value.

Disclosed. The only lock a table function's fresh storage can carry is the inert DistributedSend on a remote table (StorageDistributed.cpp:1130-1137). The exception is timeSeries*, which returns an existing catalog table that can be a MergeTree with real blockers; for a never touched alias of one, SYSTEM STOP <action> db.alias now stops nothing, deliberately: the previous forward renamed that target in memory, leaving it rejecting INSERT and OPTIMIZE with TABLE_UUID_MISMATCH on 26.8. The form with no table still reaches the target under its own name. StorageTableProxy already behaves this way while unloaded. Not addressed: the same gap on that proxy and on getColumnSizes (system.columns); and a scan still waits while another query resolves the same table function (getNestedImpl holds nested_mutex across it).

Validation. SELECT * FROM system.tables over an unreachable url table: DNS_ERROR before, OK after. information_schema.tables: 65.6 s before, 0.12 s after. The extended test fails on master and passes with the fix, 100/100 sequential and parallel.

Not #112203 as attributed:

The 13 hung queries in that report

resolveFunction appears in none of them. Twelve are SYSTEM STOP/PAUSE catalog walks (PAUSE VIEWS x4, STOP VIEWS x3, STOP MOVES x4, STOP MERGES x1); the thirteenth is SELECT ... FROM merge('information_schema', '.*').

Exactly one is the resolver, a SYSTEM PAUSE VIEWS at 1543 s elapsed and already is_cancelled: 1:

sleepForMilliseconds
ReadWriteBufferFromHTTP::doWithRetries
readSchemaFromFormat
IStorageURLBase::getTableStructureFromData
IStorageURLBase::IStorageURLBase
TableFunctionURL::executeImpl
StorageTableFunctionProxy::getNestedImpl             StorageTableFunction.h:44
StorageProxy::getActionLock                          StorageProxy.h:168
ActionLocksManager::add
InterpreterSystemQuery::startStopActionInDatabase

The other twelve are parked at StorageTableFunction.h:41 in recursive_mutex::lock: eleven behind that same getActionLock, and the information_schema read behind StorageSystemTables -> StorageProxy::totalBytes. So removing the single resolver removes all 13, and the two accessors it goes through are two of the six this PR overrides. #112930 replaces that backoff frame with an interruptible one; this removes the reason the walk reaches it.


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


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

groeneai and others added 5 commits August 27, 2026 11:34
`StorageProxy` forwards `getActionLock` and the size/bookkeeping family through
`getNested()` (`StorageProxy.h:169`, `:185-190`), and both families are asked
about every table in the catalog by callers that named none:
`startStopActionInDatabase` (`InterpreterSystemQuery.cpp:348` ->
`ActionLocksManager.cpp:42`) for all 26 `SYSTEM STOP <action>` variants, the four
lock passes of the startup Ordinary to Atomic conversion
(`loadMetadata.cpp:523-527`), and `StorageSystemTables.cpp:806/947/966/1060/1070`
for `system.tables` and `information_schema.tables`.

For `StorageTableFunctionProxy` that forward resolves the table function.
`IStorageURLBase`'s constructor runs schema inference over the network whenever
the format is `auto` (`StorageURL.cpp:216-224`), which is the case for a
file-like table function carrying no explicit format argument, and
`getNestedImpl` holds `nested_mutex` throughout. So a table nobody mentioned is
contacted over the network from inside a catalog walk, and when the endpoint is
unreachable every other query touching that table blocks behind the same mutex.
That is the shape of the `Stress test (arm_tsan)` hung check on
12d25ec: one holder, `SYSTEM PAUSE VIEWS` at
1543.4s with `is_cancelled: 1`, stuck in
`ReadWriteBufferFromHTTP::doWithRetries`, and twelve waiters at
`StorageTableFunction.h:41`.

Six methods now answer without resolving when the nested storage does not exist
yet, and forward unchanged when it does, so behaviour is identical for any table
that has been touched. This is the idiom `StorageTableProxy`, the other lazy
`StorageProxy` subclass, already applies to four of the same methods
(`StorageTableProxy.h:170,178,186,194`); the missing treatment on the
table-function proxy is the asymmetry being removed. Each neutral value is the
one `IStorage` returns by default, and a default-constructed `ActionLock` is
`expired()`, which is exactly what `ActionLocksManager::add` tests before storing
it.

Measured base against fixed. `SELECT * FROM system.tables` over an unreachable
`url()` table: `DNS_ERROR` before, no exception after.
`information_schema.tables` on the same fixture: 65.60s before, 0.12s after, and
before the fix it did not even throw, because `StorageSystemTables` wraps
`totalRows`/`totalBytes` in `try/catch`, so the symptom there was pure latency.
Per method, base then fixed: `getActionLock` `Code: 198` then success,
`getDataPaths` `Code: 198` then `[]`, `lifetimeRows` and `lifetimeBytes`
`Code: 198` then `\N`, `totalRows` `5` then `\N`, `totalBytes` `168` then `\N`.
The last two are measured against a resolvable `merge()` proxy because
`StorageSystemTables` swallows their exception, which makes the unreachable
fixture a vacuous oracle for them.

`supportsTruncate()` is deliberately left forwarding. `InterpreterDropQuery.cpp`
uses it as `if (!table_ptr->supportsTruncate()) continue;` at `:547` and `:706`,
so a neutral `false` would silently skip truncating the table.

One behaviour change: `DROP TABLE IF EMPTY` reads `totalRows` as an interlock
(`InterpreterDropQuery.cpp:188`), so for a never-touched table-function proxy it
now succeeds instead of reporting `TABLE_NOT_EMPTY`. Nothing is removed but the
table itself, a plain-table control still reports `TABLE_NOT_EMPTY`, and
`StorageTableProxy` already behaves this way for a table that has not been
loaded.

The regression test extends the existing
`02888_system_tables_with_inaccessible_table_function`, which exists for this
scenario. It fails on master with return code 198 and passes with the fix; 100 of
100 runs pass, 50 sequential and 50 at 8-way parallelism. No `no-parallel` tag is
needed, because `SYSTEM STOP MERGES <db>.<table>` is table-scoped and the
`merge()` pattern only ever matches the test's own database.

This does not make the `url` retry backoff interruptible, which is a separate
defect.

Co-Authored-By: Claude Opus 5 <[email protected]>
The six overrides `getActionLock`, `getDataPaths`, `totalRows`, `totalBytes`,
`lifetimeRows` and `lifetimeBytes` held `nested_mutex` across the forwarded call
to the nested storage. They now copy the pointer under the mutex, release it, and
forward outside.

On a proxy whose table function is already resolved, that forwarded call can read
remote metadata. `StorageObjectStorage::totalRows` and
`StorageObjectStorage::totalBytes` (src/Storages/ObjectStorage/StorageObjectStorage.cpp:570-596)
call `lazyInitializeIfNeeded` for a table function and then reach
`IcebergMetadata::totalRows`, whose own comment states that summing the per-file
`record_count` is exact "at the cost of opening the manifest files", looping over
`manifest_list_entries`. `read`, `write` and `supportedPrewhereColumns` in this
class all take the same mutex through `getNested`, so holding it across a size
query would queue every concurrent `SELECT` and `INSERT` on that table behind the
manifest reads.

`StorageProxy` forwarded all six through `getNested`
(src/Storages/StorageProxy.h:169,185,187-190), which releases the mutex before the
nested call, so this restores the concurrency master had for these methods while
keeping the answer that does not resolve the table function.

No observable answer changes: the reference file of
02888_system_tables_with_inaccessible_table_function is untouched and the six
per-override probes return the same values as before.
The guard added here answers `data_paths` with an empty list while the table function is
unresolved. The test asserted that empty answer but never the other side, so nothing pinned the
forwarding branch: `getDataPaths` could have returned `Strings{}` unconditionally and the test
would still have passed.

The new arm reads `notEmpty(data_paths)` twice around a `SELECT count()` that resolves a `file`
proxy, so the reference now records `0`, `3`, `1`. Verified by mutating only the body of
`getDataPaths` to `return Strings{};`: that reddens the third line alone and leaves the two before
it untouched, so the arm pins that branch and nothing wider. The base binary cannot serve as the
instrument here, because it aborts earlier in the same file with `DNS_ERROR` and never reaches the
new lines.

The format is `TSVWithNamesAndTypes` rather than `TSV` because the arm must not pass a `structure`
argument: that would make `hasStaticStructure` true, `ITableFunction::execute` would build a real
`StorageFile` instead of a proxy, and the arm would be vacuous. Without a structure argument the
column name comes from the file, and a headerless `TSV` yields `c1` against a cached `x`. Taking
both the name and the type from the header also keeps the arm independent of every
`schema_inference_*` setting, so no query-level pin is needed.

`lifetimeRows` and `lifetimeBytes` get no forwarding arm because they have no reachable carrier:
`StorageBuffer` is their only non-trivial implementor and no table function builds one, so such an
arm could only re-assert the `\N` that the non-forwarding arm already asserts. `getActionLock` gets
no forwarding arm because the only lock-bearing target a table function can reach is a
`timeSeries*` target, and reading one aborts a debug or sanitizer server on the pre-existing
`chassert(!getStoragePolicy())` in `getNested`; under `Stress test` the server-side AST fuzzer
re-executes statements, so that fixture would add an abort in the job class this change exists to
fix.
… IF EMPTY`

Two of the assertions added for the resolved side of this guard tested only that an
answer was present, not that it was the nested storage's own answer. After the
`SELECT count()` that resolves the proxy, the test read `isNotNull(total_bytes)` and
`notEmpty(data_paths)`, both of which an override returning an arbitrary constant
would satisfy. Measured on a build whose `getDataPaths` returns `Strings{"bogus"}`
unconditionally: `notEmpty(data_paths)` is still `1`, and with `totalBytes` returning
`1` unconditionally `isNotNull(total_bytes)` is still `1`. Neither mutation was
detected.

Both assertions now name a value. `data_paths` must hold exactly one path containing
the file the arm wrote, which `Strings{"bogus"}` fails while an empty list still fails
the length term, so the reference values do not move. `position` is used rather than
`LIKE` because a database name contains `_`, and `LIKE` would read that as a
single-character wildcard. `total_bytes` is compared against the `Memory` table the
`merge` proxy wraps rather than against a literal: `StorageMerge::totalBytes` sums
`totalBytes` over the matched tables, so with one match the two are equal by
construction, while a byte count pinned in the reference would be hostage to
Memory-engine accounting. Comparing an unknown size to a number yields NULL, so the
pre-resolution cell moves from `0` to `\N`.

The changelog entry states that `DROP TABLE ... IF EMPTY` now removes such a table
instead of reporting `TABLE_NOT_EMPTY`, and no statement exercised that path. A
proxy that is created and dropped without being read reaches
`InterpreterDropQuery.cpp:186-189`, where the row count is compared as an
`std::optional`: an empty one is not greater than zero, so the emptiness interlock
no longer refuses the table. Nothing resolves on the way out, because the proxy's
`drop` and `shutdown` no-op while the nested storage is null, so the arm also asserts
that the rows the proxy would have read are still there. Left unannotated on purpose:
the statement throws on master and succeeds here, and a `serverError` annotation would
invert that. A plain five-row table is still refused with `TABLE_NOT_EMPTY` on both
builds, so `IF EMPTY` is unchanged except for the unknown-count case.
…he resolved path exactly

The `DROP TABLE ... IF EMPTY` arm did not pin `ignore_drop_queries_probability`, and two
CI jobs set it: the stress runner appends `ignore_drop_queries_probability=0.2` to every
`Stress test` run, and `Upgrade check` passes `--fake-drop`, which the client turns into a
session-wide value of 1. `IF EMPTY` is a flag rather than a kind, so the emptiness check
runs first and the arm's own assertion passes before the statement is rewritten.

For an on-disk table that rewrite only ignores the drop, which is why other tests can
leave the setting alone. `StorageTableFunction::storesDataOnDisk` answers false, so the
rewrite takes the other branch and turns the statement into a `TRUNCATE`: that resolves
the table function, and `Merge` has no `truncate`, so the arm fails with `NOT_IMPLEMENTED`
- nondeterministically under `Stress test`, on every run under `Upgrade check`. Pinning
the setting on that one statement keeps it a `DROP`. No tag can express this: `no-stress`
is rejected outright and there is no `no-upgrade-check` tag.

The two `data_paths` cells compared the forwarded path with `position(...) > 0`, which a
path that merely contains the expected file name also satisfies. `basename` makes the
comparison exact while staying independent of the absolute `user_files` prefix; measured
against a build whose `getDataPaths` appends `.bogus` to the forwarded path, the old form
does not notice and the new one does.

Tests only, no source change; reference values are unchanged.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Aug 27, 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) plus my own cold review of the
resulting code, over 6 rounds. The final round found nothing: the gate returned no findings and my
own cold review of the last change raised no blocker or major.

# Sev Finding Verdict Evidence / action
1 ❌ A table function that returns an existing catalog table can hold real action locks, so the non-forcing getActionLock loses them for a timeSeries*-backed table AGREE on the fact, DISAGREE on the remedy Confirmed: with the alias never touched, SYSTEM STOP MERGES db.alias no longer blocks the target (OPTIMIZE ... optimize_throw_if_noop = 1 returns rc=0, against ABORTED for the same statement on the target's own name in the same run). Preserving the forward is worse, because the only way to delegate is to resolve, and resolving renames the target in memory, after which the catalog refuses the target by its own name. Measured on release 26.8, each gate proving the target healthy first and then applying one trigger: SYSTEM STOP on the alias leaves the target rejecting INSERT and OPTIMIZE with TABLE_UUID_MISMATCH, and a second alias with UNKNOWN_TABLE. A single read of data_paths, total_rows or lifetime_rows of the untouched alias in system.tables does the same, which is this pull request's own motivating query. Three negative controls stay healthy (stop on the target's own name, stop on a url() proxy, no stop at all), and with this change every one of those cases is OK. The catalog-wide SYSTEM STOP <action> is unaffected, because it reaches the target under its own catalog name. Disclosed in the description; the rename is pre-existing and out of scope here
2 ⚠️ The regression test never observes the forwarding branch of getActionLock, getDataPaths, lifetimeRows and lifetimeBytes AGREE, fixed @ 35e5f1feb38b66a True: the only post-resolution assertions were total_rows and total_bytes. Handled per method rather than in bulk. getDataPaths is now asserted after resolving a file()-backed table. lifetimeRows and lifetimeBytes are unobservable by construction, since StorageBuffer is the only storage implementing them non-trivially and no table function builds one. getActionLock forwarding is reachable only through a timeSeries* target, and such a table trips a pre-existing assertion in getNested on any debug or sanitizer build as soon as anything reads it, so a fixture there would be worse than the recorded gap
3 ⚠️ The six new overrides held nested_mutex across the forwarded call, where StorageProxy released it first (StorageTableFunction.h vs StorageProxy.h:187-190) AGREE, fixed @ ce49d116c3ff91d Real for an already resolved proxy: StorageObjectStorage::totalRows/totalBytes run lazyInitializeIfNeeded and then walk Iceberg manifest files, while read, write and supportedPrewhereColumns all need that same mutex, so one system.tables size read would have stalled concurrent queries on the table. That is the shape this pull request exists to remove. The forward now happens outside the lock, as it did before, and no observable answer changes
4 💡 Linked issues should be full GitHub URLs, one relationship per line AGREE, fixed in the description Measured over 25 recently merged pull requests: 0 use an abbreviated visible reference
5 💡 Remove the space in @ alexey-milovidov DISAGREE Deliberate: the space is how I reference a person without generating a notification, since maintainers here have asked for fewer pings. The template says nothing about mentions, and he is already notified through the thread where he asked for this fix
6 💡 The changelog entry did not state the observable output change AGREE, fixed in the description A never touched table now reports NULL sizes and an empty data_paths
7 💡 The body omitted the one lock a remote()-backed table can carry AGREE, fixed in the description DistributedSend, verified inert before writing it: StorageDistributed.cpp:1130-1137 forces synchronous inserts when relative_data_path is empty
8 💡 Literal names in text should be inline code, and function names written without parentheses AGREE, fixed in the description .claude/CLAUDE.md, which predates this branch
9 💡 DROP TABLE IF EMPTY on a never touched table no longer reports TABLE_NOT_EMPTY (InterpreterDropQuery.cpp:188) AGREE, disclosed Accepted rather than changed: nothing but the table itself is removed, and for url, file, mysql and plain s3 the check already passed on master because those report no row count
10 💡 system.columns still resolves both lazy proxies through getColumnSizes AGREE, out of scope Deliberate: getColumnSizes also feeds prewhere and join planning, so a neutral answer there could change a plan, which the size family cannot. Disclosed
11 ⚠️ StorageBuffer turns an unknown destination row count into an exact zero, so a Buffer over a never touched proxy reports no rows in system.tables while reading it returns the destination's rows AGREE on the fact, DISAGREE on the scope The fact is real: StorageBuffer::totalRows returns total_writes.rows + underlying_rows.value_or(0) (StorageBuffer.cpp:1404-1410), against IStorage.h:751-757, which says the count is exact and takes the underlying storage into account. It is not this change's to fix: that collapse is unconditional in StorageBuffer and already has three reaches on master. StorageDistributed overrides only totalBytes and not totalRows (StorageDistributed.h:109), so the documented Buffer over Distributed deployment already reports only its own writes; StorageTableProxy already answers nullopt while unloaded (StorageTableProxy.h:186-192), so a Buffer over an unloaded lazy_load_tables MergeTree already reports the same zero over real on-disk rows; and a missing destination gives it a third time. Fixing it means changing StorageBuffer's aggregation for every destination that reports an unknown count, which is a larger user-visible change, in another file, than the one this pull request makes. A test arm without that change would only pin the wrong zero
12 ⚠️ The resolved-path assertions were presence-only, so isNotNull(total_bytes) and notEmpty(data_paths) would also pass for an override returning a constant such as 1 or one bogus path AGREE, fixed @ 626d752fe3d30b5 Second time this shape was raised, after finding 2. total_rows was already a value oracle, pinning the literal 5; the other two are now value oracles too, comparing the proxy's bytes against the table the merge proxy wraps and matching the resolved path against the file the test wrote. Proved by a mutant per claim, including one that returns a constant path, so a blanket break is not what reddens the line
13 ⚠️ The changelog promised the DROP TABLE ... IF EMPTY change with no statement exercising it AGREE, fixed @ 626d752fe3d30b5 Raised after I put that sentence in the changelog. It had been measured but not shipped as a contract, so the test now creates a never read proxy, drops it with IF EMPTY, and asserts both that its catalog row is gone and that the 5 rows it would have read are still there. Refused with TABLE_NOT_EMPTY on master, and still refused there for a plain table on both builds
14 💡 The root cause named SYSTEM START among the statements that force a resolve AGREE, fixed in the description Correct: the start branch calls ActionLocksManager::remove, a map lookup, and onActionLockRemove, an empty default this class does not forward, so only the stop and pause halves ever ask for a lock
15 ❌ The new DROP TABLE ... IF EMPTY arm did not pin ignore_drop_queries_probability, so the stress runner could rewrite the drop into a truncate AGREE, fixed @ 1baf64d9561577e The stress runner sets the probability to 0.2 and the upgrade check sets it to 1 through --fake-drop. Because this table stores no data on disk, a rewritten drop becomes a truncate, which resolves the table function and then fails, and even a successful truncate would leave the table in the catalog where the reference expects it gone. Neither escape tag exists: no-stress is rejected outright and there is no upgrade-check tag, so the statement pins the setting, as the in-tree tests whose names say so already do
(04796_create_or_replace_internal_drop_not_ignored, 04913_drop_refreshable_mv_not_ignored). The pin is proved to apply by running the file with the setting forced to 1, once as shipped and once with the pin removed
16 💡 The resolved data_paths assertion matched the filename as a substring, so a forwarded path with characters appended would still pass AGREE, fixed @ 1baf64d9561577e Third round on this assertion, after findings 2 and 12. The surviving mutant is not one this method can acquire, since its body either forwards or returns the neutral value, and both of those are already caught. Tightened anyway, to an exact basename comparison, because a round was already being spent: the mutant that appends to the forwarded path now reddens the line, and the earlier constant-path mutant still does

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Two limits of this change are disclosed rather than fixed, both in the description: a scan still
waits while another query is resolving the same table function, because the resolve holds
nested_mutex for its whole duration, and the same gap remains on the sibling lazy proxy and on
getColumnSizes. The first is visible in the linked report itself, where one query is the resolver
and the other twelve are waiting on that mutex; this change removes the resolver, not the wait.

Finding 1 was missed by my own review because I enumerated lock-bearing storages by searching the
table-function sources for storage class names, which cannot see a table function that returns a
storage it never names. Redone by what executeImpl returns: of the eight catalog-reading table
functions, exactly one returns a fetched catalog storage. Its remedy was implemented and measured
before being declined, not declined on reading.

Session id: cron:clickhouse-review-slot-9:20260827-185200

@clickhouse-gh clickhouse-gh Bot closed this Aug 27, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (x String) AS url('http://some_addr:9000/nonexistent') (no format argument, so the format is inferred), then any of SYSTEM STOP MERGES t, SELECT data_paths FROM system.tables, SELECT lifetime_rows FROM system.tables fails on demand with DNS_ERROR in ~33 s. CREATE itself is 0.09 s and touches nothing.
b Root cause explained? Yes. StorageProxy forwards getActionLock and the size family through getNested(); startStopActionInDatabase (reached by the SYSTEM STOP/PAUSE forms that name no table) and StorageSystemTables ask both about every table in the catalog, having named none. For StorageTableFunctionProxy the forward resolves the table function, and IStorageURLBase's constructor runs schema inference over the network when the format is auto, all while holding nested_mutex.
c Fix matches root cause? Yes. The guard is on the class that owns the laziness, not at the two call sites: six non-forcing overrides in one header. No widened bound, no no-random-* tag, no defensive check at the failure site.
d Test intent preserved / new tests added? Yes. 02888_system_tables_with_inaccessible_table_function is extended, not replaced, and no existing arm is weakened or removed. New arms cover all six overrides plus two arms asserting the guard still forwards once the table is resolved: total_rows and total_bytes compared against the Memory table behind a merge proxy, and, behind a file proxy, length(data_paths) = 1 AND basename(data_paths[1]) = <expected file name>, which reads 0 before the read and 1 after. Both are value oracles rather than presence tests, so a body that forwards a wrong answer is caught: with getDataPaths returning Strings{"bogus"} the presence form stays green while this one reddens. Liveness was proved one mutant at a time, each moving a disjoint subset of reference lines: getDataPaths to {} moves only the post-resolution data_paths line, to {"bogus"} moves that line and the fourteen unresolved-proxy lines, totalBytes to 1 moves the two merge lines, totalRows to nullopt moves one of them, and appending to the forwarded path moves the post-resolution line alone. The base binary cannot be these arms' instrument: on base the file aborts at the first catalog SELECT ... data_paths ... with return code: 198 and never reaches the new lines.
e Both directions demonstrated? Yes. The test on the shipped tree: base [ FAIL ] 33.00 sec, return code: 198; fixed [ OK ] 0.37 sec, with the base client so only the server differs. Per override, base vs fixed: getActionLock Code: 198 after 32.82 s / ok in 0.07 s, getDataPaths Code: 198/[], lifetimeRows Code: 198/\N, lifetimeBytes Code: 198/\N, totalRows 5/\N, totalBytes 168/\N; the two servers ran side by side so the base one is a live control. Build IDs ad9478e5f8e332ee2bfe83a3c2777cbca85821d2 (base) and 8ad5094235f408ee2157e4c803b9efb038293e29 (fixed), both asserted in-server via buildId().
f Fix is general across code paths? Yes. Fixed at the storage level, so both entry families are covered at once, plus the 4 lock passes over every table during the startup Ordinary to Atomic conversion. All 7 getActionLock implementations in the tree were enumerated: the only one any table function can produce is StorageDistributed (TableFunctionRemote.cpp:69), whose DistributedSend blocker is inert for such a table because that call site passes an empty relative_data_path_ and StorageDistributed.cpp:1130-1137 therefore forces synchronous INSERTs.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Exercised on two structurally different nested storages: one that cannot be constructed without I/O (url, all six methods) and one that is cheap and returns real values (merge over Memory, non-null totalRows/totalBytes), plus the six existing postgresql/mysql/sqlite/mongodb/redis/s3 arms in the same file. Type wrappers are not a dimension: the guarded values are std::optional<UInt64>, Strings and ActionLock, and each neutral value is the one IStorage itself returns by default.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default change, no serialization or format change, no new system.tables column, no access-control change, so SettingsChangesHistory.cpp is not involved. One behaviour change is disclosed in the description: DROP TABLE IF EMPTY on a never-touched such table now succeeds instead of reporting TABLE_NOT_EMPTY. Nothing is removed but the table itself (measured: the underlying rows remain), a plain-table control still reports TABLE_NOT_EMPTY on both builds, and StorageTableProxy already behaves this way while unloaded.
i Invariants and contracts preserved? Yes. Invariant: a lazy proxy answers a bookkeeping or lock question about a table nobody named without resolving it. Every consumer of the six methods was enumerated and checked, including the trivial-count paths (nullopt only declines the optimization; the fallback read returns the same count), optimizeJoin (runs after read(), so the proxy is already resolved and forwards), and DatabaseAtomic::tryCreateSymlink, which never reaches these methods for this class because all three of its call sites are gated on storesDataOnDisk, already false here. supportsTruncate() was deliberately NOT given a neutral default, because InterpreterDropQuery.cpp:547/:706 use it as if (!supportsTruncate()) continue; and a false answer would silently skip truncating the table. nested_mutex is a recursive_mutex, and each added body copies the nested pointer under it and then forwards outside the lock, which is what StorageProxy does through getNested and what read, write and supportedPrewhereColumns in this same class already do, so neither a new lock-ordering edge nor a wider critical section is introduced; the StoragePtr copy keeps the nested storage alive for the call.

Suite runs: 100 of 100 passes on the fixed build (Build ID 8ad5094235f408ee2157e4c803b9efb038293e29), 50 sequential and 50 at 8-way parallelism, randomized settings on. No no-parallel tag was needed: every new arm is table- or database-scoped, and the file arm's path is prefixed with currentDatabase(). Sweep of the whole stateless suite for tests that create a table-function proxy and read a guarded column found 42 candidates and exactly one hit, this file. Of the 16 tests in the suite that read data_paths, lifetime_rows or lifetime_bytes, this is also the only one that creates such a proxy. The few that fail in this sandbox need Azure or S3, which it does not have, and they fail the same way on the base build.

Session id: cron:clickhouse-review-slot-9:20260827-185200

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [6622ef2]

Summary: ✅


AI Review

Summary

This PR correctly stops StorageTableFunctionProxy from resolving most lazy table-function storages just to answer system.tables bookkeeping or SYSTEM STOP queries, which addresses the motivating url() stall. Two review concerns remain in the current tree: one blocker where explicit SYSTEM STOP/PAUSE silently does nothing for untouched timeSeries* proxies, and one major where the new unknown row count propagates into Buffer as an exact zero.

Findings

❌ Blockers

  • [src/Storages/StorageTableFunction.h:69-72] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116774#discussion_r3875315875] SYSTEM STOP/PAUSE <action> db.alias still promises to affect the table the user named, but for an untouched CREATE TABLE ... AS timeSeriesSamples/Tags/Metrics(...) proxy this branch now returns an expired ActionLock and reports success without stopping the underlying table. The "another PR bans this shape" argument is not true in the current code: TableFunctionTimeSeriesTarget still inherits ITableFunction::canBeUsedToCreateTable() (src/TableFunctions/TableFunctionTimeSeries.h:14), and InterpreterCreateQuery still accepts any table function whose canBeUsedToCreateTable() returns true (src/Interpreters/InterpreterCreateQuery.cpp:2477). Suggested fix: either reject unresolved timeSeries* proxies in getActionLock() instead of returning success, or land the canBeUsedToCreateTable() = false guard for those table functions in the same PR.

⚠️ Majors

  • [src/Storages/StorageTableFunction.h:81-84] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116774#discussion_r3875315885] Returning nullopt here does not stay local to system.tables: StorageBuffer::totalRows() still collapses an unknown destination count to an exact 0 (src/Storages/StorageBuffer.cpp:1404), and DROP TABLE IF EMPTY trusts that result (src/Interpreters/InterpreterDropQuery.cpp:186). After this patch, a Buffer over an untouched CREATE TABLE ... AS merge(...) or similar table-function proxy can be dropped as "empty" even though SELECT count() would resolve the proxy and read destination rows. The pre-existing Buffer bug is real, but this PR expands it to a new supported destination shape. Suggested fix: either teach StorageBuffer::totalRows() to propagate unknown destination counts, or preserve an exact count for unresolved table-function proxies on the Buffer / IF EMPTY path.
Tests
  • ⚠️ No test exercises CREATE TABLE ... AS timeSeriesSamples/Tags/Metrics(...), so the blocker above is still uncovered by the current regression suite.
  • ⚠️ There is also no test for Buffer over an untouched table-function proxy, which is why the new exact-zero path through StorageBuffer::totalRows() remains invisible.
Final Verdict

Changes requested: the explicit-table SYSTEM STOP/PAUSE contract is still broken for timeSeries*-backed proxies, and the new nullopt row-count path leaks into Buffer as a false exact zero.

LLVM Coverage Report

Measured on commit 6622ef2.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 17/18 (94.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @vitlibar @jkartseva, could you review this? A table made with CREATE TABLE ... AS <table function>(...) is a lazy proxy, but StorageProxy forwards getActionLock and the size family through getNested, so a table-less SYSTEM STOP and a system.tables scan resolved every such table just to answer a lock or a size question, which for a url table with no format argument means network schema inference under nested_mutex. Six non-forcing overrides answer the neutral value while the table function is unresolved and forward unchanged once it is.

ActionLock getActionLock(StorageActionBlockType action_type) override
{
auto storage = nestedIfResolved();
return storage ? storage->getActionLock(action_type) : ActionLock{};

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.

SYSTEM STOP/PAUSE <action> db.alias still promises to affect the table the user named, but this branch turns it into a silent no-op for CREATE TABLE ... AS timeSeriesSamples/Tags/Metrics(...).

Those table functions return the existing catalog target directly (src/TableFunctions/TableFunctionTimeSeries.cpp:77-92), and the explicit-table path in InterpreterSystemQuery::startStopAction only asks this proxy for an ActionLock. When nested is still null we now report success without ever blocking the target, so merges/fetches keep running until some other query resolves the alias.

If we cannot preserve forwarding here, I think we need to reject those unresolved timeSeries* proxies explicitly instead of silently succeeding.

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.

Measured on that exact shape (CREATE TABLE al AS timeSeriesSamples(ts), explicit SAMPLES ts_samples target so the target has its own name), two parts in the target, oracle OPTIMIZE TABLE ts_samples SETTINGS optimize_throw_if_noop = 1, one trigger per run:

trigger master debug master release 26.8 this PR
none ok ok ok
SYSTEM STOP MERGES al SIGABRT Code: 741, then SIGSEGV ok, no lock taken
SYSTEM STOP MERGES ts_samples 236 ABORTED 236 236
SYSTEM STOP MERGES (no table) SIGABRT Code: 741, then SIGSEGV 236 ABORTED

Row 3 is the sensitivity control, so row 2 is a real measurement and you are right that the table-scoped form stops blocking the target.

Preserving the forward is not available. The forward is getNested, which asserts !getStoragePolicy() and !storesDataOnDisk() right above the comment saying that table functions cannot have a storage policy and cannot store data on disk. A samples table is an on-disk MergeTree, so the first assertion fires and a debug or sanitizer server aborts on that statement. In a release build getNestedImpl first runs nested_storage->renameInMemory(getStorageID()), so the target answers to al from then on and its own name gives Table default.ts_samples (<uuid>) does not match default.al (<same uuid>).

Row 4 is the practical one: with a proxy of this family in the catalog, the catalog-wide form reaches the target only with this change.

Rejecting is the right shape, and it is already in flight one level up, at creation instead of at lock time: #116629 makes TableFunctionTimeSeriesTarget::canBeUsedToCreateTable return false, enforced at InterpreterCreateQuery.cpp:2406, so such a proxy cannot be created at all. A rejection added here would be unreachable once that lands, so I am not adding one.

std::optional<UInt64> totalRows(ContextPtr query_context) const override
{
auto storage = nestedIfResolved();
return storage ? storage->totalRows(query_context) : std::nullopt;

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.

nullopt here is not neutral for all existing callers. StorageBuffer::totalRows() collapses an unknown destination count to an exact 0 (src/Storages/StorageBuffer.cpp:1404-1410), so after this change a Buffer over an untouched CREATE TABLE ... AS merge(...) / similar table-function proxy reports zero rows and passes DROP TABLE IF EMPTY, even though SELECT count() would resolve the proxy and see the destination rows.

Before this patch the proxy forwarded totalRows() and Buffer kept the right count. This needs either a StorageBuffer fix first, or a way to preserve exact row counts for callers that rely on them.

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.

The mechanism holds, and it is not specific to table functions. StorageBuffer::totalRows returns total_writes.rows + underlying_rows.value_or(0), so it reports an exact 0 for any destination whose engine does not override totalRows (File, View, Distributed and so on). Same fixture in every row, destination holding 5 rows, DROP TABLE IF EMPTY buf as the last statement:

Buffer destination master this PR
MergeTree 705 TABLE_NOT_EMPTY 705
File(TSV) dropped, total_rows 0, count() FROM buf 5 dropped
a VIEW dropped, total_rows 0, count() FROM buf 5 dropped
untouched AS merge(...) proxy 705 dropped

Row 1 is the sensitivity control. Rows 2 and 3 are master with no table function anywhere, so that wrong verdict already exists today and this change adds one more destination to the set. Tightening it means propagating nullopt out of StorageBuffer::totalRows, which also turns system.tables.total_rows from 0 into NULL for every Buffer over a Distributed table, so I would rather not fold it into this PR.

Nothing is lost when the drop does happen, because the buffer's own rows are counted separately: with 3 rows written into the Buffer over that proxy, total_rows is 3 and the drop is refused with 705. After the drop the destination still has its 5 rows and the proxy table is still there, so only the empty Buffer's own name goes away. That is the same property the test states for the direct DROP TABLE IF EMPTY arm.

@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 6622ef2e8 with master bb113c384 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d469feea5; 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1baf64d

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Two things worth stating before the table, because both change how the reds read:

  1. GitHub scheduled two concurrent workflow runs on this identical tree (33108372740, 33108381175), so every check name appears twice. That gives a free negative control, and I used it: each of the three Stress test reds passed in the sibling run at the same tree, so they are state/timing dependent, not tree dependent.
  2. Fast test, Style check and Config Workflow are green in both runs, so nothing below is PR-caused.
Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Inconsistent AST formatting (STID 1941-1bfa) pre-existing trunk bug: a hoisted PRIMARY KEY tuple(x) cannot be formatted back for a table created from a table function. Failed in both runs. 38 distinct PRs and 2 true-master rows in 30 days #116645 (mine, merged 2026-08-28 01:10Z). This head is 190 commits behind that merge, so the build predates the fix; the next push on this branch picks it up
AST fuzzer (amd_debug, targeted, old_compatibility) / Inconsistent AST formatting (STID 1941-1bfa) same defect, postgresql and sqlite shapes #116645 (mine, merged)
Stress test (arm_release) / Not-ready Set is passed as the second argument for function 'globalIn' (STID 0250-3e49) pre-existing trunk bug, 74 PRs and 5 true-master rows in 30 days; passed in the sibling run at this tree #102308 (external, open)
Stress test (amd_asan_ubsan) / Not-ready Set is passed as the second argument for function 'globalNotIn' (STID 0250-41a5) same family, 141 PRs and 15 true-master rows in 30 days; passed in the sibling run at this tree #102308 (external, open)
Stress test (arm_asan_ubsan) / A data stream row of AlignStreams has no matching metadata stream row (STID 0250-16db) pre-existing trunk bug, onset 2026-08-26, 17 PRs and 3 true-master rows; passed in the sibling run at this tree #116531 (external, open)
request-reviews-fork cancelled as the superseded copy of the duplicate run; SKIPPED in the other three copies. No test signal not a test check, nothing to fix

Session id: cron:our-pr-ci-monitor:20260828-010000

@PedroTadim

Copy link
Copy Markdown
Member

cc @alexey-milovidov

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

Ok. We made it lazier, which is what we wanted.

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 3, 2026
Merged via the queue into ClickHouse:master with commit 5290d52 Sep 3, 2026
175 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 3, 2026
alexey-milovidov added a commit that referenced this pull request Oct 13, 2026
…olved table function

Dropping or detaching an unresolved `StorageTableFunctionProxy` only removes
the table from the catalog and does not touch the rows behind it, so keep the
go-ahead semantics from #116774 instead of refusing it with `TABLE_NOT_EMPTY`.
`TRUNCATE ... IF EMPTY` of such a table still refuses: it would resolve the
table function and truncate the external storage. This restores the master
version of `02888_system_tables_with_inaccessible_table_function`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 17, 2026
26.8 lacks the multi-hop alias grant checks and the row policy check in
`supportsTrivialCountOptimization`, so the alias column sizes use the
existing `isTargetTableGranted` and the trivial count check keeps only
the new `SELECT` requirement.

26.8 also lacks #116774, so a
table created from a table function reports no rows or column sizes at all;
the `StorageTableFunction` override and the `m_func` size checks of the
test are left out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Nov 17, 2026
26.3 lacks the alias grant checks on the target table, the row policy
check in `supportsTrivialCountOptimization` and the context argument of
`getInMemoryMetadataPtr`. The alias forwards the query context to its
target without filtering columns, as `system.columns` does there, and the
trivial count check keeps only the new `SELECT` requirement.

26.3 also lacks #116774, so a
table created from a table function reports no rows or column sizes at all;
the `StorageTableFunction` override and the `m_func` size checks of the
test are left out. The test enables the experimental `Alias` engine.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default 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