Skip to content

fix(tools): stop auto tool_choice rejecting standard JSON Schema (#561 regression) - #603

Merged
Gajesh2007 merged 3 commits into
masterfrom
investigate/auto-toolschema-union-regression
Jul 31, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
investigate/auto-toolschema-union-regression

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

Review follow-ups (second commit)

All five Codex findings were verified real and fixed in the follow-up commit:

Finding Fix
P1 — normalizer-injected render types broke post-generation validation of admitted schemas Multi-concrete type arrays now mirror into anyOf in all three normalizers (nullable pairs byte-identical; prompt-parity vectors untouched). Swift validator: $ref nodes not-asserted; satisfied anyOf/oneOf or matched const/enum suppresses the sibling render type; allOf stays conjunctive.
P1 — none routed to providers that predate tool-hiding toolChoiceNonePromptPolicyFloor = "0.7.10" (tool-hiding shipped in v0.7.10, prod floor is 0.7.5); fail-fast goes through HasToolCapableProviderForTraits so a below-floor pool 503s instead of queue-timing-out.
P1 — if/then, dependentRequired, dependentSchemas, propertyNames silently unenforced Now enforced post-generation (decidable from the instance alone). unevaluated*/contentSchema stay not-asserted; comments state the split exactly.
P2 — 400 fired for transiently unroutable enforcing fleets New HasProviderAdvertisingToolConstraint (advertisement-only, ignores trust/freshness); 400 requires fleet-serves-model AND zero advertisers; everything else stays 503.
P2 — forged marker fold-window at depth 33–63 Guards scan to the normalizer's own budget (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 to type:"string" + anyOf mirror.

Copilot AI review requested due to automatic review settings July 30, 2026 23:33
@vercel

vercel Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jul 31, 2026 11:26pm
d-inference-console-ui-dev Ready Ready Preview Jul 31, 2026 11:26pm
d-inference-landing Ready Ready Preview Jul 31, 2026 11:26pm

Request Review

…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.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: none to not require inference-grammar capability (routes broadly; tools hidden + post-generation rejection), including multimodal admission on the provider.
  • Adjusts post-generation regex handling for auto to 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

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

  • TB-001 (Consumer → Coordinator) — consumer.go change passes validatedMode into visionToolsFailFast
  • TB-007 (Provider inference engine) — all Swift inference-path changes

Threat analysis

T-007 — Provider serves manipulated model outputs

File Change Assessment
MultiModelBatchSchedulerEngine.swift L271 guard prepared.mode == .auto || prepared.mode == .none ✅ Strengthens: .none mode previously fell through to the invalidToolPayload error for multimodal requests. It is now correctly routed through the media path (tools are stripped upstream by ToolChoicePromptPolicy; post-generation validation rejects any emitted call). The fail-closed path for .required/.named is preserved.
ToolConstraintFactory.swift L27–32 Early return nil for .none before the grammar-contract gate ✅ Strengthens: avoids incorrectly throwing when no grammar automaton is needed. .required/.named still fail closed without the pinned Gemma contract.
ToolChoicePromptPolicy.swift L30 validateAutoSchemas → rejectReservedSchemaMetadata ✅ Strengthens: the old call ran the full schema-feasibility walk on .auto paths, which was both over-restrictive (rejecting admissible JSON-Schema features) and under-specified as a security guard. The new function has an explicit threat model: detect forgery of the internal originalBooleanSchemaKey marker injected by our normalizer.
ToolConstraintValidation.swift — rejectReservedSchemaMetadata + scanReservedSchemaMetadata New depth-bounded recursive walk ✅ Strengthens: the walk is fail-closed — a schema too deep to scan at maxMetadataWalkDepth (32) is rejected, not passed. This prevents a deep schema from hiding a forged marker below the scan horizon and then having it fold upward into a trusted position. The comment at L~117 correctly explains why silent truncation would be exploitable. The early return on allowInternalSchemaMetadata == true (coordinator-fed, already-normalized bodies) is the correct bypass.
ToolConstraintValidation.swift — $ref-bearing node handling + finiteMatched Suppresses sibling type enforcement on ref-bearing and const/enum-matched nodes ℹ️ Neutral security posture: the change fixes a semantic correctness issue (normalizer-injected type on a bare $ref node shouldn't be enforced against model output). This does not widen what a consumer can send; it narrows false-positive validation rejections for legitimately structured schemas.
ToolSchemaNormalization.swift — multi-type array → anyOf Mirrors ["string","integer"] into anyOf when no combinator already exists ℹ️ Neutral: this is a normalization correctness fix. The guard dict["anyOf"] == nil, dict["oneOf"] == nil, dict["allOf"] == nil prevents overwriting author-supplied combinators, which is the right fail-safe. No new consumer-controlled surface is introduced.

T-002 — Unbounded request body causes coordinator OOM

consumer.go changes at L1553 and L3791 only add string(validatedMode) as an additional argument to visionToolsFailFast. No io.ReadAll, MaxBytesReader, or body-reading code is modified. ℹ️ Neutral — this open finding is unchanged.

T-005, T-031, T-040, T-049 — The consumer.go hunks touch only the visionToolsFailFast call sites, adding the already-computed validatedMode parameter. No authentication, URL generation, earnings, or SSRF-relevant code paths are modified. ℹ️ Neutral — these findings are unchanged.


New attack surface not covered by existing threats

Tool-schema complexity as a DoS vector (not currently modelled): scanReservedSchemaMetadata at ToolConstraintValidation.swift walks a recursively-nested consumer-supplied JSON structure. The depth bound of 32 and the early-return on non-clean results limit worst-case work, but the walk also descends into array children (e.g. allOf, anyOf, prefixItems) and through property-map values with separate loops. A schema that is exactly 32 levels deep and maximally branched (e.g. anyOf of 16 allOf members at every level) could in principle generate O(branching^depth) node visits before the depth guard fires — but the depth guard fires per call frame, not per total node count, so this is bounded by maxMetadataWalkDepth per path, not per tree. The current structure visits each node at most once per traversal path; no threat model entry covers this, but it is low severity given the 32-level cap and the early bail on the first non-clean result.

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 ToolConstraintValidation.validate for the constrained-grammar path).


SEC-* findings resolved by this PR

None 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: docs/threat-model.yaml · Updates on each push to this PR

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 15 out of 15 changed files in this pull request and generated no new comments.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread coordinator/api/tool_constraints.go Outdated
Comment on lines +350 to +352
// the provider's JSON-Schema validator, which handles anyOf/oneOf/$ref/
// pattern/if-then natively — so every other JSON-Schema construct passes
// through untouched.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread coordinator/api/inference_preprocess.go Outdated
Comment on lines +257 to +258
if !policy.enabled && !policy.prefer &&
s.registry.HasProviderForModel(model, allowedProviderSerials...) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread coordinator/api/tool_constraints.go Outdated
Comment on lines +353 to +355
func rejectReservedSchemaMetadata(schema any, depth int) error {
if depth > maxReservedMetadataDepth {
return nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Copilot AI review requested due to automatic review settings July 31, 2026 20:42
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Gajesh2007

Copy link
Copy Markdown
Member Author

Answering the threat-model review's two confirm-before-merge invariants:

1. "Confirm untrusted consumer schemas always arrive with allowInternalSchemaMetadata: false." That flag is not the consumer-facing guard — the layering is:

  • Coordinator ingress (the consumer trust boundary): rejectReservedSchemaMetadata in coordinator/api/tool_constraints.go runs on the pre-normalization body (originalRawBody) for auto and none (the constrained path has its own canonical-form marker rules in validateConstrainedSchema). Any marker there is client-supplied and rejected 400. As of the follow-up commit this walk covers the normalizer's full traversal budget (maxToolSchemaDepth = 64) and fails closed beyond it, so the constantMarkedCombinator fold can no longer lift a buried forged marker into vouched metadata.
  • Provider ingress: bodies whose wire message lacks tool_schema_metadata_protocol == 1 are byte-scanned (ToolSchemaNormalization.containsReservedMetadata, depth-unbounded) and rejected if the marker appears — that covers any path that bypasses the coordinator's normalizer.
  • allowInternalSchemaMetadata: false is the third layer, for standalone/local engines constructed without the coordinator loop (MultiModelBatchSchedulerEngine init at line ~191). The coordinator-fed engine keeps true because its bodies are normalized and legitimately carry the marker.

2. "Confirm the unenforced pre-flight is backed by a strict post-flight." Yes, with one deliberate exception: post-generation validateJSONSchema enforces allOf/anyOf/oneOf/not/enum/const/type/required/bounds/pattern/patternProperties and (since the follow-up) if/then/else, dependentRequired, dependentSchemas, propertyNames. The exception is assertions the validator cannot decide — non-literal regexes, oversized inputs, unevaluated* — which are not-asserted rather than rejections, including the additionalProperties fallback when a patternProperties key was undecidable. That is the designed invariant (an assertion the validator declines to evaluate must never fail a schema-valid call), and it is still strictly stricter than the pre-#561 state, which validated nothing.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  • HasProviderAdvertisingToolConstraint is meant to answer “can this fleet EVER enforce tool_choice for this model” (i.e., ignore transient routability gates), but it currently excludes all StatusUntrusted providers. A recoverable/transient untrust (missed challenge timeouts) can clear without reconnect; if the only tool-constraint-capable providers are temporarily StatusUntrusted while 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.
Copilot AI review requested due to automatic review settings July 31, 2026 23:25
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Gajesh2007

Copy link
Copy Markdown
Member Author

Threat-model follow-up (the updated review's ⚠️ on the $ref passthrough): taken, in 8da5eac, via your option (b).

The blanket return true on $ref-bearing nodes was indeed broader than the invariant requires. Sibling assertions are conjunctive with the reference (draft 2019-09+), so the validator now enforces everything the author wrote beside a $ref — const, enum, combinators, bounds, properties — and suppresses only the sibling type, which is the one key that cannot be attributed to the author on such nodes (the normalizer injects a render type onto every typeless $ref node, e.g. {"$ref":"#/$defs/P"} → type:"string" even when P is an object schema). A consumer can no longer wrap a tight const/enum in a $ref stub to disable its own validation; test autoRefBearingNodeEnforcesAuthorSiblings pins both directions (injected type suppressed, author enum beside the ref still rejects).

Option (a) — rejecting $ref tool definitions at admission — is exactly the #561 regression this PR removes ($defs/$ref is standard pydantic/zod output), so it was not considered.

Also added the unit test you suggested for the widened normalizer surface: a forged reserved marker planted inside an author anyOf on a multi-concrete type-array node (the collapse-only path) is still caught by the reserved-metadata walk, under both auto and none.

Re-verified: coordinator api suite green, full Swift suite 1962 tests / 199 suites green.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  • maxMetadataWalkDepth is set to 32, but the coordinator’s tool-schema normalizer recurses to maxToolSchemaDepth = 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

@Gajesh2007
Gajesh2007 merged commit fde2849 into master Jul 31, 2026
13 of 15 checks passed

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 8da5eacb Deployed Jul 31, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 8da5eacb Deployed Jul 31, 2026 by vercel[bot]
Preview – d-inference-landing — 8da5eacb Deployed Jul 31, 2026 by vercel[bot]
benchmarks — 8da5eacb Deployed Jul 31, 2026 by Gajesh2007 via E2E Benchmarks #27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants