Skip to content

fix(sql): avoid lifecycle convoy for scalar RC truncate - #29837

Merged
XuPeng-SH merged 5 commits into
mainfrom
codex/29400-truncate-lifecycle
Oct 11, 2026
Merged

XuPeng-SH merged 5 commits into
mainfrom
codex/29400-truncate-lifecycle

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 10, 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:

Addresses #29400: fresh RC TRUNCATE should wait on first lifecycle contention, and an independent ordinary scalar TRUNCATE should finish while DROP waits for another transaction's DML. Historical convoy limits remain, so this PR does not close the whole issue.

What this PR does / why we need it:

The broad global lifecycle gate lets a waiting DROP stall unrelated TRUNCATE. For permanent ordinary tables under pessimistic RC, certify that there are no FK relationships, secondary indexes, partitions, history owners or branch components; reuse existing C/G/D/K/catalog/storage locks and the applied frontier, then run the existing replacement executor under G S. Check tenant-owned user snapshots and SYS history using physical and stable logical identity. Every excluded shape, optimized DELETE, SI and temporary tables retain existing broad behavior.

FK CREATE/publication/forward-reference repair acquires actual G X before effects using existing typed plan fields. Validate planned parent generations at CREATE and ADD FK's existing locking seam. The outer destructive storage lock also owns the definition-change commit fence, which lets stale physical-generation lock callers rebuild instead of silently refreshing. Parent validation follows the planner’s parallel named FK fields without an unused unnamed-parent fallback. Extend the synchronous nested DROP receipt to one certified operator/account/table generation; broad nested CREATE borrows its outer G X without re-admission. No new persistent state, cache, protobuf field or replacement executor is introduced.

Fresh G acquisition waits with existing cancellation/deadlines; retained promotion remains FastFail and preserves whole-transaction rollback. The scoped path adds bounded metadata reads and frontier validation for independent progress; no throughput improvement is claimed. FK CREATE/repair deliberately retains broad serialization. Deployment assumes maintenance cutover with drained old transactions.

Validation on the rebased code (main dd38098853), Linux/amd64, Go 1.27.1 and stamped native libraries:

  • Owning compile package normal and complete -race: passed.
  • Existing authenticated two-CN root normal and -race: passed, including scalar/indexed retired-definition fences, parent replacement/deletion while FK CREATE waits, and snapshot/FK publication after negative preflight. All scenarios reuse one fixture.
  • Existing FK branch clone compatibility regression: passed on the rebased implementation.
  • Public fault injection after successful nested DROP: passed on the rebased production code; CREATE failure restores the original physical ID and row, and a subsequent TRUNCATE succeeds. This diagnostic overlay remains outside the PR.
  • Exact-root bounded race stress: passed (B=30s, measured T=35.13s, count=1).
  • Fresh normal coverage profiles parsed with the CI script and complete PR diff: 143/189 = 75.66%, passing the strict >75% gate without changing policy.
  • go vet and configured incremental golangci-lint: passed, zero introduced issues. Repository molint reports seven recover diagnostics in five files byte-identical to the rebased main.

Corrective design and final overall review use actual gpt-6.1-sol / xhigh CLI, verified from rollout metadata, session 01a12710-062c-7840-86a8-c66927427fd1. Both design and final overall review passed with no unresolved material blocker. Current complete reviewed 12-file patch SHA256: cb0ec82161e87fc23becc3c7d1049d8822449b9fb172ae9e49c28e86afecfb45.

QA also identified an existing tenant historical-lineage retention defect: broad positive history probes and compaction read SYS snapshots only. The new scalar path excludes those historical tables; their existing retention implementation is unchanged and is not claimed fixed here. Reproduction evidence is retained separately. The additional definition-change correction adds no lock acquisition or query. New remote CI is pending; the coverage result above is local current-code validation.

@mergify mergify Bot added kind/bug Something isn't working kind/enhancement kind/test-ci labels Oct 10, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Oct 10, 2026
@XuPeng-SH XuPeng-SH changed the title fix(sql): wait on fresh RC TRUNCATE lifecycle admission fix(sql): avoid lifecycle convoy for scalar RC truncate Oct 10, 2026
@XuPeng-SH
XuPeng-SH marked this pull request as ready for review October 10, 2026 19:44
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Overall implementation review and QA closure for c59bf1cc34c300eb7665fa25faebc37625c0546a.

Actual gpt-6.1-sol with xhigh reasoning reviewed the complete 12-file delta and its exact content hashes, then reconciled the completed validation gates: PASS, no actionable PR defects or unclosed required gates. Session: 01a12710-062c-7840-86a8-c66927427fd1; complete reviewed patch SHA256: 95a49e7e6caed10a462d5aff9aaf27a85f7cb74d4ab6ee457790c521c60d1301.

  • Existing lifecycle locks, transaction ownership, replacement executor and cleanup remain responsible. The scalar path certifies shape, FK catalog, actor/SYS history and physical/logical identity before effects; FK CREATE/repair publishes under actual G X. No unrelated cache/API/FK-state refactor remains.
  • Real two-CN SQL tests prove unrelated scalar TRUNCATE completes before the retained UPDATE releases while DROP remains waiting. They also cover same-table exclusion, fresh-gate commit/rollback/cancel/timeout, forward/ordinary FK publication and tenant snapshot/rename broad-gate fallback.
  • Owning compile normal and complete race passed. Public normal, race measurement and computed bounded same-process race stress passed. The stress count is N=1 from the 30-second budget and 43.620-second measured test, rather than an arbitrary large loop.
  • Additional public fault injection returned CREATE failure after successful nested DROP: the original physical table ID/data were restored; a later TRUNCATE succeeded. Existing branch/Snapshot/DIFF, FK clone/enforcement, index/allocator/DELETE and partition controls passed where their broad paths remain unchanged.
  • Incremental configured golangci-lint: 0 issues. go vet passed. molint has only the same seven recover diagnostics in five files byte-identical to the base. Disk-exhaustion/truncated-log attempts were excluded and rerun with complete evidence on NVMe.

Historical convoy limits remain. A separate tenant historical owner/lineage protection gap was reproduced with optimization-before production code: immediate snapshot reads pass, but the expected retired protection metadata is absent. This PR excludes these tables from the scalar path and does not claim to fix their existing retention logic or close all of #29400. CI for this pushed revision remains pending.

@matrix-meow matrix-meow added size/XL Denotes a PR that changes [1000, 1999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Oct 10, 2026

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Follow-up review: PASS on cb60cce, rebased onto main dd38098. The prior P2 definition-change notification regression and P3 unused FK fallback are fixed. Independent actual gpt-6.1-sol/xhigh corrective design and complete 12-file overall review both PASS (CLI session 01a12710-062c-7840-86a8-c66927427fd1, verified model metadata).

Current-code validation: owning compile normal/race, existing authenticated two-CN root including six adversarial regressions normal/race, bounded exact-root stress, real post-DROP CREATE-failure rollback/reuse, and FK branch clone all PASS. Incremental lint/gofmt/vet pass; molint has no introduced findings, with seven diagnostics in five files byte-identical to rebased main. Fresh local profiles parsed using the CI coverage script pass changed coverage 143/189=75.66%, strict >75%, unchanged policy. Added scenarios share the existing fixture; the correction adds no lock request, query or production state.

Local gates are closed; new remote CI is pending and is not represented as passed. Existing historical tenant-retention scope remains excluded.

@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 cb60ccebaf598059568e39fa62cc62a51d4f2085 against main dd38098853ea197699ed3fac3e69dc53975ac061: PASS for this PR's scope. No new blocking regression found. Both previous review findings are addressed. There is a separately confirmed pre-existing forward-FK defect below; this is not a claim that every lifecycle/FK scenario is correct.

Previous comments

  • P2 (original, fix reply): the outer destructive storage lock now owns changeDef=true when nested DROP borrows admission. Real remote-CN committed-definition-fence coverage is integrated. This review additionally verified that an aborted replacement does not publish a false committed fence.
  • P3 (original, fix reply): unsupported unnamed-parent fallback removed; parallel materialized FK lists are validated at their existing boundary. The real FK branch-clone compatibility test passes. Both threads are resolved.

Design, implementation and maintenance cost

The scoped path reuses existing lifecycle admission, catalog/storage locks, applied-frontier checks, transaction rollback, and the existing replacement executor. It does not add a second replacement state machine, persistent registry, cache, worker, or cleanup owner. Negative preflight is provisional: identity, shape and protection are checked again before effects. Complex/protected objects retain broad admission, and late retained-gate promotion fails fast into the existing retry mechanism. The borrowed receipt is bound to the transaction/actor/object and expires on exit; nested DROP validates it before effects.

I separately reviewed production +412/-50, tests +756/-27, and documentation +103/-3. The larger integration increment reuses the existing 2-CN fixture, with observable barriers and external identity/data/constraint oracles. It does not introduce another cluster fixture or a production-only fault hook. No further dead compatibility branch or duplicated owner requiring removal was identified. Ordinary DML's per-row path is unchanged; extra reads are in DDL admission, and broad FK publication deliberately serializes. No throughput benchmark claim is made.

Verification and unhappy paths

The complete patch fingerprint is unchanged from the previously validated revision. Reused evidence includes owning-package normal/race tests, public SQL normal/race controls, bounded race repetition, configured lint/vet and baseline-aware molint, real FK clone, and failure after real nested DROP followed by successful reuse.

Two additional targeted SQL/white-box challenges passed in this review, with diagnostic test overlays outside the PR:

  1. A unique index appears after the final negative preflight probe. TRUNCATE still completes, replaces the physical table, empties the rows, and preserves uniqueness on subsequent inserts (package 9.084s).
  2. CREATE fails after real nested DROP. Rollback restores the original physical table and row; a remote stale-generation physical lock sees neither TableDefChangedAt nor TableDefChanged; the next TRUNCATE succeeds (package 8.627s).

Ownership/cleanup, cancellation and terminal waits, lock promotion, rollback and retained-state growth were traced. No new unbounded collection or independent goroutine lifecycle was introduced.

Exact-head CI run 38090283226 now passes CI Required, Ubuntu UT, UT Coverage, ARM64 SCA, shared build, PROXY BVT and pessimistic BVT; CodeQL is also green. The actual coverage job reports 147/189 = 77.78%, passing the strict >75% gate. Skipped platform/upgrade jobs are not counted as tested.

Separate pre-existing correctness defect: stale incoming forward-FK repair

This adversarial schedule produces a real failure:

  1. With foreign_key_checks=0, create a child referencing a missing parent, then restore checks.
  2. Let CREATE of that parent finish planning while another transaction retains the lifecycle gate.
  3. That transaction drops the child and recreates the same name without any FK, then commits.
  4. Parent CREATE succeeds, but the replacement child unexpectedly acquires the old FK. Its mo_foreign_keys count is zero, while SHOW CREATE contains the FK and an otherwise legal INSERT ... VALUES (1,999) fails with error 20101.

The current-head public SQL reproduction uses an existing lock-wait observer, without production instrumentation. To distinguish a regression from an old defect, I ran the same post-planning/pre-effects scheduling barrier on head and on all five changed production files restored from exact main. Both fail with the same persisted constraint and INSERT behavior (head 8.565s; base 8.649s). The baseline differs only by that diagnostic callback; no validation or constraint logic is patched.

The unchanged forward-repair loop consumes plan-time FksReferToMe, resolves the child by name, and attaches the old definition to the replacement generation. This belongs to a separate common forward-repair fix that revalidates current FK facts/participant identity before effects and uses existing replanning on change. It is not attributed to this PR's new admission or snapshot refresh, and does not justify expanding this scoped TRUNCATE change. Reproduction sources, logs, baseline verification and an issue-ready draft are retained locally under /mnt/nvme/issue29400-artifacts/re-review-*.

No PR source was changed during this review; no subagents were used. COMMENT is used because this account is the PR author.

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

Review of current head cb60ccebaf598059568e39fa62cc62a51d4f2085: PASS for this PR's stated scope; no blocking issue found.

The scalar RC TRUNCATE path reuses the existing lifecycle locks, transaction ownership, applied-frontier checks, and DROP/CREATE executor. Eligibility and final identity/history checks bound the narrower lock path; unsupported or protected shapes retain broad admission. The prior retired-definition fence and unused FK fallback findings are fixed.

The concurrency tests and current green required CI provide evidence for the intended progress and correctness behavior. Performance impact is not benchmarked, so this review makes no throughput claim. Existing convoy limits and the separately identified baseline FK/history issues remain outside this PR's scope.

This is a review comment rather than an approval vote because the authenticated account is the PR author.

@XuPeng-SH
XuPeng-SH merged commit 4022729 into main Oct 11, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/29400-truncate-lifecycle branch October 11, 2026 01:36
XuPeng-SH pushed a commit that referenced this pull request Oct 12, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to #29814; the production fix is already included in #29837.

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

Add regression coverage for TRUNCATE lifecycle admission. The
implementation on main already lets fresh owners wait, retains FastFail
for existing-owner upgrades, and uses scalar admission where eligible.

- Exercise indexed-table TRUNCATE through broad admission, checking
exclusive lock mode, release/cancellation results, retained-owner
FastFail, and removal of wait bookkeeping on every exit.
- Add a public SQL BVT that holds the SNAPSHOT gate, requires an
ordinary-table TRUNCATE to wait for release, then checks both target
data and an unrelated database.

Validation after rebasing onto main (`035a5b61ba`):

- Full `pkg/sql/compile` tests passed.
- `TestTruncateLifecycleRCWaitPolicy` passed 100 repetitions under race.
- The CI-failing `TestIssue29400CopyAlterRetainedGatePromotionFastFails`
passed normally, under race, and with atomic coverage instrumentation of
`pkg/sql/compile` and `pkg/tests/issues`.
- New BVT passed twice (17/17 each) on a binary built from the rebased
commit.
- Incremental gofmt, go vet, configured golangci-lint, and diff checks
passed.

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

This branch was previously deployed

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants