From debce567820e7f48d5959bdf13fe6ff633a80b15 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 11:50:37 -0800 Subject: [PATCH] improvement(mothership): use the synced replay-end frame contract Sync the worker contracts: model-router candidate ids now start and end with a letter or digit and are not trimmed, and the replay-end frame's payload, kind, reasons and envelope live in mothership-stream-v1 as MothershipStreamV1ReplayEnd* instead of protocol's StreamReplayEnd. The run replay reader validates the frame against the synced kind and reason constants instead of a hand-kept copy, and logs a malformed frame with its zod issue paths. The frame stays outside the live run kinds; a contract test pins that the live parser rejects it. A model-router test runs the request body Sim builds through the synced ModelRouterRequest, so a tier id the worker would reject fails here first. --- apps/sim/lib/model-router/resolve.test.ts | 16 +++++++ .../lib/mothership/generated/model-router.ts | 15 ++++++- .../generated/mothership-stream-v1.ts | 39 +++++++++++++++++ apps/sim/lib/mothership/generated/protocol.ts | 19 +------- .../request/session/contract.test.ts | 17 +++++++- .../mothership/request/session/run-replay.ts | 43 +++++++++---------- 6 files changed, 105 insertions(+), 44 deletions(-) diff --git a/apps/sim/lib/model-router/resolve.test.ts b/apps/sim/lib/model-router/resolve.test.ts index b1fa4775dcf..5226bd2778c 100644 --- a/apps/sim/lib/model-router/resolve.test.ts +++ b/apps/sim/lib/model-router/resolve.test.ts @@ -27,6 +27,7 @@ import { addAutoRoutingCost, resolveAutoModel, } from '@/lib/model-router/resolve' +import { ModelRouterRequest } from '@/lib/mothership/generated/model-router' import type { ExecutionContext } from '@/executor/types' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' @@ -173,6 +174,21 @@ describe('resolveAutoModel', () => { expect(result.billableRoutingCost).toBeCloseTo(0.002) }) + it('sends a request body the worker contract accepts', async () => { + // The worker answers 400 to a body its contract rejects, e.g. a tier id outside its alphabet. + mockFetchWorker.mockResolvedValue(routerResponse(null, false, 503)) + await resolveAutoModel({ + ctx, + blockId: 'b1', + signals: makeSignals(), + fallbackModel: 'claude-sonnet-5', + }) + const init = mockFetchWorker.mock.lastCall?.[1] as RequestInit | undefined + const parsed = ModelRouterRequest.safeParse(JSON.parse(String(init?.body))) + expect(parsed.error).toBeUndefined() + expect(parsed.data?.candidates.map((c) => c.id)).toEqual(['1', '2', '3']) + }) + it('does not bill when the response omits billable (fail-safe)', async () => { mockFetchWorker.mockResolvedValue( routerResponse({ diff --git a/apps/sim/lib/mothership/generated/model-router.ts b/apps/sim/lib/mothership/generated/model-router.ts index 27fa5425a51..30f40e4a71f 100644 --- a/apps/sim/lib/mothership/generated/model-router.ts +++ b/apps/sim/lib/mothership/generated/model-router.ts @@ -10,8 +10,19 @@ import { z } from "zod"; * Internal-key only: customer keys never reach it. */ export const ModelRouterCandidate = z.strictObject({ - /** The token the classifier answers with, e.g. "1". */ - id: z.string().trim().min(1).max(32).regex(/^\S+$/, "a candidate id is a single token"), + /** + * The token the classifier answers with, e.g. "1": ASCII letters, digits, `_` and `-`, starting + * and ending with a letter or digit. Edge punctuation is reserved for the wrapping a model puts + * around its answer (`"2".`, `**fast**`), so the worker strips it without ever turning one + * candidate's id into another's. + */ + id: z + .string() + .max(32) + .regex( + /^[A-Za-z0-9](?:[\w-]*[A-Za-z0-9])?$/, + "a candidate id is letters, digits, _ and -, starting and ending with a letter or digit", + ), /** One line saying when this candidate fits. */ hint: z.string().max(500), }); diff --git a/apps/sim/lib/mothership/generated/mothership-stream-v1.ts b/apps/sim/lib/mothership/generated/mothership-stream-v1.ts index 9ed51b1338f..0766740d9d4 100644 --- a/apps/sim/lib/mothership/generated/mothership-stream-v1.ts +++ b/apps/sim/lib/mothership/generated/mothership-stream-v1.ts @@ -340,3 +340,42 @@ export const MothershipStreamV1ToolOutcome = { skipped: "skipped", rejected: "rejected", } as const satisfies { [K in MothershipStreamV1ToolOutcome]: K }; + +// The replay-end control frame (D117, D121). POST /api/streams/replay ends a leg short of the run's +// terminal with this one `run` frame. It is deliberately NOT a member of +// `MothershipStreamV1EventEnvelope` and its kind is NOT in `MothershipStreamV1RunKind`: Sim's live +// reader accepts exactly that const's kinds, so a replay_end arriving on a live stream is rejected, +// and only Sim's replay reader, which checks for this frame before its v1 validation, accepts it. + +export const MothershipStreamV1ReplayEndKind = "replay_end"; + +/** + * Why a replay leg ended before the run's terminal. `parked`: the run waits on tool results the + * owner's leg handed Sim. `cap`: the connection reached its length cap; replay again. `stalled`: no + * instance drives the run (stale heartbeat, not parked); replay again later, once a takeover can + * have resumed it. + */ +export type MothershipStreamV1ReplayEndReason = "parked" | "cap" | "stalled"; + +export const MothershipStreamV1ReplayEndReason = { + parked: "parked", + cap: "cap", + stalled: "stalled", +} as const satisfies { [K in MothershipStreamV1ReplayEndReason]: K }; + +/** + * `textLength` is the main text this leg's log reached — diagnostic only. A later replay sends + * Sim's OWN received length as `receivedTextChars`, never this value: the log trails live text, and + * resending from the durable end is what exposes divergence. Replayed tool activity is presentation + * only (`replay: true`) and never authorizes execution. + */ +export interface MothershipStreamV1ReplayEndPayload { + kind: typeof MothershipStreamV1ReplayEndKind; + reason: MothershipStreamV1ReplayEndReason; + textLength: number; +} + +export type MothershipStreamV1ReplayEndEnvelope = MothershipStreamV1Envelope< + typeof MothershipStreamV1EventType.run, + MothershipStreamV1ReplayEndPayload +>; diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 9c4d1f00e1b..6c6e472096a 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -474,7 +474,7 @@ export type AbortRequest = z.infer; * durable log for a reader whose cursor fell off sim's replay ring. Read-only: the owner, * its emitter, its lease and its parked calls are untouched. The SSE leg restores what * the receipt lacks, follows the log, and ends with `complete` at a terminal or with one - * `run` frame of kind `replay_end` otherwise. + * `MothershipStreamV1ReplayEndEnvelope` (mothership-stream-v1.ts) otherwise. */ export const StreamReplayRequest = z.strictObject({ streamId: z.uuid(), @@ -485,23 +485,6 @@ export const StreamReplayRequest = z.strictObject({ }); export type StreamReplayRequest = z.infer; -/** - * A replay leg that ended before the run's terminal. `parked`: the run waits on tool - * results the owner's leg handed sim. `cap`: the connection reached its length cap; - * replay again. `stalled`: no instance drives the run (stale heartbeat, not parked); - * replay again later, once a takeover can have resumed it. - * `textLength` is the main text this leg's log reached — diagnostic only. A later - * replay sends sim's OWN received length as `receivedTextChars`, never this value: the - * log trails live text, and resending from the durable end is what exposes divergence. - * Replayed tool activity is presentation only (`replay: true`) and never authorizes - * execution. - */ -export interface StreamReplayEnd extends StreamTextCompletion { - kind: "replay_end"; - reason: "parked" | "cap" | "stalled"; - textLength: number; -} - /** Accepted Stop intent is distinct from an observed terminal worker run. */ export interface AbortResponse { stopped: boolean; diff --git a/apps/sim/lib/mothership/request/session/contract.test.ts b/apps/sim/lib/mothership/request/session/contract.test.ts index 74701e1f595..e88cfd59435 100644 --- a/apps/sim/lib/mothership/request/session/contract.test.ts +++ b/apps/sim/lib/mothership/request/session/contract.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' -import { MothershipStreamV1RunKind } from '@/lib/mothership/generated/mothership-stream-v1' +import { + type MothershipStreamV1ReplayEndEnvelope, + MothershipStreamV1ReplayEndKind, + MothershipStreamV1RunKind, +} from '@/lib/mothership/generated/mothership-stream-v1' import { isContractStreamEventEnvelope, isSyntheticFilePreviewEventEnvelope, @@ -53,6 +57,17 @@ describe('stream session contract parser', () => { } }) + it('rejects the replay-end control frame as a live stream event', () => { + // D121. + const event: MothershipStreamV1ReplayEndEnvelope = { + ...BASE_ENVELOPE, + type: 'run', + payload: { kind: MothershipStreamV1ReplayEndKind, reason: 'stalled', textLength: 6 }, + } + expect(isContractStreamEventEnvelope(event)).toBe(false) + expect(parsePersistedStreamEventEnvelope(event).ok).toBe(false) + }) + it.each(['run', 'complete'])('validates activity acknowledgement on %s boundaries', (type) => { const payload = type === 'run' ? { kind: 'checkpoint_pause' } : { status: 'complete' } const event = { diff --git a/apps/sim/lib/mothership/request/session/run-replay.ts b/apps/sim/lib/mothership/request/session/run-replay.ts index 5271833e3da..86a65ed656d 100644 --- a/apps/sim/lib/mothership/request/session/run-replay.ts +++ b/apps/sim/lib/mothership/request/session/run-replay.ts @@ -4,8 +4,13 @@ import { sleep } from '@sim/utils/helpers' import { isRecordLike, toRecord } from '@sim/utils/object' import { z } from 'zod' import { WORKER_STREAM_IDLE_TIMEOUT_MS } from '@/lib/mothership/constants' -import { MothershipStreamV1EventType } from '@/lib/mothership/generated/mothership-stream-v1' -import { type StreamReplayEnd, StreamReplayRequest } from '@/lib/mothership/generated/protocol' +import { + MothershipStreamV1EventType, + MothershipStreamV1ReplayEndKind, + type MothershipStreamV1ReplayEndPayload, + MothershipStreamV1ReplayEndReason, +} from '@/lib/mothership/generated/mothership-stream-v1' +import { StreamReplayRequest } from '@/lib/mothership/generated/protocol' import { TraceAttr } from '@/lib/mothership/observability/trace-attributes' import { mothershipRequestHeaders } from '@/lib/mothership/request/headers' import { @@ -29,7 +34,7 @@ const REPLAY_HOLD_POLL_MS = 1_000 const PARKED_RUN_STATUS = 'paused_waiting_for_tool' /** How a worker replay leg ended: at the run's terminal, short of it, or cut off. */ -export type RunReplayEnd = 'complete' | StreamReplayEnd['reason'] | 'closed' +export type RunReplayEnd = 'complete' | MothershipStreamV1ReplayEndReason | 'closed' /** The worker could not serve the replay; the reader should retry later. */ export class RunReplayUnavailableError extends Error { @@ -93,35 +98,27 @@ export async function openRunReplay(params: { return response.body } -/** Every reason the worker may end a replay with; a reason added to the contract fails here. */ -const REPLAY_END_REASONS = { - parked: true, - cap: true, - stalled: true, -} as const satisfies Record - -const StreamReplayEndSchema = z.object({ - kind: z.literal('replay_end'), - reason: z - .string() - .refine((reason): reason is StreamReplayEnd['reason'] => - Object.hasOwn(REPLAY_END_REASONS, reason) - ), +const ReplayEndPayloadSchema = z.object({ + kind: z.literal(MothershipStreamV1ReplayEndKind), + reason: z.enum(MothershipStreamV1ReplayEndReason), textLength: z.number().int().nonnegative(), -}) satisfies z.ZodType +}) satisfies z.ZodType /** - * The end a `replay_end` frame reports: its reason, `closed` for a reason this build - * does not know, or `null` for any other frame. It is worker-to-Sim control, never a + * The end a `replay_end` frame reports: its reason, `closed` for a frame this build + * cannot parse (an unknown reason, a missing length), or `null` for any other frame. It is worker-to-Sim control, never a * stream event, whatever reason it carries. */ function replayEnd(value: unknown): RunReplayEnd | null { if (!isRecordLike(value) || value.type !== MothershipStreamV1EventType.run) return null const payload = toRecord(value.payload) - if (payload.kind !== 'replay_end') return null - const parsed = StreamReplayEndSchema.safeParse(payload) + if (payload.kind !== MothershipStreamV1ReplayEndKind) return null + const parsed = ReplayEndPayloadSchema.safeParse(payload) if (parsed.success) return parsed.data.reason - logger.warn('Run replay ended with an unknown reason', { reason: payload.reason }) + logger.warn('Run replay ended with a malformed replay-end frame', { + reason: payload.reason, + issues: parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'), + }) return 'closed' }