Skip to content

Commit 9194c37

Browse files
author
Codex
committed
fix(client): tighten slow-link probe extension and keep refocus retries
Pings now run every 3 seconds, so a working idle link always delivers a frame inside the 6 second quick probe window. A probe that a retry shortened now extends by the retry's window, not the original one. A mobile refocus without a background visit sends application-refocused, which restarts the retry ladder and checks for a better route but does not probe the live session. Adds a test of the read counter against real pongs.
1 parent 9c4af95 commit 9194c37

23 files changed

Lines changed: 157 additions & 52 deletions

‎apps/mobile/src/connection/app-state-wakeups.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import {
66
} from "./app-state-wakeups";
77

88
describe("mobileApplicationActiveWakeup", () => {
9-
it("skips the check when the app never left the foreground", () => {
10-
expect(mobileApplicationActiveWakeup(null, 20_000)).toBeNull();
9+
it("skips the probe when the app never left the foreground", () => {
10+
expect(mobileApplicationActiveWakeup(null, 20_000)).toBe("application-refocused");
1111
});
1212

1313
it("uses a fast probe after a short background visit", () => {

‎apps/mobile/src/connection/app-state-wakeups.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,19 @@ export const MOBILE_BACKGROUND_RECONNECT_AFTER_MS = 10_000;
44

55
export type MobileApplicationActiveWakeup = Extract<
66
Wakeups.ConnectionWakeup,
7-
"application-active-probe" | "application-active-reconnect"
7+
"application-active-probe" | "application-active-reconnect" | "application-refocused"
88
>;
99

1010
/**
1111
* The wakeup for returning to the foreground. Without a background visit the
1212
* app only went inactive, such as for Control Center or Face ID, and its
13-
* socket was never suspended, so there is nothing to check.
13+
* socket was never suspended, so it skips the probe.
1414
*/
1515
export function mobileApplicationActiveWakeup(
1616
backgroundedAtMs: number | null,
1717
activeAtMs: number,
18-
): MobileApplicationActiveWakeup | null {
19-
if (backgroundedAtMs === null) return null;
18+
): MobileApplicationActiveWakeup {
19+
if (backgroundedAtMs === null) return "application-refocused";
2020
return activeAtMs - backgroundedAtMs >= MOBILE_BACKGROUND_RECONNECT_AFTER_MS
2121
? "application-active-reconnect"
2222
: "application-active-probe";

‎apps/mobile/src/connection/platform.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ import { appAtomRegistry } from "../state/atom-registry";
2727
import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal";
2828
import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts";
2929
import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error";
30-
import { mobileApplicationActiveWakeup } from "./app-state-wakeups";
30+
import {
31+
mobileApplicationActiveWakeup,
32+
type MobileApplicationActiveWakeup,
33+
} from "./app-state-wakeups";
3134
import * as ConnectionStorage from "./storage";
3235

3336
function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" {
@@ -124,7 +127,7 @@ const networkPathChanges = Stream.callback<"network-changed">((queue) =>
124127
const layerWakeups = Wakeups.layer({
125128
changes: Stream.mergeAll(
126129
[
127-
Stream.callback<"application-active-probe" | "application-active-reconnect">((queue) =>
130+
Stream.callback<MobileApplicationActiveWakeup>((queue) =>
128131
Effect.acquireRelease(
129132
Effect.sync(() => {
130133
let backgroundedAtMs = AppState.currentState === "background" ? Date.now() : null;
@@ -134,8 +137,10 @@ const layerWakeups = Wakeups.layer({
134137
return;
135138
}
136139
if (state === "active") {
137-
const wakeup = mobileApplicationActiveWakeup(backgroundedAtMs, Date.now());
138-
if (wakeup !== null) Queue.offerUnsafe(queue, wakeup);
140+
Queue.offerUnsafe(
141+
queue,
142+
mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()),
143+
);
139144
backgroundedAtMs = null;
140145
}
141146
});

‎apps/web/src/cloud/linkEnvironment.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ function layerRegistry(options?: {
9191
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
9292
ready: Effect.void,
9393
probe: Effect.void,
94-
receivedFrames: Effect.succeed(0),
94+
receivedReads: Effect.succeed(0),
9595
closed: Effect.never,
9696
};
9797
const target = new PrimaryConnectionTarget({

‎packages/client-runtime/src/connection/registry.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
420420
Stream.die(new Error("Config is not used by registry tests.")),
421421
ready: Effect.void,
422422
probe: Effect.void,
423-
receivedFrames: Effect.succeed(0),
423+
receivedReads: Effect.succeed(0),
424424
closed: Deferred.await(closed),
425425
} satisfies RpcSession.RpcSession),
426426
() => Ref.update(releasedSessions, (count) => count + 1),

‎packages/client-runtime/src/connection/supervisor.test.ts‎

Lines changed: 69 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
157157
) => Effect.Effect<PreparedConnection, ConnectionAttemptError>;
158158
readonly ready?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
159159
readonly probe?: (attempt: number) => Effect.Effect<void, ConnectionAttemptError>;
160-
readonly receivedFrames?: Effect.Effect<number>;
160+
readonly receivedReads?: Effect.Effect<number>;
161161
readonly initialConfig?: (attempt: number) => Effect.Effect<ServerConfig, ConnectionAttemptError>;
162162
readonly checkRoute?: (route: ConnectionRoute) => Effect.Effect<ConnectionDriver.RouteCheck>;
163163
}) {
@@ -214,7 +214,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
214214
subscribeServerConfig: (input) => TEST_RPC_CLIENT.subscribeServerConfig(input),
215215
ready: options?.ready?.(attempt) ?? Effect.void,
216216
probe: options?.probe?.(attempt) ?? Effect.void,
217-
receivedFrames: options?.receivedFrames ?? Effect.succeed(0),
217+
receivedReads: options?.receivedReads ?? Effect.succeed(0),
218218
closed: Deferred.await(closed),
219219
} satisfies RpcSession.RpcSession),
220220
() => Ref.update(releaseCount, (count) => count + 1),
@@ -628,6 +628,42 @@ describe("EnvironmentSupervisor", () => {
628628
}),
629629
);
630630

631+
it.effect("a mobile refocus restarts the retry ladder but never probes a live session", () =>
632+
Effect.gen(function* () {
633+
const probeCount = yield* Ref.make(0);
634+
const harness = yield* makeHarness({
635+
prepare: (attempt) =>
636+
attempt <= 2 ? Effect.fail(transient()) : Effect.succeed(PREPARED_CONNECTION),
637+
probe: () => Ref.update(probeCount, (count) => count + 1),
638+
});
639+
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
640+
initiallyDesired: true,
641+
}).pipe(Effect.provide(harness.dependencies));
642+
643+
yield* awaitState(
644+
supervisor.state,
645+
(state) => state.phase === "backoff" && state.attempt === 1,
646+
);
647+
yield* TestClock.adjust("3 seconds");
648+
yield* eventuallyState(
649+
supervisor.state,
650+
(state) => state.phase === "backoff" && state.attempt === 2,
651+
);
652+
yield* harness.wake("application-refocused");
653+
yield* eventuallyState(
654+
supervisor.state,
655+
(state) => state.phase === "connected" && state.attempt === 1,
656+
);
657+
658+
yield* harness.wake("application-refocused");
659+
for (let attempt = 0; attempt < 100; attempt += 1) {
660+
yield* Effect.yieldNow;
661+
}
662+
expect(yield* Ref.get(probeCount)).toBe(0);
663+
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
664+
}).pipe(Effect.provide(TestClock.layer())),
665+
);
666+
631667
it.effect("explicit retry starts a fresh backoff sequence", () =>
632668
Effect.gen(function* () {
633669
const harness = yield* makeHarness({
@@ -1328,6 +1364,35 @@ describe("EnvironmentSupervisor", () => {
13281364
}).pipe(Effect.provide(TestClock.layer())),
13291365
);
13301366

1367+
it.effect("extends a retry-shortened probe by the retry's window when data arrives", () =>
1368+
Effect.gen(function* () {
1369+
const frames = yield* Ref.make(0);
1370+
const harness = yield* makeHarness({
1371+
probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1372+
receivedReads: Ref.get(frames),
1373+
});
1374+
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
1375+
initiallyDesired: true,
1376+
}).pipe(Effect.provide(harness.dependencies));
1377+
1378+
yield* awaitState(supervisor.state, (state) => state.phase === "connected");
1379+
yield* harness.wake("application-active");
1380+
yield* TestClock.adjust("1 second");
1381+
yield* supervisor.retryNow;
1382+
yield* TestClock.adjust("1 second");
1383+
yield* Ref.set(frames, 1);
1384+
// The retry's deadline lands at 7 seconds and the data extends it by the
1385+
// retry's 6 seconds to 13, not by the original 15.
1386+
yield* TestClock.adjust("10999 millis");
1387+
expect(yield* Ref.get(harness.sessionCount)).toBe(1);
1388+
yield* TestClock.adjust("1 milli");
1389+
yield* awaitState(
1390+
supervisor.state,
1391+
(state) => state.phase === "connected" && state.generation === 2,
1392+
);
1393+
}).pipe(Effect.provide(TestClock.layer())),
1394+
);
1395+
13311396
it.effect("quickly times out a stalled mobile foreground liveness probe", () =>
13321397
Effect.gen(function* () {
13331398
const harness = yield* makeHarness({
@@ -1356,7 +1421,7 @@ describe("EnvironmentSupervisor", () => {
13561421
const frames = yield* Ref.make(0);
13571422
const harness = yield* makeHarness({
13581423
probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1359-
receivedFrames: Ref.get(frames),
1424+
receivedReads: Ref.get(frames),
13601425
});
13611426
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
13621427
initiallyDesired: true,
@@ -1387,7 +1452,7 @@ describe("EnvironmentSupervisor", () => {
13871452
const frames = yield* Ref.make(0);
13881453
const harness = yield* makeHarness({
13891454
probe: (attempt) => (attempt === 1 ? Effect.never : Effect.void),
1390-
receivedFrames: Ref.get(frames),
1455+
receivedReads: Ref.get(frames),
13911456
});
13921457
const supervisor = yield* EnvironmentSupervisor.make(TARGET_ENTRY, {
13931458
initiallyDesired: true,

‎packages/client-runtime/src/connection/supervisor.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,9 @@ const CONNECTION_PROBE_TIMEOUT = "15 seconds";
4545
// Mobile resumes, explicit retries, and offline events want a fast answer:
4646
// the user is waiting, or the network may be gone. It still has to cover a
4747
// lost packet and its retransmit on a 500ms round trip, or a slow link reads
48-
// as a dead socket and every resume tears down a working session.
48+
// as a dead socket and every resume tears down a working session. It must
49+
// stay longer than PING_INTERVAL plus a round trip, so a working link always
50+
// delivers a frame that extends it.
4951
const QUICK_CONNECTION_PROBE_TIMEOUT = "6 seconds";
5052
const BACKOFF_RESET_AFTER_MS = 30_000;
5153
// While connected over a fallback route, how often to look for a better one.
@@ -636,8 +638,9 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
636638
// Monotonic nanoseconds, so a wall-clock correction cannot move the deadline.
637639
const probeStartedAt = yield* Clock.monotonicTimeNanos;
638640
const latestDeadline = probeStartedAt + Duration.toNanosUnsafe(CONNECTION_PROBE_TIMEOUT);
639-
let deadline = probeStartedAt + Duration.toNanosUnsafe(probeTimeout);
640-
let receivedFrames = yield* lease.session.receivedFrames;
641+
let window = probeTimeout;
642+
let deadline = probeStartedAt + Duration.toNanosUnsafe(window);
643+
let receivedReads = yield* lease.session.receivedReads;
641644
for (;;) {
642645
const remaining = deadline - (yield* Clock.monotonicTimeNanos);
643646
const probeEvent = yield* Effect.raceAllFirst([
@@ -653,11 +656,11 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
653656
// Data still arriving means a slow link, not a dead one: the answer
654657
// may be queued behind it. Wait another window, up to the full
655658
// probe timeout.
656-
const received = yield* lease.session.receivedFrames;
659+
const received = yield* lease.session.receivedReads;
657660
const now = yield* Clock.monotonicTimeNanos;
658-
if (received > receivedFrames && now < latestDeadline) {
659-
receivedFrames = received;
660-
const extended = now + Duration.toNanosUnsafe(probeTimeout);
661+
if (received > receivedReads && now < latestDeadline) {
662+
receivedReads = received;
663+
const extended = now + Duration.toNanosUnsafe(window);
661664
deadline = extended < latestDeadline ? extended : latestDeadline;
662665
continue;
663666
}
@@ -685,7 +688,10 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* (
685688
if (signalTimeout !== undefined) {
686689
const signalDeadline =
687690
(yield* Clock.monotonicTimeNanos) + Duration.toNanosUnsafe(signalTimeout);
688-
if (signalDeadline < deadline) deadline = signalDeadline;
691+
if (signalDeadline < deadline) {
692+
deadline = signalDeadline;
693+
window = signalTimeout;
694+
}
689695
}
690696
}
691697
}

‎packages/client-runtime/src/connection/wakeups.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ export type ConnectionWakeup =
66
| "application-active"
77
| "application-active-probe"
88
| "application-active-reconnect"
9+
// The app came back from a brief inactive state, such as Control Center or
10+
// Face ID, without being suspended. Its socket is fine, but a pending retry
11+
// should still run now.
12+
| "application-refocused"
913
| "credentials-changed"
1014
// The device moved to a different network (another Wi-Fi, Wi-Fi to
1115
// cellular) while staying online. Saved routes may have changed reach.
@@ -15,7 +19,8 @@ function isApplicationActiveWakeup(reason: ConnectionWakeup): boolean {
1519
return (
1620
reason === "application-active" ||
1721
reason === "application-active-probe" ||
18-
reason === "application-active-reconnect"
22+
reason === "application-active-reconnect" ||
23+
reason === "application-refocused"
1924
);
2025
}
2126

‎packages/client-runtime/src/operations/commands.performance.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ const makeSupervisor = Effect.fn("CommandPerformance.makeSupervisor")(function*
186186
subscribeServerConfig: (requestInput) => client.subscribeServerConfig(requestInput),
187187
ready: Effect.void,
188188
probe: Effect.void,
189-
receivedFrames: Effect.succeed(0),
189+
receivedReads: Effect.succeed(0),
190190
closed: Effect.never,
191191
};
192192
return EnvironmentSupervisor.EnvironmentSupervisor.of({

‎packages/client-runtime/src/operations/commands.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
135135
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
136136
ready: Effect.void,
137137
probe: Effect.void,
138-
receivedFrames: Effect.succeed(0),
138+
receivedReads: Effect.succeed(0),
139139
closed: Effect.never,
140140
};
141141
return EnvironmentSupervisor.EnvironmentSupervisor.of({

0 commit comments

Comments
 (0)