Skip to content

perf(frontend): reduce prepared metadata and privilege snapshot overhead - #29694

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29689-prepared-point
Oct 8, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue-29689-prepared-point

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Improvement
  • BUG

Which issue(s) this PR fixes:

Related to #29689. The matched pre-queue-repair candidate reached historical-good point-select throughput while retaining current correctness checks. This does not close the original nightly/100M-row investigation or identify its first bad commit.

What this PR does / why we need it:

Profiles show repeated frontend/admission work and amplified transaction queue scanning. The changes stay with existing owners:

  1. Snapshot admission: authorization-version reads use the txn client's policy-selected, locally applied snapshot directly. Share readiness/abort/pause, limiter, snapshot selection, logtail waiting and final close/cancellation admission; avoid creating and committing an unused read-only transaction. All seven catalog identity/pending-visibility/reconnect checks and frontend permission decisions remain. Empty/error snapshots provide no reusable proof.
  2. FIFO admission queue: retain prefix-only promotion and the existing waiter cancellation/publication state machine. Put FIFO links in that existing waiter and let ClosedEvent delete its actual operator in O(1), eliminating repeated suffix scans/compaction and enqueue growth/copies. Removed links are cleared immediately. Close drains stable waiter gates under the queue lock, then notifies outside locks without rereading a reused operator generation. Reservations, max-active capacity and unknown-commit ownership remain unchanged.
  3. Prepared metadata: retain column packets in the existing bounded runtime specialization tuple. Publish with successful compilation, discard staged data on failure/cancellation, and clear with the generation. Binding/schema/protocol invalidation and dynamic GROUP_CONCAT metadata remain; packet writers copy immutable payloads.
  4. Binding identity: use local numeric encoding with the original framed bytes and all source-domain flags. Current values and diagnostic admission remain authoritative.
  5. Complete wire equality: small ObjectRef comparisons use bounded local buffers; small uncommon Expr comparisons share one bounded heap allocation. Continue using complete generated protobuf encoders, including nested/unknown metadata. Exact-size slices preserve backwards encoding. Large Expr messages keep their original two allocation sizes; no custom ParamRef identity or hash shortcut is introduced.
  6. Repeated classification/lookups: short-circuit pure parameter classification when its current proof already makes the result irrelevant; retain constant/row diagnostic probing. Read the same Session SQL mode once for four existing token checks, with unchanged error/non-string fallbacks and invalidation.

No new transaction state machine, cache map, generation-validity flag, parser, permission decision path or table/workload-specific branch is added. Raw static block-template caching was rejected because semantic deduplication does not establish equivalent execution admission.

Diff versus the declared base: implementation 265+/131- (net134); tests 732+/82- (net650); generated mock 15+. The queue repair changes one membership owner and adapts all existing consumers; there is no transaction-ID index, new node allocation or duplicated transaction state. Existing tests retain their independent FIFO, cancellation, capacity and unknown-commit oracles. Added coverage checks arbitrary unlink order/reference cleanup, stable Close gates and real New/Rollback cancellation cohorts using existing callbacks. Queue benchmarks stay in the owning UT package; review documents and baseline benchmark implementations are not committed.

Validation

Base remains 1a0088790c8823bd3fe824ad9ff2ef1ce130eb31 (Go1.27.1 minimum). Current queue repair: 82322ceced.

Current queue repair

Root cause: after a live FIFO head was promoted, canceled suffix creators could each scan and compact the remaining slice under the shared client mutex. The N-request cleanup cost was O(N²); the same cost also existed without a promotion. The repair gives the existing queue O(1) enqueue/unlink and O(consumed prefix) promotion.

  • Go1.27.1, GOMAXPROCS2, repository CGo wrapper and verified matching native artifacts; other machine workloads preserved.
  • Owning pkg/txn/client normal and race 191 top-level tests plus80 subtest selections PASS in each mode. Six exact cancellation/promotion/Close/Restart tests each race×100 PASS, including the final public cancellation regression asserting queue cleanup, zero active transactions and zero user reservations.
  • Complete intended 19-file PR closure: gofmt, vet, pinned molint and configured golangci-lint v2.14.0 checked across frontend, generated frontend mocks, planner, txn/client and disttae. Molint's existing diagnostics are in byte-identical untouched base files; no introduced finding. Final configured lint result: 0 issues, all incremental SCA commands exit0.
  • 6.1-sol/xhigh produced the design and independently reviewed the complete original PR plus this repair; final review APPROVED 82322ceced and all19 changed files with no material unresolved blockers.
  • No fresh full BVT/multi-CN or whole-query QPS run is claimed for this repair: it changes an internal client queue, with public New/Rollback cancellation and existing real ownership/Close/Restart tests exercising its consumer boundary. SQL/protocol and distributed routing contracts are unchanged.

Controlled queue-only comparisons use exact pre-repair prefix/slice cleanup and pre-PR compaction controls, same toolchain and fixtures, with no task-owned build/test/lint overlap. Medians of three repetitions:

Queue mechanism Before repair Repaired
claim+reenqueue, depth1 53.87ns,16B/2alloc 42.40ns,8B/1alloc
claim+reenqueue, depth8 50.43ns,24B/1alloc 43.04ns,8B/1alloc
claim+reenqueue, depth1000 49.36ns,30B/1alloc 43.72ns,8B/1alloc
3000 canceled suffix cleanups after promotion 19.795ms 14.453us
3000 cancellations without promotion 19.981ms 14.200us

The original full-compaction control costs51.365us for the promoted cohort. Repaired enqueue+3000-request cohort cleanup costs about25.6us including enqueue. Queue links add24 raw bytes to a queued waiter; measured waiter/channel allocated bytes rise160→176B with2allocations unchanged. Nonqueued operators have no new fields. This is a deliberate bounded memory tradeoff for linear cohort cleanup, not an end-to-end QPS or universal resource reduction claim.

Earlier whole-query evidence (before queue repair)

The measurements and full frontend/protocol checks below were recorded for the original candidate at 4c54e989c2. Their unchanged metadata/planner/snapshot contracts remain covered; historical QPS is not presented as a new measurement of the repaired revision. The Go1.27.0 investigation preceded the upstream toolchain bump, followed by a matched Go1.27.1 confirmation.

One isolated local CN, GOMAXPROCS8, GOGC200, GOMEMLIMIT4GiB, ARCHSIMD0/GOAMD64v3; tracing/metrics disabled. Sysbench1.0.20, seed29689, 1000 binary prepared MYSQL_TYPE_LONG clients, 30s repetitions; no build/test/lint overlap. Historical good is b1b68925d7f6fb32153e788b5285f424222e85ca. Both variants use matching toolchains/configuration/fixture. User accepts current-machine small-data reproduction.

Fixture: 10000 rows inserted once; nopk(id INT NOT NULL,k INT NOT NULL,c CHAR(120),pad CHAR(60),KEY xid(id),KEY k_1(k)); ids1..10000, fixed c/pad lengths120/60. PK control has the same data with id PRIMARY KEY. Query: SELECT c FROM <table> WHERE id=?, uniform bindings. Separate functional checks select id, so identical c cannot hide stale values.

Go1.27.0 investigation and reverse controls

NoPK QPS Three repetitions
Historical good, before 26040.52 / 25793.54 / 26301.99
Final source candidate 26354.92 / 26559.20 / 26533.50
Historical good, reverse 26268.10 / 26465.83 / 26116.77

Candidate median26533.50 versus reverse historical median26268.10: local parity/no observed slowdown, point estimate+1.01%; overlapping variation does not establish a universal or statistically significant1% speedup. PK control38941.83 versus historical reverse34744.43, with no observed regression. All workload errors zero. Previous current-main baseline median19444.30 was measured on8929ab49 before the first rebase; it is contextual evidence, not a contemporaneous final-base A/B.

Warmed whole-query CPU estimates: candidate299.14us versus historical305.74us. The full-tail claim/canceled-waiter stacks disappear. Cumulative stacks overlap and must not be summed.

Allocation-profile deltas showed GC-publication-window variation, so use separate runtime MemStats TotalAlloc/Mallocs counter deltas from the existing heap debug endpoint:

Estimated per query Pre-change main8929ab49 Historical good Candidate
Allocated bytes 65211 61221 61656
Allocations 687.66 636.49 646.60
GC cycles / million queries 72.21 54.46 73.71

Net patch bytes/allocations decrease about5.45%/5.97% versus pre-change main. Versus historical good, bytes+0.71% and allocations+1.59% remain; fewer GC cycles or universal resource dominance is not claimed. Background GC CPU is about9.56us/query versus historical8.78; total CPU still improves. Query denominators use interpolation of10s reports, so small percentage differences are estimates. Snapshot freshness/statistics/diagnostic checks remain; measured throughput restoration is not achieved by bypassing them.

Small ObjectRef benchmark: zero allocations versus original2; small Expr fallback:1 versus2 with equal rounded bytes. Large messages retain original allocation count/sizes. Pure synthetic tests have no timing thresholds.

Earlier Go1.27.1 confirmation at 4c54e98

Both historical and final binaries were rebuilt with Go1.27.1, ARCHSIMD0/GOAMD64v3. Matching fixture/configuration and clean sequential measurement intervals:

QPS Historical good Final candidate
NoPK, three repetitions 25895.83 / 26760.09 / 25718.58 26094.37 / 26358.23 / 26078.45
NoPK median / mean 25895.83 / 26124.83 26094.37 / 26177.02
PK control 35915.19 39590.89

All errors/reconnects zero. Median+0.77% and mean+0.20% with overlapping ranges support local parity/no observed slowdown; they do not establish a statistically significant speedup. The strict public result/type/NULL/current-binding/revoke/regrant oracle also passes with its client rebuilt on Go1.27.1. Independent GPT-6.1-sol xhigh final QA approves HEAD4c54e989c2 against base1a0088790c.

Earlier original-candidate correctness and delivery evidence

  • Full owning frontend normal/race, txn/client normal/race, planner normal, selected complete-wire identity race and engine authorization race pass on Go1.27.1.
  • Exact C8 cancellation/promotion/queued snapshot failure/Close tests have bounded adaptive race stress; unchanged source evidence is retained alongside new-toolchain owning race runs.
  • Current-row/missing/out-of-range, signed/unsigned binary values, NULL/string/type transitions pass. Warmed normal-user prepared execution rejects REVOKE from another connection inside an older explicit transaction; regrant returns the current binding.
  • Real-packet tests cover metadata/type/protocol changes and failures, compilation/cancellation publication, schema/GROUP_CONCAT/diagnostic controls. Legacy-key and original-encoder oracles are independent of the new implementation.
  • Incremental repository-pinned molint and configured golangci-lint v2.14.0 pass for all changed owners and generated frontend mocks; both tools rebuilt with Go1.27.1. Dependent mo-service builds successfully.
  • Independent GPT-6.1-sol xhigh design and implementation QA completed, including FIFO/ref cleanup, wire collision resolution, unsuccessful generation publication, current permission proof and cost accounting.

Local UT reproduction after native prerequisites: .agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/frontend ./pkg/txn/client ./pkg/sql/plan ./pkg/vm/engine/disttae; use affected race families/full owners as above. No CI wait or rerun is required for delivery.

Remaining scope

Original129/100M-row nightly restoration and controlled first-bad attribution remain unproved. The historical74/75TPS diagnostic-pushdown defect was a separate already repaired failure. This PR retains fresh grants, current statistics, warning ownership and scan/remote reset checks.

@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 →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of head 8af8963 against merge-base dce6063. All 11 changed files/hunks reviewed; no subagents.

Technical conclusion: no blocking finding; approvable on the reviewed scope. COMMENT rather than APPROVE because the authenticated reviewer is also this PR's author. This is not an independent approval.

Design: this is a focused optimization of existing owners, not a second authorization cache or transaction state machine. The transaction client still owns readiness/freshness; disttae still proves the seven catalog identities/versions; frontend still owns permission evaluation and the bounded prepared specialization tuple. The 109 added/28 removed production lines and generated mock update are proportionate. No new disk/wire format, configuration, background worker, or cross-request cache.

Change/QA closure:

  • R3 freshness and cancellation: GetLatestSnapshot preserves the existing rate limiter, abort/readiness barrier, pause/resume, snapshot policy and logtail wait. The final lifecycle gate rejects close and context cancellation even when a waiter returns late success. Removing New/Commit removes disposable transaction admission, not the engine's ready/catalog-identity/visibility checks. Empty snapshots and errors remain non-reusable permission proofs. The unchanged frontend captures the proof before permission evaluation and raises the session minimum snapshot; it does not authorize solely from the timestamp.
  • R2 prepared metadata: bytes are staged with the candidate key/plan and published only after successful compilation. Metadata generation or compilation failure retains the prior tuple. Rebuild, schema/session/protocol changes and Close clear the tuple. Diagnostic/value-dependent specialization and GROUP_CONCAT exclusions remain in force. Column payload construction depends on the bound result types/columns; the packet writer copies bytes and does not mutate the retained payload. Different parameter values cannot replay old rows; type changes select/rebuild a different specialization. EXPLAIN's transaction-DDL-sensitive title is outside reusable execution.
  • R2 binding key: the new append-based framing retains the previous separators, signed integer representation, flags and NULL/type distinctions; the independent old-format oracle covers all five boolean dimensions. Actual non-NULL values deliberately do not form the specialization identity.
Audit Closure
Q1 ownership No temporary txn/operator is created; waiter ownership stays with the existing client. Failed candidate metadata is discarded; installed metadata has the same replacement/rebuild/Close owner as the single-entry specialization.
Q2 waits Limiter/readiness/logtail waits retain context/client-close exits; the final lifecycle gate is acquired only after the client mutex is released. No new worker or dependent cancellation chain.
Q3 growth One metadata slice per existing specialization, replaced/cleared with it; no new unbounded key/value cache, queue, transaction registry entry or retention owner.

Evidence and limitations:

  • Verified current-head CI success: https://github.com/matrixorigin/matrixone/actions/runs/37738960140 (UT, SCA, shared build, both enabled multi-CN BVT jobs, coverage and CI Required). Skipped legacy/upgrade variants are not counted as passing tests.
  • Reused the PR's explicit normal/race and real-protocol evidence, including late-success barriers, failed replacement, current parameter values/type transitions, and warmed non-admin REVOKE/regrant with an older explicit transaction. These are distinct oracles rather than repeated same-path tests.
  • The author-recorded matched NoPK secondary-index prepared workload shows median throughput +8.75%, supported by CPU/allocation measurements and a switchback. This supports the targeted workload, not a blanket TPCH/ClickBench or universal performance claim; the PK control has insufficient samples for a broad claim.
  • An additional local focused race run was attempted, but the CGo wrapper rejected unavailable/mismatched native artifacts before tests started. It is not a local PASS; no unsafe artifact borrowing or production-source modification was performed. The conclusion uses source closure plus the existing recorded/CI evidence, not that attempt.
  • No historical substantive review comments or review threads exist at this head; no unresolved comment was silently treated as fixed. Persisted-data compatibility is unchanged; mixed-version rolling upgrades were excluded per the requested scope.

@XuPeng-SH
XuPeng-SH force-pushed the codex/issue-29689-prepared-point branch from 8af8963 to 4c54e98 Compare October 8, 2026 08:26
@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner October 8, 2026 08:26
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Oct 8, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of HEAD 4c54e989c2c404d6d725b56dc5aa13797606e44d against merge-base 1a0088790c8823bd3fe824ad9ff2ef1ce130eb31. All 14 changed files and hunks were reviewed directly; no subagents were used in this review.

Technical verdict: APPROVE; no blocking findings. Submitted as COMMENT because the authenticated reviewer is also the PR author. This is not an independent GitHub approval.

Design and ownership:

  • Snapshot admission remains owned by txn/client: rate limiting, readiness/abort/pause barriers, snapshot policy, locally applied logtail and final close/cancellation admission. disttae still validates all seven catalog identities, versions and visibility; frontend retains permission evaluation. No authorization check is bypassed.
  • FIFO promotion consumes only the prefix needed for admission. Reservation/publication and cancellation ownership remain with the existing waiter and ClosedEvent paths; detached references are cleared. Front reslicing can require amortized enqueue growth/copy, an explicit cost accounted for in the whole-query measurements.
  • Prepared result metadata belongs to the existing bounded specialization generation. Candidate data is published after successful compilation; failure retains the previous tuple, and rebuild/Close clear it. GROUP_CONCAT retains dynamic metadata construction. Cached packets are immutable and the protocol writer copies them.
  • Binding-key framing preserves the old identity. Expression comparison still uses complete generated protobuf encoders, including nested and unknown fields; small-buffer optimization does not weaken equality or change large-message allocation sizes. Diagnostic short-circuiting skips only pure classification already made irrelevant by the current proof. SQL mode is read once through its existing session owner.
Lifecycle audit Closure
Q1 ownership Snapshot reads create no disposable txn operator; promotion/cancellation keep their existing ownership barrier. Metadata has one installed generation and the existing replacement/Close cleanup owner.
Q2 waits Limiter/readiness/logtail waits retain context/client-close exits. Final lifecycle admission occurs after blocking waits. Promotion does not inspect or lock untouched suffix waiters.
Q3 growth Consumed queue references are cleared; cancellation removes suffix ownership. Metadata is bounded by the existing single specialization entry, with no new unbounded cache or worker.

Unhappy-path review covered cancellation, Close, late waiter success, cancellation during promotion, queued snapshot failure, metadata construction/compile failure, generation replacement and warmed prepared execution after REVOKE. No new leak, double cleanup or invalid-state publication path was found.

Engineering and test quality:

  • Production: +164/-80, net +84; tests: +438/-46, net +392; generated mock: +15; no repository documentation increment. The additions have concrete ownership/performance or regression-oracle purposes; no redundant state machine, workload-specific branch or unused abstraction was found.
  • Tests extend existing fixtures and exercise real protocol metadata, current values, cache replacement failures, deterministic cancellation/promotion and complete-wire boundary/unknown-field identity against original encoders.
  • Verified and reused matching local terminal evidence rather than claiming new runs: owning frontend/client normal and race tests, planner normal tests, selected wire/engine authorization race checks, bounded exact-test race stress, strict live protocol oracle, dependent service build and incremental static analysis. The current diff matches the recorded final patch SHA-256 40e88bddbe22e514e92fb5bf92517ec180eb2579b1467bf5006994761fccf7c5. golangci reports zero incremental issues. Raw molint output includes baseline warnings in unchanged files; no new warning belongs to this patch.

Performance scope:

  • Matched Go 1.27.1, local 10,000-row/1,000-client NoPK repetitions: candidate median 26,094.37 QPS versus historical-good 25,895.83, with zero errors/reconnects. Overlapping variation supports local parity/no observed slowdown, not a statistically significant or universal speedup.
  • Resource dominance is not claimed: Go 1.27.0 counter estimates versus historical good retain about +0.71% allocated bytes and +1.59% allocation count per query, with slightly higher background GC CPU despite lower total CPU. These are disclosed tradeoffs, not hidden behind QPS.
  • Original 100M-row nightly recovery and first-bad-commit attribution remain unproved. Keep #29689 open for that remaining scope.

Comment closure: there are no unresolved substantive inline comments or review threads. The previous review covered the older head; this review additionally covers the latest queue and expression-comparison changes.

Remote CI was still running when checked and is not claimed as passed. Main advanced by one commit (ffcce7ecbab7, #29679) during review, so the PR is behind; this verdict is scoped to the reviewed head/base above.

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/L Denotes a PR that changes [500,999] lines labels Oct 8, 2026
XuPeng-SH added a commit that referenced this pull request Oct 8, 2026
…9708)

## What type of PR is this?

- [x] BUG
- [x] Test and CI

## Which issue(s) this PR fixes:

Fixes #29709

Fixes the `pkg/shardservice/TestRead` listener leak reported by [PR
#29694's coverage
job](https://github.com/matrixorigin/matrixone/actions/runs/37761393016/job/113259178297?pr=29694).

## What this PR does / why we need it:

`NewService` starts an RPC server, but `Close` only closed the RPC
client. A real socket probe against the failing CI revision confirms
that the closed service still accepts connections. Close both owned
endpoints and preserve both errors, including when server shutdown
fails.

The shared test fixture invoked its leak check immediately at entry and
released services only after a successful callback. Defer the leak check
until teardown; register independent cleanup as each cluster, server,
storage timestamp waiter, and CN service is acquired. Assertion
failures, callback panic, partial fixture setup, and close errors no
longer bypass remaining cleanup. Storage and cluster resources remain
owned by the fixture.

Regression tests prove that a live socket is disconnected and refuses
new connections after shutdown, and that both RPC endpoints are closed
when either or both return an error. No new state machine, public API,
or hot-path work is added.

Validation (Go 1.27.1, Linux/amd64, repository CGo wrapper):

- Owning `pkg/shardservice` package: normal and race pass, 75
tests/subcases each.
- Owning package in CI's short / `matrixone_test` / set-coverage mode
passes; instrumentation covers shardservice, morpc, txn/client, and
clusterservice.
- Exact `TestRead`: race ×15; `TestServiceCloseListener`: race ×100,
using the repository's bounded adaptive repetition budget.
- Real fixture probes confirm teardown after callback panic, partial
setup, `t.Fatal`, and an injected server close error. Removing server
shutdown makes the new regression fail locally with listener leaks and
an open connection, rather than a process timeout.
- Incremental gofmt, vet, molint, and configured golangci-lint pass (0
new issues).

Related: #29676 also closes this server as part of a broader constructor
ownership change. This PR is a focused, independently mergeable
correction; it does not take on that constructor/API refactor.

New PR CI has not yet run. SQL BVT is not applicable: this change
restores component teardown without changing SQL or wire behavior.

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Post-merge deep review of final PR head 0924d4aa74a32bcaac7120750b220788f3be54c1 against ca5008de9aa1569504d593350ed92059217c85e4. The PR merged during this review as 83d82b8ee0cd694e0c6a7146902d74ae4dfb415a; both commits have the identical tree 9adc3cd7e67239591e55fe58aa9a3190d3737dc0. The merge-from-main has no conflict-resolution delta, the PR patch-id is unchanged, and all 19 PR-touched files are identical to reviewed 82322ceced.

Decision: no blocking implementation finding in this scope. This is a COMMENT on a self-authored, already-merged PR, not an independent GitHub APPROVE or a claim that final-head CI has completed. No subagents or production edits.

Design and ownership

The optimization remains within existing owners. It does not add a second authorization cache, transaction cancellation state machine, or prepared-plan execution path. The design tradeoff is proportionate: one metadata payload per existing specialization and three links in the already-allocated admission waiter, in exchange for removing repeated metadata encoding/empty read-only transactions and quadratic canceled-queue removal.

Closure Adversarial checks and conclusion
Prepared metadata generation Cache payload, plan, key and diagnostics are installed together only after successful compilation; failure/cancel discards the candidate and preserves the previous generation. Rebuild/Close clears it. Dynamic GROUP_CONCAT still rebuilds metadata; AP does not retain execution topology. Packet-writing consumers copy the bytes rather than mutate the retained payload.
Binding key / SQL modes The new encoder preserves the old signed framing and all domain/null flags. Actual values deliberately remain outside generation identity and still pass existing diagnostic admission. One SQL-mode lookup preserves the old helpers' fallback behavior.
Protobuf equality Exact-sized buffers preserve the complete generated wire representation, including unknown/nested fields; 63/64/65-byte boundaries retain the full-Marshal oracle. This is allocation optimization, not a weaker equality test.
Snapshot-only API / authorization proof Uses the existing limiter, readiness/abort barrier, timestamp policy and logtail waiter. No lifecycle lock is held across waits; late success is rejected after Close/cancel. Zero/failed proof still forces privilege-cache invalidation. All seven physical catalog identities, DataVersion visibility, pending subscription and final readiness/cache-identity checks remain. The removed internal transaction was non-user and was already committed before these catalog reads.
Admission FIFO / cancellation / reuse Queue membership is owned by client.mu; the existing waiter mutex still owns promotion versus cancellation. Removal detaches links in O(1), promotion examines only the required prefix, and Close captures old waiter identities before releasing the lock. ClosedEvent detaches membership before terminal completion permits Restart. Cancellation after promotion waits for publication without holding the waiter mutex. Unknown-commit reservations keep their existing release owner.

This is a focused optimization of existing contracts, not a new persisted format/protocol or mixed-version upgrade design. No disk/wire migration is introduced. Security and lifecycle closure were reviewed separately from ordinary SQL-result correctness.

QA and validation

Fresh local tests use Go 1.27.1, darwin/arm64, the repository CGo wrapper, matching rebuilt native libraries, and the final merged tree plus a review-only test file. The ONNX download initially timed out; the supported prebuilt-directory input was then used with the exact source-pinned SHA-256, without bypassing native provenance.

  • Full pkg/txn/client, -race -count=1 -timeout=240s: PASS (12.419s).
  • Added an independent public-New/rollback challenge: maxActive=2, canceled head and canceled interior surrounding two live FIFO admissions; delay both canceled ClosedEvents, promote both live entries, then release delayed cleanup. It asserts FIFO progress, exact reservation counts, zero residual queue and zero active count.
  • Added snapshot admission across the abort-scan barrier: release/cancel/Close, checking no early snapshot, no downstream timestamp call on failed admission, and no transaction ownership.
  • Both additional challenges, -race -count=100 -timeout=120s: PASS (2.568s), after a separate initial run with the existing snapshot and promotion regression tests.
  • Additional final-tree focused race tests, -race -p 1 -count=1 -timeout=240s: frontend PASS (4.070s), plan PASS (4.357s), disttae PASS (2.065s). Selected TestPreparedExecutionBindingKeyPreservesIdentity, TestRuntimeSpecializationReplacementCommitsOnlyAfterCompileSuccess, TestPreparedOrdinaryFloatRuntimeCacheReusesCompile, TestInitExecuteStmtParamSpecializesBinaryRuntimePlan, TestObjectRefEqualWireBoundaries, TestExprWireEqualMatchesMarshal, and both TestPrivilegeCacheVersion* tests.
  • Full-range git diff --check: PASS.

Reusable evidence: inspected exact 82322ceced CI run 37761393016, including the downloaded UT checkpoint artifact showing actual -race selection and successful terminal phases, not merely a green rollup. The old run's SCA/UT/enabled BVT passed. This is unchanged-delta evidence, not a substitute claim that the later main-integration CI has finished.

The new post-merge TKE image-build failure occurs resolving the Docker Hub builder manifest: dial tcp ...:443: i/o timeout. It fails at Dockerfile FROM, before compiling MatrixOne. It is not evidence of a regression in these execution paths; the final-head regular CI remains separate/pending at inspection.

Performance, test quality, and previous comments

The previous full-cohort cancellation concern is addressed structurally: prefix-only promotion alone left O(n) arbitrary removal and O(n²) cancellation bursts; intrusive membership removes that remaining scan without adding a second cancellation authority. The published paired mechanism measurements support that improvement, but were not independently rerun here. The reported small prepared-query QPS comparison is parity within the observed spread, not a demonstrated broad workload speedup. The PR does not prove that the entire 100M-row/nightly regression in #29689 is solved.

Increment reviewed separately: production +265/-131; tests +732/-82; generated mock +15; no documentation increment. The tests mostly cover distinct contract axes rather than repetitions: wire oracle/buffer boundary, key flags, failed publication, pause/limiter/cancel/Close, queue ordering/removal/generation and retained reservations. Removed commit-error testing corresponds to the removed empty-transaction operation, not suppressed failure handling; snapshot-error/empty-proof tests remain. I found no new abstraction or compatibility branch whose maintenance cost lacks a concrete benefit.

Checked both prior substantive reviews and the discussion; there are no inline review threads. No earlier blocking finding remains unresolved for this scoped optimization. The broader performance investigation remains a separate known limitation, not silently declared complete.

XuPeng-SH added a commit that referenced this pull request Oct 8, 2026
…29725)

## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes #29714

## What this PR does / why we need it:

When an old lock owner closes, a remote Unlock can receive a wrapped
EPIPE instead of an already-classified backend-closed error. Previously
Unlock returned immediately, skipped allocator binding refresh, and
retained the stale binding and closing transaction. This is the
production defect exposed by the coverage failure in PR #29694.

Recognize EPIPE, ECONNRESET and net.ErrClosed through errors.Is in the
existing shared transport classifier. Recovery continues through the
existing allocator validation and retry paths: a changed authoritative
binding completes old-generation cleanup; an unchanged binding still
requires owner acknowledgement. Cancellation and deterministic business
errors retain their current behavior. No new retry loop, state, protocol
or storage is introduced; the successful request path is unchanged.

Extend existing fixtures to cover wrapped errors and negative
classifications, public Unlock binding refresh plus transaction removal,
unchanged-binding retry, changed-binding behavior for
Lock/Unlock/GetTxnLock, and cancellation after EPIPE. The public
regression deterministically fails on the clean base with broken pipe
and a stale owner binding.

Validation (Go 1.27.1, Linux/CGo):

- Entire pkg/lockservice passes normally and under -race.
- Nine focused recovery/cancellation/rejection/batch tests pass in CI
coverage mode (-short -tags=matrixone_test -covermode=set), producing a
coverage profile.
- Individually repeated race tests: public Unlock 100, changed binding
100, unchanged-binding retry 96, cancellation 100; counts derived from
single-run durations with a 30-second budget and 100-run cap.
- Formatting, go vet, repository molint and configured incremental
golangci-lint over pkg/lockservice complete; no introduced findings.
molint reports two existing warnings in unchanged test_helper.go and
txn_test.go.
- gpt-6.1-sol / xhigh design and final review recorded locally. Remote
CI remains pending.

This branch was previously deployed

1 inactive deployment
ci — 0924d4aa Deployed Oct 8, 2026 by XuPeng-SH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working kind/enhancement size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants