From 7f1b988f9c22ce96897845edb1508a462ae054a9 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:08:21 -0800 Subject: [PATCH 1/8] feat(scripts): server metrics attach real clients and time a reconnect storm Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 15 +++ scripts/server-metrics.ts | 157 ++++++++++++++++++++++++++++++- 2 files changed, 171 insertions(+), 1 deletion(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 3ccd4235244b5..342fff2b26c21 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -48,6 +48,20 @@ export const Measured = Schema.Struct({ scaling: Schema.optional(Scaling), streaming: Schema.optional(Window), soak: Schema.optional(Soak), + /** One web-like client attached over the WebSocket RPC, with N threads subscribed. */ + clients: Schema.optional( + Schema.Struct({ + /** The quiet window by subscribed thread count. */ + attached: Schema.Record(Schema.String, Window), + /** Every client drops and reconnects at once. */ + storm: Schema.Struct({ + clients: Schema.Number, + resubscribedMs: Schema.Number, + loopDelayP99Ms: Schema.Number, + loopDelayMaxMs: Schema.Number, + }), + }), + ), /** A server on a copy of the developer's real database, its projects backed by clones. */ busy: Schema.optional( Schema.Struct({ @@ -232,6 +246,7 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre metric.endsWith("loopSamples") || metric === "busy.projects" || metric === "busy.ballastMB" || + metric === "clients.storm.clients" || metric.startsWith("scaling.points") ) { continue; diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 78e7dd87654e1..793b5b2c47542 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -18,6 +18,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; +import * as Exit from "effect/Exit"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -32,7 +33,10 @@ import * as Stream from "effect/Stream"; import { Argument, Command, Flag } from "effect/cli"; import { ORCHESTRATION_PROTOCOL_HEADER, + ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_VERSION_TEXT, + ThreadId, + WsRpcGroup, } from "@t3tools/contracts"; import { HttpClient, @@ -42,6 +46,8 @@ import { HttpServerResponse, } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import * as Scope from "effect/Scope"; import * as Socket from "effect/socket/Socket"; import { run } from "./scenarios/shell.ts"; @@ -70,6 +76,8 @@ import { const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)); const MODEL = "claude-haiku-4-5"; const SLOW_MARKER = "[[stream-slowly]]"; +/** Clients that drop and reconnect at once in the clients scenario. */ +const STORM_CLIENTS = 20; /** Event-loop delay sampling interval; each sample wakes the loop once. */ const LOOP_RESOLUTION_MS = 10; const LoopStats = Schema.Struct({ @@ -906,6 +914,9 @@ const startServer = Effect.fn("serverMetrics.startServer")(function* ( profile: devtools.profile, snapshot: devtools.snapshot, heapAfterGc: devtools.heapAfterGc, + loopStart: devtools.loopStart, + loopRead: devtools.loopRead, + project, ballast: devtools.ballast, issueToken: cli(["auth", "session", "issue", "--token-only"]).pipe( Effect.map(({ stdout }) => stdout.trim()), @@ -1042,7 +1053,95 @@ const gitTraffic = Effect.fn("serverMetrics.gitTraffic")(function* (server: Serv }); }); -const SCENARIOS = ["startup", "rest", "firstWord", "quiet", "streaming", "busy"] as const; +/** + * One client over the real WebSocket RPC, signed in like a paired device, holding the + * subscriptions a web client opens: the shell, VCS status of the project, and the given threads. + * Succeeds once every subscription has delivered its snapshot. + */ +const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( + server: Server, + token: string, + threadIds: ReadonlyArray, +) { + const http = yield* HttpClient.HttpClient; + const ticketResponse = yield* http.execute( + HttpClientRequest.post(`${server.origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(token), + ), + ); + const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))( + yield* ticketResponse.text, + ); + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${server.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + ), + ); + const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); + const ready = Effect.fn("serverMetrics.subscription")(function* ( + stream: Stream.Stream, + isReady: (item: A) => boolean, + ) { + const synchronized = yield* Deferred.make(); + yield* stream.pipe( + Stream.runForEach((item) => + isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void, + ), + Effect.catchCause(() => + Deferred.fail(synchronized, new MetricsError({ message: "a subscription failed" })), + ), + Effect.forkScoped, + ); + return Deferred.await(synchronized); + }); + const synchronized = (item: { readonly kind: string }) => item.kind === "synchronized"; + const waits = [ + yield* ready( + client["orchestration.subscribeShell"]({ + requestCompletionMarker: true, + omitIdleSubagents: true, + omitOlderSettled: true, + }), + synchronized, + ), + yield* ready(client.subscribeVcsStatus({ cwd: server.project }), () => true), + ...(yield* Effect.forEach(threadIds, (threadId) => + ready( + client["orchestration.subscribeThread"]({ + threadId: ThreadId.make(threadId), + requestCompletionMarker: true, + acceptBoundedSnapshot: true, + acceptDeferredWork: true, + acceptCompactTurnItems: true, + acceptCompactIds: true, + acceptDedupedBodies: true, + }), + synchronized, + ), + )), + ]; + yield* Effect.all(waits, { concurrency: "unbounded", discard: true }).pipe( + Effect.timeoutOrElse({ + duration: Duration.seconds(60), + orElse: () => new MetricsError({ message: "a subscription never synchronized" }), + }), + ); +}); + +const SCENARIOS = [ + "startup", + "rest", + "firstWord", + "quiet", + "streaming", + "clients", + "busy", +] as const; /** Scenarios that read the developer's real database, so they run only when named. */ const OPT_IN_SCENARIOS: ReadonlyArray = ["busy"]; @@ -1154,6 +1253,62 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + if (wanted("clients")) { + yield* withServer("clients", (server) => + Effect.gen(function* () { + const token = yield* server.issueToken; + const most = Math.max(STORM_CLIENTS, ...options.threads); + const threads = yield* openThreads(server, 0, most); + const attached: Record = {}; + for (const count of options.threads) { + yield* Effect.scoped( + Effect.gen(function* () { + yield* attachClient(server, token, threads.slice(0, count)); + yield* Effect.sleep(Duration.seconds(10)); + attached[`${count}`] = yield* server.measure(30); + }), + ); + } + // Every client holds the shell, VCS status and one thread, then all drop and come back. + const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => Scope.make()); + const attachAll = Effect.forEach( + clients, + (scope, index) => + attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), + { concurrency: "unbounded", discard: true }, + ); + yield* attachAll; + yield* Effect.sleep(Duration.seconds(10)); + yield* server.loopStart; + const dropped = yield* nowMs; + yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { + concurrency: "unbounded", + discard: true, + }); + const reopened = yield* Effect.forEach(clients, () => Scope.make()); + yield* Effect.forEach( + reopened, + (scope, index) => + attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), + { concurrency: "unbounded", discard: true }, + ); + const resubscribedMs = Math.round((yield* nowMs) - dropped); + const loop = yield* server.loopRead; + yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { + discard: true, + }); + measured.clients = { + attached, + storm: { + clients: STORM_CLIENTS, + resubscribedMs, + loopDelayP99Ms: round(loop.p99), + loopDelayMaxMs: round(loop.max), + }, + }; + }), + ); + } if (wanted("streaming")) { yield* withServer("streaming", (server) => Effect.gen(function* () { From 0887eb64a684b802395b287581be52a6ebcd955d Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:53:14 -0800 Subject: [PATCH 2/8] fix(scripts): server metrics close storm clients on every exit path Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 793b5b2c47542..982c14637f7be 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1269,8 +1269,13 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption }), ); } + // Each client gets its own scope so the storm can drop them on cue; the server's scope + // still closes any left open when a step fails or is interrupted. + const clientScope = Effect.acquireRelease(Scope.make(), (scope, exit) => + Scope.close(scope, exit), + ); // Every client holds the shell, VCS status and one thread, then all drop and come back. - const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => Scope.make()); + const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => clientScope); const attachAll = Effect.forEach( clients, (scope, index) => @@ -1285,7 +1290,7 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption concurrency: "unbounded", discard: true, }); - const reopened = yield* Effect.forEach(clients, () => Scope.make()); + const reopened = yield* Effect.forEach(clients, () => clientScope); yield* Effect.forEach( reopened, (scope, index) => From cec087a59ae0cdf7f9a57144749e313e30360c65 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:09:31 -0800 Subject: [PATCH 3/8] fix(scripts): attached clients report activity like the web client and surface lost subscriptions Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 54 ++++++++++++++++++++++++++++++++------- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 982c14637f7be..cdfe45e868a2f 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1083,22 +1083,50 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ), ); const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); + // A subscription that fails or ends after its snapshot leaves the window measuring less than a + // client costs, so the first such loss is kept for `healthy` to report. + const lost = yield* Ref.make(undefined); const ready = Effect.fn("serverMetrics.subscription")(function* ( stream: Stream.Stream, isReady: (item: A) => boolean, ) { const synchronized = yield* Deferred.make(); + const lose = (message: string) => + Ref.update(lost, (first) => first ?? message).pipe( + Effect.andThen(Deferred.fail(synchronized, new MetricsError({ message }))), + ); yield* stream.pipe( Stream.runForEach((item) => isReady(item) ? Deferred.succeed(synchronized, undefined) : Effect.void, ), - Effect.catchCause(() => - Deferred.fail(synchronized, new MetricsError({ message: "a subscription failed" })), - ), + Effect.andThen(lose("a subscription ended")), + Effect.catchCause(() => lose("a subscription failed")), Effect.forkScoped, ); return Deferred.await(synchronized); }); + // Reports presence the way the web client does, so work held for an active client runs. + const clientId = `bench-${yield* Random.nextIntBetween(0, 1_000_000_000)}`; + const report = Effect.gen(function* () { + yield* client["server.reportClientActivity"]({ + clientId, + clientKind: "web", + visible: true, + focused: true, + recentlyInteracted: true, + appState: "active", + scopes: [{ type: "provider-status" }, { type: "vcs-status", cwd: server.project }], + ttlMs: 45_000, + observedAt: yield* DateTime.now, + }); + }); + yield* report; + yield* report.pipe( + Effect.delay(Duration.seconds(25)), + Effect.forever, + Effect.catchCause(() => Ref.update(lost, (first) => first ?? "an activity report failed")), + Effect.forkScoped, + ); const synchronized = (item: { readonly kind: string }) => item.kind === "synchronized"; const waits = [ yield* ready( @@ -1131,6 +1159,12 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( orElse: () => new MetricsError({ message: "a subscription never synchronized" }), }), ); + return { + /** Fails if any of this client's subscriptions or reports was lost since it attached. */ + healthy: Effect.flatMap(Ref.get(lost), (message) => + message === undefined ? Effect.void : Effect.fail(new MetricsError({ message })), + ), + }; }); const SCENARIOS = [ @@ -1263,9 +1297,10 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption for (const count of options.threads) { yield* Effect.scoped( Effect.gen(function* () { - yield* attachClient(server, token, threads.slice(0, count)); + const client = yield* attachClient(server, token, threads.slice(0, count)); yield* Effect.sleep(Duration.seconds(10)); attached[`${count}`] = yield* server.measure(30); + yield* client.healthy; }), ); } @@ -1276,14 +1311,14 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption ); // Every client holds the shell, VCS status and one thread, then all drop and come back. const clients = yield* Effect.forEach(threads.slice(0, STORM_CLIENTS), () => clientScope); - const attachAll = Effect.forEach( + const first = yield* Effect.forEach( clients, (scope, index) => attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded", discard: true }, + { concurrency: "unbounded" }, ); - yield* attachAll; yield* Effect.sleep(Duration.seconds(10)); + yield* Effect.forEach(first, (client) => client.healthy, { discard: true }); yield* server.loopStart; const dropped = yield* nowMs; yield* Effect.forEach(clients, (scope) => Scope.close(scope, Exit.void), { @@ -1291,14 +1326,15 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption discard: true, }); const reopened = yield* Effect.forEach(clients, () => clientScope); - yield* Effect.forEach( + const second = yield* Effect.forEach( reopened, (scope, index) => attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), - { concurrency: "unbounded", discard: true }, + { concurrency: "unbounded" }, ); const resubscribedMs = Math.round((yield* nowMs) - dropped); const loop = yield* server.loopRead; + yield* Effect.forEach(second, (client) => client.healthy, { discard: true }); yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { discard: true, }); From a493c3fc168be4a017ff7339dbc990d0ecb4f505 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:50:10 -0800 Subject: [PATCH 4/8] fix(scripts): client activity reports time out, and the storm checks both cohorts after the drop Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index cdfe45e868a2f..7f1dfd9a7a865 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1119,7 +1119,13 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( ttlMs: 45_000, observedAt: yield* DateTime.now, }); - }); + }).pipe( + // A server that keeps the socket open but never answers would otherwise hang the scenario. + Effect.timeoutOrElse({ + duration: Duration.seconds(15), + orElse: () => new MetricsError({ message: "an activity report got no answer" }), + }), + ); yield* report; yield* report.pipe( Effect.delay(Duration.seconds(25)), @@ -1334,7 +1340,8 @@ const runOnce = Effect.fn("serverMetrics.runOnce")(function* (options: RunOption ); const resubscribedMs = Math.round((yield* nowMs) - dropped); const loop = yield* server.loopRead; - yield* Effect.forEach(second, (client) => client.healthy, { discard: true }); + // The first cohort again: a loss between its check and the drop happened in the storm. + yield* Effect.forEach([...first, ...second], (client) => client.healthy, { discard: true }); yield* Effect.forEach(reopened, (scope) => Scope.close(scope, Exit.void), { discard: true, }); From 135fdf289d28bd643ad3740452b5c9c86af8d292 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:24:18 -0800 Subject: [PATCH 5/8] fix(scripts): attached clients time out on the ticket and renew activity from each send Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 7f1dfd9a7a865..82c7f2acef6a5 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1064,14 +1064,21 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( threadIds: ReadonlyArray, ) { const http = yield* HttpClient.HttpClient; - const ticketResponse = yield* http.execute( - HttpClientRequest.post(`${server.origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(token), - ), - ); - const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))( - yield* ticketResponse.text, - ); + // Headers alone do not finish a request; the deadline covers the body too. + const ticketBody = yield* http + .execute( + HttpClientRequest.post(`${server.origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(token), + ), + ) + .pipe( + Effect.flatMap((response) => response.text), + Effect.timeoutOrElse({ + duration: Duration.seconds(15), + orElse: () => new MetricsError({ message: "the WebSocket ticket never arrived" }), + }), + ); + const { ticket } = yield* decodeJson(Schema.Struct({ ticket: Schema.String }))(ticketBody); const protocol = yield* Layer.build( RpcClient.layerProtocolSocket().pipe( Layer.provide( @@ -1127,9 +1134,11 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( }), ); yield* report; + // Renewals start every 25 s from the previous send, not its reply, so with the 15 s deadline + // each lands well inside the 45 s lease. yield* report.pipe( + Effect.repeat(Schedule.fixed(Duration.seconds(25))), Effect.delay(Duration.seconds(25)), - Effect.forever, Effect.catchCause(() => Ref.update(lost, (first) => first ?? "an activity report failed")), Effect.forkScoped, ); From 8e8effdb04cdf7c9196f05d183b83d53e156e426 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:47:45 -0800 Subject: [PATCH 6/8] fix(scripts): the first activity renewal counts from the first send Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 82c7f2acef6a5..15d74a2ad4503 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -1133,12 +1133,13 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( orElse: () => new MetricsError({ message: "an activity report got no answer" }), }), ); + const firstSent = yield* nowMs; yield* report; // Renewals start every 25 s from the previous send, not its reply, so with the 15 s deadline - // each lands well inside the 45 s lease. - yield* report.pipe( - Effect.repeat(Schedule.fixed(Duration.seconds(25))), - Effect.delay(Duration.seconds(25)), + // each lands well inside the 45 s lease. The first one counts from the first send too. + yield* nowMs.pipe( + Effect.flatMap((now) => Effect.sleep(Duration.millis(Math.max(0, 25_000 - (now - firstSent))))), + Effect.andThen(report.pipe(Effect.repeat(Schedule.fixed(Duration.seconds(25))))), Effect.catchCause(() => Ref.update(lost, (first) => first ?? "an activity report failed")), Effect.forkScoped, ); From 857c84e7e8c9a763d6417aff4686e8e0a194aac3 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:01:19 -0800 Subject: [PATCH 7/8] fix(scripts): activity renewals keep to 25 s from each send and fail past the lease's safe point Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 15 +++++++++++++++ scripts/server-metrics.test.ts | 11 +++++++++++ scripts/server-metrics.ts | 21 +++++++++++++++------ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 342fff2b26c21..4a14fc7d938fe 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -426,3 +426,18 @@ export function pathRewrites(from: string, to: string) { const pairs = new Map(spellings.map((spell) => [spell(from), spell(to)] as const)); return [...pairs]; } + +/** + * When the next activity report goes out, `intervalMs` after the previous send, and whether it + * starts too late to renew the lease that send took: past `latestMs`, a renewal can land after it + * lapsed. + */ +export function nextActivityReport( + lastSentAt: number, + now: number, + intervalMs = 25_000, + latestMs = 40_000, +) { + const due = lastSentAt + intervalMs; + return { waitMs: Math.max(0, due - now), late: Math.max(due, now) - lastSentAt > latestMs }; +} diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 8d4fe431fe7c7..62d8bacb40024 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, heapGrowth, + nextActivityReport, parsePsCpuTime, parseRunSelection, pathRewrites, @@ -304,3 +305,13 @@ describe("pathRewrites", () => { expect(rewrite(text, from, to)).toBe(expected); }); }); + +describe("nextActivityReport", () => { + it.each([ + ["before it is due: wait out the interval", 1_000, 10_000, { waitMs: 16_000, late: false }], + ["a slow reply: send now, still inside the lease", 1_000, 31_000, { waitMs: 0, late: false }], + ["past the safe point: the lease would lapse", 1_000, 42_000, { waitMs: 0, late: true }], + ])("%s", (_name, lastSentAt, now, expected) => { + expect(nextActivityReport(lastSentAt, now)).toEqual(expected); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 15d74a2ad4503..2388fc658f91e 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -62,6 +62,7 @@ import { ServerMetrics, slope, spread, + nextActivityReport, parsePsCpuTime, pathRewrites, pathSpellings, @@ -1133,13 +1134,21 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( orElse: () => new MetricsError({ message: "an activity report got no answer" }), }), ); - const firstSent = yield* nowMs; + let lastSent = yield* nowMs; yield* report; - // Renewals start every 25 s from the previous send, not its reply, so with the 15 s deadline - // each lands well inside the 45 s lease. The first one counts from the first send too. - yield* nowMs.pipe( - Effect.flatMap((now) => Effect.sleep(Duration.millis(Math.max(0, 25_000 - (now - firstSent))))), - Effect.andThen(report.pipe(Effect.repeat(Schedule.fixed(Duration.seconds(25))))), + // Each renewal goes out 25 s after the previous send, however long its reply took; one that + // would start past the lease's safe point marks the client lost instead. + yield* Effect.gen(function* () { + while (true) { + const next = nextActivityReport(lastSent, yield* nowMs); + if (next.late) { + return yield* new MetricsError({ message: "an activity renewal missed its lease" }); + } + yield* Effect.sleep(Duration.millis(next.waitMs)); + lastSent = yield* nowMs; + yield* report; + } + }).pipe( Effect.catchCause(() => Ref.update(lost, (first) => first ?? "an activity report failed")), Effect.forkScoped, ); From a14571064c916834409167f157d39b32d1884f12 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:13:53 -0800 Subject: [PATCH 8/8] fix(scripts): an activity renewal sent late or answered after the lease marks the client lost Co-Authored-By: Claude Opus 5.5 --- scripts/server-metrics-report.ts | 14 ++++++++++++++ scripts/server-metrics.test.ts | 11 +++++++++++ scripts/server-metrics.ts | 7 ++++++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 4a14fc7d938fe..6e03db8ff84a3 100644 --- a/scripts/server-metrics-report.ts +++ b/scripts/server-metrics-report.ts @@ -441,3 +441,17 @@ export function nextActivityReport( const due = lastSentAt + intervalMs; return { waitMs: Math.max(0, due - now), late: Math.max(due, now) - lastSentAt > latestMs }; } + +/** + * Whether a renewal let the previous send's lease lapse: it went out past `latestMs` after that + * send (a stalled loop wakes late), or its answer came after the lease (`leaseMs`) ran out. + */ +export function activityRenewalMissed( + previousSentAt: number, + sentAt: number, + repliedAt: number, + latestMs = 40_000, + leaseMs = 45_000, +) { + return sentAt - previousSentAt > latestMs || repliedAt - previousSentAt > leaseMs; +} diff --git a/scripts/server-metrics.test.ts b/scripts/server-metrics.test.ts index 62d8bacb40024..760c850dbbbea 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, + activityRenewalMissed, heapGrowth, nextActivityReport, parsePsCpuTime, @@ -315,3 +316,13 @@ describe("nextActivityReport", () => { expect(nextActivityReport(lastSentAt, now)).toEqual(expected); }); }); + +describe("activityRenewalMissed", () => { + it.each([ + ["sent on time, answered inside the lease", 25_000, 30_000, false], + ["a delayed wake: sent past the safe point", 41_000, 42_000, true], + ["sent on time, answered after the lease lapsed", 25_000, 46_000, true], + ])("%s", (_name, sentAt, repliedAt, missed) => { + expect(activityRenewalMissed(0, sentAt, repliedAt)).toBe(missed); + }); +}); diff --git a/scripts/server-metrics.ts b/scripts/server-metrics.ts index 2388fc658f91e..4f0b67b66c83e 100644 --- a/scripts/server-metrics.ts +++ b/scripts/server-metrics.ts @@ -62,6 +62,7 @@ import { ServerMetrics, slope, spread, + activityRenewalMissed, nextActivityReport, parsePsCpuTime, pathRewrites, @@ -1145,8 +1146,12 @@ const attachClient = Effect.fn("serverMetrics.attachClient")(function* ( return yield* new MetricsError({ message: "an activity renewal missed its lease" }); } yield* Effect.sleep(Duration.millis(next.waitMs)); - lastSent = yield* nowMs; + const sentAt = yield* nowMs; yield* report; + if (activityRenewalMissed(lastSent, sentAt, yield* nowMs)) { + return yield* new MetricsError({ message: "an activity renewal missed its lease" }); + } + lastSent = sentAt; } }).pipe( Effect.catchCause(() => Ref.update(lost, (first) => first ?? "an activity report failed")),