Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions changelog.d/gemma-tool-union-render-type.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
### Gemma 4 tool parameters typed as a string-first union render their typed member

A tool parameter declared as a union of `string` and one other scalar type,
for example `{"type": ["string", "integer"]}` or an `anyOf` / `oneOf` of the
two, was shown to Gemma 4 as `STRING`: its template prints a single type and
never the union, and the schema repair picked the first member. Gemma then
quoted typed values (`"-4200"` for `-4200`). Gemma 4 now sees the other member
(`INTEGER`, `NUMBER` or `BOOLEAN`); a `null` member still renders as
`nullable`. The union itself stays in the request, so validation accepts both
members as before. Unions with more members, other types or an `enum` keep
`STRING`, and other model families are unchanged.

A Gemma 4 tool parameter declared without any type (`{}`, any value) was also
shown as `STRING`, the type the schema repair fills in, so Gemma quoted its
values. Gemma 4 now sees it untyped (`type:<|"|><|"|>`), as the template
renders a typeless property; this reads the caller's declarations as sent.

The prompt contract stays `darkbloom-request-normalization-v9`, which still
renders `STRING`, so a coordinator request whose Gemma tool declaration either
change affects is served without the prompt cache, like requests whose tool-call
history carries a null. `darkbloom logs` notes each such request and the
daemon state counts them (`promptCacheSkippedToolUnionType`).
19 changes: 19 additions & 0 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -5164,6 +5164,25 @@ history and already kept these nulls. Such a request still plans and counts
under normalization v9, which drops them, so it is served without the
coordinator's prompt cache ([prefix cache](prefix-cache.md)).

Gemma 4's `format_parameters` prints one render type per parameter and never
`anyOf` / `oneOf`. The shared schema repair (`ToolSchemaNormalization`) gives
a union the first non-null member's type, so a `string`-first union of
`string` and one other scalar type rendered `STRING` and the model quoted
typed values. Gemma's tool enforcement now renders the other member there
(`INTEGER`, `NUMBER`, `BOOLEAN`; invariant 7 in
`provider-swift/Sources/ProviderCore/Inference/Tools/Gemma4ToolSchemaEnforcement.swift`).
The union stays on the wire, so the validator and constrained decoding, which
read the request's tools rather than the render input, accept both members.
Unions with more members, non-scalar members or an `enum` keep `STRING`, and
other families keep the shared repair's render type. A property the caller
declared without any type or schema keyword (`{}`) renders an empty type
(`type:<|"|><|"|>`, the served template's rendering of a typeless property)
instead of the injected `string` (invariant 8). Gemma's render reads the
caller's declarations as sent (`ChatTemplateControls.declaredTools`) on every
path that renders a coordinator request: serving, prompt recount and the
diffusion media path. Such a request is also
served without the coordinator's prompt cache ([prefix cache](prefix-cache.md)).

A template `raise_exception` at request time is classified `jinja_template`
and returned as HTTP 500, the provider-fault class, so a caller control that
a template is known to reject must be resolved before rendering. The
Expand Down
11 changes: 11 additions & 0 deletions docs/architecture/prefix-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,17 @@ still come from the planned context. `darkbloom logs` notes each such request
and the daemon state counts them (`promptCacheSkippedToolCallNull`)
(`provider-swift/Sources/ProviderCore/Inference/PrefixCache/ToolCallHistoryNullCache.swift`).

A Gemma 4 request is served cold the same way when its declared tools carry a
parameter whose `string`-first union of `string` and one other scalar type now
renders as that other type, or a parameter declared without a type that now
renders untyped (`Gemma4ToolSchemaEnforcement` invariants 7 and 8), while
normalization v9 renders `STRING`. The check runs the shared tool path once
more on the declared tools, a superset of the rendered ones, and reports
whether invariant 7 or 8 changed a render type
(`ChatTemplateFixes.changesGemmaToolRenderType`,
`provider-swift/Sources/ProviderCore/Inference/PrefixCache/GemmaToolUnionTypeCache.swift`);
its counter is `promptCacheSkippedToolUnionType`.

Native MiMo historical checkpoints retain only actual uniform-chunk frontiers
whose target and optional assistant state completed their native observation
and promotion fences. Their fork target is the deepest successfully captured
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ public final class AtomicProviderStats: Sendable {
// cache because their tool-call history carries a null argument
// (`ToolCallHistoryNullCache`).
private let _promptCacheSkippedToolCallNull = ManagedAtomic<UInt64>(0)
// The same for a Gemma tool union rendered as its typed member
// (`GemmaToolUnionTypeCache`).
private let _promptCacheSkippedToolUnionType = ManagedAtomic<UInt64>(0)

public init() {}

Expand Down Expand Up @@ -175,6 +178,12 @@ public final class AtomicProviderStats: Sendable {
_promptCacheSkippedToolCallNull.add(1)
}

public var promptCacheSkippedToolUnionType: UInt64 { _promptCacheSkippedToolUnionType.load() }

public func incrementPromptCacheSkippedToolUnionType() {
_promptCacheSkippedToolUnionType.add(1)
}

public func incrementGenerationErrorsAfterOutput() {
_generationErrorsAfterOutput.add(1)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import MLXLMServer

/// A Gemma tool parameter whose render type changed while the prompt contract
/// the coordinator plans and counts with (normalization v9) still renders the
/// shared normalizer's: a union of `string` and one other scalar type with
/// `string` first renders as the other type, and a property declared without a
/// type renders an empty type (`Gemma4ToolSchemaEnforcement` invariants 7 and
/// 8). Such a request is served without the coordinator's prompt cache, as
/// `ToolCallHistoryNullCache` serves its requests; every other request keeps
/// its context.
enum GemmaToolUnionTypeCache {
/// Whether the request's declared tools get a changed Gemma render type.
/// Its tools are a superset of the rendered ones (tool choice only narrows
/// them), so this never misses a changed prompt. `declared` are the
/// caller's declarations as sent (`ChatTemplateControls.declaredTools`).
static func changesRender(
_ request: OpenAIChatCompletionRequest, modelType: String?, declared: [OpenAITool]? = nil
) -> Bool {
guard let tools = request.tools, !tools.isEmpty else { return false }
return ChatTemplateFixes.changesGemmaToolRenderType(
tools.map { $0.toolSpec() }, context: .init(modelId: request.model, modelType: modelType),
declared: declared)
}

/// The cache context `request` is served with: `context`, or one without a
/// scope or receipt nonce when `context` still plans a cache attempt and
/// the request's Gemma tool render changed. `servedCold` reports that case.
static func servingContext(
_ context: RemotePrefixCacheContext, for request: OpenAIChatCompletionRequest, modelType: String?,
declared: [OpenAITool]? = nil
) -> (context: RemotePrefixCacheContext, servedCold: Bool) {
guard context.scope != nil || context.receiptNonce != nil,
changesRender(request, modelType: modelType, declared: declared)
else { return (context, false) }
return (RemotePrefixCacheContext(cacheScope: nil, cacheReceiptNonce: nil), true)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ struct ChatTemplateFixContext: Sendable {
enum ChatTemplateFixes {
/// Share the native turn/tool input format without broadening Gemma's
/// separate autoregressive grammar eligibility predicate.
private static func usesGemmaInputFormat(_ context: ChatTemplateFixContext) -> Bool {
static func usesGemmaInputFormat(_ context: ChatTemplateFixContext) -> Bool {
context.modelType == "diffusion_gemma" || Gemma4TemplateFix.applies(to: context)
}

Expand Down Expand Up @@ -64,9 +64,13 @@ enum ChatTemplateFixes {
return Qwen35TemplateFix.normalizeMessages(messages)
}

/// `declared` are the caller's tool declarations as sent, before ingress
/// normalization (`ChatTemplateControls.declaredTools`); Gemma's render
/// reads them (`Gemma4ToolSchemaEnforcement` invariant 8).
static func normalizeTools(
_ tools: [[String: any Sendable]]?,
context: ChatTemplateFixContext
context: ChatTemplateFixContext,
declared: [OpenAITool]? = nil
) -> [[String: any Sendable]]? {
let metadataScoped = normalizeToolMetadata(tools, context: context)
if MiMoV26TemplateFix.applies(to: context) {
Expand All @@ -80,11 +84,26 @@ enum ChatTemplateFixes {
return GPTOSSHarmonyTemplateFix.normalizeTools(sanitized)
}
if usesGemmaInputFormat(context) {
return Gemma4TemplateFix.normalizeTools(sanitized)
return Gemma4TemplateFix.normalizeTools(sanitized, declared: declared?.map { $0.toolSpec() })
}
return sanitized
}

/// Whether `normalizeTools` gives these tools a Gemma render type that
/// differs from the shared normalizer's (`Gemma4ToolSchemaEnforcement`
/// invariants 7 and 8), on the same input path.
static func changesGemmaToolRenderType(
_ tools: [[String: any Sendable]]?,
context: ChatTemplateFixContext,
declared: [OpenAITool]? = nil
) -> Bool {
guard usesGemmaInputFormat(context),
let sanitized = sanitizeTools(normalizeToolMetadata(tools, context: context))
else { return false }
return Gemma4ToolSchemaEnforcement.normalizeToolSpecsReportingRenderType(
sanitized, declared: declared?.map { $0.toolSpec() }).changedRenderType
}

/// Native media producers preserve their own message/schema representation,
/// but must apply the same model-scoped SDK metadata policy as text requests.
static func normalizeToolMetadata(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ enum Gemma4TemplateFix {
}

static func normalizeTools(
_ tools: [[String: any Sendable]]
_ tools: [[String: any Sendable]],
declared: [[String: any Sendable]]? = nil
) -> [[String: any Sendable]] {
Gemma4ToolSchemaEnforcement.normalizeToolSpecs(tools)
Gemma4ToolSchemaEnforcement.normalizeToolSpecs(tools, declared: declared)
}

static func extraEOSTokenIds(tokenToId: (String) -> Int?) -> Set<Int> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ enum ProviderPromptContractPipeline {
}
return try NormalizedInput(
messages: ChatTemplateFixes.normalizeMessages(messages, context: context),
tools: ChatTemplateFixes.normalizeTools(tools, context: context),
tools: ChatTemplateFixes.normalizeTools(tools, context: context, declared: templateControls.declaredTools),
additionalContext: additionalContext)
}
}
Loading
Loading