Repository navigation
Fix stale and deleted rows when reading a MaterializedPostgreSQL database through Merge - #109339
Conversation
|
Workflow [PR], commit [4772d7c] Summary: ✅
AI ReviewSummaryThis PR changes Findings❌ Blockers
Final Verdict
|
| if (local_context->isInternalQuery() || materialized_tables.empty()) | ||
| return DatabaseAtomic::getTablesIterator(StorageMaterializedPostgreSQL::makeNestedTableContext(local_context), filter_by_table_name, skip_not_loaded); | ||
|
|
||
| /// For user-facing enumeration return the StorageMaterializedPostgreSQL wrappers, consistently |
There was a problem hiding this comment.
This changes the contract of getTablesIterator for every non-internal caller, not just StorageMerge: they now see a StorageMaterializedPostgreSQL wrapper instead of the physical nested ReplacingMergeTree.
That breaks a bunch of iterator-based paths that expect to operate on the real MergeTree storage. For example:
InterpreterSystemQuery::startStopActionInDatabasenow adds the action lock to the wrapper, so database-wide/globalSYSTEM STOP/START MERGESno longer reaches the table that actually performs background merges.StorageSystemPartsBase,StorageSystemMutations, andServerAsynchronousMetricsalldynamic_castthe iterator result toMergeTreeData; after this change they silently skip these tables, which is whysystem.partsdisappears and bytes/rows/parts metrics stop counting them.
Can we keep the generic iterator returning the nested table and fix StorageMerge/the merge table function more locally, or otherwise teach the generic iterator path to preserve the existing physical-storage contract for these callers?
…r for user queries Consumers reading data through the database tables iterator (e.g. Merge tables and the merge table function) used to get the nested ReplacingMergeTree tables directly, without the _sign = 1 filter and the forced FINAL, exposing stale and deleted row versions. Return the StorageMaterializedPostgreSQL wrappers for non-internal queries, consistently with tryGetTable. Backups keep enumerating the nested tables through the nested context. Co-Authored-By: Claude Fable 5 <[email protected]>
99039fd to
4772d7c
Compare
| /// Internal queries (replication machinery, DDL, backups) work on the nested ReplacingMergeTree | ||
| /// tables directly. If materialized_tables is empty, all access goes to the nested tables as | ||
| /// well - it is the case after replication_handler was shutdown (see tryGetTable). | ||
| if (local_context->isInternalQuery() || materialized_tables.empty()) |
There was a problem hiding this comment.
materialized_tables.empty() is not just the shutdown case. The new backup check a few lines below already documents that after CREATE DATABASE or a server restart the map stays empty until startSynchronization finishes fetchRequiredTables, and it can stay empty while synchronization is failing and retrying.
With this fallback, a user Merge / merge read in that window still goes through DatabaseAtomic::getTablesIterator(StorageMaterializedPostgreSQL::makeNestedTableContext(...)), so it enumerates the nested ReplacingMergeTree tables directly and bypasses both the _sign = 1 filter and the forced FINAL. In other words, the stale/deleted-row bug this PR is fixing is still reproducible right after restart or during retry loops.
Can we distinguish the real shutdown path from the "wrappers not populated yet" path here, and fail closed or wait for the wrappers instead of treating every empty map as nested-table mode for user queries?
| } | ||
| } | ||
|
|
||
| return std::make_unique<DatabaseTablesSnapshotIterator>(std::move(tables), getDatabaseName()); |
There was a problem hiding this comment.
Returning a plain DatabaseTablesSnapshotIterator here drops the atomic iterator's uuid() override, so this path falls back to IDatabaseTablesIterator::uuid() == UUIDHelpers::Nil.
system.tables reads iterator->uuid() rather than table->getStorageID().uuid, which means every MaterializedPostgreSQL table in a database now reports an all-zero UUID. That is a user-visible metadata regression for any tooling that keys off the stable Atomic UUID.
If we want to return wrapper storages here, the iterator still needs to preserve the nested table UUIDs, for example by overriding uuid() with StorageMaterializedPostgreSQL::getNestedStorageID().uuid.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 11/12 (91.67%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: Release-transition baseline: compared against the last 26.7 master because no 26.8 master baseline exists at or before the trusted base-commit anchor. This PR only changes DatabaseMaterializedPostgreSQL's getTablesIterator and getTablesForBackup so that Merge over a MaterializedPostgreSQL database reads through the FINAL/_sign wrappers; it does not touch the query-execution hot path that ClickBench or TPC-H exercise. Every flagged improvement (Q12, Q13, Q33, Q34) sits off the changed code path, so I downgraded them to not_sure — the consistent-looking negative deltas are run-to-run variance, not a PR effect. Q15's -12.0% was already correctly suppressed as within master's current variance band, and Q18/Q32 remain borderline with mixed test signals. Net: no credible perf change attributable to this diff. clickbenchFlagged queries (6 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
Why this was reverted (#112381) and what the actual defect wasResubmitted as #112382 with the fix. Recording the investigation here so the analysis is on the original PR. Symptom
That is the cascade, not the cause. Root cause:
|
| Access | Location | Lock actually held |
|---|---|---|
materialized_tables[table_name] = storage |
startSynchronization |
handler_mutex |
materialized_tables.empty() |
tryGetTable |
none |
materialized_tables.find(name) |
tryGetTable |
tables_mutex |
| iterate | getFormattedTablesList |
none |
materialized_tables[table_name] = storage |
attachTable |
none |
materialized_tables[table_name] (inserts!) |
detachTablePermanently |
none |
materialized_tables.erase |
detachTablePermanently |
handler_mutex |
materialized_tables.clear() |
stopReplication |
handler_mutex |
materialized_tables.empty() |
getTablesIterator |
none |
iterate + hasNested() |
getTablesIterator |
tables_mutex |
iterate + hasNested() |
getTablesForBackup |
tables_mutex |
DROP DATABASE reaches stopReplication, which does materialized_tables.clear() under handler_mutex — freeing the StorageMaterializedPostgreSQL wrappers while a reader holding only tables_mutex is walking the map and calling storage->as<StorageMaterializedPostgreSQL>()->hasNested() on them.
Why this PR made it fire
The mismatch is old — tryGetTable has had it for years — but it was only reachable from user queries against a MaterializedPostgreSQL database that was concurrently being dropped, so nobody hit it. Replacing the one-line delegation in getTablesIterator with a walk over materialized_tables put it on the ServerAsynchronousMetrics::updateImpl path, which enumerates the tables of every database once per second. That is what turned a theoretical window into one hit routinely.
Evidence
Four master runs, three distinct sanitizer signatures, one defect:
| Commit | Check | stderr.log verdict |
|---|---|---|
edf159f617d 19:08 |
amd_tsan, 1/6 |
heap-use-after-free in shared_ptr<IStorage>::operator-> |
e94e3689ff7 19:17 |
amd_tsan, 1/6 |
data race in dyn_cast_get_derived_info (the dynamic_cast on a wrapper mid-destruction) |
5854921c25b 20:25 |
amd_tsan, 1/6 |
heap-use-after-free + data race on __tree::size (the unguarded empty()) |
2253a27f55a 23:05 |
amd_msan, 1/8 |
use-of-uninitialized-value at DatabaseMaterializedPostgreSQL.cpp:553 |
Every one of them has the same pair of stacks — reader:
#1 DB::DatabaseMaterializedPostgreSQL::getTablesIterator(...)
#2 DB::ServerAsynchronousMetrics::updateImpl(...)
#3 DB::AsynchronousMetrics::update(...) src/Common/AsynchronousMetrics.cpp:2582
#4 DB::AsynchronousMetrics::run() src/Common/AsynchronousMetrics.cpp:465
and writer:
#9 DB::DatabaseMaterializedPostgreSQL::stopReplication() .../DatabaseMaterializedPostgreSQL.cpp:510
#10 DB::InterpreterDropQuery::executeToDatabaseImpl(...) src/Interpreters/InterpreterDropQuery.cpp:492
#16 DB::TCPHandler::runImpl() src/Server/TCPHandler.cpp:899
The MSan run pinpoints the exact dereference:
SUMMARY: MemorySanitizer: use-of-uninitialized-value
src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:553:17
in DB::DatabaseMaterializedPostgreSQL::getTablesIterator(...)
Member fields were destroyed
#1 DB::StorageMaterializedPostgreSQL::~StorageMaterializedPostgreSQL()
#13 DB::DatabaseMaterializedPostgreSQL::stopReplication() ...:510
Onset matches exactly: all four failing commits contain 47f99a8b8f0 (this PR's merge, 13:16 UTC); the last clean run before them, b05161aa67d on 07-27, does not. Its single test_detach_table_with_pending_buffer failure on amd_cfi is unrelated.
Blast radius in the first ten hours: those 4 master runs plus ~22 PR CI runs on amd_tsan / amd_msan / amd_asan_ubsan — #112156 with 46 failures, #111399 with 42, #109225 with 40, and so on.
The fix in #112382
tables_mutex becomes the single owner of materialized_tables, annotated TSA_GUARDED_BY, so clang's thread-safety analysis proves the coverage rather than leaving it to review. Reintroducing the original unguarded read now fails the build:
error: reading variable 'materialized_tables' requires holding mutex 'tables_mutex'
[-Werror,-Wthread-safety-analysis]
587 | if (!local_context->isInternalQuery() || materialized_tables.empty())
| ^
note: guarded_by declared here
109 | std::map<std::string, StoragePtr> materialized_tables TSA_GUARDED_BY(tables_mutex);
handler_mutex is taken before tables_mutex where both are needed, and no call that can re-enter handler_mutex or the base class mutex happens while tables_mutex is held — startSynchronization builds the wrappers into a local map and publishes it with one locked assignment, attachTable runs its InterpreterAlterQuery outside the lock, and stopReplication swaps the map out under the lock and destroys the wrappers after releasing it.
Two more things came out of it: detachTablePermanently used materialized_tables[table_name] for its existence check, which inserted an empty entry for an unknown name and left that null StoragePtr in the map after throwing, so a later tryGetTable would dereference it. And the behaviour of getTablesIterator/tryGetTable is otherwise unchanged — the emptiness fast path still falls through to DatabaseAtomic, just decided under the lock.
The resubmit also adds test_drop_database_while_enumerating_tables, which reads system.tables from four threads while creating and dropping the database in a loop, so the path is driven from the test rather than depending on the async metrics thread to land in the window.
Requires: #108979
DatabaseMaterializedPostgreSQL::getTablesIteratorreturned the nestedReplacingMergeTreetables, so reads through aMergetable bypassed theStorageMaterializedPostgreSQLwrapper and lost both the_sign = 1filter and the forcedFINAL, exposing stale and deleted rows. Now the iterator returns the wrappers for non-internal queries, consistently withtryGetTable; internal queries and backups keep working on the nested tables.Side effects:
system.tablesnow shows theMaterializedPostgreSQLengine for these tables, andsystem.partsno longer lists their parts. TheEXPLAINassertions in the new test need theFINAL: 1marker from #108979, so that PR should merge first.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fix stale and deleted rows appearing when reading tables of a
MaterializedPostgreSQLdatabase through aMergetable.