Skip to content

Commit debce56

Browse files
committed
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.
1 parent 6e73e14 commit debce56

6 files changed

Lines changed: 105 additions & 44 deletions

File tree

‎apps/sim/lib/model-router/resolve.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
addAutoRoutingCost,
2828
resolveAutoModel,
2929
} from '@/lib/model-router/resolve'
30+
import { ModelRouterRequest } from '@/lib/mothership/generated/model-router'
3031
import type { ExecutionContext } from '@/executor/types'
3132
import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
3233

@@ -173,6 +174,21 @@ describe('resolveAutoModel', () => {
173174
expect(result.billableRoutingCost).toBeCloseTo(0.002)
174175
})
175176

177+
it('sends a request body the worker contract accepts', async () => {
178+
// The worker answers 400 to a body its contract rejects, e.g. a tier id outside its alphabet.
179+
mockFetchWorker.mockResolvedValue(routerResponse(null, false, 503))
180+
await resolveAutoModel({
181+
ctx,
182+
blockId: 'b1',
183+
signals: makeSignals(),
184+
fallbackModel: 'claude-sonnet-5',
185+
})
186+
const init = mockFetchWorker.mock.lastCall?.[1] as RequestInit | undefined
187+
const parsed = ModelRouterRequest.safeParse(JSON.parse(String(init?.body)))
188+
expect(parsed.error).toBeUndefined()
189+
expect(parsed.data?.candidates.map((c) => c.id)).toEqual(['1', '2', '3'])
190+
})
191+
176192
it('does not bill when the response omits billable (fail-safe)', async () => {
177193
mockFetchWorker.mockResolvedValue(
178194
routerResponse({

‎apps/sim/lib/mothership/generated/model-router.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,19 @@ import { z } from "zod";
1010
* Internal-key only: customer keys never reach it.
1111
*/
1212
export const ModelRouterCandidate = z.strictObject({
13-
/** The token the classifier answers with, e.g. "1". */
14-
id: z.string().trim().min(1).max(32).regex(/^\S+$/, "a candidate id is a single token"),
13+
/**
14+
* The token the classifier answers with, e.g. "1": ASCII letters, digits, `_` and `-`, starting
15+
* and ending with a letter or digit. Edge punctuation is reserved for the wrapping a model puts
16+
* around its answer (`"2".`, `**fast**`), so the worker strips it without ever turning one
17+
* candidate's id into another's.
18+
*/
19+
id: z
20+
.string()
21+
.max(32)
22+
.regex(
23+
/^[A-Za-z0-9](?:[\w-]*[A-Za-z0-9])?$/,
24+
"a candidate id is letters, digits, _ and -, starting and ending with a letter or digit",
25+
),
1526
/** One line saying when this candidate fits. */
1627
hint: z.string().max(500),
1728
});

‎apps/sim/lib/mothership/generated/mothership-stream-v1.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,3 +340,42 @@ export const MothershipStreamV1ToolOutcome = {
340340
skipped: "skipped",
341341
rejected: "rejected",
342342
} as const satisfies { [K in MothershipStreamV1ToolOutcome]: K };
343+
344+
// The replay-end control frame (D117, D121). POST /api/streams/replay ends a leg short of the run's
345+
// terminal with this one `run` frame. It is deliberately NOT a member of
346+
// `MothershipStreamV1EventEnvelope` and its kind is NOT in `MothershipStreamV1RunKind`: Sim's live
347+
// reader accepts exactly that const's kinds, so a replay_end arriving on a live stream is rejected,
348+
// and only Sim's replay reader, which checks for this frame before its v1 validation, accepts it.
349+
350+
export const MothershipStreamV1ReplayEndKind = "replay_end";
351+
352+
/**
353+
* Why a replay leg ended before the run's terminal. `parked`: the run waits on tool results the
354+
* owner's leg handed Sim. `cap`: the connection reached its length cap; replay again. `stalled`: no
355+
* instance drives the run (stale heartbeat, not parked); replay again later, once a takeover can
356+
* have resumed it.
357+
*/
358+
export type MothershipStreamV1ReplayEndReason = "parked" | "cap" | "stalled";
359+
360+
export const MothershipStreamV1ReplayEndReason = {
361+
parked: "parked",
362+
cap: "cap",
363+
stalled: "stalled",
364+
} as const satisfies { [K in MothershipStreamV1ReplayEndReason]: K };
365+
366+
/**
367+
* `textLength` is the main text this leg's log reached — diagnostic only. A later replay sends
368+
* Sim's OWN received length as `receivedTextChars`, never this value: the log trails live text, and
369+
* resending from the durable end is what exposes divergence. Replayed tool activity is presentation
370+
* only (`replay: true`) and never authorizes execution.
371+
*/
372+
export interface MothershipStreamV1ReplayEndPayload {
373+
kind: typeof MothershipStreamV1ReplayEndKind;
374+
reason: MothershipStreamV1ReplayEndReason;
375+
textLength: number;
376+
}
377+
378+
export type MothershipStreamV1ReplayEndEnvelope = MothershipStreamV1Envelope<
379+
typeof MothershipStreamV1EventType.run,
380+
MothershipStreamV1ReplayEndPayload
381+
>;

‎apps/sim/lib/mothership/generated/protocol.ts‎

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ export type AbortRequest = z.infer<typeof AbortRequest>;
474474
* durable log for a reader whose cursor fell off sim's replay ring. Read-only: the owner,
475475
* its emitter, its lease and its parked calls are untouched. The SSE leg restores what
476476
* the receipt lacks, follows the log, and ends with `complete` at a terminal or with one
477-
* `run` frame of kind `replay_end` otherwise.
477+
* `MothershipStreamV1ReplayEndEnvelope` (mothership-stream-v1.ts) otherwise.
478478
*/
479479
export const StreamReplayRequest = z.strictObject({
480480
streamId: z.uuid(),
@@ -485,23 +485,6 @@ export const StreamReplayRequest = z.strictObject({
485485
});
486486
export type StreamReplayRequest = z.infer<typeof StreamReplayRequest>;
487487

488-
/**
489-
* A replay leg that ended before the run's terminal. `parked`: the run waits on tool
490-
* results the owner's leg handed sim. `cap`: the connection reached its length cap;
491-
* replay again. `stalled`: no instance drives the run (stale heartbeat, not parked);
492-
* replay again later, once a takeover can have resumed it.
493-
* `textLength` is the main text this leg's log reached — diagnostic only. A later
494-
* replay sends sim's OWN received length as `receivedTextChars`, never this value: the
495-
* log trails live text, and resending from the durable end is what exposes divergence.
496-
* Replayed tool activity is presentation only (`replay: true`) and never authorizes
497-
* execution.
498-
*/
499-
export interface StreamReplayEnd extends StreamTextCompletion {
500-
kind: "replay_end";
501-
reason: "parked" | "cap" | "stalled";
502-
textLength: number;
503-
}
504-
505488
/** Accepted Stop intent is distinct from an observed terminal worker run. */
506489
export interface AbortResponse {
507490
stopped: boolean;

‎apps/sim/lib/mothership/request/session/contract.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { describe, expect, it } from 'vitest'
2-
import { MothershipStreamV1RunKind } from '@/lib/mothership/generated/mothership-stream-v1'
2+
import {
3+
type MothershipStreamV1ReplayEndEnvelope,
4+
MothershipStreamV1ReplayEndKind,
5+
MothershipStreamV1RunKind,
6+
} from '@/lib/mothership/generated/mothership-stream-v1'
37
import {
48
isContractStreamEventEnvelope,
59
isSyntheticFilePreviewEventEnvelope,
@@ -53,6 +57,17 @@ describe('stream session contract parser', () => {
5357
}
5458
})
5559

60+
it('rejects the replay-end control frame as a live stream event', () => {
61+
// D121.
62+
const event: MothershipStreamV1ReplayEndEnvelope = {
63+
...BASE_ENVELOPE,
64+
type: 'run',
65+
payload: { kind: MothershipStreamV1ReplayEndKind, reason: 'stalled', textLength: 6 },
66+
}
67+
expect(isContractStreamEventEnvelope(event)).toBe(false)
68+
expect(parsePersistedStreamEventEnvelope(event).ok).toBe(false)
69+
})
70+
5671
it.each(['run', 'complete'])('validates activity acknowledgement on %s boundaries', (type) => {
5772
const payload = type === 'run' ? { kind: 'checkpoint_pause' } : { status: 'complete' }
5873
const event = {

‎apps/sim/lib/mothership/request/session/run-replay.ts‎

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,13 @@ import { sleep } from '@sim/utils/helpers'
44
import { isRecordLike, toRecord } from '@sim/utils/object'
55
import { z } from 'zod'
66
import { WORKER_STREAM_IDLE_TIMEOUT_MS } from '@/lib/mothership/constants'
7-
import { MothershipStreamV1EventType } from '@/lib/mothership/generated/mothership-stream-v1'
8-
import { type StreamReplayEnd, StreamReplayRequest } from '@/lib/mothership/generated/protocol'
7+
import {
8+
MothershipStreamV1EventType,
9+
MothershipStreamV1ReplayEndKind,
10+
type MothershipStreamV1ReplayEndPayload,
11+
MothershipStreamV1ReplayEndReason,
12+
} from '@/lib/mothership/generated/mothership-stream-v1'
13+
import { StreamReplayRequest } from '@/lib/mothership/generated/protocol'
914
import { TraceAttr } from '@/lib/mothership/observability/trace-attributes'
1015
import { mothershipRequestHeaders } from '@/lib/mothership/request/headers'
1116
import {
@@ -29,7 +34,7 @@ const REPLAY_HOLD_POLL_MS = 1_000
2934
const PARKED_RUN_STATUS = 'paused_waiting_for_tool'
3035

3136
/** How a worker replay leg ended: at the run's terminal, short of it, or cut off. */
32-
export type RunReplayEnd = 'complete' | StreamReplayEnd['reason'] | 'closed'
37+
export type RunReplayEnd = 'complete' | MothershipStreamV1ReplayEndReason | 'closed'
3338

3439
/** The worker could not serve the replay; the reader should retry later. */
3540
export class RunReplayUnavailableError extends Error {
@@ -93,35 +98,27 @@ export async function openRunReplay(params: {
9398
return response.body
9499
}
95100

96-
/** Every reason the worker may end a replay with; a reason added to the contract fails here. */
97-
const REPLAY_END_REASONS = {
98-
parked: true,
99-
cap: true,
100-
stalled: true,
101-
} as const satisfies Record<StreamReplayEnd['reason'], true>
102-
103-
const StreamReplayEndSchema = z.object({
104-
kind: z.literal('replay_end'),
105-
reason: z
106-
.string()
107-
.refine((reason): reason is StreamReplayEnd['reason'] =>
108-
Object.hasOwn(REPLAY_END_REASONS, reason)
109-
),
101+
const ReplayEndPayloadSchema = z.object({
102+
kind: z.literal(MothershipStreamV1ReplayEndKind),
103+
reason: z.enum(MothershipStreamV1ReplayEndReason),
110104
textLength: z.number().int().nonnegative(),
111-
}) satisfies z.ZodType<StreamReplayEnd>
105+
}) satisfies z.ZodType<MothershipStreamV1ReplayEndPayload>
112106

113107
/**
114-
* The end a `replay_end` frame reports: its reason, `closed` for a reason this build
115-
* does not know, or `null` for any other frame. It is worker-to-Sim control, never a
108+
* The end a `replay_end` frame reports: its reason, `closed` for a frame this build
109+
* cannot parse (an unknown reason, a missing length), or `null` for any other frame. It is worker-to-Sim control, never a
116110
* stream event, whatever reason it carries.
117111
*/
118112
function replayEnd(value: unknown): RunReplayEnd | null {
119113
if (!isRecordLike(value) || value.type !== MothershipStreamV1EventType.run) return null
120114
const payload = toRecord(value.payload)
121-
if (payload.kind !== 'replay_end') return null
122-
const parsed = StreamReplayEndSchema.safeParse(payload)
115+
if (payload.kind !== MothershipStreamV1ReplayEndKind) return null
116+
const parsed = ReplayEndPayloadSchema.safeParse(payload)
123117
if (parsed.success) return parsed.data.reason
124-
logger.warn('Run replay ended with an unknown reason', { reason: payload.reason })
118+
logger.warn('Run replay ended with a malformed replay-end frame', {
119+
reason: payload.reason,
120+
issues: parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'),
121+
})
125122
return 'closed'
126123
}
127124

0 commit comments

Comments
 (0)