Skip to content

fix(disttae): fence PK checks on table subscription readiness - #25888

Merged
mergify[bot] merged 10 commits into
matrixorigin:mainfrom
LeftHandCold:agent/fix-logtail-pk-check-readiness
Jul 21, 2026
Merged

mergify[bot] merged 10 commits into
matrixorigin:mainfrom
LeftHandCold:agent/fix-logtail-pk-check-readiness

Conversation

@LeftHandCold

@LeftHandCold LeftHandCold commented Jul 20, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #25704

What this PR does / why we need it:

During a long-running SELECT ... FOR UPDATE, a table scan can produce a batch
before LockOp waits for a conflicting transaction. If the CN logtail client
reconnects while the lock is waiting, reconnect rebuilds the table subscription
and latest in-memory partition state.

After the lock is granted, LockOp calls PrimaryKeysMayBeModified to decide
whether the pre-lock batch must be retried. The old implementation called
LazyLoadLatestCkp directly and could inspect an empty partition while the
table was still Subscribing. It then returned unchanged before the
subscription response was applied. In TPCC NewOrder this can reuse a committed
d_next_o_id and surface as a duplicate bmsql_oorder key.

This change makes the PK modification check use the existing subscription state
machine and the per-table applied fence:

  • Subscribing and SubRspReceived wait until checkpoint loading completes
    instead of treating an incomplete state as unchanged;
  • the pending marker is captured before the immutable partition snapshot while
    holding the subscription generation, so reconnect cannot make a snapshot from
    the old generation appear ready;
  • the push-client admission gate is checked before and after snapshot capture;
    reconnect closes this gate before it clears the old subscription map, covering
    that otherwise-stale intermediate window;
  • if reconnect has closed admission, return ErrRetryForCNRollingRestart so
    frontend rolls back the whole transaction and releases the already-acquired
    row lock instead of retaining locks until the 24-hour default session timeout;
  • preserve that rollback error across shardservice's errors.Join boundary
    for remotely sharded tables, without changing other replica-read errors;
  • a known pending table update waits until the table state covers the check's
    upper timestamp, then recaptures the current state before checking PKs;
  • SubRspTableNotExist may still resolve an old transaction snapshot from
    finite historical checkpoints; that fallback is terminal instead of entering
    another subscribe/snapshot-read cycle, and it is accepted only when its
    physical [start,end] range covers the PK-check upper timestamp;
  • cancellation now wakes logTailSubscriber.waitReady, so a statement canceled
    during reconnect does not remain blocked after it has acquired a row lock;
  • tables created in the current transaction keep their empty remote-history
    behavior;
  • PrimaryKeysMayBeUpserted keeps its existing lazy-check semantics.

An earlier revision returned changed=true immediately for an incomplete
subscription. Pessimistic BVT exposed that this retries an entire LOAD DATA
statement after auto-increment values have already been allocated. Since
auto-increment allocation is non-transactional, the retry consumed a second
range and changed expected values (for example 4/5/6 became 7/8/9). The current
revision waits for the already-running subscription and performs one definitive
PK check, so it does not create a statement retry merely because first-table
subscription is in flight.

The normal Subscribed path issues no RPC, creates no timer, and captures one
partition snapshot. Waiting is limited to first subscription or a known pending
per-table apply. Every wait observes the statement context; a reconnect fails
the affected transaction through an existing whole-transaction rollback error.
The snapshot method refreshes the existing subscription-GC timestamp, so
write-only tables retain the same GC behavior as isSubscribed. No wire format,
lock ownership, transaction protocol, or configuration semantics change.

Regression tests cover:

  • waiting for Subscribing and SubRspReceived without retrying a
    no-conflict statement;
  • seeing a matching PK version loaded by the completed subscription;
  • rejection of a snapshot from a reset subscription generation;
  • fail-fast whole-transaction rollback while reconnect has closed push-client
    admission but the old subscription entry is still present;
  • preservation of rolling-restart rollback classification through nested and
    multi-replica error wrappers;
  • recapturing the state after a pending update is applied;
  • terminating after one historical snapshot fallback, both when the finite
    checkpoint range covers the PK-check timestamp and when it must conservatively
    report changed because it does not;
  • context cancellation both while subscription state is incomplete and while
    the logtail subscriber itself is not ready;
  • pending per-table apply;
  • the subscribed fast path, empty keys, transaction-local table creation, and
    unchanged auto-increment upsert semantics.

Test

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=10m ./pkg/vm/engine/disttae

.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=1 -timeout=15m ./pkg/vm/engine/disttae

.agents/skills/mo-dev/scripts/mo-cgo-test -race -count=100 -timeout=5m -run 'TestPKCheckHistoricalSnapshotFallbackIsTerminal|TestNormalizePKCheckErrorPreservesRollingRestart|TestPKCheckSnapshot|TestLogTailSubscriberWaitReadyReturnsOnContextCancel|TestPrimaryKeysMayBeModified' ./pkg/vm/engine/disttae

.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -timeout=10m ./pkg/sql/colexec/lockop ./pkg/frontend

go build ./pkg/vm/engine/disttae

go vet ./pkg/vm/engine/disttae

@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 Jul 20, 2026
@mergify mergify Bot added the kind/test-ci label Jul 20, 2026
@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Jul 20, 2026
@LeftHandCold
LeftHandCold force-pushed the agent/fix-logtail-pk-check-readiness branch from 4255f50 to d0d509a Compare July 20, 2026 08:29

@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

The readiness fence fixes the intended subscribed path, but it drops the pre-existing snapshot-read terminal path and can leave a lock-holding PK check looping until its context expires. Existing PR reviews/threads were empty; focused local tests could not run because this checkout has no go executable.

P1 - Preserve the successful snapshot-read fallback instead of re-subscribing forever (pkg/vm/engine/disttae/txn_table.go:3021)

getPartitionState deliberately converts a SubRspTableNotExist subscription result into a historical snapshot read and can return a non-nil partition state with no error (lines 2502-2553). This new loop discards that successful result. toSubscribeTable clears the subscription entry on that response (logtail_consumer.go:517-519), so the next iteration sees Unsubscribed, invokes getPartitionState again, and repeats the subscription/snapshot-read cycle until the statement context ends. This is a regression for the existing missing-table/snapshot-read path and is especially harmful here because PrimaryKeysMayBeModified runs after LockOp has acquired its row lock. Consume/return the valid fallback state (with an appropriate readiness decision) or return a terminal error, and add a regression test for a NoSuchTable subscription followed by a successful snapshot read.

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

The reconnect generation fence, pending-update ordering, cancellation wakeup, and rolling-restart rollback propagation are sound on the covered paths. However, the new PK-check state machine still has a reachable non-terminating path after the caller has acquired its row lock: a successful historical snapshot fallback is discarded after SubRspTableNotExist. This must be fixed before merge. Please make the fallback a terminal outcome and add a deterministic regression test that proves there is no repeated subscribe/snapshot-read cycle.

Comment thread pkg/vm/engine/disttae/txn_table.go Resolved

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

Re-reviewed the latest head (aaa17ec0). The previous blocker is closed: a finite historical partition returned after SubRspTableNotExist is now a terminal outcome, it is accepted only when its physical range covers the PK-check upper timestamp, and the new regression test proves both the in-range and conservative out-of-range paths perform one snapshot read with no repeated subscribe cycle.

I also re-checked the full lifecycle: reconnect closes admission before resetting the subscription map; the PK snapshot is fenced before and after capture under the subscription generation; pending-table apply is recaptured; subscriber cancellation wakes the condition wait; and the sharded-read path preserves the concrete rolling-restart error so frontend performs a whole-transaction rollback and releases acquired locks.

Fresh local validation on this head passed:

  • focused concurrency regressions with -race -count=100;
  • full ./pkg/vm/engine/disttae tests, with and without -race;
  • dependent ./pkg/sql/colexec/lockop and ./pkg/frontend tests;
  • go build and go vet for disttae with the repository CGo environment.

No remaining correctness, performance, hang, or resource-lifecycle blocker found. CI is still in progress at review time.

@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

No concrete correctness, compatibility, concurrency, resource, performance, or coverage regressions found. The prior historical-snapshot fallback blocker is fixed; applicable CI checks pass. Local focused execution was blocked by missing CGo artifacts.

@mergify mergify Bot added the queued label Jul 21, 2026
@mergify

mergify Bot commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-21 02:31 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-21 03:41 UTC · at 3069214d410736d7c07d29369659fda80fb7b908 · squash

This pull request spent 1 hour 10 minutes 41 seconds in the queue, including 1 hour 10 minutes 15 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-neutral = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
    • check-skipped = Matrixone Standlone CI / Multi-CN e2e BVT Test on Linux/x64(LAUNCH, PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

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

4 participants