Skip to content

fix(txn): prevent stale table generation writes after DDL - #26757

Merged
XuPeng-SH merged 5 commits into
mainfrom
fix/issue-26756-ddl-generation-retry
Aug 6, 2026
Merged

XuPeng-SH merged 5 commits into
mainfrom
fix/issue-26756-ddl-generation-retry

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 6, 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:

fixes #26756

What this PR does / why we need it:

A copy-based ALTER TABLE can replace a physical table generation between CN catalog resolution and DML locking. A late CN could therefore lock the old table ID without observing the completed DDL, carry that ID into PrecommitWriteCmd, and expose TN's internal ExpectedEOB.

Required invariant:

After a statement snapshot crosses a committed table-definition change, a plan bound to the previous physical generation must not execute.

This PR closes that invariant at both ownership boundaries:

  1. Lockservice retains the latest committed definition-change timestamp per lock table. DDL abort never advances the fence.
  2. Definition intent belongs to a holder generation:
    • waiting behind ordinary DML cannot clear the DDL request's own intent;
    • promotion and same-transaction re-entry apply the requester's intent;
    • ownership transfer replaces the predecessor bit;
    • aborted DDL clears the old holder generation before notifying successors, so a later ordinary commit cannot manufacture a fence.
  3. Lockservice only returns the retained marker to transactions whose creation timestamp predates it. CN then compares the marker with the precise statement snapshot. Fresh transactions have no marker on the wire.
  4. For RC, a stale statement waits for logtail, advances its snapshot, and returns ErrTxnNeedRetryWithDefChanged; compile retry rebuilds the logical plan. SI returns a write-write conflict.
  5. Definition retry takes precedence over refresh-expression because refreshing row versions cannot repair a stale physical table ID.
  6. TN uses one catalog-resolution helper for every relation-bound write entry. Database/relation ExpectedEOB becomes ErrTxnNeedRetryWithDefChanged for normal writes and SOFT_DELETE_OBJECT; object-level ExpectedEOB keeps its existing “already absent” meaning.

Performance and compatibility

  • Tables with no committed DDL add only a nil check.
  • After same-ID/in-place DDL, fresh transactions add one timestamp comparison in lockservice but no response allocation, marker wire bytes, RPC, catalog lookup, or plan rebuild.
  • Only transactions old enough to contain a stale plan receive the optional marker. Long-running transactions whose statement snapshot is already fresh receive it conservatively but do not retry.
  • The retained state is one immutable timestamp per local lock table; later DDL replaces it instead of mutating in-flight results.
  • Protobuf field 11 is optional and wire-compatible: old readers ignore it and new readers treat absence as no retained fence.
  • When TN is upgraded, its authoritative fallback preserves correctness with old CN/lockservice nodes and across lock-table restart/rebind. Wire compatibility alone does not make an old TN perform the new retry mapping.

Validation

Deterministic lockservice coverage for row and range locks:

  • ordinary commit does not create a fence;
  • committed DDL creates and advances a fence;
  • DDL abort does not create or advance one;
  • DDL intent survives waiting behind ordinary DML;
  • holder promotion replaces predecessor intent;
  • an ordinary successor after aborted DDL cannot manufacture a fence;
  • same-transaction re-entry promotes definition intent;
  • fresh transaction responses omit the marker through protobuf round-trip.

CN coverage:

  • a stale statement rebuilds before row-version scanning;
  • refresh-expression cannot mask definition retry;
  • an aborted/uncommitted definition signal does not rebuild.

TN coverage:

  • replace a physical table while preserving its logical name;
  • writes bound to the old ID return ErrTxnNeedRetryWithDefChanged;
  • normal INSERT and SOFT_DELETE_OBJECT;
  • optimistic and pessimistic modes.

Fresh local validation after the final semantic edit:

  • focused adaptive race stress:
    • lockservice tests: measured 0.14s / 0.38s / 0.14s, -race -count=100/78/100;
    • CN tests: measured 0.08s / 0.08s, -race -count=100;
    • TN test: measured 0.05s, -race -count=100.
  • full normal and race packages:
    • ./pkg/lockservice
    • ./pkg/sql/colexec/lockop
    • ./pkg/vm/engine/tae/rpc
  • go build and go vet passed for all three owning packages.

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

