Skip to content

Commit 3139326

Browse files
authored
improvement(mothership): shadow-check worker stream frames against the contract schemas (#10354)
* 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. * 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.
1 parent b627a8b commit 3139326

11 files changed

Lines changed: 873 additions & 301 deletions

File tree

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

Lines changed: 339 additions & 254 deletions
Large diffs are not rendered by default.

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

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -271,47 +271,54 @@ export const ChatPayloadSchema = z
271271
ctx.addIssue({ code: "custom", message: "Assistant context requires Assistant mode" });
272272
});
273273

274+
// The stream fields mothership-stream-v1 payloads share. Each is `?: T | undefined`, so
275+
// `.optional()`; the stream file spreads these shapes into its payload schemas.
276+
274277
/** A pause or terminal acknowledges all preceding activity only after the receiver handles it. */
275-
export interface StreamActivityCheckpoint {
276-
activityReceipt?: StreamActivityReceipt | undefined;
277-
}
278+
export const StreamActivityCheckpointSchema = z.object({
279+
activityReceipt: ActivityReceiptSchema.optional(),
280+
});
281+
export type StreamActivityCheckpoint = z.infer<typeof StreamActivityCheckpointSchema>;
278282

279283
/** Main-assistant text position within this run, measured in UTF-16 code units. */
280-
export interface StreamTextPosition {
281-
textOffset?: number | undefined;
282-
}
284+
export const StreamTextPositionSchema = z.object({
285+
textOffset: z.number().int().nonnegative().safe().optional(),
286+
});
287+
export type StreamTextPosition = z.infer<typeof StreamTextPositionSchema>;
283288

284289
/** Successful completion states the complete main-answer size, including any replayed prefix. */
285-
export interface StreamTextCompletion {
286-
textLength?: number | undefined;
287-
}
290+
export const StreamTextCompletionSchema = z.object({
291+
textLength: z.number().int().nonnegative().safe().optional(),
292+
});
293+
export type StreamTextCompletion = z.infer<typeof StreamTextCompletionSchema>;
288294

289-
/** Replayed tool activity is presentation only; it never authorizes execution or approval. */
290-
export interface StreamToolReplay {
291-
replay?: true | undefined;
292-
/** Requested operation target, authorized independently by Sim. */
293-
workspaceId?: string | undefined;
294-
}
295+
/**
296+
* Replayed tool activity is presentation only; it never authorizes execution or approval.
297+
* `workspaceId` is the requested operation target, authorized independently by Sim.
298+
*/
299+
export const StreamToolReplaySchema = z.object({
300+
replay: z.literal(true).optional(),
301+
workspaceId: z.string().optional(),
302+
});
303+
export type StreamToolReplay = z.infer<typeof StreamToolReplaySchema>;
295304

296305
/**
297306
* How long the worker waits for one handed tool call's result, measured from the hand-off.
298307
* Sim converts it to an absolute deadline on receipt, persists it with the call (a takeover
299308
* re-run inherits what remains) and settles the call, cancellation included, by
300309
* `deadlineMs - TOOL_DEADLINE_SETTLE_MARGIN_MS`: approval wait, pickup, execution and lease
301310
* extensions all fit inside it. Sim policy may only end a call sooner. Absent = the
302-
* receiver's own bounds.
311+
* receiver's own bounds. `waitTimeoutMs`, for a workflow tool (`run_workflow`,
312+
* `run_workflow_until_block`, `run_from_block`, `run_block`) on a Sim that declares
313+
* {@link WORKFLOW_TOOL_WAIT_TIMEOUT_CAPABILITY}: how long Sim waits for the call's run to
314+
* settle once it starts waiting on it. A run still going then keeps going and the call settles
315+
* with a {@link WorkflowToolRunningResult}. Absent = held until the run settles.
303316
*/
304-
export interface StreamToolDeadline {
305-
deadlineMs?: number | undefined;
306-
/**
307-
* For a workflow tool (`run_workflow`, `run_workflow_until_block`, `run_from_block`,
308-
* `run_block`) on a Sim that declares {@link WORKFLOW_TOOL_WAIT_TIMEOUT_CAPABILITY}: how long
309-
* Sim waits for the call's run to settle once it starts waiting on it. A run still going then
310-
* keeps going and the call settles with a {@link WorkflowToolRunningResult}. Absent = held
311-
* until the run settles.
312-
*/
313-
waitTimeoutMs?: number | undefined;
314-
}
317+
export const StreamToolDeadlineSchema = z.object({
318+
deadlineMs: z.number().int().positive().optional(),
319+
waitTimeoutMs: z.number().int().positive().optional(),
320+
});
321+
export type StreamToolDeadline = z.infer<typeof StreamToolDeadlineSchema>;
315322

316323
/**
317324
* Room between Sim settling a call and the worker's own bound for it: Sim's resume-gate

‎apps/sim/lib/mothership/observability/metric-names.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
export const Metric = {
77
CopilotDegradedCount: 'copilot.degraded.count',
8+
CopilotStreamContractDisagreements: 'copilot.stream_contract.disagreements',
89
CopilotToolCalls: 'copilot.tool.calls',
910
CopilotToolDuration: 'copilot.tool.duration',
1011
} as const

‎apps/sim/lib/mothership/observability/trace-attribute-values.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,19 @@ export const CopilotStopOutcome = {
113113
ValidationError: 'validation_error',
114114
} as const
115115

116+
/**
117+
* Which way the generated stream-contract schema disagrees with Sim's ingest validator on one
118+
* worker frame: `schema_rejects` frames would start failing were the schema the validator.
119+
*/
120+
export const CopilotStreamContractDirection = {
121+
SchemaAccepts: 'schema_accepts',
122+
SchemaRejects: 'schema_rejects',
123+
} as const
124+
125+
/** One {@link CopilotStreamContractDirection} value, as the metric label carries it. */
126+
export type CopilotStreamContractDirectionValue =
127+
(typeof CopilotStreamContractDirection)[keyof typeof CopilotStreamContractDirection]
128+
116129
export const CopilotSurface = {
117130
Copilot: 'copilot',
118131
Mothership: 'mothership',

‎apps/sim/lib/mothership/observability/trace-attributes.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ export const TraceAttr = {
122122
CopilotStopContentLength: 'copilot.stop.content_length',
123123
CopilotStopOutcome: 'copilot.stop.outcome',
124124
CopilotStream: 'copilot.stream',
125+
CopilotStreamContractDirection: 'copilot.stream_contract.direction',
126+
CopilotStreamContractEventType: 'copilot.stream_contract.event_type',
127+
CopilotStreamContractVariant: 'copilot.stream_contract.variant',
125128
CopilotSurface: 'copilot.surface',
126129
CopilotTableId: 'copilot.table.id',
127130
CopilotTableOutcome: 'copilot.table.outcome',

‎apps/sim/lib/mothership/request/metrics.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { TOOL_CATALOG } from '@/lib/mothership/generated/tool-catalog-v1'
1111
import { Metric } from '@/lib/mothership/observability/metric-names'
1212
import {
1313
type CopilotDegradedReasonValue,
14+
type CopilotStreamContractDirectionValue,
1415
ToolExecutor,
1516
} from '@/lib/mothership/observability/trace-attribute-values'
1617
import { TraceAttr } from '@/lib/mothership/observability/trace-attributes'
@@ -25,6 +26,7 @@ interface CopilotMeterInstruments {
2526
toolDuration: Histogram
2627
toolCalls: Counter
2728
degradedCount: Counter
29+
streamContractDisagreements: Counter
2830
}
2931

3032
let cached: CopilotMeterInstruments | undefined
@@ -42,6 +44,7 @@ function instruments(): CopilotMeterInstruments {
4244
}),
4345
toolCalls: meter.createCounter(Metric.CopilotToolCalls),
4446
degradedCount: meter.createCounter(Metric.CopilotDegradedCount),
47+
streamContractDisagreements: meter.createCounter(Metric.CopilotStreamContractDisagreements),
4548
}
4649
return cached
4750
}
@@ -92,3 +95,20 @@ export function recordDegraded(reason: CopilotDegradedReasonValue): void {
9295
[TraceAttr.CopilotDegradedReason]: reason,
9396
})
9497
}
98+
99+
/**
100+
* Counts one worker frame on which Sim's ingest validator and the generated contract schema
101+
* disagree. `eventType` and `variant` must already be capped to the contract's own
102+
* vocabularies (else "other").
103+
*/
104+
export function recordStreamContractDisagreement(
105+
direction: CopilotStreamContractDirectionValue,
106+
eventType: string,
107+
variant: string
108+
): void {
109+
instruments().streamContractDisagreements.add(1, {
110+
[TraceAttr.CopilotStreamContractDirection]: direction,
111+
[TraceAttr.CopilotStreamContractEventType]: eventType,
112+
[TraceAttr.CopilotStreamContractVariant]: variant,
113+
})
114+
}

0 commit comments

Comments
 (0)