Skip to content

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

Merged
vdimir merged 11 commits into
masterfrom
revert-112381-revert-109339-vdimir/fix-materialized-postgresql-merge-final
Aug 5, 2026
Merged

vdimir merged 11 commits into
masterfrom
revert-112381-revert-109339-vdimir/fix-materialized-postgresql-merge-final

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

Resubmit of #109339 (reverted in #112381), plus the fix for the regression that caused the revert.

Reading a MaterializedPostgreSQL database through Merge now reads with the forced FINAL and the _sign = 1 filter, instead of hitting the nested ReplacingMergeTree tables directly and exposing stale and deleted row versions. The mapping from an enumerated table to the StorageMaterializedPostgreSQL wrapper it must be read through lives in a new IDatabase::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. getTablesIterator keeps 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_tables covers 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) took tables_mutex, while the writers (startSynchronization, attachTable, detachTablePermanently, stopReplication) took handler_mutex or nothing at all, and the materialized_tables.empty() fast paths read the map completely unguarded. So DROP DATABASE, whose stopReplication calls materialized_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 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. The sanitizer builds turn the report into an aborted server, which is why the failures showed up as Connection refused for every remaining test in test_postgresql_replica_database_engine:

Run Check stderr.log
edf159f61 amd_tsan, 1/6 heap-use-after-free in shared_ptr<IStorage>::operator-> from getTablesIterator
e94e3689f amd_tsan, 1/6 data race in dyn_cast_get_derived_info (the dynamic_cast on a wrapper being destroyed)
5854921c2 amd_tsan, 1/6 heap-use-after-free, plus a data race on the unguarded materialized_tables.empty()
2253a27f5 amd_msan, 1/8 use-of-uninitialized-value at DatabaseMaterializedPostgreSQL.cpp:553 (storage->as<...>()->hasNested())

Every report had the same pair of stacks: ServerAsynchronousMetrics::updateImpl -> DatabaseMaterializedPostgreSQL::getTablesIterator against InterpreterDropQuery -> DatabaseMaterializedPostgreSQL::stopReplication.

The fix makes tables_mutex the only mutex that guards the map and marks 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 nothing that can reach back into handler_mutex or the base class mutex is called while holding tables_mutex.

The empty-map startup window is now handled as well: right after CREATE / ATTACH DATABASE and after a server restart, materialized_tables stays empty until startSynchronization has fetched the tables list from PostgreSQL and published the wrappers, and tryGetTable / getTableForRead used to fall back to the nested tables in that window - re-exposing stale and deleted row versions to user-facing reads until synchronization finished. A replication_stopped flag (guarded by tables_mutex) now distinguishes that window from the after-shutdown state, and while it lasts the nested tables are wrapped into StorageMaterializedPostgreSQL on the fly, so reads keep the forced FINAL and the _sign = 1 filter while the data replicated before the restart stays readable. test_reads_during_startup_window_use_final holds the window open deterministically by pausing PostgreSQL across a ClickHouse restart.

Also fixed along the way: detachTablePermanently used materialized_tables[table_name] for its existence check, which inserted an empty entry for an unknown name; that null StoragePtr stayed in the map after the exception, so a later tryGetTable would dereference it.

DROP DATABASE had one more way to race with startup: tryStartSynchronization keeps re-scheduling itself every 5 seconds until startup succeeds, and InterpreterDropQuery calls stopReplication long before shutdown deactivates the task, so a queued retry could re-enter startSynchronization and recreate replication_handler and the wrapper map while the tables were being flushed and dropped. stopReplication now deactivates the startup task first (before taking handler_mutex, which the task body also locks). test_drop_database_cancels_startup_retries covers it by restarting the server with PostgreSQL unreachable (so the retry loop is live and the nested tables exist), holding DROP DATABASE open on a pausable failpoint across several retry periods, and checking that no retry fires anymore.

Added test_drop_database_while_enumerating_tables, which reads system.tables and reads through merge from 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 to continue without advancing the iterator.

StorageMerge discovers the capabilities and the statistics of its children through the very same enumeration that it reads through, so those checks now see the StorageMaterializedPostgreSQL wrapper too. The wrapper hands the SelectQueryInfo over to the nested ReplacingMergeTree untouched, so it now forwards supportsPrewhere, canMoveConditionsToPrewhere, supportedPrewhereColumnsIncludeSubcolumns, supportsSubcolumns, supportsOptimizationToSubcolumns, getColumnSizes and totalRows / totalBytes to the nested table - otherwise Merge over a MaterializedPostgreSQL database would silently lose PREWHERE, the optimization to subcolumns and the size estimates. The 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, so counting its parts would report exactly the stale rows this PR removes from the read path. test_merge_keeps_child_table_capabilities covers the PREWHERE (including a subcolumn condition, which StorageMerge admits only when every child reports supportedPrewhereColumnsIncludeSubcolumns), the size estimates and a direct subcolumn read through the wrapper.

Related: #109339
Related: #112381

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Version info

  • Merged into: 26.8.1.851 (included in 26.8 and later)

@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fe63ba9]

Summary: ✅


AI Review

Summary

This PR fixes the direct Merge/MaterializedPostgreSQL stale-row path and closes the reported races, but two gaps remain in the final head. The new getTableForRead contract does not survive proxy databases such as DatabaseOverlay, and the new backup fail-close check misclassifies a healthy zero-table database as "startup not finished". I cannot approve it as-is.

Findings

❌ Blockers

  • [src/Storages/StorageMerge.cpp:120] Merge only asks the top-level database to remap iterator entries. DatabaseOverlay::getTablesIterator flattens child tables under the overlay name, so merge() over an overlay that contains a MaterializedPostgreSQL child still reads the raw nested ReplacingMergeTree and exposes stale/deleted rows.
    Suggested fix: preserve the producing database across iteration, or resolve the source database from the enumerated storage before calling getTableForRead.

⚠️ Majors

  • [src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp:699-701] BACKUP DATABASE now fails forever after the last replicated table is detached, because materialized_tables.empty() is treated as "startup not finished" even though detachTablePermanently can legitimately leave a fully started database with zero tables.
    Suggested fix: track whether the initial table list has been populated separately from the current table count.
Tests
  • ⚠️ Add a focused regression covering Merge over a DatabaseOverlay child that points at a MaterializedPostgreSQL database, with an UPDATE/DELETE proving the wrapper mapping still applies through the proxy.
  • ⚠️ Add a BACKUP DATABASE regression for the "detach the last table, then back up the empty database" case.
Final Verdict

Request changes.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.70% -0.10%

Changed lines: Changed C/C++ lines covered: 103/141 (73.05%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Jul 29, 2026
`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.
@alexey-milovidov alexey-milovidov changed the title Revert "Revert "Fix stale and deleted rows when reading a MaterializedPostgreSQL database through Merge"" Fix stale and deleted rows when reading a MaterializedPostgreSQL database through Merge Jul 29, 2026
…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
@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 87/96 (90.62%) · Uncovered code

Full report · Diff report

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.
Comment thread src/Storages/StorageMerge.cpp Resolved
Comment thread tests/server.pid.txt Resolved
`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
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI failure on 57affb5b was Stress test (arm_release) with Logical error: Join is supported only for pipelines with one output port, got A and B, which is unrelated to this PR (its diff only touches src/Databases/PostgreSQL, src/Storages/PostgreSQL and StorageMerge's table enumeration - no JOIN pipeline code). It is a known full_sorting_merge JOIN sharding issue, with a fix already in progress in #109393.

Pushed e756068927d: the AI review's major (capabilities and statistics lost when Merge discovers its children through the wrapper) is addressed by forwarding them from StorageMaterializedPostgreSQL to the nested table, the stray tests/server.pid.txt is removed, and master is merged.

…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only CI red on e756068927d, AST fuzzer (amd_tsan) — Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1 on SELECT cume_dist() ... OVER (...) FROM remoteSecure(..., view(SELECT '' FROM numbers(65537))) ... — is unrelated to this PR: the query touches neither Merge nor MaterializedPostgreSQL. It is a window function over a remote read of a subquery projecting a constant, the same family as #103695, with a fix already in progress in #108045.

…t-109339-vdimir/fix-materialized-postgresql-merge-final
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both CI reds on ade7a152d84 are unrelated to this PR (its diff touches only src/Databases/PostgreSQL, src/Storages/PostgreSQL and StorageMerge table enumeration):

AI review on ade7a152d84 is ✅ Approve and there are no unresolved review threads.

@vdimir vdimir self-assigned this Aug 5, 2026
@vdimir
vdimir added this pull request to the merge queue Aug 5, 2026
Merged via the queue into master with commit 2c4490d Aug 5, 2026
180 checks passed
@vdimir
vdimir deleted the revert-112381-revert-109339-vdimir/fix-materialized-postgresql-merge-final branch August 5, 2026 16:09
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 5, 2026
rorylshanks pushed a commit to rorylshanks/ClickHouse that referenced this pull request Nov 4, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog 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.

3 participants