Skip to content

feat(tools): enforce Gemma tool choices at inference - #561

Merged
Gajesh2007 merged 21 commits into
masterfrom
fix/tool-choice-enforcement
Jul 22, 2026
Merged

Gajesh2007 merged 21 commits into
masterfrom
fix/tool-choice-enforcement

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jul 20, 2026 •

Copy link
Copy Markdown
Member

Outcome

Gemma tool-choice policies are now enforced during token sampling, not merely checked after generation. Chat Completions, Responses, and Anthropic Messages are normalized into one bounded policy; constrained requests route only to providers that explicitly advertise protocol-v1 support for the concrete model; the provider compiles a byte-level grammar and the pinned CBv2 engine masks invalid tokens per row.

Engine dependencies: merged Layr-Labs/mlx-swift-lm#80 plus merged lifecycle follow-up #81, pinned to exact latest main SHA 74895ead8ae887dc5f9804ba450ffe7c9438b73d. This parent branch is based on master at 85681bba2ddd83db9e13f9391c2a937d6d1400e4 and pins that merged engine SHA.

Enforcement architecture

  1. Go validates endpoint-native tool choice, tool history, stop bounds, and the supported schema subset before routing.
  2. Responses and Anthropic requests lower to the same private provider contract without exposing prompt/tool content in telemetry.
  3. Registry traits require protocol-v1 plus concrete-model capability for none, required, and named choices; hot models_update messages refresh inventory and capability atomically.
  4. Swift normalizes the schema again, binds the code-level pinned Gemma template policy, compiles a bounded byte NFA/product automaton, and attaches it to the CBv2 row.
  5. The engine applies the grammar mask once at the final pre-filter boundary after arithmetic transforms, preserves raw model logprobs, advances state after host-confirmed samples, and fails closed if the sampler lifecycle or output budget cannot honor the constraint.
  6. Parsed calls are validated again against name, arguments, cardinality, and parallel-call policy before streaming or final response emission.

The pinned Gemma template remains byte-identical at SHA-256 94899c0f917d93f6fe81c95744d1e8ddab2d21d39228d2e4aec1fb2a25bff413. This PR changes enforcement code; it does not modify model files or templates.

Errors fixed

  • Required/named/none policies that previously relied on model compliance.
  • Cross-request grammar state leakage during batching, cancellation, preemption, and request-id reuse.
  • Invalid tokens surviving top-k/top-p/min-p ordering or being resurrected by penalties/logit bias.
  • Completion paths that could select a token and later discover insufficient output budget.
  • Stop composition heuristics, recursion depth, and unbounded stop automata.
  • Optional-schema grammar blowups and cross-runtime complexity drift.
  • Parser delimiter constants, UTF-8/control-byte handling, numeric overflow/lexical ambiguity, and nullable-union drift across Go/Rust/Swift.
  • Stale tokenizer-vocabulary construction under concurrent cold requests.
  • Responses parallel-history grouping, tool-call indices, and effective policy echo.
  • Scalar stop wire incompatibility on the coordinator path.
  • Old-provider queue stalls for constrained requests, immediate constrained-waiter failure when the last capable provider disconnects, and stale capability after live model updates.
  • Explicit null array bounds and nullable branches that previously drifted between front-door validation and provider compilation.
  • Draft-04 tuple-form items/additionalItems validation and JSON-Schema integer acceptance for integral finite doubles in unconstrained auto output.
  • Hybrid-cache rebase conflict: tool constraints are now translated through the post-#559 SSD staging/overflow path while retaining exact prefix receipt and full-span accounting.

Intentionally retained constraints

  • tool_choice:auto remains mixed-version compatible and does not require inference grammar.
  • Inference-enforced constraints are text-only Gemma; multimodal constrained requests fail before dispatch.
  • Constrained rows intentionally use target-only decode: no chained decode and no MTP proposal for that row.
  • The supported JSON Schema subset is bounded; unsupported shapes return 422 before inference.
  • number enum/const is rejected because Go/Rust/Swift cannot preserve an identical JSON lexical representation; use integer or string choices for exact values.
  • Physical v0.7.10 mixed-version E2E remains opt-in and requires a verified released binary; deterministic protocol/unit coverage runs normally.

Protocol, rollout, and privacy

Providers advertise tool_constraint_protocol: 1 and a concrete tool_constraint_models set at registration and in live model updates. The coordinator never infers capability from binary version. During rollout, old providers continue serving auto requests but cannot receive constrained policies. Rollback is a normal parent revert plus pin rollback; do not advertise protocol-v1 against an engine older than the SHA above.

Tool/property names and schema details stay inside the existing end-to-end encrypted request path. Metrics use bounded mode/result labels only. No prompt, tool arguments, schema values, model files, cache artifacts, or generated outputs are added to git.

Before

flowchart LR
  subgraph Behavior
    B1[Client sends required or named tool choice] --> B2[Coordinator routes by generic tools capability]
    B2 --> B3[Provider samples unrestricted output]
    B3 --> B4[Parser validates after generation]
    B4 --> B5[Violation, retry, or inconsistent response]
  end
  subgraph Code
    C1[consumer.go] --> C2[RequestTraits.HasTools]
    C2 --> C3[MultiModelBatchSchedulerEngine]
    C3 --> C4[Unconstrained CBv2 sampler]
    C4 --> C5[ToolCallProcessor]
  end
Loading

After

flowchart LR
  subgraph Behavior
    B1[Client request] --> B2[Normalize and validate bounded policy]
    B2 --> B3[Route only to protocol-v1 concrete-model provider]
    B3 --> B4[Compile pinned Gemma grammar]
    B4 --> B5[Mask to budget-safe language per token]
    B5 --> B6[Validate and stream policy-consistent calls]
  end
  subgraph Code
    C1[tool_constraints.go + prompt sidecar] --> C2[registry.RequestTraits]
    C2 --> C3[protocol capability registration / models_update]
    C3 --> C4[ToolChoicePromptPolicy + ToolConstraintFactory]
    C4 --> C5[CBv2TokenConstraintSampler at engine SHA 74895ea]
    C5 --> C6[ToolConstraintValidation + endpoint response adapters]
    C4 -. constrained rows stay target-only .-> C7[MTP/chained gates]
    C4 -. exact cache receipts preserved .-> C8[SSD stage + frozen-full replay]
  end
Loading

Verification

Engine

  • Merged-follow-up focused scheduler/sampler/MTP/OpenAI suites: 32 XCTest + 45 Swift Testing = 77 passed locally.
  • Merged follow-up PR full suite: 395 XCTest + 512 Swift Testing = 907 passed.
  • Release build passed on the follow-up PR.
  • Latest focused sampler run remained below its asserted bound: 0.000 / 0.194 / 0.193 ms per step at B=1/2/4.

Parent

  • Focused coordinator API/registry/protocol/prompt-contract suites passed.
  • Full coordinator go test ./... and go vet ./... passed.
  • golangci-lint: 0 issues.
  • Linux/amd64 coordinator build passed.
  • Rust sidecar fmt + locked all-target tests passed (50 tests); the static Linux parity build also passes in CI.
  • Focused provider integration: 86 passed.
  • Full provider suite: 82 XCTest + 1,588 Swift Testing = 1,670 passed locally and in final CI.
  • Provider release build passed. Production prompt parity vectors also passed across Rust planning, the serving Swift tokenizer, Go prompt-contract consumption, and shared Rust vectors.
  • Isolated real-provider E2E integration: 13 passed in 529.258s; full-network multi-model smoke skipped behind DARKBLOOM_FULL_NETWORK_SMOKE=1.
  • Exact hybrid-cache routing E2E passed in 105.31s.
  • Physical released-provider mixed-version E2E skipped as designed without DARKBLOOM_MIXED_VERSION=1 and the verified v0.7.10 binary.
  • An unfiltered go test ./e2e/... also starts heavy benchmarks and hit Go's 10-minute package timeout in TestBenchmark_HeavyLoad_100Concurrent_10KB; the isolated non-benchmark integration and exact-cache gates above passed.
  • Parent and nested git diff --check and IDE lints passed.

Rollout / rollback

Engine PRs #80 and #81 are merged, and this parent pins exact latest engine main at 74895ead8ae887dc5f9804ba450ffe7c9438b73d. Capability advertising makes rollout fail closed while old providers remain useful for auto. Rollback by reverting the parent capability/validation commit and restoring the prior engine pin; no database, catalog, template, or model migration is required.

Made with Cursor


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

Validate and lower constrained tool policies before dispatch, route them only to explicitly capable providers, and compile bounded Gemma grammars into row-local CBv2 constraints. Keep protocol rollout fail closed while preserving mixed-version auto behavior, privacy, streaming, batching, MTP, logprobs, and schema parity across Go, Rust, and Swift.

Co-authored-by: Cursor <cursoragent@cursor.com>
@vercel

vercel Bot commented Jul 20, 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 22, 2026 6:53pm
d-inference-console-ui-dev Ready Ready Preview Jul 22, 2026 6:53pm
d-inference-landing Ready Ready Preview Jul 22, 2026 6:53pm

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: COMMENT

Security — ✅ No issues found

Performance — ✅ No issues found

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

✅ All four passes clean. No issues found.

🤖 Automated review by Centaur · DAR-186

@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces inference-enforced tool-choice grammar (Gemma-4 token constraints) and rewires alias resolution to be trait-aware; no existing security mitigations are weakened, but the new grammar pipeline introduces one new attack surface that warrants attention before merge.


Trust boundaries touched

Boundary Role
TB-001 (Consumer → Coordinator) resolveRequestedModel now accepts RequestTraits built from consumer-supplied tool schemas
TB-002 (Coordinator → Provider WebSocket) MergeProviderModelsWithCapabilities propagates provider-advertised ToolConstraintProtocol / ToolConstraintModels
TB-007 (Provider inference engine) New token-constraint pipeline runs inside the provider process on consumer-supplied input

Per-threat assessment

T-002 — Unbounded request body causes coordinator OOM
ℹ️ Neutral. originalRawBody is captured and validateToolConstraintPolicy is called on it before any heavy work, but no new io.ReadAll call is introduced. The pre-existing open finding (no MaxBytesReader on plaintext inference endpoints) is unchanged; this PR doesn't worsen it.

T-007 — Provider serves manipulated model outputs / T-012 / T-027 — Weight hash enforcement
ℹ️ Neutral. The new grammar pipeline has no effect on weight-hash advertisement or enforcement. Gemma4ToolConstraintContract.isVerified pins chat_template.jinja to a single SHA-256 (pinnedTemplateSHA256 = "94899c..." in Gemma4ToolConstraintContract.swift), which is a new, positive integrity signal that partially closes the gap by ensuring the production template hasn't been swapped. The coordinator's weight-hash enforcement remains fail-open (SEC-007) — not changed here.

T-008 — Regression exposes plaintext SSE chunks on encryption failure
✅ Strengthens. ProviderLoop+InferenceHandler.swift is touched (diff omitted but listed). The fail-closed invariant for encryption errors is confirmed preserved — the new constraint path feeds into the existing inference_error abort path, not a new code branch that could bypass it. No plaintext emission path was introduced.

T-006 — Unauthenticated WebSocket floods provider registry
ℹ️ Neutral. MergeProviderModelsWithCapabilities adds two new provider-self-reported fields (ToolConstraintProtocol int, ToolConstraintModels map[string]struct{}) stored on the Provider struct (registry.go:529–532). These are consumed only during routing decisions, not during trust evaluation, so an attacker spamming registrations gains no additional leverage from these fields.

T-034 — Provider runs modified code while advertising trusted identity
ℹ️ Neutral. The toolConstraintContractVerified flag on TokenizerHandle (InferenceTypes.swift:102) is set at load time based on Gemma4ToolConstraintContract.isVerified, which reads chat_template.jinja from disk and hashes it. A malicious operator could replace this file; however, providerStructurallyCanRouteBuildLocked → providerEligibleForTraitsLocked gates routing on the coordinator's ToolConstraintModels allowlist populated from the provider's ModelsUpdateMessage, so the coordinator ultimately controls which builds are eligible. No regression to T-034 mitigations.

T-036 — Trust level elevated without completing full MDM/MDA chain
ℹ️ Neutral. Trait-aware alias resolution (ResolveModelConstrainedWithTraits, registry.go:1833) runs entirely within the routing/alias layer and has no influence on trust state assignment. The MDM/MDA chain is untouched.

T-041 (T-041 in TB-007) — Cross-tenant KV cache prefix sharing
ℹ️ Neutral. EngineV2Bridge.swift adds tokenConstraint threading but does not touch cacheSalt derivation, SSD block keys, or HMAC tag construction. No new at-rest surface.


🚨 New attack surface not covered by existing threats

Consumer-controlled tool schemas compile into unbounded automaton state in the provider process.

  • GemmaToolCallTokenConstraint and ForbiddenSubstringTokenConstraint build DFA/NFA state lazily per request. ToolConstraintSchemaCompiler caps grammar complexity at maxGrammarComplexity = 50_000 units (ToolConstraintSchema.swift:79) and NFA nodes at 100,000 (GemmaToolCallTokenConstraint.swift init). GemmaTokenVocabulary caps vocabulary scan at maximumVocabularySize = 400_000 with a terminalMissingRun = 1_024 sentinel.
  • Concern: transitionCache, stateIndex, completionCache, locallyAllowedCache, and viabilityEnvelopeCache inside ForbiddenSubstringTokenConstraint and GemmaToolCallTokenConstraint grow on the heap per-request with no cap on the number of reachable DFA states beyond the NFA node count. A consumer supplying a maximally complex schema + stop sequences hitting many distinct KMP prefix states could cause significant per-request heap growth inside the provider process. This is partially mitigated by the NFA node limit (100 k) and grammar complexity budget, but the relationship between NFA node count and DFA state explosion is not linear — worth a fuzz or worst-case analysis before the grammar node cap is treated as the memory bound.
  • Affected files: ForbiddenSubstringTokenConstraint.swift (transitionCache unbounded), GemmaToolCallTokenConstraint.swift (dfaStates unbounded), called from ToolConstraintFactory.make on the hot inference path.
  • Suggested action: add a hard cap on dfaStates.count and states.count (e.g. 10× the NFA node limit) with a ToolConstraintSchemaError.unsupported throw, and add a fuzz target exercising schema + stop-sequence combinations.

Provider-self-reported ToolConstraintProtocol version is trusted for routing.

  • registry.go:529–532 stores ToolConstraintProtocol int directly from the provider's ModelsUpdateMessage with no validation beyond the existing per-message read cap. The coordinator uses this to build the ToolConstraintModels set that gates inference-enforced routing. A malicious provider could advertise ToolConstraintProtocol = MaxInt or an empty ToolConstraintModels map to manipulate routing decisions. This is a routing correctness issue rather than a confidentiality/integrity issue for consumer data (T-007's weight-hash path is the data integrity control), but it could cause a constrained request to land on an incapable provider, yielding a constraint violation surfaced back to the consumer.
  • Suggested action: validate ToolConstraintProtocol against a known set of supported values and enforce a maximum ToolConstraintModels map size at registration.

SEC findings resolved by this PR

None explicitly. The Gemma4ToolConstraintContract.pinnedTemplateSHA256 check is new positive signal toward template integrity but does not close any named SEC finding.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

Treat the downloaded production tokenizer as an optional live fixture so clean CI hosts skip that integration test instead of recording a false failure. Keep a strict require once discovery enables the test, preserving local coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
@Gajesh2007

Copy link
Copy Markdown
Member Author

Provider CI follow-up: the first run correctly exposed that the new production-tokenizer integration recorded a failure when the optional downloaded Gemma fixture was absent on a clean runner. Commit 00f57bd10 now gates discovery with Swift Testing's .enabled(if:) trait and retains a strict #require once enabled. The focused suite passes 21/21 locally (including the real tokenizer), and the repository pre-push hook passed before the normal push. No production path changed.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 6 finding(s) (5 blocking)

  • 🔵 [INFO] coordinator/api/consumer.go:1468 — toolChoicePolicyFromBody called twice for same constraintBody
    • Suggestion: Cache the result from the first call at line 1482 and reuse it at line 1468
  • 🟡 [MEDIUM] coordinator/api/consumer.go:3132-3150 — finalizeResponsesEnvelope calls responsesToolPolicy twice for same traits
    • Suggestion: Call responsesToolPolicy once and assign both return values: toolChoice, parallelToolCalls := responsesToolPolicy(traits)
  • 🟡 [MEDIUM] coordinator/api/tool_constraint_history.go:1-110 — validateToolHistory creates unbounded maps without size limits
    • Suggestion: Add reasonable limits on message count and tool call count to prevent memory exhaustion attacks
  • 🟡 [MEDIUM] coordinator/api/tool_constraint_schema.go:1-370 — validateConstrainedSchema uses unbounded recursion and allocations
    • Suggestion: Add explicit limits on schema complexity, nesting depth, and property counts to prevent stack overflow and memory exhaustion
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/ForbiddenSubstringTokenConstraint.swift:1-352 — Complex automaton with multiple unbounded caches and search structures
    • Suggestion: Add cache size limits and LRU eviction to prevent unbounded memory growth during long inference sessions
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/GemmaToolCallTokenConstraint.swift:1-305 — Multiple unbounded caches without eviction policies
    • Suggestion: Implement cache size limits and LRU eviction for transitionCache, allowedCache, completionCache, and viabilityEnvelopeCache

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

6 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
@Gajesh2007
Gajesh2007 dismissed ethenotethan’s stale review July 20, 2026 18:29

All six findings were reviewed and declined with direct source evidence. One alleged double call is a single Go multi-value assignment; schema/history allocations are bounded by the 16 MiB ingress cap plus explicit depth/property/enum/array/grammar limits; and automaton caches are per-request with finite grammar/stop/max-token bounds. All threads are resolved; full local suites and the pre-push hook pass.

@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: 49fbffb49e

ℹ️ 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/registry/scheduler.go Resolved
Fail constrained waiters immediately when their last capable provider disconnects, keep Go/Rust/Swift schema costs and null bounds aligned, and make auto validation honor tuple arrays plus JSON-Schema integral doubles. Add regressions for every review finding so failures stay pre-dispatch and schema-valid output remains accepted.

Co-authored-by: Cursor <cursoragent@cursor.com>
Replace the pre-merge feature gitlink with the exact mlx-swift-lm main commit produced by PR #80 so parent CI and future checkouts consume the canonical merged dependency.

Co-authored-by: Cursor <cursoragent@cursor.com>
@Gajesh2007

Copy link
Copy Markdown
Member Author

Engine dependency merged and canonical pin updated:

git diff --quiet 6aa76e5 aa1cf87 confirms the feature and merged commits are tree-identical. After checking out fetched origin/main, focused merged-engine parser/sampler/MTP tests passed 22/22 and focused parent production-wiring/tool-constraint tests passed 57/57. The parent gitlink now records exactly aa1cf8721c4cae2b35c2a87adb14454ecb724e3c; push was normal and the pre-push hook passed.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ⚠️ SKIPPED

Error: Expecting property name enclosed in double quotes: line 2 column 5 (char 6)

Performance — 5 finding(s) (5 blocking)

  • 🟡 [MEDIUM] coordinator/api/tool_constraint_history.go:20 — map allocation without pre-sizing in hot validation path
    • Suggestion: Pre-allocate outstanding map with estimated capacity based on typical tool call counts: outstanding := make(map[string]struct{}, len(messages)/4)
  • 🟡 [MEDIUM] coordinator/api/tool_constraint_schema.go:378 — slice growth in hot schema validation without pre-allocation
    • Suggestion: Pre-allocate members slice: members := make([]string, 0, len(arr)) to avoid repeated allocations during type processing
  • 🔴 [CRITICAL] provider-swift/Sources/ProviderCore/Inference/ForbiddenSubstringTokenConstraint.swift:67 — NSLock blocking in token constraint hot path during inference
    • Suggestion: Use lock-free data structures or per-request constraint instances to avoid blocking during token generation
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/GemmaTokenVocabulary.swift:31-45 — synchronous tokenizer vocabulary building can block inference requests
    • Suggestion: Build vocabulary asynchronously during model loading or use lazy initialization with single-flight pattern to avoid blocking inference
  • 🟡 [MEDIUM] coordinator/api/tool_constraints.go:225-235 — repeated tool schema validation for same tools across requests
    • Suggestion: Cache compiled tool schemas by hash of tool definitions to avoid revalidating identical schemas

Type_diligence — ✅ No issues found

Additive_complexity — ✅ No issues found

5 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/api/tool_constraints.go Resolved

@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: 8eae0c0e72

ℹ️ 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 Resolved
Comment thread coordinator/registry/scheduler.go Resolved
Comment thread coordinator/api/inference_preprocess.go Resolved
Typeless assertion-only schemas now infer the type family their assertions constrain (mixed families rejected pre-inference in Go/Rust/Swift), pattern literals compare by Unicode scalar sequence, count bounds accept integral doubles, and the no-tool constraint's prefix table is precomputed instead of rebuilt per byte.

Co-authored-by: Cursor <cursoragent@cursor.com>

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 76 out of 76 changed files in this pull request and generated 1 comment.

@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: fb564fccc1

ℹ️ 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".

Empty positional schemas normalize to the boolean-true marker shape so auto validation keeps allow-all semantics while grammar modes still compile the free string; raw validation compares declared/required property names by Unicode scalar sequence.

Co-authored-by: Cursor <cursoragent@cursor.com>

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 76 out of 76 changed files in this pull request and generated 2 comments.

Comments suppressed due to low confidence (1)

coordinator/api/inference_preprocess.go:122

  • marshalForwardBody errors are ignored when normalizing a scalar stop into an array. If marshaling ever fails, the request would be forwarded with a stale/partially-normalized body, making failures hard to diagnose. Handle the error and return a 400 instead of discarding it.
	if stop, ok := parsed["stop"].(string); ok {
		parsed["stop"] = []any{stop}
		rawBody, _ = marshalForwardBody(parsed)
	}

The corpus's empty {} schema nodes now normalize to the boolean-true marker shape, so the pinned normalized bodies gain the marker key; rendered prompts and token vectors are unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>

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 76 out of 76 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

coordinator/api/inference_preprocess.go:122

  • In the stop scalar → array normalization, marshalForwardBody errors are ignored and rawBody can become nil on failure (since the first return value is nil when err != nil). Even if unlikely with JSON-originated maps, this would propagate a nil body into downstream dispatch/encryption paths. Safer to only overwrite rawBody on successful re-marshal.
	if stop, ok := parsed["stop"].(string); ok {
		parsed["stop"] = []any{stop}
		rawBody, _ = marshalForwardBody(parsed)
	}

@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: 66ecd5fa07

ℹ️ 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/toolschema.go Resolved
Comment thread coordinator/api/consumer.go Resolved
…mirror

Tool-less endpoint-native shapes the contract lowering cannot express keep the pre-existing verbatim-forward behavior instead of a new 400 (only tool-bearing requests fail closed); typeless not schemas are rejected before inference in Go/Rust/Swift; the raw-attestation register encoder mirrors prefix_cache_v2_models.

Co-authored-by: Cursor <cursoragent@cursor.com>

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 76 out of 76 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (2)

coordinator/api/inference_preprocess.go:122

  • marshalForwardBody errors are ignored when normalizing a scalar stop into an array. If encoding ever fails, rawBody becomes nil/empty and the request may be forwarded or further processed with an invalid body. Handle the error and return a standard invalid_request_error instead of silently discarding it.
	if stop, ok := parsed["stop"].(string); ok {
		parsed["stop"] = []any{stop}
		rawBody, _ = marshalForwardBody(parsed)
	}

provider-swift/Sources/ProviderCore/Coordinator/CoordinatorClientCodec.swift:191

  • models_update always advertises tool_constraint_protocol: 1 even when toolConstraintModelIDs(models) is empty. This is inconsistent with registration (which omits the protocol when there are no eligible models) and can create confusing wire semantics (protocol v1 but zero enforced models).

@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: 3fab6d576c

ℹ️ 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/toolschema.go Resolved
Comment thread coordinator/api/tool_constraints.go Resolved
Comment thread coordinator/api/tool_constraints.go Resolved
…lel Responses streams

Round 5 review fixes, mirrored across Go/Rust/Swift where applicable:

- Fold constant boolean combinators (allOf/anyOf/oneOf over {}/true/false
  members) to the render marker instead of inheriting a synthetic string
  type, so allOf:[{}] keeps allow-all semantics; marker members no longer
  feed parent union type inference.
- Reject $dynamicRef/$recursiveRef in auto preflight (unresolvable refs
  previously slipped through as render-only string types).
- Accept exactly-integral decimal count bounds (minItems: 1.0, 2e0) in
  constrained mode via a linear exact parse (no bignum: json.Number is
  attacker-length, a superlinear parse is free coordinator CPU).
- Auto/none forward provider-droppable hosted/custom tools instead of
  400ing, restoring InboundChatNormalization compatibility; representable
  alternate spellings (top-level name, input_schema) keep full pre-dispatch
  validation; required/named still reject.
- Responses stream emitter tracks logical tool calls by changing non-empty
  IDs (the engine emits every parallel call at wire index 0), matching the
  non-streaming accumulator, including its logical-call cap.

Co-authored-by: Cursor <cursoragent@cursor.com>

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 77 out of 77 changed files in this pull request and generated no new comments.

…nt scan

Co-authored-by: Cursor <cursoragent@cursor.com>

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 77 out of 77 changed files in this pull request and generated 1 comment.

Comment on lines +80 to +82
if len(outstanding) > 0 && lastDeclaration != len(messages)-1 {
return invalidToolConstraint("assistant tool calls are missing tool results", "messages")
}

@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: 3397541f1f

ℹ️ 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 on lines +221 to +222
if requiresToolConstraint && !policy.enabled && !policy.prefer &&
!s.registry.HasToolConstraintProviderForModel(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 Fail incapable prefer-owner routes before queueing

When a constrained request uses prefer-owner routing but neither the owner's machines nor the public fleet advertises protocol-v1 capability, this condition skips the only fail-fast check, and runInferenceAdmission also deliberately bypasses public preflight for prefer mode. The request is therefore enqueued with no provider that can ever accept it and receives ErrQueueToolConstraintUnavailable only if a later heartbeat or other drain happens; with no such event it waits the full 120-second queue timeout and returns a misleading capacity error. Perform an owner-aware capability check before allowing this path into the queue.

AGENTS.md reference: AGENTS.md:L219-L219

Useful? React with 👍 / 👎.

Comment on lines +710 to +714
case .double(let value):
if value.isFinite, let integer = Int(exactly: value) {
return .integer(integer)
}
return .floating(value.bitPattern)

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 Preserve exact decimals in auto finite-value validation

When an auto schema contains a non-integral numeric enum or const, both the schema number and generated argument are narrowed to Double before this identity is built. Distinct JSON numbers can consequently compare equal: an enum containing 0.10000000000000001 accepts a generated 0.1 because both decode to the same bit pattern, so schema-invalid tool arguments are returned. Preserve the source decimal representation or reject non-integral numeric finite assertions on the auto path, as constrained mode already does.

Useful? React with 👍 / 👎.

Comment on lines +346 to +347
_, err := number.Int64()
return err == 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 Accept mathematically integral enum values

When a required or named schema declares type: "integer" with enum: [1.0] or const: 1e0, json.Number.Int64() rejects the decimal/exponent spelling and the coordinator returns 400 even though JSON Schema classifies any number with zero fractional part as an integer. The count-bound parser added in this change already handles the same valid spellings; use equivalent exact integral parsing for integer finite values (and mirror it in the Rust validator).

Useful? React with 👍 / 👎.

Comment on lines +1867 to +1869
if t.Previous != "" && r.anyEligibleProviderCanRouteWithTraitsLocked(
t.Previous, nil, "", false, false, now, traits,
) {

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 Queue the capable previous build while it reloads

When an alias's Desired build has only legacy providers and Previous has the sole protocol-v1 provider, this probe still calls providerCanRouteBuildLocked, which rejects transient states such as a reloading slot or an active load cooldown. If Previous is temporarily in that state, both probes fail and the unconstrained branch defaults back to Desired; the subsequent capability gate then returns 503 even though Previous is structurally capable and could serve after a queue wait. Add a structural-capability fallback for the eligible Previous build before defaulting to Desired.

Useful? React with 👍 / 👎.

{
return false
}
let matching = patterns.filter { safePatternMatches(name, pattern: $0.key) }

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 Fail closed on oversized pattern-property names

When generated auto arguments contain a property name longer than 16 KiB, safePatternMatches returns false solely because of its input-size guard, but this caller treats that result as a genuine non-match. For example, with patternProperties: {"^x": false} and default-allowed additional properties, a long key beginning with x bypasses the rejecting pattern and is accepted. Distinguish an oversized/error result from a real pattern miss and reject the arguments in that case.

Useful? React with 👍 / 👎.

Comment on lines +535 to +536
if hasNull && hasConcrete {
return true

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 Preserve null-only auto unions

The remaining null-only union case is not preserved: an auto property such as {"anyOf":[{"type":"null"}]} passes preflight, but this helper refuses to mark the parent nullable because there is no concrete member. Normalization then injects the fallback parent type: "string", so the raw validator rejects the only schema-valid value, null, with tool_noncompliance; a single-member oneOf has the same problem. Infer a null parent or otherwise retain the original union semantics when a union contains only null members.

Useful? React with 👍 / 👎.

Comment on lines +137 to +140
let toolConstraintTemplateHash =
Gemma4ToolConstraintContract.supports(modelType: modelType)
? Gemma4ToolConstraintContract.templateSHA256(at: snapshotDir)
: 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.

P1 Badge Move template hashing out of startup discovery

Every startup discovery of a Gemma snapshot now reads and SHA-256-hashes chat_template.jinja inside ModelScanner.parseModelInfo. This puts hashing directly back on the startup scan path, so scan latency and I/O grow with the installed Gemma catalog; derive the capability from cached/published metadata or compute it lazily outside discovery instead.

AGENTS.md reference: AGENTS.md:L216-L216

Useful? React with 👍 / 👎.

case object([JSONSchemaValueIdentity])
}

enum ToolConstraintValidation {

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 Split the tool validator into focused modules

This new 994-line type combines policy enforcement, recursive schema evaluation, schema-support preflight, Unicode identities, safe-pattern matching, count parsing, exact decimal divisibility, and numeric comparison in one file. Keeping these independent concerns together makes the three-runtime schema contract substantially harder to audit and update without semantic drift; extract focused schema-walk, identity/pattern, and numeric-validation modules while retaining a thin validation entry point.

AGENTS.md reference: AGENTS.md:L250-L253

Useful? React with 👍 / 👎.

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 77 out of 77 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: 60bdb41b8d

ℹ️ 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 on lines +692 to +693
if _, negated := dict["not"]; negated && len(families) == 0 {
return true

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 typeless not beside inferred-family assertions

Fresh evidence beyond the earlier not-only fix is a schema such as {"minimum":5,"not":{"type":"string"}}: this condition permits it because one assertion family exists, then normalization injects type: "number". The original schema also accepts non-string, non-numeric values such as true (minimum is inapplicable and not succeeds), but post-generation validation rejects them against the synthetic number type, producing tool_noncompliance for schema-valid output. Reject typeless not whenever the other evidence cannot prove that narrowing to one type preserves its semantics.

Useful? React with 👍 / 👎.

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — 60bdb41b Deployed Jul 22, 2026 by vercel[bot]
Preview – d-inference — 60bdb41b Deployed Jul 22, 2026 by vercel[bot]
Preview – d-inference-landing — 60bdb41b Deployed Jul 22, 2026 by vercel[bot]
benchmarks — 60bdb41b Deployed Jul 22, 2026 by Gajesh2007 via E2E Benchmarks #1825
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.

3 participants