Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions apps/sim/lib/model-router/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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({
Expand Down
15 changes: 13 additions & 2 deletions apps/sim/lib/mothership/generated/model-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
});
Expand Down
39 changes: 39 additions & 0 deletions apps/sim/lib/mothership/generated/mothership-stream-v1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
>;
19 changes: 1 addition & 18 deletions apps/sim/lib/mothership/generated/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,7 @@ export type AbortRequest = z.infer<typeof AbortRequest>;
* 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(),
Expand All @@ -485,23 +485,6 @@ export const StreamReplayRequest = z.strictObject({
});
export type StreamReplayRequest = z.infer<typeof StreamReplayRequest>;

/**
* 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;
Expand Down
17 changes: 16 additions & 1 deletion apps/sim/lib/mothership/request/session/contract.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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 = {
Expand Down
43 changes: 20 additions & 23 deletions apps/sim/lib/mothership/request/session/run-replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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<StreamReplayEnd['reason'], true>

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<StreamReplayEnd>
}) satisfies z.ZodType<MothershipStreamV1ReplayEndPayload>

/**
* 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'
}

Expand Down
Loading