Skip to content

refactor(disttae): redesign CN transaction workspace - #27013

Closed
gouhongshen wants to merge 30 commits into
matrixorigin:mainfrom
gouhongshen:codex/txn-workspace-access-index
Closed

gouhongshen wants to merge 30 commits into
matrixorigin:mainfrom
gouhongshen:codex/txn-workspace-access-index

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Aug 12, 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.

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 to txn.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:

  • StatementJournal owns statement identity, retry attempts, rollback resources, RC boundaries, DDL operations, and LOAD-created files.
  • TableOverlay owns each table's active mutations, PK candidates, row/block tombstones, uncommitted objects, and DDL visibility.
  • PayloadStore owns memory batches and spilled objects through generation-based leases. Readers pin payload generations instead of retaining unowned raw batch pointers.
  • WorkspaceReadView is an immutable logical visibility boundary. WorkspaceWriteMark identifies one write scope without exposing physical workspace positions.
  • CommitBuilder freezes 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:

  • statement begin/end, active write-scope ownership, out-of-order branch completion, exactly-once closure, and retry identity;
  • statement rollback and RC snapshot advancement as one workspace boundary transition;
  • reader visibility across local, combined, delegated, and sharded data sources;
  • CN transfer and table-meta readers using the exact read view captured by their execution;
  • three-phase spill (capture/pin -> I/O -> validate/publish) so stale or rolled-back attempts cannot publish;
  • DDL create/drop/rename visibility and exact rollback, including one active catalog name per table ID;
  • LOAD object ownership and cleanup across statement retries;
  • payload generation reclamation only after all leases close;
  • construction of the existing TN commit protocol through CommitBuilder.

Protocol-order correctness

Logical visibility order and TN precommit protocol order are separate concerns. This PR models protocol order with a commitEpoch advanced by ordinary Compile read-view publication:

  • write scopes are active ownership tokens rather than a LIFO stack, because UNION branches and internal Data Branch SQL may complete in a different order from their start order;
  • internal SQL inherits the caller's epoch, allowing later-produced catalog mutations to precede user-table mutations within one Compile;
  • a new ordinary Compile advances the epoch, preventing a later statement's catalog mutation from crossing an earlier statement boundary;
  • same-statement physical rewrites preserve the source mutation's immutable commit order;
  • a later statement rewriting an older mutation receives the current epoch, so recreated catalog metadata is sent before rewritten table data.

This fixes the DDL/DML regression exposed by delete_workspace.sql without reintroducing physical workspace offsets.

Retry preparation and physical payload maintenance

RollbackLastStatement leaves the failed attempt rolled back and retry-pending, while IncrStatementID(false) may compact or spill completed mutations before opening the successor attempt. Physical maintenance now uses a deliberately narrow owner-preserving replacement path:

  • only mutations owned by earlier completed attempts are accepted;
  • immutable StatementID, AttemptID, commit order, and visibility are preserved;
  • replacement never registers the mutation in the failed or successor attempt;
  • ordinary logical rewrites, failed-attempt mutations, and cross-attempt replacement remain rejected.

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:

  • PublishReadView and CurrentReadView replace snapshot/write offset accessors.
  • BeginWriteAttempt and Adjust(WorkspaceWriteMark) replace positional adjustment.
  • Ranges, CollectTombstones, and reader construction accept WorkspaceReadView instead 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:

UPDATE volume_files SET sandbox_path = ? WHERE id = ?;

The test preloads 500,000 rows, executes all 500,000 single-row UPDATEs in one transaction, and then either rolls back or commits.

Build / database 500,000 UPDATEs
Issue baseline, MatrixOne main did not finish in 30 minutes; 170,000 completed
This PR at ae69b2b3c3 106.91-107.72s
MySQL reference about 114.19s
PostgreSQL reference about 105.76s

The latest rollback runs completed in 107.719s and 107.555s. The commit run completed UPDATEs in 106.911s, committed in 1.857s, and finished in 108.768s total.

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 at 200.588us, p95 at 271.100us, and p99 at 284.804us.

Post-commit validation confirmed 500,000 rows, 500,000 distinct sandbox_path values, and correct first/middle/last values.

ORM Unit of Work

Protocol from #26796:

  • fresh MatrixOne instance and data directory for each sample;
  • 30,000 rows preloaded outside measurement;
  • one client, one connection, one long transaction;
  • 30,000 prepared parameterized UPDATEs against different primary keys;
  • one COMMIT after all UPDATEs;
  • primary key plus unique indexes on email and external_id.
UPDATE customer_profile
SET level = level + 1, updated_at = ?
WHERE id = ?;
Build / database Transaction phase First-to-last window behavior
MatrixOne main at a4b0ce286d 19.465s 0.212766ms -> 1.081877ms (5.0848x)
This PR at ae69b2b3c3, fresh sample median 3.773s average ratio at most 1.20x; p50 ratio 0.98-1.09x
MySQL 8.4.11 6.432s 0.9798x
PostgreSQL 18.4 6.097s 0.9531x

Three fresh PR samples completed the UPDATE phase in 2.783s, 3.773s, and 6.644s. Their first-three versus last-three window p50 ratios were 1.001x, 0.983x, and 1.086x. The average-window ratios remained below 1.20x; isolated 30-70ms outliers appeared at unrelated transaction positions rather than increasing with transaction size.

COMMIT took 71-100ms in 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.

Build / database Transaction phase COMMIT Last 3 / first 3 window p50
Issue baseline, MatrixOne main 30.479s 125.189ms 3.3118x
This PR, fresh sample 1 5.116s 201.940ms 1.016x
This PR, fresh sample 2 5.220s 431.742ms 0.993x
This PR, fresh sample 3 5.338s 208.670ms 1.012x
MySQL reference 9.618s 6.867ms 1.0046x
PostgreSQL reference 9.030s 0.419ms 0.9989x

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.

Build / database Transaction phase COMMIT Last 3 / first 3 window p50
Issue baseline, MatrixOne main 29.354s 93.728ms 4.1613x
This PR, fresh sample 1 4.191s 158.537ms 0.964x
This PR, fresh sample 2 4.271s 171.149ms 0.991x
This PR, fresh sample 3 4.092s 158.975ms 0.962x
MySQL reference 8.588s 5.824ms 1.0029x
PostgreSQL reference 8.054s 0.468ms 0.9991x

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.

Build / database Transaction phase COMMIT Last 3 / first 3 avg window Last 3 / first 3 read latency
Issue baseline, MatrixOne main 72.504s 50.965ms 7.5155x 46.278x
This PR, fresh sample 1 4.202s 61.859ms 0.882x 0.550x
This PR, fresh sample 2 4.109s 62.415ms 1.017x 0.652x
This PR, fresh sample 3 4.123s 63.007ms 0.918x 0.684x
MySQL reference 6.583s 4.703ms 1.0172x 1.001x
PostgreSQL reference 6.268s 0.433ms 0.9494x 2.269x

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 equivalent INSERT ... 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.

Build / database Transaction phase COMMIT Total Median last 3 / first 3 avg window
Issue baseline, MatrixOne main 289.070s 131.372ms 289.201s 0.942x
This PR, fresh sample 1 10.945s 156.657ms 11.102s 0.997x
This PR, fresh sample 2 10.903s 162.006ms 11.065s 1.077x
This PR, fresh sample 3 10.519s 181.164ms 10.700s 1.022x
MySQL 8.4 11.281s 0.368ms 11.282s 1.042x
PostgreSQL 18 11.330s 0.563ms 11.331s 1.030x

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 DELETE and one parent UPDATE for 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.

Build / database Transaction phase COMMIT Last 3 / first 3 avg window
Issue baseline, MatrixOne main 172.976s 105.567ms 0.034x
This PR, fresh sample 1 56.980s 147.989ms 0.503x
This PR, fresh sample 2 56.829s 145.512ms 0.507x
This PR, fresh sample 3 56.817s 145.900ms 0.505x
MySQL reference 8.558s 6.559ms 0.996x
PostgreSQL reference 7.944s 0.663ms 0.972x

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 deleted and 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_key had UNIQUE.

This PR schema Transaction phase DELETE total UPDATE total COMMIT
Without UNIQUE(product_key) 5.450s 2.826s 2.617s 114.771ms
With UNIQUE(product_key) 60.199s 57.288s 2.904s 156.150ms

The 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 ANALYZE confirmed 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=1
  • make build
  • DDL BVT: 7,815 total, 7,695 passed, 120 ignored, 0 failed
  • DML BVT excluding CDC: 5,855 total, 5,735 passed, 120 ignored, 0 failed
  • Snapshot BVT: 17,716 total, 17,716 passed, 0 failed
  • CDC syntax: 4/4 passed
  • CDC behavior: 11/11 passed using an uncommitted temporary endpoint-only test adjustment
  • distributed TPCC and write-oriented sysbench regression workflows completed without correctness failures
  • git diff --check

The 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:

  • sampled ANALYZE captures one immutable WorkspaceReadView and uses it consistently for ranges, tombstones, and readers;
  • historical IVF hidden-table scans use the snapshot clone operator read view rather than the parent transaction read view;
  • parallel-reader cancellation tests reach reader construction through a real relation fixture, while statically false scans retain the EmptyReader fast path;
  • lock handoff diagnostics use the holders abstraction instead of the removed map field;
  • prepared integer casts use the corrected upstream constant-folding behavior from 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. normalizeScanReaders now assigns every source reader to exactly one pipeline, fills genuinely empty slots with EmptyReader, and balances surplus readers. Full pkg/sql/compile tests 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 TestODKUEmptyUniqueValidation regression 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 bab4b3286a in 466b74de6d, resolving the textual conflicts and adapting newly introduced callers/tests to the logical workspace API:

  • preserve upstream runtime trace retirement, statement callbacks, and terminal table-deletion checks;
  • maintain the planner's conservative insert-row estimate incrementally in TableOverlay, rather than reintroducing a transaction-wide write scan; mutation rewrite, retirement, selections, and statement rollback keep the derived estimate consistent;
  • preserve RC tombstone-transfer improvements and the distinction between physical catalog relation names and authorized write names in transfer, spill, and object compaction;
  • preserve Data Branch pessimistic-RC admission, latest runtime-filter empty-scan semantics, IVF in-memory partition ownership, and embedded Sirius read-view propagation;
  • retain the memory-delete row-offset bounds check while using the workspace index.

Verification on this integrated code (Go 1.27.0, macOS arm64):

  • go build -p 2 ./...: passed.
  • Full unit suites: pkg/vm/engine/disttae, pkg/frontend, pkg/sql/compile, pkg/txn/client, pkg/vectorindex/ivfflat, and pkg/lockservice: passed.
  • Two-CN regressions TestODKUEmptyUniqueValidation, TestDataBranchPickDeletedKeyWorkspaceStatementOwnership, and TestIssue26404MixedDataBranchLifecycleDoesNotDeadlock: passed.
  • Focused race suite for Test(TxnWorkspace|Workspace|TombstoneTransfer|PartitionRowEstimate|TransientTableStats) in pkg/vm/engine/disttae: passed.
  • New regressions cover planner row bounds after rewrite/rollback and preservation of catalog write names during physical relation lookup.
  • Diff whitespace check against merged main: passed. Full distributed/Proxy BVT and Linux CI have not yet been validated on this revision.

One full frontend run observed the unchanged TestConnMeasuresDelayedBufferedFlush fail 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)

  • Reset Compile.TxnReadView when a pooled Compile is cleared. Without that reset, a remote query could inherit another transaction's view and fail with workspace read view belongs to another transaction. Added a reuse regression test and verified the affected remote DML/isolated issue tests.
  • Data Branch needs one operation-owned workspace statement across concurrent producer/consumer SQL. Per-nested-SQL boundaries fail with workspace statement has unfinished write scopes in pick_8.sql and TestDataBranchPick; 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.
  • At 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. At 99d22aa0d9, full local compile, dml, issues, and issues/isolated packages pass; full frontend passes when rerun alone. The unrelated TestConnMeasuresOnlyPhysicalOutputWrite failed once when all five packages ran concurrently, then passed three isolated repeats and the full frontend rerun. Full CI run 35959322935 completed successfully at 99d22aa0d9: ordinary UT, coverage UT and aggregation, shared build, SCA, Connector/J E2E, Proxy Compose BVT, Pessimistic multi-CN BVT, and CI Required all passed. The former Proxy failure pick_8.sql passed 72/72 statements with 0 failures; the former UT failure TestDataBranchPick and the new 20-iteration ownership regression passed in the UT log.

Spill failure ownership review follow-up (September 24)

  • The workspace spill adapter now aborts a failed CNS3Writer before Close, collecting both persisted and commit-ambiguous object names. Cleanup uses a cancellation-independent, bounded context; the original staging error is preserved alongside any cleanup error.
  • Objects from earlier staged groups are not handed to generic asynchronous GC after publication fails. Their exact names move to an Engine-owned cleanup ledger before deletion; failed deletes stay owned and are retried, including during Engine.Close. Successfully published objects never enter this ledger. The retry ledger is process-local; crash-durable CN orphan recovery is not claimed by this follow-up.
  • Corrected CNS3Writer.Close to release its block-info batch even if sinker.Close reports an error. The design document now states the out-of-order active write-scope contract and the spill cleanup ownership boundary.
  • Deterministic regressions cover first-object persistence followed by later post-persist Write/Sync failure, canceled request context, deletion failure and later retry, successful publication, payload lease/MPool baseline, and the Engine.Close failure path.
  • Local verification: full disttae and colexec unit suites; targeted race tests for the new spill cases; git diff --check. All passed.

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.

…-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 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.

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.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

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.

This branch had an error being deployed

1 failed deployment
ci — 466b74de Deployed Oct 8, 2026 by gouhongshen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/api-change kind/bug Something isn't working kind/enhancement kind/refactor Code refactor kind/test-ci size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants