Skip to content

Fix stale and deleted rows when reading a MaterializedPostgreSQL database through Merge - #109339

Merged
vdimir merged 1 commit into
masterfrom
vdimir/fix-materialized-postgresql-merge-final
Jul 28, 2026
Merged

vdimir merged 1 commit into
masterfrom
vdimir/fix-materialized-postgresql-merge-final

Conversation

@vdimir

@vdimir vdimir commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

Requires: #108979

DatabaseMaterializedPostgreSQL::getTablesIterator returned the nested ReplacingMergeTree tables, so reads through a Merge table bypassed the StorageMaterializedPostgreSQL wrapper and lost both the _sign = 1 filter and the forced FINAL, exposing stale and deleted rows. Now the iterator returns the wrappers for non-internal queries, consistently with tryGetTable; internal queries and backups keep working on the nested tables.

Side effects: system.tables now shows the MaterializedPostgreSQL engine for these tables, and system.parts no longer lists their parts. The EXPLAIN assertions in the new test need the FINAL: 1 marker from #108979, so that PR should merge first.

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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 MaterializedPostgreSQL database through a Merge table.

@clickhouse-gh

clickhouse-gh Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [4772d7c]

Summary: ✅


AI Review

Summary

This PR changes DatabaseMaterializedPostgreSQL::getTablesIterator to return StorageMaterializedPostgreSQL wrappers so Merge / merge reads pick up the forced FINAL and the _sign = 1 filter. That fixes the steady-state read path, but the current implementation still regresses iterator-based operations that need the physical MergeTree storage, still leaves the stale-row bug reachable while the wrapper map is empty after restart/retry, and now drops table UUIDs from system.tables.

Findings

❌ Blockers

  • [src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:540-560] getTablesIterator no longer preserves the old physical-storage contract for iterator consumers. Database-wide/global commands such as SYSTEM STOP MERGES, SYSTEM START MERGES, all-tables SYSTEM LOAD PRIMARY KEY / SYSTEM UNLOAD PRIMARY KEY, and SYSTEM RESTART DISK iterate tables and then act on MergeTreeData or action locks. After this change they see StorageMaterializedPostgreSQL wrappers instead of the nested ReplacingMergeTree, so they silently skip these tables or no-op.
    Suggested fix: keep returning the physical nested storage for generic iterator users, or explicitly unwrap StorageMaterializedPostgreSQL in the iterator-based command paths that need the real MergeTree object while keeping read paths on the wrapper.
  • [src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:537-538] The materialized_tables.empty() fallback keeps the old wrong-read behavior alive during startup and retry windows. The backup code later in the same file already documents that right after CREATE DATABASE or a server restart the map can stay empty until startSynchronization finishes fetchRequiredTables, and it can remain empty while synchronization is failing and retrying. In that state a user Merge / merge query still enumerates the nested ReplacingMergeTree tables directly, so it bypasses FINAL and _sign = 1 and can still expose stale/deleted rows after restart.
    Suggested fix: do not treat every empty map as "use nested tables for user queries". Distinguish real shutdown/internal paths from "wrappers not populated yet", and fail closed or wait for wrappers in the latter case.

⚠️ Majors

  • [src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:560] Returning a plain DatabaseTablesSnapshotIterator drops the atomic iterator's uuid() override, so iterator->uuid() becomes UUIDHelpers::Nil. system.tables uses iterator->uuid(), which means these tables now report all-zero UUIDs.
    Suggested fix: preserve the nested table UUID in this iterator path, for example with a custom iterator override that returns StorageMaterializedPostgreSQL::getNestedStorageID().uuid.
Final Verdict
  • Status: ❌ Block
  • Keep the physical-storage iterator contract for non-read/system callers, or explicitly unwrap StorageMaterializedPostgreSQL in those iterator-based command paths.
  • Do not route user-facing Merge / merge enumeration to nested tables while materialized_tables is still empty during startup/retry.
  • Preserve stable nested-table UUIDs in the iterator path so system.tables.uuid stays correct.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 3, 2026
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

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.

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::startStopActionInDatabase now adds the action lock to the wrapper, so database-wide/global SYSTEM STOP/START MERGES no longer reaches the table that actually performs background merges.
  • StorageSystemPartsBase, StorageSystemMutations, and ServerAsynchronousMetrics all dynamic_cast the iterator result to MergeTreeData; after this change they silently skip these tables, which is why system.parts disappears 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?

@kssenii kssenii self-assigned this Jul 6, 2026
…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]>
@vdimir
vdimir force-pushed the vdimir/fix-materialized-postgresql-merge-final branch from 99039fd to 4772d7c Compare July 9, 2026 16:27
/// 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())

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.

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());

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.

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.

@clickhouse-gh

clickhouse-gh Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.80% 85.80% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 11/12 (91.67%) · Uncovered code

Full report · Diff report

@vdimir
vdimir requested a review from kssenii July 13, 2026 10:15
@clickhouse-gh

clickhouse-gh Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 37 queries analysed

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.

clickbench

⚠️ 6 inconclusive

Flagged queries (6 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 12 not_sure 296 266 -10.1% <0.0001 This PR only changes MaterializedPostgreSQL table enumeration; ClickBench Q12 never runs that path, so the -10.1% is run-to-run variance, not a PR effect.
⚠️ 13 not_sure 490 420 -14.4% <0.0001 The changed code (MaterializedPostgreSQL iterator/backup) is off Q13's execution path, so this -14.4% delta is noise rather than a real improvement.
⚠️ 18 not_sure 1418 1299 -8.4% 0.0031 Already not_sure with mixed signals from the two tests; the PR does not touch Q18's path, so the -8.4% is not attributable to this change.
⚠️ 32 not_sure 1460 1301 -10.9% 0.0001 Borderline with mixed test signals; the MaterializedPostgreSQL-only diff cannot plausibly move Q32, so treat the -10.9% as variance.
⚠️ 33 not_sure 1645 1248 -24.1% <0.0001 The diff only affects MaterializedPostgreSQL enumeration/backup, which Q33 never exercises, so this -24.1% is off-path variance and not a PR-driven improvement.
⚠️ 34 not_sure 1512 1231 -18.6% <0.0001 Same off-path reasoning: Q34 does not run the changed MaterializedPostgreSQL code, so the -18.6% is run-to-run variance rather than a real gain.

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
  • StressHouse run: f912f409-5b50-42dc-b8f1-0fe896ed47a1
  • MIRAI run: d31323f1-4a9a-44f3-a5c5-d26e9e3c154b
  • PR check IDs:
    • clickbench_576723_1785184858
    • clickbench_576730_1785184858
    • clickbench_576741_1785184858
    • tpch_adapted_1_official_576753_1785184858
    • tpch_adapted_1_official_576765_1785184858
    • tpch_adapted_1_official_576790_1785184858

@vdimir
vdimir added this pull request to the merge queue Jul 28, 2026
Merged via the queue into master with commit 47f99a8 Jul 28, 2026
176 checks passed
@vdimir
vdimir deleted the vdimir/fix-materialized-postgresql-merge-final branch July 28, 2026 14:02
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 28, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

Why this was reverted (#112381) and what the actual defect was

Resubmitted as #112382 with the fix. Recording the investigation here so the analysis is on the original PR.

Symptom

test_postgresql_replica_database_engine went red on master starting 2026-07-28 ~19:00 UTC, with 4, 33, 54 and 6 failing tests across four runs. Almost every individual failure read:

E   helpers.client.QueryRuntimeException: Client failed! Return code: 210, stderr:
    Code: 210. DB::NetException: Connection refused (172.16.2.5:9000). (NETWORK_ERROR)

That is the cascade, not the cause. base/base/sanitizer_options.h sets halt_on_error=1 abort_on_error=1 for both TSan (:55) and MSan (:21), so the first sanitizer report aborts the server and every remaining test in the module then fails against a dead process. One run was instead observed as a 300 s SOCKET_TIMEOUT inside Connection::receiveHello — the server was still in the middle of dumping core.

Root cause: materialized_tables was guarded by two different mutexes

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.

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

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants