Skip to content

Randomize tests with DETACH/ATTACH table before query execution - #96130

Open
alexey-milovidov wants to merge 502 commits into
masterfrom
random-reattach-tables-v2
Open

alexey-milovidov wants to merge 502 commits into
masterfrom
random-reattach-tables-v2

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Feb 5, 2026 •

Copy link
Copy Markdown
Member

Add reattach_tables_before_query_execution and reattach_tables_before_query_execution_probability settings that enable randomly detaching and reattaching tables used in a query before its execution.

This is a testing-only feature designed to find bugs related to table reattachment. Before executing a query, the system collects all tables referenced in the AST, and for each eligible table (stores data on disk, supports detaching, has no action locks or dependencies, and is not in use by another query), it performs a DETACH followed by ATTACH.

Changes:

  • Add supportsDetachingTables virtual method to IDatabase (overridden to false for engines that do not support non-permanent DETACH TABLE: DatabaseDictionary, DatabaseReplicated, DatabaseSQLite, DatabaseBackup, DatabaseFilesystem, DatabaseHDFS, DatabaseS3, DatabaseURL, DatabaseRemote, DatabaseDataLake, DatabaseMaterializedPostgreSQL)
  • Add has/hasAny methods to ActionLocksManager for checking existing locks (skipping expired weak_ptr entries)
  • Add table collection visitor and reattach logic in executeQuery (runs after AST validations, process list admission, and external tables initialization; skips EXPLAIN, transactions, internal/non-initial queries, and CTE name collisions)
  • Skip a table another query is using: the internal DETACH TABLE ... SYNC waits for the detached storage to stop being referenced, so reattaching a table held by a concurrent long-running query would block the current query until that one finishes
  • Keep a rejected query side-effect free: a statement whose interpreter stops on its own target before it reaches the tables it reads must not reattach those tables, so the collector mirrors each interpreter's fast-fail order (mainTableTouchedIfExists, createQueryStopsBeforeSources, mutationQueryStopsBeforeSources for DELETE/UPDATE/ALTER, insertQueryStopsBeforeSources), including the IN PARTITION clause a mutation carries, which every carrier resolves against its target before the commands' own predicates and expressions, and the hook preflights the access the query is going to check
  • Skip a table the internal ATTACH back could not restore: the user must hold the full DETACH/ATTACH authorization for the object's kind (including the TABLE ENGINE grant), and the table's database must not already be over its own max_tables limit
  • Skip a table whose definition builds its own disk with the disk function: a plain ATTACH TABLE is a user-initiated attach, and only a load from existing metadata is exempt from the security checks over a dynamic disk definition (dynamic_disk_allow_from_env, dynamic_disk_allow_include, dynamic_disk_allow_from_zk, and the restriction on a dynamic S3 disk resolving the server's own credentials), so the ATTACH back would be rejected with ACCESS_DENIED and leave the table detached
  • Run the internal DETACH/ATTACH pair with the server's default settings instead of the outer query's. Copying the query context copied its settings too, so a setting that only describes how that statement reads its data could make the ATTACH back fail - and then the recovery ATTACH inherited it and failed the same way, leaving the table detached
  • Skip what the query does not safely read: a Set/Join table with persistent = 0 (its rows live only in memory and ATTACH restores only the backup files), the right-hand side of IN (it may be bound to a column or a lambda argument, qualified or not), and the tables of CTE definitions the query never references; skip the whole hook for a query that references a view (the tables of its body escape the existence and access preflights) or a mutation rejected by checkNoRowPolicyForSetOperands
  • Name the Keeper component the hook uses (Coordination::setCurrentComponent). The hook runs under no interpreter, so with enforce_keeper_component_tracking on, the first Keeper request its preflight makes on a database whose metadata lives in Keeper was an unnamed request, which is a LOGICAL_ERROR
  • Run the recovery ATTACH (after a failed DETACH/ATTACH pair) outside the outer query's process list and with database_atomic_wait_for_drop_and_detach_synchronously, so a query cancelled while the DETACH waited for a concurrent reader does not leave the table detached
  • Fix off-by-one in MergeTreeDeduplicationLog::dropOutdatedLogs (don't drop the active log), open the appending writer lazily so shutting a table down without writing a record does not leave a phantom blob in the log file's metadata on object storage, and sync the writer in shutdown
  • Fix the startup/shutdown races the randomization exposes in StorageMergeTree, StorageReplicatedMergeTree and ReplicatedMergeTreeAttachThread: a DETACH racing an in-flight async startup could leave background workers armed on a logically shut-down table, hang waitFirstTry forever, or tear the interserver parts exchange endpoint down under a concurrent full shutdown
  • Add no-random-detach tag to tests incompatible with this feature
  • Add --no-random-detach and --reattach-tables-probability options to clickhouse-test
  • Add the 02461_reattach_tables suite, split across 02461_reattach_tables, 05099_reattach_tables_access, 05100_reattach_tables_create, 05101_reattach_tables_engines, 05102_reattach_tables_mutations, 05103_reattach_tables_internal_settings and 05104_reattach_tables_dynamic_disk so that no part approaches the per-test timeout - a check costs one clickhouse-client invocation, and a sanitizer-built client starts in seconds - with the shared helpers in 02461_reattach_tables.lib

Continuation of #55943. Continuation of #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 randomly DETACH and ATTACH 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)

Note

Medium Risk
Introduces new pre-execution mutations (internal DETACH/ATTACH) in executeQuery, which can affect table availability and concurrency behavior if enabled; guarded by new experimental settings but touches core query execution paths.

Overview
Adds experimental settings reattach_tables_before_query_execution and ..._probability to optionally DETACH and ATTACH back eligible tables referenced by a query immediately before execution, including AST table discovery that accounts for CTE scoping, privilege checks, dependency/lock checks, and safety skips (e.g. system, non-disk storages, dynamic-structure columns, transactions, EXPLAIN, internal/non-initial queries).

Extends IDatabase with supportsDetachingTables() and marks multiple database engines as not supporting non-permanent detach; adds ActionLocksManager::has/hasAny helpers to avoid detaching tables with active action locks. Updates the test runner and stress tooling to randomize this behavior (with --no-random-detach and probability control), adds a new 02461_reattach_tables test, and tags many existing tests to opt out where DETACH/ATTACH would add flakiness/overhead. Also fixes MergeTreeDeduplicationLog cleanup to avoid dropping the active log and ensures writer sync() on shutdown.

Reviewed by Cursor Bugbot for commit a369371. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@clickhouse-gh

clickhouse-gh Bot commented Feb 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e516363]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
05617_autopr_undecided_retry FAIL cidb
04249_query_condition_cache_fine_grained_granules FAIL cidb
Integration tests (amd_msan, targeted) FAIL
test_storage_rabbitmq/test.py::test_rabbitmq_handle_error_mode_stream FAIL cidb
Stateless tests (amd_debug, flaky check) FAIL
05839_system_start_view_through_alias FAIL cidb
Stateless tests (amd_debug, sequential) FAIL
05816_query_condition_cache_ast_limits FAIL cidb
05099_query_condition_cache_formatdatetime_settings FAIL cidb
04242_query_condition_cache_topk_collate FAIL cidb
03229_query_condition_cache_profile_events FAIL cidb
02354_vector_search_drop_cache_for_table_on_cluster FAIL cidb
02354_vector_search_drop_cache_for_table FAIL cidb
Stateless tests (amd_debug, distributed plan, s3 storage, sequential) FAIL
05367_reader_executor_temporary_cache FAIL cidb
02354_vector_search_drop_cache_for_table_on_cluster FAIL cidb
Stateless tests (arm_binary, parallel) FAIL
05617_autopr_undecided_retry FAIL cidb
Stateless tests (arm_binary, sequential, 1/2) FAIL
02354_vector_search_drop_cache_for_table FAIL cidb
Stateless tests (arm_binary, sequential, 2/2) FAIL
05816_query_condition_cache_ast_limits FAIL cidb
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) FAIL
05839_system_start_view_through_alias FAIL cidb
Stateless tests (amd_debug, ParallelReplicas, s3 storage, parallel) FAIL
05141_settings_constraints_nested_settings_effective FAIL cidb
01283_max_threads_simple_query_optimization NOT_FAILED cidb
01414_push_predicate_when_contains_with_clause NOT_FAILED cidb
00542_access_to_temporary_table_in_readonly_mode NOT_FAILED cidb

AI Review

Summary

The PR adds experimental pre-query table reattachment, eligibility and authorization preflights, action-lock tracking, and test-runner randomization. One blocker remains: aggregate names carried as strings bypass the stored-definition authorization guard, allowing the hook to detach a table that the querying user cannot attach back. Replied once to the explicit fix claim and reopened the existing review thread.

Findings

❌ Blockers

  • src/Interpreters/executeQuery.cpp:3889: containsFlameGraphAggregateFunction checks only ASTFunction and ASTIdentifier. It misses aggregate construction from string literals. For example, an administrator with allow_introspection_functions = 1 can create:

    CREATE TABLE t
    (
        trace Array(UInt64),
        INDEX i length(arrayReduce('flameGraph', [trace]))
            TYPE minmax GRANULARITY 1
    )
    ENGINE = MergeTree ORDER BY tuple();

    Give another user SELECT, CREATE TABLE, DROP TABLE, and TABLE ENGINE ON MergeTree, without INTROSPECTION. Their ordinary row count succeeds, but SELECT count() FROM t SETTINGS reattach_tables_before_query_execution = 1, use_skip_indexes = 0 can detach the table permanently: both ATTACH attempts rebuild the index through IndexDescription::initExpressionInfo, and arrayReduce constructs flameGraph, which rejects the missing grant. The stored metadata retains the string literal, so the new guard never runs its privilege check. Type strings in CAST, and aggregate-name strings in arrayReduceInRanges and initializeAggregation, share this representation gap. Validate construction using the attach context before detaching, or conservatively exclude these carriers. The query-level guard shares the helper and needs the same coverage.

Tests
  • ⚠️ Extend the restricted-user regression with the stored arrayReduce index above; verify that the denied user leaves the table attached and queryable, and retain a granted positive control. Cover string-carrier calls in the query-level guard as well. This finding is source-traced; no local server is available. The fetched CI reports show 15,398 passed, 0 failed, and 4,578 skipped, but the existing regression covers direct aggregate syntax only.
Final Verdict

Status: ❌ Block

Close the string-carrier authorization gap before DETACH and add the focused regression coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Feb 5, 2026
Comment thread src/Core/Settings.cpp Resolved
alexey-milovidov added a commit that referenced this pull request Feb 8, 2026
Tests that fail with the random DETACH/ATTACH feature:
- `01781_merge_tree_deduplication`: dedup log state changes with random detach/attach cycles
- `03595_pread_threadpool_direct_io`: `PrewarmCaches` entries appear in output after reattach
- `02504_regexp_dictionary_ua_parser`: `INVALID_USAGE_OF_INPUT` exception with `input()` table function
- `02265_column_ttl`: TTL operations interfered by random detach
- `01671_ddl_hang_timeout_long`: DDL timeouts with added detach overhead

#96130

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@alexey-milovidov
alexey-milovidov force-pushed the random-reattach-tables-v2 branch from b5650bf to 64e6436 Compare February 17, 2026 23:00
alexey-milovidov added a commit that referenced this pull request Feb 21, 2026
The 5-minute margin introduced in #97214 is not enough for the cleanup
phase, which includes server shutdown, system table export via
`clickhouse local`, and log collection — all significantly slower under
sanitizers (ASan, TSan, etc.).

For example, in #96130,
the `amd_asan` flaky check hit the hard timeout during
`aggregated_zookeeper_log` export, killing the process before results
could be uploaded (0 test results in the report). The ClickHouse server
shutdown alone took ~80 seconds, and each system table export took
~50 seconds under ASan.

Changelog category: CI Fix or Improvement
Changelog entry: Increase soft timeout margin for flaky check to prevent job timeouts with empty results.

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

Copy link
Copy Markdown
Member Author

It looks like all tests have passed!

@Algunenano Algunenano self-assigned this Feb 23, 2026

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

The failures:

  • 00326_long_function_multi_if is using tables and many queries. We could disable or change the queries to reduce them.
  • 00090_union_race_conditions_1 times out. Also disable?
  • 02015_async_inserts_4 is broken already when running it in parallel/multiple times. The user and roles should be random (which is trivial, just include the database name in the script).

Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved
@ClickHouse ClickHouse deleted a comment from CLAassistant Feb 28, 2026
@alexey-milovidov
alexey-milovidov force-pushed the random-reattach-tables-v2 branch from f3af9c0 to 7d4766e Compare February 28, 2026 17:15
@ClickHouse ClickHouse deleted a comment from CLAassistant Mar 1, 2026
@alexey-milovidov
alexey-milovidov force-pushed the random-reattach-tables-v2 branch from 9df2db6 to 047958c Compare March 1, 2026 20:47
@clickhouse-gh clickhouse-gh Bot added the submodule changed At least one submodule changed in this PR. label Mar 1, 2026
Comment thread src/Interpreters/ActionLocksManager.cpp Resolved
Comment thread src/Interpreters/executeQuery.cpp Resolved

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread tests/clickhouse-test Resolved
alexey-milovidov added a commit that referenced this pull request Mar 13, 2026
The test uses transactions with mutations and part-level operations.
Random DETACH/ATTACH during these operations causes warnings about
parts with transaction metadata being skipped, which appear on stderr
and fail the test.

The sibling tests `01168_mutations_isolation_2` and
`01168_mutations_isolation_3` already have this tag in PR #96130
but this one was missed.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=81b056185e2a9cfca43182bf2e1985b1d22deaef&name_0=PR&name_1=Stateless%20tests%20%28amd_asan%2C%20distributed%20plan%2C%20parallel%2C%202%2F2%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Mar 13, 2026
The test uses transactions with mutations and part-level operations.
Random DETACH/ATTACH during these operations causes warnings about
parts with transaction metadata being skipped, which appear on stderr
and fail the test.

The sibling tests `01168_mutations_isolation_2` and
`01168_mutations_isolation_3` already have this tag in PR #96130
but this one was missed.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96130&sha=81b056185e2a9cfca43182bf2e1985b1d22deaef&name_0=PR&name_1=Stateless%20tests%20%28amd_asan%2C%20distributed%20plan%2C%20parallel%2C%202%2F2%29

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
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 2 commits November 9, 2026 07:09
# Conflicts:
#	src/Interpreters/executeQuery.cpp
#	tests/queries/0_stateless/05183_prewhere_statistics_pruned_parts.sql
#	tests/queries/0_stateless/05210_prewhere_statistics_planning_paths.sql
…_conversion`

The test was added on `master` and checks with `EXPLAIN` that a part
written with the old enum type is pruned by statistics. After a
`DETACH`/`ATTACH` of the table, that part is no longer pruned, so the
check fails when the randomization reattaches the table.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=latest&name_0=PR&name_1=Fast%20test

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

Copy link
Copy Markdown
Member Author

🕵 /continue-pr-auto pass on 2026-11-10: pushed 125b9c3115d → fba4056d3f5.

  • Fast test failure: 05448_statistics_representation_preserving_conversion (added on master in Do not prune a part by statistics while an alter mutation is pending #119337) failed when the randomization reattached its table. I reproduced it with a plain DETACH TABLE ... SYNC / ATTACH TABLE and no part of this PR involved. After the reattach, the part that still has the old Enum8 type is no longer pruned by statistics for e = 'c', so the EXPLAIN indexes = 1 check returns 0 instead of 1. Only pruning is affected; the query results stay correct. I added no-random-detach to the test and wrote the reason in its Tags comment.
  • Review threads: none are unresolved.
  • I did not merge master again, because the branch was merged with it on 2026-11-09.

alexey-milovidov and others added 2 commits November 11, 2026 16:42
The test checks with `ProfileEvents` from `system.query_log` which
statistics and primary indexes are loaded, relying on what is kept in
memory between queries. A random `DETACH`/`ATTACH` of the table drops
them, so the counters differ. The CI diagnosis confirms the failure
requires the DETACH/ATTACH randomization.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=latest&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

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

Copy link
Copy Markdown
Member Author

🕵 /continue-pr-auto pass on 2026-11-11: pushed fba4056d3f5 → 0377709931f.

  • Stateless test failure: 05407_statistics_skip_small_reads failed in three jobs (amd_debug, distributed plan, s3 storage, arm_binary, parallel, arm_binary, AsyncInsert, s3 storage). The CI diagnosis showed that it fails only with the DETACH/ATTACH randomization. The test uses ProfileEvents to check which statistics and primary indexes are loaded, and that depends on what stays in memory between queries. Added no-random-detach with an explanation.
  • Merged master: no conflicts. The merged tree builds and links (ninja clickhouse).
  • Review threads: none are unresolved.

Comment thread src/Interpreters/ActionLocksManager.cpp Resolved
alexey-milovidov and others added 4 commits November 13, 2026 02:00
…les-v2

Conflicts:
- `ActionLocksManager.cpp`: master keys action locks by the loaded storage of a
  `StorageTableProxy` (`lockKey`); the PR reworked the lock bookkeeping with owners.
  Kept the PR's design and applied `lockKey` to the table and owner keys in `add`,
  `remove` and `has`/`hasAny`.
- `executeQuery.cpp`: kept the PR's `executeQueryFailpoints` and moved master's new
  `segfault_read_access` and `segfault_write_access` failpoints into it.
- Test tags: master removed `no-fasttest`; kept the PR's `no-random-detach`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ly nested `SETTINGS` as the analyzer does

- A CTE is reachable only by the full name of an identifier. Function names and the
  first part of a compound identifier now make only scalar `WITH` bindings reachable,
  so `WITH count AS (SELECT * FROM src) SELECT count()` and
  `WITH unused AS (...) SELECT unused.a FROM lhs AS unused` no longer reattach `src`.
- The scope settings of a select with a nested `SETTINGS` clause are now taken from a
  copy of the enclosing scope's context with the whole clause applied through
  `Context::applyNestedQuerySettingsClamped`, the sequence `QueryTreeBuilder` uses. So a
  constraint introduced by an earlier change of the clause (`readonly = 1`) is honoured
  for the later scope setting change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…it up in `SYSTEM START`

`ActionLocksManager::remove` resolved the target of a forwarding storage before checking
that the user may run the statement on it. The lookup runs with the alias's own context
and may reach an external database, so a user granted only the alias could trigger it
and see its errors. Now each declared target is checked before it is looked up, and the
resolution stops at the first one that is not allowed.

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/PRs/96130/0377709931fdc81245fbd6e32129c2ad88af8571/pr/ast_fuzzer_amd_debug_targeted_old_compatibility/fatal.log (AST fuzzer (amd_debug, targeted, old_compatibility): Inconsistent AST formatting (STID: 1941-26fa) for a fuzzed CREATE TABLE ... (number Nullable(Int16) CODEC(__compose(...) % FirstApplicable(...), ...)) ... COMMENT '\0'; the two AST dumps are identical, so the difference is in the formatted text) and provide a fix in a separate PR. If the fix is already in progress, link it here. This PR does not touch the parser or the formatter.

The other CI failures (03707_statistics_cache, 05496_dynamic_disk_wrapper_of_server_credentials_disk) needed DETACH/ATTACH randomization to fail; they are now tagged no-random-detach (9ebbe7b). Master is merged in, with the ActionLocksManager conflict reconciled with the lazy-table lockKey from master.

@groeneai

Copy link
Copy Markdown
Collaborator

This one is already fixed by #125567 (merged 2026-11-11 18:44 UTC). The failing run built 229eeca3c0ae, which does not contain it; your current head 12df77d47787 does, so no separate PR is needed.

I checked the exact fuzzed query from server.log (CREATE TABLE shard_0.tbl__fuzz_67 ... CODEC(modulo(timeSeriesBottomKMasks | arrayPackBitsToFixedString(_), FirstApplicable(Multiple(PCO(), Delta(1)), ALP(), LZ4(), LZ4()))) ...):

The two other hits of STID 1941-26fa in CIDB since the merge also ran on builds without #125567.

alexey-milovidov and others added 3 commits November 14, 2026 13:18
…the caller's context

`StorageAlias::tryGetTargetTable` uses the alias's global context, so the source access checks of the
target's database (for example `READ ON URL` / `READ ON FILE` of a `URL` database) did not apply
to the caller. `ActionLocksManager::remove` now takes the context to resolve the forwarding target with
instead of a flag, and `resolveActionLockOwner` looks the approved target up with it.

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

Copy link
Copy Markdown
Member Author

🕵 /continue-pr-auto pass on 2026-11-14: pushed 12df77d47787 → 27a9196f377d.

  • Build (arm_tidy, 3/4): clang-analyzer-core.FixedAddressDereference fired on the segfault failpoints after they moved into executeQueryFailpoints. Added targeted NOLINTs (f9601a9).
  • Review blocker (ActionLocksManager): SYSTEM START now resolves a forwarding target with the caller's query context, so the source access checks of the target's database still apply. 05630 is extended with a URL database case: SYSTEM MERGES on both names but no source grant (cd71ff0).
  • Merged master: no conflicts. The changed TUs (ActionLocksManager.cpp, InterpreterSystemQuery.cpp, executeQuery.cpp) compile. A full local link could not finish, because the compiler of the unrelated Aggregator.cpp was repeatedly terminated under machine load. CI will verify the build and the test.

Comment thread src/Interpreters/ActionLocksManager.cpp Resolved
alexey-milovidov and others added 2 commits November 16, 2026 11:12
…caller's context

`ActionLocksManager::add` resolved an `Alias` with `StorageAlias::tryGetTargetTable`, which uses the
alias's global context, so `SYSTEM STOP MERGES alias` could look up a target in a protected source
database (for example, a file in a `URL` database without `READ ON FILE`) or expose the connection
error of an unreachable external database to a user granted only the alias.

Now `add` takes the caller's context and the same access check as `remove`: each target is checked
before it is looked up, no lock is taken when the caller may not run the statement on the target,
and the lookup runs with the caller's context, so the source checks of the target's database apply.
`05630_system_start_alias_target_access_before_lookup` covers the `SYSTEM STOP` variants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
const auto create_query = database.tryGetCreateTableQuery(table_id.getTableName(), context);
if (!create_query)
return true;
return containsStorageReadingScalarFunctionCall(*create_query) || containsSQLUserDefinedFunctionCall(*create_query);

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.

[Blocker] Check aggregate-type construction privileges before detaching

The stored-definition check misses privileges required by aggregate types. An administrator can create an otherwise eligible table with s AggregateFunction(flameGraph, Array(UInt64)) under allow_introspection_functions = 1. Give another user SELECT, CREATE TABLE, and DROP TABLE on that table plus TABLE ENGINE ON MergeTree, without INTROSPECTION. Their ordinary SELECT count() succeeds, but enabling reattach_tables_before_query_execution detaches the table and leaves it detached.

Reparsing the stored column type reaches DataTypeAggregateFunction::create and then createAggregateFunctionFlameGraph, which checks INTROSPECTION at src/AggregateFunctions/AggregateFunctionFlameGraph.cpp:48. The internal context enables allow_introspection_functions but retains the restricted user, so both the normal and recovery ATTACH fail with ACCESS_DENIED. Neither scanner here detects that aggregate type. The existing 05479 regression uses the administrator and therefore misses the missing grant.

Validate aggregate construction privileges, or skip these stored definitions before DETACH, and add a restricted-user regression proving the table remains attached and queryable. The query-level authorization guard should cover direct flameGraph calls as well.

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 dfc9c60. storedDefinitionMayFailToAttach now skips a table whose stored definition names flameGraph (with any combinator) unless the querying user holds INTROSPECTION. The grant is in effect only under allow_introspection_functions, which the internal ATTACH turns on, so it is checked on a copy of the context with that setting on - the administrator case of 05479_reattach_tables_type_gates_refreshable_view (the query has allow_introspection_functions = 0) still reattaches. The hook is also skipped for a query that calls flameGraph itself. 05840_reattach_tables_flamegraph_introspection_grant covers the restricted user from the comment (SELECT, CREATE TABLE, DROP TABLE, TABLE ENGINE ON MergeTree, no INTROSPECTION): the table is not detached and stays queryable, a direct flameGraph call gets ACCESS_DENIED without a DETACH, and after GRANT INTROSPECTION the table is reattached.

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.

[Blocker] The direct column-type case is covered now, but the same failed-restoration issue remains when the aggregate name is a string. containsFlameGraphAggregateFunction at src/Interpreters/executeQuery.cpp:3889-3892 checks only ASTFunction and ASTIdentifier, so it misses this stored definition (created by an administrator with allow_introspection_functions = 1):

CREATE TABLE t
(
    trace Array(UInt64),
    INDEX i length(arrayReduce('flameGraph', [trace])) TYPE minmax GRANULARITY 1
)
ENGINE = MergeTree ORDER BY tuple();

For the restricted user from the original finding, SELECT count() FROM t SETTINGS reattach_tables_before_query_execution = 1, use_skip_indexes = 0 passes the hook's guards and detaches the table. During both normal and recovery ATTACH, IndexDescription::initExpressionInfo rebuilds the index; FunctionArrayReduceOverloadResolver::resolveAggregateFunction constructs flameGraph from the literal, and createAggregateFunctionFlameGraph rejects the missing INTROSPECTION grant. The table remains detached. This is a source trace; no local server is available in this review job.

The same representation gap exists for type strings passed to CAST (including its AS syntax), and aggregate-name strings in arrayReduceInRanges / initializeAggregation. Please validate aggregate construction under the attach context before detaching, or conservatively exclude these carriers, and extend the restricted-user regression with a stored string-carrier expression. The query-level guard uses the same helper and needs the same coverage.

Comment thread src/Interpreters/ActionLocksManager.cpp Resolved
alexey-milovidov and others added 7 commits November 21, 2026 01:50
…tarted through an alias

`resolveAliases` in `ActionLocksManager` stopped after 16 hops and returned the storage it was on even
when that was still an `Alias`. `ActionLocksManager::add` then asked it for the lock, and
`StorageAlias::getActionLock` resolved the rest of the chain with the alias's global context, with
neither the `may_resolve` check nor the source access checks of the caller. Follow the chain to its end
whatever its length, checking every hop, and detect a cycle with a set of the visited storages instead
of a bound: a cycle resolves to no storage. `resolveActionLockOwner` uses the same cycle detection.
`05630_system_start_alias_target_access_before_lookup` covers a chain of 17 aliases.

`SYSTEM STOP VIEW` and `SYSTEM PAUSE VIEW` through an `Alias` of a refreshable materialized view with an
inner table stopped the refresher, but `SYSTEM START VIEW` through the same `Alias` did not resume it:
the inner table holds no lock for these actions, so no owner was recorded, and the owner resolution walked
past the view to the inner table, so `onActionLockRemove` was called on the inner table and on the alias
but not on the view. The `ViewRefresh` and `ViewRefreshPause` actions belong to the view, so the walk
stops at it for them. `05839_system_start_view_through_alias` covers it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…ut the `INTROSPECTION` grant

Re-parsing a column of the type `AggregateFunction(flameGraph, ...)` creates the aggregate function, which
checks the `INTROSPECTION` grant of the querying user. The internal `ATTACH` of
`reattach_tables_before_query_execution` keeps that user, so for a user without the grant both it and the
recovery `ATTACH` failed with `ACCESS_DENIED` and left the table detached. `storedDefinitionMayFailToAttach`
now skips such a table unless the user holds the grant. The grant is in effect only under
`allow_introspection_functions`, which the internal `ATTACH` turns on, so it is checked with that setting on.

A query that calls `flameGraph` itself is rejected for a user without the grant only when the function is
created, after the hook, so the hook is skipped for such a query.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…` as `no-random-detach`

`05460_fsync_error_dedup_log_sync_error`: the part that failed to sync is neither detached nor durable, and
the failed removal from the deduplication log is remembered only in memory, so a reattach of the table
loses both and the test sees the rows of one insert instead of two.

`05616_lazy_load_tables_replace_proxy_held`: the reattach of the table the reader uses loads it, so the
reader holds the loaded storage rather than the proxy and the next lookup has no proxy to keep. Reproduced
locally with `--reattach-tables-probability 1`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=c299a6e02b78a6e1b305d316c8808b64a331f927&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20sequential%29
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=c299a6e02b78a6e1b305d316c8808b64a331f927&name_0=PR&name_1=Fast%20test%20%28arm_darwin%29
#96130

Co-Authored-By: Claude Fable 5.2 <[email protected]>
….12 in the settings history

The current version is 26.12, and the `settings_changes_history` style check requires
a new setting to be recorded under the current version:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=e57737d751b780f7945d114c7bd306f2cc62cc2c&name_0=PR&name_1=Style%20check

Co-Authored-By: Claude Fable 5.2 <[email protected]>
`05258_query_condition_cache_prewhere_attribution` and `02346_text_index_bug108519_qcc_skip_index`
check `QueryConditionCacheHits` of a query that reuses the entries written by a previous one.
Attaching a `MergeTree` table clears the query condition cache, so with the randomization
of `DETACH`/`ATTACH` the second query misses the entries:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=e57737d751b780f7945d114c7bd306f2cc62cc2c&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 /continue-pr-auto pass on 2026-11-24: pushed e57737d751b7 → e5163634a52d.

  • Style check (settings_changes_history): the current version is now 26.12, so the history records of reattach_tables_before_query_execution and reattach_tables_before_query_execution_probability moved from 26.11 to 26.12 (64a7c92).
  • Fast test: 05258_query_condition_cache_prewhere_attribution and 02346_text_index_bug108519_qcc_skip_index failed only with the DETACH/ATTACH randomization. Both check QueryConditionCacheHits of a query that reuses the entries of a previous one, and attaching a MergeTree table clears the query condition cache (StorageMergeTree, LoadingStrictnessLevel::ATTACH). Tagged no-random-detach with the reason (939da03).
  • Merged master: no conflicts. The translation units touched by this PR compile on the merged tree; I did not do a full link locally, so CI will verify the complete build.
  • Review threads: none are unresolved.

This branch has not been deployed

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

Labels

comp-testing Test content only (no production code). pr-build Pull request with build/testing/packaging improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants