Skip to content

Reading existing row count for the LWD mutation part - #78271

Open
fhw12345 wants to merge 51 commits into
ClickHouse:masterfrom
fhw12345:read_existing_row_count
Open

fhw12345 wants to merge 51 commits into
ClickHouse:masterfrom
fhw12345:read_existing_row_count

Conversation

@fhw12345

@fhw12345 fhw12345 commented Mar 26, 2025 •

Copy link
Copy Markdown
Contributor

Lightweight deletes leave physical rows in a part and hide them with _row_exists. Metadata-only counting is currently disabled for these parts, even when an exact live-row count has already been calculated for merge-size estimation. Reuse that count through the implicit _minmax_count_projection so eligible SELECT count() FROM table queries do not need to scan the data or deletion masks.

The optimization is deliberately limited to ungrouped, argument-free count on lightweight-delete parts. It does not enable metadata answers for min, max, or count(expr), and it keeps the guard against granule-based counting over deletion masks. Filters must still be computable by the implicit projection; this is not a shortcut for arbitrary filtered counts.

To make the reused counts safe for query results:

  • Treat existing_rows_count as either exact or unknown (std::nullopt), rather than substituting the physical row count when it was not calculated.
  • Preserve or invalidate counts appropriately when loading, inserting, or mutating parts. Changing table settings alone does not make an old count exact.
  • Decline the optimization if any selected masked part has an unknown count.
  • Respect apply_deleted_mask = 0 by using physical row counts, and preserve empty-input semantics when all visible rows have been deleted.
  • Materialize constant/sparse mask columns before counting, and propagate mask-reading errors instead of treating an estimate as an exact answer.

The existing exclude_deleted_rows_for_part_size_in_merge setting enables counting during lightweight-delete mutations. Together with load_existing_rows_count_for_old_parts, it also enables calculating counts when loading existing parts; this can increase table-loading I/O. Implicit projection optimization must be enabled. No setting defaults or on-disk formats are changed.

Functional coverage includes Wide and Compact parts, deleted extrema, primary-key range filters, settings changes, mixed known/unknown counts, part reloads, row-removing mutations, empty inputs, and exceptions from count arguments. The focused 20,000-row test returns the same count (19999) while reducing read_rows from 20000 to 1 when exact live-row counts are available. This read-volume reduction was also verified with a PR CI binary in Docker; it is not an elapsed-time speedup claim.

Related: #47930
Related: #66699

Changelog category (leave one):

  • Performance Improvement

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

Speed up ungrouped count queries on MergeTree tables with lightweight deletes when exact live-row counts are available, by reusing those counts through implicit projections instead of scanning the parts.


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

@fhw12345

fhw12345 commented Mar 26, 2025 •

Copy link
Copy Markdown
Contributor Author

#47930 #66699
I think this PR can resolve the problem of slow count query to the LWD part data.

@bharatnc bharatnc added the can be tested Allows running workflows for external contributors label Mar 26, 2025
@clickhouse-gh

clickhouse-gh Bot commented Mar 26, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [20496dc]

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Mar 26, 2025
@CLAassistant

CLAassistant commented Mar 27, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@fhw12345
fhw12345 marked this pull request as draft March 27, 2025 08:18
@fhw12345
fhw12345 requested a review from amosbird March 27, 2025 10:40
@fhw12345
fhw12345 force-pushed the read_existing_row_count branch from 396b050 to b0fb1c5 Compare April 8, 2025 06:46
@fhw12345
fhw12345 marked this pull request as ready for review April 8, 2025 06:57
@fhw12345

Copy link
Copy Markdown
Contributor Author

Hi @KochetovNicolai, could you help review this PR thanks.
what this PR do:
Still can apply minmax projection on LWD part for the simple COUNT() query and return the existing row count rather than row count as the result.

@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ab689bc]

Summary: ✅


AI Review

Summary

This PR lets ungrouped, argument-free count queries reuse exact live-row counts through _minmax_count_projection after lightweight deletes. Counts remain unknown when they cannot be trusted, and the optimization respects deletion-mask settings and empty-input semantics. The previous argument-evaluation finding is fixed; the vertical-merge concern does not hold in the current code. No unresolved findings remain. All three added stateless tests pass in the CI report for head ab689bc4aca304ca23a9ef79e42af44f2f1eea68, including the asserted reduction in read_rows from 20000 to 1. No local build or test rerun was performed.

Final Verdict

Status: ✅ Approve

@abashkeev abashkeev added the comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). label Sep 3, 2026
Preserve unknown counts through part loading and mutations, respect `apply_deleted_mask`, and keep extrema and empty-input semantics correct.

Related: ClickHouse#78271
Preserve mutation-snapshot guards, aggregate matching, and projection diagnostics. Adapt `readRows` to the current `MutableColumns` interface while retaining exact-count validation.

Related: ClickHouse#78271
@clickhouse-gh clickhouse-gh Bot added comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). and removed comp-projections Projections: precomputed layouts for accelerating queries (projection parts, maintenance). labels Oct 8, 2026
Enable `optimize_use_projections` and `optimize_use_implicit_projections` explicitly so CI randomized settings cannot disable the optimization being asserted. Use exact query text in `system.query_log` to avoid matching the inspection queries and returning multiple rows from the scalar subquery.

Validated against the PR CI binary: both original failures reproduced; 41 post-fix runs passed, including 31 recorded CI setting combinations. One truncated combination could not be replayed; parallel-replica cases used a single-node loopback cluster.

Related: ClickHouse#78271

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=78271&sha=b31f98a09522dbd3274d7cdad3dcf0346f508b82&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29
Require empty aggregate arguments when relaxing the lightweight-delete projection guard. Preserve expression evaluation and exceptions for `count(expr)` without changing the existing non-lightweight-delete or granule-count paths.

Add functional coverage for `Wide` and `Compact` parts, throwing arguments, count normalization, `Nullable` values, and empty visible input. The unmodified new test exposes four missing exceptions on the pre-fix PR CI binary; scan-path controls match the reference. The new C++ restriction still requires CI build validation.

Related: ClickHouse#78271

Review: ClickHouse#78271 (comment)
Include the replacement of the remaining `FifoQueue` reference with `RequestQueue` and the updated serialization fuzzer setting. Preserve the lightweight-delete count optimization and its regression tests.

Related: ClickHouse#124798

Related: ClickHouse#78271

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=78271&sha=4be83ae0c641cc6ad1e9eb286f9f0f2a40bee698&name_0=PR&name_1=Build%20%28arm_tidy%2C%202%2F4%29
@clickhouse-gh

clickhouse-gh Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ab689bc4a with master 5e817c7b7 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

13 translation units recompiled, 118 s compile time in total, 13 of them have a recent master baseline.

Job report

Use three fixed 32-row granules and 80 rows for `Wide` parts, and 100 rows for the `Compact` part lifecycle checks. Preserve deleted extrema, exact-range boundaries, settings changes, reloads, and all forced projection assertions.

The recorded CI settings pass locally before and after the change. The reduced test passed three replays in 1.46-1.66 seconds; the original took 2.12 seconds. The 264.97-second CI timeout was not reproduced locally.

Related: ClickHouse#78271

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=78271&sha=6bdd5ab22238a2d8ae0e11967860d3e3297ff2a5&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29
Include the upstream rollback of the AWS SDK upgrade associated with the `aws_common_private_has_avx2` TSan reports. Preserve the count-projection fixes and reduced regression-test workload.

Related: ClickHouse#125030

Related: ClickHouse#78271

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=78271&sha=6bdd5ab22238a2d8ae0e11967860d3e3297ff2a5&name_0=PR&name_1=Integration%20tests%20%28amd_tsan%2C%20targeted%29
@fhw12345

Copy link
Copy Markdown
Contributor Author

🕵 Hi @alexey-milovidov, could you please review this PR, or suggest someone familiar with MergeTree projection optimization who could take a look? It speeds up bare count queries after lightweight deletes by reusing exact per-part live-row counts, with regression coverage for part lifecycle changes and argument evaluation. Thanks!

@fhw12345

Copy link
Copy Markdown
Contributor Author

🕵 Hi @KochetovNicolai, could you please review this PR, or point us to the right maintainer? It enables metadata-only bare count after lightweight deletes when exact per-part live-row counts are available, while preserving expression evaluation and the granule-count guard. Previous review feedback has been addressed, and the latest checks have no failures; CH Inc sync is still pending. The regression tests cover part lifecycle changes, settings changes, empty inputs, and throwing arguments. Thanks!

@clickhouse-gh clickhouse-gh Bot added comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. and removed comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). labels Oct 15, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
Adapt `readExistingRowsCount` to both mutable and shared `readRows` outputs, keeping mask-read errors explicit. Preserve the upstream storage-type-change guard together with deletion-mask invalidation when reusing `existing_rows_count`.

Related: ClickHouse#78271
@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements and removed pr-improvement Pull request with some product improvements labels Nov 4, 2026
Keep the upstream candidate list passed to `getAggregateProjectionCandidates`, including hypothetical projections for `EXPLAIN WHATIF`. Preserve the argument-free count restriction and lightweight-delete guards without rebuilding or shadowing that list.

Related: ClickHouse#78271
@fhw12345

Copy link
Copy Markdown
Contributor Author

🕵 Hi @CurtizJ, could you please review this PR? Thanks!

This branch has not been deployed

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

Labels

can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants