Skip to content

Protect borrowed vector data during in-place mutation - #32076

Merged
mergify[bot] merged 15 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/130f302b956f6c78ab0369d49bf4df2587e131c621f8ade373b08389c69103bf
Nov 3, 2026
Merged

mergify[bot] merged 15 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/loom/develop/130f302b956f6c78ab0369d49bf4df2587e131c621f8ade373b08389c69103bf

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Nov 3, 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:

What this PR does / why we need it:

Shrink and in-place sorting can overwrite borrowed vector data, changing retained views. Prepare a writable copy of borrowed data before mutation, while preserving independently shared variable-length area. Propagate allocation errors through callers and clean up their owned resources; a failed batch operation does not promise rollback of earlier columns. Preserve row metadata and sorted-state behavior.

Validation:

  • Owning and direct consumer package tests cover all 31 affected Go packages, with vector and batch rerun after the final production change. Vector package race tests and six targeted lifecycle tests repeated under race passed; final vector tests include ordered shrink boundary coverage.

  • Nullable IN BVT: the targeted case passed twice (42/42 each), and the directory passed (87/87). These runs used an instrumented server binary and tester configuration, so they do not establish a pass for the final uninstrumented artifact or CI.

  • Single-machine, alternating 1-second benchmark comparisons showed zero allocations on the measured ordinary paths. The four final-product comparisons had median changes of +0.80% to +7.42%; a separate repeat of the +7.42% case was +0.89%. Results vary with machine and binary layout and do not establish equivalence or SQL throughput across platforms. Borrowed-data copy costs were measured separately.

  • Linux SCA, UT, UT coverage and both BVT producers passed at 224819e826cb1006ff8d2338b70c8f9cdfda11cb in run 41602040942. Its changed-code coverage gate failed at 299/447 (66.89%).

  • Tests at aea318d8fa74d3685d219dd058f9ae6ac6107dda cover fixed-type compaction/retained owners, mask and constant boundaries, metadata admission rejection, and caller error propagation. Local Darwin/arm64 mo-cgo-test -short -tags matrixone_test -covermode=set -count=1 passed vector, batch and readutil; vet, golangci-lint v2.14.0, pinned molint and header checks passed. Reusing that CI profile for unchanged production code and merging the new local profile, the same pinned CI parser reports 336/447 (75.17%), above the unchanged 75% threshold. This is combined local evidence; the new Linux coverage gate remains pending.

CI results are pending.

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

@mergify mergify Bot added the kind/bug Something isn't working label Nov 3, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Nov 3, 2026
@XuPeng-SH

XuPeng-SH commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: aea318d8fa74d3685d219dd058f9ae6ac6107dda

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Commit: aea318d8fa74d3685d219dd058f9ae6ac6107dda

Assessment: approve

No actionable defects remain. Data-only copy-on-write reuses existing lease and allocation ownership, preserves shared varlen areas, and propagates failures through caller cleanup without adding batch-wide rollback machinery.

Model: gpt-6.1-sol / max

Session: 01a1a004-9884-72c0-ad39-f096c4209c4a · slot 1 · generation 0

Validation:

  • Reviewed all 80 changed files, linked issue requirements, complete discussion, and affected ownership/error paths.

  • Frozen-head CI reports successful build, UT, SCA, coverage, proxy BVT and pessimistic BVT.

  • Local static audit passed: checks/1793706271722291853-2.json and source-audit.log confirm clean frozen source, matching delta, whitespace checks and complete discussion coverage.

Limitations:

  • No local Go, race, benchmark or BVT runs. Detailed CI logs and author execution artifacts were not supplied; reported performance and race results were not independently reproduced.

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

mergify Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

✅ Merged into main as 523ab21 at 15:13 UTC

3 h 27 min in the queue, 1 h 3 min of it CI.

So far

  • ✅ Entered the queue Tue 3 Nov, 11:46 · rule main · triggered by rule Automatic queue on approval for main
  • ✅ Passed · in place
  • ✅ Merged 15:13 · 523ab21 · squash
3 merge conditions met
  • #review-threads-unresolved = 0 · required by GitHub branch protection
  • github-review-approved · required by GitHub branch protection
  • any of · required by GitHub branch protection:
    • check-success = CI Required
    • check-neutral = CI Required
    • check-skipped = CI Required

Times in UTC · dashboard · how the merge queue works

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

Codex automated review

Reviewed the full diff origin/main...HEAD (aea318d) for PR #32076, saved to scratch and re-inspected in this pass. The change makes Vector.Shrink/ShrinkByMask/InplaceSort/InplaceSortAndCompact and Batch.Shrink/ShrinkByMask copy-on-write safe for borrowed and LegacyAlias backing via the new PrepareDataForInplaceMutation, converts roughly 83 call sites to the new error-returning signatures, and adds regression tests. Prior behavior: in-place mutation wrote directly into borrowed data, corrupting shared buffers (issue #32045). I verified from code that the new behavior satisfies the issue contract: PrepareDataForInplaceMutation is a no-op unless cantFreeData && len(data)>0, copies only data (never the independently owned varlen area), and a failed allocation leaves the existing backing and lease unchanged, as its tests prove. In Shrink I re-verified the needsWrite/skipData boundary math: negate deletes write only when sels[0] < length-len(sels) (ordered sels, so suffix deletes are free), select writes only when some sels[i] != i (prefix keeps are free), empty sels never write; the skipData path still remaps gsp/nsp via nulls.FilterInPlaceOrdered, adjusts length, and runs the same prepareParamKinds/stringSources remaps as the compact loop, with areaDisjoint cleared for varlen in both paths. InplaceSort/InplaceSortAndCompact conditionally ensure null/grouping/string-source capacity, publish compacted length only when no nulls/metadata exist, extend the row-metadata sorter gate with nsp/gsp checks, and their early returns match old behavior; supportsInplaceSort matches the sort switch exactly. Error propagation and cleanup check out at the converted callers: disttae txn deleteBatch prepares all vectors before mutation with ascending selections, logtailreplay change_handle.filterBatch sorts delete lists before negate shrinks and cleans partial state on error, local_disttae_datasource releases deletedMask on every path, cteaccount uses Rollback vs Discard verbs consistently with adjacent Commit-error paths, and hashbuild/indexbuild/fuzzyfilter fallback helpers pre-exist on origin/main. readutil nil-mpool COW rejection leaves input bytes untouched; the partitionprune fail-open path is deliberate and tested. Owned-path performance adds at most one nil check plus a no-op call, and skipData avoids an O(n) copy for borrowed prefix/suffix selections. Coverage includes borrowed/LegacyAlias regression tests, negate-boundary tests, allocation-failure admission tests, batch no-rollback contract tests, and BVT cases for nullable IN constants; production code is identical to the CI-passed commit 224819e (only tests added since). PR discussion loaded: one mo-bot review APPROVED with no actionable defects, no inline review comments, and no human findings to deduplicate or reconcile. Limitation: I could not compile or run tests in this checkout because the jemalloc thirdparty headers are absent and CGO_ENABLED=0 fails with undefined: malloc.SimpleCAllocator, and environment repair was prohibited; I compensated with gofmt and a syntax parse of all 78 changed Go files plus a strict scan for old-arity call sites, all clean. No blocking or non-blocking defects found.

@mergify
mergify Bot merged commit 523ab21 into matrixorigin:main Nov 3, 2026
@mergify mergify Bot removed the queued label Nov 3, 2026
gouhongshen added a commit to gouhongshen/matrixone that referenced this pull request Nov 3, 2026
Merge origin/main (523ab21) to clear the base conflict. The only
textual conflict was pkg/vm/engine/disttae/txn.go: main's matrixorigin#32076 copies
borrowed vector data before in-place mutation and propagates allocation
failures through shrinkWorkspaceEntryBatchLocked, deleteBatch and their
callers, while this branch retires fully-superseded workspace entries
through the same functions (issue matrixorigin#25590).

The resolution keeps both contracts:

- shrinkWorkspaceEntryBatchLocked returns (retired bool, err error):
  every vector's borrowed data is copied into writable storage before
  any row is shrunk and an allocation failure propagates before
  mutation, leaving the entry's accounting and pending selections
  untouched (upstream matrixorigin#32076), while an entirely-superseded batch is
  still retired through releaseWorkspaceEntryBatchLocked with the
  branch's statement-dump ordering (matrixorigin#25590).
- mergeTxnWorkspaceLocked propagates the shrink error; upstream's
  failure oracle (TestBorrowedWorkspacePreparationFailurePreservesState)
  now also asserts that a failed preparation retires nothing.
- The branch's nine deleteBatch test call sites take two values with an
  explicit NoError check on the now-fallible path.
- All other overlapped hunks merged cleanly with both sides' guarantees
  intact: fileservice's concurrent-deletion IsNotExist swallow lives
  inside main's deleteLocalFile helper; sinker keeps the capacity-hook
  plumbing around main's fetchBuffer/pushStaged/WriteOwned error-path
  ownership fixes; s3WriterDelegate layers main's ShrinkByMask error and
  taken-ownership-on-error semantics over the branch's delegate rebind;
  multi_update's filterTargetRows keeps the reused-delegate workspace
  rebind around main's shrink-failure cleanup; CommitWaitInjected runs
  through scoped fault triggers preserving the branch's commit-barrier
  selectors.

Focused disttae regressions (upstream failure oracle plus the branch's
retirement, rollback and mixed-ownership families) pass on the merged
tree.
mergify Bot pushed a commit that referenced this pull request Nov 4, 2026
…orphan-cleanup ownership (#30988)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to #25590

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

Long explicit transactions repeatedly updating the same primary-key rows rescan superseded workspace history at statement boundaries and during reads. This PR keeps incremental per-table views and compacts superseded entries so maintenance follows the live working set. The issue's UPDATE, REPLACE and DELETE+INSERT cases are covered by focused workspace tests and SQL cases.

Persistence and compaction also need a complete ownership contract: every unpublished object must reserve bounded capacity and remain owned until publication or cleanup. The implementation centralizes that contract in the workspace/engine, retains failed cleanup work, and drains it with bounded batches/backoff and a single shutdown budget. Local writers and remote fragments share the same same-version admission contract running on one build; remote ownership transfer proves the coordinator's intake adoption through the run's own batch-flow sequence/ack/drain barrier, installed in both stream modes (negotiated windowed and no-window alike), and clone-borrowed objects retain their existing owner. No per-feature protocol version, peer-capability gate or legacy fallback exists anywhere in the diff (the design document's `r16`/`r17` records record that removal). Main's #26796 key-index/envelope ownership and Engine.Close shutdown ordering are preserved.

The [versioned design](https://github.com/gouhongshen/matrixone/blob/agent/issue-25590-6d5e84a3/docs/design/20261021-issue-25590-workspace-scaling-and-cleanup-ownership.md) carries the operative r17 design, the decision log, the per-round review records with their approval trace, and the per-invariant validation criteria (§7).

### Delivered behavior

- **Workspace statement scaling** — statement boundaries retire and compact superseded entries, per-table views follow the live working set, and rollback/commit recovery keeps the frontend's statement semantics intact.
- **Ownership and capacity** — every persisted-but-unpublished object joins a fail-closed per-object admission bound at creation (insert sinkers, temporary data and tombstone writers, compaction rewriters, direct-S3 writers and the RC tombstone transfer), holds its unit until publication, transfer, or a proven deletion, and stays enumerable by exactly one owner at every instant; the aggregate obligation population stays pinned at the per-engine sums under sustained stalled deletion.
- **Settle and retire lifetimes** — a proven deletion retires the ledger membership, the owning workspaces' per-claim capacity, and the transaction's recorded-name copy together; queued recorded names retire through the drain through a holder that never retains the completed transaction's graph; an accepted GC job holds its batch's capacity until the storage call proves the deletion, and a failed or unproven batch requeues losslessly to the bounded retry owner instead of settling.
- **Reuse and reset** — writer Reset clears its failure-only staged slice; a reused delegate rebinds its persistent sinkers' capacity hook to the current workspace at Prepare and clears it at Reset, so no execution-scoped workspace reference outlives its transaction.
- **Remote fragments (same-version plane only)** — the coordinator's intake adopts every relayed name through the same reservation before a clean run can settle; the adoption/drain barrier exists in both stream modes; a transferred settlement settles the ledger, keeps the adopted objects' recorded-name fate, and tears down the mirror's local workspace and segment claims; owner-scoped retirement keeps CN-wide segment-map scans out of fragment settlement.

### Validation

Focused deterministic regressions cover each contract in its owning packages (`pkg/vm/engine/disttae`, `pkg/sql/colexec` with `multi_update`/`insert`/`deletion`, `pkg/sql/compile`, `pkg/objectio/ioutil`) and at the engine level (`pkg/vm/engine/test`), with `-race` legs for every synchronization-bearing change and counterexample-red/green proofs run during review. The context-blind deletion barrier's own failure path is pinned the same way: its release and bounded drain join run through the test's registered cleanup (idempotent against the explicit ordering-oracle release), and `TestIssue25590DeleteGateCleanupReleasesParkedWorker` proves the state a failing assertion leaves behind holds no parked worker. SQL-visible behavior is pinned by `test/distributed/cases/dml/{update,delete,replace}_workspace.*` and `update_remote_fragment_capability.{sql,result}`; every generated result was inspected against the intended semantics. The maintained per-invariant coverage spine and its criteria are recorded in the design document's §7.

### Review and validation history

Each review round's finding, repair decision, and outcome is recorded in the design document's review records, with the compact approval trace in that document's header. This description previously carried the per-round execution chronicle as well; it was removed on 2026-10-30 after the delivery review's P2 on the same class in the design document (the repository's review contract excludes per-run evidence and review attestations from tracked delivery). The pre-cleanup design document and description are archived byte-identical outside the tracked repository with the loop controller; per-run CI evidence remains available through GitHub's run artifacts.

- **2026-11-03 base merge**: cleared the `CONFLICTING` base state by merging `origin/main` at `523ab21543` (upstream #32076 among other advances). The single conflict, `pkg/vm/engine/disttae/txn.go`, resolved to the union of #25590's superseded-entry retirement and #32076's borrowed-vector protection: `shrinkWorkspaceEntryBatchLocked` now returns `(retired bool, err error)` — borrowed vector data is copied into writable storage before any in-place shrink, an allocation failure propagates before mutation and retires nothing, and a fully-superseded batch still retires through the statement-dump-ordered release. `mergeTxnWorkspaceLocked` propagates the shrink error, upstream's failure oracle now also asserts that a failed preparation retires nothing, and the branch's `deleteBatch` test call sites assert the now-fallible path. Post-merge validation: the focused disttae regressions (upstream failure oracle plus the retirement/rollback/mixed-ownership families), the full `TestIssue25590*` regression family, the `multi_update` and `objectio/ioutil` package suites, and `go vet` across the changed closure all pass through the repository's CGo wrapper.

### Known limitations

- The lossless contract's restart clause: a crash mid-queue can leak objects the base build could also leak (the accepted class documented in the design's §6).
- Pre-existing, unrelated CI flake classes are tracked on their own issues — #8767 (logservice hakeeper churn), #30949 (PROXY compose subscription-source flake), #31044 (`TestCrossTargetUpgradeRecovery` hang) — with reproduction records posted there; this PR's CI record is evaluated against them.
- Local macOS/arm64 validation runs through the repository's CGo wrapper for the focused families; the CI matrix (UT, coverage, SCA, multi-CN and e2e BVT) is the authoritative full-suite evidence for the changed closure.




Approved-by: XuPeng-SH <[email protected]>
Approved-by: fengttt <[email protected]>
Approved-by: aunjgr <[email protected]>
mergify Bot pushed a commit that referenced this pull request Nov 7, 2026
## What type of PR is this?

- [x] Test and CI

## Which issue(s) this PR fixes:

issue #32045

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

Update 12 JDBC metadata expectations in the early filter fallback result fixture: ten `varchar(20)` widths, the `SUM(rows_cnt)` decimal type code, and the `mo_ctl` result width. The SQL, values, remaining metadata, and comparison strength are unchanged. These expectations follow the declared output types and address feedback after #32076 was merged; the original borrowed-data fix is already in #32076.

Validation on this revision:
- Strict comparison of the target case passed twice (42/42 each); strict comparison of the owning directory passed (87/87), using a fixed tester and a single instance.
- Vector and batch package tests, vector package race tests, and targeted consumer failure and cleanup tests passed.
- CI remains to run. The single-instance SQL run does not establish that SQL exercised borrowed backing.

Performance: this result-only change does not modify production code or its hot paths. Performance measurements for the original fix are historical and were not repeated as a current comparison against the pre-fix revision.


Approved-by: XuPeng-SH <[email protected]>

This branch was previously deployed

1 inactive deployment
ci — 781dcefe Deployed Nov 3, 2026 by mergify[bot]
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 size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants