Skip to content

Fix count() being multiplied by the number of replicas inside a transaction - #116365

Merged
alexey-milovidov merged 16 commits into
masterfrom
fix-transactional-count-duplicate-with-replicas
Sep 26, 2026
Merged

alexey-milovidov merged 16 commits into
masterfrom
fix-transactional-count-duplicate-with-replicas

Conversation

@kirillshokhin

@kirillshokhin kirillshokhin commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

SELECT count() inside a transaction returned N times the real value when parallel replicas
were enabled, where N is the number of participating replicas.

applyTrivialCountIfPossible declined the trivial count optimization whenever a transaction was
open, because MergeTree maintains its row counter over Active parts while a transaction needs the
count over its own snapshot, which may still include Outdated parts. That decline happened before
the block that disables parallel replicas, so the query was still distributed. A follower has no
transaction of its own — the TID is not part of the query protocol — so it passed the same check,
answered from totalRows(), and MergingAggregatedStep summed the per-replica partial states with
nothing to deduplicate them.

applyTrivialCountWithSparsityFilterIfPossible, which serves count() WHERE <predicate> from the
per-column num_defaults counter, had the same ordering and the same consequence.

Approach

Instead of rejecting the trivial count optimization inside a transaction, make it behave correctly with respect to the parts visible to the transaction.

  • StorageMergeTree::totalRows sums rows_count over getVisibleDataPartsVector when a transaction
    is open, and keeps the O(1) atomic counter otherwise.
  • MergeTreeData::getColumnDefaultnessStatsUnavailableReason no longer refuses outright on an open
    transaction: getActivePartsForColumnDefaultnessStats already returns snapshot-visible parts for
    storages that support transactions. It still refuses for storages that do not.
  • StorageReplicatedMergeTree::totalRows returns std::nullopt inside a transaction, since
    foreachActiveParts cannot restrict itself to a snapshot and the engine does not support
    transactions anyway.

This allows the initiator to apply the trivial count optimization and not involve the followers at all.

As a defensive measure, additional check added to both applyTrivialCountIfPossible and applyTrivialCountWithSparsityFilterIfPossible which rejects the trivial count optimization on the followers. The rationale is that the follower should wait for the specific set of parts to be assigned by the initiator before serving the request.

Side effects

  • count() inside a transaction is now served from part metadata instead of a full read.
  • system.tables.total_rows is snapshot-aware inside a transaction for MergeTree, and NULL
    inside a transaction for ReplicatedMergeTree.
  • Cascades optimizer row estimates become O(parts) rather than an atomic load while a transaction is
    open.
  • Removed a dead static overload of getColumnDefaultnessStatsUnavailableReason.

Testing

Two stateless tests, both using the parallel_replicas_wait_for_unused_replicas failpoint. Without
it the duplication may be hidden by a race: a follower that takes the shortcut never
announces to the coordinator, so once the initiator's local plan has claimed every mark range the
coordinator cancels the unused replicas and may discard their answers before they are consumed.
The failpoint skips registering that cancellation callback, which makes the duplication
deterministic.

Related: #115442

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):

Fixed SELECT count() returning a value multiplied by the number of replicas when executed inside a transaction with parallel replicas enabled. Trivial count optimization now is not rejected inside a transaction, so it's executed solely on the initiator. Followers no longer apply the trivial count optimization during the query planning, which previously caused each of them to independently answer with the total row count read from the table's metadata whenever the query reached them.


Workflow [PR]
Sync PR [sync-upstream/pr/116365]

Version info

  • Merged into: 26.10.1.716-master (included in 26.10 and later)

1. MergeTree::totalRows now is transaction-aware, so returns correct
   number of rows visible to the current transaction if there's any. It
   allows not to propagate the query to followers, which resulted into
   duplication of the result.
2. As a consequence `system.tables.total_rows` is now snapshot-aware as
   well, which is arguably another fix. It will also report NULL for
   ReplicatedMergeTree inside a transaction.
3. Followers do not apply trivial count optimization right-away, though
   defer it to the read phase, where they do know the exact set of parts
   to count rows in.
4. ReplicatedStorageMergeTree is unchanged since it does not support
   transaction. `return nullopt;` is added as a defensive check if
   it is still called inside a transaction.
…ctional queries

1. Followers do not apply the optimization.
2. `getColumnDefaultnessStatsUnavailableReason` rejects transactions
   only if they are not supported by the storage.
3. Ongoing transaction does not reject the trivial count optimization
   anymore, so in the parallel replica setup it's handled by the
   initiator.
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2109d31]

Summary: ✅


AI Review

Summary

This PR fixes the parallel-replica duplication bug by making the trivial-count metadata paths transaction-aware and by blocking follower-side rewrites. The duplication issue itself looks addressed, but the new totalRows implementation still leaves one transactional correctness hole around lightweight deletes / delete patches, and it also keeps a non-transactional O(parts) regression that the current discussion did not resolve.

