Skip to content

Commit 258b0b0

Browse files
committed
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 2b87d3a commit 258b0b0

5 files changed

Lines changed: 59 additions & 24 deletions

File tree

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -315,8 +315,8 @@ export type StreamToolReplay = z.infer<typeof StreamToolReplaySchema>;
315315
* with a {@link WorkflowToolRunningResult}. Absent = held until the run settles.
316316
*/
317317
export const StreamToolDeadlineSchema = z.object({
318-
deadlineMs: z.number().optional(),
319-
waitTimeoutMs: z.number().optional(),
318+
deadlineMs: z.number().int().positive().optional(),
319+
waitTimeoutMs: z.number().int().positive().optional(),
320320
});
321321
export type StreamToolDeadline = z.infer<typeof StreamToolDeadlineSchema>;
322322

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ export const CopilotStreamContractDirection = {
122122
SchemaRejects: 'schema_rejects',
123123
} as const
124124

125+
/** One {@link CopilotStreamContractDirection} value, as the metric label carries it. */
125126
export type CopilotStreamContractDirectionValue =
126127
(typeof CopilotStreamContractDirection)[keyof typeof CopilotStreamContractDirection]
127128

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,9 +96,11 @@ export function recordDegraded(reason: CopilotDegradedReasonValue): void {
9696
})
9797
}
9898

99-
// recordStreamContractDisagreement counts one worker frame on which Sim's ingest
100-
// validator and the generated contract schema disagree. `eventType` and `variant`
101-
// must already be capped to the contract's own vocabularies (else "other").
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+
*/
102104
export function recordStreamContractDisagreement(
103105
direction: CopilotStreamContractDirectionValue,
104106
eventType: string,

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,14 +252,30 @@ describe('parseIngestedStreamEventEnvelope', () => {
252252
expect(recordStreamContractDisagreement).not.toHaveBeenCalled()
253253
})
254254

255+
it('still compares a worker frame that carries a stray previewPhase', () => {
256+
// Shaped to pass the synthetic check too, but the contract check accepts it first.
257+
const stray = frame('tool', {
258+
phase: 'call',
259+
previewPhase: 'file_preview_start',
260+
toolCallId: 'tool-stray',
261+
toolName: 'prepare_file_edit',
262+
})
263+
expect(parseIngestedStreamEventEnvelope(stray)).toEqual({ ok: true, event: stray })
264+
expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith(
265+
'schema_rejects',
266+
'tool',
267+
'call'
268+
)
269+
})
270+
255271
it('logs a repeated disagreement once per window but counts every frame', () => {
256272
const value = frame('complete', { status: 'complete', usage: { output_tokens: 'many' } })
257273

258274
for (let i = 0; i < 3; i++) parseIngestedStreamEventEnvelope(value)
259275
expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(3)
260276
expect(logger.warn).toHaveBeenCalledTimes(1)
261277

262-
vi.advanceTimersByTime(10 * 60 * 1000)
278+
vi.advanceTimersByTime(10 * 60 * 1000 + 1)
263279
parseIngestedStreamEventEnvelope(value)
264280
expect(recordStreamContractDisagreement).toHaveBeenCalledTimes(4)
265281
expect(logger.warn).toHaveBeenCalledTimes(2)

‎apps/sim/lib/mothership/request/session/contract-shadow.ts‎

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createLogger } from '@sim/logger'
22
import { getErrorMessage } from '@sim/utils/errors'
33
import { isRecordLike, toRecord } from '@sim/utils/object'
4+
import { LRUCache } from 'lru-cache'
45
import {
56
MothershipStreamV1EventEnvelopeSchema,
67
MothershipStreamV1ResourceOp,
@@ -12,6 +13,7 @@ import {
1213
import { CopilotStreamContractDirection } from '@/lib/mothership/observability/trace-attribute-values'
1314
import { recordStreamContractDisagreement } from '@/lib/mothership/request/metrics'
1415
import {
16+
isContractStreamEventEnvelope,
1517
KNOWN_EVENT_TYPES,
1618
type ParseStreamEventEnvelopeResult,
1719
parsePersistedStreamEventEnvelope,
@@ -31,7 +33,7 @@ const logger = createLogger('StreamContractShadow')
3133

3234
/** One log line per distinct disagreement per window; the counter still sees every frame. */
3335
const LOG_WINDOW_MS = 10 * 60 * 1000
34-
/** Distinct disagreements remembered at once; past it the oldest is forgotten. */
36+
/** Memory backstop on distinct disagreements tracked within one window. */
3537
const MAX_TRACKED_DISAGREEMENTS = 256
3638
/** Issue paths kept per log line. */
3739
const MAX_LOGGED_ISSUES = 8
@@ -44,7 +46,15 @@ const KNOWN_VARIANTS: ReadonlySet<string> = new Set<string>([
4446
...Object.values(MothershipStreamV1ResourceOp),
4547
])
4648

47-
const recentDisagreements = new Map<string, { loggedAt: number; suppressed: number }>()
49+
/** Each logged disagreement, live for its window, with the repeats skipped since it logged. */
50+
const recentDisagreements = new LRUCache<string, { suppressed: number }>({
51+
max: MAX_TRACKED_DISAGREEMENTS,
52+
ttl: LOG_WINDOW_MS,
53+
// Wall-clock windows read fresh on every check (no timer-cached `now`): one clock read per
54+
// disagreement costs nothing, and it is the clock tests move.
55+
perf: { now: () => Date.now() },
56+
ttlResolution: 0,
57+
})
4858

4959
/**
5060
* Parses one stream frame a worker sent this server. The verdict is exactly
@@ -68,9 +78,7 @@ export function parseIngestedStreamEventEnvelope(value: unknown): ParseStreamEve
6878
}
6979

7080
function shadowCheck(value: unknown, result: ParseStreamEventEnvelopeResult): void {
71-
// Sim's own synthetic file-preview frames are outside the contract; only they carry
72-
// `previewPhase`, so the cheap check stands in for re-running the contract validator.
73-
if (result.ok && isRecordLike(value) && toRecord(value.payload).previewPhase !== undefined) return
81+
if (result.ok && acceptedAsSyntheticPreview(value)) return
7482
const schema = MothershipStreamV1EventEnvelopeSchema.safeParse(value)
7583
if (schema.success === result.ok) return
7684

@@ -100,6 +108,21 @@ function shadowCheck(value: unknown, result: ParseStreamEventEnvelopeResult): vo
100108
})
101109
}
102110

111+
/**
112+
* Whether the validator accepted this frame as one of Sim's synthetic file-preview frames,
113+
* which are outside the contract. It tries the contract first, so that is exactly a frame the
114+
* contract check rejects; only a payload with `previewPhase` can be one, which keeps the
115+
* re-check off every other frame. A worker frame with a stray `previewPhase` that passes the
116+
* contract check is still compared.
117+
*/
118+
function acceptedAsSyntheticPreview(value: unknown): boolean {
119+
return (
120+
isRecordLike(value) &&
121+
toRecord(value.payload).previewPhase !== undefined &&
122+
!isContractStreamEventEnvelope(value)
123+
)
124+
}
125+
103126
/** The frame's type and payload discriminant, each capped to the contract's vocabulary. */
104127
function describeFrame(value: unknown): { eventType: string; variant: string } {
105128
if (!isRecordLike(value)) return { eventType: 'other', variant: 'none' }
@@ -118,19 +141,12 @@ function describeFrame(value: unknown): { eventType: string; variant: string } {
118141
* line, or `null` while its window is still open.
119142
*/
120143
function takeLogSlot(key: string): number | null {
121-
const now = Date.now()
122-
const seen = recentDisagreements.get(key)
123-
if (seen && now - seen.loggedAt < LOG_WINDOW_MS) {
124-
seen.suppressed += 1
144+
const live = recentDisagreements.peek(key)
145+
if (live) {
146+
live.suppressed += 1
125147
return null
126148
}
127-
recentDisagreements.delete(key)
128-
// Every entry is (re)inserted when it logs, so insertion order is `loggedAt` order: the
129-
// oldest entry is the most expired one, and evicting it never drops a live window first.
130-
if (recentDisagreements.size >= MAX_TRACKED_DISAGREEMENTS) {
131-
const oldest = recentDisagreements.keys().next().value
132-
if (oldest !== undefined) recentDisagreements.delete(oldest)
133-
}
134-
recentDisagreements.set(key, { loggedAt: now, suppressed: 0 })
135-
return seen?.suppressed ?? 0
149+
const expired = recentDisagreements.peek(key, { allowStale: true })
150+
recentDisagreements.set(key, { suppressed: 0 })
151+
return expired?.suppressed ?? 0
136152
}

0 commit comments

Comments
 (0)