Repository navigation
Fix count() being multiplied by the number of replicas inside a transaction - #116365
Conversation
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.
|
Workflow [PR], commit [2109d31] Summary: ✅
AI ReviewSummaryThis 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 Findings❌ Blockers
|
| 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
The test verifies that the set of parts visible to the transaction is used when the trivial count optimization is applied inside a transaction.
Build profile diff (arm_release)Commit See the job log for details. |
|
@groeneai investigate the logical error in the stress test |
|
Not from this PR. It is a master regression from #116128, and @ Michicosun already has a fix open in #116531. The failure. The query belongs to master's Why it is not yours. Mechanism. A streaming read round builds two independent 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. |
| 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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())) |
There was a problem hiding this comment.
I am a bit confused, why !query_context here with transaction? Does no query_context mean non-tx?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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 ....
There was a problem hiding this comment.
- 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.
MergeTreeData::supportsTrivialCountOptimizationdeclines the trivial count optimization if there are lightweight deletes, socount()behaves correctly in both cases.
…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]>
Problem
SELECT count()inside a transaction returned N times the real value when parallel replicaswere enabled, where N is the number of participating replicas.
applyTrivialCountIfPossibledeclined the trivial count optimization whenever a transaction wasopen, because
MergeTreemaintains its row counter over Active parts while a transaction needs thecount 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(), andMergingAggregatedStepsummed the per-replica partial states withnothing to deduplicate them.
applyTrivialCountWithSparsityFilterIfPossible, which servescount() WHERE <predicate>from theper-column
num_defaultscounter, 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::totalRowssumsrows_countovergetVisibleDataPartsVectorwhen a transactionis open, and keeps the O(1) atomic counter otherwise.
MergeTreeData::getColumnDefaultnessStatsUnavailableReasonno longer refuses outright on an opentransaction:
getActivePartsForColumnDefaultnessStatsalready returns snapshot-visible parts forstorages that support transactions. It still refuses for storages that do not.
StorageReplicatedMergeTree::totalRowsreturnsstd::nulloptinside a transaction, sinceforeachActivePartscannot restrict itself to a snapshot and the engine does not supporttransactions 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
applyTrivialCountIfPossibleandapplyTrivialCountWithSparsityFilterIfPossiblewhich 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_rowsis snapshot-aware inside a transaction forMergeTree, andNULLinside a transaction for
ReplicatedMergeTree.open.
getColumnDefaultnessStatsUnavailableReason.Testing
Two stateless tests, both using the
parallel_replicas_wait_for_unused_replicasfailpoint. Withoutit 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):
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
26.10.1.716-master(included in26.10and later)