Repository navigation
fix(tools): stop auto tool_choice rejecting standard JSON Schema (#561 regression) - #603
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
…regression) #561 added a fail-closed "auto tool schema" scan to the coordinator, the provider, and the prompt sidecar. It is gated on the tool_choice literal alone, so every model -- not just Gemma -- started returning 422 for tool definitions containing anyOf/oneOf unions, $ref/$defs, regex pattern or patternProperties, if/then, dependency assertions, or multi-type `type` arrays. Those are ordinary SDK output (pydantic and zod hoist definitions into $defs/$ref; unions become anyOf), so tool calling broke for mainstream OpenAI-compatible clients on gpt-oss-20b, which worked on v0.7.11. The scan answers a question auto never asks. ToolConstraintFactory.make returns nil for .auto -- auto compiles no sampler grammar -- and the compiler's keyword allowlist excludes those constructs anyway, so auto's compiledTools is always nil and its emitted calls are checked by validateJSONSchema, which implements allOf/anyOf/oneOf/not/pattern/ patternProperties correctly. Delete the scan in all three mirrors instead of gating it on the resolved model. Kept: the client-forgery guard for the x-darkbloom-original-boolean-schema marker, narrowed to exactly that key in Go and Swift and now also covering tool_choice:"none", which previously had no guard. Both walks are depth-bounded and stop descending rather than reject, and they inspect schema positions only so a property named after the marker is not mistaken for forgery. The sidecar gets no guard: it receives the already-normalized body where the marker is legitimate. validateJSONSchema no longer fails on assertions it cannot evaluate. safePatternMatches -> patternAssertionSatisfied returns nil for a non-literal regex or oversized input, only a decisive false rejects, and an undecidable patternProperties key suppresses the additionalProperties fallback for that property so `additionalProperties: false` cannot reject a name that might have matched. tool_choice:"none" no longer requires an inference-enforcing provider: requiresGrammar() is now required||named, ToolConstraintFactory.make returns nil for .none off the pinned Gemma contract, and the engine's multimodal guard admits .none. A Gemma provider still installs GemmaNoToolTokenConstraint; everyone else honors none by hiding the tools and rejecting any emitted call after generation. Previously `none` with zero declared tools 503'd on gpt-oss-20b. required/named with no enforcing build now return 400 invalid_request_error when the fleet serves the model, keeping 503 model_unavailable only when nothing serves it -- a permanent per-model incapability must not look like retryable capacity. required/named keep their fail-closed compile-time validation in all three languages; every construct above still 422s under required.
There was a problem hiding this comment.
Pull request overview
Fixes a regression introduced in #561 where tool_choice: "auto" (which does not compile an inference grammar) began rejecting mainstream SDK-generated JSON Schemas (e.g., $defs/$ref, anyOf/oneOf, patternProperties) before model resolution, causing global 422s across all models. The PR restores “auto forwards schemas; validate post-generation” behavior while keeping required/named modes fail-closed for the constrained grammar subset.
Changes:
- Removes the model-blind “auto schema support” preflight scan from all three mirrors (Go coordinator, Swift provider, Rust sidecar), replacing it with a narrow reserved-metadata forgery guard.
- Updates
tool_choice: noneto not require inference-grammar capability (routes broadly; tools hidden + post-generation rejection), including multimodal admission on the provider. - Adjusts post-generation regex handling for
autoto be tri-state (decidable false rejects; undecidable patterns are not asserted) to avoid rejecting valid tool calls on unevaluatable regexes.
Reviewed changes
Copilot reviewed 19 out of 19 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| provider-swift/Tests/ProviderCoreTests/GemmaToolConstraintTests.swift | Adds regression coverage for auto schema forwarding, .none off-contract behavior, and tri-state regex semantics. |
| provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift | Ensures forced tool choices still reject multimodal, while .none is admitted on the multimodal path. |
| provider-swift/Sources/ProviderCore/Inference/ToolConstraintValidation.swift | Replaces auto preflight schema scan with reserved-metadata guard; changes regex assertion to tri-state (undecidable ⇒ not asserted). |
| provider-swift/Sources/ProviderCore/Inference/ToolConstraintFactory.swift | Makes .none return nil off pinned Gemma contract (while keeping required/named fail-closed). |
| provider-swift/Sources/ProviderCore/Inference/ToolChoicePromptPolicy.swift | Swaps validateAutoSchemas for rejectReservedSchemaMetadata in the .auto preparation path. |
| provider-swift/Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift | Allows .none through the multimodal media path (still rejecting required/named). |
| docs/reports/2026-07-30-auto-tool-schema-rejection-root-cause.md | Adds the detailed root-cause writeup and documents the shipped fix behavior. |
| docs/reports/2026-07-25-prefill-and-fleet-performance-findings.md | Adds/updates performance findings notes (report content). |
| docs/reports/2026-07-25-paged-kv-migration-plan.md | Adds/updates paged-KV migration planning notes (report content). |
| docs/reports/2026-07-25-paged-attention-for-prefill-decision.md | Adds/updates the paged-attention decision note (report content). |
| coordinator/registry/request_traits.go | Updates trait documentation to reflect that only required/named imply grammar enforcement. |
| coordinator/promptsidecar/src/tool_constraint.rs | Deletes the third copy of the auto schema scan in the Rust sidecar. |
| coordinator/promptsidecar/src/normalize.rs | Removes raw-auto schema preflight from normalization (auto schemas now pass through). |
| coordinator/api/tool_constraints.go | Removes auto schema scan; adds reserved-metadata walk; changes requiresGrammar() to exclude none. |
| coordinator/api/tool_constraints_test.go | Updates unit tests to assert auto/none acceptance of standard JSON Schema constructs + reserved-marker rejection. |
| coordinator/api/tool_constraint_http_test.go | Adds HTTP-level regression proving auto union reaches routing gate rather than 422ing. |
| coordinator/api/inference_preprocess.go | Splits 400 vs 503 in visionToolsFailFast to distinguish permanent incapability from transient absence. |
| coordinator/api/auto_toolschema_regression_test.go | Adds comprehensive regression suite covering the construct corpus + none/auto behavior + capability error split. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0dc79669f9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // skips — auto and none. | ||
| tools, err := validateDeclaredTools( | ||
| root["tools"], enforceSchema, selected, mode == toolChoiceAuto) | ||
| root["tools"], enforceSchema, selected, !enforceSchema) |
There was a problem hiding this comment.
Preserve admitted schemas through normalization
For tool_choice:"auto" schemas using a multi-type union or an object-valued $ref, this now admits the request but still dispatches the output of NormalizeToolSchemas: a typeless anyOf node is assigned the first branch's type, an array-valued type is collapsed to its first concrete member, and a $ref-only property becomes type:"string". ToolConstraintValidation.validateJSONSchema then validates that rewritten schema without resolving $ref, so a valid integer union branch or referenced object is rejected as invalidToolPayload (or the model is prompted to emit the wrong type). Preserve the original schema for post-generation validation or make normalization lossless for these newly admitted constructs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified and fixed in 9c25847, in two halves:
Multi-concrete type arrays (the lossy case — the union was destroyed on the wire): all three normalizers now mirror the distinct concrete members into anyOf before collapsing the render type ({"type":["string","integer"]} → {"type":"string","anyOf":[{"type":"string"},{"type":"integer"}]}). Nullable pairs (["x","null"]) stay byte-identical to before — the prompt-parity vectors are untouched and their tests pass. A node that already carries a combinator keeps the author's conjunctive semantics (documented as knowingly narrowed).
Injected render types on anyOf/$ref/enum nodes (the union survives the wire, but the validator enforced the injected type conjunctively): validateJSONSchema now treats a $ref-bearing node as entirely not-asserted (it cannot resolve the reference, so the siblings — including the injected type — belong to whatever it resolves to), and a satisfied non-empty anyOf/oneOf or a matched const/enum suppresses the sibling type check. allOf is deliberately not exempted (conjunctive branches imply the derived type anyway). Regression tests pin the real normalized wire shapes, e.g. {"anyOf":[…],"type":"string"} accepting both branches while each branch's inner assertions (minimum, minLength) still bite.
| // Gemma-class constrained provider pool. | ||
| func (m toolChoiceMode) requiresGrammar() bool { | ||
| return m == toolChoiceNone || m == toolChoiceRequired || m == toolChoiceNamed | ||
| return m == toolChoiceRequired || m == toolChoiceNamed |
There was a problem hiding this comment.
Gate none on the provider version that implements it
When a tool_choice:"none" request is routed to a provider older than v0.7.10, clearing RequiresToolConstraint lets it pass the generic tools floor (v0.6.3), but those builds predate ToolChoicePromptPolicy and render the request's tools without hiding them or adding the no-tool instruction. Production currently permits providers back to v0.7.5, so a mixed fleet can return an actual tool call despite the caller explicitly selecting none; use a capability/version floor that guarantees the prompt policy rather than routing none to every tool-capable provider.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed — tool-hiding (ToolChoicePromptPolicy) first shipped in v0.7.10 (#538, verified via ancestry: 5c33a32 is in the v0.7.10 release), and prod routes ≥ 0.7.5 (EIGENINFERENCE_MIN_PROVIDER_VERSION=0.7.5), so a 0.7.5–0.7.9 provider would render the declared tools and could emit a call despite none.
Fixed in 9c25847 with a capability floor rather than a name match: toolChoiceNonePromptPolicyFloor = "0.7.10" in providerMeetsTraitFloorsLocked, applied when HasTools && ToolChoiceMode == "none" (tool-less none needs no floor — nothing to render). The consumer fail-fast now goes through the new HasToolCapableProviderForTraits with the same traits, so a pool entirely below the floor 503s immediately instead of passing the trait-blind preflight and dying in the 120s queue. Registry test: 0.7.9 ineligible for tools+none, 0.7.10 eligible, auto/required at 0.7.9 unaffected.
0dc7966 to
a957be9
Compare
|
This PR adds tool-choice mode propagation, a fail-closed reserved-metadata forgery guard, and multi-type schema normalization — all changes are neutral-to-positive for the security posture; no mitigations are weakened and no new trust boundaries are crossed. Trust boundaries touched
Threat analysisT-007 — Provider serves manipulated model outputs
T-002 — Unbounded request body causes coordinator OOM
T-005, T-031, T-040, T-049 — The New attack surface not covered by existing threatsTool-schema complexity as a DoS vector (not currently modelled): No action required unless tool-schema input size limits are not already enforced upstream (they should be, given the existing body-size concerns in T-002 for the coordinator side and the provider's own SEC-* findings resolved by this PRNone explicitly resolved. No open SEC-* findings are directly addressed; the PR is a correctness fix with security-positive side effects in the tool-schema forgery guard. 🔐 Threat model: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a957be9b0c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // the provider's JSON-Schema validator, which handles anyOf/oneOf/$ref/ | ||
| // pattern/if-then natively — so every other JSON-Schema construct passes | ||
| // through untouched. |
There was a problem hiding this comment.
Enforce newly admitted schema assertions
When an auto tool schema uses if/then, dependentRequired, dependentSchemas, or propertyNames, this newly added claim is false: ToolConstraintValidation.validateJSONSchema has no logic for those keywords. For example, a schema requiring billing_address whenever credit_card is present now passes admission, but a generated call containing only credit_card is accepted post-generation. Either continue rejecting constructs the validator cannot evaluate or implement their assertions before admitting them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right — the claim over-reached. Fixed in 9c25847 by making it true where decidable: validateJSONSchema now enforces if/then/else (conditional application), dependentRequired (same unicode-scalar key discipline as required; malformed entries are skipped, never rejections), dependentSchemas, and propertyNames — all fully decidable from the instance alone. Your credit_card-without-billing_address example is now rejected post-generation (test: autoIfThenElseIsEnforced, autoDependentRequiredIsEnforced).
unevaluatedProperties/unevaluatedItems/contentSchema need annotation tracking this validator does not do; they stay not-asserted, and the code comments (coordinator + provider) now state the enforced-vs-not-asserted split exactly instead of claiming blanket coverage. Continuing to reject them pre-flight was not an option — that is precisely the regression this PR removes, and not-asserted is still strictly stricter than the pre-#561 state (no validation at all).
| if !policy.enabled && !policy.prefer && | ||
| s.registry.HasProviderForModel(model, allowedProviderSerials...) { |
There was a problem hiding this comment.
Separate capability from temporary routability
When every model-advertising provider is temporarily ineligible—for example because runtime verification or attestation-challenge freshness has lapsed—HasToolConstraintProviderForRouting returns false, but HasProviderForModel still returns true because it checks only status, trust classification, and model advertisement. This branch therefore reports a terminal 400 claiming the model lacks tool-choice support even when a provider advertises that capability and is merely temporarily unroutable; use a capability-specific predicate that ignores transient routing gates, or retain the retryable 503 for this case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed — HasToolConstraintProviderForRouting gates on providerStructurallyCanRouteBuildLocked (trust minimums, freshness), which HasProviderForModel does not, so a trust-lapsed enforcing fleet would have produced the permanent 400.
Fixed in 9c25847 with a capability-specific predicate: Registry.HasProviderAdvertisingToolConstraint mirrors HasProviderForModel's gate set exactly (online, non-untrusted, catalog build, serial allowlist) plus providerSupportsToolConstraintLocked, and deliberately ignores trust minimums / attestation freshness / capacity. The 400 arm now requires the fleet to serve the model AND zero providers to advertise the capability; every other shortfall keeps the retryable 503. Regression test: an advertising provider below MinTrustLevel yields 503, not 400.
| func rejectReservedSchemaMetadata(schema any, depth int) error { | ||
| if depth > maxReservedMetadataDepth { | ||
| return nil |
There was a problem hiding this comment.
Reject reserved markers beyond the walk limit
When an auto schema places the reserved marker below depth 32 but within NormalizeToolSchemas' 64-level traversal budget—for example under a chain of single-member anyOf nodes—this returns success without inspecting it. The normalizer then walks to the forged canonical marker and constantMarkedCombinator folds the marker-only unions bottom-up, potentially lifting it into a shallow schema that the provider trusts as coordinator-generated metadata and evaluates as allow-all or deny-all. Scan at least as deeply as normalization, or fail closed when the forgery walk reaches its bound.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch — the fold-window was real: the guard walked ≤32 fail-open while NormalizeToolSchemas walks to maxToolSchemaDepth (64) and constantMarkedCombinator folds marker-only combinators toward the root, so a forged marker at depth 33–63 could surface as shallow, coordinator-vouched metadata (the provider's own byte-scan only guards unvouched bodies).
Fixed in 9c25847: the Go guard now walks to maxToolSchemaDepth itself (same constant, cannot drift) and FAILS CLOSED beyond it — a schema too deep to scan cannot be vouched marker-free. The Swift guard (standalone-server path, whose normalizer walk is unbounded) got the same fail-closed semantics at its own bound. Smoke-verified: a forged marker under 40 single-member anyOf wrappers is now a 400 (tool schema contains reserved internal metadata), a clean 40-deep schema still clears admission, and >64-deep schemas reject (tool schema exceeds the reserved-metadata scan depth) — matching the pre-fix scan's posture, which rejected >32.
…on, floor none, tighten guards Five follow-ups from Codex review, all verified against the code before fixing: Normalization vs validation (P1): NormalizeToolSchemas stamps a render type (first union branch, first finite value, or "string" for $ref-only nodes) and collapsed multi-concrete `type` arrays to their first member, so the provider's post-generation validator enforced constraints the author never wrote and rejected schema-valid emissions from every other branch. Multi- concrete arrays now mirror their members into `anyOf` in all three normalizers (nullable pairs stay byte-identical; prompt-parity vectors untouched), and the Swift validator treats $ref-bearing nodes as not-asserted while a satisfied anyOf/oneOf or matched const/enum suppresses the sibling render type. allOf stays conjunctive. tool_choice "none" version floor (P1): tool-hiding shipped in v0.7.10 (ToolChoicePromptPolicy, #538) but prod routes providers >= 0.7.5, so a 0.7.5-0.7.9 provider renders the declared tools and can emit a call despite the caller's explicit none. Tools-declaring none requests now carry a v0.7.10 floor (toolChoiceNonePromptPolicyFloor), and visionToolsFailFast uses HasToolCapableProviderForTraits so a whole pool below the floor fails fast instead of dying in the 120s queue. Newly enforced keywords (P1): if/then/else, dependentRequired, dependentSchemas, and propertyNames are decidable from the instance alone and are now enforced post-generation; unevaluated*/contentSchema stay not-asserted and the comments now say exactly that instead of over-claiming. 400 vs 503 (P2): the permanent-incapability 400 additionally requires HasProviderAdvertisingToolConstraint to be false — an advertisement-only scan that deliberately ignores trust minimums and attestation freshness — so a trust-lapsed enforcing fleet stays a retryable 503. Reserved-metadata fold window (P2): the forgery guards now scan to the normalizer's own traversal budget and fail closed beyond it (Go: maxToolSchemaDepth; Swift: walk bound with rejection). Previously a forged marker at depth 33-63 escaped the 32-deep fail-open walk and constantMarkedCombinator folded it into shallow coordinator-vouched metadata the provider trusts.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Answering the threat-model review's two confirm-before-merge invariants: 1. "Confirm untrusted consumer schemas always arrive with
2. "Confirm the unenforced pre-flight is backed by a strict post-flight." Yes, with one deliberate exception: post-generation |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 23 out of 23 changed files in this pull request and generated no new comments.
Suppressed comments (2)
coordinator/registry/dedicated_models.go:170
HasProviderAdvertisingToolConstraintis meant to answer “can this fleet EVER enforce tool_choice for this model” (i.e., ignore transient routability gates), but it currently excludes allStatusUntrustedproviders. A recoverable/transient untrust (missed challenge timeouts) can clear without reconnect; if the only tool-constraint-capable providers are temporarilyStatusUntrustedwhile other non-enforcing providers still serve the model, this will incorrectly trip the permanent 400 path ("no build ... will EVER enforce") instead of the retryable 503.
p.mu.Lock()
eligible := p.Status != StatusOffline && p.Status != StatusUntrusted &&
r.providerServesCatalogModelLocked(p, model) &&
providerSupportsToolConstraintLocked(p, model)
p.mu.Unlock()
docs/reports/2026-07-30-auto-tool-schema-rejection-root-cause.md:175
- This section says the reserved-metadata guards “stop descending instead of rejecting” when exceeding the depth bound, but the actual implementation (and tests) now fail closed and reject schemas beyond the scan depth (400 / invalidToolPayload). The doc should match the shipped behavior/security rationale.
Both metadata walks are depth-bounded and, on exceeding the bound, stop descending
instead of rejecting: the guard must never fail a schema for anything but the marker.
They also walk schema *positions* only, so a tool that declares a property literally
named after the marker is not mistaken for a forgery.
… follow-up)
The previous commit made a $ref-bearing node entirely not-asserted, which
was broader than the invariant requires: sibling assertions are conjunctive
with the reference (draft 2019-09+), so skipping them let a schema wrap a
tight const/enum in a $ref stub and disable its own validation. Only the
sibling `type` is unattributable on such nodes -- the normalizer injects a
render type onto typeless $ref nodes (a bare {"$ref":...} becomes
type:"string" even when the referenced schema is an object) -- so `type`
alone stays suppressed and every author-written assertion (const, enum,
combinators, bounds, properties) is enforced again.
Also adds the guard regression the threat-model review suggested: a forged
reserved marker planted inside an author anyOf on a multi-concrete
type-array node (the collapse-only normalization path) is still caught.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Threat-model follow-up (the updated review's The blanket Option (a) — rejecting Also added the unit test you suggested for the widened normalizer surface: a forged reserved marker planted inside an author Re-verified: coordinator api suite green, full Swift suite 1962 tests / 199 suites green. |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 23 out of 23 changed files in this pull request and generated no new comments.
Suppressed comments (1)
provider-swift/Sources/ProviderCore/Inference/ToolConstraintValidation.swift:29
maxMetadataWalkDepthis set to 32, but the coordinator’s tool-schema normalizer recurses tomaxToolSchemaDepth = 64(coordinator/api/toolschema.go:61) and this PR’s own writeup says the reserved-metadata guard should scan to the normalizer’s budget. With 32 here, the standalone-server path (allowInternalSchemaMetadata: false) will reject clean schemas between depths 33–64 even though the rest of the system can handle them, and it diverges from the intended cross-language parity.
private static let maxSafePatternBytes = 128
private static let maxSafePatternCount = 32
private static let maxSafePatternInputBytes = 16 * 1024
private static let maxMetadataWalkDepth = 32
private static let exactDoubleIntegerLimit = 9_007_199_254_740_992.0
Review follow-ups (second commit)
All five Codex findings were verified real and fixed in the follow-up commit:
typearrays now mirror intoanyOfin all three normalizers (nullable pairs byte-identical; prompt-parity vectors untouched). Swift validator:$refnodes not-asserted; satisfiedanyOf/oneOfor matchedconst/enumsuppresses the sibling render type;allOfstays conjunctive.nonerouted to providers that predate tool-hidingtoolChoiceNonePromptPolicyFloor = "0.7.10"(tool-hiding shipped in v0.7.10, prod floor is 0.7.5); fail-fast goes throughHasToolCapableProviderForTraitsso a below-floor pool 503s instead of queue-timing-out.if/then,dependentRequired,dependentSchemas,propertyNamessilently unenforcedunevaluated*/contentSchemastay not-asserted; comments state the split exactly.HasProviderAdvertisingToolConstraint(advertisement-only, ignores trust/freshness); 400 requires fleet-serves-model AND zero advertisers; everything else stays 503.maxToolSchemaDepth= 64) and fail closed beyond it, in Go and Swift.Re-verified after the follow-ups: Go 24/24 packages (
-count=1), Rust 78 tests, Swift 1962 tests / 199 suites. Smoke: issue body still clears admission; forged marker at depth 40 → 400; clean depth-40 schema passes;["string","integer"]normalizes totype:"string"+anyOfmirror.