Skip to content

test: remove CDC timing races and isolate ISCP recovery checks - #28173

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-cdc-iscp-proxy-flakes
Sep 5, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-cdc-iscp-proxy-flakes

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • Test and CI
  • BUG

Which issue(s) this PR fixes:

Fixes #28167.
Addresses the demonstrated cold-start budget coupling in #27997; keep that issue open for CI confirmation.
Related to #27809: test-result arbitration, phase-local contexts and diagnostic/cleanup improvements, not a claimed historical root-cause fix.

What this PR does / why we need it:

Evidence and first-principles contracts

  1. [Bug]: TestTableChangeStream_FullPipeline_RandomDelaysAndErrors is flaky in CI #28167: fault injection races the operation it is supposed to fail. The test observed a recorded commit, then installed rollback failure. Cleanup could already have read its rollback result; a later 50ms sleep cannot establish a happens-before relationship. Install both faults before starting the stream, wait for Run to finish, then assert the original commit error, terminal non-retryability, sink rollback error, stale-read recovery and exactly begin -> commit -> rollback. Remove cancellation-as-success, repeated stable-state polling and configuration-only injection flags. Keep the historical test name for traceability.
  2. [Bug]: TestInvalidTimestamp flakes when ISCP watermark stays at 0-0 after invalid-timestamp fault #27997: the failed run recovered job discovery but spent the recovery budget on cold consumer initialization. In the failing CI job, add or update job follows the injected error. The worker then creates the destination database/table; job-state commit takes 3.54s and database creation commit takes 2.95s. The timeout occurs during destination table creation, not another logged invalid-timestamp failure. Prepare the empty destination schema before fault injection, leaving discovery, snapshot copying and watermark advancement in the unchanged 10s recovery budget. Add bidirectional source/destination data comparison. The injection barrier still proves the worker hit the fault and no job watermark exists before release. Defer barrier removal before executor shutdown on assertion failure. This isolates the recovery contract; it does not prove every possible watermark stall has been fixed. Other integration tests retain cold-start consumer DDL coverage.
  3. [Bug]: TestProxyRetryPreservesAppliedHandoffRepresentative times out in coverage CI #27809: no proven blocked edge yet. Current-main focused, race and coverage repetitions pass. Preserve the existing handoff/liveness assertions and 30s acquisition budget. On failure capture owner holders/waiters/status/notification count, proxy representative/pending handoffs, event-queue length and bounded all-goroutine stacks. Use TryRLock so diagnostics cannot wait on the potentially blocked mutex. Cancel and boundedly join the exclusive-lock worker before service teardown. The issue must remain open until a reproduced failure identifies the missing progress edge; no speculative lock-protocol change is included.
  4. Same-pattern audit: circuit breaker cooldown. TestExecutor_execWithRetry_CircuitBreakerOpens assumed the next call occurred within a 50ms cooldown. A scheduler pause invalidates that assumption. Use a long open window and explicitly age openedAt under the existing mutex for the expiry phase. Keep both rejection-before-expiry and recovery-after-expiry assertions without a sleep. No production clock abstraction is added.

Scope, risks and unhappy paths

  • Four test files only; no production API, lock protocol, transaction/retry policy or runtime performance changes.
  • Audited nearby CDC injection setters, sleep-based state assumptions and ISCP fault barriers. This is a targeted same-pattern audit, not a claim that all repository flakes are eliminated. Delays that intentionally model slow operations were not mechanically removed.
  • Recovery still must propagate real data, not merely observe job existence. Destination preparation copies schema only, never source rows.
  • Handoff diagnostics are failure-only and bounded (2MiB stack buffer per dump). Owner/proxy snapshots are individually locked, not a cross-service atomic snapshot. An unavailable lock and stack truncation are explicitly reported. Cancellation cleanup adds at most a 5s diagnostic budget, not extra time to pass the acquisition assertion.
  • Repeated passes do not establish the cause of the historical [Bug]: TestProxyRetryPreservesAppliedHandoffRepresentative times out in coverage CI #27809 timeout. Linux CI and its resource contention remain unverified locally.

Validation

Base: 313991b503fb10d0b72daf811c716e57fe7f2a07, macOS arm64, Go 1.26.4, native dependencies built with make -j8 cgo. All Go commands used .agents/skills/mo-dev/scripts/mo-cgo-test for platform-correct native linking.

  • CDC full package: -short -count=1 -timeout=12m ./pkg/cdc — PASS.
  • CDC full-pipeline and rollback-failure tests: 20 focused repetitions — PASS.
  • CDC full-pipeline, rollback-failure and circuit-breaker tests: -race -short -count=10 -timeout=15m — PASS.
  • TestInvalidTimestamp: 3 focused repetitions and -race -short -count=5 -timeout=15m — PASS, including the added data comparison.
  • TestProxyRetryPreservesAppliedHandoffRepresentative: 20 baseline repetitions, 20 race repetitions and 50 coverage repetitions — PASS.
  • gofmt and git diff --check — PASS.

Self-review checked fault-installation ordering, terminal-state assertions, failure-path teardown, snapshot lock safety, unchanged time budgets, retained data/ordering oracles and production-performance scope. No remaining defect found in these changes; historical #27809 remains unresolved.

Follow-up deep review: failure paths and non-overfit checks

The first delivery review missed test-fixture cleanup problems; green exit status alone was insufficient. This follow-up traced ownership through assertion failure and inspected successful-test logs as well.

Closure Verified finding / resolution
Q1: recording sink output ownership Even a passing full-pipeline test logged 24 bytes / 2 outstanding objects. The fake sink retained transferred DecoderOutput batches without releasing them. The shared harness now drains outputs after Run joins and before pool destruction; draining detaches the slice and is idempotent. The focal test explicitly requires zero remaining pool bytes.
Q1/Q2: newly added SQL steps execSql uses a caller-owned transaction and returns on SQL error without rollback. New setup and both data-comparison queries now use SQLExecutor.Exec without an external transaction, so the executor owns commit/rollback; results are closed before fatal assertions. The unsafe legacy helper itself is not broadly refactored in this PR.
Q2: assertions under a mutex The handoff test made fatal assertions while retaining proxy.mu.RLock. It now copies the representative and pending count under the lock, releases it, and then asserts.
Q3: cost and bounds No production changes, added sleep, passing-timeout extension, new service fixture or retry-to-pass mechanism. Captured output batches are released at fixture termination rather than left behind.

Counterexample validation deliberately disabled rollback failure in the focal CDC test. It failed at the non-retryability assertion in 0.44s and exited with status 1; after the cleanup fix that failure no longer left the outstanding-ownership warning. The temporary mutation was restored and is not delivered. This demonstrates a discriminating oracle and failure cleanup, not just repeated green runs.

Single-test race measurements (excluding build): CDC full pipeline 0.41s; TestInvalidTimestamp 1.60s; proxy handoff 0.23s. These are local observations, not flaky timing assertions or a claim of a statistically established speedup. Empty destination setup isolates the recovery phase; it does not remove total DDL work or claim to optimize slow TN commits. Cold-start DDL remains covered by other integration cases.

The broader statement “all three historical flakes are fixed and can never hang” is not supported: #27809's missing-progress edge is still unproven, and no change here repairs its unknown historical root cause. Keep that issue open. A bounded diagnostic join also is not a proof that arbitrary future production deadlocks can be interrupted by Go contexts.

#27809 follow-up: confirmed test defects, historical cause still open

  • A Go select can choose the deadline even when the successful Lock result is already buffered. The test now does one nonblocking result recheck on the deadline path. A completed result wins; an actual Lock error is preserved, and an expired context without a result still fails immediately. There is no additional waiting or retry-to-pass. This establishes completion, not a strict wall-clock latency SLA.
  • Final shared-lock release and exclusive-lock cleanup now each use their own 5s context instead of reusing setup's aging 5s context. The exclusive acquisition retains its original 30s budget, including the release phase; these contexts do not restart or extend that budget.
  • Seven no-sleep unit cases cover success, actual error, both-ready success/error, deadline without result, and closed-without-result with/without an expired deadline. Unexpected channel closure cannot masquerade as successful acquisition.
  • Code tracing and temporary controlled experiments exercised notification before waiting and delayed progress after notification. Both progressed; no missing notification, abandoned representative or lock cycle was demonstrated. Temporary diagnostic experiments are not shipped. These findings do not establish which edge stalled in the historical Linux coverage runs, and [Bug]: TestProxyRetryPreservesAppliedHandoffRepresentative times out in coverage CI #27809 must remain open.
  • Scope remains test-only: no production lock protocol, retry policy or runtime hot-path cost changes. Actual acquisition errors still trigger bounded failure diagnostics and fail the test.

Validation of this final follow-up source (macOS arm64, same native wrapper): exact handoff + result-arbitration tests -race -short -count=100 -timeout=120s PASS (26.089s); the same selection -cover -short -count=50 -timeout=120s PASS (13.029s); owning ./pkg/lockservice package -short -count=1 -timeout=240s PASS (89.516s). All seven result-arbitration cases executed. gofmt and git diff --check passed. Prior CDC/ISCP evidence is reused because this follow-up changes only the proxy test file. These passes are validation of the delivered changes, not proof that the historical Linux flake cannot recur.

Follow-up validation on the delivered source: CDC owning package normal PASS (12.618s, previous delivery 12.725s) and race PASS (14.496s); exact full-pipeline test race x73 PASS; exact invalid-timestamp test race x19 PASS; exact proxy-handoff test race x100 PASS. Repetition counts follow the measured test-body / 30s-budget rule. All commands terminated, and the temporary negative-control mutation was removed before the final tests and commit. Earlier circuit-breaker evidence is reused because its code and dependency contract did not change. Linux CI remains separate from these macOS results.

@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 merged commit e74cdbe into matrixorigin:main Sep 5, 2026
26 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-cdc-iscp-proxy-flakes branch September 5, 2026 00:47
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…xorigin#28173)

## What type of PR is this?

- [x] Test and CI
- [x] BUG

## Which issue(s) this PR fixes:

Fixes matrixorigin#28167.
Addresses the demonstrated cold-start budget coupling in matrixorigin#27997; keep
that issue open for CI confirmation.
Related to matrixorigin#27809: test-result arbitration, phase-local contexts and
diagnostic/cleanup improvements, **not a claimed historical root-cause
fix**.

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

### Evidence and first-principles contracts

1. **matrixorigin#28167: fault injection races the operation it is supposed to
fail.** The test observed a recorded commit, then installed rollback
failure. Cleanup could already have read its rollback result; a later
50ms sleep cannot establish a happens-before relationship. Install both
faults before starting the stream, wait for Run to finish, then assert
the original commit error, terminal non-retryability, sink rollback
error, stale-read recovery and exactly `begin -> commit -> rollback`.
Remove cancellation-as-success, repeated stable-state polling and
configuration-only injection flags. Keep the historical test name for
traceability.
2. **matrixorigin#27997: the failed run recovered job discovery but spent the
recovery budget on cold consumer initialization.** In [the failing CI
job](https://github.com/matrixorigin/matrixone/actions/runs/33587927832/job/100115871094),
`add or update job` follows the injected error. The worker then creates
the destination database/table; job-state commit takes 3.54s and
database creation commit takes 2.95s. The timeout occurs during
destination table creation, not another logged invalid-timestamp
failure. Prepare the *empty* destination schema before fault injection,
leaving discovery, snapshot copying and watermark advancement in the
unchanged 10s recovery budget. Add bidirectional source/destination data
comparison. The injection barrier still proves the worker hit the fault
and no job watermark exists before release. Defer barrier removal before
executor shutdown on assertion failure. This isolates the recovery
contract; it does not prove every possible watermark stall has been
fixed. Other integration tests retain cold-start consumer DDL coverage.
3. **matrixorigin#27809: no proven blocked edge yet.** Current-main focused, race
and coverage repetitions pass. Preserve the existing handoff/liveness
assertions and 30s acquisition budget. On failure capture owner
holders/waiters/status/notification count, proxy representative/pending
handoffs, event-queue length and bounded all-goroutine stacks. Use
TryRLock so diagnostics cannot wait on the potentially blocked mutex.
Cancel and boundedly join the exclusive-lock worker before service
teardown. The issue must remain open until a reproduced failure
identifies the missing progress edge; no speculative lock-protocol
change is included.
4. **Same-pattern audit: circuit breaker cooldown.**
`TestExecutor_execWithRetry_CircuitBreakerOpens` assumed the next call
occurred within a 50ms cooldown. A scheduler pause invalidates that
assumption. Use a long open window and explicitly age `openedAt` under
the existing mutex for the expiry phase. Keep both
rejection-before-expiry and recovery-after-expiry assertions without a
sleep. No production clock abstraction is added.

### Scope, risks and unhappy paths

- Four test files only; no production API, lock protocol,
transaction/retry policy or runtime performance changes.
- Audited nearby CDC injection setters, sleep-based state assumptions
and ISCP fault barriers. This is a targeted same-pattern audit, not a
claim that all repository flakes are eliminated. Delays that
intentionally model slow operations were not mechanically removed.
- Recovery still must propagate real data, not merely observe job
existence. Destination preparation copies schema only, never source
rows.
- Handoff diagnostics are failure-only and bounded (2MiB stack buffer
per dump). Owner/proxy snapshots are individually locked, not a
cross-service atomic snapshot. An unavailable lock and stack truncation
are explicitly reported. Cancellation cleanup adds at most a 5s
diagnostic budget, not extra time to pass the acquisition assertion.
- Repeated passes do not establish the cause of the historical matrixorigin#27809
timeout. Linux CI and its resource contention remain unverified locally.

### Validation

Base: `313991b503fb10d0b72daf811c716e57fe7f2a07`, macOS arm64, Go
1.26.4, native dependencies built with `make -j8 cgo`. All Go commands
used `.agents/skills/mo-dev/scripts/mo-cgo-test` for platform-correct
native linking.

- CDC full package: `-short -count=1 -timeout=12m ./pkg/cdc` — PASS.
- CDC full-pipeline and rollback-failure tests: 20 focused repetitions —
PASS.
- CDC full-pipeline, rollback-failure and circuit-breaker tests: `-race
-short -count=10 -timeout=15m` — PASS.
- `TestInvalidTimestamp`: 3 focused repetitions and `-race -short
-count=5 -timeout=15m` — PASS, including the added data comparison.
- `TestProxyRetryPreservesAppliedHandoffRepresentative`: 20 baseline
repetitions, 20 race repetitions and 50 coverage repetitions — PASS.
- `gofmt` and `git diff --check` — PASS.

Self-review checked fault-installation ordering, terminal-state
assertions, failure-path teardown, snapshot lock safety, unchanged time
budgets, retained data/ordering oracles and production-performance
scope. No remaining defect found in these changes; historical matrixorigin#27809
remains unresolved.

### Follow-up deep review: failure paths and non-overfit checks

The first delivery review missed test-fixture cleanup problems; green
exit status alone was insufficient. This follow-up traced ownership
through assertion failure and inspected successful-test logs as well.

| Closure | Verified finding / resolution |
|---|---|
| Q1: recording sink output ownership | Even a passing full-pipeline
test logged 24 bytes / 2 outstanding objects. The fake sink retained
transferred DecoderOutput batches without releasing them. The shared
harness now drains outputs **after Run joins and before pool
destruction**; draining detaches the slice and is idempotent. The focal
test explicitly requires zero remaining pool bytes. |
| Q1/Q2: newly added SQL steps | `execSql` uses a caller-owned
transaction and returns on SQL error without rollback. New setup and
both data-comparison queries now use SQLExecutor.Exec without an
external transaction, so the executor owns commit/rollback; results are
closed before fatal assertions. The unsafe legacy helper itself is not
broadly refactored in this PR. |
| Q2: assertions under a mutex | The handoff test made fatal assertions
while retaining proxy.mu.RLock. It now copies the representative and
pending count under the lock, releases it, and then asserts. |
| Q3: cost and bounds | No production changes, added sleep,
passing-timeout extension, new service fixture or retry-to-pass
mechanism. Captured output batches are released at fixture termination
rather than left behind. |

Counterexample validation deliberately disabled rollback failure in the
focal CDC test. It failed at the non-retryability assertion in 0.44s and
exited with status 1; after the cleanup fix that failure no longer left
the outstanding-ownership warning. The temporary mutation was restored
and is not delivered. This demonstrates a discriminating oracle and
failure cleanup, not just repeated green runs.

Single-test race measurements (excluding build): CDC full pipeline
0.41s; TestInvalidTimestamp 1.60s; proxy handoff 0.23s. These are local
observations, not flaky timing assertions or a claim of a statistically
established speedup. Empty destination setup isolates the recovery
phase; it does not remove total DDL work or claim to optimize slow TN
commits. Cold-start DDL remains covered by other integration cases.

The broader statement “all three historical flakes are fixed and can
never hang” is **not supported**: matrixorigin#27809's missing-progress edge is
still unproven, and no change here repairs its unknown historical root
cause. Keep that issue open. A bounded diagnostic join also is not a
proof that arbitrary future production deadlocks can be interrupted by
Go contexts.

### matrixorigin#27809 follow-up: confirmed test defects, historical cause still
open

- A Go select can choose the deadline even when the successful Lock
result is already buffered. The test now does one nonblocking result
recheck on the deadline path. A completed result wins; an actual Lock
error is preserved, and an expired context without a result still fails
immediately. There is no additional waiting or retry-to-pass. This
establishes completion, not a strict wall-clock latency SLA.
- Final shared-lock release and exclusive-lock cleanup now each use
their own 5s context instead of reusing setup's aging 5s context. The
exclusive acquisition retains its original 30s budget, including the
release phase; these contexts do not restart or extend that budget.
- Seven no-sleep unit cases cover success, actual error, both-ready
success/error, deadline without result, and closed-without-result
with/without an expired deadline. Unexpected channel closure cannot
masquerade as successful acquisition.
- Code tracing and temporary controlled experiments exercised
notification before waiting and delayed progress after notification.
Both progressed; no missing notification, abandoned representative or
lock cycle was demonstrated. Temporary diagnostic experiments are not
shipped. These findings do **not** establish which edge stalled in the
historical Linux coverage runs, and matrixorigin#27809 must remain open.
- Scope remains test-only: no production lock protocol, retry policy or
runtime hot-path cost changes. Actual acquisition errors still trigger
bounded failure diagnostics and fail the test.

Validation of this final follow-up source (macOS arm64, same native
wrapper): exact handoff + result-arbitration tests `-race -short
-count=100 -timeout=120s` PASS (26.089s); the same selection `-cover
-short -count=50 -timeout=120s` PASS (13.029s); owning
`./pkg/lockservice` package `-short -count=1 -timeout=240s` PASS
(89.516s). All seven result-arbitration cases executed. `gofmt` and `git
diff --check` passed. Prior CDC/ISCP evidence is reused because this
follow-up changes only the proxy test file. These passes are validation
of the delivered changes, not proof that the historical Linux flake
cannot recur.

Follow-up validation on the delivered source: CDC owning package normal
PASS (12.618s, previous delivery 12.725s) and race PASS (14.496s); exact
full-pipeline test race x73 PASS; exact invalid-timestamp test race x19
PASS; exact proxy-handoff test race x100 PASS. Repetition counts follow
the measured test-body / 30s-budget rule. All commands terminated, and
the temporary negative-control mutation was removed before the final
tests and commit. Earlier circuit-breaker evidence is reused because its
code and dependency contract did not change. Linux CI remains separate
from these macOS results.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…xorigin#28173)

## What type of PR is this?

- [x] Test and CI
- [x] BUG

## Which issue(s) this PR fixes:

Fixes matrixorigin#28167.
Addresses the demonstrated cold-start budget coupling in matrixorigin#27997; keep
that issue open for CI confirmation.
Related to matrixorigin#27809: test-result arbitration, phase-local contexts and
diagnostic/cleanup improvements, **not a claimed historical root-cause
fix**.

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

### Evidence and first-principles contracts

1. **matrixorigin#28167: fault injection races the operation it is supposed to
fail.** The test observed a recorded commit, then installed rollback
failure. Cleanup could already have read its rollback result; a later
50ms sleep cannot establish a happens-before relationship. Install both
faults before starting the stream, wait for Run to finish, then assert
the original commit error, terminal non-retryability, sink rollback
error, stale-read recovery and exactly `begin -> commit -> rollback`.
Remove cancellation-as-success, repeated stable-state polling and
configuration-only injection flags. Keep the historical test name for
traceability.
2. **matrixorigin#27997: the failed run recovered job discovery but spent the
recovery budget on cold consumer initialization.** In [the failing CI
job](https://github.com/matrixorigin/matrixone/actions/runs/33587927832/job/100115871094),
`add or update job` follows the injected error. The worker then creates
the destination database/table; job-state commit takes 3.54s and
database creation commit takes 2.95s. The timeout occurs during
destination table creation, not another logged invalid-timestamp
failure. Prepare the *empty* destination schema before fault injection,
leaving discovery, snapshot copying and watermark advancement in the
unchanged 10s recovery budget. Add bidirectional source/destination data
comparison. The injection barrier still proves the worker hit the fault
and no job watermark exists before release. Defer barrier removal before
executor shutdown on assertion failure. This isolates the recovery
contract; it does not prove every possible watermark stall has been
fixed. Other integration tests retain cold-start consumer DDL coverage.
3. **matrixorigin#27809: no proven blocked edge yet.** Current-main focused, race
and coverage repetitions pass. Preserve the existing handoff/liveness
assertions and 30s acquisition budget. On failure capture owner
holders/waiters/status/notification count, proxy representative/pending
handoffs, event-queue length and bounded all-goroutine stacks. Use
TryRLock so diagnostics cannot wait on the potentially blocked mutex.
Cancel and boundedly join the exclusive-lock worker before service
teardown. The issue must remain open until a reproduced failure
identifies the missing progress edge; no speculative lock-protocol
change is included.
4. **Same-pattern audit: circuit breaker cooldown.**
`TestExecutor_execWithRetry_CircuitBreakerOpens` assumed the next call
occurred within a 50ms cooldown. A scheduler pause invalidates that
assumption. Use a long open window and explicitly age `openedAt` under
the existing mutex for the expiry phase. Keep both
rejection-before-expiry and recovery-after-expiry assertions without a
sleep. No production clock abstraction is added.

### Scope, risks and unhappy paths

- Four test files only; no production API, lock protocol,
transaction/retry policy or runtime performance changes.
- Audited nearby CDC injection setters, sleep-based state assumptions
and ISCP fault barriers. This is a targeted same-pattern audit, not a
claim that all repository flakes are eliminated. Delays that
intentionally model slow operations were not mechanically removed.
- Recovery still must propagate real data, not merely observe job
existence. Destination preparation copies schema only, never source
rows.
- Handoff diagnostics are failure-only and bounded (2MiB stack buffer
per dump). Owner/proxy snapshots are individually locked, not a
cross-service atomic snapshot. An unavailable lock and stack truncation
are explicitly reported. Cancellation cleanup adds at most a 5s
diagnostic budget, not extra time to pass the acquisition assertion.
- Repeated passes do not establish the cause of the historical matrixorigin#27809
timeout. Linux CI and its resource contention remain unverified locally.

### Validation

Base: `313991b503fb10d0b72daf811c716e57fe7f2a07`, macOS arm64, Go
1.26.4, native dependencies built with `make -j8 cgo`. All Go commands
used `.agents/skills/mo-dev/scripts/mo-cgo-test` for platform-correct
native linking.

- CDC full package: `-short -count=1 -timeout=12m ./pkg/cdc` — PASS.
- CDC full-pipeline and rollback-failure tests: 20 focused repetitions —
PASS.
- CDC full-pipeline, rollback-failure and circuit-breaker tests: `-race
-short -count=10 -timeout=15m` — PASS.
- `TestInvalidTimestamp`: 3 focused repetitions and `-race -short
-count=5 -timeout=15m` — PASS, including the added data comparison.
- `TestProxyRetryPreservesAppliedHandoffRepresentative`: 20 baseline
repetitions, 20 race repetitions and 50 coverage repetitions — PASS.
- `gofmt` and `git diff --check` — PASS.

Self-review checked fault-installation ordering, terminal-state
assertions, failure-path teardown, snapshot lock safety, unchanged time
budgets, retained data/ordering oracles and production-performance
scope. No remaining defect found in these changes; historical matrixorigin#27809
remains unresolved.

### Follow-up deep review: failure paths and non-overfit checks

The first delivery review missed test-fixture cleanup problems; green
exit status alone was insufficient. This follow-up traced ownership
through assertion failure and inspected successful-test logs as well.

| Closure | Verified finding / resolution |
|---|---|
| Q1: recording sink output ownership | Even a passing full-pipeline
test logged 24 bytes / 2 outstanding objects. The fake sink retained
transferred DecoderOutput batches without releasing them. The shared
harness now drains outputs **after Run joins and before pool
destruction**; draining detaches the slice and is idempotent. The focal
test explicitly requires zero remaining pool bytes. |
| Q1/Q2: newly added SQL steps | `execSql` uses a caller-owned
transaction and returns on SQL error without rollback. New setup and
both data-comparison queries now use SQLExecutor.Exec without an
external transaction, so the executor owns commit/rollback; results are
closed before fatal assertions. The unsafe legacy helper itself is not
broadly refactored in this PR. |
| Q2: assertions under a mutex | The handoff test made fatal assertions
while retaining proxy.mu.RLock. It now copies the representative and
pending count under the lock, releases it, and then asserts. |
| Q3: cost and bounds | No production changes, added sleep,
passing-timeout extension, new service fixture or retry-to-pass
mechanism. Captured output batches are released at fixture termination
rather than left behind. |

Counterexample validation deliberately disabled rollback failure in the
focal CDC test. It failed at the non-retryability assertion in 0.44s and
exited with status 1; after the cleanup fix that failure no longer left
the outstanding-ownership warning. The temporary mutation was restored
and is not delivered. This demonstrates a discriminating oracle and
failure cleanup, not just repeated green runs.

Single-test race measurements (excluding build): CDC full pipeline
0.41s; TestInvalidTimestamp 1.60s; proxy handoff 0.23s. These are local
observations, not flaky timing assertions or a claim of a statistically
established speedup. Empty destination setup isolates the recovery
phase; it does not remove total DDL work or claim to optimize slow TN
commits. Cold-start DDL remains covered by other integration cases.

The broader statement “all three historical flakes are fixed and can
never hang” is **not supported**: matrixorigin#27809's missing-progress edge is
still unproven, and no change here repairs its unknown historical root
cause. Keep that issue open. A bounded diagnostic join also is not a
proof that arbitrary future production deadlocks can be interrupted by
Go contexts.

### matrixorigin#27809 follow-up: confirmed test defects, historical cause still
open

- A Go select can choose the deadline even when the successful Lock
result is already buffered. The test now does one nonblocking result
recheck on the deadline path. A completed result wins; an actual Lock
error is preserved, and an expired context without a result still fails
immediately. There is no additional waiting or retry-to-pass. This
establishes completion, not a strict wall-clock latency SLA.
- Final shared-lock release and exclusive-lock cleanup now each use
their own 5s context instead of reusing setup's aging 5s context. The
exclusive acquisition retains its original 30s budget, including the
release phase; these contexts do not restart or extend that budget.
- Seven no-sleep unit cases cover success, actual error, both-ready
success/error, deadline without result, and closed-without-result
with/without an expired deadline. Unexpected channel closure cannot
masquerade as successful acquisition.
- Code tracing and temporary controlled experiments exercised
notification before waiting and delayed progress after notification.
Both progressed; no missing notification, abandoned representative or
lock cycle was demonstrated. Temporary diagnostic experiments are not
shipped. These findings do **not** establish which edge stalled in the
historical Linux coverage runs, and matrixorigin#27809 must remain open.
- Scope remains test-only: no production lock protocol, retry policy or
runtime hot-path cost changes. Actual acquisition errors still trigger
bounded failure diagnostics and fail the test.

Validation of this final follow-up source (macOS arm64, same native
wrapper): exact handoff + result-arbitration tests `-race -short
-count=100 -timeout=120s` PASS (26.089s); the same selection `-cover
-short -count=50 -timeout=120s` PASS (13.029s); owning
`./pkg/lockservice` package `-short -count=1 -timeout=240s` PASS
(89.516s). All seven result-arbitration cases executed. `gofmt` and `git
diff --check` passed. Prior CDC/ISCP evidence is reused because this
follow-up changes only the proxy test file. These passes are validation
of the delivered changes, not proof that the historical Linux flake
cannot recur.

Follow-up validation on the delivered source: CDC owning package normal
PASS (12.618s, previous delivery 12.725s) and race PASS (14.496s); exact
full-pipeline test race x73 PASS; exact invalid-timestamp test race x19
PASS; exact proxy-handoff test race x100 PASS. Repetition counts follow
the measured test-body / 30s-budget rule. All commands terminated, and
the temporary negative-control mutation was removed before the final
tests and commit. Earlier circuit-breaker evidence is reused because its
code and dependency contract did not change. Linux CI remains separate
from these macOS results.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…xorigin#28173)

## What type of PR is this?

- [x] Test and CI
- [x] BUG

## Which issue(s) this PR fixes:

Fixes matrixorigin#28167.
Addresses the demonstrated cold-start budget coupling in matrixorigin#27997; keep
that issue open for CI confirmation.
Related to matrixorigin#27809: test-result arbitration, phase-local contexts and
diagnostic/cleanup improvements, **not a claimed historical root-cause
fix**.

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

### Evidence and first-principles contracts

1. **matrixorigin#28167: fault injection races the operation it is supposed to
fail.** The test observed a recorded commit, then installed rollback
failure. Cleanup could already have read its rollback result; a later
50ms sleep cannot establish a happens-before relationship. Install both
faults before starting the stream, wait for Run to finish, then assert
the original commit error, terminal non-retryability, sink rollback
error, stale-read recovery and exactly `begin -> commit -> rollback`.
Remove cancellation-as-success, repeated stable-state polling and
configuration-only injection flags. Keep the historical test name for
traceability.
2. **matrixorigin#27997: the failed run recovered job discovery but spent the
recovery budget on cold consumer initialization.** In [the failing CI
job](https://github.com/matrixorigin/matrixone/actions/runs/33587927832/job/100115871094),
`add or update job` follows the injected error. The worker then creates
the destination database/table; job-state commit takes 3.54s and
database creation commit takes 2.95s. The timeout occurs during
destination table creation, not another logged invalid-timestamp
failure. Prepare the *empty* destination schema before fault injection,
leaving discovery, snapshot copying and watermark advancement in the
unchanged 10s recovery budget. Add bidirectional source/destination data
comparison. The injection barrier still proves the worker hit the fault
and no job watermark exists before release. Defer barrier removal before
executor shutdown on assertion failure. This isolates the recovery
contract; it does not prove every possible watermark stall has been
fixed. Other integration tests retain cold-start consumer DDL coverage.
3. **matrixorigin#27809: no proven blocked edge yet.** Current-main focused, race
and coverage repetitions pass. Preserve the existing handoff/liveness
assertions and 30s acquisition budget. On failure capture owner
holders/waiters/status/notification count, proxy representative/pending
handoffs, event-queue length and bounded all-goroutine stacks. Use
TryRLock so diagnostics cannot wait on the potentially blocked mutex.
Cancel and boundedly join the exclusive-lock worker before service
teardown. The issue must remain open until a reproduced failure
identifies the missing progress edge; no speculative lock-protocol
change is included.
4. **Same-pattern audit: circuit breaker cooldown.**
`TestExecutor_execWithRetry_CircuitBreakerOpens` assumed the next call
occurred within a 50ms cooldown. A scheduler pause invalidates that
assumption. Use a long open window and explicitly age `openedAt` under
the existing mutex for the expiry phase. Keep both
rejection-before-expiry and recovery-after-expiry assertions without a
sleep. No production clock abstraction is added.

### Scope, risks and unhappy paths

- Four test files only; no production API, lock protocol,
transaction/retry policy or runtime performance changes.
- Audited nearby CDC injection setters, sleep-based state assumptions
and ISCP fault barriers. This is a targeted same-pattern audit, not a
claim that all repository flakes are eliminated. Delays that
intentionally model slow operations were not mechanically removed.
- Recovery still must propagate real data, not merely observe job
existence. Destination preparation copies schema only, never source
rows.
- Handoff diagnostics are failure-only and bounded (2MiB stack buffer
per dump). Owner/proxy snapshots are individually locked, not a
cross-service atomic snapshot. An unavailable lock and stack truncation
are explicitly reported. Cancellation cleanup adds at most a 5s
diagnostic budget, not extra time to pass the acquisition assertion.
- Repeated passes do not establish the cause of the historical matrixorigin#27809
timeout. Linux CI and its resource contention remain unverified locally.

### Validation

Base: `313991b503fb10d0b72daf811c716e57fe7f2a07`, macOS arm64, Go
1.26.4, native dependencies built with `make -j8 cgo`. All Go commands
used `.agents/skills/mo-dev/scripts/mo-cgo-test` for platform-correct
native linking.

- CDC full package: `-short -count=1 -timeout=12m ./pkg/cdc` — PASS.
- CDC full-pipeline and rollback-failure tests: 20 focused repetitions —
PASS.
- CDC full-pipeline, rollback-failure and circuit-breaker tests: `-race
-short -count=10 -timeout=15m` — PASS.
- `TestInvalidTimestamp`: 3 focused repetitions and `-race -short
-count=5 -timeout=15m` — PASS, including the added data comparison.
- `TestProxyRetryPreservesAppliedHandoffRepresentative`: 20 baseline
repetitions, 20 race repetitions and 50 coverage repetitions — PASS.
- `gofmt` and `git diff --check` — PASS.

Self-review checked fault-installation ordering, terminal-state
assertions, failure-path teardown, snapshot lock safety, unchanged time
budgets, retained data/ordering oracles and production-performance
scope. No remaining defect found in these changes; historical matrixorigin#27809
remains unresolved.

### Follow-up deep review: failure paths and non-overfit checks

The first delivery review missed test-fixture cleanup problems; green
exit status alone was insufficient. This follow-up traced ownership
through assertion failure and inspected successful-test logs as well.

| Closure | Verified finding / resolution |
|---|---|
| Q1: recording sink output ownership | Even a passing full-pipeline
test logged 24 bytes / 2 outstanding objects. The fake sink retained
transferred DecoderOutput batches without releasing them. The shared
harness now drains outputs **after Run joins and before pool
destruction**; draining detaches the slice and is idempotent. The focal
test explicitly requires zero remaining pool bytes. |
| Q1/Q2: newly added SQL steps | `execSql` uses a caller-owned
transaction and returns on SQL error without rollback. New setup and
both data-comparison queries now use SQLExecutor.Exec without an
external transaction, so the executor owns commit/rollback; results are
closed before fatal assertions. The unsafe legacy helper itself is not
broadly refactored in this PR. |
| Q2: assertions under a mutex | The handoff test made fatal assertions
while retaining proxy.mu.RLock. It now copies the representative and
pending count under the lock, releases it, and then asserts. |
| Q3: cost and bounds | No production changes, added sleep,
passing-timeout extension, new service fixture or retry-to-pass
mechanism. Captured output batches are released at fixture termination
rather than left behind. |

Counterexample validation deliberately disabled rollback failure in the
focal CDC test. It failed at the non-retryability assertion in 0.44s and
exited with status 1; after the cleanup fix that failure no longer left
the outstanding-ownership warning. The temporary mutation was restored
and is not delivered. This demonstrates a discriminating oracle and
failure cleanup, not just repeated green runs.

Single-test race measurements (excluding build): CDC full pipeline
0.41s; TestInvalidTimestamp 1.60s; proxy handoff 0.23s. These are local
observations, not flaky timing assertions or a claim of a statistically
established speedup. Empty destination setup isolates the recovery
phase; it does not remove total DDL work or claim to optimize slow TN
commits. Cold-start DDL remains covered by other integration cases.

The broader statement “all three historical flakes are fixed and can
never hang” is **not supported**: matrixorigin#27809's missing-progress edge is
still unproven, and no change here repairs its unknown historical root
cause. Keep that issue open. A bounded diagnostic join also is not a
proof that arbitrary future production deadlocks can be interrupted by
Go contexts.

### matrixorigin#27809 follow-up: confirmed test defects, historical cause still
open

- A Go select can choose the deadline even when the successful Lock
result is already buffered. The test now does one nonblocking result
recheck on the deadline path. A completed result wins; an actual Lock
error is preserved, and an expired context without a result still fails
immediately. There is no additional waiting or retry-to-pass. This
establishes completion, not a strict wall-clock latency SLA.
- Final shared-lock release and exclusive-lock cleanup now each use
their own 5s context instead of reusing setup's aging 5s context. The
exclusive acquisition retains its original 30s budget, including the
release phase; these contexts do not restart or extend that budget.
- Seven no-sleep unit cases cover success, actual error, both-ready
success/error, deadline without result, and closed-without-result
with/without an expired deadline. Unexpected channel closure cannot
masquerade as successful acquisition.
- Code tracing and temporary controlled experiments exercised
notification before waiting and delayed progress after notification.
Both progressed; no missing notification, abandoned representative or
lock cycle was demonstrated. Temporary diagnostic experiments are not
shipped. These findings do **not** establish which edge stalled in the
historical Linux coverage runs, and matrixorigin#27809 must remain open.
- Scope remains test-only: no production lock protocol, retry policy or
runtime hot-path cost changes. Actual acquisition errors still trigger
bounded failure diagnostics and fail the test.

Validation of this final follow-up source (macOS arm64, same native
wrapper): exact handoff + result-arbitration tests `-race -short
-count=100 -timeout=120s` PASS (26.089s); the same selection `-cover
-short -count=50 -timeout=120s` PASS (13.029s); owning
`./pkg/lockservice` package `-short -count=1 -timeout=240s` PASS
(89.516s). All seven result-arbitration cases executed. `gofmt` and `git
diff --check` passed. Prior CDC/ISCP evidence is reused because this
follow-up changes only the proxy test file. These passes are validation
of the delivered changes, not proof that the historical Linux flake
cannot recur.

Follow-up validation on the delivered source: CDC owning package normal
PASS (12.618s, previous delivery 12.725s) and race PASS (14.496s); exact
full-pipeline test race x73 PASS; exact invalid-timestamp test race x19
PASS; exact proxy-handoff test race x100 PASS. Repetition counts follow
the measured test-body / 30s-budget rule. All commands terminated, and
the temporary negative-control mutation was removed before the final
tests and commit. Earlier circuit-breaker evidence is reused because its
code and dependency contract did not change. Linux CI remains separate
from these macOS results.

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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: TestTableChangeStream_FullPipeline_RandomDelaysAndErrors is flaky in CI

2 participants