Repository navigation
Randomize tests with DETACH/ATTACH table before query execution - #96130
alexey-milovidov wants to merge 502 commits into
Conversation
|
Workflow [PR], commit [e516363] Summary: ❌
AI ReviewSummaryThe 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
Tests
Final VerdictStatus: ❌ Block Close the string-carrier authorization gap before |
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]>
b5650bf to
64e6436
Compare
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]>
|
It looks like all tests have passed! |
Algunenano
left a comment
There was a problem hiding this comment.
The failures:
00326_long_function_multi_ifis using tables and many queries. We could disable or change the queries to reduce them.00090_union_race_conditions_1times out. Also disable?02015_async_inserts_4is 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).
f3af9c0 to
7d4766e
Compare
9df2db6 to
047958c
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
There are 3 total unresolved issues (including 2 from previous reviews).
Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
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]>
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]>
# 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]>
|
🕵
|
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]>
|
🕵
|
…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]>
…_disk_wrapper_of_server_credentials_disk` Both fail in CI only with the DETACH/ATTACH randomization: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=latest&name_0=PR #96130 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]>
|
🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/PRs/96130/0377709931fdc81245fbd6e32129c2ad88af8571/pr/ast_fuzzer_amd_debug_targeted_old_compatibility/fatal.log ( The other CI failures ( |
|
This one is already fixed by #125567 (merged 2026-11-11 18:44 UTC). The failing run built I checked the exact fuzzed query from
The two other hits of STID 1941-26fa in CIDB since the merge also ran on builds without #125567. |
… failpoints of `executeQueryFailpoints` The failpoints were moved into a separate function, which makes `clang-tidy` analyze them. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=96130&sha=12df77d4778721ef33c9b35d8ee4dba28298b2e4&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
|
🕵
|
…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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
[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.
…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]>
|
🕵
|

Add
reattach_tables_before_query_executionandreattach_tables_before_query_execution_probabilitysettings 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
DETACHfollowed byATTACH.Changes:
supportsDetachingTablesvirtual method toIDatabase(overridden tofalsefor engines that do not support non-permanentDETACH TABLE:DatabaseDictionary,DatabaseReplicated,DatabaseSQLite,DatabaseBackup,DatabaseFilesystem,DatabaseHDFS,DatabaseS3,DatabaseURL,DatabaseRemote,DatabaseDataLake,DatabaseMaterializedPostgreSQL)has/hasAnymethods toActionLocksManagerfor checking existing locks (skipping expiredweak_ptrentries)executeQuery(runs after AST validations, process list admission, and external tables initialization; skipsEXPLAIN, transactions, internal/non-initial queries, and CTE name collisions)DETACH TABLE ... SYNCwaits 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 finishesmainTableTouchedIfExists,createQueryStopsBeforeSources,mutationQueryStopsBeforeSourcesforDELETE/UPDATE/ALTER,insertQueryStopsBeforeSources), including theIN PARTITIONclause 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 checkATTACHback could not restore: the user must hold the fullDETACH/ATTACHauthorization for the object's kind (including theTABLE ENGINEgrant), and the table's database must not already be over its ownmax_tableslimitdiskfunction: a plainATTACH TABLEis 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 theATTACHback would be rejected withACCESS_DENIEDand leave the table detachedDETACH/ATTACHpair 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 theATTACHback fail - and then the recoveryATTACHinherited it and failed the same way, leaving the table detachedSet/Jointable withpersistent = 0(its rows live only in memory andATTACHrestores only the backup files), the right-hand side ofIN(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 bycheckNoRowPolicyForSetOperandsCoordination::setCurrentComponent). The hook runs under no interpreter, so withenforce_keeper_component_trackingon, the first Keeper request its preflight makes on a database whose metadata lives in Keeper was an unnamed request, which is aLOGICAL_ERRORATTACH(after a failedDETACH/ATTACHpair) outside the outer query's process list and withdatabase_atomic_wait_for_drop_and_detach_synchronously, so a query cancelled while theDETACHwaited for a concurrent reader does not leave the table detachedMergeTreeDeduplicationLog::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, andsyncthe writer in shutdownstartup/shutdownraces the randomization exposes inStorageMergeTree,StorageReplicatedMergeTreeandReplicatedMergeTreeAttachThread: aDETACHracing an in-flight async startup could leave background workers armed on a logically shut-down table, hangwaitFirstTryforever, or tear the interserver parts exchange endpoint down under a concurrent full shutdownno-random-detachtag to tests incompatible with this feature--no-random-detachand--reattach-tables-probabilityoptions toclickhouse-test02461_reattach_tablessuite, split across02461_reattach_tables,05099_reattach_tables_access,05100_reattach_tables_create,05101_reattach_tables_engines,05102_reattach_tables_mutations,05103_reattach_tables_internal_settingsand05104_reattach_tables_dynamic_diskso that no part approaches the per-test timeout - a check costs oneclickhouse-clientinvocation, and a sanitizer-built client starts in seconds - with the shared helpers in02461_reattach_tables.libContinuation of #55943. Continuation of #42336
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add
reattach_tables_before_query_executionandreattach_tables_before_query_execution_probabilitysettings that randomlyDETACHandATTACHtables 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
Note
Medium Risk
Introduces new pre-execution mutations (internal
DETACH/ATTACH) inexecuteQuery, 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_executionand..._probabilityto 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
IDatabasewithsupportsDetachingTables()and marks multiple database engines as not supporting non-permanent detach; addsActionLocksManager::has/hasAnyhelpers to avoid detaching tables with active action locks. Updates the test runner and stress tooling to randomize this behavior (with--no-random-detachand probability control), adds a new02461_reattach_tablestest, and tags many existing tests to opt out where DETACH/ATTACH would add flakiness/overhead. Also fixesMergeTreeDeduplicationLogcleanup to avoid dropping the active log and ensures writersync()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]