diff --git a/scripts/server-metrics-report.ts b/scripts/server-metrics-report.ts index 3ccd4235244b5..6e03db8ff84a3 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; @@ -411,3 +426,32 @@ 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 }; +} + +/** + * 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 8d4fe431fe7c7..760c850dbbbea 100644 --- a/scripts/server-metrics.test.ts +++ b/scripts/server-metrics.test.ts @@ -3,7 +3,9 @@ import { describe, expect, it } from "vite-plus/test"; import { compareMetrics, + activityRenewalMissed, heapGrowth, + nextActivityReport, parsePsCpuTime, parseRunSelection, pathRewrites, @@ -304,3 +306,23 @@ 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); + }); +}); + +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 78e7dd87654e1..4f0b67b66c83e 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"; @@ -56,6 +62,8 @@ import { ServerMetrics, slope, spread, + activityRenewalMissed, + nextActivityReport, parsePsCpuTime, pathRewrites, pathSpellings, @@ -70,6 +78,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 +916,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 +1055,157 @@ 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; + // 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( + 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)); + // 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.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, + }); + }).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" }), + }), + ); + let lastSent = yield* nowMs; + yield* report; + // 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)); + 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")), + Effect.forkScoped, + ); + 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" }), + }), + ); + 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 = [ + "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 +1317,70 @@ 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* () { + 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; + }), + ); + } + // 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), () => clientScope); + const first = yield* Effect.forEach( + clients, + (scope, index) => + attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), + { concurrency: "unbounded" }, + ); + 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), { + concurrency: "unbounded", + discard: true, + }); + const reopened = yield* Effect.forEach(clients, () => clientScope); + const second = yield* Effect.forEach( + reopened, + (scope, index) => + attachClient(server, token, threads.slice(index, index + 1)).pipe(Scope.provide(scope)), + { concurrency: "unbounded" }, + ); + const resubscribedMs = Math.round((yield* nowMs) - dropped); + const loop = yield* server.loopRead; + // 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, + }); + 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* () {