Skip to content

[4.2-dev] Speed up cold COUNT(*) after bulk updates and deletes - #33295

Merged
mergify[bot] merged 9 commits into
matrixorigin:4.2-devfrom
ck89119:issue-33274-4.2-dev
Nov 27, 2026
Merged

mergify[bot] merged 9 commits into
matrixorigin:4.2-devfrom
ck89119:issue-33274-4.2-dev

Conversation

@ck89119

@ck89119 ck89119 commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Related to #33274.

What this PR does / why we need it:

After a bulk update or delete, COUNT(*) consults tombstones to determine which rows are visible. Two changes reduce the cost of that read on 4.2-dev.

  • Size regular UPDATE and DELETE flushes by the bytes retained for writing. Reserve the block-level deletion workspace once per contiguous block-ID run. In the scaled workload, the resulting layout reduced the number of tombstone objects visible to COUNT from 220 to 9.
  • Backport bounded asynchronous disk cache publication from fix(fileservice): harden disk cache async update lifecycle #27368 and the directory cleanup fix from fix(fileservice): serialize disk cache directory cleanup #27840. The cache owns a copy of each queued range. For a whole file, the caller finishes the source read before handing sync and publication to the worker. This takes disk sync off the foreground read path while preserving source errors and handling cancellation, deletion and shutdown.

Cold COUNT on the same snapshots. Each cell shows median elapsed time and object-store GET requests across three fresh MatrixOne instances with empty local caches. The main binary is the revision used in the issue, f5fa451732.

Snapshot 4.2-dev reader before backport 4.2-dev reader with backport nightly main reader
220 tombstone objects 6.441 s / 458 GETs 4.007 s / 458 GETs 3.088 s / 554 GETs
9 tombstone objects 1.071 s / 30 GETs 0.595 s / 30 GETs 0.409 s / 27 GETs

On the original layout, the cache backport cut cold COUNT latency by 38% at the same median GET count. With the original reader, changing the layout reduced median GETs from 458 to 30. Small-layout timings varied across batches on the shared host. Validation on the billion-row nightly workload remains pending.

Validation

  • All 54 COUNT queries returned 5,237,637. Each of the 18 runs returned the same SUM of 2,621,524,317. A separate SQL transaction verified read-after-update, read-after-delete and rollback.
  • Ran the full multi_update package tests. For the cache backport, ran full tests with and without -race for fileservice, fileservice/fifocache and util/metric/v2.
  • Changed-statement coverage was 22/23 for the writer change and 695/735 for the cache change. Targeted go vet and golangci-lint checks passed.

Adapt main matrixorigin#27368 and its directory cleanup fix matrixorigin#27840 to 4.2-dev. Transfer range bytes or a staged full file to the cache worker, fence admitted publications across deletion and shutdown, and preserve the branch's read and upload contracts.
Drain disk cache publication on every S3FS close while allowing active shared decoders to retire memory later. Preserve successful buffered reads on late cache cancellation, fetch prefixed objects by their canonical key, and wait for disk publication before asserting a cache hit.
@XuPeng-SH

XuPeng-SH commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 55ca5b3fac144997c614d462a3b475967d29b28a

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

mo-bot review · mo-bot-local · review

Commit: 55ca5b3fac144997c614d462a3b475967d29b28a

Assessment: request_changes

The backport reuses FIFO eviction and per-block delete accounting to reduce foreground cache synchronization and produce larger DML batches. Full-file cache staging, however, is bounded only by job count and can consume far more disk space than the configured cache capacity.

Model: gpt-6.1-terra / max

Session: 01a2179b-7a0e-7812-94c2-dc2707e03412 · slot 0 · generation 18

  • P2 pkg/fileservice/disk_cache.go:802: Default asynchronous S3 reads, writes, or prefetches stage distinct full objects while the single finalizer is delayed in file.Sync.
    Impact: Up to 64 complete temporary files can accumulate outside FIFO capacity accounting. Even sequential prefetches can consume many times the configured cache size and exhaust the volume, affecting other filesystem operations.
    Evidence: The caller copies the whole object before this handoff and then returns. tryReserveAsyncFileFinalize in disk_cache_async.go reserves a slot but no disk bytes, and the file is counted only after finalizeFile publishes it. A barrier-controlled S3FS.PrefetchFile probe staged 4 MiB in a 1 MiB cache while indexed usage remained zero; see cache-public-tests.log and checks/1795714881247793264-3.json. The base waits for each call's sync before returning. Bound staged full-file bytes against a disk budget, with cleanup on cancellation and failure, so deferred publication cannot accumulate uncontrolled temporary data.

Validation:

  • Private /tmp and loopback preflight passed: preflight.log and checks/1795714103295320587-3.json.

  • The fifocache package tests passed: fifo-test-public-proxy.log and checks/1795714593102177109-3.json.

  • Focused fileservice lifecycle tests and the public prefetch probe passed, both normally and under the race detector: cache-public-tests.log, cache-race.log, checks/1795714881247793264-3.json, and checks/1795714988696231015-3.json.

  • Three focused multi_update tests covering block-run credits, admission, and projected-byte flushing passed: dml-tests.log and checks/1795715010132174812-3.json.

  • git diff --check passed: diff-check.log and checks/1795714513991591295-3.json. Discussion assessment covers all three indexed keys.

Limitations:

  • The prefetch probe used disk-backed test object storage and an injected blocked sync; it did not exhaust a physical device or exercise a remote S3 service.

  • The initial FIFO test timed out while using the configured module proxy; it passed after dependency acquisition was retried through the standard Go proxy.

  • Full fileservice and multi_update suites and the reported cold COUNT measurements were not independently rerun. The PR describes the billion-row workload as pending.

  • A separate active-reader/directory-reuse probe exposed a cache eviction interaction, but the base has the same read reindexing and eviction behavior, so it is not reported as a regression.

@XuPeng-SH

XuPeng-SH commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: 41d70579b06c15b223d48685ca64c17830e2fc0c

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

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.

mo-bot review · mo-bot-local · review

Commit: 41d70579b06c15b223d48685ca64c17830e2fc0c

Assessment: approve

The prior unbounded full-file staging concern is resolved by capacity-based reservations and cleanup when a source exceeds the budget. The backport reuses FIFO eviction and adds bounded worker and path-ownership state to move cache synchronization off the foreground path. The DML changes retain the existing memory-admission mechanism. No actionable defect remains in the reviewed scope.

Model: gpt-6.1-terra / max

Session: 01a21a72-1486-7ab1-8684-6ee66672b7e4 · slot 0 · generation 20

Validation:

  • Private temporary-directory and loopback preflight passed; see preflight.log and checks/1795751304062238383-5.json.

  • The FIFO eviction lifecycle test passed; see fifo-focused.log and checks/1795751506301804206-5.json.

  • The full-file staging and S3 prefetch capacity tests passed; see staging-focused.log and checks/1795751599578767695-5.json.

  • Five focused staging, deletion, close-publication and callback tests passed under the race detector; see cache-lifecycle-race.log and checks/1795751867177107857-5.json.

  • The frozen evidence reports successful x86 unit-test and pessimistic multi-CN BVT CI jobs for the assigned head.

Limitations:

  • The author reports that validation on the billion-row workload is pending; the reported scaled COUNT measurements were not independently repeated.

  • The S3 prefetch check used disk-backed object storage rather than a remote S3 service.

  • The bodies of the linked earlier backport PRs were not supplied; the changed ownership and lifecycle paths were assessed from the assigned source and evidence.

@mergify mergify Bot added the queued label Nov 27, 2026
@mergify

mergify Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into 4.2-dev as b2460f5 at 04:05 UTC

Less than a minute in the queue, with no time running CI.

So far

  • ✅ Entered the queue Fri 27 Nov, 04:05 · rule release-4.2 · triggered by rule Automatic queue on approval for release-4.2
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged 04:05 · b2460f5 · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

@mergify
mergify Bot merged commit b2460f5 into matrixorigin:4.2-dev Nov 27, 2026
33 checks passed
@mergify mergify Bot removed the queued label Nov 27, 2026
@ck89119
ck89119 deleted the issue-33274-4.2-dev branch November 27, 2026 04:05
XuPeng-SH pushed a commit that referenced this pull request Nov 27, 2026
…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.

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/enhancement size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants