Skip to content

fix(pipeline): preserve late remote terminal errors - #28278

Merged
mergify[bot] merged 6 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-28277-c4ea83b7
Sep 6, 2026
Merged

mergify[bot] merged 6 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-28277-c4ea83b7

Conversation

@gouhongshen

@gouhongshen gouhongshen commented Sep 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:

Related to #28277

What this PR does / why we need it:

Root cause

A remote pipeline receive can observe internal context cancellation immediately before the execution CN publishes its terminal response. That cancellation was normalized as a successful early stop. The existing StopSending cleanup handshake subsequently consumed the remote terminal error but discarded it. At the local pipeline boundary, scope cancellation could also win before a retained connector Error terminal was observed, even though the PipelineEdge had already recorded the substantive failure durably.

The local multi-input receiver had two related arbitration gaps: it knew only the pipeline context and therefore could replace a query-owned cancellation with a late edge failure, and it returned the first durable edge error in source order even when that error was cancellation fallout and a later edge held the real execution failure. Together these races allowed an execution-side duplicate-key failure to reach the SQL client as success or allowed the wrong terminal class to win.

Remote StopSending arbitration also initially applied its teardown result before resolving the cancellation that triggered cleanup. When the pipeline already carried a substantive execution cause, a simultaneous StopSending send failure, response closure, or timeout could therefore replace that SQL error with a transport error.

Changes

  • Make the existing StopSending handshake return its terminal result, then resolve the original query/pipeline cancellation first. The handshake result supplies the outcome only when that original cancellation is secondary, so a known execution cause cannot be hidden by teardown while a cause-less terminal-less handshake still fails closed.
  • Claim StopSending arbitration once under the sender state lock, so cleanup force-closes after a terminal-less attempt rather than waiting for the same 30-second deadline twice. Cleanup-only callers explicitly ignore the already-arbitrated result.
  • Preserve query-owned cancellation, deadlines, and substantive pipeline execution causes when that bounded handshake fails without a terminal; cleanup still runs and force-closes the unhealthy stream.
  • Publish the retained local root Error terminal before canceling the remote scope.
  • Initialize production Merge receivers from the Process so they retain both the query context and the child pipeline context. Query cancellation/deadline now owns every receiver terminal return, including a directly received or durably synthesized Error signal.
  • When the query remains active, resolve canceled receivers from the process cancellation cause and all durable input-edge failures. A substantive failure outranks cancellation-only fallout independent of input order; a cancellation error is retained only when every recorded edge error is cancellation-shaped.
  • Extend the composite-primary-key BVT with post-failure row-count assertions for both six-column and nineteen-column composite keys.

Issue-to-test proof

  • TestRemoteRunNormalizesPipelineCancellationCause/remote_failure_returned_after_internal_cancellation_survives deterministically forces cancellation to win the first receive and releases the duplicate-key terminal only after StopSending. The test failed before the handshake return-value change and now requires the duplicate-key error at both RemoteRun and the retained root edge.
  • The same unit test covers an immediate remote execution failure, terminal publication before scope cancellation, graceful internal cancellation, query cancellation, deadline cancellation, and a late remote QueryInterrupted terminal that must remain secondary.
  • Its StopSending cases deterministically cover a substantive send failure, a cancellation-shaped send failure mapped to closed transport, response-channel closure before terminal, and an injected 10 ms timeout. Every case asserts the client/root error class, and the timeout case asserts exactly one StopSending request across arbitration and cleanup.
  • Six cross-product cases combine query cancellation and query deadline with StopSending send failure, response-channel closure, and timeout. They require the query-owned terminal at both RemoteRun and the retained root while preserving substantive handshake failures for internal cancellation.
  • Three cross-product cases combine a DuplicateEntry pipeline cancellation cause with StopSending send failure, response-channel closure, and timeout. All three failed before the final arbitration-order change with BackendClosed, StreamClosed, or RPCTimeout respectively; they now require DuplicateEntry at both RemoteRun and the retained root. The existing cause-less cases continue to require the teardown errors.
  • TestPipelineSignalReceiverCancellationPreservesExecutionCause, TestPipelineSignalReceiverCancellationPreservesDeadlineClass, and TestPipelineSignalReceiverCancellationPreservesDurableEdgeFailure cover substantive process causes, joined errors, graceful cancellation, deadline identity, full-channel Error delivery, and QueryInterrupted cancellation.
  • TestPipelineSignalReceiverDurableFailureSelectionIsOrderIndependent fills both input channels so Error publication can succeed only through durable edge state, then proves DuplicateEntry outranks QueryInterrupted in both edge orders and that an all-cancellation set remains cancellation-shaped. Its cancellation-first case failed before the production change.
  • TestMergePreservesQueryTerminalOverLateEdgeFailure uses separate query and pipeline contexts through the real Merge Prepare/Call path. It cancels or deadlines the query before recording an undeliverable late DuplicateEntry and requires the query terminal in both cases. The cancellation case failed before the production change.
  • comprimary_key.sql still requires the exact duplicate errors for cpk_table_5 and cpk_table_6, and now proves failure atomicity by requiring four rows after each rejected INSERT ... SELECT.

Tests run

  • make build on committed head 1e1fbaaf69
  • Focused receiver, Merge, and remote arbitration regressions after the latest rebase; the Merge query-terminal case passed 20 repetitions
  • Complete RemoteRun arbitration matrix on committed head 1e1fbaaf69 under -race, 100 repetitions; the three new pipeline-cause/StopSending cross-products also passed independently
  • Focused receiver and Merge arbitration tests under -race, 100 repetitions
  • Full ./pkg/sql/compile normal and race suites on committed head 1e1fbaaf69; full affected-package tests on rebased predecessor 3d829006a3: ./pkg/vm/process, ./pkg/sql/colexec/merge, and ./pkg/sql/compile
  • Full race tests: ./pkg/vm/process and ./pkg/sql/colexec/merge
  • Earlier unchanged closure coverage remains green for ./pkg/sql/colexec/connector and ./pkg/sql/colexec/dispatch
  • go vet -mod=readonly ./pkg/sql/compile on committed head 1e1fbaaf69; earlier full affected-package vet remains green
  • Repository-configured golangci-lint 2.6.2 on all three changed package trees at 3d829006a3: 0 issues. gofmt -d is empty for every changed Go file on 1e1fbaaf69.
  • Native two-CN Proxy BVT: comprimary_key.sql, 300 repetitions, 21,900/21,900 statements passed; all generated reports were inspected and contained no failures. After review and rebases, the case was repeatedly rerun on fresh two-CN Proxy clusters. On semantic head 9bc9c3ae60, it passed 73/73 statements with an empty error report; the six-column duplicate was client-visible and the post-failure row count remained four. The subsequent commit changes only test whitespace.

The documented Docker topology could not be built locally because Docker Hub authentication returned EOF. The same repository etc/launch-with-proxy two-CN topology was run natively through Proxy with the rebuilt mo-service; no topology configuration is included in this PR.

Rebase verification

Rebased onto main commit 6e5f82f568. The new upstream commit changes JSON binary subtype handling and does not overlap this PR's production code, terminal tests, or BVT. The full receiver, Merge, and compile package suites plus repository-configured lint were rerun after rebase. The exact two-CN Proxy comprimary_key.sql BVT passed 73/73 with an empty error report at 9bc9c3ae60; the later 3d829006a3 commit changed only test formatting. The final RemoteRun precedence change is covered by exact deterministic UT and a committed-head binary build, while fresh PR CI supplies the current-head Proxy BVT.

Residual risks

The original CI symptom is timing-dependent. Forced unit tests provide deterministic coverage of cancellation-before-terminal ordering, terminal-less StopSending outcomes, query-vs-pipeline-vs-teardown ownership, and multi-edge priority independent of source order, while repeated Proxy BVT supplies end-to-end stress evidence. Terminal-less StopSending paths fail closed with explicit transport/protocol/timeout errors and have a single bounded wait; no retry, fallback channel, or unbounded resource lifecycle was added.

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Sep 6, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Sep 6, 2026
@gouhongshen
gouhongshen force-pushed the agent/issue-28277-c4ea83b7 branch from a2e03b0 to 167bc74 Compare September 6, 2026 09:28
@gouhongshen

gouhongshen commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor Author

Unrelated CI blocker: coverage UT intermittently failed the pre-existing CDC writer-first task-row lock waiter assertion. Tracked in #28282. The one permitted failed-job rerun for workflow run 34024743134 was requested after attempt 1 became terminal.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Valid and fixed in 2b102a42e2.

RemoteRun still performs the same bounded, one-shot StopSending handshake, but a terminal-less handshake failure now replaces the receive result only while the query context remains active. An already canceled/deadlined query therefore keeps ownership of the terminal result and the retained root receives the same error; internal cancellation still surfaces BackendClosed/StreamClosed/RPCTimeout instead of success.

I added the full 2×3 cross-product: query cancellation and deadline, each with StopSending send failure, response-channel closure, and timeout. All six failed before the production change with the teardown error, then passed after it. The complete arbitration matrix passed -race -count=100, the full pkg/sql/compile suite and make build passed, and the committed head passed the exact two-CN Proxy comprimary_key.sql BVT 73/73 with an empty error report. Could you please review the updated head?

@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 latest RemoteRun change correctly closes the previous query-cancellation/StopSending finding, and the earlier terminal-less and double-wait findings remain fixed. Two equivalent arbitration gaps remain in the local multi-input receiver path.

[P1] Preserve query-owned cancellation before consulting durable edge failures

PipelineSignalReceiver is initialized with only proc.Ctx, so contextDoneError cannot distinguish external query cancellation from internal pipeline cancellation. After plain context.Canceled, it scans the edges and returns any recorded error (process_spoolr.go:522-537). A concrete production-shaped sequence is: build pipelineCtx as a child of queryCtx, initialize a Merge receiver, cancel queryCtx, then let an input edge record a late duplicate-key error before the receiver wakes. Whether GetNextBatch selects the context, Ch2, or Done branch, it returns the duplicate error. normalizeScopeRunError then short-circuits at compile.go:744-746 because the error is substantive, and Compile.Run returns the runOnce error before checking GetQueryContextError (compile2.go:467-470). The client sees duplicate-key instead of the query-owned context.Canceled, contradicting the existing plain external cancellation remains primary contract and the new RemoteRun policy.

Please make receiver arbitration query-aware: when the query context is already canceled/deadlined, preserve that external terminal; consult process causes and durable edges only while the query remains active. Add a deterministic cross-layer test with separate query and pipeline contexts, query cancellation first, and a late durable edge failure.

[P1] Do not let the first cancellation-shaped edge hide a later execution failure

When the query is active and the pipeline context is internally canceled, contextDoneError returns the first non-nil reg.Err() in source order. With two ready inputs where edge 0 records QueryInterrupted/context cancellation and edge 1 records DuplicateEntry, the helper returns edge 0 without examining edge 1. The caller can then normalize that cancellation to nil, recreating the false-success class this PR is intended to eliminate. Reversing the edge order changes the result, even though the terminal facts are identical.

Please inspect all durable edge errors and prefer a substantive execution error over cancellation-only fallout; retain a cancellation error only when every recorded error is cancellation-shaped. Cover both edge orders, preferably with the data channel occupied so the durable-state fallback rather than successful enqueue is the oracle.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Both findings were valid and are addressed in 9bc9c3ae60.

  • Merge now constructs PipelineSignalReceiver from the Process, so the receiver retains the query context separately from the child pipeline context. Query cancellation/deadline is checked before process causes or edge failures and also before returning directly received or durably synthesized Error/Abort terminals.
  • With an active query, contextDoneError scans every durable edge error. It returns the first substantive execution failure and uses a cancellation-shaped error only when no substantive edge failure exists, so input order cannot recreate false success.

The new Merge-level test uses separate query/pipeline contexts, cancels or deadlines the query before recording a late undeliverable DuplicateEntry, and requires the query terminal through the real Prepare/Call path. The receiver-level table fills both input channels and covers cancellation-first, failure-first, and all-cancellation durable states. The two reported pre-fix cases failed before the production change.

Focused receiver and Merge cases passed 100 repetitions under -race; full pkg/vm/process, pkg/sql/colexec/merge, and pkg/sql/compile tests, full race tests for the two changed owning packages, focused vet, and make build passed. After rebasing onto 9ae27d218d, the exact two-CN Proxy comprimary_key.sql BVT passed 73/73 with an empty error report and retained four rows after the rejected six-column duplicate insert. Could you please review the updated head?

@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 previous receiver-arbitration findings are fixed on 3d829006a384, and the exact-head CI evidence is green. One error-precedence cross-product still blocks the PR.

[P1] Preserve an already-known pipeline execution cause over StopSending teardown failures

RemoteRun replaces the cancellation-shaped receive error with every non-nil StopSending result whenever the query context is still active. That replacement happens before normalizeScopeRunError can recover a substantive context.Cause(s.Proc.Ctx). Because BackendClosed, StreamClosed, and RPCTimeout are not cancellation-shaped, normalization then returns early and the cleanup transport error hides the execution failure that originally canceled the pipeline.

A deterministic extension of the existing table reproduces this with:

cancelCause: duplicateErr,
stopSendErr: moerr.NewBackendClosedNoCtx(),
wantErr: duplicateErr,

The exact focused run fails with:

expected: Duplicate entry 1 for key primary
in chain: backend connection closed

This is production-reachable when one local scope records a duplicate-key or other substantive failure in the shared pipeline cancellation cause while a remote scope wakes with QueryInterrupted, then its StopSending transport fails during teardown. The client receives a reconnect/retry-shaped transport error instead of the deterministic SQL execution error, and the retained root edge receives the same wrong terminal. Response-channel closure and timeout have the identical precedence defect.

Please resolve the original cancellation through its query/pipeline context before applying the handshake result, or otherwise arbitrate teardown errors only when no query-owned or substantive pipeline-owned terminal already exists. Add the three cross-products of a substantive pipeline cause with StopSending send failure, response closure, and timeout; retain the current behavior where those handshake failures are substantive for a cause-less internal cancellation.

The one-attempt timeout bound, query cancel/deadline priority, receiver edge-order handling, root publication ordering, resource ownership, and steady-state performance path otherwise close correctly in this head.

@gouhongshen

Copy link
Copy Markdown
Contributor Author

@XuPeng-SH Valid and fixed in 1e1fbaaf69.

RemoteRun now retains the StopSending result separately, then resolves the original cancellation through the query/pipeline contexts first. A query terminal or substantive pipeline cause therefore remains primary; StopSending supplies the result only when the original internal cancellation normalizes to secondary. The cause-less send-failure, response-closure, and timeout cases still fail closed, and cleanup remains one bounded handshake followed by force-close.

I added all three DuplicateEntry pipeline-cause cross-products. Before the production change they returned BackendClosed, StreamClosed, and RPCTimeout respectively; afterward they return DuplicateEntry at both RemoteRun and the retained root. The complete arbitration matrix passed -race -count=100, the full pkg/sql/compile normal and race suites passed, focused vet passed, and make build passed on the committed head. Could you please review the updated head?

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

Reviewed exact head 1e1fbaa against base 6e5f82f.

The latest change closes the remaining precedence blocker: RemoteRun resolves the original query/pipeline cancellation before consulting StopSending, so a substantive execution cause cannot be replaced by BackendClosed, StreamClosed, or RPCTimeout. The new cross-product covers all three teardown outcomes while cause-less internal cancellation still fails closed.

I rechecked the full change map and unhappy paths: StopSending has one owner and one bounded wait; the root durable terminal is published before cancellation; Merge separates query and pipeline contexts and prefers substantive durable edge errors independent of edge order; cleanup adds no retry, goroutine, unbounded queue, or steady-state RPC. The only new O(live inputs) scan is on cancellation/error arbitration, not the data path. Current-head UT/SCA and Proxy/PESSIMISTIC BVT are green. No blocking correctness, liveness, resource, performance, compatibility, or test-quality issue remains.

@mergify

mergify Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-06 18:43 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks skipped · PR is already up-to-date
  • ✅ Merged — 2026-09-06 18:44 UTC · at f14eb824df4c74fb341ebecd46d2da3358503a95 · squash

This pull request spent 19 seconds in the queue, including 4 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]
  • 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
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • 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 UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)

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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants