Skip to content

Add reattach_tables_before_query_execution setting - #121674

Closed
alexey-milovidov wants to merge 54 commits into
masterfrom
reattach-tables-before-query-execution
Closed

alexey-milovidov wants to merge 54 commits into
masterfrom
reattach-tables-before-query-execution

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Add the settings reattach_tables_before_query_execution and reattach_tables_before_query_execution_probability. When enabled, they detach and attach back the tables used in a query right before its execution. This is a testing-only feature for finding bugs related to table reattachment.

This PR adds only the feature, off by default. Enabling it at random in clickhouse-test and the stress tests (plus the no-random-detach tags) stays in #96130.

  • IDatabase::supportsDetachingTables (returns false for Dictionary, Overlay, Replicated, SQLite, Backup, Filesystem, HDFS, S3, URL, Remote, DataLake, MaterializedPostgreSQL).
  • ActionLocksManager::has/hasAny to check for existing action locks.
  • The table collection and the reattach hook in executeQuery:
    • It runs after AST validations, process list admission and external tables initialization.
    • It skips EXPLAIN, transactions, internal and non-initial queries, and CTE name collisions.
    • It also collects the Join table named by joinGet and preflights the dictGet access of the dictionaries named by the dictGet family; a function-carried name that cannot be determined from the AST skips the hook.
    • It skips tables another query is using, and tables that the internal ATTACH could not restore (missing grants, database over max_tables, a dynamic disk definition).
    • It mirrors each interpreter's fast-fail order, so that a query rejected on its own target has no side effects.
    • It runs the internal DETACH/ATTACH with the server's default settings and without charging the user's quota (QueryFlags::ignore_quota).
    • It skips a SELECT with use_query_cache, which may be served from the query result cache.
    • It skips queries whose settings carry query text (additional_result_filter, additional_table_filters, implicit_table_at_top_level) or set a nested profile.
  • Tests: the 02461_reattach_tables suite (02461, 05099-05104, shared 02461_reattach_tables.lib) 04646_reattach_create_undrop_existing_target, 05258_reattach_tables_function_objects, 05339_reattach_tables_quota_query_cache, and the review follow-ups (05366, 05406-05408, 05427, 05448, 05449, 05453).

Related: #96130
Related: #55943
Related: #42336

Changelog category (leave one):

  • Build/Testing/Packaging Improvement

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

Add reattach_tables_before_query_execution and reattach_tables_before_query_execution_probability settings that DETACH and ATTACH back the tables used in a query before its execution. This is a testing-only feature that helps find reattachment-related bugs.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code


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

Add the testing-only settings `reattach_tables_before_query_execution` and
`reattach_tables_before_query_execution_probability`. When enabled, the tables
used in a query are detached and attached back right before its execution,
to find bugs related to table reattachment.

The hook runs in `executeQuery` after AST validations, process list admission
and external tables initialization, and skips `EXPLAIN`, transactions,
internal and non-initial queries. A table is reattached only when it stores
data on disk, its database supports a non-permanent `DETACH`
(`IDatabase::supportsDetachingTables`), it has no action locks
(`ActionLocksManager::has`/`hasAny`) or dependencies, and no other query is
using it. The collector mirrors each interpreter's fast-fail order so that a
query rejected on its own target has no side effects, preflights the access
the query is going to check and the grants the internal `DETACH`/`ATTACH`
needs, and runs that pair with the server's default settings.

Both settings are off by default; nothing enables them in CI yet.

Split out of #96130
Continuation of #55943 and #42336

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [95871fd]

Summary: ✅


AI Review

Summary

The PR adds experimental, disabled-by-default settings to reattach tables before query execution for testing. Most earlier findings are addressed, but restoration can still leave tables detached under memory or quota limits, and one additional table-function insert path violates the access-rejection contract. Changes are required.

Findings

❌ Blockers

  • src/Interpreters/executeQuery.cpp:3629: A finite default memory limit can still strand a persistent Set. Equality with the server default passes the new guard. With a 10 MB default, populate a million-key set using a 100 MB query override, then query it with reattachment enabled and the inherited default. Both attachment attempts rebuild the full hash under the 10 MB outer tracker and can fail, leaving the table detached. Isolate restoration from the caller's memory budget or skip unsafe candidates under finite effective limits. Existing finding.
  • src/Interpreters/executeQuery.cpp:4175: Stored-constraint scalar subqueries bypass the quota exemption and can prevent restoration. For a one-row table with CONSTRAINT c ASSUME x >= (SELECT sum(number) FROM numbers(1)) and MAX read_rows = 1, preflight consumes the allowance. DETACH succeeds, then attachment and recovery rerun the scalar with the user's quota and fail with QUOTA_EXCEEDED. Raw metadata and normalized attachment ASTs have different scalar-cache hashes. Propagate the exemption through validation and attachment scalar work, or skip this case before detaching. Existing quota finding.

⚠️ Majors

  • src/Interpreters/executeQuery.cpp:3353: Table-function insert arguments escape the whole-query access preflight. An INSERT INTO FUNCTION url(joinGet('db.j', 'v', toUInt64(1)), 'CSV', 'x UInt64') ... VALUES (1) collects and reattaches an eligible j before failing the missing WRITE ON URL grant. The SELECT variant also traverses the destination arguments. Mark insert.table_function unverifiable before descending into its children. New inline finding.
  • src/Interpreters/executeQuery.cpp:4324: The internal pair still consumes profile-event quotas through the outer query. Both statements increment ProfileEvents::Query in the inherited thread group; outer accounting charges those counters despite ignore_quota. A reattaching query therefore consumes at least three Query events instead of one, prematurely exhausting MAX Query quotas. Exclude the hook's work from outer quota accounting. This shares the existing quota thread.
  • src/Interpreters/executeQuery.cpp:6169: SQL UDF expansion still hides object references from collection. [dismissed by author -- https://github.com/Add reattach_tables_before_query_execution setting #121674#discussion_r4112232000] Deferred by the author; the current collector still runs before expansion, so a hidden joinGet, dictionary lookup, or IN can reattach another table before access fails. Expand before collection or skip queries containing SQL UDFs; no new inline comment is posted for this deferred point.
Tests
  • ⚠️ Add restoration coverage with a finite server default smaller than an existing persistent Set; the current test covers only a lowered query limit.
  • ⚠️ Add a stored-constraint read-quota case asserting that the table remains attached, and a profile-event quota case proving internal work is excluded.
  • ⚠️ Add denied WRITE ON URL coverage for destination-function arguments in both VALUES and SELECT inserts, with a positive reattachment control.
Missing context / blind spots
  • ⚠️ The findings are concrete source traces, not locally executed reproductions. No ClickHouse binary or build directory is available in this checkout; focused runs of the cases above would close that validation gap. Existing CI reports were fetched through the repository tool.
Final Verdict

❌ Block. Make restoration safe under effective memory and quota limits, exclude table-function insert destinations from the hook, and cover those cases. The explicitly deferred SQL UDF contract gap remains recorded above.

@clickhouse-gh clickhouse-gh Bot added the pr-build Pull request with build/testing/packaging improvement label Sep 23, 2026
Comment thread src/Interpreters/executeQuery.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. label Sep 23, 2026
alexey-milovidov and others added 2 commits September 26, 2026 16:29
…ore-query-execution

# Conflicts:
#	src/Core/SettingsChangesHistory.cpp
…family

`collectTablesInQuery` special-cased only `IN`, so a query like
`SELECT count() FROM src WHERE joinGet(no_access_join, 'v', id) = 1` recorded only `src`: the hook
could `DETACH`/`ATTACH` `src` and only then fail on the `SELECT` check of `FunctionJoinGet::prepare`
(and likewise on the `dictGet` check of `FunctionDictHelper::getDictionary`).

Now the first argument of `joinGet`/`joinGetOrNull` (identifier or constant string) is collected as a
reattach candidate requiring `SELECT`, and the dictionaries named by the `dictGet` family are folded
into the access preflight (requiring `dictGet` on every database an unqualified name can resolve to).
A first argument whose value is not known from the AST (bound to an alias, or an expression) skips
the hook for the whole query.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 95871fd1e with master 6b959f5a7 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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 ⚠️

57 object files changed (+359.77 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Interpreters/executeQuery.cpp.o 1.07 MiB 1.40 MiB +335.57 KiB (+30.62%)

719 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

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

Translation unit Master PR Δ vs median
src/Interpreters/executeQuery.cpp 12.8 s 19.6 s +6.7 s (+51%)

Job report

…ore-query-execution

Resolve the conflict with the move of the settings changes history into the setting declarations
(ee6b44f): the history records this PR added to `SettingsChangesHistory.cpp` now live as
trailing arguments of the `DECLARE` of each setting.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov self-assigned this Sep 27, 2026
alexey-milovidov and others added 5 commits October 3, 2026 13:51
… and slow runners

`05103_reattach_tables_internal_settings` now only counts the `query_log` entries of
the current run, and `05102_reattach_tables_mutations` fails explicitly when the
concurrent `INSERT` never shows up in `system.processes` instead of testing an idle table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The new `storage_casts` style check rejects a direct `dynamic_cast` to a deferrable
engine: a lazily loaded table is reached through `StorageTableProxy`, so the cast
would fail and silently skip the guarded logic. All four casts concern tables the
query names, so use `DeferredTable::Load`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=805beacbab625ea8affb3ba3be6844cb1b8c7546&name_0=PR&name_1=Style%20check
#121674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Interpreters/executeQuery.cpp
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 3 commits October 8, 2026 02:20
The hook skips a table whose exclusive lock it cannot take within its 100 ms
busy probe, and on a loaded runner a background task of the freshly created
table can hold the lock that long, so the control check reported `FAIL` in
the flaky check. The query is read-only, so retry it a few times.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20flaky%20check)
#121674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nction

A table function checks its access only when it is executed, after the hook:
the source grant, `CREATE TEMPORARY TABLE`, and its own checks over the
objects it names (`dictionary('d')` checks the dictionary grant in
`StorageDictionary::read`). So `SELECT ... FROM local JOIN dictionary('d')`
could `DETACH`/`ATTACH` `local` before failing with `ACCESS_DENIED`. Mark
such queries as unverifiable, like an unresolvable `joinGet` argument.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=latest&name_0=PR&name_1=Integration%20tests%20(arm_binary%2C%20distributed%20plan%2C%20targeted) (test_backup_restore_on_cluster/test.py::test_shutdown_waits_for_backup, BACKUP_CANCELLED instead of BACKUP_CREATED) and provide a fix in a separate PR. If the fix is already in progress, link it here. It seems to be addressed by #124334.

The 05104_reattach_tables_dynamic_disk flaky-check failure was this PR's own: the busy-lock probe, which has a 100 ms timeout, missed the control table on a loaded runner. The read-only control query is now retried (0a1ec3b).

@groeneai

groeneai commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Yes, this is the failure #124334 fixes (my PR, open, CI green on its head, review requested). It is a pre-existing race, not caused by this PR.

node2's log for this run shows the same mechanism as the earlier occurrences: the DDL worker started the internal BACKUP TABLE tbl TO Disk('backups', '32') leg (ddl_entry=query-0000000300) 11 ms before SIGTERM. Graceful shutdown waits only for backups already registered in BackupsWorker, then killAllQueries() cancelled this leg (Failed to make internal backup Disk('backups', '32'): Code: 394 ... Query was cancelled on node2), so node1's ON CLUSTER backup ended BACKUP_CANCELLED. #124334 makes that killAllQueries() skip the BACKUP/RESTORE parts run by the DDL worker when shutdown_wait_backups_and_restores is on.

if (need_reattach_tables)
{
LOG_DEBUG(getLogger("executeQuery"), "Will DETACH and ATTACH back tables used in query");
reattachTablesUsedInQuery(out_ast, context);

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 hook still runs before both the query-result-cache fast path and the generic quota accounting later in executeQueryImpl. The internal DETACH/ATTACH round-trip is implemented as ordinary executeQuery(...) calls, so a session with exactly one QUERIES slot left can spend it on the inner DETACH, then fail both the inner ATTACH and the recovery ATTACH with QUOTA_EXCEEDED, leaving the table detached. A pure query-cache hit also ends up mutating tables it never executes against.

I think this needs to move after the result-cache / quota gates, or the internal reattach queries need to bypass those paths entirely.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Fixed in f038805: the internal DETACH/ATTACH pair now runs with a new QueryFlags::ignore_quota, so it is not charged to the user's quota, and the hook is skipped for a SELECT with use_query_cache, which may be served from the query result cache. I kept the hook where it is rather than moving it past the cache probe: by then insert_table and the input() storage already hold references to the target table. Covered by 05339_reattach_tables_quota_query_cache (a user with MAX queries = 1).

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.

The QueryFlags::ignore_quota part is not fully fixed yet. Both executeQuery exception paths still call logExceptionBeforeStart (src/Interpreters/executeQuery.cpp:5005 and src/Interpreters/executeQuery.cpp:5833), and that helper unconditionally does context->getQuota()->usedForQuery(..., QuotaType::ERRORS, 1, ...) at src/Interpreters/executeQuery.cpp:1110.

So if the internal DETACH/ATTACH pair fails anywhere on this path, it still burns the caller's ERRORS quota even though the query was launched with QueryFlags{..., .ignore_quota = true}. The fix needs to thread the flag into logExceptionBeforeStart (or guard those call sites) too.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Fixed in 6876a3e: logExceptionBeforeStart now takes an ignore_quota argument, and both call sites in executeQueryImpl pass flags.ignore_quota, so a failure of the internal DETACH/ATTACH no longer adds to the caller's ERRORS quota. The in-execution exception path was already safe: there the quota is only charged when my_quota was set, and it is never set under ignore_quota.

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.

The cache part of the fix is still incomplete at src/Interpreters/executeQuery.cpp:5374: this gate checks only the outer query's use_query_cache. A subquery can explicitly opt in while the outer query has it disabled:

SELECT * FROM
    (SELECT * FROM t SETTINGS use_query_cache = 1)
SETTINGS use_query_cache = 0, reattach_tables_before_query_execution = 1;

After warming that subquery entry with the same settings, the hook still reattaches t on the next execution. shouldUseQueryCacheForSubquery in src/Planner/Planner.cpp:2618 accepts explicit subquery opt-in independently of the outer flag, and the cache-hit branch returns before building the storage-reading plan. Please account for nested cache settings as well, with a warmed-subquery regression test asserting no reattach on a hit.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Fixed in fab9561: the gate now also skips the hook when any SETTINGS clause in the query, including a subquery's, sets use_query_cache (astMentionsUseQueryCache). Covered in 05406_reattach_tables_preflight_followups with the subquery opt-in shape from your example.

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.

The quota exemption is still incomplete at src/Interpreters/executeQuery.cpp:4175 and :4324: a scalar subquery evaluated from stored constraints installs the user's quota independently of QueryFlags::ignore_quota (InterpreterSelectQueryAnalyzer.cpp:563–564).

A concrete case is a populated, otherwise eligible MergeTree table t with:

ALTER TABLE t ADD CONSTRAINT c ASSUME
    x >= (SELECT sum(number) FROM numbers(1));

For an authorized user with MAX read_rows = 1, a normal SELECT x FROM t can read its one row. With reattachment enabled, the constraint preflight at line 4175 consumes one row instead; DETACH succeeds, then short ATTACH reevaluates the scalar subquery and exceeds the quota. Recovery reevaluates it too, so both attachments fail with QUOTA_EXCEEDED and leave t detached. The copied scalar cache does not prevent the second scan: metadata parsing leaves UNION_DEFAULT, short ATTACH normalizes it to UNION_ALL at InterpreterCreateQuery.cpp:2236, and that mode participates in the scalar-cache hash.

There is also a profile-event quota path after the master merge: both internal statements increment ProfileEvents::Query in the inherited outer thread group, and the outer usedQuotaProfileEvents charges those counters without excluding the hook. Thus the flag does not exempt that work from MAX Query quotas either.

Please propagate the exemption through the validation/attachment scalar work and exclude the hook's counters from outer quota accounting, or skip the hook when its work cannot be exempted. Add a stored-constraint read-quota regression that verifies the table remains attached, plus a profile-event quota case. These are source traces; I have not executed them locally.

Comment thread src/Databases/DatabaseOverlay.h Resolved
…sult cache

The internal `DETACH`/`ATTACH` pair ran through `executeQuery` and was charged to the user's quota, so a
session with one `QUERIES` slot left spent it on the `DETACH` and then failed the `ATTACH` and the recovery
`ATTACH` with `QUOTA_EXCEEDED`, leaving the table detached. Add `QueryFlags::ignore_quota` and set it for
the internal pair.

A `SELECT` with `use_query_cache` may be served from the query result cache without touching its tables,
so the hook is skipped for it.

`DatabaseOverlayReadOnly` now also returns `false` from `supportsDetachingTables`: its tables are
`StorageAlias` objects resolved through the source databases, so there is nothing to reattach.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 4 commits October 9, 2026 10:33
…r tables of the query

The skip checks of the mutation, `CREATE ... AS SELECT` and alias-bound `joinGet` cases only looked
at the source table, so a regression reattaching the target, the pre-existing destination or the
`Join` table would still pass. Check those tables too.

#121674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… by the busy probe

The hook skips a table whose exclusive lock it cannot take within its 100 ms busy probe, and on a
loaded runner a background task of the fresh table can hold the lock that long, so the quota check
reported `FAIL (not detached ...)` in the flaky check. Retry the control check and the quota check,
re-creating the quota for every attempt so that each one starts with exactly one query left.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=f0388054d1c0a6591a8e85fa1fb0336bba1aefca&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29
#121674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… `ignore_quota`

`logExceptionBeforeStart` unconditionally added an error to the caller's quota,
so a failure of the internal `DETACH`/`ATTACH` of
`reattach_tables_before_query_execution` (run with `QueryFlags::ignore_quota`)
still consumed the user's `ERRORS` quota. Pass the flag through and skip the
accounting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 2 commits October 25, 2026 15:52
…ts, `joinGet` in refreshable views

- A query with a `WITH` definition that is never referenced and names any object skips the hook: the
  analyzer never analyzes such a definition, so collecting it would reattach a table the query does
  not use.
- A read of a storage that reads other tables (`Buffer`, `Merge`, `Distributed`, `Alias`, ...) skips the
  hook, because the access to those tables is checked only in `read`. So does a read of a lazily loaded
  table that is not loaded yet.
- The stored constraints are analyzed with `InterpreterCreateQuery::getConstraintsDescription` under the
  settings of the internal `ATTACH` before detaching, like the columns, indices and keys.
- An unqualified `joinGet` in the `SELECT` of a refreshable materialized view is resolved in the view's
  database, which is the current one while that `SELECT` is analyzed. The mutation carriers keep the
  session's database for `joinGet`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
…self-referencing constraints

- A `WITH` definition counts as used only if it is reachable from the rest of
  the `SELECT`, directly or through other used definitions. A reference from an
  unused sibling no longer makes it used, so
  `WITH a AS (SELECT x FROM t), unused AS (SELECT x FROM a) SELECT 1` skips the hook.
- A query that sets `profile` in any `SETTINGS` clause skips the hook: a nested
  profile may carry `additional_table_filters`, `use_query_cache` and other
  settings that the literal setting-name checks do not see.
- A table is not reattached if one of its constraints may name the table itself:
  the scalar subquery is analyzable while the table is attached, but the
  `ATTACH` back fails with `UNKNOWN_TABLE`, leaving the table detached.

Add `05449_reattach_tables_review_followups_4` covering all three, with controls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=660cb5a2eea7efc974c72871133b9d62da7cff2c&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 (Logical error: Column or subcolumn 'vec.quantized' not found in Buffer table) and provide a fix in a separate PR. It looks like #118714, which #127793 is already fixing. It is not related to this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

This is #118714: the fuzzer's copy of the table from 02354_vector_search_quantize_codec_subcolumn_read_bytes (a Quantized('product', ...) column) is a Buffer, and the codes of rows still held in the buffer cannot be computed in memory, so BufferSource::generate threw the logical error. My PR #127793 fixes it: such a read now throws NOT_IMPLEMENTED until the buffer is flushed. Its test runs the same query and passes in CI.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed db218c1: merged master (no conflicts). This brings in the fix for 05218_text_index_substreams_opened_lazily with use_columns_cache (abf2e19, 4649977), which was the only failing test in Stateless tests (arm_binary, sequential). The Build profile diff failure was a CI infrastructure error (LogClusterNotReady: the endpoint never became ready). @groeneai, thanks for confirming that the Buffer AST fuzzer failure is #118714, which #127793 fixes.

…gacy `MergeTree` keys

Address review: a stored column expression such as `f String ALIAS file('anything', '')`
is expanded only during the analysis of the query, after the reattach hook, so the
privileges checked by functions from `functionChecksOwnAccess` cannot be preflighted.
Skip such tables.

A `MergeTree` table with the legacy syntax keeps its sorting and sampling keys in the
engine arguments, which the stored-key validation did not cover; the internal `ATTACH`
could reject them under the server default settings and leave the table detached.
Skip legacy definitions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=db218c1373d13e87c5cbbf0099edcb61f81f7779&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29 (ThreadSanitizer: data race in DB::ClientBase::onProgress) and provide a fix in a separate PR. If the fix is already in progress, link it here. It looks like #128019 covers it. The Build profile diff failure is a CI infrastructure error (LogClusterNotReady).

@groeneai

Copy link
Copy Markdown
Collaborator

Yes, #128019 covers it: the stack on db218c1 is the same race. ClientBase::onProgress (ClientBase.cpp:2179) is entered through the LocalConnection::sendQuery cancel callback (LocalConnection.cpp:337) from a pipeline thread (materialized view query, evaluateScalarSubqueryIfNeeded -> PullingAsyncPipelineExecutor::pull) and from the embedded client thread (CompletedPipelineExecutor::execute poll) at the same time. Not caused by this PR.

#128019 has not run CI yet: it is waiting for the can be tested label.

Comment thread src/Interpreters/executeQuery.cpp Resolved
…ery before any reattachment

- A collected table whose stored column list calls a function that checks privileges of its own
  (`functionChecksOwnAccess`) now skips the hook for the whole query instead of only that table, so
  `SELECT p.x, a.f FROM t_plain AS p CROSS JOIN t_alias AS a` no longer reattaches `t_plain` before
  failing with `ACCESS_DENIED`.
- A read of a materialized view (`isView` on the resolved storage) skips the hook, because
  `StorageMaterializedView::readImpl` checks the access to its target under the definer.
- An insert into a storage that writes to other tables (`Buffer`, `Distributed`, ...) or into a table
  with dependent views skips the hook, because `BufferSink::consume` and the views pushed to check the
  access only during the insert.

New test: `05454_reattach_tables_review_followups_5`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 926ee16 to address the three review threads: stored expressions that check their own access, reads of materialized views, and inserts into delegating storages or tables with dependent views now skip the hook for the whole query, before any table is detached. New test: 05454_reattach_tables_review_followups_5. The only red job on the previous head was Build profile diff, a CI infrastructure error (LogClusterNotReady: the endpoint never became ready). The SQL UDF item in the AI review stays deferred, as discussed before.

Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 2 commits October 30, 2026 09:02
…ons and `Dictionary` tables

`collectTablesInQuery` collects the objects named by `joinGet` and the `dictGet` family only from the
submitted query, so a stored column expression calling them hid a `Join` table or a dictionary the
caller may not access. Treat these functions (and `predictXGBoost`, `assignCentroid`) like the other
functions that check access on their own when they appear in a stored column expression.

A `Dictionary` table checks the access to its underlying dictionary only in `StorageDictionary::read`,
so a read of it now skips the hook for the whole query, like views and storages reading other tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +4034 to +4035
internal_context->setSettings(context->getGlobalContext()->getSettingsRef());
internal_context->setProcessListElement(context->getProcessListElementSafe());

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.

[P1] Keep restoration independent of the outer query's memory limit

Resetting the settings here does not reset the active memory tracker. The outer ProcessList::insert has already installed max_memory_usage on the thread group, and .inherit_process_list_element = true skips that initialization for both internal statements. A persistent Set rebuilds its hash table during StorageSetOrJoinBase::restore, without a memory-tracking blocker.

For example, create and populate this table without the small limit, then run:

CREATE TABLE s (k UInt64) ENGINE = Set;
INSERT INTO s SELECT number FROM numbers(1000000);
SELECT 1 IN s
SETTINGS max_memory_usage = 10000000,
         max_untracked_memory = 1,
         reattach_tables_before_query_execution = 1;

Reading the existing set needs little memory, but restoring its million-key hash exceeds the outer limit. DETACH can finish, then both the ordinary and recovery ATTACH fail under the same tracker, leaving s detached. Please isolate restoration from the caller's query-level memory budget, or skip such candidates before detaching, and add a regression asserting that the table remains available after this low-memory query. This is a source trace; I have not executed the reproduction locally.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

🕵 Fixed in 9db9c18: the hook is skipped for a query whose max_memory_usage is lower than the server default (or set while the default is unlimited), since the internal ATTACH runs under the outer query's memory tracker. Covered in 05459_reattach_tables_review_followups_7 with a persistent Set of 1M keys queried under a 10 MB limit; the set stays attached and readable.

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.

The memory fix is still incomplete at src/Interpreters/executeQuery.cpp:3629: equality with a finite server default passes the guard, but the stored table can be larger than that per-query default.

For example, with the server default max_memory_usage = 10000000, populate the same million-key persistent Set using INSERT ... SETTINGS max_memory_usage = 100000000, then run:

SELECT 1 IN s
SETTINGS max_untracked_memory = 1,
         reattach_tables_before_query_execution = 1;

This inherits the 10 MB default, so the guard permits the cycle. StorageSetOrJoinBase::restore still rebuilds the whole hash table under that outer tracker; both the ATTACH at line 4324 and recovery at line 4353 can fail with MEMORY_LIMIT_EXCEEDED, leaving s detached. Freeing the original set does not supply negative query-memory credit: MemoryTracker::decrementLocalUsage clamps process-level usage to zero.

Please isolate restoration from the caller's query memory budget, or skip these candidates whenever a finite effective limit can prevent restoration. The regression needs a finite default and a set larger than it, in addition to the existing lowered-query-limit case. This is a source trace; I have not executed it locally.

Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
alexey-milovidov and others added 3 commits October 31, 2026 04:17
…` leaving tables detached or acting before an access check

- Skip the hook for a query lowering `max_memory_usage` below the default: the internal `ATTACH` runs
  under the outer query's memory tracker, and restoring e.g. a persistent `Set` can exceed it, failing
  both the `ATTACH` back and the recovery `ATTACH`.
- Skip a table whose projections may name the table itself (a scalar subquery), as already done for
  constraints: the `ATTACH` back re-analyzes them while the table is detached.
- Treat `IN` over a table and subqueries in stored column expressions like the functions that check
  their own access, so a hidden `Set` table the caller cannot read disables the hook.
- Require the privileges that system tables check on their own (`SYSTEM_JEMALLOC`, `SHOW_USERS`, ...)
  for any collected system table except the data generators.
- Skip the hook for a query using a `QueryRunner` table, which checks `READ`/`WRITE` on `REMOTE` only in
  its sink.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	src/Interpreters/QueryFlags.h
#	src/Interpreters/executeQuery.cpp
… with a subquery in a constraint

The previous commit made `astCallsFunctionCheckingOwnAccess` count any subquery or `IN` over a table in
the stored columns definition, which includes the constraints. A read never analyzes a `CHECK`
constraint, and the constraint subqueries are already executed under the caller's access when the hook
validates the definition for the `ATTACH` back, so this disabled the hook for every read of such a
table. Apply the subquery rule to the constraints only when the query writes to the table.

This fixes `05448_reattach_tables_review_followups_3` (setting-dependent constraint) in Fast test:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121674&sha=9db9c18f06f386c59d69b816919c870d8611972e&name_0=PR&name_1=Fast%20test
PR: #121674

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 6924f17 (after merging master; the conflicts in QueryFlags.h and executeQuery.cpp were additive, and both sides are kept). It fixes the Fast test failure of 05448_reattach_tables_review_followups_3: the previous commit counted any subquery in the stored columns definition, including the constraints, as an access-checking expression, which disabled the hook for every read of a table with a subquery in a constraint. A subquery in a constraint now disables the hook only for a write to the table: a read never analyzes CHECK constraints, and the hook already runs their scalar subqueries under the caller's access when it validates the definition. Only the object file was compiled locally; the build machine was too overloaded to link and run the test.

Comment thread src/Interpreters/executeQuery.cpp Resolved
Resolve conflicts in `executeQuery`: master replaced the `ignore_quota` argument of
`logExceptionBeforeStart` with `charge_quota` and introduced `quota_ignored`. The PR's
`QueryFlags::ignore_quota` now initializes `quota_ignored` (and is kept when the result
is served from the query result cache), and is passed as `charge_quota = !flags.ignore_quota`.
Also follow the move of `ASTHypotheticalObjectQuery.h` to `Parsers/WhatIf/`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pushed 95871fd: merged master and resolved the conflicts in executeQuery. Master replaced the ignore_quota argument of logExceptionBeforeStart with charge_quota and added a quota_ignored variable. The PR's QueryFlags::ignore_quota now initializes quota_ignored, stays set when the result comes from the query result cache, and is passed as charge_quota = !flags.ignore_quota. I also updated the include for ASTHypotheticalObjectQuery.h, which moved to Parsers/WhatIf/. The build passes locally, and 05339_reattach_tables_quota_query_cache, 05100_reattach_tables_create and 05406_reattach_tables_preflight_followups pass.

/// `SELECT` is left out: the destination above is touched by a rejected insert too, and none of
/// the statement's other children (the column list, the `PARTITION BY`, the settings, the
/// `FROM INFILE` path) names a table.
if (insert->select && insertQueryStopsBeforeSources(*insert, data.context))

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.

[P2] Skip table-function insert destinations before collecting their arguments

The ASTInsertQuery branch only suppresses insert->select; it still walks insert->table_function, and a VALUES insert does not call insertQueryStopsBeforeSources at all. This leaves a table-function access check outside the whole-query preflight.

For example, create a persistent Join table j(k UInt64, v String) containing (1, 'http://127.0.0.1:1/out.csv'). Give a user SELECT, DROP TABLE, and CREATE TABLE on j, plus the applicable engine grants, but no WRITE ON URL. Then:

INSERT INTO FUNCTION url(joinGet('db.j', 'v', toUInt64(1)), 'CSV', 'x UInt64')
SETTINGS reattach_tables_before_query_execution = 1, async_insert = 0
VALUES (1);

collects and reattaches j, then fails with ACCESS_DENIED in ITableFunction::checkSourceAccess. The constant joinGet argument is evaluated during argument parsing; the explicit format and structure avoid schema inference, and the source-access check runs before any HTTP request. This violates the documented guarantee that access-rejected queries produce no reattachment side effects. The INSERT ... SELECT variant also traverses these destination arguments after suppressing its source.

Please mark an insert->table_function destination unverifiable for the whole hook before descending into its children, as already done for FROM/JOIN table functions, and add denied-user coverage for both insert forms. This is a source trace; I have not executed the reproduction locally.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

I doubt this. Can we achieve the same effect much simpler? - Do not try to find out which tables the query is using. Instead, randomly detach and attach tables in the current database, with some probability, before every query.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Superseded by a much simpler version: #129939 - it reattaches random tables of the current database before every query, instead of finding out which tables the query uses.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-query-execution Runtime execution pipeline, processors, vectorized operators, resource management during execution. pr-build Pull request with build/testing/packaging improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants