Repository navigation
Do not resolve a table function to answer a SYSTEM STOP or a system.tables size query - #116774
Conversation
`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.
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
Severity: ❌ blocker / Two limits of this change are disclosed rather than fixed, both in the description: a scan still Finding 1 was missed by my own review because I enumerated lock-bearing storages by searching the Session id: cron:clickhouse-review-slot-9:20260827-185200 |
Pre-PR validation gate (click to expand)
Suite runs: 100 of 100 passes on the fixed build (Build ID Session id: cron:clickhouse-review-slot-9:20260827-185200 |
|
Workflow [PR], commit [6622ef2] Summary: ✅
AI ReviewSummaryThis PR correctly stops Findings❌ Blockers
Tests
Final VerdictChanges requested: the explicit-table LLVM Coverage ReportMeasured on commit 6622ef2.
Changed lines: Changed C/C++ lines covered: 17/18 (94.44%) · Uncovered code |
|
cc @vitlibar @jkartseva, could you review this? A table made with |
| ActionLock getActionLock(StorageActionBlockType action_type) override | ||
| { | ||
| auto storage = nestedIfResolved(); | ||
| return storage ? storage->getActionLock(action_type) : ActionLock{}; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 13 s compile time in total, 7 of them have a recent master baseline. |
CI finish ledger - 1baf64dEvery 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 Two things worth stating before the table, because both change how the reds read:
Session id: cron:our-pr-ci-monitor:20260828-010000 |
alexey-milovidov
left a comment
There was a problem hiding this comment.
Ok. We made it lazier, which is what we wanted.
…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]>
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]>
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]>
Changelog category (leave one):
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 aSYSTEM STOP-family lock query or asystem.tablessize 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 reportsNULLsizes and an emptydata_paths, andDROP TABLE ... IF EMPTYremoves it instead of reportingTABLE_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.
StorageProxyforwardsgetActionLockand the size family throughgetNested, and a table-lessSYSTEM STOP/PAUSEandStorageSystemTablesask them about every catalog table. ForStorageTableFunctionProxythat 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
DistributedSendon aremotetable (StorageDistributed.cpp:1130-1137). The exception istimeSeries*, which returns an existing catalog table that can be aMergeTreewith real blockers; for a never touched alias of one,SYSTEM STOP <action> db.aliasnow stops nothing, deliberately: the previous forward renamed that target in memory, leaving it rejectingINSERTandOPTIMIZEwithTABLE_UUID_MISMATCHon 26.8. The form with no table still reaches the target under its own name.StorageTableProxyalready behaves this way while unloaded. Not addressed: the same gap on that proxy and ongetColumnSizes(system.columns); and a scan still waits while another query resolves the same table function (getNestedImplholdsnested_mutexacross it).Validation.
SELECT * FROM system.tablesover an unreachableurltable:DNS_ERRORbefore, 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
resolveFunctionappears in none of them. Twelve areSYSTEM STOP/PAUSEcatalog walks (PAUSE VIEWSx4,STOP VIEWSx3,STOP MOVESx4,STOP MERGESx1); the thirteenth isSELECT ... FROM merge('information_schema', '.*').Exactly one is the resolver, a
SYSTEM PAUSE VIEWSat 1543 s elapsed and alreadyis_cancelled: 1:The other twelve are parked at
StorageTableFunction.h:41inrecursive_mutex::lock: eleven behind that samegetActionLock, and theinformation_schemaread behindStorageSystemTables->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]