From 2b87d3ad0be46a6fc28729e68514dd397f0dea94 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 12:52:17 -0800 Subject: [PATCH 1/2] improvement(mothership): shadow-check worker stream frames against the contract schemas Takes the regenerated mothership-stream-v1 contract, whose types are now inferred from zod schemas. Frames the worker sends this server (the live leg and the run replay) go through parseIngestedStreamEventEnvelope: the existing validator still decides every frame, and the contract schema runs beside it. A disagreement in either direction increments copilot.stream_contract.disagreements (direction, event type, capped kind/phase) and logs the zod issue paths, once per distinct disagreement per ten minutes; a failure of the check itself is logged under the same limit. Synthetic file-preview frames are skipped by their previewPhase. The browser and the outbox reader are unchanged. Tests pin a representative set of frames the validator accepts and the schema rejects, one per kind of gap. The run replay reader validates replay-end payloads with the synced MothershipStreamV1ReplayEndPayloadSchema instead of a local copy of the same shape, and the shadow reuses the contract parser's event-type set. --- .../generated/mothership-stream-v1.ts | 593 ++++++++++-------- apps/sim/lib/mothership/generated/protocol.ts | 61 +- .../mothership/observability/metric-names.ts | 1 + .../observability/trace-attribute-values.ts | 12 + .../observability/trace-attributes.ts | 3 + apps/sim/lib/mothership/request/metrics.ts | 18 + .../request/session/contract-shadow.test.ts | 283 +++++++++ .../request/session/contract-shadow.ts | 136 ++++ .../mothership/request/session/contract.ts | 5 +- .../mothership/request/session/run-replay.ts | 17 +- .../lib/mothership/request/worker/stream.ts | 10 +- 11 files changed, 838 insertions(+), 301 deletions(-) create mode 100644 apps/sim/lib/mothership/request/session/contract-shadow.test.ts create mode 100644 apps/sim/lib/mothership/request/session/contract-shadow.ts diff --git a/apps/sim/lib/mothership/generated/mothership-stream-v1.ts b/apps/sim/lib/mothership/generated/mothership-stream-v1.ts index 0766740d9d4..7c03474a099 100644 --- a/apps/sim/lib/mothership/generated/mothership-stream-v1.ts +++ b/apps/sim/lib/mothership/generated/mothership-stream-v1.ts @@ -4,233 +4,351 @@ // The mothership-stream-v1 SSE wire: every `data:` frame the worker emits to Sim (each leg // ends with a literal `data: [DONE]` line), and the vocabulary Sim re-emits to the browser // (Sim adds `session` chat/title frames of its own). -// The worker's emitter (apps/server/src/protocol/envelope.ts) builds these envelopes, so a -// frame that drifts from what Sim parses fails typecheck. Each discriminant const below is -// checked against its payload union, because Sim's reader accepts exactly the const's values. - -import type { - StreamActivityCheckpoint, - StreamTextCompletion, - StreamTextPosition, - StreamToolDeadline, - StreamToolReplay, +// The zod schemas below are the single source (D122): every type is inferred from them, so the +// worker's emitter (apps/server/src/protocol/envelope.ts) fails typecheck on a frame that drifts, +// and a reader can validate a frame at runtime against the same definition. Each discriminant +// const below is checked against its payload union, because Sim's reader accepts exactly the +// const's values. Objects strip unknown keys: a newer emitter's extra field never fails a reader. +// Its own optional fields are `?: T` (`.exactOptional()`); the protocol.ts fields it spreads +// are `?: T | undefined`. + +import { z } from "zod"; +import { + StreamActivityCheckpointSchema, + StreamTextCompletionSchema, + StreamTextPositionSchema, + StreamToolDeadlineSchema, + StreamToolReplaySchema, } from "./protocol"; -import type { ResourcePayload } from "./resources"; +import { ResourcePayload } from "./resources"; -/** The shell every frame shares. */ -export interface MothershipStreamV1Envelope { - payload: TPayload; - scope?: MothershipStreamV1StreamScope; - seq: number; - stream: MothershipStreamV1StreamRef; - trace?: MothershipStreamV1Trace; - ts: string; - type: TType; - v: 1; -} - -/** Every frame on the wire, one member per payload shape. */ -export type MothershipStreamV1EventEnvelope = - | MothershipStreamV1Envelope<"session", MothershipStreamV1SessionStartPayload> - | MothershipStreamV1Envelope<"session", MothershipStreamV1SessionChatPayload> - | MothershipStreamV1Envelope<"session", MothershipStreamV1SessionTitlePayload> - | MothershipStreamV1Envelope<"text", MothershipStreamV1TextPayload> - | MothershipStreamV1Envelope<"tool", MothershipStreamV1ToolCallDescriptor> - | MothershipStreamV1Envelope<"tool", MothershipStreamV1ToolArgsDeltaPayload> - | MothershipStreamV1Envelope<"tool", MothershipStreamV1ToolResultPayload> - | MothershipStreamV1Envelope<"span", MothershipStreamV1SubagentSpanPayload> - | MothershipStreamV1Envelope<"resource", ResourcePayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1CheckpointPausePayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1CompactionStartPayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1CompactionDonePayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1SteeringAppliedPayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1TaskArmedPayload> - | MothershipStreamV1Envelope<"run", MothershipStreamV1TaskDeliveredPayload> - | MothershipStreamV1Envelope<"error", MothershipStreamV1ErrorPayload> - | MothershipStreamV1Envelope<"complete", MothershipStreamV1CompletePayload>; +// Each value enum's const is its single source; its schema reads the const. -/** The payload a frame of `type` carries. */ -type PayloadOf = Extract< - MothershipStreamV1EventEnvelope, - { type: TType } ->["payload"]; +export const MothershipStreamV1TextChannel = { + assistant: "assistant", + thinking: "thinking", +} as const; +export type MothershipStreamV1TextChannel = + (typeof MothershipStreamV1TextChannel)[keyof typeof MothershipStreamV1TextChannel]; -export type MothershipStreamV1TextChannel = "assistant" | "thinking"; /** * Where a tool call executes. `go` means the worker executes it: the name is a persisted * historical value (stored chat blocks and self-hosted Sims read it), so it stays on the wire. */ -export type MothershipStreamV1ToolExecutor = "go" | "sim" | "client"; -export type MothershipStreamV1ToolMode = "sync" | "async"; +export const MothershipStreamV1ToolExecutor = { + go: "go", + sim: "sim", + client: "client", +} as const; +export type MothershipStreamV1ToolExecutor = + (typeof MothershipStreamV1ToolExecutor)[keyof typeof MothershipStreamV1ToolExecutor]; + +export const MothershipStreamV1ToolMode = { + sync: "sync", + async: "async", +} as const; +export type MothershipStreamV1ToolMode = + (typeof MothershipStreamV1ToolMode)[keyof typeof MothershipStreamV1ToolMode]; + +export const MothershipStreamV1ToolStatus = { + generating: "generating", + awaiting_approval: "awaiting_approval", + executing: "executing", + success: "success", + error: "error", + cancelled: "cancelled", + skipped: "skipped", + rejected: "rejected", +} as const; export type MothershipStreamV1ToolStatus = - | "generating" - | "awaiting_approval" - | "executing" - | "success" - | "error" - | "cancelled" - | "skipped" - | "rejected"; -export type MothershipStreamV1CompletionStatus = "complete" | "error" | "cancelled"; - -export interface MothershipStreamV1StreamScope { - agentId?: string; - lane: "subagent"; - parentSpanId?: string; - parentToolCallId?: string; - spanId?: string; -} -export interface MothershipStreamV1StreamRef { - chatId?: string; - cursor?: string; - streamId: string; -} -export interface MothershipStreamV1Trace { - requestId: string; - spanId?: string; -} + (typeof MothershipStreamV1ToolStatus)[keyof typeof MothershipStreamV1ToolStatus]; -export interface MothershipStreamV1SessionStartPayload { - data?: MothershipStreamV1SessionStartData; - kind: "start"; -} -export interface MothershipStreamV1SessionStartData { - responseId?: string; -} -/** Emitted by Sim, not the worker. */ -export interface MothershipStreamV1SessionChatPayload { - chatId: string; - kind: "chat"; +export const MothershipStreamV1SpanLifecycleEvent = { + start: "start", + end: "end", +} as const; +export type MothershipStreamV1SpanLifecycleEvent = + (typeof MothershipStreamV1SpanLifecycleEvent)[keyof typeof MothershipStreamV1SpanLifecycleEvent]; + +export const MothershipStreamV1CompletionStatus = { + complete: "complete", + error: "error", + cancelled: "cancelled", +} as const; +export type MothershipStreamV1CompletionStatus = + (typeof MothershipStreamV1CompletionStatus)[keyof typeof MothershipStreamV1CompletionStatus]; + +const StreamScopeSchema = z.object({ + agentId: z.string().exactOptional(), + lane: z.literal("subagent"), + parentSpanId: z.string().exactOptional(), + parentToolCallId: z.string().exactOptional(), + spanId: z.string().exactOptional(), +}); +export type MothershipStreamV1StreamScope = z.infer; + +const StreamRefSchema = z.object({ + chatId: z.string().exactOptional(), + cursor: z.string().exactOptional(), + streamId: z.string().min(1), +}); +export type MothershipStreamV1StreamRef = z.infer; + +const TraceSchema = z.object({ + requestId: z.string(), + spanId: z.string().exactOptional(), +}); +export type MothershipStreamV1Trace = z.infer; + +const EnvelopeShellSchema = z.object({ + scope: StreamScopeSchema.exactOptional(), + seq: z.number(), + stream: StreamRefSchema, + trace: TraceSchema.exactOptional(), + ts: z.string(), + v: z.literal(1), +}); + +/** The shell every frame shares. */ +export interface MothershipStreamV1Envelope + extends z.infer { + payload: TPayload; + type: TType; } + +const SessionStartDataSchema = z.object({ responseId: z.string().exactOptional() }); +export type MothershipStreamV1SessionStartData = z.infer; + +const SessionStartPayloadSchema = z.object({ + data: SessionStartDataSchema.exactOptional(), + kind: z.literal("start"), +}); +export type MothershipStreamV1SessionStartPayload = z.infer; + /** Emitted by Sim, not the worker. */ -export interface MothershipStreamV1SessionTitlePayload { - kind: "title"; - title: string; -} +const SessionChatPayloadSchema = z.object({ chatId: z.string(), kind: z.literal("chat") }); +export type MothershipStreamV1SessionChatPayload = z.infer; -export interface MothershipStreamV1TextPayload extends StreamTextPosition { - channel: MothershipStreamV1TextChannel; - text: string; -} +/** Emitted by Sim, not the worker. */ +const SessionTitlePayloadSchema = z.object({ kind: z.literal("title"), title: z.string() }); +export type MothershipStreamV1SessionTitlePayload = z.infer; + +const TextPayloadSchema = z.object({ + ...StreamTextPositionSchema.shape, + channel: z.enum(MothershipStreamV1TextChannel), + text: z.string(), +}); +export type MothershipStreamV1TextPayload = z.infer; + +const ToolUISchema = z.object({ + clientExecutable: z.boolean().exactOptional(), + hidden: z.boolean().exactOptional(), + inbandOwned: z.boolean().exactOptional(), + internal: z.boolean().exactOptional(), + simExecutable: z.boolean().exactOptional(), +}); +export type MothershipStreamV1ToolUI = z.infer; + +const ToolCallDescriptorSchema = z.object({ + ...StreamToolReplaySchema.shape, + ...StreamToolDeadlineSchema.shape, + activityDescription: z.string().exactOptional(), + arguments: z.record(z.string(), z.unknown()).exactOptional(), + execName: z.string().exactOptional(), + executor: z.enum(MothershipStreamV1ToolExecutor), + mode: z.enum(MothershipStreamV1ToolMode), + partial: z.boolean().exactOptional(), + phase: z.literal("call"), + status: z.enum(MothershipStreamV1ToolStatus).exactOptional(), + toolCallId: z.string(), + toolName: z.string(), + ui: ToolUISchema.exactOptional(), +}); +export type MothershipStreamV1ToolCallDescriptor = z.infer; -export interface MothershipStreamV1ToolCallDescriptor extends StreamToolReplay, StreamToolDeadline { - activityDescription?: string; - arguments?: Record; - execName?: string; - executor: MothershipStreamV1ToolExecutor; - mode: MothershipStreamV1ToolMode; - partial?: boolean; - phase: "call"; - status?: MothershipStreamV1ToolStatus; - toolCallId: string; - toolName: string; - ui?: MothershipStreamV1ToolUI; -} -export interface MothershipStreamV1ToolUI { - clientExecutable?: boolean; - hidden?: boolean; - inbandOwned?: boolean; - internal?: boolean; - simExecutable?: boolean; -} /** Draw-only argument text as it generates; never replayed, never dispatched on. */ -export interface MothershipStreamV1ToolArgsDeltaPayload { - argumentsDelta: string; - phase: "args_delta"; - toolCallId: string; - toolName: string; -} -export interface MothershipStreamV1ToolResultPayload extends StreamToolReplay { - error?: string; - executor: MothershipStreamV1ToolExecutor; - mode: MothershipStreamV1ToolMode; - output?: unknown; - phase: "result"; - status?: MothershipStreamV1ToolStatus; - success: boolean; - toolCallId: string; - toolName: string; -} +const ToolArgsDeltaPayloadSchema = z.object({ + argumentsDelta: z.string(), + phase: z.literal("args_delta"), + toolCallId: z.string(), + toolName: z.string(), +}); +export type MothershipStreamV1ToolArgsDeltaPayload = z.infer; + +const ToolResultPayloadSchema = z.object({ + ...StreamToolReplaySchema.shape, + error: z.string().exactOptional(), + executor: z.enum(MothershipStreamV1ToolExecutor), + mode: z.enum(MothershipStreamV1ToolMode), + output: z.unknown().exactOptional(), + phase: z.literal("result"), + status: z.enum(MothershipStreamV1ToolStatus).exactOptional(), + success: z.boolean(), + toolCallId: z.string(), + toolName: z.string(), +}); +export type MothershipStreamV1ToolResultPayload = z.infer; /** A subagent lane's display title (on start) or failure (on end). */ -export interface MothershipStreamV1SubagentSpanData { - name?: string; - error?: string; -} +const SubagentSpanDataSchema = z.object({ + name: z.string().exactOptional(), + error: z.string().exactOptional(), +}); +export type MothershipStreamV1SubagentSpanData = z.infer; + +const SubagentSpanPayloadSchema = z.object({ + agent: z.string().exactOptional(), + data: SubagentSpanDataSchema.exactOptional(), + event: z.enum(MothershipStreamV1SpanLifecycleEvent), + kind: z.literal("subagent"), +}); +export type MothershipStreamV1SubagentSpanPayload = z.infer; + +const CheckpointPausePayloadSchema = z.object({ + ...StreamActivityCheckpointSchema.shape, + checkpointId: z.string(), + executionId: z.string(), + kind: z.literal("checkpoint_pause"), + pendingToolCallIds: z.array(z.string()), + runId: z.string(), +}); +export type MothershipStreamV1CheckpointPausePayload = z.infer; + +const CompactionStartPayloadSchema = z.object({ kind: z.literal("compaction_start") }); +export type MothershipStreamV1CompactionStartPayload = z.infer; + +const CompactionDonePayloadSchema = z.object({ kind: z.literal("compaction_done") }); +export type MothershipStreamV1CompactionDonePayload = z.infer; -export interface MothershipStreamV1SubagentSpanPayload { - agent?: string; - data?: MothershipStreamV1SubagentSpanData; - event: "start" | "end"; - kind: "subagent"; -} +/** + * A steer reached the run's model input (the loss-free ack for POST /api/streams/steer). + * `eventSeq` is as in SteerV2Response's `applied`; absent only on frames from workers without + * steer v2. + */ +const SteeringAppliedPayloadSchema = z.object({ + eventSeq: z.number().exactOptional(), + kind: z.literal("steering_applied"), + steeringId: z.string(), + textOffset: z.number().exactOptional(), +}); +export type MothershipStreamV1SteeringAppliedPayload = z.infer; + +const TaskArmedPayloadSchema = z.object({ + kind: z.literal("task_armed"), + note: z.string(), + target: z.record(z.string(), z.unknown()), + taskId: z.string(), + taskKind: z.enum(["timer", "workflow_run"]), +}); +export type MothershipStreamV1TaskArmedPayload = z.infer; + +const TaskDeliveredPayloadSchema = z.object({ + kind: z.literal("task_delivered"), + status: z.enum(["completed", "failed", "stopped", "expired"]), + summary: z.string(), + taskId: z.string(), +}); +export type MothershipStreamV1TaskDeliveredPayload = z.infer; -export interface MothershipStreamV1CheckpointPausePayload extends StreamActivityCheckpoint { - checkpointId: string; - executionId: string; - kind: "checkpoint_pause"; - pendingToolCallIds: string[]; - runId: string; -} -export interface MothershipStreamV1CompactionStartPayload { - kind: "compaction_start"; -} -export interface MothershipStreamV1CompactionDonePayload { - kind: "compaction_done"; -} -/** A steer reached the run's model input (the loss-free ack for POST /api/streams/steer). */ -export interface MothershipStreamV1SteeringAppliedPayload { - /** As in SteerV2Response's `applied`; absent only on frames from workers without steer v2. */ - eventSeq?: number; - kind: "steering_applied"; - steeringId: string; - textOffset?: number; -} -export interface MothershipStreamV1TaskArmedPayload { - kind: "task_armed"; - note: string; - target: Record; - taskId: string; - taskKind: "timer" | "workflow_run"; -} -export interface MothershipStreamV1TaskDeliveredPayload { - kind: "task_delivered"; - status: "completed" | "failed" | "stopped" | "expired"; - summary: string; - taskId: string; -} +/** + * `message` is required. `error` is a Sim-emitted copy of it (Sim's terminal-failure frame sets + * both) and `data` Sim-emitted detail (e.g. the replay-gap bounds); the worker sends neither. + * Sim's own emitters are typed by this schema, so none sends `error` without `message` (D122). + */ +const ErrorPayloadSchema = z.object({ + code: z.string().exactOptional(), + data: z.unknown().exactOptional(), + displayMessage: z.string().exactOptional(), + error: z.string().exactOptional(), + message: z.string(), + provider: z.string().exactOptional(), +}); +export type MothershipStreamV1ErrorPayload = z.infer; + +const CostDataSchema = z.object({ + input: z.number().exactOptional(), + output: z.number().exactOptional(), + total: z.number().exactOptional(), +}); +export type MothershipStreamV1CostData = z.infer; + +const UsageDataSchema = z.object({ + cache_creation_input_tokens: z.number().exactOptional(), + cache_read_input_tokens: z.number().exactOptional(), + input_tokens: z.number().exactOptional(), + model: z.string().exactOptional(), + output_tokens: z.number().exactOptional(), + total_tokens: z.number().exactOptional(), +}); +export type MothershipStreamV1UsageData = z.infer; + +const CompletePayloadSchema = z.object({ + ...StreamTextCompletionSchema.shape, + ...StreamActivityCheckpointSchema.shape, + cost: CostDataSchema.exactOptional(), + reason: z.string().exactOptional(), + response: z.unknown().exactOptional(), + status: z.enum(MothershipStreamV1CompletionStatus), + usage: UsageDataSchema.exactOptional(), +}); +export type MothershipStreamV1CompletePayload = z.infer; + +const SessionPayloadSchema = z.discriminatedUnion("kind", [ + SessionStartPayloadSchema, + SessionChatPayloadSchema, + SessionTitlePayloadSchema, +]); +const ToolPayloadSchema = z.discriminatedUnion("phase", [ + ToolCallDescriptorSchema, + ToolArgsDeltaPayloadSchema, + ToolResultPayloadSchema, +]); +const RunPayloadSchema = z.discriminatedUnion("kind", [ + CheckpointPausePayloadSchema, + CompactionStartPayloadSchema, + CompactionDonePayloadSchema, + SteeringAppliedPayloadSchema, + TaskArmedPayloadSchema, + TaskDeliveredPayloadSchema, +]); -export interface MothershipStreamV1ErrorPayload { - code?: string; - /** Sim-emitted detail (e.g. the replay-gap bounds); the worker sends none. */ - data?: unknown; - displayMessage?: string; - /** Sim-emitted alias of `message`; the worker sends none. */ - error?: string; - message: string; - provider?: string; -} +/** + * Every live frame on the wire. On success a reader keeps its own value, not the parsed copy: + * the copy has unknown keys stripped. Its inferred type is not distributed over the payloads; + * readers type a frame as {@link MothershipStreamV1EventEnvelope}. + */ +export const MothershipStreamV1EventEnvelopeSchema = z.discriminatedUnion("type", [ + EnvelopeShellSchema.extend({ type: z.literal("session"), payload: SessionPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("text"), payload: TextPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("tool"), payload: ToolPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("span"), payload: SubagentSpanPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("resource"), payload: ResourcePayload }), + EnvelopeShellSchema.extend({ type: z.literal("run"), payload: RunPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("error"), payload: ErrorPayloadSchema }), + EnvelopeShellSchema.extend({ type: z.literal("complete"), payload: CompletePayloadSchema }), +]); + +/** One envelope member per payload variant, so `Extract<…, { payload: { phase: "call" } }>` works. */ +type EnvelopesOf = TPayload extends unknown + ? MothershipStreamV1Envelope + : never; -export interface MothershipStreamV1CompletePayload extends StreamTextCompletion, StreamActivityCheckpoint { - cost?: MothershipStreamV1CostData; - reason?: string; - response?: unknown; - status: MothershipStreamV1CompletionStatus; - usage?: MothershipStreamV1UsageData; -} -export interface MothershipStreamV1CostData { - input?: number; - output?: number; - total?: number; -} -export interface MothershipStreamV1UsageData { - cache_creation_input_tokens?: number; - cache_read_input_tokens?: number; - input_tokens?: number; - model?: string; - output_tokens?: number; - total_tokens?: number; -} +/** Every frame on the wire, one member per payload shape. */ +export type MothershipStreamV1EventEnvelope = + | EnvelopesOf<"session", z.infer> + | EnvelopesOf<"text", MothershipStreamV1TextPayload> + | EnvelopesOf<"tool", z.infer> + | EnvelopesOf<"span", MothershipStreamV1SubagentSpanPayload> + | MothershipStreamV1Envelope<"resource", ResourcePayload> + | EnvelopesOf<"run", z.infer> + | EnvelopesOf<"error", MothershipStreamV1ErrorPayload> + | EnvelopesOf<"complete", MothershipStreamV1CompletePayload>; + +/** The payload a frame of `type` carries. */ +type PayloadOf = Extract< + MothershipStreamV1EventEnvelope, + { type: TType } +>["payload"]; export type MothershipStreamV1EventType = MothershipStreamV1EventEnvelope["type"]; @@ -253,11 +371,6 @@ export const MothershipStreamV1SessionKind = { start: "start", } as const satisfies { [K in MothershipStreamV1SessionKind]: K }; -export const MothershipStreamV1TextChannel = { - assistant: "assistant", - thinking: "thinking", -} as const satisfies { [K in MothershipStreamV1TextChannel]: K }; - export type MothershipStreamV1ToolPhase = PayloadOf<"tool">["phase"]; export const MothershipStreamV1ToolPhase = { @@ -266,41 +379,12 @@ export const MothershipStreamV1ToolPhase = { result: "result", } as const satisfies { [K in MothershipStreamV1ToolPhase]: K }; -export const MothershipStreamV1ToolExecutor = { - go: "go", - sim: "sim", - client: "client", -} as const satisfies { [K in MothershipStreamV1ToolExecutor]: K }; - -export const MothershipStreamV1ToolMode = { - sync: "sync", - async: "async", -} as const satisfies { [K in MothershipStreamV1ToolMode]: K }; - -export const MothershipStreamV1ToolStatus = { - generating: "generating", - awaiting_approval: "awaiting_approval", - executing: "executing", - success: "success", - error: "error", - cancelled: "cancelled", - skipped: "skipped", - rejected: "rejected", -} as const satisfies { [K in MothershipStreamV1ToolStatus]: K }; - export type MothershipStreamV1SpanPayloadKind = PayloadOf<"span">["kind"]; export const MothershipStreamV1SpanPayloadKind = { subagent: "subagent", } as const satisfies { [K in MothershipStreamV1SpanPayloadKind]: K }; -export type MothershipStreamV1SpanLifecycleEvent = PayloadOf<"span">["event"]; - -export const MothershipStreamV1SpanLifecycleEvent = { - start: "start", - end: "end", -} as const satisfies { [K in MothershipStreamV1SpanLifecycleEvent]: K }; - export type MothershipStreamV1ResourceOp = ResourcePayload["op"]; export const MothershipStreamV1ResourceOp = { @@ -321,12 +405,6 @@ export const MothershipStreamV1RunKind = { task_delivered: "task_delivered", } as const satisfies { [K in MothershipStreamV1RunKind]: K }; -export const MothershipStreamV1CompletionStatus = { - complete: "complete", - error: "error", - cancelled: "cancelled", -} as const satisfies { [K in MothershipStreamV1CompletionStatus]: K }; - /** The terminal outcomes Sim reports for a tool call it executed (a subset of the tool status). */ export type MothershipStreamV1ToolOutcome = Extract< MothershipStreamV1ToolStatus, @@ -355,13 +433,13 @@ export const MothershipStreamV1ReplayEndKind = "replay_end"; * 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 }; +} as const; +export type MothershipStreamV1ReplayEndReason = + (typeof MothershipStreamV1ReplayEndReason)[keyof typeof MothershipStreamV1ReplayEndReason]; /** * `textLength` is the main text this leg's log reached — diagnostic only. A later replay sends @@ -369,11 +447,18 @@ export const MothershipStreamV1ReplayEndReason = { * 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 const MothershipStreamV1ReplayEndPayloadSchema = z.object({ + kind: z.literal(MothershipStreamV1ReplayEndKind), + reason: z.enum(MothershipStreamV1ReplayEndReason), + textLength: z.number().int().nonnegative(), +}); +export type MothershipStreamV1ReplayEndPayload = z.infer; + +/** The replay-end frame, validated on its own: it is outside the live envelope union. */ +export const MothershipStreamV1ReplayEndEnvelopeSchema = EnvelopeShellSchema.extend({ + type: z.literal(MothershipStreamV1EventType.run), + payload: MothershipStreamV1ReplayEndPayloadSchema, +}); export type MothershipStreamV1ReplayEndEnvelope = MothershipStreamV1Envelope< typeof MothershipStreamV1EventType.run, diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 6c6e472096a..069ed284a9b 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -271,27 +271,36 @@ export const ChatPayloadSchema = z ctx.addIssue({ code: "custom", message: "Assistant context requires Assistant mode" }); }); +// The stream fields mothership-stream-v1 payloads share. Each is `?: T | undefined`, so +// `.optional()`; the stream file spreads these shapes into its payload schemas. + /** A pause or terminal acknowledges all preceding activity only after the receiver handles it. */ -export interface StreamActivityCheckpoint { - activityReceipt?: StreamActivityReceipt | undefined; -} +export const StreamActivityCheckpointSchema = z.object({ + activityReceipt: ActivityReceiptSchema.optional(), +}); +export type StreamActivityCheckpoint = z.infer; /** Main-assistant text position within this run, measured in UTF-16 code units. */ -export interface StreamTextPosition { - textOffset?: number | undefined; -} +export const StreamTextPositionSchema = z.object({ + textOffset: z.number().int().nonnegative().safe().optional(), +}); +export type StreamTextPosition = z.infer; /** Successful completion states the complete main-answer size, including any replayed prefix. */ -export interface StreamTextCompletion { - textLength?: number | undefined; -} +export const StreamTextCompletionSchema = z.object({ + textLength: z.number().int().nonnegative().safe().optional(), +}); +export type StreamTextCompletion = z.infer; -/** Replayed tool activity is presentation only; it never authorizes execution or approval. */ -export interface StreamToolReplay { - replay?: true | undefined; - /** Requested operation target, authorized independently by Sim. */ - workspaceId?: string | undefined; -} +/** + * Replayed tool activity is presentation only; it never authorizes execution or approval. + * `workspaceId` is the requested operation target, authorized independently by Sim. + */ +export const StreamToolReplaySchema = z.object({ + replay: z.literal(true).optional(), + workspaceId: z.string().optional(), +}); +export type StreamToolReplay = z.infer; /** * How long the worker waits for one handed tool call's result, measured from the hand-off. @@ -299,19 +308,17 @@ export interface StreamToolReplay { * re-run inherits what remains) and settles the call, cancellation included, by * `deadlineMs - TOOL_DEADLINE_SETTLE_MARGIN_MS`: approval wait, pickup, execution and lease * extensions all fit inside it. Sim policy may only end a call sooner. Absent = the - * receiver's own bounds. + * receiver's own bounds. `waitTimeoutMs`, for a workflow tool (`run_workflow`, + * `run_workflow_until_block`, `run_from_block`, `run_block`) on a Sim that declares + * {@link WORKFLOW_TOOL_WAIT_TIMEOUT_CAPABILITY}: how long Sim waits for the call's run to + * settle once it starts waiting on it. A run still going then keeps going and the call settles + * with a {@link WorkflowToolRunningResult}. Absent = held until the run settles. */ -export interface StreamToolDeadline { - deadlineMs?: number | undefined; - /** - * For a workflow tool (`run_workflow`, `run_workflow_until_block`, `run_from_block`, - * `run_block`) on a Sim that declares {@link WORKFLOW_TOOL_WAIT_TIMEOUT_CAPABILITY}: how long - * Sim waits for the call's run to settle once it starts waiting on it. A run still going then - * keeps going and the call settles with a {@link WorkflowToolRunningResult}. Absent = held - * until the run settles. - */ - waitTimeoutMs?: number | undefined; -} +export const StreamToolDeadlineSchema = z.object({ + deadlineMs: z.number().optional(), + waitTimeoutMs: z.number().optional(), +}); +export type StreamToolDeadline = z.infer; /** * Room between Sim settling a call and the worker's own bound for it: Sim's resume-gate diff --git a/apps/sim/lib/mothership/observability/metric-names.ts b/apps/sim/lib/mothership/observability/metric-names.ts index d26fe095e38..95f46aebfef 100644 --- a/apps/sim/lib/mothership/observability/metric-names.ts +++ b/apps/sim/lib/mothership/observability/metric-names.ts @@ -5,6 +5,7 @@ export const Metric = { CopilotDegradedCount: 'copilot.degraded.count', + CopilotStreamContractDisagreements: 'copilot.stream_contract.disagreements', CopilotToolCalls: 'copilot.tool.calls', CopilotToolDuration: 'copilot.tool.duration', } as const diff --git a/apps/sim/lib/mothership/observability/trace-attribute-values.ts b/apps/sim/lib/mothership/observability/trace-attribute-values.ts index 830bcffa42f..150008e5900 100644 --- a/apps/sim/lib/mothership/observability/trace-attribute-values.ts +++ b/apps/sim/lib/mothership/observability/trace-attribute-values.ts @@ -113,6 +113,18 @@ export const CopilotStopOutcome = { ValidationError: 'validation_error', } as const +/** + * Which way the generated stream-contract schema disagrees with Sim's ingest validator on one + * worker frame: `schema_rejects` frames would start failing were the schema the validator. + */ +export const CopilotStreamContractDirection = { + SchemaAccepts: 'schema_accepts', + SchemaRejects: 'schema_rejects', +} as const + +export type CopilotStreamContractDirectionValue = + (typeof CopilotStreamContractDirection)[keyof typeof CopilotStreamContractDirection] + export const CopilotSurface = { Copilot: 'copilot', Mothership: 'mothership', diff --git a/apps/sim/lib/mothership/observability/trace-attributes.ts b/apps/sim/lib/mothership/observability/trace-attributes.ts index def75de8727..3a1207fea16 100644 --- a/apps/sim/lib/mothership/observability/trace-attributes.ts +++ b/apps/sim/lib/mothership/observability/trace-attributes.ts @@ -122,6 +122,9 @@ export const TraceAttr = { CopilotStopContentLength: 'copilot.stop.content_length', CopilotStopOutcome: 'copilot.stop.outcome', CopilotStream: 'copilot.stream', + CopilotStreamContractDirection: 'copilot.stream_contract.direction', + CopilotStreamContractEventType: 'copilot.stream_contract.event_type', + CopilotStreamContractVariant: 'copilot.stream_contract.variant', CopilotSurface: 'copilot.surface', CopilotTableId: 'copilot.table.id', CopilotTableOutcome: 'copilot.table.outcome', diff --git a/apps/sim/lib/mothership/request/metrics.ts b/apps/sim/lib/mothership/request/metrics.ts index e66ddeb42ba..168dc907301 100644 --- a/apps/sim/lib/mothership/request/metrics.ts +++ b/apps/sim/lib/mothership/request/metrics.ts @@ -11,6 +11,7 @@ import { TOOL_CATALOG } from '@/lib/mothership/generated/tool-catalog-v1' import { Metric } from '@/lib/mothership/observability/metric-names' import { type CopilotDegradedReasonValue, + type CopilotStreamContractDirectionValue, ToolExecutor, } from '@/lib/mothership/observability/trace-attribute-values' import { TraceAttr } from '@/lib/mothership/observability/trace-attributes' @@ -25,6 +26,7 @@ interface CopilotMeterInstruments { toolDuration: Histogram toolCalls: Counter degradedCount: Counter + streamContractDisagreements: Counter } let cached: CopilotMeterInstruments | undefined @@ -42,6 +44,7 @@ function instruments(): CopilotMeterInstruments { }), toolCalls: meter.createCounter(Metric.CopilotToolCalls), degradedCount: meter.createCounter(Metric.CopilotDegradedCount), + streamContractDisagreements: meter.createCounter(Metric.CopilotStreamContractDisagreements), } return cached } @@ -92,3 +95,18 @@ export function recordDegraded(reason: CopilotDegradedReasonValue): void { [TraceAttr.CopilotDegradedReason]: reason, }) } + +// recordStreamContractDisagreement counts one worker frame on which Sim's ingest +// validator and the generated contract schema disagree. `eventType` and `variant` +// must already be capped to the contract's own vocabularies (else "other"). +export function recordStreamContractDisagreement( + direction: CopilotStreamContractDirectionValue, + eventType: string, + variant: string +): void { + instruments().streamContractDisagreements.add(1, { + [TraceAttr.CopilotStreamContractDirection]: direction, + [TraceAttr.CopilotStreamContractEventType]: eventType, + [TraceAttr.CopilotStreamContractVariant]: variant, + }) +} diff --git a/apps/sim/lib/mothership/request/session/contract-shadow.test.ts b/apps/sim/lib/mothership/request/session/contract-shadow.test.ts new file mode 100644 index 00000000000..c264ffaf06b --- /dev/null +++ b/apps/sim/lib/mothership/request/session/contract-shadow.test.ts @@ -0,0 +1,283 @@ +/** + * @vitest-environment node + */ +import { getMockLogger } from '@sim/testing/mocks/logger.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { parsePersistedStreamEventEnvelope } from '@/lib/mothership/request/session/contract' +import { parseIngestedStreamEventEnvelope } from '@/lib/mothership/request/session/contract-shadow' + +const { recordStreamContractDisagreement } = vi.hoisted(() => ({ + recordStreamContractDisagreement: vi.fn(), +})) +vi.mock('@/lib/mothership/request/metrics', () => ({ recordStreamContractDisagreement })) + +vi.mock('@/lib/mothership/request/session/contract', async () => { + const actual = await vi.importActual( + '@/lib/mothership/request/session/contract' + ) + return { + ...actual, + parsePersistedStreamEventEnvelope: vi.fn(actual.parsePersistedStreamEventEnvelope), + } +}) + +const logger = getMockLogger('StreamContractShadow') + +const shell = { + v: 1, + seq: 7, + ts: '2026-11-23T00:00:00.000Z', + stream: { streamId: 'stream-1', chatId: 'chat-1' }, + trace: { requestId: 'req-1' }, +} +const toolCall = { + phase: 'call', + toolCallId: 'tool-1', + toolName: 'sim_cli', + executor: 'sim', + mode: 'async', + status: 'executing', + arguments: { argv: ['tables', 'list'] }, + deadlineMs: 600_000, +} +const toolResult = { + phase: 'result', + toolCallId: 'tool-1', + toolName: 'sim_cli', + executor: 'sim', + mode: 'async', + success: true, +} +const argsDelta = { phase: 'args_delta', toolCallId: 'tool-1', toolName: 'sim_cli' } +const spanStart = { kind: 'subagent', event: 'start', agent: 'research' } +const checkpoint = { + kind: 'checkpoint_pause', + checkpointId: 'ckpt-1', + executionId: 'exec-1', + runId: 'run-1', + pendingToolCallIds: ['tool-1'], +} +const complete = { status: 'complete', usage: { input_tokens: 12, output_tokens: 3 } } + +const frame = (type: string, payload: Record, extra: object = {}) => ({ + ...shell, + ...extra, + type, + payload, +}) + +/** + * A representative set of frames the stream validator accepts today that the contract schema + * rejects, one per kind of gap (missing or mistyped field, unknown enum value, the `error`-only + * alias), not an exhaustive list. Each row names the issue path the schema reports. + */ +const SCHEMA_ONLY_REJECTS: Array<[string, Record, string, string]> = [ + [ + 'args_delta without argumentsDelta', + frame('tool', argsDelta), + 'args_delta', + 'payload.argumentsDelta', + ], + [ + 'args_delta with a numeric argumentsDelta', + frame('tool', { ...argsDelta, argumentsDelta: 42 }), + 'args_delta', + 'payload.argumentsDelta', + ], + [ + 'tool call without executor or mode', + frame('tool', { ...toolCall, executor: undefined, mode: undefined }), + 'call', + 'payload.executor', + ], + [ + 'tool call with string arguments', + frame('tool', { ...toolCall, arguments: 'str' }), + 'call', + 'payload.arguments', + ], + [ + 'tool call with a string deadlineMs', + frame('tool', { ...toolCall, deadlineMs: 'soon' }), + 'call', + 'payload.deadlineMs', + ], + [ + 'tool call with an unknown status', + frame('tool', { ...toolCall, status: 'bogus' }), + 'call', + 'payload.status', + ], + [ + 'tool result without success', + frame('tool', { ...toolResult, success: undefined }), + 'result', + 'payload.success', + ], + [ + 'span with an unknown event', + frame('span', { ...spanStart, event: 'middle' }), + 'subagent', + 'payload.event', + ], + ['span with string data', frame('span', { ...spanStart, data: 'x' }), 'subagent', 'payload.data'], + [ + 'checkpoint_pause without checkpointId', + frame('run', { ...checkpoint, checkpointId: undefined }), + 'checkpoint_pause', + 'payload.checkpointId', + ], + [ + 'checkpoint_pause with string pendingToolCallIds', + frame('run', { ...checkpoint, pendingToolCallIds: 'tool-1' }), + 'checkpoint_pause', + 'payload.pendingToolCallIds', + ], + [ + 'steering_applied without steeringId', + frame('run', { kind: 'steering_applied', eventSeq: 3 }), + 'steering_applied', + 'payload.steeringId', + ], + [ + 'complete with an unknown status', + frame('complete', { ...complete, status: 'done' }), + 'none', + 'payload.status', + ], + [ + 'complete with string usage tokens', + frame('complete', { ...complete, usage: { input_tokens: '12' } }), + 'none', + 'payload.usage.input_tokens', + ], + [ + 'error carrying only the `error` alias', + frame('error', { error: 'boom' }), + 'none', + 'payload.message', + ], + [ + 'session start with string data', + frame('session', { kind: 'start', data: 'x' }), + 'start', + 'payload.data', + ], + [ + 'scope with a numeric spanId', + frame( + 'text', + { channel: 'assistant', text: 'hi' }, + { scope: { lane: 'subagent', agentId: 'research', spanId: 7 } } + ), + 'none', + 'scope.spanId', + ], +] + +let clock = Date.UTC(2026, 10, 23) + +describe('parseIngestedStreamEventEnvelope', () => { + beforeEach(() => { + // Each test starts past the previous one's log window, so no test sees another's dedupe. + vi.useFakeTimers() + clock += 24 * 60 * 60 * 1000 + vi.setSystemTime(clock) + }) + + it.each(SCHEMA_ONLY_REJECTS)( + 'keeps accepting %s and reports the schema rejecting it', + (_name, value, variant, path) => { + const result = parseIngestedStreamEventEnvelope(value) + + expect(result).toEqual(parsePersistedStreamEventEnvelope(value)) + expect(result.ok && result.event).toBe(value) + expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith( + 'schema_rejects', + value.type, + variant + ) + expect(logger.warn).toHaveBeenCalledExactlyOnceWith( + 'Stream contract schema disagrees with the stream validator', + expect.objectContaining({ + direction: 'schema_rejects', + eventType: value.type, + issues: expect.arrayContaining([expect.stringMatching(new RegExp(`^${path}: `))]), + }) + ) + } + ) + + it('keeps a rejection the schema would accept and reports it', () => { + const value = frame('tool', { ...toolCall, toolCallId: 'tool-accepted' }) + const rejection = { + ok: false as const, + reason: 'invalid_stream_event' as const, + message: 'A stream event failed validation.', + errors: ['hypothetical'], + } + vi.mocked(parsePersistedStreamEventEnvelope).mockReturnValueOnce(rejection) + + expect(parseIngestedStreamEventEnvelope(value)).toBe(rejection) + expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith( + 'schema_accepts', + 'tool', + 'call' + ) + expect(logger.warn).toHaveBeenCalledExactlyOnceWith( + 'Stream contract schema disagrees with the stream validator', + expect.objectContaining({ direction: 'schema_accepts', validatorErrors: ['hypothetical'] }) + ) + }) + + it('reports nothing when both accept or both reject', () => { + const accepted = frame('tool', toolCall) + expect(parseIngestedStreamEventEnvelope(accepted)).toEqual({ ok: true, event: accepted }) + expect(parseIngestedStreamEventEnvelope(frame('nope', { kind: 'start' })).ok).toBe(false) + expect( + parseIngestedStreamEventEnvelope(frame('run', { kind: 'replay_end', reason: 'cap' })).ok + ).toBe(false) + + expect(recordStreamContractDisagreement).not.toHaveBeenCalled() + expect(logger.warn).not.toHaveBeenCalled() + }) + + it('skips Sim synthetic file-preview frames, which are outside the contract', () => { + const preview = frame('tool', { + previewPhase: 'file_preview_start', + toolCallId: 'tool-1', + toolName: 'prepare_file_edit', + }) + expect(parseIngestedStreamEventEnvelope(preview).ok).toBe(true) + expect(recordStreamContractDisagreement).not.toHaveBeenCalled() + }) + + it('logs a repeated disagreement once per window but counts every frame', () => { + const value = frame('complete', { status: 'complete', usage: { output_tokens: 'many' } }) + + for (let i = 0; i < 3; i++) parseIngestedStreamEventEnvelope(value) + expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(3) + expect(logger.warn).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(10 * 60 * 1000) + parseIngestedStreamEventEnvelope(value) + expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(4) + expect(logger.warn).toHaveBeenCalledTimes(2) + expect(logger.warn).toHaveBeenLastCalledWith( + 'Stream contract schema disagrees with the stream validator', + expect.objectContaining({ suppressedSinceLastLog: 2 }) + ) + }) + + it('rate-limits the warning when the shadow check itself keeps failing', () => { + recordStreamContractDisagreement.mockImplementation(() => { + throw new Error('meter unavailable') + }) + const value = frame('tool', { ...argsDelta, argumentsDelta: 7, toolCallId: 'tool-meter' }) + + for (let i = 0; i < 3; i++) expect(parseIngestedStreamEventEnvelope(value).ok).toBe(true) + expect(logger.warn).toHaveBeenCalledExactlyOnceWith('Stream contract shadow check failed', { + error: 'meter unavailable', + }) + }) +}) diff --git a/apps/sim/lib/mothership/request/session/contract-shadow.ts b/apps/sim/lib/mothership/request/session/contract-shadow.ts new file mode 100644 index 00000000000..6eba1bf12d2 --- /dev/null +++ b/apps/sim/lib/mothership/request/session/contract-shadow.ts @@ -0,0 +1,136 @@ +import { createLogger } from '@sim/logger' +import { getErrorMessage } from '@sim/utils/errors' +import { isRecordLike, toRecord } from '@sim/utils/object' +import { + MothershipStreamV1EventEnvelopeSchema, + MothershipStreamV1ResourceOp, + MothershipStreamV1RunKind, + MothershipStreamV1SessionKind, + MothershipStreamV1SpanPayloadKind, + MothershipStreamV1ToolPhase, +} from '@/lib/mothership/generated/mothership-stream-v1' +import { CopilotStreamContractDirection } from '@/lib/mothership/observability/trace-attribute-values' +import { recordStreamContractDisagreement } from '@/lib/mothership/request/metrics' +import { + KNOWN_EVENT_TYPES, + type ParseStreamEventEnvelopeResult, + parsePersistedStreamEventEnvelope, +} from '@/lib/mothership/request/session/contract' + +/** + * Server-side ingest of worker stream frames, with a shadow check of the generated + * contract schema (mothership-stream-v1, its zod schemas the single source). + * + * `parsePersistedStreamEventEnvelope` keeps deciding every frame. The schema runs beside it + * on the frames the worker sends Sim (the live leg and the run replay), never in the browser, + * and each disagreement is counted and logged, so the frames the schema would newly reject + * are known before it becomes the validator. + */ + +const logger = createLogger('StreamContractShadow') + +/** One log line per distinct disagreement per window; the counter still sees every frame. */ +const LOG_WINDOW_MS = 10 * 60 * 1000 +/** Distinct disagreements remembered at once; past it the oldest is forgotten. */ +const MAX_TRACKED_DISAGREEMENTS = 256 +/** Issue paths kept per log line. */ +const MAX_LOGGED_ISSUES = 8 + +const KNOWN_VARIANTS: ReadonlySet = new Set([ + ...Object.values(MothershipStreamV1SessionKind), + ...Object.values(MothershipStreamV1ToolPhase), + ...Object.values(MothershipStreamV1SpanPayloadKind), + ...Object.values(MothershipStreamV1RunKind), + ...Object.values(MothershipStreamV1ResourceOp), +]) + +const recentDisagreements = new Map() + +/** + * Parses one stream frame a worker sent this server. The verdict is exactly + * `parsePersistedStreamEventEnvelope`'s; the shadow check only observes. + */ +export function parseIngestedStreamEventEnvelope(value: unknown): ParseStreamEventEnvelopeResult { + const result = parsePersistedStreamEventEnvelope(value) + try { + shadowCheck(value, result) + } catch (error) { + const message = getErrorMessage(error) + const suppressed = takeLogSlot(`shadow_check_failed|${message}`) + if (suppressed !== null) { + logger.warn('Stream contract shadow check failed', { + error: message, + ...(suppressed > 0 ? { suppressedSinceLastLog: suppressed } : {}), + }) + } + } + return result +} + +function shadowCheck(value: unknown, result: ParseStreamEventEnvelopeResult): void { + // Sim's own synthetic file-preview frames are outside the contract; only they carry + // `previewPhase`, so the cheap check stands in for re-running the contract validator. + if (result.ok && isRecordLike(value) && toRecord(value.payload).previewPhase !== undefined) return + const schema = MothershipStreamV1EventEnvelopeSchema.safeParse(value) + if (schema.success === result.ok) return + + const direction = result.ok + ? CopilotStreamContractDirection.SchemaRejects + : CopilotStreamContractDirection.SchemaAccepts + const { eventType, variant } = describeFrame(value) + recordStreamContractDisagreement(direction, eventType, variant) + + const issues = schema.success + ? [] + : schema.error.issues + .slice(0, MAX_LOGGED_ISSUES) + .map((issue) => `${issue.path.map(String).join('.') || '(root)'}: ${issue.code}`) + const validatorErrors = result.ok ? [] : (result.errors ?? []) + const key = [direction, eventType, variant, ...issues, ...validatorErrors].join('|') + const suppressed = takeLogSlot(key) + if (suppressed === null) return + + logger.warn('Stream contract schema disagrees with the stream validator', { + direction, + eventType, + variant, + ...(issues.length > 0 ? { issues } : {}), + ...(validatorErrors.length > 0 ? { validatorErrors } : {}), + ...(suppressed > 0 ? { suppressedSinceLastLog: suppressed } : {}), + }) +} + +/** The frame's type and payload discriminant, each capped to the contract's vocabulary. */ +function describeFrame(value: unknown): { eventType: string; variant: string } { + if (!isRecordLike(value)) return { eventType: 'other', variant: 'none' } + const eventType = + typeof value.type === 'string' && KNOWN_EVENT_TYPES.has(value.type) ? value.type : 'other' + const payload = toRecord(value.payload) + const discriminant = payload.phase ?? payload.kind ?? payload.op + if (discriminant === undefined) return { eventType, variant: 'none' } + const variant = + typeof discriminant === 'string' && KNOWN_VARIANTS.has(discriminant) ? discriminant : 'other' + return { eventType, variant } +} + +/** + * Whether this disagreement may be logged now: the number of repeats skipped since its last + * line, or `null` while its window is still open. + */ +function takeLogSlot(key: string): number | null { + const now = Date.now() + const seen = recentDisagreements.get(key) + if (seen && now - seen.loggedAt < LOG_WINDOW_MS) { + seen.suppressed += 1 + return null + } + recentDisagreements.delete(key) + // Every entry is (re)inserted when it logs, so insertion order is `loggedAt` order: the + // oldest entry is the most expired one, and evicting it never drops a live window first. + if (recentDisagreements.size >= MAX_TRACKED_DISAGREEMENTS) { + const oldest = recentDisagreements.keys().next().value + if (oldest !== undefined) recentDisagreements.delete(oldest) + } + recentDisagreements.set(key, { loggedAt: now, suppressed: 0 }) + return seen?.suppressed ?? 0 +} diff --git a/apps/sim/lib/mothership/request/session/contract.ts b/apps/sim/lib/mothership/request/session/contract.ts index 17fc7e16ad0..d2e974c42e5 100644 --- a/apps/sim/lib/mothership/request/session/contract.ts +++ b/apps/sim/lib/mothership/request/session/contract.ts @@ -189,7 +189,10 @@ function isStreamScope(value: unknown): value is MothershipStreamV1StreamScope { // already performs strict schema validation; the client only needs enough // structural checking to safely dispatch inside the switch statement. -const KNOWN_EVENT_TYPES: ReadonlySet = new Set(Object.values(MothershipStreamV1EventType)) +/** The event types the contract names; a frame of any other type is invalid. */ +export const KNOWN_EVENT_TYPES: ReadonlySet = new Set( + Object.values(MothershipStreamV1EventType) +) function isValidEnvelopeShell(value: unknown): value is JsonRecord & { v: 1 diff --git a/apps/sim/lib/mothership/request/session/run-replay.ts b/apps/sim/lib/mothership/request/session/run-replay.ts index 86a65ed656d..8b0af5982aa 100644 --- a/apps/sim/lib/mothership/request/session/run-replay.ts +++ b/apps/sim/lib/mothership/request/session/run-replay.ts @@ -2,13 +2,12 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' 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, MothershipStreamV1ReplayEndKind, - type MothershipStreamV1ReplayEndPayload, - MothershipStreamV1ReplayEndReason, + MothershipStreamV1ReplayEndPayloadSchema, + type MothershipStreamV1ReplayEndReason, } from '@/lib/mothership/generated/mothership-stream-v1' import { StreamReplayRequest } from '@/lib/mothership/generated/protocol' import { TraceAttr } from '@/lib/mothership/observability/trace-attributes' @@ -16,8 +15,8 @@ import { mothershipRequestHeaders } from '@/lib/mothership/request/headers' import { isTerminalStreamStatus, type PersistedStreamEventEnvelope, - parsePersistedStreamEventEnvelope, } from '@/lib/mothership/request/session/contract' +import { parseIngestedStreamEventEnvelope } from '@/lib/mothership/request/session/contract-shadow' import { toReplayEnvelope } from '@/lib/mothership/request/session/types' import { fetchWorker } from '@/lib/mothership/request/worker/fetch' import { FatalSseEventError, processSSEStream } from '@/lib/mothership/request/worker/parser' @@ -98,12 +97,6 @@ export async function openRunReplay(params: { return response.body } -const ReplayEndPayloadSchema = z.object({ - kind: z.literal(MothershipStreamV1ReplayEndKind), - reason: z.enum(MothershipStreamV1ReplayEndReason), - textLength: z.number().int().nonnegative(), -}) satisfies z.ZodType - /** * 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 @@ -113,7 +106,7 @@ function replayEnd(value: unknown): RunReplayEnd | null { if (!isRecordLike(value) || value.type !== MothershipStreamV1EventType.run) return null const payload = toRecord(value.payload) if (payload.kind !== MothershipStreamV1ReplayEndKind) return null - const parsed = ReplayEndPayloadSchema.safeParse(payload) + const parsed = MothershipStreamV1ReplayEndPayloadSchema.safeParse(payload) if (parsed.success) return parsed.data.reason logger.warn('Run replay ended with a malformed replay-end frame', { reason: payload.reason, @@ -142,7 +135,7 @@ async function readRunReplay( end = control return true } - const parsed = parsePersistedStreamEventEnvelope(raw) + const parsed = parseIngestedStreamEventEnvelope(raw) if (!parsed.ok) throw new FatalSseEventError(`Invalid run replay event: ${parsed.message}`) if (!onEvent(parsed.event)) return true if (parsed.event.type === MothershipStreamV1EventType.complete) { diff --git a/apps/sim/lib/mothership/request/worker/stream.ts b/apps/sim/lib/mothership/request/worker/stream.ts index 8d4ea9bddca..0e278b0b564 100644 --- a/apps/sim/lib/mothership/request/worker/stream.ts +++ b/apps/sim/lib/mothership/request/worker/stream.ts @@ -17,12 +17,8 @@ import { flushThinkingBlock, } from '@/lib/mothership/request/handlers/types' import { getCopilotTracer } from '@/lib/mothership/request/otel' -import { - AbortReason, - eventToStreamEvent, - hasAbortMarker, - parsePersistedStreamEventEnvelope, -} from '@/lib/mothership/request/session' +import { AbortReason, eventToStreamEvent, hasAbortMarker } from '@/lib/mothership/request/session' +import { parseIngestedStreamEventEnvelope } from '@/lib/mothership/request/session/contract-shadow' import { forgetToolCallEvent, shouldSkipToolCallEvent, @@ -373,7 +369,7 @@ export async function runStreamLoop( } await options.assertControllerOwnership?.() - const parsedEvent = parsePersistedStreamEventEnvelope(raw) + const parsedEvent = parseIngestedStreamEventEnvelope(raw) if (!parsedEvent.ok) { const detail = [parsedEvent.message, ...(parsedEvent.errors ?? [])] .filter(Boolean) From 258b0b0b841732bafe03fc9c29f8dbdb0be82ece Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 23 Nov 2026 13:27:09 -0800 Subject: [PATCH 2/2] improvement(mothership): tighten the stream contract shadow's skip and dedupe The shadow skipped any accepted frame carrying a payload previewPhase, so a worker frame with a stray previewPhase hid its schema rejection. It now skips only a frame the contract check rejects, which is exactly one the validator accepted as a synthetic file-preview frame; the previewPhase test stays as the cheap prefilter. A test pins the stray-field case. The log dedupe is an lru-cache (max 256, ttl the ten-minute window, read against Date.now) instead of a hand-rolled TTL map, still reporting the repeats skipped since the last line. Takes the regenerated protocol contract, whose tool deadlines are positive integers, and documents the new metric recorder and direction type with TSDoc. --- apps/sim/lib/mothership/generated/protocol.ts | 4 +- .../observability/trace-attribute-values.ts | 1 + apps/sim/lib/mothership/request/metrics.ts | 8 +-- .../request/session/contract-shadow.test.ts | 18 ++++++- .../request/session/contract-shadow.ts | 52 ++++++++++++------- 5 files changed, 59 insertions(+), 24 deletions(-) diff --git a/apps/sim/lib/mothership/generated/protocol.ts b/apps/sim/lib/mothership/generated/protocol.ts index 069ed284a9b..4cd2319d58d 100644 --- a/apps/sim/lib/mothership/generated/protocol.ts +++ b/apps/sim/lib/mothership/generated/protocol.ts @@ -315,8 +315,8 @@ export type StreamToolReplay = z.infer; * with a {@link WorkflowToolRunningResult}. Absent = held until the run settles. */ export const StreamToolDeadlineSchema = z.object({ - deadlineMs: z.number().optional(), - waitTimeoutMs: z.number().optional(), + deadlineMs: z.number().int().positive().optional(), + waitTimeoutMs: z.number().int().positive().optional(), }); export type StreamToolDeadline = z.infer; diff --git a/apps/sim/lib/mothership/observability/trace-attribute-values.ts b/apps/sim/lib/mothership/observability/trace-attribute-values.ts index 150008e5900..cb392fc4d39 100644 --- a/apps/sim/lib/mothership/observability/trace-attribute-values.ts +++ b/apps/sim/lib/mothership/observability/trace-attribute-values.ts @@ -122,6 +122,7 @@ export const CopilotStreamContractDirection = { SchemaRejects: 'schema_rejects', } as const +/** One {@link CopilotStreamContractDirection} value, as the metric label carries it. */ export type CopilotStreamContractDirectionValue = (typeof CopilotStreamContractDirection)[keyof typeof CopilotStreamContractDirection] diff --git a/apps/sim/lib/mothership/request/metrics.ts b/apps/sim/lib/mothership/request/metrics.ts index 168dc907301..7d0fe33e4c3 100644 --- a/apps/sim/lib/mothership/request/metrics.ts +++ b/apps/sim/lib/mothership/request/metrics.ts @@ -96,9 +96,11 @@ export function recordDegraded(reason: CopilotDegradedReasonValue): void { }) } -// recordStreamContractDisagreement counts one worker frame on which Sim's ingest -// validator and the generated contract schema disagree. `eventType` and `variant` -// must already be capped to the contract's own vocabularies (else "other"). +/** + * Counts one worker frame on which Sim's ingest validator and the generated contract schema + * disagree. `eventType` and `variant` must already be capped to the contract's own + * vocabularies (else "other"). + */ export function recordStreamContractDisagreement( direction: CopilotStreamContractDirectionValue, eventType: string, diff --git a/apps/sim/lib/mothership/request/session/contract-shadow.test.ts b/apps/sim/lib/mothership/request/session/contract-shadow.test.ts index c264ffaf06b..caa7c8538de 100644 --- a/apps/sim/lib/mothership/request/session/contract-shadow.test.ts +++ b/apps/sim/lib/mothership/request/session/contract-shadow.test.ts @@ -252,6 +252,22 @@ describe('parseIngestedStreamEventEnvelope', () => { expect(recordStreamContractDisagreement).not.toHaveBeenCalled() }) + it('still compares a worker frame that carries a stray previewPhase', () => { + // Shaped to pass the synthetic check too, but the contract check accepts it first. + const stray = frame('tool', { + phase: 'call', + previewPhase: 'file_preview_start', + toolCallId: 'tool-stray', + toolName: 'prepare_file_edit', + }) + expect(parseIngestedStreamEventEnvelope(stray)).toEqual({ ok: true, event: stray }) + expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith( + 'schema_rejects', + 'tool', + 'call' + ) + }) + it('logs a repeated disagreement once per window but counts every frame', () => { const value = frame('complete', { status: 'complete', usage: { output_tokens: 'many' } }) @@ -259,7 +275,7 @@ describe('parseIngestedStreamEventEnvelope', () => { expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(3) expect(logger.warn).toHaveBeenCalledTimes(1) - vi.advanceTimersByTime(10 * 60 * 1000) + vi.advanceTimersByTime(10 * 60 * 1000 + 1) parseIngestedStreamEventEnvelope(value) expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(4) expect(logger.warn).toHaveBeenCalledTimes(2) diff --git a/apps/sim/lib/mothership/request/session/contract-shadow.ts b/apps/sim/lib/mothership/request/session/contract-shadow.ts index 6eba1bf12d2..2484e77b0a6 100644 --- a/apps/sim/lib/mothership/request/session/contract-shadow.ts +++ b/apps/sim/lib/mothership/request/session/contract-shadow.ts @@ -1,6 +1,7 @@ import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' import { isRecordLike, toRecord } from '@sim/utils/object' +import { LRUCache } from 'lru-cache' import { MothershipStreamV1EventEnvelopeSchema, MothershipStreamV1ResourceOp, @@ -12,6 +13,7 @@ import { import { CopilotStreamContractDirection } from '@/lib/mothership/observability/trace-attribute-values' import { recordStreamContractDisagreement } from '@/lib/mothership/request/metrics' import { + isContractStreamEventEnvelope, KNOWN_EVENT_TYPES, type ParseStreamEventEnvelopeResult, parsePersistedStreamEventEnvelope, @@ -31,7 +33,7 @@ const logger = createLogger('StreamContractShadow') /** One log line per distinct disagreement per window; the counter still sees every frame. */ const LOG_WINDOW_MS = 10 * 60 * 1000 -/** Distinct disagreements remembered at once; past it the oldest is forgotten. */ +/** Memory backstop on distinct disagreements tracked within one window. */ const MAX_TRACKED_DISAGREEMENTS = 256 /** Issue paths kept per log line. */ const MAX_LOGGED_ISSUES = 8 @@ -44,7 +46,15 @@ const KNOWN_VARIANTS: ReadonlySet = new Set([ ...Object.values(MothershipStreamV1ResourceOp), ]) -const recentDisagreements = new Map() +/** Each logged disagreement, live for its window, with the repeats skipped since it logged. */ +const recentDisagreements = new LRUCache({ + max: MAX_TRACKED_DISAGREEMENTS, + ttl: LOG_WINDOW_MS, + // Wall-clock windows read fresh on every check (no timer-cached `now`): one clock read per + // disagreement costs nothing, and it is the clock tests move. + perf: { now: () => Date.now() }, + ttlResolution: 0, +}) /** * Parses one stream frame a worker sent this server. The verdict is exactly @@ -68,9 +78,7 @@ export function parseIngestedStreamEventEnvelope(value: unknown): ParseStreamEve } function shadowCheck(value: unknown, result: ParseStreamEventEnvelopeResult): void { - // Sim's own synthetic file-preview frames are outside the contract; only they carry - // `previewPhase`, so the cheap check stands in for re-running the contract validator. - if (result.ok && isRecordLike(value) && toRecord(value.payload).previewPhase !== undefined) return + if (result.ok && acceptedAsSyntheticPreview(value)) return const schema = MothershipStreamV1EventEnvelopeSchema.safeParse(value) if (schema.success === result.ok) return @@ -100,6 +108,21 @@ function shadowCheck(value: unknown, result: ParseStreamEventEnvelopeResult): vo }) } +/** + * Whether the validator accepted this frame as one of Sim's synthetic file-preview frames, + * which are outside the contract. It tries the contract first, so that is exactly a frame the + * contract check rejects; only a payload with `previewPhase` can be one, which keeps the + * re-check off every other frame. A worker frame with a stray `previewPhase` that passes the + * contract check is still compared. + */ +function acceptedAsSyntheticPreview(value: unknown): boolean { + return ( + isRecordLike(value) && + toRecord(value.payload).previewPhase !== undefined && + !isContractStreamEventEnvelope(value) + ) +} + /** The frame's type and payload discriminant, each capped to the contract's vocabulary. */ function describeFrame(value: unknown): { eventType: string; variant: string } { if (!isRecordLike(value)) return { eventType: 'other', variant: 'none' } @@ -118,19 +141,12 @@ function describeFrame(value: unknown): { eventType: string; variant: string } { * line, or `null` while its window is still open. */ function takeLogSlot(key: string): number | null { - const now = Date.now() - const seen = recentDisagreements.get(key) - if (seen && now - seen.loggedAt < LOG_WINDOW_MS) { - seen.suppressed += 1 + const live = recentDisagreements.peek(key) + if (live) { + live.suppressed += 1 return null } - recentDisagreements.delete(key) - // Every entry is (re)inserted when it logs, so insertion order is `loggedAt` order: the - // oldest entry is the most expired one, and evicting it never drops a live window first. - if (recentDisagreements.size >= MAX_TRACKED_DISAGREEMENTS) { - const oldest = recentDisagreements.keys().next().value - if (oldest !== undefined) recentDisagreements.delete(oldest) - } - recentDisagreements.set(key, { loggedAt: now, suppressed: 0 }) - return seen?.suppressed ?? 0 + const expired = recentDisagreements.peek(key, { allowStale: true }) + recentDisagreements.set(key, { suppressed: 0 }) + return expired?.suppressed ?? 0 }