11import { createLogger } from '@sim/logger'
22import { getErrorMessage } from '@sim/utils/errors'
33import { isRecordLike , toRecord } from '@sim/utils/object'
4+ import { LRUCache } from 'lru-cache'
45import {
56 MothershipStreamV1EventEnvelopeSchema ,
67 MothershipStreamV1ResourceOp ,
@@ -12,6 +13,7 @@ import {
1213import { CopilotStreamContractDirection } from '@/lib/mothership/observability/trace-attribute-values'
1314import { recordStreamContractDisagreement } from '@/lib/mothership/request/metrics'
1415import {
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. */
3335const 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 . */
3537const MAX_TRACKED_DISAGREEMENTS = 256
3638/** Issue paths kept per log line. */
3739const 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
7080function 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. */
104127function 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 */
120143function 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