@matrix-meow matrix-meow added the size/S Denotes a PR that changes [10,99] lines label Aug 6, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Aug 6, 2026
@matrix-meow matrix-meow added size/M Denotes a PR that changes [100,499] lines and removed size/S Denotes a PR that changes [10,99] lines labels Aug 6, 2026
@XuPeng-SH XuPeng-SH changed the title fix(tae): retry writes bound to stale table generations fix(txn): prevent stale table generation writes after DDL Aug 6, 2026
@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 Aug 6, 2026

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed the full diff at 820e9a4. The stale-generation retry boundary is closed across lockservice holder handoff/reentrant row and range locks, CN definition-retry precedence, and TN normal/soft-delete write resolution. The earlier holder-generation blocker is fixed. Focused counterexamples and adaptive race stress, full owning-package normal/race tests, build, and vet all pass locally.

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

Reviewed the full diff from 6798bd6 through 820e9a4. I traced the lockservice holder-generation state across row/range locks, commit/abort, waiter promotion/cancellation, re-entry, remote protobuf transport, and restart/rebind fallback; also checked CN RC/SI definition-retry precedence and TN relation-resolution handling for normal and soft-delete writes. I found no P0-P3 issues. The targeted regression coverage matches the changed boundaries, and all 31 checks are complete with no failures.

@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 820e9a4.

The overall direction and root-cause analysis are sound: retaining a committed definition fence closes the late-locker window, and mapping TN relation-resolution ExpectedEOB to definition retry provides the necessary final correctness backstop for normal and soft-delete writes.

I traced row/range holder generations, waiter promotion/cancellation, re-entry, commit/abort, protobuf transport, RC/SI retry precedence, restart/rebind fallback, and TN write preparation. The steady-state hot path remains bounded (a nil check; no per-lock allocation before a DDL fence), and I found no new leak, deadlock, unbounded queue/state, or OOM path.

One statement-snapshot invariant is still open. The inline P1 is reproducible and should be fixed before relying on the CN fence as an early-execution boundary. The TN fallback prevents the stale write from committing, but it does not prevent the stale statement from doing all intermediate work.

Comment thread pkg/sql/colexec/lockop/lock_op.go Outdated
// timestamp in the lock table as well, so a late locker can detect that its
// statement was compiled against an older physical table generation.
definitionChanged := (result.TableDefChanged && result.HasPrevCommit) ||
(result.TableDefChangedAt != nil && snapshotTS.Less(*result.TableDefChangedAt))

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.

[P1] Compare the fence with an immutable plan-bound snapshot

snapshotTS is read from the mutable transaction metadata here. performLock calls doLock for multiple targets (and batches), and an earlier target can call UpdateSnapshot during the ordinary RC refresh path before a later target reaches this comparison. If target A advances the snapshot to/past F and target B returns TableDefChangedAt=F, this condition is false even though B's plan was bound before the DDL.

I reproduced this deterministically with two targets and refresh-expression enabled: target A reports a new version and advances the snapshot; target B carries the retained definition fence; ctr.defChanged remains false and no definition retry is scheduled. The TN ExpectedEOB fallback still rejects eventual precommit, but the stale plan can execute its full intermediate/workspace/S3 work first.

Capture the snapshot against which the statement plan was bound once at statement-execution scope, use it for every definition-fence comparison across targets/batches/operators, and add this two-target ordering as a regression test.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Systematic follow-up pushed in 297d12f35a:

  • Bind an immutable snapshot to each logical plan/execution generation and use it only for DDL-definition fence checks.
  • Preserve that binding across data-only retries; refresh it for rebuilt plans and prepared-statement executions.
  • Propagate it by immutable pointer to all local pipeline processes and once through ProcessInfo to remote CNs; older messages safely fall back to the transaction snapshot.
  • Keep ordinary RC row-version scans on the current refreshed transaction snapshot, so the fix does not widen scan ranges.

Added counterexamples for cross-target snapshot advancement, the non-stale fence boundary, current-snapshot scan ranges, prepared/retry generations, both child-process constructors, remote codec/server reconstruction, and legacy wire messages.

Local verification passed: full pkg/vm/process, pkg/sql/colexec/lockop, and pkg/sql/compile tests; the same full package set under -race; owning-package build and vet. New CI is running.

@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 Aug 6, 2026
@XuPeng-SH
XuPeng-SH requested a review from aptend August 6, 2026 14:49

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed the update through 297d12f. The immutable plan-snapshot binding closes the cross-target RC advancement gap and is propagated across prepared reuse, data/definition retries, local child processes, and remote execution. I found no remaining P0-P3 code issues.

@XuPeng-SH
XuPeng-SH merged commit d0057b3 into main Aug 6, 2026
6 of 11 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/issue-26756-ddl-generation-retry branch August 6, 2026 15:58
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…in#26757)

## 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 matrixorigin#26756

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

A copy-based `ALTER TABLE` can replace a physical table generation
between CN catalog resolution and DML locking. A late CN could therefore
lock the old table ID without observing the completed DDL, carry that ID
into `PrecommitWriteCmd`, and expose TN's internal `ExpectedEOB`.

Required invariant:

> After a statement snapshot crosses a committed table-definition
change, a plan bound to the previous physical generation must not
execute.

This PR closes that invariant at both ownership boundaries:

1. Lockservice retains the latest **committed** definition-change
timestamp per lock table. DDL abort never advances the fence.
2. Definition intent belongs to a holder generation:
- waiting behind ordinary DML cannot clear the DDL request's own intent;
- promotion and same-transaction re-entry apply the requester's intent;
   - ownership transfer replaces the predecessor bit;
- aborted DDL clears the old holder generation before notifying
successors, so a later ordinary commit cannot manufacture a fence.
3. Lockservice only returns the retained marker to transactions whose
creation timestamp predates it. CN then compares the marker with the
precise statement snapshot. Fresh transactions have no marker on the
wire.
4. For RC, a stale statement waits for logtail, advances its snapshot,
and returns `ErrTxnNeedRetryWithDefChanged`; compile retry rebuilds the
logical plan. SI returns a write-write conflict.
5. Definition retry takes precedence over refresh-expression because
refreshing row versions cannot repair a stale physical table ID.
6. TN uses one catalog-resolution helper for every relation-bound write
entry. Database/relation `ExpectedEOB` becomes
`ErrTxnNeedRetryWithDefChanged` for normal writes and
`SOFT_DELETE_OBJECT`; object-level `ExpectedEOB` keeps its existing
“already absent” meaning.

## Performance and compatibility

- Tables with no committed DDL add only a nil check.
- After same-ID/in-place DDL, fresh transactions add one timestamp
comparison in lockservice but no response allocation, marker wire bytes,
RPC, catalog lookup, or plan rebuild.
- Only transactions old enough to contain a stale plan receive the
optional marker. Long-running transactions whose statement snapshot is
already fresh receive it conservatively but do not retry.
- The retained state is one immutable timestamp per local lock table;
later DDL replaces it instead of mutating in-flight results.
- Protobuf field 11 is optional and wire-compatible: old readers ignore
it and new readers treat absence as no retained fence.
- When TN is upgraded, its authoritative fallback preserves correctness
with old CN/lockservice nodes and across lock-table restart/rebind. Wire
compatibility alone does not make an old TN perform the new retry
mapping.

## Validation

Deterministic lockservice coverage for row and range locks:

- ordinary commit does not create a fence;
- committed DDL creates and advances a fence;
- DDL abort does not create or advance one;
- DDL intent survives waiting behind ordinary DML;
- holder promotion replaces predecessor intent;
- an ordinary successor after aborted DDL cannot manufacture a fence;
- same-transaction re-entry promotes definition intent;
- fresh transaction responses omit the marker through protobuf
round-trip.

CN coverage:

- a stale statement rebuilds before row-version scanning;
- refresh-expression cannot mask definition retry;
- an aborted/uncommitted definition signal does not rebuild.

TN coverage:

- replace a physical table while preserving its logical name;
- writes bound to the old ID return `ErrTxnNeedRetryWithDefChanged`;
- normal INSERT and `SOFT_DELETE_OBJECT`;
- optimistic and pessimistic modes.

Fresh local validation after the final semantic edit:

- focused adaptive race stress:
- lockservice tests: measured 0.14s / 0.38s / 0.14s, `-race
-count=100/78/100`;
  - CN tests: measured 0.08s / 0.08s, `-race -count=100`;
  - TN test: measured 0.05s, `-race -count=100`.
- full normal and race packages:
  - `./pkg/lockservice`
  - `./pkg/sql/colexec/lockop`
  - `./pkg/vm/engine/tae/rpc`
- `go build` and `go vet` passed for all three owning packages.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…in#26757)

## 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 matrixorigin#26756

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

A copy-based `ALTER TABLE` can replace a physical table generation
between CN catalog resolution and DML locking. A late CN could therefore
lock the old table ID without observing the completed DDL, carry that ID
into `PrecommitWriteCmd`, and expose TN's internal `ExpectedEOB`.

Required invariant:

> After a statement snapshot crosses a committed table-definition
change, a plan bound to the previous physical generation must not
execute.

This PR closes that invariant at both ownership boundaries:

1. Lockservice retains the latest **committed** definition-change
timestamp per lock table. DDL abort never advances the fence.
2. Definition intent belongs to a holder generation:
- waiting behind ordinary DML cannot clear the DDL request's own intent;
- promotion and same-transaction re-entry apply the requester's intent;
   - ownership transfer replaces the predecessor bit;
- aborted DDL clears the old holder generation before notifying
successors, so a later ordinary commit cannot manufacture a fence.
3. Lockservice only returns the retained marker to transactions whose
creation timestamp predates it. CN then compares the marker with the
precise statement snapshot. Fresh transactions have no marker on the
wire.
4. For RC, a stale statement waits for logtail, advances its snapshot,
and returns `ErrTxnNeedRetryWithDefChanged`; compile retry rebuilds the
logical plan. SI returns a write-write conflict.
5. Definition retry takes precedence over refresh-expression because
refreshing row versions cannot repair a stale physical table ID.
6. TN uses one catalog-resolution helper for every relation-bound write
entry. Database/relation `ExpectedEOB` becomes
`ErrTxnNeedRetryWithDefChanged` for normal writes and
`SOFT_DELETE_OBJECT`; object-level `ExpectedEOB` keeps its existing
“already absent” meaning.

## Performance and compatibility

- Tables with no committed DDL add only a nil check.
- After same-ID/in-place DDL, fresh transactions add one timestamp
comparison in lockservice but no response allocation, marker wire bytes,
RPC, catalog lookup, or plan rebuild.
- Only transactions old enough to contain a stale plan receive the
optional marker. Long-running transactions whose statement snapshot is
already fresh receive it conservatively but do not retry.
- The retained state is one immutable timestamp per local lock table;
later DDL replaces it instead of mutating in-flight results.
- Protobuf field 11 is optional and wire-compatible: old readers ignore
it and new readers treat absence as no retained fence.
- When TN is upgraded, its authoritative fallback preserves correctness
with old CN/lockservice nodes and across lock-table restart/rebind. Wire
compatibility alone does not make an old TN perform the new retry
mapping.

## Validation

Deterministic lockservice coverage for row and range locks:

- ordinary commit does not create a fence;
- committed DDL creates and advances a fence;
- DDL abort does not create or advance one;
- DDL intent survives waiting behind ordinary DML;
- holder promotion replaces predecessor intent;
- an ordinary successor after aborted DDL cannot manufacture a fence;
- same-transaction re-entry promotes definition intent;
- fresh transaction responses omit the marker through protobuf
round-trip.

CN coverage:

- a stale statement rebuilds before row-version scanning;
- refresh-expression cannot mask definition retry;
- an aborted/uncommitted definition signal does not rebuild.

TN coverage:

- replace a physical table while preserving its logical name;
- writes bound to the old ID return `ErrTxnNeedRetryWithDefChanged`;
- normal INSERT and `SOFT_DELETE_OBJECT`;
- optimistic and pessimistic modes.

Fresh local validation after the final semantic edit:

- focused adaptive race stress:
- lockservice tests: measured 0.14s / 0.38s / 0.14s, `-race
-count=100/78/100`;
  - CN tests: measured 0.08s / 0.08s, `-race -count=100`;
  - TN test: measured 0.05s, `-race -count=100`.
- full normal and race packages:
  - `./pkg/lockservice`
  - `./pkg/sql/colexec/lockop`
  - `./pkg/vm/engine/tae/rpc`
- `go build` and `go vet` passed for all three owning packages.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…in#26757)

## 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 matrixorigin#26756

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

A copy-based `ALTER TABLE` can replace a physical table generation
between CN catalog resolution and DML locking. A late CN could therefore
lock the old table ID without observing the completed DDL, carry that ID
into `PrecommitWriteCmd`, and expose TN's internal `ExpectedEOB`.

Required invariant:

> After a statement snapshot crosses a committed table-definition
change, a plan bound to the previous physical generation must not
execute.

This PR closes that invariant at both ownership boundaries:

1. Lockservice retains the latest **committed** definition-change
timestamp per lock table. DDL abort never advances the fence.
2. Definition intent belongs to a holder generation:
- waiting behind ordinary DML cannot clear the DDL request's own intent;
- promotion and same-transaction re-entry apply the requester's intent;
   - ownership transfer replaces the predecessor bit;
- aborted DDL clears the old holder generation before notifying
successors, so a later ordinary commit cannot manufacture a fence.
3. Lockservice only returns the retained marker to transactions whose
creation timestamp predates it. CN then compares the marker with the
precise statement snapshot. Fresh transactions have no marker on the
wire.
4. For RC, a stale statement waits for logtail, advances its snapshot,
and returns `ErrTxnNeedRetryWithDefChanged`; compile retry rebuilds the
logical plan. SI returns a write-write conflict.
5. Definition retry takes precedence over refresh-expression because
refreshing row versions cannot repair a stale physical table ID.
6. TN uses one catalog-resolution helper for every relation-bound write
entry. Database/relation `ExpectedEOB` becomes
`ErrTxnNeedRetryWithDefChanged` for normal writes and
`SOFT_DELETE_OBJECT`; object-level `ExpectedEOB` keeps its existing
“already absent” meaning.

## Performance and compatibility

- Tables with no committed DDL add only a nil check.
- After same-ID/in-place DDL, fresh transactions add one timestamp
comparison in lockservice but no response allocation, marker wire bytes,
RPC, catalog lookup, or plan rebuild.
- Only transactions old enough to contain a stale plan receive the
optional marker. Long-running transactions whose statement snapshot is
already fresh receive it conservatively but do not retry.
- The retained state is one immutable timestamp per local lock table;
later DDL replaces it instead of mutating in-flight results.
- Protobuf field 11 is optional and wire-compatible: old readers ignore
it and new readers treat absence as no retained fence.
- When TN is upgraded, its authoritative fallback preserves correctness
with old CN/lockservice nodes and across lock-table restart/rebind. Wire
compatibility alone does not make an old TN perform the new retry
mapping.

## Validation

Deterministic lockservice coverage for row and range locks:

- ordinary commit does not create a fence;
- committed DDL creates and advances a fence;
- DDL abort does not create or advance one;
- DDL intent survives waiting behind ordinary DML;
- holder promotion replaces predecessor intent;
- an ordinary successor after aborted DDL cannot manufacture a fence;
- same-transaction re-entry promotes definition intent;
- fresh transaction responses omit the marker through protobuf
round-trip.

CN coverage:

- a stale statement rebuilds before row-version scanning;
- refresh-expression cannot mask definition retry;
- an aborted/uncommitted definition signal does not rebuild.

TN coverage:

- replace a physical table while preserving its logical name;
- writes bound to the old ID return `ErrTxnNeedRetryWithDefChanged`;
- normal INSERT and `SOFT_DELETE_OBJECT`;
- optimistic and pessimistic modes.

Fresh local validation after the final semantic edit:

- focused adaptive race stress:
- lockservice tests: measured 0.14s / 0.38s / 0.14s, `-race
-count=100/78/100`;
  - CN tests: measured 0.08s / 0.08s, `-race -count=100`;
  - TN test: measured 0.05s, `-race -count=100`.
- full normal and race packages:
  - `./pkg/lockservice`
  - `./pkg/sql/colexec/lockop`
  - `./pkg/vm/engine/tae/rpc`
- `go build` and `go vet` passed for all three owning packages.

This branch was previously deployed

1 inactive deployment
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.

[Bug]: stale table generation after cross-CN ALTER can surface ExpectedEOB

4 participants