Repository navigation
refactor(disttae): redesign CN transaction workspace - #27013
gouhongshen wants to merge 30 commits into
Conversation
…-access-index # Conflicts: # pkg/lockservice/lock_table_local.go # pkg/sql/compile/bloomfilter_cover_test.go # pkg/sql/compile/compile.go # pkg/sql/compile/scope.go # pkg/sql/compile/scope_test.go # pkg/vm/engine/disttae/object_list.go
…-access-index # Conflicts: # pkg/frontend/back_exec.go # pkg/frontend/mysql_cmd_executor.go # pkg/sql/compile/scope.go # pkg/vm/engine/disttae/txn.go
…-access-index # Conflicts: # pkg/vm/engine/disttae/txn_table.go # pkg/vm/engine/disttae/types.go # pkg/vm/engine/disttae/util_test.go
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review of ec8f17c: REQUEST_CHANGES for the spill failure ownership boundary.
[P1] Preserve/clean objects persisted before a failed spill Sync
In the new stageWorkspaceSpillGroup (pkg/vm/engine/disttae/txn_workspace_spill.go), a failed writer.Write or writer.Sync returns the local stats slice and defers only writer.Close. CNS3Writer.Sync (pkg/sql/colexec/s3util.go:304-310) returns immediately on sinker.Sync failure, without exporting any previously persisted objects. Thus a large group can successfully persist object A during Write, then fail/cancel on the final Sync; this group's returned stats are nil and cleanStagedWorkspaceSpillLocked cannot schedule A for deletion. Commit-ambiguous Sync object names are lost in the same way.
This is not cleanup performed implicitly by Close: at this exact head Sinker.Close clears staged.persisted/unpublished without deleting files. Sinker.DeletePersisted exists specifically to collect successful and commit-ambiguous objects (including drained pipeline siblings) and retain references on deletion failure. The new workspace adapter never invokes or exposes it. The source leases are closed correctly, but the external object owner disappears without a workspace publication or GC handoff.
Fix: add an abort/ownership-transfer surface to CNS3Writer that drains writers and snapshots all unpublished object names before Close, using the sinker's existing DeletePersisted contract (or equivalent explicit handoff). On failed Write/Sync, either delete with a cleanup context that survives request cancellation, or register failed deletions with a retryable owner before releasing writer state. Preserve the original staging error and report cleanup failure. On success transfer object ownership exactly once to the workspace; never delete successfully published objects. The GC-submission-error path should likewise retain an owner rather than only ignore/log the error.
Required deterministic validation: force a first object to persist, inject failure/cancellation on a later Write/Sync, then assert no object is published and every persisted/ambiguous object is deleted or retained for retry. Inject deletion failure and prove a later cleanup succeeds; cover a successful publish control and assert all payload leases/MPool allocations return to baseline.
Review scope: complete change map and all 401 lines of the workspace design read; reviewed the new spill/commit adapters, payload pin/release/reclamation and underlying writer/sinker error contracts. This is a confirmed source-level ownership gap, not a claim of a fresh object-store fault-injection run or full approval of the roughly 100-file transaction rewrite. The reported benchmark and broad BVT results are useful author evidence, not substitutes for this unhappy-path oracle. Preserve the generation validation, frozen commit input, lock-free IO and active-set complexity improvements. Also reconcile the design's remaining LIFO wording with the implementation/body's out-of-order active write-scope contract before final readiness.
|
Addressed the spill-failure ownership review in de10dc6. CNS3Writer now exposes AbortUnpublished, so a failed Write/Sync drains and deletes persisted or commit-ambiguous objects before Close. Cleanup is detached from request cancellation; if deletion fails, exact names move to an Engine-owned retry ledger before the writer releases them. The earlier staged-group cleanup no longer ignores GC submission errors. Original errors remain visible alongside cleanup errors; successful publication never enters cleanup. I also reconciled the design document's write-scope ordering language. Deterministic tests cover a first persisted object followed by a later post-persist failure, canceled request context, failed deletion and successful later retry, no failed publication, successful publication, payload/MPool baseline, and Engine.Close retaining pending ownership. Full disttae and colexec unit suites and targeted race tests pass. The cleanup ledger is process-local; this change does not claim crash-durable CN orphan recovery. Please re-review the ownership boundary. |
Preserve upstream statement callbacks, catalog physical-name lookup, runtime-filter empty scans, and IVF ownership while keeping logical workspace views. Maintain planner insert-row bounds in table overlays and extend merge regressions for rewrite, rollback, and catalog resolution.
What type of PR is this?
Which issue(s) this PR fixes:
Related to #26796.
Issue #26796 remains the benchmark record for transaction performance versus transaction size. This PR removes the positional workspace architecture behind the measured current-state degradation, but does not claim to close every transaction-performance case recorded there.
What this PR does / why we need it:
Problem
The CN transaction workspace used physical positions in a global write slice as statement boundaries, read visibility, rollback markers, and commit inputs. Readers and transaction operators depended on
txnOffset,snapshotWriteOffset,offsets, and direct access totxn.writes.That representation coupled logical transaction semantics to mutable slice layout. Statement retry, compaction, spilling, DDL rollback, CN transfer, and payload reclamation had to scan or rewrite shared positional state. As retired history grew, current-state work could become proportional to the transaction's total history instead of its active working set.
Architecture
This PR replaces the positional model with explicit owners and opaque identities:
StatementJournalowns statement identity, retry attempts, rollback resources, RC boundaries, DDL operations, and LOAD-created files.TableOverlayowns each table's active mutations, PK candidates, row/block tombstones, uncommitted objects, and DDL visibility.PayloadStoreowns memory batches and spilled objects through generation-based leases. Readers pin payload generations instead of retaining unowned raw batch pointers.WorkspaceReadViewis an immutable logical visibility boundary.WorkspaceWriteMarkidentifies one write scope without exposing physical workspace positions.CommitBuilderfreezes logical mutations, pins referenced payloads, and builds the existing TN commit requests without mutating live workspace state.The workspace maintains ordered active indexes. Current-state reads, commit preparation, object-delete lookup, DDL lookup, and rollback use active indexes rather than scanning retired mutation history. Historical access is limited to an explicit statement-scoped read view.
Transaction semantics
The implementation preserves and tests:
capture/pin -> I/O -> validate/publish) so stale or rolled-back attempts cannot publish;CommitBuilder.Protocol-order correctness
Logical visibility order and TN precommit protocol order are separate concerns. This PR models protocol order with a
commitEpochadvanced by ordinary Compile read-view publication:This fixes the DDL/DML regression exposed by
delete_workspace.sqlwithout reintroducing physical workspace offsets.Retry preparation and physical payload maintenance
RollbackLastStatementleaves the failed attempt rolled back and retry-pending, whileIncrStatementID(false)may compact or spill completed mutations before opening the successor attempt. Physical maintenance now uses a deliberately narrow owner-preserving replacement path:StatementID,AttemptID, commit order, and visibility are preserved;Compaction planning
The 500,000-row exact UPDATE benchmark exposed a remaining transaction-size-dependent cost: every statement completion entered compaction planning, enumerated all pending mutation IDs, built a read view, and pinned/materialized pending payloads before checking whether enough new input existed to compact.
Compaction eligibility is now checked in O(1) from generation counters before planning or pinning. A plan is built only after the configured input threshold is reached. Immutable half-block payloads are sealed once; compaction outputs are not requeued, so one row is not repeatedly rewritten by later plans.
Regression coverage verifies both pre-plan deferral and single-seal payload behavior.
API changes
The internal engine workspace contract no longer exposes positional write offsets:
PublishReadViewandCurrentReadViewreplace snapshot/write offset accessors.BeginWriteAttemptandAdjust(WorkspaceWriteMark)replace positional adjustment.Ranges,CollectTombstones, and reader construction acceptWorkspaceReadViewinstead of transaction offsets.All in-repository callers and mocks are migrated. No positional compatibility wrapper or fallback implementation is retained.
Performance progress
Exact workload from #26796:
The test preloads 500,000 rows, executes all 500,000 single-row UPDATEs in one transaction, and then either rolls back or commits.
ae69b2b3c3The latest rollback runs completed in
107.719sand107.555s. The commit run completed UPDATEs in106.911s, committed in1.857s, and finished in108.768stotal.The 50,000-operation windows remained stable instead of degrading with accumulated transaction size: approximately
206.9-228.6us/UPDATE, with the all-operation median at200.588us, p95 at271.100us, and p99 at284.804us.Post-commit validation confirmed 500,000 rows, 500,000 distinct
sandbox_pathvalues, and correct first/middle/last values.ORM Unit of Work
Protocol from #26796:
emailandexternal_id.a4b0ce286d19.465s0.212766ms -> 1.081877ms(5.0848x)ae69b2b3c3, fresh sample median3.773s1.20x; p50 ratio0.98-1.09x6.432s0.9798x6.097s0.9531xThree fresh PR samples completed the UPDATE phase in
2.783s,3.773s, and6.644s. Their first-three versus last-three window p50 ratios were1.001x,0.983x, and1.086x. The average-window ratios remained below1.20x; isolated 30-70ms outliers appeared at unrelated transaction positions rather than increasing with transaction size.COMMIT took
71-100msin these samples. This remains higher than the MySQL/PostgreSQL reference commit times and is recorded separately from the eliminated workspace-size degradation.Inventory + Order Item + Transactional Outbox
Protocol from #26796: preload 15,000 inventory rows, then execute 15,000 business operations in one transaction. Each operation performs one inventory UPDATE, one order-item INSERT, and one transactional-outbox INSERT. Latency is summarized in 1,000-operation windows; COMMIT is measured separately.
The PR completes the transaction phase approximately 5.7-6.0x faster than the MatrixOne main baseline. The first-to-last p50 ratios remain 0.993-1.016x across three fresh instances; there is no monotonic latency growth with accumulated transaction size. Periodic 100-153ms outliers raise some window averages, but occur at non-terminal positions and do not form a size-dependent trend. Post-commit validation confirmed all 15,000 inventory updates, order items, and unique outbox events.
COMMIT took 202-432ms in these samples. This remains higher than the database reference commit times and is recorded separately from the eliminated workspace-size degradation.
Ledger Posting
Protocol from #26796: preload 20,000 account balances, then execute 20,000 postings in one transaction. Each posting performs one account-balance UPDATE and one ledger-entry INSERT with a unique
transaction_id. Latency is summarized in 1,000-posting windows; COMMIT is measured separately.The PR completes the transaction phase approximately 6.9-7.2x faster than the MatrixOne main baseline. The last-to-first p50 ratios remain 0.962-0.991x across three fresh instances; there is no monotonic latency growth with accumulated transaction size. Periodic 61-84ms individual outliers occur in non-terminal windows and do not form a size-dependent trend. Post-commit validation confirmed all 20,000 balance updates and 20,000 unique ledger transactions.
COMMIT took 159-171ms in these samples. This remains higher than the database reference commit times and is recorded separately from the eliminated workspace-size degradation.
Write After Read
Protocol from #26796: preload 30,000 inventory rows, then update 30,000 different primary keys in one transaction. After every 100 UPDATEs, execute
SELECT SUM(available)for one warehouse in the same transaction. Operation latency is summarized in 1,000-UPDATE windows, including the ten in-transaction reads in each window; COMMIT is measured separately.The PR completes the transaction phase approximately 17.3-17.6x faster than the MatrixOne main baseline. The last-to-first operation-window ratios remain 0.882-1.017x across three fresh instances. The median of the first three in-transaction reads was 4.804-5.417ms, while the final three were 2.981-3.365ms; the read path no longer grows with accumulated transaction size. Post-commit validation confirmed all 30,000 rows were updated exactly once.
Bulk Upsert
Protocol from #26796: preload 60,000 rows, then execute 60,000 prepared upserts against those existing unique keys in one transaction. MatrixOne and MySQL use
INSERT ... ON DUPLICATE KEY UPDATE; PostgreSQL uses the equivalentINSERT ... ON CONFLICT (id) DO UPDATE. All runs use one client, one connection, one prepared statement, one long transaction, 1,000-operation latency windows, a separately measured COMMIT, and post-commit row-state validation. Preload time is excluded.The PR completes the transaction phase approximately 26.4-27.5x faster than the MatrixOne main baseline. Its 60,000-operation transaction phase is 3.0-6.8% faster than MySQL and 3.4-7.2% faster than PostgreSQL in this aligned run. The last-to-first average-window ratios remain 0.997-1.077x across the three PR samples, 1.042x on MySQL, and 1.030x on PostgreSQL; none shows monotonic latency growth with accumulated transaction size. All post-commit validations confirmed 60,000 rows at revision 1 with the expected updated payload.
MatrixOne COMMIT remains materially slower at 157-181ms versus less than 1ms in these local MySQL/PostgreSQL references. It is recorded separately from the eliminated workspace-size degradation.
Cascade-style Delete + Parent Update
Protocol from #26796: preload 20,000 parent rows and 20,000 child rows, then execute one child
DELETEand one parentUPDATEfor each key in a single transaction. The combined latency of each delete/update pair is summarized in 1,000-operation windows; COMMIT is measured separately.The PR completes the transaction phase approximately 3.0x faster than the MatrixOne main baseline. The last-to-first average-window ratios remain 0.503-0.507x across three fresh instances, so latency does not grow with accumulated transaction size. Post-commit validation confirmed that all 20,000 parent rows had status
deletedand no child rows remained. Absolute transaction time is still 6.6-7.2x above the MySQL/PostgreSQL references and remains under investigation.Cascade unique-index ablation
A same-build control run isolated hidden unique-index maintenance from transaction-workspace cost. Both variants executed the same 20,000 child DELETEs and 20,000 parent UPDATEs; the only schema difference was whether
customer_order_line.product_keyhadUNIQUE.UNIQUE(product_key)5.450s2.826s2.617s114.771msUNIQUE(product_key)60.199s57.288s2.904s156.150msThe no-unique variant is faster than the MySQL/PostgreSQL end-to-end references above. The remaining absolute Cascade gap is isolated to per-statement hidden unique-index maintenance, not transaction-workspace growth.
EXPLAIN PHYPLAN ANALYZEconfirmed that the hidden-index runtime filter reduces the probe to one output row; the overhead is the repeated point-delete maintenance pipeline rather than an unfiltered full-table output scan.Validation
Previously recorded local validation (before the October 8 integration):
go test ./pkg/vm/engine/disttae -count=1make buildgit diff --checkThe ownership, visibility, lock-order, payload-lifecycle, spill, rollback, and commit contracts are documented in
docs/design/cn-transaction-workspace.md.Latest main integration
The branch is merged through MatrixOne main
bab4b3286a(October 8). The integration preserves the transaction-workspace architecture and resolves semantic conflicts without restoring positional offsets:ANALYZEcaptures one immutableWorkspaceReadViewand uses it consistently for ranges, tombstones, and readers;EmptyReaderfast path;d107499817.Additional September 24 integration points: Data Branch retains upstream lineage lifecycle locking and gives each independent DIFF/PICK/MERGE operation one workspace statement owner across concurrent internal SQL; SourceCommitTS reads the new table overlay rather than the removed global write slice; CREATE DATABASE catalog-tuple validation runs in CommitBuilder; and the retired CN merge path remains removed. The merge was validated with full disttae and frontend unit tests, ivfflat unit tests, a mo-service build, and a clean PR diff against main. Coverage follow-up is recorded below.
The same integration exposed an existing reader-count normalization bug: when a relation produced fewer readers than scan pipelines, integer division yielded a zero-sized group and an unbounded loop.
normalizeScanReadersnow assigns every source reader to exactly one pipeline, fills genuinely empty slots withEmptyReader, and balances surplus readers. Fullpkg/sql/compiletests pass; the new cardinality/ownership regression covers 0, 1, 2, 3, and 5 source readers across parallelism 1-3.Runtime-filter behavior
The integrated branch preserves upstream #29650: a runtime-filter DROP or statically false predicate returns empty readers before range collection or ordinary reader construction. PASS, nonempty filters, required-filter errors, cancellation, reader ownership, and immutable workspace read views retain their respective execution paths.
The complete compile suite and the two-CN
TestODKUEmptyUniqueValidationregression pass on the integrated revision. The latter covers ordinary, KEY/RANGE-partitioned, and composite-UNIQUE tables, prepared DROP/INSERT reuse, physical zero-scan accounting, duplicate rejection, and join behavior. The earlier September SQL-task BVT results were obtained on the pre-integration implementation; a fresh full two-CN/Proxy BVT run remains for CI.October 8 conflict resolution
Merged current main
bab4b3286ain466b74de6d, resolving the textual conflicts and adapting newly introduced callers/tests to the logical workspace API:TableOverlay, rather than reintroducing a transaction-wide write scan; mutation rewrite, retirement, selections, and statement rollback keep the derived estimate consistent;Verification on this integrated code (Go 1.27.0, macOS arm64):
go build -p 2 ./...: passed.pkg/vm/engine/disttae,pkg/frontend,pkg/sql/compile,pkg/txn/client,pkg/vectorindex/ivfflat, andpkg/lockservice: passed.TestODKUEmptyUniqueValidation,TestDataBranchPickDeletedKeyWorkspaceStatementOwnership, andTestIssue26404MixedDataBranchLifecycleDoesNotDeadlock: passed.Test(TxnWorkspace|Workspace|TombstoneTransfer|PartitionRowEstimate|TransientTableStats)inpkg/vm/engine/disttae: passed.One full frontend run observed the unchanged
TestConnMeasuresDelayedBufferedFlushfail because its measured wait was zero; the subsequent complete frontend run passed. Both that test and its implementation are identical to merged main, and no timing-test changes are included.Original local launch configuration and
.bench/files remain outside the PR. No CI workflow or PR state changes are included.Coverage CI follow-up (September 24)
Compile.TxnReadViewwhen a pooled Compile is cleared. Without that reset, a remote query could inherit another transaction's view and fail withworkspace read view belongs to another transaction. Added a reuse regression test and verified the affected remote DML/isolated issue tests.workspace statement has unfinished write scopesinpick_8.sqlandTestDataBranchPick; nested Compile retry against an operation-owned boundary incorrectly rolls back prior staged DDL (TestIssue26404). The fix disables nested retries when the process does not own the statement and retries the complete independent PICK/MERGE transaction on RC retry errors. DIFF is not replayed because it can stream output or write files. A new two-CN regression repeats the deleted-key PICK 20 times.1025987545, ordinary UT and Proxy Compose BVT failed on the same Data Branch ownership bug; downstream Coverage aggregation failed because ordinary UT did not publish a complete profile. Coverage UT, shared build, SCA, Connector/J E2E, and Pessimistic multi-CN BVT passed. At99d22aa0d9, full localcompile,dml,issues, andissues/isolatedpackages pass; fullfrontendpasses when rerun alone. The unrelatedTestConnMeasuresOnlyPhysicalOutputWritefailed once when all five packages ran concurrently, then passed three isolated repeats and the full frontend rerun. Full CI run 35959322935 completed successfully at99d22aa0d9: ordinary UT, coverage UT and aggregation, shared build, SCA, Connector/J E2E, Proxy Compose BVT, Pessimistic multi-CN BVT, andCI Requiredall passed. The former Proxy failurepick_8.sqlpassed 72/72 statements with 0 failures; the former UT failureTestDataBranchPickand the new 20-iteration ownership regression passed in the UT log.Spill failure ownership review follow-up (September 24)
QA Decision
QA required: yes — transaction workspace ownership, spill/rollback, visibility and distributed readers change. Verify long transactions, in-transaction reads, cancellation and failed spill cleanup, prepared DML, Data Branch and two-CN/Proxy behavior on the delivered revision. Preserve the separate transaction-phase and COMMIT performance measurements above; deployment/crash recovery are not inferred from local tests.