Findings
❌ Blockers
  • [src/Storages/StorageMergeTree.cpp:388] The new transactional totalRows path sums part->rows_count over the snapshot-visible regular parts, but a transaction can also see row removals through a lightweight delete mask or a visible delete patch. In that case system.tables.total_rows (and any other transactional caller of totalRows) still reports the pre-delete row count even though this PR now treats totalRows as the snapshot-aware source of truth. Suggested fix: if the visible snapshot carries lightweight deletes / delete patches, return std::nullopt instead of a stale count, or derive the total from the post-delete row counts; add a regression that checks system.tables.total_rows inside a transaction after DELETE.
⚠️ Majors
  • [src/Storages/StorageMergeTree.cpp:393-395] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116365#discussion_r4054378893] The non-transactional branch now re-sums every active regular part on every call. That makes ordinary trivial count(), system.tables.total_rows, and Cascades row estimation O(parts) even when there is no transaction and no patch/delete state to justify it. The reply explains why the old atomic counter is wrong once patch parts exist, but it does not justify regressing the common no-patch case. Suggested fix: keep the scan for transactional / patched tables, but restore the atomic fast path when the active set has no patch parts or lightweight delete state.
Final Verdict

Changes requested.

LLVM Coverage Report

Measured on commit 2109d31.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 36/50 (72.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 25, 2026
The test verifies that the set of parts visible to the transaction is used
when the trivial count optimization is applied inside a transaction.
@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 2109d31d54b4e1f6f64828e779cbed28b765c6f2 was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@kirillshokhin

Copy link
Copy Markdown
Contributor Author

@groeneai investigate the logical error in the stress test

@groeneai

Copy link
Copy Markdown
Collaborator

Not from this PR. It is a master regression from #116128, and @ Michicosun already has a fix open in #116531.

The failure. Stress test (arm_tsan), 2026-08-26 18:09:32, query cf780685-c3e9-4be0-8eed-7645a04e2774, server abort (signal 6) on the assertion:

Logical error: 'The metadata stream of AlignStreams ended before all data stream rows were matched'
15. src/Storages/MergeTree/Streaming/ReadingPlan/AlignStreams.cpp:333
16. src/Processors/Executors/ExecutionThreadContext.cpp:128

Report

The query belongs to master's 05042_streaming_queries_watermark_filter_push_down, not to your 05042_transactional_count_duplicate, and it ran with max_rows_to_read = 100000 and read_overflow_mode = 'break' (Stress randomizes both; ast_fuzzer_runs = 0 on it, so that is the real query text).

Why it is not yours. AlignStreams.cpp is a new file added by #116128 (merged 2026-08-26 08:46:40Z). It does not exist at your head cf5db72f, nor at your merge base 34a01adf (2026-08-25 16:36Z). The binary that aborted was built from CI's merge commit 9feced7b ("Merge cf5db72 into d33f211"), where that file's blob is byte-identical to master's, so the whole aligner came in from master. Your diff touches totalRows and the two trivial-count call sites, nothing in the streaming read path.

Mechanism. A streaming read round builds two independent ReadFromMergeTree plans from one SelectQueryInfo (buildReadRoundPipeline.cpp:158 data, :186 metadata). makeStreamingSelectQueryInfo resets prewhere, filter, trivial_limit and order, but not storage_limits, so the break-mode read limit is installed on the sources of both branches. The branches read different column sets, so they cancel at unrelated row boundaries, the metadata stream stops being a superset of the data stream, and the aligner reports it. #116531 clears info.storage_limits there, clears the round's sort limits, and rejects read limits for streaming queries outright.

Breadth. 4 occurrences in CIDB, all on 2026-08-26, on 4 distinct heads and 4 different Stress arms (arm_release, arm_debug, arm_tsan, arm_msan), 0 in the preceding 13 days. The master one: report.

So nothing to do here beyond rebasing once #116531 lands. Separate and minor: #116128 also landed tests numbered 05042 and 05043, so those two numbers are now duplicated in the merge with yours.

@tuanpach tuanpach self-assigned this Aug 31, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
Comment thread src/Storages/StorageMergeTree.cpp Outdated
UInt64 res = 0;
/// `local_context` should not be nullptr, but still preserve the non-transaction-aware behavior in case there's code that
/// relies on it.
const auto txn = local_context ? local_context->getCurrentTransaction() : nullptr;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think splitting into 2 cases: non-tx and tx would be cleaner.

if (local_context && local_context->getCurrentTransaction()) {
    // Handle tx case

}
else 
{
    // Handle non-tx case
}

So we don't need is_visible and states. In non-tx case, we don't need to check if (is_visible(part)) for each part.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The intention was to avoid the vector building overhead for both cases. I agree that the separate branches look cleaner, so I've made the split in b5fc0ac.

I also think that it may be worth adding a common helper function to iterate over the visible set of parts, WDYT?
E.g. StorageMergeTree::totalBytes could benefit from it, since it also seems to lack the transaction-aware branch and there may be other such places.

I'd do it as a separate change, though.

std::optional<UInt64> StorageReplicatedMergeTree::totalRows(ContextPtr query_context) const
{
/// Transactions are not supported for ReplicatedMergeTree.
if (unlikely(!query_context || query_context->getCurrentTransaction()))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am a bit confused, why !query_context here with transaction? Does no query_context mean non-tx?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The query_context should never be nullptr here, so it's more of a defensive check than transaction-related behavior.

I've made the contract explicit in b5fc0ac and updated the only call site passing nullptr to pass the actual context pointer. That branch is gated with a type cast and never dereferences the pointer, so there was no issue either.

Split transactional and non-transactional case into two separate
branches.

Also assert on the query context being non-nullptr.
SET automatic_parallel_replicas_mode = 0;
SET enable_parallel_replicas = 1, max_parallel_replicas = 3, cluster_for_parallel_replicas = 'parallel_replicas',
parallel_replicas_for_non_replicated_merge_tree = 1, parallel_replicas_local_plan = 1;
SET parallel_replicas_only_with_analyzer = 0; -- necessary for CI runs with the old analyzer

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 is the only new old-analyzer coverage in the PR, but it still exercises only the plain totalRows() case (SELECT count() with no WHERE). The change in InterpreterSelectQuery::getTrivialCount also re-enables the old-analyzer totalRowsByPartitionPredicate() path inside a transaction, and that exact branch already needed the follow-up ReplicatedMergeTree guard added in this PR. Because 05043 is tagged no-old-analyzer, nothing here fails if the transactional partition-predicate path regresses again. Please add an enable_analyzer = 0 case such as SELECT count() FROM ... WHERE _partition_id = '...' (or another partition-only predicate) with parallel_replicas_only_with_analyzer = 0 and throw_on_unsupported_query_inside_transaction = 0 so that path is covered too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The old analyzer is deprecated and will be removed soon, so no regressions added to cover these codepaths.

else
{
auto lock = readLockParts();
for (const auto & part : getDataPartsStateRange(DataPartState::Active, MergeTreePartInfo::Kind::Regular))

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.

The transactional branch needs to walk the visible parts, but the non-transactional branch used to stay on the total_active_size_rows atomic. Re-summing every active part here makes ordinary SELECT count(), system.tables.total_rows, and the Cascades row estimators O(parts) again for every non-transactional read, which is a noticeable regression on fragmented tables unrelated to the transactional fix. Please keep the snapshot-aware branch, but restore the non-transactional path to getTotalActiveSizeInRows().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using the cached values is incorrect here, since it includes rows from the patch parts as well. See 8009242

res += part->rows_count;
if (local_context->getCurrentTransaction())
{
for (const auto & part : getVisibleDataPartsVector(local_context))

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.

totalRows() is now the transactional source of truth for system.tables.total_rows, but this branch still sums part->rows_count. Transactional lightweight DELETE is supported, and MergeTree readers apply _row_exists masks at read time while parts separately track existing_rows_count specifically for the post-delete row count. In a transaction that sees a lightweight delete mask or a visible delete patch, system.tables.total_rows (and any other caller of totalRows()) will still overcount deleted rows even though this PR now advertises snapshot-aware totals.

Please either return std::nullopt whenever the visible snapshot carries lightweight deletes / delete patches, or derive the count from the post-delete row count (existing_rows_count / the visible delete mask) and add a regression such as BEGIN TRANSACTION; DELETE ...; SELECT total_rows FROM system.tables ....

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. The behavior is the same for the transactional and non-transactional cases. I'd leave discussing and changing this behavior out of scope for this PR.
  2. MergeTreeData::supportsTrivialCountOptimization declines the trivial count optimization if there are lightweight deletes, so count() behaves correctly in both cases.

@alexey-milovidov alexey-milovidov self-assigned this Sep 26, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 26, 2026
Merged via the queue into master with commit 3349a04 Sep 26, 2026
177 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-transactional-count-duplicate-with-replicas branch September 26, 2026 01:51
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 26, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 27, 2026
…ss check

`MergeTreeData::getColumnDefaultnessStatsUnavailableReason(query_context,
mutations_snapshot)` was removed by ClickHouse#116365, which had no caller for it on
master; `readsColumnsWithoutTransformations` was its only caller, so the merge
of master broke the build (`Fast test`, `Build (arm_tidy)`).

Its checks are inlined: refuse on an active transaction, and on patch parts,
data mutations or alter mutations in the captured snapshot. The transaction
check stays unconditional. The remaining live check now skips it for storages
that support transactions, so calling that one alone would make the pass fuse
inside a transaction on a plain MergeTree, which it refused before. The pass's
admissibility is unchanged.

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

comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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.

5 participants