Repository navigation
Description
Problem
Our current resilience story (circuit breaker + provider failover + validateToolCalls) handles loud provider failures well, but leaves two gaps for the classic "API silently deprecated a field at 2am" scenario:
- No response envelope schema validation. Each provider's parser reads fields like
stop_reason,usage.input_tokens,choices[0].message.contentvia direct property access. If a provider renames/drops a field, we get an uncaughtTypeErroror a silently-undefined value propagating intoLLMResponse. Failover rescues us, but only after a failure; the first requests hitting the broken shape either throw or return corrupt data. - No schema drift detection. We learn about breaking changes from production errors, not from canaries. There's no golden-sample comparison, no nightly probe, no changelog watcher.
The existing validateToolCalls (src/providers/base.ts:335) is the right pattern — drop malformed entries with a warning instead of crashing — but it only covers the tool_calls array. We should extend the same defensive-parse posture to the whole response envelope.
Proposal
Part 1 — Response envelope schema validation (per provider)
Add a zod (or valibot, lighter runtime) schema per provider describing the raw upstream response shape. Parse through it before field access in generateResponse. On validation failure:
- Log a structured warning with provider, model, and the offending path
- Emit a
schema_drifthook event (see src/utils/hooks.ts) so observability can alert - Throw a new
SchemaDriftErrorthat the circuit breaker/failover path treats like a transient provider error (so we fail over to a healthy provider instead of crashing the caller)
Files likely touched:
src/providers/anthropic.ts,openai.ts,groq.ts,cerebras.ts,cloudflare.ts— add per-provider schema, parse before accesssrc/errors.ts— addSchemaDriftErrorsrc/factory.ts— treatSchemaDriftErroras fallback-eligible ingetFallbackDecisionsrc/utils/hooks.ts— newschema_driftevent type
Part 2 — Schema drift canary
A separate opt-in module (src/utils/schema-canary.ts) that:
- Sends a minimal known-good request to each configured provider
- Captures the raw response
- Compares against a committed golden fixture (
src/__tests__/fixtures/response-shapes/<provider>.json) - Reports added/removed/renamed top-level and usage fields
Consumer-facing surface: a runSchemaCanary(providers) function that returns a diff report. Leave scheduling to the consumer (cron Worker, GitHub Action, whatever) — the library shouldn't own cadence.
Stretch: a scripts/update-golden-shapes.ts that refreshes fixtures after human review of a diff (never automatically).
Tests
- Unit: each provider's schema rejects known-bad shapes (missing
usage, wrong type oncontent, etc.) and accepts current golden shapes - Integration: factory fails over on
SchemaDriftErrorlike it does onProviderError - Canary smoke: golden shape comparison logic — fixture-driven, no network
Out of scope
- Changelog/RSS polling — separate concern, different cadence
- Auto-healing / auto-patching parsers — humans review drift diffs, period
- Schema validation of request payloads — we already validate in
validateRequest
Priority
Medium. Current failover + circuit breaker means this is a defense-in-depth upgrade, not a hair-on-fire gap. But the cost of the 2am JSON parse error is high enough that being proactive wins.
Activity
feat(schema-drift): add response envelope validation for Anthropic + …
Merge pull request #40 from Stackbilt-dev/feat/schema-drift-detection
stackbilt-admin commentedon Apr 12, 2026
Slice 1 shipped — PR #40 merged (1a57f1f)
What landed
SchemaDriftErrorclass — non-retryable, codeSCHEMA_DRIFT, statusCode 422 (Unprocessable Entity, not 502)validateSchemautility — zero-dep path-based validator with:string | number | boolean | array | object | string-or-null)optional: trueitems.discriminator+items.variantspath / expected / actualsurfaced on drifttext,tool_use) before parsingSchemaDriftErroris fallback-eligible, routes to next healthy provideronSchemaDriftobservability hook — fires from factory with{ provider, model, requestId, path, expected, actual }SchemaDriftError,validateSchema,SchemaField,SchemaFieldType,SchemaDriftEventall exported from package rootTests: 201 → 212 (11 new). Covers validator primitives, Anthropic drift detection, factory fallback, hook firing, circuit breaker opening after repeated drift, end-of-chain propagation, security (no value leakage in error surface), nested content-block validation, forward-compat, optional fields.
CI green on Node 18/20/22. #42 closed in-PR.
Remaining work (follow-up PRs)
Part 1 — Response envelope schema validation
itemspattern forchoices[0].message.tool_calls[]Each provider is a ~50-line PR following the Anthropic template. Parallelizable.
Part 2 — Schema drift canary (
src/utils/schema-canary.ts)runSchemaCanary(providers)that sends known-good minimal requests, captures responses, and diffs against committed golden fixturessrc/__tests__/fixtures/response-shapes/<provider>.jsonscripts/update-golden-shapes.tsfor human-reviewed fixture refreshPart 3 — Streaming path validation (#41)
streamResponseneeds its own delta-shape schema + drift handlingReview findings deferred from PR #40
validateSchemaAllvariant that collects all drifts instead of fail-fast (for debuggability in logging paths)onRequestErrorfires beforeonSchemaDriftfor the same incidentsrc/providers/schemas.tsor per-provider colocated exports (after slice 2 wire-ups land)Closing criteria for #39
This parent issue closes when:
onSchemaDriftKeeping this issue open until then.
feat(schema-drift): envelope validation for openai/groq/cerebras (#39 …
stackbilt-admin commentedon Apr 27, 2026
Auditor note: the parent checklist is stale relative to main. OpenAI, Groq, and Cerebras now each define response envelope schemas and call
validateSchema()before formatting; Anthropic is also wired. Cloudflare still appears to be the remaining non-streaming provider without envelope validation.Suggested issue hygiene update:
response,choices,output, wrappedresult), so its schema likely needs a provider-specific union rather than copying the OpenAI-compatible schema.onSchemaDrift; the hook exists and is exported, but public docs do not describe the event or expected consumer behavior.This parent issue is useful, but it should now read as a remaining-work tracker rather than an implementation proposal.
stackbilt-admin commentedon Apr 27, 2026
Part 1 (envelope schema validation) was completed in an earlier session. Part 2 (schema drift canary) now ships as
src/utils/schema-canary.ts:extractShape(obj)— walks a raw response and returns a flatpath → typemapcompareShapes(golden, live)— diffs two shape maps into{ added, removed, changed }runCanaryCheck(provider, golden, liveResponse)— one-shot check returning aCanaryReportsrc/__tests__/fixtures/response-shapes/for all five providers (Anthropic, OpenAI, Groq, Cerebras, Cloudflare)schema-canary.test.tsincluding golden parity checks for all providersfeat: resolve all open issues — SSE validation, cache hints, schema c…