Repository navigation
Fix stale and deleted rows when reading a MaterializedPostgreSQL database through Merge - #112382
Conversation
…dPostgreSQL database through Merge""
|
Workflow [PR], commit [fe63ba9] Summary: ✅
AI ReviewSummaryThis PR fixes the direct Findings❌ Blockers
Tests
Final VerdictRequest changes. LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 103/141 (73.05%) · Uncovered code |
`DatabaseMaterializedPostgreSQL::materialized_tables` was guarded by two different mutexes: readers (`tryGetTable`, `getTablesIterator`, `getTablesForBackup`) took `tables_mutex`, while the writers (`startSynchronization`, `attachTable`, `detachTablePermanently`, `stopReplication`) took `handler_mutex` or no lock at all. The emptiness fast paths read the map completely unguarded. So `DROP DATABASE` - whose `stopReplication` calls `materialized_tables.clear()` - destroyed the `StorageMaterializedPostgreSQL` wrappers while another thread was still walking the map and dereferencing them. The sanitizer builds reported this as a heap use-after-free in `getTablesIterator` and aborted the server, after which every remaining test in `test_postgresql_replica_database_engine` failed with `Connection refused`. The mismatch was older than the previous version of this change, but only reachable from user queries; returning the wrappers from `getTablesIterator` put it on the `ServerAsynchronousMetrics` path, which enumerates the tables of every database once per second, so the window started being hit routinely. Make `tables_mutex` the only mutex that guards the map and mark it `TSA_GUARDED_BY`, so clang's thread-safety analysis rejects an unguarded access at compile time - reintroducing the original unguarded `materialized_tables.empty()` now fails the build with `-Wthread-safety-analysis`. `handler_mutex` is taken before `tables_mutex` where both are needed, and no call that can reach back into `handler_mutex` or the base class mutex is made while holding `tables_mutex`. Also stop `detachTablePermanently` from using `materialized_tables[table_name]` for the existence check: it inserted an empty entry for an unknown name, and that null `StoragePtr` stayed in the map after the exception, so a later `tryGetTable` would dereference it.
…t-109339-vdimir/fix-materialized-postgresql-merge-final
Right after CREATE / ATTACH DATABASE and after a server restart, `materialized_tables` is empty until `startSynchronization` has fetched the tables list from PostgreSQL and published the wrappers. In that window `tryGetTable` and `getTablesIterator` fell back to the nested `ReplacingMergeTree` tables, so user-facing reads (including `Merge`) bypassed the forced `FINAL` and the `_sign = 1` filter and exposed stale and deleted row versions. Distinguish that startup window from the after-`stopReplication` state with a `replication_stopped` flag guarded by `tables_mutex`, and build `StorageMaterializedPostgreSQL` wrappers over the nested tables on the fly while the window lasts. `test_reads_during_startup_window_use_final` holds the window open deterministically by pausing PostgreSQL across a server restart, so synchronization keeps retrying and can never publish the wrappers.
`tryStartSynchronization` keeps re-scheduling itself every 5 seconds until startup succeeds, but `InterpreterDropQuery` calls `stopReplication` long before `shutdown` deactivates the task. A queued retry could therefore re-enter `startSynchronization` and recreate `replication_handler` and the wrapper map while the database tables were being flushed and dropped. Deactivate the task in `stopReplication`, before taking `handler_mutex` (the task body locks the same mutex, and `deactivate` waits for a running execution). Add a pausable failpoint `database_materialized_postgresql_pause_before_table_drop` and the integration test `test_drop_database_cancels_startup_retries`, which holds `DROP DATABASE` open at the failpoint across several retry periods and checks that no retry fires anymore. Co-Authored-By: Claude Fable 5 <[email protected]>
…t-109339-vdimir/fix-materialized-postgresql-merge-final
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 87/96 (90.62%) · Uncovered code |
Returning `StorageMaterializedPostgreSQL` wrappers from `DatabaseMaterializedPostgreSQL::getTablesIterator` for every non-internal caller broke generic introspection: the wrappers carry no Atomic UUID, so `system.tables.uuid` became `Nil`, and they are not `MergeTreeData`, so the `dynamic_cast<MergeTreeData *>` in `StorageSystemPartsBase` and in `ServerAsynchronousMetrics` stopped matching and the tables disappeared from `system.parts` and from the asynchronous table metrics. Narrow the change instead. `getTablesIterator` goes back to exposing the physical nested `ReplacingMergeTree` tables together with their UUIDs, and the mapping to the wrapper moves into a new `IDatabase::getTableForRead`, which by default returns the enumerated storage unchanged. `StorageMerge` - the only consumer that reads data through the iterator - maps every enumerated table through it, so `Merge` over a `MaterializedPostgreSQL` database still reads with the forced `FINAL` and the `_sign = 1` filter, including during the startup window where the wrappers have not been published yet. `getTablesForBackup` no longer needs to force the nested context, since the iterator never hands out wrappers anymore. Also call `next` on the null-storage path of `ReadFromMerge::getSelectedTables`: it used to `continue` without advancing the iterator, which is an endless loop. Added `test_database_introspection_sees_nested_tables`, which checks that `system.tables.uuid` is not `Nil` and that `system.parts` still accounts for the rows of a replicated table, while reads still go through the wrapper. The drop race test now also reads through `merge`, so it keeps exercising the wrapper map that `getTablesIterator` no longer touches.
`Merge` discovers the capabilities and the statistics of its children through the very same enumeration that it reads through, so `supportsPrewhere`, `canMoveConditionsToPrewhere`, `supportsOptimizationToSubcolumns`, `getColumnSizes`, `totalRows` and `totalBytes` now see the `StorageMaterializedPostgreSQL` wrapper instead of the nested `ReplacingMergeTree`. The wrapper hands the `SelectQueryInfo` over to the nested table untouched, so it has to report what the nested table supports - otherwise a `Merge` over a `MaterializedPostgreSQL` database silently loses `PREWHERE`, the optimization to subcolumns and the size estimates. The same forwarding also fixes those capabilities for a direct read of a `MaterializedPostgreSQL` table, where the wrapper has always been the storage the query sees. `supportsTrivialCountOptimization` is deliberately left at the `IStorage` default: the nested table still holds the deleted rows (`_sign = 0`) and the superseded versions of the updated rows, which `read` filters out, so counting its parts would report more rows than a read returns. Added `test_merge_keeps_child_table_capabilities`, and dropped the `tests/server.pid.txt` runtime artifact that got committed by accident.
…t-109339-vdimir/fix-materialized-postgresql-merge-final # Conflicts: # src/Storages/StorageMerge.cpp
|
🕵 The only CI failure on Pushed |
…olumns` to the nested table `StorageMerge::supportedPrewhereColumnsIncludeSubcolumns` ANDs the bit across its children, so leaving `StorageMaterializedPostgreSQL` at the `IStorage` default `false` silently dropped a subcolumn condition from `PREWHERE` for the whole `Merge` table. `supportsSubcolumns` is forwarded as well, so a direct read of a subcolumn through the wrapper matches the nested table too. Extended `test_merge_keeps_child_table_capabilities` with `PREWHERE value.null = 0` through `Merge` (rejected with `ILLEGAL_PREWHERE` without the forwarding) and a direct subcolumn read through the wrapper.
|
🕵 The only CI red on |
…t-109339-vdimir/fix-materialized-postgresql-merge-final
|
🕵 Both CI reds on
AI review on |
When the nested ReplacingMergeTree of a MaterializedPostgreSQL table has no parts, its read adds no step, and readFinalFromNestedStorage added its own empty source with the nested table's physical columns as the header. Since ClickHouse#112382 the wrapper reports the nested table's support for subcolumns, so the analyzer reads `x.null` for `x IS NULL`, `count(x)` (optimize_functions_to_subcolumns) or an explicit `x.null`, and the planner failed with NOT_FOUND_COLUMN_IN_BLOCK because the header lacked it. Virtual columns such as `_part` failed the same way. Build the empty source from the requested columns with getSampleBlockForColumns, as IStorage::readFromPipe and the planner do for every other empty read. The requested list already contains the inputs of the row policy and of PREWHERE that addEmptySourceToQueryPlan applies on this header. Closes ClickHouse#128712 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resubmit of #109339 (reverted in #112381), plus the fix for the regression that caused the revert.
Reading a
MaterializedPostgreSQLdatabase throughMergenow reads with the forcedFINALand the_sign = 1filter, instead of hitting the nestedReplacingMergeTreetables directly and exposing stale and deleted row versions. The mapping from an enumerated table to theStorageMaterializedPostgreSQLwrapper it must be read through lives in a newIDatabase::getTableForRead, whose default implementation returns the enumerated storage unchanged;StorageMerge- the only consumer that reads data through the iterator - maps every enumerated table through it.getTablesIteratorkeeps exposing the physical nested tables together with their Atomic UUIDs, so generic introspection -system.tables.uuid,system.parts,ServerAsynchronousMetrics, backups - is unaffected.test_database_introspection_sees_nested_tablescovers that.The reverted version did that by walking
materialized_tables, which turned out to be guarded by two different mutexes: readers (tryGetTable, the enumeration path,getTablesForBackup) tooktables_mutex, while the writers (startSynchronization,attachTable,detachTablePermanently,stopReplication) tookhandler_mutexor nothing at all, and thematerialized_tables.empty()fast paths read the map completely unguarded. SoDROP DATABASE, whosestopReplicationcallsmaterialized_tables.clear(), destroyed the wrappers while another thread was still walking the map and dereferencing them. The mismatch predates #109339 but was only reachable from user queries; returning the wrappers fromgetTablesIteratorput it on theServerAsynchronousMetricspath, which enumerates the tables of every database once per second, so the window started being hit routinely. The sanitizer builds turn the report into an aborted server, which is why the failures showed up asConnection refusedfor every remaining test intest_postgresql_replica_database_engine:stderr.logedf159f61amd_tsan, 1/6heap-use-after-freeinshared_ptr<IStorage>::operator->fromgetTablesIteratore94e3689famd_tsan, 1/6data raceindyn_cast_get_derived_info(thedynamic_caston a wrapper being destroyed)5854921c2amd_tsan, 1/6heap-use-after-free, plus adata raceon the unguardedmaterialized_tables.empty()2253a27f5amd_msan, 1/8use-of-uninitialized-valueatDatabaseMaterializedPostgreSQL.cpp:553(storage->as<...>()->hasNested())Every report had the same pair of stacks:
ServerAsynchronousMetrics::updateImpl->DatabaseMaterializedPostgreSQL::getTablesIteratoragainstInterpreterDropQuery->DatabaseMaterializedPostgreSQL::stopReplication.The fix makes
tables_mutexthe only mutex that guards the map and marks itTSA_GUARDED_BY, so clang's thread-safety analysis rejects an unguarded access at compile time - reintroducing the original unguardedmaterialized_tables.empty()now fails the build with-Wthread-safety-analysis.handler_mutexis taken beforetables_mutexwhere both are needed, and nothing that can reach back intohandler_mutexor the base class mutex is called while holdingtables_mutex.The empty-map startup window is now handled as well: right after
CREATE/ATTACH DATABASEand after a server restart,materialized_tablesstays empty untilstartSynchronizationhas fetched the tables list from PostgreSQL and published the wrappers, andtryGetTable/getTableForReadused to fall back to the nested tables in that window - re-exposing stale and deleted row versions to user-facing reads until synchronization finished. Areplication_stoppedflag (guarded bytables_mutex) now distinguishes that window from the after-shutdown state, and while it lasts the nested tables are wrapped intoStorageMaterializedPostgreSQLon the fly, so reads keep the forcedFINALand the_sign = 1filter while the data replicated before the restart stays readable.test_reads_during_startup_window_use_finalholds the window open deterministically by pausing PostgreSQL across a ClickHouse restart.Also fixed along the way:
detachTablePermanentlyusedmaterialized_tables[table_name]for its existence check, which inserted an empty entry for an unknown name; that nullStoragePtrstayed in the map after the exception, so a latertryGetTablewould dereference it.DROP DATABASEhad one more way to race with startup:tryStartSynchronizationkeeps re-scheduling itself every 5 seconds until startup succeeds, andInterpreterDropQuerycallsstopReplicationlong beforeshutdowndeactivates the task, so a queued retry could re-enterstartSynchronizationand recreatereplication_handlerand the wrapper map while the tables were being flushed and dropped.stopReplicationnow deactivates the startup task first (before takinghandler_mutex, which the task body also locks).test_drop_database_cancels_startup_retriescovers it by restarting the server with PostgreSQL unreachable (so the retry loop is live and the nested tables exist), holdingDROP DATABASEopen on a pausable failpoint across several retry periods, and checking that no retry fires anymore.Added
test_drop_database_while_enumerating_tables, which readssystem.tablesand reads throughmergefrom four threads while creating and dropping the database in a loop, driving the same code path from the test instead of relying on the async metrics thread to hit it.Also fixed an endless loop on the null-storage path of
ReadFromMerge::getSelectedTables, which used tocontinuewithout advancing the iterator.StorageMergediscovers the capabilities and the statistics of its children through the very same enumeration that it reads through, so those checks now see theStorageMaterializedPostgreSQLwrapper too. The wrapper hands theSelectQueryInfoover to the nestedReplacingMergeTreeuntouched, so it now forwardssupportsPrewhere,canMoveConditionsToPrewhere,supportedPrewhereColumnsIncludeSubcolumns,supportsSubcolumns,supportsOptimizationToSubcolumns,getColumnSizesandtotalRows/totalBytesto the nested table - otherwiseMergeover aMaterializedPostgreSQLdatabase would silently losePREWHERE, the optimization to subcolumns and the size estimates. The forwarding also fixes those capabilities for a direct read of aMaterializedPostgreSQLtable, where the wrapper has always been the storage the query sees.supportsTrivialCountOptimizationis deliberately left at theIStoragedefault: the nested table still holds the deleted rows (_sign = 0) and the superseded versions of the updated rows, so counting its parts would report exactly the stale rows this PR removes from the read path.test_merge_keeps_child_table_capabilitiescovers thePREWHERE(including a subcolumn condition, whichStorageMergeadmits only when every child reportssupportedPrewhereColumnsIncludeSubcolumns), the size estimates and a direct subcolumn read through the wrapper.Related: #109339
Related: #112381
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Version info
26.8.1.851(included in26.8and later)