Skip to content

perf(disttae): bound in-transaction point-read cost by the probed key - #30685

Merged
mergify[bot] merged 5 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26796-0d9ccb10
Oct 21, 2026
Merged

mergify[bot] merged 5 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-26796-0d9ccb10

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Oct 20, 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 #26796

Design review gate (required before implementation approval)

Review 5593891733
classified this change as design-mandatory under the repository's
feature-design-review contract:
the change introduces a transaction-lifetime exact-key index (a stateful
cache with hydration, invalidation and charge/refund lifecycle) on the
workspace read hot path, and the 647 changed non-generated production
lines also exceed the 500-line default size trigger.

  • Design document, exact reviewed revision (rev 1):
    docs/design/20261021-disttae-workspace-point-read-bounding.md,
    added in commit 3a758d8ffd88e416b3a0e220d75fd94a25babdf1. It records the gate record, the invariant set,
    ownership and lifecycle, memory bounds and accounting, the hot-path cost
    model including ordinary workloads, alternatives, compatibility, the
    validation mapping, and an approval record for this design review.
  • Implementation approval stays blocked until the design review passes, per
    the contract. Design review is requested on this PR.

What this PR does / why we need it:

Problem

Inside one long transaction, every statement's transaction-local read
(filterInMemUnCommittedInserts) ran MemPKFilter.FilterVector over
every workspace insert batch, re-encoding all accumulated rows per
read — even when the batch's primary-key column could not possibly
contain the probed key. Because statement-boundary merging packs
shuffled keys into large fat batches, the batch-level min/max envelope
defeats range-only pruning, so the per-statement cost grows with the
in-transaction modification count (quadratic in total over the
transaction). Measured at base eb18dbfa03 with the workload recorded
in the issue: 1,000-statement window medians grow 3.628x late/early
over a 30k single-transaction point-update run, and
MemPKFilter.FilterVector occupies 31.06% cumulative CPU in a
mid-transaction profile.

Change

  1. pkg/vm/engine/readutil/pk_filter_mem.go,
    pkg/vm/engine/readutil/filter_util.go: keep an encoded-primary-key
    envelope per insert batch (written once at write time, kept through
    its lifecycle); add a lazily hydrated, budget-charged exact-key
    index per batch. The read gate now applies only to single-column
    EQUAL primary-key probes on a batch without attached membership
    filters; anything else (composite/serial keys, non-EQUAL
    predicates, disjunctions, prefix ops, membership filters) keeps the
    original unpruned path, fail-closed.
  2. pkg/vm/engine/disttae/local_disttae_datasource.go: probe
    workspace insert batches through the envelope skip and the exact
    index before falling back to the full-vector filter.
  3. pkg/vm/engine/disttae/txn.go, txn.go, txn_table.go,
    types.go: make the index's ownership and lifecycle sound —
    • unaccountInsertKeyOffsetsLocked centralizes refund + map drop,
      used by every terminal path (commit finalization, rollback, merge
      destination and source, shrink, release, dump-drop, ALTER
      transfer), so a hydrated index is charged exactly once and
      refunded exactly once;
    • transferWorkspaceWritesForAlterLocked moves the ALTER
      writes-transfer loop and resets the duplicate's key index
      ownership so it re-hydrates under its own charge;
    • clearVacatedWriteSlots clears retired entries from the vacated
      backing-array tail at all four compaction sites; the commit-time
      dumpAll compaction now clears through the original full-length
      slice (the previously used prefix-shortened append target panicked
      index out of range when a DROP/TRUNCATE hole was retained below
      the merge gate);
    • inMemEntryDataSize counts batch + index bytes for
      scanInMemInsertSize and dumpInsertTableSelectionLocked, so the
      dump gate, quota arithmetic, and per-table selection see the same
      bytes the budget charges;
    • zero-row entries fail closed instead of hydrating an empty
      charged index.
  4. Tests: 13 focused unit tests +
    test/distributed/cases/disttae/disttae_filters/issue_26796_long_txn_point_updates
    BVT case.

Issue-to-test proof

Behavior Test (RED at base → GREEN with fix)
Per-statement point-read work stays bounded as the workspace grows TestIssue26796PointReadWorkStaysBounded, TestIssue26796WorkspaceMaintenanceWorkBounded (base: 64 / 512 / 400 rows encoded vs bound 8)
Statement-boundary cost stays constant TestIssue26796WorkspaceMergingBoundsEntryCount (base: fails at first statement)
Pruning preserves read semantics; gate fail-closed TestIssue26796PruningKeepsReadSemantics, TestIssue26796MembershipFilterGatesExactProbePath, TestIssue26796EnvelopeWrittenOnceAndKeptByLifecycle
Index charged once, refunded once, dropped on every terminal path TestIssue26796KeyIndexLifecycle, TestIssue26796KeyIndexMemoryAccounting, TestIssue26796TeardownClearsKeyIndexesWithDebugAccounting (RED: debug-accounting panic at commit/rollback)
ALTER transfer never clones ownership TestIssue26796AlterTransferResetsKeyIndexOwnership (RED: workspace accounting mismatch 604 per 888)
Compactions leave no retired batch/map reachable TestIssue26796WorkspaceCompactionClearsRetiredIndexSlots (RED: vacated slot 29 holds retired batch)
Commit dump with retained hole cannot panic TestIssue26796DumpAllClearsVacatedSlotsThroughFullSlice (RED: index out of range [1] with length 1)
Spill sizing sees hydrated index bytes TestIssue26796SpillSizingSeesHydratedKeyIndexBytes (RED: batch-only numbers 0x14e vs 0xa0)
SQL-visible behavior unchanged BVT case replay 328/328 at 100%

Test commands and outcomes

  • Unit: GOEXPERIMENT=simd CGO_CFLAGS="-I$ROOT/cgo -I$ROOT/thirdparties/install/include" go test -run 'Issue26796' -v -count=1 ./pkg/vm/engine/disttae → 13/13 PASS, exit 0; package
    suites disttae, disttae/cache, disttae/logtailreplay,
    disttae/route, disttae/sidecar, readutil all ok; gofmt
    and go vet clean.
  • BVT: mo-tester comparison replay of the added case directory →
    TOTAL 328, SUCCESS 328, FAILED 0, rate 100%, verdict this test succeed.
  • Live benchmark (frozen instance of this tree): 10,000 parameterized
    single-row pk UPDATEs in one transaction over a 10,000-row table
    with two unique keys — window medians 0.81–1.70ms with no growth
    trend (late/early ratios 1.040 / 1.111 across recorded runs), COMMIT
    0.13–0.20s, exact post-commit validation
    (count/distinct/sum/bad = 10000/10000/10000/10000/0); 30s
    mid-transaction CPU profile: FilterVector and MemPKFilter absent
    from the cumulative report vs 31.06% at base.

Residual risks

  • Predicates outside the read gate deliberately keep the unpruned
    FilterVector path for correctness.
  • Spill decisions now include index bytes: a workspace already near
    the threshold may spill slightly earlier (intended consequence of
    honest accounting; exercised live with identical validation and
    commit latency).
  • Draft PR refactor(disttae): redesign CN transaction workspace #27013 (workspace redesign, 113 files) overlaps this area
    and may textually conflict on Entry fields, the read gate, and the
    compaction/transfer helpers.

In one long transaction, every statement's transaction-local read ran
MemPKFilter.FilterVector over every workspace insert batch, re-encoding
all accumulated rows per read even when the batch could not contain the
probed key. Statement-boundary merging packs shuffled keys into fat
batches whose min/max envelopes defeat range-only pruning, so the cost
of a single-row pk UPDATE statement grows with the in-transaction
modification count. Measured at the base: 3.628x late/early latency
growth over a 30k-statement single-transaction workload, FilterVector
at 31.06 percent cumulative in the CPU profile.

Add an encoded-primary-key envelope per insert batch (written once,
kept through the lifecycle) plus a lazily hydrated, budget-charged
exact-key index per batch. A transaction-local point read can then skip
whole batches by envelope or resolve them through the exact index
instead of re-encoding the full batch. Predicates outside the gate
(non-EQUAL preds, serial or composite keys, membership filters,
disjunctions, prefix ops) keep the unpruned path, fail-closed.

Ownership and lifecycle invariants enforced and tested by this change:

- each hydrated index charges the workspace budget exactly once and is
  refunded exactly once on every terminal path (commit finalization,
  rollback, merge destination and source, shrink, release, dump-drop,
  ALTER transfer), centralized in unaccountInsertKeyOffsetsLocked
- the ALTER writes-transfer duplicate re-hydrates under its own
  ownership and never clones a charged map
- forward compactions clear the vacated backing-array slots through
  the original full-length slice so retired batches and refunded maps
  stay unreachable; clearing through the commit dumpAll compaction's
  prefix-shortened append target used to panic out-of-range when a
  DROP/TRUNCATE hole was retained below the merge gate
- spill sizing (scanInMemInsertSize, the dump gate and per-table
  selection) counts batch plus index bytes so the spill decision sees
  what the budget charges
- zero-row entries fail closed instead of hydrating an empty charged
  index

Verified by 13 focused unit tests (RED-first: bounded point-read work,
statement-boundary cadence, envelope contracts, exact-probe gating,
index lifecycle and memory accounting, teardown under enforced debug
accounting, ALTER ownership, merge and dumpAll vacated-slot clearing,
spill sizing with hydrated charge, fail-closed zero-row hydration), a
328-statement BVT case replayed at 100 percent, and a live 10k
single-transaction point-update benchmark that stays flat with the
reader path absent from the profile.

Related to matrixorigin#26796.
@gouhongshen

Copy link
Copy Markdown
Contributor Author

Unrelated CI / merge-infrastructure blockers currently observed on this PR, each tracked by an existing issue:

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@gouhongshen

Copy link
Copy Markdown
Contributor Author

Addressed the design-gate finding from review 5593891733 (mo-bot-xupeng, request_changes at f4fd8cfc4e).

Verification before action. Checked the finding against the actual diff: the change does introduce Entry.keyOffsets, a transaction-lifetime lazily hydrated exact-key index, with charge/refund accounting (keyIndexAccountedSize), invalidation across merge/shrink/release/dump/ALTER-transfer/teardown, and spill-selection integration — a stateful cache on the workspace read hot path under the feature-design-review contract. The non-generated production delta is also 647 lines (85 + 324 + 25 + 48 + 1 + 164 additions plus deletions), above the 500-line default trigger. Classification: valid and in scope; the PR body previously linked no design.

Action (commit 3a758d8ffd, docs-only, whitespace check clean). Added the required versioned design at docs/design/20261021-disttae-workspace-point-read-bounding.md — rev 1. It covers the exact areas the finding requests: gate record with both triggers, problem and evidence from issue #26796, the invariant set (envelope soundness, index/layout agreement, singleness of charge, fail-closed gate, honest spill sizing, retirement, concurrency), state ownership and lifecycle, memory bounds and accounting (the deterministic charge estimate and its charge/refund mirror), the hot-path cost model for point-update and ordinary workloads, five alternatives with tradeoffs, compatibility and operations, the validation mapping onto the 13 focused unit tests and the BVT case, and drawbacks/risks/open decisions with owners. The document identifies its owning issue (#26796) and implementation PR (#30685), and the PR description now links this exact revision. No production code changed on this head.

Per the contract, implementation approval remains blocked until this design revision is reviewed in this thread; requesting that review here.

@aptend aptend 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.

Independent deep review of exact head 3a758d8ffd88e416b3a0e220d75fd94a25babdf1, base/merge-base 20f7f8dd2e0d514a1ed4105a301ae3cec5136338. Read all history/discussion (no inline threads), the linked issue, every current changed hunk and affected lifecycle callers.

Distinct design-first decision: ACCEPT rev1 docs/design/20261021-disttae-workspace-point-read-bounding.md at this exact head. The new artifact closes the earlier missing-design concern; this is a traceable review decision, not a request for a status badge. The two-tier design, per-layout invalidation, single refund owner and integration with existing spill sizing are coherent. Write-side encoding, two uncharged envelope-key clones per entry and approximate retained-index accounting remain explicit tradeoffs; no global O(1) lookup or free-write claim.

Implementation closure: canonical range pruning remains conservative; exact probes require equality, matching column and no independent membership filter. Unknown/unmodeled cases keep the original filter path; the common tombstone/output tail remains. Traced index creation through merge/shrink/release, ALTER duplication, dump/compaction, statement rollback and commit/transaction teardown. No stale layout or shared-charge owner found. Vacated tail slots clear references, and spill gate/quota/table selection include the same index charges. Q1/Q2/Q3: one live owner/refund, existing workspace mutex with no new asynchronous waits, transaction-local bounded state tied to existing spill containment. No blocking finding.

Verified evidence reuse: f4fd8cfc4eff6d682ff13b7eeace96fbe4944a59..HEAD changes only the design document, so implementation/test/native inputs are identical. Reconciled raw logs and downloaded artifacts from successful CI run 39520372413:

  • Ubuntu UT job 118962565013: checkpoint explicitly selects complete disttae and readutil owning packages under -short -tags matrixone_test -race, with terminal light-stage exit0; all 13 new roots are in the unfiltered selection and have no short skips.
  • Normal coverage producer 118962609967: terminal exit0, 82679 pass events and no failed package/test events. This is CI-mode normal-suite evidence, not a separately computed changed-line coverage percentage.
  • SCA 118962565049: repository vet/molint and golangci2.14.0 completed successfully.
  • Compose/Proxy BVT 118965296885: the new case actually executed 328/328 assertions, zero failure/ignore/abnormal; suite terminal success. Positive seed, repeated updated-row/unique-key lookup, postcommit data and rollback assertions are present.
  • git diff --check: PASS.

No new local test/benchmark or mixed-topology measurement claimed; local native preflight executed no tests, and the equivalent green CI evidence was reused. No source changes or review probes were added. Approval is for the documented optimization and lifecycle contract, not independent verification of the author's live benchmark numbers.

@XuPeng-SH

XuPeng-SH commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · done

Commit: 3a758d8ffd88e416b3a0e220d75fd94a25babdf1

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-xupeng · review

Commit: 3a758d8ffd88e416b3a0e220d75fd94a25babdf1

Assessment: approve

Reviewed the complete 12-file delta, linked issue, frozen comments, design and affected callers. The design-gate concern is closed. Filtering, index ownership, invalidation, accounting and spill integration are coherent; no actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a15209-2c6d-71e2-b8f3-aa17387fa283 · slot 2 · generation 0

Validation:

  • Verified clean source, assigned HEAD/merge-base, supplied patch consistency and git diff --check.

  • Traced cache lifecycle through hydration, merge/shrink, ALTER transfer, spill, compaction, statement rollback and transaction teardown. Reviewed all 13 new test roots and SQL/result oracles.

  • Independently reconciled CI run 39520372413 at f4fd8cf. Only the design document differs from the assessed HEAD; implementation, tests and build inputs are identical.

  • Race checkpoint selects complete disttae/readutil packages with -short -tags matrixone_test -race and no test-name filter; terminal status is 0. Normal coverage producer reports exit 0 and no failed package/test events. Vet/molint and golangci-lint completed successfully.

  • Compose/Proxy BVT logs confirm the new SQL case executed all 328 statements successfully, with zero failures, ignored or abnormal results and terminal suite success.

  • Retained evidence and hashes in attempt-1/review-evidence.json and analysis in review-notes.json. Audit receipt checks/1792553494509118563-4.json matches the command, clean source fingerprint, exit 0 and review-audit.stdout.log/review-audit.stderr.log.

Limitations:

  • No local Go tests, native builds, BVT or benchmarks were repeated; equivalent CI execution was reused. Individual race-test event records were unavailable, so verification used package selection, source skip checks and terminal status.

  • Author latency figures, ordinary-write overhead and peak heap usage were not independently measured. Write-time encoding, two uncharged envelope keys per entry and approximate index accounting are explicit accepted design costs.

  • This optimization bounds repeated encoding within batch layouts; entry scanning and fallback filtering remain. Approval does not assert global constant-time reads or resolution of every workload in issue #26796.

@mergify mergify Bot added the queued label Oct 21, 2026
@mergify

mergify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-21 03:34 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-21 07:14 UTC · at 838cc78aa1efe46693876a48c05c202979047b7b · squash

This pull request spent 3 hours 40 minutes 46 seconds in the queue, including 1 hour 5 minutes 17 seconds running CI.

Required conditions to merge

This branch was previously deployed

1 inactive deployment
ci — f8c0bb23 Deployed Oct 21, 2026 by mergify[bot]
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.

4 participants