Repository navigation
Reduce tombstone-heavy COUNT reads and prefer cache-local execution - #33293
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
gouhongshen
left a comment
There was a problem hiding this comment.
Codex automated review
Reviewed origin/main...d3418c8 in full. No prior reviews or inline comments existed on the PR, so no findings were deduplicated. The new sealed-block COUNT computes block-header rows minus visibly-deleted rows through the same LocalDisttaeDataSource.GetTombstones call the ordinary reader uses, and leaves appendable, memory, or unrecognized blocks in a remaining RelData for the normal reader; since the ordinary reader applies per-row commit-timestamp filtering only for appendable blocks, the two agree by construction for every block this path counts. The cache-placement change probes at most three remote CNs with one deterministic sample, shares a 100 ms budget, and reverts to the original placement on any inconclusive result; old CNs reject CmdMethod_CountCachedObjectFiles with a 'not supported' error that demotes safely to the fallback, and the merge-scope wrap keeps partial-count merge and final projection on the coordinator. Startup resource accounting is attached to the scan owner, deep-copied by CloneForExport, and cleared on reuse (directly asserted in the new tests). I found no correctness, compatibility, concurrency, resource-handling, or unhappy-path defect. Two independently testable changed packages passed: go test -v ./pkg/sql/schedule/... ./pkg/pb/query/... (exit 0). Every other changed package (pkg/sql/compile, pkg/vm/engine/disttae, pkg/objectio, pkg/fileservice, pkg/cnservice, pkg/sql/colexec/table_scan, pkg/vm/process, pkg/sql/models) transitively depends on pkg/common/malloc, whose build fails with 'jemalloc.h' file not found because the prebuilt thirdparties/install artifacts (make cgo / make -C thirdparties) are absent from this checkout; per review constraints I did not build or install those prerequisites, so the PR's own focused-test claims could not be re-executed here. That is a verification limitation, not a defect attributed to the PR. Two non-blocking observations are reported.
P2 - One failed cache probe aborts the whole COUNT placement decision (pkg/sql/compile/starcount_cache_placement.go:226)
In bestStarCountCacheWorker, the first probe result with !r.ok (or a hits value outside [0, sampleSize]) returns not-found immediately, so a single unresponsive, draining, or old-version CN among the up-to-three probed targets makes every heavy COUNT(*) keep its original placement even when the other probed CNs reported strictly more whole-object disk-cache hits than the local CN. During a rolling upgrade old CNs answer CmdMethod_CountCachedObjectFiles with 'not supported: 47 not support in current version', so any cluster whose first eligible target is an old CN loses cache routing entirely until the upgrade finishes. The fallback keeps the original behavior, so result correctness is unaffected; treating a failed probe as a non-candidate and deciding on the workers that did answer (when at least one outscored the local CN) would preserve locality through upgrades.
P2 - The new heavy-tombstone COUNT path is never exercised by the distributed SQL regression (test/distributed/cases/disttae/count_sealed_blocks.sql:6)
The sealed-block count and the cache-placement sampler only trigger when the tombstone estimate exceeds defaultStarCountTombstoneThreshold (pkg/sql/compile/scope.go:1834, 5,000,000 rows), and the cache-placement sampler applies the same threshold via minRows. The tables in count_sealed_blocks.sql hold a handful of rows, so every SELECT COUNT(*) in this distributed case exercises only the pre-existing rel.StarCount fast path; the new CountSealedBlocks branch (block-header rows minus visible tombstones, partial merge-group results, remaining-range reader) and the remote discovery path are not covered by this BVT at all, and coverage currently rests on the unit tests plus the author's local 6.28M-tombstone fixture. Making the threshold overridable (a session variable, GUC, or env knob consumed by both the estimate gate and the sampler) would let the distributed suite drive the new branch end to end, including on multi-CN setups.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: d3418c8c1d050dacf2118470226f8798a9199cd0
Assessment: request_changes
The sealed-count path reuses existing metadata and tombstone handling, and the bounded cache-sampling design is reasonable. Changes are needed for probe cancellation, resource attribution, and maintained coverage of the new SQL and multi-CN paths. The prior reviewer's concern that the SQL case misses the optimized path remains valid; conservative fallback on a failed cache probe is acceptable under the supported shutdown-only upgrade policy.
Model: gpt-6.1-terra / max
Session: 01a2172e-434d-7533-8bcf-86e4c749a300 · slot 1 · generation 20
-
P2
pkg/sql/compile/starcount_cache_placement.go:178: An eligible heavy COUNT probes a CN while the shared query RPC writer is stalled on an earlier write.
Impact: The placement caller returns when its 100 ms context expires, but a probe goroutine can remain blocked until the queued write completes. Repeated queries can retain goroutines, futures, and request buffers during the stall.
Evidence: The query client uses an unowned morpc future, whose waitSendCompleted waits for writtenC without selecting on cancellation. The controlled probe in rpc-cancel-probe-retry.log exercised the real placement worker, query client, and Future.Get: the default request remained blocked after cancellation, while an owned-request control exited. Make probe requests cancellation-safe while preserving request ownership until the writer is finished. -
P2
pkg/vm/engine/disttae/count_sealed_blocks.go:104: A sealed-block count performs CPU work while collecting and applying tombstones.
Impact: The entire operation is recorded as filesystem wait, so the new startup interval understates active CPU and overstates filesystem wait. When the canonical resource summary is used, this also understates the CPU-priced component of statement CU.
Evidence: GetTombstones includes in-memory and workspace deletion processing as well as persisted-object processing; MeasureWait requires CPU work to remain outside its blocking boundary. In cpu-wait-probe.log, a CPU-only fake datasource spent about 35 ms in the real count path and that interval was recorded as filesystem wait. Attribute only actual storage blocking to filesystem wait, retaining CPU work as active time. -
P2
test/distributed/cases/disttae/count_sealed_blocks.sql:7: The maintained SQL case inserts only three rows and never approaches the more-than-5,000,000 committed-tombstone threshold used by the new sealed-count and cache-placement paths.
Impact: The case exercises the existing StarCount path, leaving the new public SQL result and successful remote-routing integration without a maintained regression oracle. This is a validation gap, not a demonstrated wrong query result.
Evidence: scope.go:1862 and starcount_cache_placement.go:121 apply the threshold. The pinned testing contract requires public-path proof for SQL behavior and relevant-topology coverage for multi-CN routing. Reviewer-only lowered-threshold SQL probes passed, including a forced remote winner, but are not maintained tests. Add small, controllable maintained coverage that reaches the sealed-count path with remaining rows and transaction visibility, plus a deterministic successful multi-CN selection; a test-only control is sufficient.
Validation:
-
Artifacts and receipts are under /mnt/nvme/mo-bot-55-live/state/jobs/a312bac7122773daa630f92d/attempt-1.
-
Private-runtime preflight passed: preflight.log and checks/1795700005803678213-2.json.
-
Focused sealed-count, visibility, placement, cache RPC, and resource tests passed: focused-tests.log and checks/1795700407678182381-2.json.
-
Selected placement and scan-accounting race tests passed: race-tests.log and checks/1795700962641438063-2.json.
-
A lowered-threshold SQL overlay reached the sealed-count path and matched an independent aggregate across transaction cases: count-sql-probe.log and checks/1795700454523478289-2.json.
-
A two-CN SQL overlay with forced cache hints passed for a committed in-memory row and a writable-transaction local control: remote-inmem-probe.log and checks/1795701654616788626-2.json.
-
Controlled CPU-attribution and queued-RPC cancellation probes passed: cpu-wait-probe.log with checks/1795700543175491103-2.json, and rpc-cancel-probe-retry.log with checks/1795701270593803896-2.json.
-
The frozen patch, clean source fingerprint, and native-input provenance were audited: source-audit.log and checks/1795700708725230903-2.json.
Limitations:
-
The SQL and two-CN probes used review-only overlays to lower the threshold and control cache hints; they do not replace maintained BVT coverage or establish production-scale performance.
-
An initial forced-hint two-CN probe did not select a remote worker before its fixture deadline; a traced retry and a deterministic local-miss variant passed. The PR's reported benchmark was not independently reproduced.
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: 4d92ac888aa530890530b40f2c64a08060deb304
Assessment: approve
The COUNT optimization reuses the existing tombstone reader and cache owners, with bounded cache probing and a conservative placement fallback. The earlier concerns about RPC cancellation, filesystem-wait attribution, and maintained heavy-count and multi-CN coverage are resolved. The failed-probe fallback remains an acceptable tradeoff.
Model: gpt-6.1-terra / max
Session: 01a2172e-434d-7533-8bcf-86e4c749a300 · slot 1 · generation 20
Validation:
-
Private-runtime preflight and native-input provenance checks passed.
-
Focused RPC, fileservice, objectio, planner, engine, runtime, and accounting tests passed; selected cancellation and ownership tests also passed under the race detector.
-
The maintained two-CN SQL test passed, including a remote cache winner, sealed and in-memory rows, a writable transaction, and rollback.
-
Review-only SQL-shape and prepared-statement probes passed across committed changes.
-
Commands, source fingerprints, exits, and retained logs are reconciled in attempt-1/validation-reconciliation.json.
Limitations:
-
The reported large-data performance measurements used an earlier build and were not independently repeated after the follow-up changes.
-
The small distributed SQL case alone does not cross the production tombstone threshold; the maintained two-CN test uses a scoped test threshold to exercise the new paths.
✅ Merged into
|
…xecution (#33307) ## What type of PR is this? - [ ] API-change - [ ] BUG - [x] Improvement - [ ] Documentation - [ ] Feature - [ ] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to #33274. Backports #33293 to 4.2-dev. ## What this PR does / why we need it: When a heavy, unfiltered COUNT falls back to a per-block scan, sealed blocks can be counted from their metadata and the distinct deleted rows visible to the transaction. This avoids loading ordinary columns just to count surviving rows. The existing reader handles the other ranges. A cold CN can run the scan on an eligible CN that has more of the sampled tombstone objects in its whole-file disk cache. Light queries skip peer discovery for cache probes. Sampling, node discovery and probing share a 100 ms budget. An inconclusive probe keeps the existing placement. Plans that need coordinator state, such as FOUND_ROWS() or a named-lock function, also keep their original placement. The backport uses the 4.2 snapshot admission path, FIFO cache index and scheduler. The optional RPC uses the same wire identifiers as main. The original eleven commits retain their cherry-pick references. This PR is independent of the write-path and asynchronous-cache changes in #33295. ### Design revision 1 This 4.2-dev backport addresses #33274. Both optimizations must return the row count that an ordinary scan would see in the same transaction. [Implementation at 20c80f4](20c80f4) **Where the scan runs.** The coordinator considers moving an otherwise local, single-table scalar count only when the transaction workspace is read-only and the plan can run remotely. Queries with uncommitted writes or coordinator-only expressions keep their original placement. The coordinator samples committed tombstone objects visible at the transaction snapshot. A selected peer restores the shipped transaction snapshot, waits for its local logtail, opens the relation and owns the complete scan. Final projection and output remain on the coordinator. [Scan placement](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/sql/compile/scan_scheduler.go#L50-L71) · [Snapshot restoration](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/txn/client/client.go#L772-L800) **How the rows add up.** For an unfiltered, ungrouped count, the existing fast path applies up to 5,000,000 estimated committed tombstone rows. Above that threshold, a singleton scope that owns the matching scan and aggregate can count sealed blocks from metadata. For each supported block, DistTAE reads the exact header row count and subtracts distinct, visible deleted offsets using the ordinary data source and the statement’s transaction offset. Memory, appendable and other ineligible ranges stay with the reader. Only after all sealed-block reads succeed does the scope replace the input ranges and give their subtotal to its `MergeGroup`, which adds the remaining reader’s count once. An unsupported relation retains its existing execution path. A read error or cancellation discards the unfinished subtotal. [Sealed-block count](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/vm/engine/disttae/count_sealed_blocks.go#L27-L117) · [Aggregate handoff](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/sql/compile/scope.go#L1645-L1693) **What a cache probe owns.** After ordinary snapshot admission, sampling, cache lookups and peer discovery share a 100 ms deadline. For a heavy count the coordinator compares at most 16 sampled object IDs against the whole-file disk-cache index on the local CN and up to three eligible peers. A unique best score above the local score wins. A tie for best, a missing reply, a busy or unsupported peer, or an expired probe budget keeps the original placement. Query cancellation propagates. Each query client allows one outstanding write per peer address for these probes. Before enqueue, the client recycles a rejected request and releases any slot it acquired. After enqueue, the writer owns both until the write completes, fails or is skipped. The caller can stop waiting as soon as its context expires. [Selection](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/sql/compile/starcount_cache_placement.go#L145-L269) · [Request ownership](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/queryservice/client/query_client.go#L120-L153) **What happens if the selected CN fails.** Once the scheduler selects a peer, the ordinary remote pipeline owns execution. Connection, send, execution and receive failures use its cleanup and error path. A peer failure does not trigger a local rerun or reuse a partial count. Only the existing statement retry policy can start a fresh execution attempt. The optional internal RPC uses the same method and request/response field numbers as main (47, 49 and 50). Cache eviction after a probe can cost extra reads, but transaction visibility still determines the result. [Remote execution](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/sql/compile/remoterunClient.go#L70-L117) · [Retry policy](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/sql/compile/compile.go#L575-L583) **Acceptance.** The mixed-range SQL regression checks two sealed rows plus three workspace rows against an ordinary scan. The blocked-writer regression cancels one probe and verifies that 16 further probes to the same peer leave the queue bounded. The two-CN measurements below check placement and object-store reads on the same data. [SQL regression](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/tests/issues/isolated/starcount/starcount_sealed_blocks_test.go#L100-L160) · [Blocked-writer regression](https://github.com/matrixorigin/matrixone/blob/20c80f4171bd74c085497b3356a27b37b00ab93c/pkg/queryservice/client/query_client_test.go#L170-L249) Local design review accepted revision 1 for this backport. **Local verification on 4.2-dev** Two CNs used separate local caches and the same MinIO bucket. The fixture had 6,291,456 source rows and 6,285,165 visible rows after updates and deletion. The table reports median COUNT latency across three runs per case. Both CNs restarted for each measurement with A's warm disk cache restored and B's cache empty. The billion-row nightly workload was not run. | SQL entry point | 4.2-dev baseline | With backport | | --- | ---: | ---: | | Cold CN B | 4,987.0 ms | 584.6 ms | | Warm CN A | 1,118.4 ms | 1,008.2 ms | For cold ingress, shared object-store reads across both CNs fell from 79.2 MiB to 3.7 KiB. Scan metrics confirmed that B placed the eligible COUNT on A. - Validated HAVING with FOUND_ROWS and IS_FREE_LOCK, two light table counts, and read-your-writes against an ordinary scan. Both scans returned 6,285,166 inside the transaction. Rolling it back restored 6,285,165. - Focused unit tests passed using the repository CGo wrapper and Go 1.26.4. The SQL regression passed all 21 checks with mo-tester. Unit and instrumented SQL tests covered 412 of 488 changed executable Go lines (84.4%) and 350 of 409 changed Go statements (85.6%). - Ran incremental go vet and golangci-lint on the changed packages.
What type of PR is this?
Which issue(s) this PR fixes:
Related to #33274. This PR addresses the COUNT latency observed on main.
What this PR does / why we need it:
A table-wide UPDATE can leave millions of tombstones. When the existing COUNT fast path exceeds its threshold, the reader can load an ordinary data column just to get the surviving row count. A scan running on a different CN from the preceding write can also fetch tombstones that another CN already has on disk.
For a sealed block, the new count reads the row count from the block header and subtracts distinct deleted rows visible to the transaction. The ordinary reader handles the remaining ranges. The scan owns cancellation and resource accounting for these reads.
For a heavy, single-table COUNT, the planner samples visible tombstone object IDs and compares whole-object disk-cache hits on eligible CNs. It moves the scan only when a single remote CN has more hits. Light counts skip remote discovery. Snapshot admission uses the normal query context. Sampling, node discovery and cache probes share a 100 ms timeout. An inconclusive result keeps the original scan placement. Queries that require coordinator session state keep their existing execution path.
Local performance
Two CNs had separate disk caches and shared one MinIO bucket. The same snapshot contained 6,285,165 visible rows after updates and a delete, with 6,366,952 estimated tombstone rows. Each measurement restarted both CNs, restored A's warm disk cache, emptied B's cache and used an established SQL connection. The table shows median elapsed time in milliseconds over three interleaved rounds following one calibration round. The combined build was d73896b.
On cold ingress, CN object-storage reads fell from 78.9 MiB to 9.8 KiB with both changes. Scan metrics confirmed that both placement variants executed on A. On warm ingress A, the sealed-block change alone had the lowest median. Adding cache placement increased that median by 21 ms. A normal reader supplied the reference row count, including a transaction with two inserts, one delete and a rollback. The timings above use the local fixture. The billion-row nightly timing remains a separate measurement.
Validation