Skip to content

Fix ISCP index consumer cancellation during DROP INDEX - #25733

Merged
XuPeng-SH merged 23 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-iscp-index-consumer-cancel
Jul 20, 2026
Merged

XuPeng-SH merged 23 commits into
matrixorigin:mainfrom
jiangxinmeng1:fix-iscp-index-consumer-cancel

Conversation

@jiangxinmeng1

@jiangxinmeng1 jiangxinmeng1 commented Jul 15, 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:

issue #25711

What this PR does / why we need it:

This PR fixes DROP INDEX and other destructive ISCP-backed index DDL paths by
canceling and draining the active index consumer before index metadata and hidden
tables are removed.

Changes:

  • Add ISCP runtime tracking for running job consumers.

  • Fence dropped index job generations so new iterations skip them while DDL is
    waiting for quiescence.

  • Cancel the consumer context and data retriever, then wait for the running
    consumer to exit.

  • Route DROP INDEX, ALTER TABLE DROP INDEX, DROP TABLE, and DROP DATABASE
    through the ISCP drain path before deleting metadata or hidden tables.

  • Use the existing global ISCP daemon task runner UUID from sys_daemon_task as
    the single ISCP executor owner.

  • Add a queryservice-based cross-CN drain request so a DDL CN can ask the actual
    ISCP runner CN to cancel and drain the local executor.

  • Keep the local executor fast path for single-CN and same-runner cases.

  • Fail closed when quiescence cannot be confirmed, including missing query client,
    missing runner query address, or remote drain RPC failure.

  • Clean remote generation fences through transaction commit/rollback callbacks.

  • Make data retrievers reject/cleanup queued data after cancellation.

  • Add ctx-aware fault injection for WAIT and SLEEP.

  • Fix WAIT fault removal so blocked waiters are notified, including the
    TriggerFaultWithContext path.

  • Add ISCP cancel failpoints for different consumer phases, including
    per-index-name injection.

  • Add unit tests for runtime cancel, retriever cleanup, fault cancellation,
    local drain, remote queryservice drain, remote fence cleanup, and DDL drain
    behavior.

Test Matrix:

Area Scenario Result
Original reproduction Reproduced the documented ISCP DROP INDEX cancel issue.
Fixed: DROP INDEX no longer leaves a background consumer running.
Single-process multi-CN Started local multi-CN launch and issued DROP INDEX from
different CNs. Passed for both directions.
Docker multi-process CN Started make dev-up with separate mo-cn1 and mo-cn2
containers. ISCP runner was on mo-cn2; DDL was issued from non-runner mo-cn1.
Passed.
Cross-CN DROP INDEX Created async HNSW index from CN1 and dropped it from CN1 while
runner was CN2. DROP INDEX succeeded through queryservice remote drain.
Cross-CN DROP TABLE Created ISCP-backed HNSW table and dropped table from non-
runner CN. DROP TABLE succeeded.
Cross-CN ALTER TABLE DROP INDEX Created ISCP-backed HNSW table and ran ALTER TABLE
DROP INDEX from non-runner CN. ALTER succeeded and index metadata was removed.
Cross-CN DROP DATABASE Created ISCP-backed tables and dropped database from non-
runner CN. DROP DATABASE succeeded.
In-flight remote consumer Injected fj/iscp/cancel/after-register-consumer WAIT on
the runner CN, then issued DROP INDEX from another CN. DROP waited before fault
removal, then completed after the runner consumer exited.
Cancel after consumer registration fj/iscp/cancel/after-register-consumer. DROP
waits for drain, then succeeds.
Cancel after worker submit fj/iscp/cancel/after-submit. Fenced job is skipped,
DROP succeeds.
Cancel during fanout fj/iscp/cancel/fanout-before-send. Canceled retriever
rejects data, DROP succeeds.
Cancel before HNSW update fj/iscp/cancel/long/hnsw-before-update. DROP returns
quickly.
Cancel before HNSW save fj/iscp/cancel/long/hnsw-before-save. DROP returns
quickly.
Cancel before watermark update fj/iscp/cancel/long/before-watermark. DROP
returns quickly.
Cancel before SQL execution fj/iscp/cancel/long/before-exec with fulltext ASYNC.
DROP returns quickly.
Long wait via sleep fj/iscp/cancel/long/before-send:idx01 with sleep 30. DROP
returns quickly after canceling the consumer context.
Iteration already failed before cancel Injected iteration error before DROP. Job
records the error path correctly; DROP still succeeds and sets drop_at.
Multiple jobs in one iteration Two HNSW indexes on different columns, cancel only
idx01. idx01 removed; idx02 preserved.
Fault cleanup Listed fault points after tests. No remaining fault points.
Goroutine cleanup Checked pprof goroutines after fault/ISCP tests. No stuck
cancel/scan/ISCP goroutines.
Unit tests `go test -count=1 ./pkg/iscp ./pkg/sql/compile ./pkg/cnservice ./pkg/
queryservice/client` with local CGo flags. Passed.
Build/package graph make build. Passed, including Go package graph check.
Static check git diff --check. Passed.

@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 15, 2026
@matrix-meow matrix-meow added the size/XL Denotes a PR that changes [1000, 1999] lines label Jul 15, 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.

There is still a generation-safety gap in the cancellation fence.

The fence is stored only in the current executor's in-memory fencedJobs map. If the ISCP executor restarts or the daemon-task lease migrates while the DROP transaction is unresolved, the replacement executor starts with an empty fence map and can rebuild/admit the still-visible job (dropAt is not committed yet). The local lease also keeps renewing the old executor pointer.

The remote path has the same safety hole after restart or expiry: RenewJobFence silently does nothing when the exact fence is absent, while handleISCPDrainConsumer returns success. The DDL side therefore believes the fence is renewed even though the consumer can run again, reopening the DROP INDEX/consumer race this PR is intended to close.

Please make the fence durable or executor-generation/lease-owner aware, and require renewal to prove that the exact fence still exists (otherwise re-resolve the runner and re-drain/reinstall it before acknowledging success). The DDL must not commit if quiescence can no longer be proven. Please also add coverage for executor restart/task migration during an unresolved DDL transaction and renewal after the fence has expired or disappeared.

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Found one remaining correctness issue in the remote fence renewal. The lease can still expire while a renewal RPC is in flight, and a late renewal is then silently acknowledged after the key has already been deleted, permanently losing the protection during an open DDL transaction. Requesting changes for the inline issue. I rechecked the consumer cancellation/drain, fan-out refcounting, rollback cleanup, and committed drop-logtail handoff; those paths look closed. The affected package tests pass.

Comment thread pkg/sql/compile/iscp_util.go Resolved
@jiangxinmeng1

jiangxinmeng1 commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor Author

There is still a generation-safety gap in the cancellation fence.

The fence is stored only in the current executor's in-memory fencedJobs map. If the ISCP executor restarts or the daemon-task lease migrates while the DROP transaction is unresolved, the replacement executor starts with an empty fence map and can rebuild/admit the still-visible job (dropAt is not committed yet). The local lease also keeps renewing the old executor pointer.

The remote path has the same safety hole after restart or expiry: RenewJobFence silently does nothing when the exact fence is absent, while handleISCPDrainConsumer returns success. The DDL side therefore believes the fence is renewed even though the consumer can run again, reopening the DROP INDEX/consumer race this PR is intended to close.

Please make the fence durable or executor-generation/lease-owner aware, and require renewal to prove that the exact fence still exists (otherwise re-resolve the runner and re-drain/reinstall it before acknowledging success). The DDL must not commit if quiescence can no longer be proven. Please also add coverage for executor restart/task migration during an unresolved DDL transaction and renewal after the fence has expired or disappeared.

I agree that an in-memory fence cannot provide a hard guarantee across runner restart
or daemon-task lease migration while the DDL transaction is still unresolved. I also
agree that a non-durable re-resolve/re-drain scheme has its own risks: it adds more
cross-CN retry logic inside an open DDL transaction, has to reason about unknown commit
outcomes, and can still fail to prove quiescence under partitions or runner churn.

For this PR, I intentionally kept the fence process-local and transaction-scoped. The
default TTL is now 30 minutes and the lease is renewed while the DDL transaction
remains unresolved, so the normal long-transaction case is covered without adding a new
durable state machine or a complex cross-runner handoff protocol. Persisting the fence
is also risky: a stale durable fence can permanently suppress a still-valid ISCP job
and leave the index stale until manual intervention.

Given that tradeoff, I would prefer to keep this PR scoped to the active-runner
lifecycle: cancel and drain the current consumer, keep the in-memory generation fence
alive during the unresolved DDL transaction, remove it on rollback, and clear it after
the committed drop_at is installed. Runner crash or daemon-task migration during an
unresolved destructive DDL is a narrower availability/failure-domain case that should
be handled by a separate lifecycle design rather than by opportunistically persisting
this fence map in this PR.

@aptend

@aptend

aptend commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

@jiangxinmeng1 Thanks, I agree that persisting the fence is not necessarily the right scope for this PR, and runner restart/daemon-task lease migration can be tracked as a separate lifecycle design.

However, the current implementation still does not guarantee the active-runner lifecycle described here. No restart or migration is required: a renewal RPC starts at TTL/2 but may run for a full TTL. The existing fence can therefore expire while renewal is still in flight. Once IsJobFenced deletes the expired key, RenewJobFence silently no-ops and handleISCPDrainConsumer still returns success. The DDL side consequently does not fail closed, and the consumer can be admitted again while the transaction remains unresolved.

This is the same active-runner case described in #25733 (comment), and does not require a durable fence. Please make renewal finish within the remaining lease with a safety margin, return an explicit error for a missing/expired fence, and ensure loss of the lease prevents the DDL from committing. With that closed, I am fine with documenting restart/migration as a separate follow-up.

…umer-cancel

# Conflicts:
#	pkg/pb/query/query.pb.go

@LeftHandCold LeftHandCold left a comment

Copy link
Copy Markdown
Collaborator

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 fc114288d7. The remaining fence-renewal failure mode can re-expose an intermittent DDL deadlock/retry window, but it does not establish a committed data-correctness failure: the initial consumer drain closes the active race, the destructive DDL changes are transactional, and consumer result updates do not clear drop_at. Treating renewal as best-effort avoids turning a transient control-plane failure into a guaranteed rollback of an otherwise valid transaction. I do not see a remaining blocker on this head.

@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

@jiangxinmeng1 Thanks, I agree that persisting the fence is not necessarily the right scope for this PR, and runner restart/daemon-task lease migration can be tracked as a separate lifecycle design.

However, the current implementation still does not guarantee the active-runner lifecycle described here. No restart or migration is required: a renewal RPC starts at TTL/2 but may run for a full TTL. The existing fence can therefore expire while renewal is still in flight. Once IsJobFenced deletes the expired key, RenewJobFence silently no-ops and handleISCPDrainConsumer still returns success. The DDL side consequently does not fail closed, and the consumer can be admitted again while the transaction remains unresolved.

This is the same active-runner case described in #25733 (comment), and does not require a durable fence. Please make renewal finish within the remaining lease with a safety margin, return an explicit error for a missing/expired fence, and ensure loss of the lease prevents the DDL from committing. With that closed, I am fine with documenting restart/migration as a separate follow-up.

@aptend
The original issue already demonstrates that, without a confirmed ISCP quiescence
fence, the DDL path does not silently succeed in the observed race. It fails with
cannot confirm ISCP consumer quiescence / DDL conflict instead of completing hidden-
table removal under an active consumer. So losing the renewal does not necessarily mean
the DDL must be force-aborted by the lease layer itself; the underlying DDL/lock path
can still fail the statement.

That said, I agree the renewal ACK semantics must not be misleading. I have changed
RenewJobFence / RenewFenceOnly so a missing or expired exact fence returns an
explicit error, and I bounded the renewal RPC timeout to complete within the lease
window. With that change, renewal loss is visible instead of being acknowledged as
success.

I would prefer not to add another pre-commit abort path in this PR unless we can show
that the DDL can silently commit hidden-table removal after the active-runner fence is
lost. The currently observed failure mode is an explicit DDL error, which is acceptable
for this best-effort in-memory fence.

@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 fence-renewal failure path is not enforced, so a runner restart during an open DROP INDEX transaction can re-enable the consumer before the drop commits.

P1 - Abort or otherwise preserve quiescence when fence renewal fails (pkg/sql/compile/iscp_util.go:365)

Fence state is in-memory only. If the ISCP runner restarts (or the fence expires) while the DDL transaction remains open, RenewJobFence correctly returns false, but this goroutine only logs the error and continues. The replacement executor has no fence and RegisterRunningConsumer accepts the still-active, uncommitted job, allowing it to resume writes to the index being dropped. The new handler error for a missing fence is therefore never propagated to the DDL transaction. The renewal failure must keep the job fenced or cause the DROP transaction to fail/abort; logging is insufficient.

…umer-cancel

# Conflicts:
#	pkg/cnservice/server_query_test.go
@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

Codex automated review

The fence-renewal failure path is not enforced, so a runner restart during an open DROP INDEX transaction can re-enable the consumer before the drop commits.

P1 - Abort or otherwise preserve quiescence when fence renewal fails (pkg/sql/compile/iscp_util.go:365)

Fence state is in-memory only. If the ISCP runner restarts (or the fence expires) while the DDL transaction remains open, RenewJobFence correctly returns false, but this goroutine only logs the error and continues. The replacement executor has no fence and RegisterRunningConsumer accepts the still-active, uncommitted job, allowing it to resume writes to the index being dropped. The new handler error for a missing fence is therefore never propagated to the DDL transaction. The renewal failure must keep the job fenced or cause the DROP transaction to fail/abort; logging is insufficient.

@gouhongshen
I do not think renewal loss should automatically abort the DDL transaction.

The cancellation fence is an in-memory guard used to improve the chance that the DROP
can complete cleanly by keeping the active ISCP consumer out of the hidden-table path
while the DDL transaction is unresolved. If that fence is lost, the system falls back
to the pre-fence behavior: the DDL and the consumer may contend on the hidden tables /
ISCP log rows, and the normal transaction, lock, deadlock-detection, and table-deletion
paths decide the outcome.

That can increase the probability that the DROP statement fails or is rolled back by
the underlying DDL/lock conflict handling, but it does not by itself create a
correctness violation. A consumer error after or during hidden-table removal is
acceptable for a job whose index is being dropped; the index no longer needs to be
maintained. The important part is that renewal loss is no longer acknowledged as
success: RenewJobFence / RenewFenceOnly now return an explicit error when the exact
fence is missing or expired, and the renewal RPC is bounded within the lease window.

Given that, I would prefer not to add a separate pre-commit abort path in this PR. The
fence remains a best-effort active-runner quiescence guard, not durable DDL state.

@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

Two blocking lifecycle gaps can let DROP INDEX race with ISCP work after cancellation.

P1 - Executor handoff can silently lose the DROP INDEX fence (pkg/sql/compile/iscp_util.go:365)

Fence renewal failures are only logged. The fence is stored in the selected executor instance; if that runner stops/restarts, the DDL lease continues using the old executor or fixed query address, while the replacement executor starts with an empty fence map and rebuilds the still-uncommitted job as active. Its candidate scan then admits the job. Renewal failure or generation replacement must be treated as a failed quiescence operation or transferred to the current executor generation.

P1 - InitSQL index builds are not drained or cancellable (pkg/iscp/runtime_cancel.go:120)

CancelAndDrainJobConsumer only cancels entries in runningConsumers. The InitSQL branch in ExecuteIterationWithRuntime calls ProcessInitSQL and returns before runISCPTaskIterationConsumers registers a RunningJobConsumer, so an async CAGRA/IVF-PQ build can pass the one-time fence check, continue in its own transaction, and never be awaited by DROP INDEX before hidden index tables are dropped. The InitSQL execution needs the same runtime registration/cancellation lifecycle or a fence recheck plus join.

@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 head 9677012a68.

  1. [P1][correctness] Do not mark InitSQL complete when registration loses to a fence. runInitSQLWithRuntime returns nil when RegisterRunningConsumer rejects an already-fenced generation. The caller treats that as successful execution, changes the status stage to JobStage_Running, and flushes it as completed. A concrete sequence is: the scheduler passes its earlier fence check; DROP installs the fence before this registration; registration returns false; the DROP later rolls back; the independent status flush then succeeds, but the InitSQL was never executed. The live job will permanently skip its initial CAGRA/IVF-PQ build (or restore rebuild), leaving the index incomplete. Return a cancellation/fenced sentinel and exit before the stage/status transition; add a caller-level regression for fence-before-register followed by DROP rollback. (pkg/iscp/iteration.go, runInitSQLWithRuntime and the needInit branch.)

  2. [P2][fault correctness] Canceling a context-aware WAIT still releases a plain WAIT on the same fault point. The context watcher calls the shared condition variable’s Broadcast, while the non-context do(WAIT) performs one unconditional cond.Wait() with no predicate. With one TriggerFault waiter and one TriggerFaultWithContext waiter on the same entry, canceling only the latter makes both return. I reproduced this deterministically on this head. Use per-waiter cancellation/notification, or make every wait path use a predicate that does not interpret another waiter’s cancellation broadcast as NOTIFY. (pkg/util/fault/fault.go:177-184, 241-247.)

  3. [P2][index-plugin gate] Keep HNSW-specific drop ordering out of the generic SQL layer. makeNewDropConstraint now checks the literal hnsw and Hnsw_TblType_Storage. This reintroduces per-algorithm dispatch in pkg/sql/compile, which the index-plugin contract explicitly forbids. Expose hidden-table drop priority/order through the plugin hooks and keep the SQL layer algorithm-agnostic. (pkg/sql/compile/ddl.go:2584-2589.)

The previously reported fence-renewal failure also remains open; I did not duplicate that finding here.

@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 head ba9bf8a8eadf5b35d6a72c80964a2669da483e5f. The latest update fixes the previous fenced-registration status transition, moves HNSW drop ordering behind the plugin hook, and closes the direct plain-WAIT cancellation repro. Two correctness gaps remain, and the previously reported renewal blocker is unchanged:

  1. [P1][InitSQL lifecycle] Return the terminal transaction error before advancing the job stage. ProcessInitSQL defers txnOp.Commit(ctx) and discards its result. The context is now the cancelable runtime context installed by runInitSQLWithRuntime. If DROP cancels after RunSql has returned success but before the deferred commit completes, Commit can fail on the canceled context while ProcessInitSQL still returns nil; the caller then writes JobStage_Running even though the initial index-build transaction did not commit. Error paths also attempt commit rather than rollback. Please perform explicit commit/rollback with an independent bounded cleanup context, propagate the terminal error, and add a regression where the SQL body succeeds but commit fails/cancellation races with commit. (pkg/iscp/iteration.go:1037-1040, caller at lines 158-185.)

  2. [P2][fault correctness] A prior NOTIFY plus a later cancellation releases unrelated waiters. All waiters capture the same global notifySeq. NOTIFY increments it and signals one waiter; if one remaining context waiter is then canceled, its watcher broadcasts the shared condition. Every other waiter observes the sequence change caused by the earlier single NOTIFY and exits too. I reproduced this deterministically with three waiters: one NOTIFY followed by cancellation of one remaining context released all three. A notification needs per-waiter ownership/token accounting (or per-waiter channels); a global generation cannot distinguish which waiter consumed a single Signal. (pkg/util/fault/fault.go:177-206, 240-255.)

  3. [P1][existing generation-safety blocker] Fence-renewal failure is still only logged. startISCPJobFenceLease continues after renewal failure, so an unresolved DDL transaction cannot enforce or observe loss of quiescence. The previously requested fail-closed/handoff behavior remains absent. (pkg/sql/compile/iscp_util.go:348-368.)

Validation: the existing pkg/util/fault suite passes, the supplemental three-waiter regression fails with “one NOTIFY plus one cancellation released 3 waiters”, and git diff --check passes. CI for this head is still in progress.

@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 head 65c05b3969ab95d938e219d7ca34b44ea4bfb6ee. The latest update correctly propagates the InitSQL transaction terminal result and replaces the shared WAIT condition with per-waiter channels, closing the two findings from the previous round. One generation-safety blocker remains.

P1 - Transfer or fail the open-DDL fence when the executor generation changes

The local drain path captures the current exec pointer in its lease-renewal closure (pkg/sql/compile/iscp_util.go:255-272). If the ISCP executor restarts or is replaced on the same CN while the DROP transaction is unresolved, RegisterExecutorRuntime publishes a new executor with an empty fencedJobs map, but the lease continues renewing the captured old executor successfully. The replacement executor can therefore admit the still-visible, uncommitted job generation through RegisterRunningConsumer and start a new consumer after the original one was drained. DROP can then remove the hidden tables while that new consumer is active, reopening the race this PR is intended to close.

The remote form is also not fail-closed: a missing/replaced executor makes renewal return an error, but startISCPJobFenceLease only logs it and continues (pkg/sql/compile/iscp_util.go:348-368), so the DDL transaction cannot observe that quiescence was lost.

Please bind the lease to the current executor generation/runner and re-resolve plus re-drain/reinstall the exact fence on replacement, or propagate loss of quiescence so the DDL cannot commit. Add a deterministic regression that replaces the executor while a DROP transaction remains open and verifies the replacement cannot admit that job generation.

Fresh validation on this exact head passed the focused InitSQL/fault lifecycle tests under -race -count=10, the full pkg/iscp, pkg/sql/compile, pkg/cnservice, pkg/queryservice/client, and pkg/util/fault suites, plugin guard greps, and git diff --check. A supplemental executor-replacement regression fails deterministically because the new executor admits the fenced job.

@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

Re-reviewed head 65c05b3969ab95d938e219d7ca34b44ea4bfb6ee. The latest update correctly propagates the InitSQL transaction terminal result and replaces the shared WAIT condition with per-waiter channels, closing the two findings from the previous round. One generation-safety blocker remains.

P1 - Transfer or fail the open-DDL fence when the executor generation changes

The local drain path captures the current exec pointer in its lease-renewal closure (pkg/sql/compile/iscp_util.go:255-272). If the ISCP executor restarts or is replaced on the same CN while the DROP transaction is unresolved, RegisterExecutorRuntime publishes a new executor with an empty fencedJobs map, but the lease continues renewing the captured old executor successfully. The replacement executor can therefore admit the still-visible, uncommitted job generation through RegisterRunningConsumer and start a new consumer after the original one was drained. DROP can then remove the hidden tables while that new consumer is active, reopening the race this PR is intended to close.

The remote form is also not fail-closed: a missing/replaced executor makes renewal return an error, but startISCPJobFenceLease only logs it and continues (pkg/sql/compile/iscp_util.go:348-368), so the DDL transaction cannot observe that quiescence was lost.

Please bind the lease to the current executor generation/runner and re-resolve plus re-drain/reinstall the exact fence on replacement, or propagate loss of quiescence so the DDL cannot commit. Add a deterministic regression that replaces the executor while a DROP transaction remains open and verifies the replacement cannot admit that job generation.

Fresh validation on this exact head passed the focused InitSQL/fault lifecycle tests under -race -count=10, the full pkg/iscp, pkg/sql/compile, pkg/cnservice, pkg/queryservice/client, and pkg/util/fault suites, plugin guard greps, and git diff --check. A supplemental executor-replacement regression fails deterministically because the new executor admits the fenced job.

@aptend
Thanks for the re-review. I agree this is a remaining limitation of the current in-
memory fence design, but I do not plan to address executor restart / lease migration in
this PR.

The fence here is intentionally a best-effort quiescence aid for improving DROP success
and avoiding the known active-consumer conflict window. It is not the source of DDL
correctness. If the fence is lost, renewal failure or a restarted executor may increase
the chance that the foreground DDL hits the existing lock/conflict path and fails
explicitly, but it does not make the DDL silently correct/incorrect by itself.

Making the fence survive executor replacement would require a separate lifecycle
protocol: generation ownership, handoff, recovery, rollback cleanup, unknown commit
outcome handling, and stale-fence GC. Persisting or transferring this opportunistically
in this PR would carry a higher risk of leaving a stale fence that suppresses a still-
valid ISCP job indefinitely, which is worse than the current best-effort in-memory
behavior.

So for this PR I am keeping the fence process-local and transaction-scoped, and I am
treating executor restart / daemon-task lease migration during an unresolved DDL as a
known follow-up design item rather than extending this fix further.

@aptend

aptend commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

@jiangxinmeng1 Thanks for the clarification. I rechecked the generation boundary and agree the previous review over-calibrated this as a P1 correctness blocker.

The remaining factual gap is limited to executor replacement / daemon-task lease migration while a remote DDL transaction is still unresolved: the new executor can start without the old in-memory fence and may reintroduce the hidden-table lock/deadlock window. A same-instance ISCPTaskExecutor.Restart() preserves fencedJobs, and a full local CN restart also terminates that CNs DDL transaction. More importantly, the supplemental regression proved re-admission on a replacement executor, but did not prove a silent partial DDL commit or data-corruption outcome; the established failure mode is an explicit DDL conflict/deadlock and rollback.

Given that, I accept the best-effort in-memory fence scope for this PR and treat runner migration during an unresolved DDL as a non-blocking follow-up lifecycle item. The InitSQL transaction outcome, per-waiter fault cancellation, plugin dispatch, and active-runner drain paths are closed on the current head. I am updating my review accordingly.

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

Approved after re-review. The current implementation closes the active-runner cancellation/drain lifecycle, InitSQL transaction outcome, fault WAIT ownership, and plugin-dispatch issues. I accept executor replacement or daemon-task migration during an unresolved DDL as a documented non-blocking availability follow-up; no remaining merge blocker found. Focused race tests, affected package suites, plugin guards, diff checks, and CI pass.

@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

Two P1 fence-lifecycle failures can reopen the DROP INDEX race or leave a rolled-back index stale for 30 minutes.

P1 - Fail the DDL when a fence renewal cannot be maintained (pkg/sql/compile/iscp_util.go:365)

The remote fence lives for 30 minutes, but renewal runs only every TTL/2 and a failed renewal is merely logged. A first renewal can consume its TTL/4 RPC timeout, after which the next attempt is scheduled 15 minutes later—past the original fence expiry. IsJobFenced then deletes the expired fence and the scheduler admits the consumer while the same DROP transaction may still be open, allowing it to write a hidden table that DROP is about to remove. Renewal loss must abort/rollback the DDL or retry before the current fence can expire.

P1 - Retry or otherwise guarantee remote rollback fence removal (pkg/sql/compile/iscp_util.go:331)

On rollback the callback stops the lease and makes exactly one RemoveFenceOnly RPC. Its error is discarded by txnOperator.rollbackOwned, which invokes rollback callbacks without checking triggerEventLocked's returned error. A transient RPC or handler failure therefore leaves the job fenced even though the drop rolled back; getCandidate skips it until the 30-minute TTL expires, so subsequent writes are not propagated to the still-existing index. Add a reliable retry or compensation path rather than returning an error from a callback whose caller ignores it.

@jiangxinmeng1

Copy link
Copy Markdown
Contributor Author

Codex automated review

Two P1 fence-lifecycle failures can reopen the DROP INDEX race or leave a rolled-back index stale for 30 minutes.

P1 - Fail the DDL when a fence renewal cannot be maintained (pkg/sql/compile/iscp_util.go:365)

The remote fence lives for 30 minutes, but renewal runs only every TTL/2 and a failed renewal is merely logged. A first renewal can consume its TTL/4 RPC timeout, after which the next attempt is scheduled 15 minutes later—past the original fence expiry. IsJobFenced then deletes the expired fence and the scheduler admits the consumer while the same DROP transaction may still be open, allowing it to write a hidden table that DROP is about to remove. Renewal loss must abort/rollback the DDL or retry before the current fence can expire.

P1 - Retry or otherwise guarantee remote rollback fence removal (pkg/sql/compile/iscp_util.go:331)

On rollback the callback stops the lease and makes exactly one RemoveFenceOnly RPC. Its error is discarded by txnOperator.rollbackOwned, which invokes rollback callbacks without checking triggerEventLocked's returned error. A transient RPC or handler failure therefore leaves the job fenced even though the drop rolled back; getCandidate skips it until the 30-minute TTL expires, so subsequent writes are not propagated to the still-existing index. Add a reliable retry or compensation path rather than returning an error from a callback whose caller ignores it.

@gouhongshen

Thanks for the review. I understand both points, but I do not plan to make the in-
memory fence lifecycle fully fail-closed in this PR.

The cancellation fence in this patch is intentionally a best-effort quiescence
mechanism. Its purpose is to improve DROP success by stopping the active ISCP consumer
during the destructive DDL window. It is not intended to become a durable or
transaction-authoritative state machine.

For renewal failure: if the fence cannot be maintained, the system falls back to the
pre-existing DDL/lock conflict behavior. That can increase the chance of an explicit
DDL failure, but it does not by itself make the DDL silently commit incorrectly. Making
renewal failure abort the DDL would require wiring an asynchronous lease goroutine into
transaction commit/rollback semantics, which is a larger lifecycle contract than this
PR is trying to introduce.

For rollback cleanup: the fence has a bounded TTL specifically to avoid permanent
suppression of a live job if rollback cleanup delivery fails. A transient stale fence
may delay the job, but it self-recovers without manual intervention. Making cleanup
reliable across transient RPC failures, executor replacement, unknown transaction
outcome, and retry ownership is a separate cross-CN lifecycle design.

So I would prefer to keep this PR scoped to cancel/drain of active consumers and
bounded in-memory fences. A fully fail-closed or durable fence protocol should be
handled as a follow-up design rather than added opportunistically here.

@mergify

mergify Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-20 09:12 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-07-20 13:15 UTC · at 24a552ee47a53016a4e06b5690ccca21f2447860

This pull request spent 4 hours 2 minutes 36 seconds in the queue, with no time running CI.

Waiting for any of
  • check-neutral = Matrixone Utils CI / Coverage
  • check-skipped = Matrixone Utils CI / Coverage
  • check-success = Matrixone Utils CI / Coverage
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • #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 CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64

Reason

Pull request #25733 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Failing checks:

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

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/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants