Skip to content

fix(atunnel): close both relay ends - #1101

Closed
NekoPunch (orangeCatDeveloper) wants to merge 1 commit into
agent-substrate:mainfrom
orangeCatDeveloper:fix/relay-ingress-cancel-race
Closed

NekoPunch (orangeCatDeveloper) wants to merge 1 commit into
agent-substrate:mainfrom
orangeCatDeveloper:fix/relay-ingress-cancel-race

Conversation

@orangeCatDeveloper

@orangeCatDeveloper NekoPunch (orangeCatDeveloper) commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1100

TestRelayIngressCancellationClosesBothSides fails on about 1% of -race runs, on branches unrelated to the relay.

Root cause

The test asserts a close that happens on a goroutine it never waits for.

relayIngressWithHalfClose closed both sides from a context.AfterFunc callback, which runs on its own goroutine. cancel() returning therefore says nothing about whether the streams are closed — and the test asserted right after it.

The client side is an unbuffered io.Pipe, where a Write cannot complete on its own; it needs someone on the other end. Two goroutines can be that someone:

Whichever gets there first Outcome
the AfterFunc callback closes the pipe Write fails → test passes
the relay's io.Copy, still parked in Read it takes the bytes, Write returns nil → test fails

The scheduler picks the winner, so the test is a coin flip. -race widens the window by two orders of magnitude — 1 failure per 10000 plain, 89 with -race — and CI runs go test -race -v ./....

The actor.Read assertion just above races the same close, but carries a one-second deadline and so almost always wins. The Write has no such slack, which is why the failure is always line 123.

Fix

Production. Close both sides in the ctx.Done() branch the relay loop already selects on, rather than from a detached goroutine. This turns

both sides are eventually closed

into

both sides are closed before this returns

which is what a caller can build on, and it drops a goroutine plus its stop() bookkeeping.

Test. Wait for the relay to return, then assert. The SetReadDeadline error check goes with it: once the relay has closed the pipe, setting a deadline on it fails by design, and the deadline was only ever a guard against hanging if the connection had been left open.

Nothing changes about the bytes the relay moves — this is a shutdown-ordering fix, not a data-plane one.

Before / after

$ go test ./internal/atunnel/ -race -run TestRelayIngressCancellationClosesBothSides -count=10000
--- FAIL: TestRelayIngressCancellationClosesBothSides (0.00s)
    ingress_test.go:123: client stream remained open after relay cancellation
... 89 of 10000 iterations
FAIL	github.com/agent-substrate/substrate/internal/atunnel

$ go test ./internal/atunnel/ -race -run TestRelayIngressCancellationClosesBothSides -count=10000
ok  	github.com/agent-substrate/substrate/internal/atunnel	3.035s

Linux/x86_64, 4 cores, matching CI. On darwin/arm64 the same runs give 202 failures before and 0 after.

  • Tests pass
  • Appropriate changes to documentation are included in the PR

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.

Thanks for the fit

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.

Verified the analysis and the fix.

  • The race is exactly as described: the context.AfterFunc closes ran on a detached goroutine, so cancel() returning guaranteed nothing about stream state, and the unbuffered io.Pipe write in the test raced the relay's io.Copy against the close. Moving the closes into the ctx.Done() branch of the relay loop makes "both sides closed before return" an actual postcondition, and the copy goroutines are still unblocked by those same closes (the done channel is buffered, so no leak).
  • Behavior on the normal completion path is unchanged — the relay still doesn't close either side when both copies finish, same as before with defer stop().
  • Ran go test -race ./internal/atunnel/ -run TestRelayIngressCancellationClosesBothSides -count=5000 locally (darwin/arm64): green. Also green with this branch merged into current main, -race -count=50 over the relay/serve tests.

LGTM.

Aditya Shantanu (aditya-shantanu) added a commit to aditya-shantanu/substrate that referenced this pull request Aug 24, 2026
Adopted from agent-substrate#1101 by @orangeCatDeveloper to unblock CI velocity.
Fixes TestRelayIngressCancellationClosesBothSides (agent-substrate#1100): the close
ran on a context.AfterFunc goroutine the test never waited for.

Co-authored-by: NekoPunch <[email protected]>
@aditya-shantanu

Copy link
Copy Markdown
Collaborator

Heads-up: adopted this fix (unchanged, with Co-authored-by credit) into the consolidated flake-fix PR #1160 to get CI green faster. If maintainers prefer landing this PR individually, #1160 can drop the commit or be closed — whatever lands first wins.

Cancellation closed streams asynchronously, so callers could observe relay completion before shutdown finished. Close both ends before returning to make completion deterministic.
@orangeCatDeveloper NekoPunch (orangeCatDeveloper) changed the title atunnel: close the relay's both ends before returning fix(atunnel): close both relay ends Aug 25, 2026
Yufan Su (yufan-su) pushed a commit that referenced this pull request Aug 25, 2026
…relay) (#1160)

Fixes #675, fixes #1100, fixes #1146; addresses the CI flake in #1106.

## Why this PR

Flaky tests are the single biggest drag on this repo's velocity right
now: the three flakes fixed here account for the majority of red CI runs
over the last 7 days (identity: 35 failures, parking: 32, relay: 9 —
from the flake dashboard's cross-PR analysis of ~630 runs). Every red
run costs a contributor a rebase-and-rerun cycle and costs reviewers
signal. **This PR consolidates the three root-caused, in-flight fixes
into one change to get CI green now and unblock the community — the goal
is velocity, not authorship.**

## Credit where it's due

All three fixes were root-caused and written by others; this PR adopts
them onto latest main with their tests, unchanged in substance. Each
commit carries a `Co-authored-by` trailer:

| Commit | Original PR | Author | Root cause |
|---|---|---|---|
| e2e: give each probe fixture its own worker pool | #1147 |
@orangeCatDeveloper | identity/egressmitm/imagevolume suites share one
`workload: probe` pool label; cross-suite selection under concurrent
suite processes dials workers that are not there |
| atenet: never cancel an in-flight resume at the park budget | #991 |
@omeryahud | the park budget doubled as the ResumeActor RPC deadline; a
mid-restore cancel strands a RESUMING actor on a live worker |
| atunnel: close the relay's both ends before returning | #1101 |
@orangeCatDeveloper | the relay closed both ends from a
`context.AfterFunc` goroutine the test never waits for |

@Stevenjin8's #1107 correctly diagnosed the ateom readiness race in
#1106; the control-plane readiness gap it targets remains real and open
— this PR only removes the e2e-fixture contention that makes it fire
constantly in CI.

If maintainers prefer to land the original PRs individually instead,
closing this one is completely fine — the point is that the fixes land
somewhere, soon.

## Evidence the flakes are actually fixed

**TestRelayIngressCancellationClosesBothSides (unit, `-race`):**
- Unpatched main, `-count=3000`: **83 failures (2.8%)** — matches the
2.9% observed across 308 CI runs this week
- This branch, `-count=10000`: **0 failures**

**TestRequestParking (park-budget cancellation):**
- The new `InFlightAttemptRunsToCompletion` and
`LateRetryableErrorIsBudgetExhaustion` unit tests (from #991) encode the
exact failure mode from #675 and pass under `go test -race -count=100
./cmd/atenet/internal/router/ingress/`
- The pre-fix behavior (budget cancelling the in-flight RPC) is
deterministically reproduced by the old test it replaces

**TestActorIdentity_AfterRestore_IsOwnID_NotGolden (probe pool
isolation):**
- Not reproducible outside CI (needs concurrent suite processes on a
contended kind node), so verified statically: `${FIXTURE_SUFFIX}` is
always `-<suite>` (internal/e2e/sandbox.go:189,201 — never empty),
`probe-sized` already uses its own label, and no other manifest or
selector references `workload: probe`. #1147's CI data shows all three
failure signatures (missing `ateom.sock`, `runsc restore` killed, router
502/503) trace to cross-suite pool sharing; per-suite labels make the
selector suite-local by construction
- The definitive check is this PR's own CI plus the flake dashboard's
7-day window after merge — I will report the post-merge rates on #1106

Also run: `go build ./...`, `go vet` and the full `-race` suites of both
touched packages — all green.

## What this PR deliberately does NOT fix

`TestActorEgressHTTPS` (#1050, 4.6% this week, below the 5% flake
threshold) has no root-caused fix yet — the 503 `upstream connect error`
path needs investigation in a live cluster. #1103 (@orangeCatDeveloper)
tightens the related `TestActorArbitraryPortAccess` assertion so those
503s stop passing silently; it should land after #1050's cause is fixed,
or it converts hidden flakiness into visible red.


## Update (post-CI investigation)

The first e2e runs failed on `TestRequestParking/ParkThenServed`
(micro-VM lane). Investigation showed this is the **pre-existing
dominant mode** of #675 — identical failures in main-era runs
32305728993 / 32397291519 / 32487958077 — not a regression: on micro-VM,
`SuspendActor` returns before the snapshot upload completes, so the
worker legitimately isn't free within the 5s park budget and the
router's 503 is correct behavior. #991 fixes the *other* (mid-restore
cancellation/stranding) mode. Commit d637690 makes the subtest retry
while the worker is still freeing; a stranded worker still fails every
attempt, so the regression stays pinned.

**Additional validation:**
- CI e2e-test now **passes both lanes** (run 32754691017)
- Local kind cluster built from this branch: parking suite **10/10
consecutive passes**; identity + egressmitm + imagevolume run
**concurrently** (the exact contention behind the identity flake) × 3
iterations — **9/9 suite passes**

---------

Co-authored-by: Aditya Shantanu <[email protected]>
Co-authored-by: NekoPunch <[email protected]>
Co-authored-by: Omer Yahud <[email protected]>
@orangeCatDeveloper
NekoPunch (orangeCatDeveloper) deleted the fix/relay-ingress-cancel-race branch August 25, 2026 18:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

E2E test flake: TestRelayIngressCancellationClosesBothSides

3 participants