Skip to content

Commit fb545bd

Browse files
authored
fix(mothership): strip unknown resource owner keys and tighten contract follow-ups (#10376)
* docs(mothership): say the stream validator is the one verdict on every frame * test(mothership): pin the schema-accepts shadow case on a real frame * fix(workflows): offer the ollama model example only where ollama can run * fix(mothership): sync the resource owner strip and stream contract notes from the worker A resource frame whose owner carries a key a newer worker added no longer fails Sim's resource check (ResourcePayload): the owner now strips unknown keys. Copies of worker/packages/contracts resources.ts and mothership-stream-v1.ts. * docs(mothership): note that resource payloads use their generated schema
1 parent 17b32fb commit fb545bd

6 files changed

Lines changed: 58 additions & 33 deletions

File tree

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

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44
// The mothership-stream-v1 SSE wire: every `data:` frame the worker emits to Sim (each leg
55
// ends with a literal `data: [DONE]` line), and the vocabulary Sim re-emits to the browser
66
// (Sim adds `session` chat/title frames of its own).
7-
// The zod schemas below are the single source (D122): every type is inferred from them, so the
8-
// worker's emitter (apps/server/src/protocol/envelope.ts) fails typecheck on a frame that drifts,
9-
// and a reader can validate a frame at runtime against the same definition. Each discriminant
10-
// const below is checked against its payload union, because Sim's reader accepts exactly the
11-
// const's values. Objects strip unknown keys: a newer emitter's extra field never fails a reader.
7+
// The zod schemas below are the single source (D122): every payload type is inferred from them,
8+
// so the worker's emitter (apps/server/src/protocol/envelope.ts) fails typecheck on a frame that
9+
// drifts, and a reader can validate a frame at runtime against the same definition. Each
10+
// discriminant const below is checked against its payload union, because Sim's reader accepts
11+
// exactly the const's values. Objects strip unknown keys: a newer emitter's extra field never
12+
// fails a reader, except in a `resource` payload's `resource.search.nativeQueries` entries, which
13+
// reuse Sim's strict model tool-input schema.
1214
// Its own optional fields are `?: T` (`.exactOptional()`); the protocol.ts fields it spreads
1315
// are `?: T | undefined`.
1416

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,11 @@ export const SearchResource = z.object({
4141
});
4242
export type SearchResource = z.infer<typeof SearchResource>;
4343

44+
/** Resource frames and tool output cross versions, so an owner's unknown keys strip. */
45+
const ResourceOwner = z.object(FileOwner.shape);
46+
4447
export const ResourceAddress = z.object({
45-
owner: FileOwner.optional(),
48+
owner: ResourceOwner.optional(),
4649
workspaceId: z.uuid().optional(),
4750
workspaceName: z.string().optional(),
4851
type: ResourceType,
@@ -93,7 +96,7 @@ export const ResourceChange = z.discriminatedUnion("op", [
9396
resource: z.union([
9497
z.object({
9598
type: ResourceType,
96-
owner: FileOwner.optional(),
99+
owner: ResourceOwner.optional(),
97100
workspaceId: z.uuid().optional(),
98101
id: z.string().regex(/\S/).optional(),
99102
}),

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

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,6 @@ const { recordStreamContractDisagreement } = vi.hoisted(() => ({
1111
}))
1212
vi.mock('@/lib/mothership/request/metrics', () => ({ recordStreamContractDisagreement }))
1313

14-
vi.mock('@/lib/mothership/request/session/contract', async () => {
15-
const actual = await vi.importActual<typeof import('@/lib/mothership/request/session/contract')>(
16-
'@/lib/mothership/request/session/contract'
17-
)
18-
return {
19-
...actual,
20-
parsePersistedStreamEventEnvelope: vi.fn(actual.parsePersistedStreamEventEnvelope),
21-
}
22-
})
23-
2414
const logger = getMockLogger('StreamContractShadow')
2515

2616
const shell = {
@@ -209,24 +199,25 @@ describe('parseIngestedStreamEventEnvelope', () => {
209199
)
210200

211201
it('keeps a rejection the schema would accept and reports it', () => {
212-
const value = frame('tool', { ...toolCall, toolCallId: 'tool-accepted' })
213-
const rejection = {
214-
ok: false as const,
215-
reason: 'invalid_stream_event' as const,
216-
message: 'A stream event failed validation.',
217-
errors: ['hypothetical'],
218-
}
219-
vi.mocked(parsePersistedStreamEventEnvelope).mockReturnValueOnce(rejection)
202+
// The validator rejects a null activityReceipt; the schema does not declare the key and
203+
// strips it. This fails by design once the two are aligned: then pick another real split.
204+
const value = frame('run', { kind: 'compaction_start', activityReceipt: null })
205+
const result = parseIngestedStreamEventEnvelope(value)
220206

221-
expect(parseIngestedStreamEventEnvelope(value)).toBe(rejection)
207+
expect(result.ok).toBe(false)
208+
expect(result).toEqual(parsePersistedStreamEventEnvelope(value))
222209
expect(recordStreamContractDisagreement).toHaveBeenCalledExactlyOnceWith(
223210
'schema_accepts',
224-
'tool',
225-
'call'
211+
'run',
212+
'compaction_start'
226213
)
227214
expect(logger.warn).toHaveBeenCalledExactlyOnceWith(
228215
'Stream contract schema disagrees with the stream validator',
229-
expect.objectContaining({ direction: 'schema_accepts', validatorErrors: ['hypothetical'] })
216+
expect.objectContaining({
217+
direction: 'schema_accepts',
218+
eventType: 'run',
219+
variant: 'compaction_start',
220+
})
230221
)
231222
})
232223

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,12 @@ function isStreamScope(value: unknown): value is MothershipStreamV1StreamScope {
185185
//
186186
// Validates the envelope shell (v, seq, ts, stream, trace?, scope?) and that
187187
// `type` is one of the known event types with a non-null payload object.
188-
// Per-payload-variant validation is intentionally lightweight: the server
189-
// already performs strict schema validation; the client only needs enough
190-
// structural checking to safely dispatch inside the switch statement.
188+
// This is the one verdict on every stream frame: on Sim's server (worker ingest,
189+
// Redis buffer reads) and in the browser. Only a resource payload is checked
190+
// against its generated schema (ResourcePayload). The generated envelope schema
191+
// (MothershipStreamV1EventEnvelopeSchema) is not enforced at runtime: the
192+
// worker's emitter is only typed against it, and on worker ingest it only
193+
// shadows this verdict, counting disagreements (contract-shadow.ts).
191194

192195
/** The event types the contract names; a frame of any other type is invalid. */
193196
export const KNOWN_EVENT_TYPES: ReadonlySet<string> = new Set(

‎apps/sim/lib/workflows/editing/validation-models.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,23 @@ describe('model ids no provider declares', () => {
146146
const { errors } = validateModel('router_v2', 'llama3.1:8b')
147147
expect(errors[0]?.error).toContain('Unknown model id')
148148
})
149+
150+
it('offers an ollama/ namespace example only where Ollama can serve it', () => {
151+
expect(validateModel('router_v2', 'best available model').errors[0]?.error).toContain(
152+
'"ollama/llama3.1:8b"'
153+
)
154+
155+
setEnvFlags({ isHosted: true })
156+
expect(validateModel('router_v2', 'best available model').errors[0]?.error).not.toContain(
157+
'ollama/'
158+
)
159+
160+
setEnvFlags({ isHosted: false })
161+
envFlagsMockFns.getBlacklistedProvidersFromEnv.mockReturnValue(['ollama'])
162+
expect(validateModel('router_v2', 'best available model').errors[0]?.error).not.toContain(
163+
'ollama/'
164+
)
165+
})
149166
})
150167

151168
describe('fallback model rows', () => {

‎apps/sim/lib/workflows/editing/validation.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1025,14 +1025,23 @@ export function validateValueForSubBlockType(
10251025
const suggestions = suggestModelIdsForUnknownModel(trimmed)
10261026
const suggestionText =
10271027
suggestions.length > 0 ? ` Valid options include: ${suggestions.join(', ')}.` : ''
1028+
const namespaceExamples = [
1029+
'azure/my-deployment',
1030+
'azure-anthropic/my-deployment',
1031+
'bedrock/my-inference-profile',
1032+
'vertex/my-model',
1033+
...(isOllamaAvailable() ? ['ollama/llama3.1:8b'] : []),
1034+
]
1035+
.map((example) => `"${example}"`)
1036+
.join(', ')
10281037
return {
10291038
valid: false,
10301039
error: {
10311040
blockId,
10321041
blockType,
10331042
field: fieldName,
10341043
value,
1035-
error: `Unknown model id "${trimmed}" for block "${blockType}". Read components/blocks/${blockType}.json (the model.options array) for valid ids; prefer entries with recommended: true and avoid deprecated: true. For user-configured models, use a supported provider namespace, e.g. "azure/my-deployment", "azure-anthropic/my-deployment", "bedrock/my-inference-profile", "vertex/my-model", "ollama/llama3.1:8b", or "openrouter/provider/model".${suggestionText}`,
1044+
error: `Unknown model id "${trimmed}" for block "${blockType}". Read components/blocks/${blockType}.json (the model.options array) for valid ids; prefer entries with recommended: true and avoid deprecated: true. For user-configured models, use a supported provider namespace, e.g. ${namespaceExamples}, or "openrouter/provider/model".${suggestionText}`,
10361045
},
10371046
}
10381047
}

0 commit comments

Comments
 (0)