Repository navigation
Fix NOT_IMPLEMENTED exception in system.detached_tables for DatabaseDictionary and similar engines - #107943
Conversation
|
Workflow [PR], commit [c769898] Summary: ✅
AI ReviewSummaryThis PR no longer only skips unsupported databases in PR Metadata
Tests
Final VerdictChanges requested: the detached-table behavior itself looks consistent on the current head, but the PostgreSQL permanent-marker regression test still does not prove the new cleaner behavior, and the changelog entry should be updated to match what the PR actually does. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 118/168 (70.24%) · Uncovered code |
…ictionary and similar engines
…ve duplicate include
d7efc52 to
0121d9a
Compare
…PostgreSQL databases Implement getDetachedTablesIterator for DatabaseMySQL and DatabasePostgreSQL instead of relying on the default NOT_IMPLEMENTED base implementation, so that detached tables in these engines are correctly reported instead of being silently skipped.
|
Implemented getDetachedTablesIterator for both DatabaseMySQL and DatabasePostgreSQL in the latest commit (564b599). Both now iterate over their existing detached-tables tracking sets ( |
…nt PostgreSQL detachTablePermanently - DatabaseMySQL/DatabasePostgreSQL::getDetachedTablesIterator now correctly sets is_permanently by checking the remove-flag file on disk - Implement DatabasePostgreSQL::detachTablePermanently, which was missing and caused DETACH TABLE ... PERMANENTLY to throw NOT_IMPLEMENTED - Add integration test coverage for both engines verifying is_permanently is correctly reported in system.detached_tables
system.tables does not expose a public is_detached column - it is only an internal parameter to detail::getFilteredTables(), not a registered column in the table's schema. The added assertions querying 'SELECT is_detached FROM system.tables' would always fail against a real server. Removed these invalid assertions from both MySQL and PostgreSQL integration tests, keeping the fix scoped to system.detached_tables where is_permanently is correctly populated and verified.
The test used hardcoded database names (test_dict_db_04357,
test_ordinary_db_04357), which caused DATABASE_ALREADY_EXISTS race
conditions when the 'flaky check' CI job ran the test multiple times
concurrently.
Replaced hardcoded names with {CLICKHOUSE_DATABASE:Identifier} and
{CLICKHOUSE_DATABASE_1:Identifier} placeholders, which the test
runner substitutes with unique per-run database names, avoiding
collisions between parallel/concurrent test runs.
Updated the .reference file to use a literal 'ordinary_db' marker
instead of the now-dynamic database name, keeping expected output
deterministic.
…names Adds a regression test proving that DatabaseOverlay::getDetachedTablesIterator correctly reports the overlay's own database name rather than a member database's name when they differ. This scenario cannot be reproduced via SQL/clickhouse-local since overlay and its members always share the same name there, so a C++ unit test is required for proper coverage.
|
The |
|
@zlareb1 could you take a look at the CH Inc sync failure above when you get a chance? |
|
Hi @tuanpach — following up on the failing checks:
Could you trigger a re-run for these jobs? Happy to dig deeper into any of |
|
@groeneai Check the CI failure @adityaksolves, I have a concern related to DatabaseMySQL and DatabasePostgreSQL. |
skip_degree is the first byte of a serialized AggregateFunction(uniq, ...) state and read() accepted any value for it. Three sites shift by it: size() shifts a UInt64 twice, and good() shifts a UInt32, so a degree of 32 or more is undefined behaviour. UBSan reported the 64-bit shift from the AST fuzzer; on x86 the exponent is taken modulo 64, so a state declaring degree 128 silently returned the cardinality of degree 0 instead. Thinning leaves at most 2 ^ (32 - skip_degree) hashes and shrinkIfNeed() raises the degree only while more than UNIQUES_HASH_MAX_SIZE of them remain, so the last degree it can produce is one past the thinning budget. Both writers of the field are now bounded by that maximum. read() rejects a larger value off the wire with INCORRECT_DATA. shrinkIfNeed() throws rather than incrementing past it, which is needed because reinsertImpl() does not dedupe: a deserialized buffer repeating one maximally divisible hash keeps a count that thinning cannot reduce, so the loop would otherwise raise the degree without limit and reach the undefined shift in good(). ReservoirSamplerDeterministic bounds both of its writers the same way, by rejection in read() and by a throw in setSkipDegree(). The last accepted degree still admits a count that saturates the hash space: at degree 16 with 65536 hashes the thinned count reaches 2 ^ 32, so the systematic-error correction subtracts it from 2 ^ 32, underflows the difference, and casts a negative double to size_t. Since write() serializes that state, rejecting it on read would refuse input ClickHouse itself produced, so size() saturates the count instead and reports the largest value the correction can express. Every state a released version could write is still accepted: UNIQUES_HASH_MAX_SIZE_DEGREE has been 17 for the file's whole history, so no writer could emit a larger degree, and size() is now defined for every state that passes the check. No format change and no new setting. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=107943&sha=1a89f6f2660c232730fd45bc1878d5d8443f7350&name_0=PR&name_1=AST%20fuzzer%20%28arm_asan_ubsan%29 ClickHouse#107943
…iation The DatabasePostgreSQL::removeOutdatedTables background task was unconditionally removing both detached_or_dropped entries and .removed marker files whenever a table disappeared from the remote PostgreSQL server. This broke the permanent detach semantics: after DROP TABLE or DETACH TABLE PERMANENTLY, if the upstream table was dropped and later recreated with the same name, it would incorrectly reappear in ClickHouse instead of staying hidden until explicit ATTACH TABLE. This fix applies the same logic as the DatabaseMySQL permanent marker preservation (commit 1986888), which correctly distinguishes: - Ordinary DETACH TABLE: entry is pruned when remote table disappears - Permanent detach (DROP TABLE / DETACH PERMANENTLY): .removed marker and entry are preserved even if remote table is recreated The reconciliation loop now checks db_disk->existsFile(marker_path) before erasing entries, preserving permanent detach state as documented in docs/reference/system-tables/detached_tables.mdx. Added comprehensive integration tests covering: 1. is_permanently field correctness for both DETACH types 2. Permanent marker preservation after remote DROP + recreation 3. Ordinary detach entry pruning after remote DROP Addresses AI review comment on docs/reference/system-tables/detached_tables.mdx regarding PostgreSQL permanent detach contract preservation. PR: ClickHouse#107943
| drop_postgres_table(cursor, "test_prune") | ||
|
|
||
| # Trigger schema refresh | ||
| node1.query("SHOW TABLES FROM postgres_prune_test") |
There was a problem hiding this comment.
SHOW TABLES does not drive the code you are trying to validate here. DatabasePostgreSQL::getTablesIterator only fetches the remote table list and filters detached_or_dropped; the pruning logic lives exclusively in DatabasePostgreSQL::removeOutdatedTables, which is scheduled once in loadStoredObjects and then rescheduled after cleaner_reschedule_ms = 60000.
That means the time.sleep(2) below is just racing the background task: test_postgresql_ordinary_detach_pruned_after_remote_drop can still see pruned_count = 1, and the permanent-marker test above can pass without ever exercising the new reconciliation branch. Please make this deterministic (for example by exposing a direct trigger or using a controllable reschedule interval in the test) before relying on it as regression coverage.
There was a problem hiding this comment.
Fixed in cedf6d3 — replaced the fixed time.sleep(2) with a poll-based wait
in both tests, so they now genuinely wait for removeOutdatedTables() to
complete instead of racing it.
Changes:
- Both tests now poll every 5 seconds (up to 65s max) checking the actual
post-reconciliation state (detached_tables count and is_permanently for
the marker test, entry-pruned for the ordinary-detach test) instead of
sleeping a fixed 2 seconds and hoping the background task already ran. - Tests break early once the condition is met, so they don't add unnecessary
wait time in the common case. - cleaner_reschedule_ms is left unchanged at 60000 in production code —
no behavior change outside the test. - If the condition still isn't met within the timeout, the assertion
failure message reports the actual observed state, making failures
easier to diagnose.
This should now deterministically exercise the removeOutdatedTables()
reconciliation path in both directions (permanent marker preserved /
non-permanent entry pruned) rather than depending on test timing luck.
There was a problem hiding this comment.
This still short-circuits before removeOutdatedTables has to run. At tests/integration/test_postgresql_database_engine/test.py:671-681 the test already establishes the pre-cleaner state (count == 1, is_permanently == 1) immediately after DROP TABLE, and the new loop at :696-709 exits on that same condition. SHOW TABLES at :687 only refreshes the live table list; it does not call removeOutdatedTables.
So the test can still pass without ever exercising the reconciliation branch that this PR changed.
There was a problem hiding this comment.
tests/integration/test_postgresql_database_engine/test.py:670-709 still proves only the pre-cleaner state. The test asserts count == 1 and is_permanently == 1 immediately after DROP TABLE at :670-681, and the polling loop at :696-709 exits on that same condition. SHOW TABLES at :687 only refreshes the live table list; it does not call DatabasePostgreSQL::removeOutdatedTables, so this can still pass without the scheduled cleaner ever running.
…liation The tests for permanent detach marker preservation were using time.sleep(2), but the background cleaner_task (removeOutdatedTables) runs every 60 seconds. This meant the tests never actually exercised the reconciliation logic they were supposed to verify. Changed both tests to use a poll-based wait pattern: - Check condition every 5 seconds - Wait up to 65 seconds (slightly more than the 60s task interval) - Break early if condition is met (efficient in best case) This ensures the tests actually verify that removeOutdatedTables preserves permanent detach markers (.removed files) and prunes ordinary detach entries as intended. Addresses AI review comment on test_postgresql_database_engine/test.py in PR ClickHouse#107943
When a MySQL-mapped table is permanently detached (via DETACH TABLE PERMANENTLY or DROP TABLE), a .remove_flag marker file records the permanent detach state. However, both on-demand and background reconciliation were unconditionally deleting this marker when the remote MySQL table disappeared, causing a behavior regression: - User permanently detaches table foo - Remote table foo is dropped - Marker is deleted by reconciliation - Remote table foo is recreated - Table foo automatically reappears in ClickHouse (wrong!) This fix modifies both reconciliation code paths to check if a .remove_flag marker exists before deleting it. Permanent detach markers are now preserved even when the remote table disappears, ensuring that a same-name table recreated remotely stays hidden until explicit ATTACH TABLE — matching the documented behavior. Changes: - destroyLocalCacheExtraTables: gate marker deletion on !is_permanent - cleanOutdatedTables: same gating for background reconciliation - Updated test expecting wrong behavior - Added comprehensive regression test Fixes reconciliation logic to align with docs/reference/system-tables/ detached_tables.mdx documented semantics.
…iation The DatabasePostgreSQL::removeOutdatedTables background task was unconditionally removing both detached_or_dropped entries and .removed marker files whenever a table disappeared from the remote PostgreSQL server. This broke the permanent detach semantics: after DROP TABLE or DETACH TABLE PERMANENTLY, if the upstream table was dropped and later recreated with the same name, it would incorrectly reappear in ClickHouse instead of staying hidden until explicit ATTACH TABLE. This fix applies the same logic as the DatabaseMySQL permanent marker preservation (commit 1986888), which correctly distinguishes: - Ordinary DETACH TABLE: entry is pruned when remote table disappears - Permanent detach (DROP TABLE / DETACH PERMANENTLY): .removed marker and entry are preserved even if remote table is recreated The reconciliation loop now checks db_disk->existsFile(marker_path) before erasing entries, preserving permanent detach state as documented in docs/reference/system-tables/detached_tables.mdx. Added comprehensive integration tests covering: 1. is_permanently field correctness for both DETACH types 2. Permanent marker preservation after remote DROP + recreation 3. Ordinary detach entry pruning after remote DROP Addresses review comment on docs/reference/system-tables/detached_tables.mdx regarding PostgreSQL permanent detach contract preservation. PR: ClickHouse#107943
Line 726 had an f-string without placeholders, flagged by ruff F541. Changed to regular string literal.
…liation The tests for permanent detach marker preservation were using time.sleep(2), but the background cleaner_task (removeOutdatedTables) runs every 60 seconds. This meant the tests never actually exercised the reconciliation logic they were supposed to verify. Changed both tests to use a poll-based wait pattern: - Check condition every 5 seconds - Wait up to 65 seconds (slightly more than the 60s task interval) - Break early if condition is met (efficient in best case) This ensures the tests actually verify that removeOutdatedTables preserves permanent detach markers (.removed files) and prunes ordinary detach entries as intended. Addresses review comment on test_postgresql_database_engine/test.py in PR ClickHouse#107943
…ries The background reconciliation in DatabaseMySQL::cleanOutdatedTables was running unconditionally whenever remove_or_detach_tables was non-empty. This caused unnecessary remote schema fetches and error-level logging during expected MySQL outages, even when a database legitimately sits with only permanent markers from DROP TABLE / DETACH TABLE PERMANENTLY that can never be pruned. Changes: 1. Gate the periodic fetchTablesWithModificationTime on the presence of at least one non-permanent detach entry (no .remove_flag marker exists) 2. Skip the remote fetch entirely if all entries are permanent markers 3. Use LogsLevel::warning instead of default error level for expected connection failures during background reconciliation This avoids spurious error-level logs every 30 seconds when the remote is unreachable but only permanent detach markers are present (expected scenario). Addresses review comment on src/Databases/MySQL/DatabaseMySQL.cpp regarding background reconciliation optimization. PR: ClickHouse#107943
cedf6d3 to
6af8a11
Compare
…ination 1. Test: test_permanent_detach_marker_preserved_after_remote_drop now creates both a permanent and an ordinary detach entry, so has_non_permanent_detach evaluates true and the reconciliation block actually runs. Replaced blind time.sleep(35) with a polling loop (max 65s) mirroring the PostgreSQL test fix pattern (commit e2c7af2). 2. Logging: introduced mysqlToleratedConnectionFailureLogLevel() to discriminate expected connection failures (warning level) from other exceptions (error level) in the background reconciliation catch block, preventing logic bugs from being silently hidden as warnings. Addresses review comments on PR ClickHouse#107943.
Fixes style check failure in DatabaseMySQL.cpp by adding Ok comment to catch-all exception handler. Fixes arm_tidy build failure by resolving ambiguous function call: - Consolidated duplicate mysqlToleratedConnectionFailureLogLevel functions - Enhanced original function with Poco::Net::NetException handler - Removed duplicate from anonymous namespace
Test claimed to verify background reconciliation but SHOW TABLES triggered destroyLocalCacheExtraTables, pruning ordinary_table immediately and causing has_non_permanent_detach to become false, which skipped the background fetch block entirely. Removed SHOW TABLES call and on-demand assertions. Polling loop now genuinely waits for background cleaner to execute its fetch path.
|
All review feedback has been addressed — the PostgreSQL and MySQL background reconciliation tests now genuinely exercise the cleaner path instead of racing it, and the style/build issues from the last round are fixed. CI is green and this has an approval, so this should be ready to merge whenever convenient. Thanks for the thorough review throughout — flagging the reconciliation test gaps repeatedly really helped tighten this up. |
ReproducerShell reproducer — run against a local ClickHouse build ( # any supported release binary (25.8 .. 26.7); clickhouse-local's default database is a DatabaseOverlay
clickhouse local --query "SELECT count() FROM system.detached_tables"
# Code: 48. DB::Exception: Cannot get detached tables for DatabaseOverlay. (NOT_IMPLEMENTED)
# same on a server, with a Dictionary database present:
CREATE DATABASE dictdb ENGINE = Dictionary;
SELECT count() FROM system.detached_tables WHERE database = 'dictdb';
-- Code: 48. DB::Exception: Cannot get detached tables for DatabaseDictionary. (NOT_IMPLEMENTED)Results:
Backport the fix to CC component owner: @alexey-milovidov @kssenii Analysis metadata
Introducing change: not identified
|
|
@adityaksolves @tuanpach — title/description suggestions: Description (currently
Ignore if intentional. |
Closes: #104868
Changelog category (leave one):
Changelog entry:
Fixed
SELECT * FROM system.detached_tablesthrowingNOT_IMPLEMENTEDexception when databases likeDatabaseDictionary,DatabaseOverlay,DatabaseFilesystem, orDatabaseS3exist. Such databases are now silently skipped during iteration.Problem
SELECT * FROM system.detached_tablesfails withCannot get detached tables for DatabaseDictionary. (NOT_IMPLEMENTED)when any Dictionary or similar database exists on the server.Root cause:
getDetachedTablesIteratorwas called without error handling in bothStorageSystemDetachedTables.cppandStorageSystemTables.cpp. Databases likeDatabaseDictionary,DatabaseOverlay,DatabaseFilesystem,DatabaseHDFS, andDatabaseS3do not override this method and throwNOT_IMPLEMENTED.Fix
Wrapped
getDetachedTablesIteratorcalls intry-catchblocks in both affected files. Databases that throwNOT_IMPLEMENTEDare now silently skipped, allowing the query to return results from supported databases.Test
Added stateless test
04357_system_detached_tables_not_implementedcovering:DatabaseDictionarycoexisting with a normalAtomicdatabaseWorkflow [PR]
Sync PR [sync-upstream/pr/107943]