Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Refuse unknown request fields, accept auto as the prefill cap (#171)
Andrey Mikhaylov6c044011c24d
diff --git a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swiftindex 8105b3e6..d8e44b60 100644--- a/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift+++ b/Sources/TurboFieldfare/Runtime/Configuration/RuntimeConfiguration.swift@@ -23,6 +23,29 @@ public struct RuntimeConfiguration: Sendable, Equatable {public static let allowedExpertCacheSlots = [8, 16, 24, 32]public static let allowedPrefillChunkTokens = PrefillRuntimeConfig.allowedChunkTokenspublic static let minimumExpertCacheSlotsForChunkedPrefill = 16+ /// The one rendering shared by every help text and every rejection that+ /// names one of the arrays above, so neither can name a value the guard+ /// does not accept: the hardcoded "32, 64, or 128" outlived the widening of+ /// the allowed set and told users 256 was illegal while the guard accepted+ /// it. It lives here, beside the arrays, because the CLI's usage and the+ /// server's usage and rejections all render the same sets.+ ///+ /// `alsoAccepting` appends parse-level aliases after the integers, so+ /// `--prefill-chunk-tokens` renders "32, 64, 128, 256, or auto". They come+ /// last because they are not members of the array the guards test, and+ /// because the help line's integers are read back by+ /// `usageNamesExactlyTheAllowedValues`.+ public static func allowedValueList(_ values: [Int],+ alsoAccepting aliases: [String] = []) -> String {+ let words = values.map(String.init) + aliases+ switch words.count {+ case 0: return ""+ case 1: return words[0]+ case 2: return "\(words[0]) or \(words[1])"+ default:+ return words.dropLast().joined(separator: ", ") + ", or " + words[words.count - 1]+ }+ }public let expertCacheSlots: Intpublic let expertCachePolicy: RuntimeExpertCachePolicydiff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swiftindex d816df34..524edc88 100644--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {// Most users build from a clone, where there is no Info.plist to read a// version from, so this constant is what they see. Scripts/check_app_version.rb// fails CI when it falls behind the newest published release.- public static let fallbackShortVersion = "0.7.1"+ public static let fallbackShortVersion = "0.7.2"private static let licenseURL = URL(string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!diff --git a/Sources/TurboFieldfareCLI/Args.swift b/Sources/TurboFieldfareCLI/Args.swiftindex de719331..95d2550a 100644--- a/Sources/TurboFieldfareCLI/Args.swift+++ b/Sources/TurboFieldfareCLI/Args.swift@@ -102,6 +102,16 @@ public enum ArgsError: Error, Equatable, CustomStringConvertible {}extension Args {+ /// Whether `--prefill-chunk-tokens auto` has a size to resolve at all.+ ///+ /// Under `--prefill off` the config is `.off` and the size is inert, and an+ /// image turn there is coerced to the runtime's own chunked default rather+ /// than to a resolved size, so resolving one would only announce a number+ /// nothing goes on to use.+ public var resolvesPrefillChunkAuto: Bool {+ prefillChunkTokensAuto && prefillPolicy != .off+ }+public static let usage = """TurboFieldfareCLI — Gemma 4 26B-A4B text generation@@ -129,12 +139,12 @@ extension Args {--seed <uint64> Deterministic sampling seed (default off).--stop <string> Stop substring (repeatable).--quiet Suppress the timing footer.- --expert-cache-slots <n> Expert-cache slots: 8, 16, 24, or 32 (default 16).+ --expert-cache-slots <n> Expert-cache slots: \(RuntimeConfiguration.allowedValueList(RuntimeConfiguration.allowedExpertCacheSlots)) (default 16).--expert-cache-policy <s> Expert-cache policy: lfu or lru (default lfu).--prefill on|off Enable or disable chunked prompt prefill (default on).Chunked prefill requires 16 or more cache slots.--prefill-chunk-tokens <n|auto>- Prefill chunk size: 32, 64, 128, 256, or auto+ Prefill chunk size: \(RuntimeConfiguration.allowedValueList(RuntimeConfiguration.allowedPrefillChunkTokens, alsoAccepting: ["auto"]))(default 128). Each chunk re-reads the routedexpert pool, so larger chunks read less; autopicks the smallest size that covers the prompt.@@ -306,6 +316,9 @@ extension Args {RuntimeConfiguration.allowedPrefillChunkTokens.contains(parsed) else {throw ArgsError.invalidValue(flag: flag, value: value)}+ // A repeated flag is last-one-wins in both directions: without+ // this clear, an explicit size after `auto` parses and is then+ // overridden at run time by the resolved size.prefillChunkTokensAuto = falseprefillChunkTokens = parsedcase "--rdadvise":diff --git a/Sources/TurboFieldfareCLI/Run.swift b/Sources/TurboFieldfareCLI/Run.swiftindex 4995d257..9143a294 100644--- a/Sources/TurboFieldfareCLI/Run.swift+++ b/Sources/TurboFieldfareCLI/Run.swift@@ -108,7 +108,7 @@ public func run(args: Args,}var effectiveArgs = args- if args.prefillChunkTokensAuto {+ if args.resolvesPrefillChunkAuto {let promptTokens = try estimatedPromptTokens(input: input, tokenizer: tokenizer, device: device)effectiveArgs.prefillChunkTokens =diff --git a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift b/Sources/TurboFieldfareServer/Core/OpenAIModels.swiftindex 0430585a..3d6a5bff 100644--- a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift+++ b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift@@ -134,6 +134,36 @@ public struct OpenAIStreamOptions: Codable, Equatable, Sendable {}}+/// Bounds what a rejection quotes back. The body cap is 5 MiB, so a caller must+/// not be able to have an arbitrary slice of its own request echoed back;+/// `String(reflecting:)` also escapes a value that embeds a quote, which would+/// otherwise read as two values.+private func boundedQuoted(_ text: String, maxLength: Int) -> String {+ String(reflecting: bounded(text, maxLength: maxLength))+}++/// The unquoted form, for an error's `param`. A `param` names a field rather+/// than quoting prose, but it needs the same bound: an unknown key is echoed+/// back out of the request body, and the 5 MiB body cap is the only other+/// limit on how long that key can be.+///+/// The bound is in UTF-8 bytes, never Characters: one Character can carry+/// megabytes of combining marks, so a Character-counted prefix of a key like+/// "a" followed by a million U+0301 is the whole key. Cutting between scalars+/// may split a grapheme, which is harmless in a diagnostic.+private func bounded(_ text: String, maxLength: Int) -> String {+ var bytes = 0+ var head = String.UnicodeScalarView()+ for scalar in text.unicodeScalars {+ bytes += scalar.utf8.count+ if bytes > maxLength {+ return String(head) + "..."+ }+ head.append(scalar)+ }+ return text+}+public struct OpenAIChatRequest: Codable, Equatable, Sendable {public let model: Stringpublic let messages: [OpenAIChatMessage]@@ -154,6 +184,11 @@ public struct OpenAIChatRequest: Codable, Equatable, Sendable {public let logprobs: Bool?public let presencePenalty: Float?public let frequencyPenalty: Float?+ /// Kept as raw JSON. Only `type` is ever read, because the rest of a+ /// `response_format` describes a schema this server cannot honour, and a+ /// value of any other shape has to reach the validator as a request error+ /// rather than reading as malformed JSON.+ public let responseFormat: JSONValue?enum CodingKeys: String, CodingKey {case model, messages, stream, temperature, stop, seed, tools, n, logprobs@@ -167,6 +202,131 @@ public struct OpenAIChatRequest: Codable, Equatable, Sendable {case repetitionPenalty = "repetition_penalty"case presencePenalty = "presence_penalty"case frequencyPenalty = "frequency_penalty"+ case responseFormat = "response_format"+ }++ /// Top-level keys accepted and ignored because they are caller-side+ /// bookkeeping that cannot change what the model generates. Every other+ /// undeclared key is a 400, so a misspelled option cannot silently+ /// generate under settings the caller did not ask for. This set is the+ /// only place the list lives; the OpenAI server doc quotes it.+ static let toleratedKeys: Set<String> = [+ "user",+ "store",+ "metadata",+ "service_tier",+ "prompt_cache_key",+ "safety_identifier",+ ]++ /// Real OpenAI parameters this server cannot honour. They are refused as+ /// unsupported rather than unknown, so a caller sending a parameter that+ /// exists is not told it looks like a typo. Refused here, before the typed+ /// decode, so the answer is the same beside a mistyped declared field as+ /// alone; a refusal left to the validator would lose to whatever+ /// DecodingError the typed decode raised first.+ static let unsupportedKeys: Set<String> = [+ "logit_bias",+ "top_logprobs",+ "reasoning_effort",+ "verbosity",+ "modalities",+ "audio",+ "prediction",+ "web_search_options",+ "functions",+ "function_call",+ ]++ /// Refusals that can point at the supported replacement. Every other+ /// member of `unsupportedKeys` is refused with the plain form.+ static let unsupportedKeyMessages: [String: String] = [+ "functions": "legacy functions are not supported; use tools",+ "function_call": "legacy function_call is not supported; use tools and tool_choice",+ ]++ /// Reads the request object's keys as written, which the `CodingKeys`+ /// container cannot: that one reports only the keys it declares, so an+ /// undeclared key is discarded before validation could see it.+ private struct AnyKey: CodingKey {+ let stringValue: String+ var intValue: Int? { nil }++ init?(stringValue: String) { self.stringValue = stringValue }+ init?(intValue: Int) { nil }+ }++ private static let maximumNamedKeyLength = 64+ private static let maximumNamedKeys = 8++ private static func renderedKeyNames(_ names: [String]) -> String {+ let shown = names.prefix(maximumNamedKeys).map {+ boundedQuoted($0, maxLength: maximumNamedKeyLength)+ }+ let listed = shown.joined(separator: ", ")+ let remaining = names.count - shown.count+ return remaining > 0 ? "\(listed), and \(remaining) more" : listed+ }++ public init(from decoder: any Decoder) throws {+ // The key sweep runs before any typed decode, so a misspelled key is+ // named as itself rather than answered with whatever DecodingError+ // another field happens to raise first.+ let anyKeys = try decoder.container(keyedBy: AnyKey.self)+ // A key set to null asks for nothing: openai-python sends an unset+ // option as an explicit `null`, and the declared keys already read null+ // as absent through `decodeIfPresent`.+ let written = try anyKeys.allKeys+ .filter { try !anyKeys.decodeNil(forKey: $0) }+ .map(\.stringValue)+ // Sorted throughout so the answer never depends on the order the keys+ // arrived in.+ if let unsupported = written.filter(Self.unsupportedKeys.contains).sorted().first {+ throw ServerRequestError.invalid(+ message: Self.unsupportedKeyMessages[unsupported]+ ?? "\(unsupported) is not supported",+ param: unsupported,+ code: "unsupported_value")+ }+ let unknown = written+ .filter { CodingKeys(stringValue: $0) == nil && !Self.toleratedKeys.contains($0) }+ .sorted()+ if let first = unknown.first {+ throw ServerRequestError.invalid(+ message: "unrecognized request field\(unknown.count == 1 ? "" : "s") "+ + Self.renderedKeyNames(unknown),+ param: bounded(first, maxLength: Self.maximumNamedKeyLength),+ code: "unknown_parameter")+ }++ let container = try decoder.container(keyedBy: CodingKeys.self)+ model = try container.decode(String.self, forKey: .model)+ messages = try container.decode([OpenAIChatMessage].self, forKey: .messages)+ stream = try container.decodeIfPresent(Bool.self, forKey: .stream)+ streamOptions = try container.decodeIfPresent(+ OpenAIStreamOptions.self, forKey: .streamOptions)+ temperature = try container.decodeIfPresent(Float.self, forKey: .temperature)+ topP = try container.decodeIfPresent(Float.self, forKey: .topP)+ maxTokens = try container.decodeIfPresent(Int.self, forKey: .maxTokens)+ maxCompletionTokens = try container.decodeIfPresent(+ Int.self, forKey: .maxCompletionTokens)+ stop = try container.decodeIfPresent(OpenAIStop.self, forKey: .stop)+ seed = try container.decodeIfPresent(UInt64.self, forKey: .seed)+ tools = try container.decodeIfPresent([OpenAITool].self, forKey: .tools)+ toolChoice = try container.decodeIfPresent(JSONValue.self, forKey: .toolChoice)+ parallelToolCalls = try container.decodeIfPresent(+ Bool.self, forKey: .parallelToolCalls)+ topK = try container.decodeIfPresent(Int.self, forKey: .topK)+ repetitionPenalty = try container.decodeIfPresent(+ Float.self, forKey: .repetitionPenalty)+ n = try container.decodeIfPresent(Int.self, forKey: .n)+ logprobs = try container.decodeIfPresent(Bool.self, forKey: .logprobs)+ presencePenalty = try container.decodeIfPresent(+ Float.self, forKey: .presencePenalty)+ frequencyPenalty = try container.decodeIfPresent(+ Float.self, forKey: .frequencyPenalty)+ responseFormat = try container.decodeIfPresent(+ JSONValue.self, forKey: .responseFormat)}}@@ -337,10 +497,7 @@ private enum OpenAIToolName {}static func validationMessage(for name: String) -> String {- let prefix = name.prefix(maximumLength + 1)- let displayed = String(prefix.prefix(maximumLength))- + (prefix.count > maximumLength ? "..." : "")- return "tool name \(String(reflecting: displayed)) must contain 1 to 64 ASCII letters, numbers, underscores, or hyphens"+ "tool name \(boundedQuoted(name, maxLength: maximumLength)) must contain 1 to 64 ASCII letters, numbers, underscores, or hyphens"}}@@ -375,7 +532,35 @@ public enum OpenAIRequestValidator {throw invalid("parallel_tool_calls=false is not supported","parallel_tool_calls", "unsupported_value")}-+ switch request.responseFormat {+ case nil:+ break+ case .object(let fields)?:+ switch fields["type"] {+ case nil, .null?:+ throw invalid("response_format.type is required",+ "response_format", "invalid_value")+ case .string(let type)?:+ switch type {+ case "text":+ break+ case "json_object", "json_schema":+ throw invalid("structured output is not supported",+ "response_format", "unsupported_value")+ default:+ throw invalid(+ "response_format type \(boundedQuoted(type, maxLength: 64)) "+ + "is not recognized",+ "response_format", "invalid_value")+ }+ default:+ throw invalid("response_format.type must be a string",+ "response_format", "invalid_value")+ }+ default:+ throw invalid(#"response_format must be an object such as {"type": "text"}"#,+ "response_format", "invalid_value")+ }let temperature = request.temperature ?? 0.2guard temperature >= 0, temperature <= 2 else {throw invalid("temperature must be between 0 and 2",diff --git a/Sources/TurboFieldfareServer/Core/ServerArguments.swift b/Sources/TurboFieldfareServer/Core/ServerArguments.swiftindex 8b1db046..56d3f740 100644--- a/Sources/TurboFieldfareServer/Core/ServerArguments.swift+++ b/Sources/TurboFieldfareServer/Core/ServerArguments.swift@@ -29,13 +29,19 @@ public struct ServerArguments: Equatable, Sendable {--queue-limit <count> Maximum queued requests (default 4).--prompt-cache-mode <off|single-prefix>Prompt KV reuse mode (default single-prefix).- --expert-cache-slots <n> Expert-cache slots: \(allowedValueList(RuntimeConfiguration.allowedExpertCacheSlots)) (default 16).+ --expert-cache-slots <n> Expert-cache slots: \(RuntimeConfiguration.allowedValueList(RuntimeConfiguration.allowedExpertCacheSlots)) (default 16).--expert-cache-policy <s> Expert-cache policy: lfu or lru (default lfu).--prefill on|off Enable or disable chunked prompt prefill (default on).Chunked prefill requires 16 or more cache slots.- --prefill-chunk-tokens <n> Prefill chunk size: \(allowedValueList(RuntimeConfiguration.allowedPrefillChunkTokens))+ --prefill-chunk-tokens <n|auto>+ Prefill chunk size: \(RuntimeConfiguration.allowedValueList(RuntimeConfiguration.allowedPrefillChunkTokens, alsoAccepting: ["auto"]))(default 128). Each chunk re-reads the routed- expert pool, so larger chunks read less.+ expert pool, so larger chunks read less; auto+ runs at the cap, 256, which prefills every+ prompt in the same spans a per-request size+ would. Prefill scratch is sized from the chunk,+ so the cap holds about 32.5 MB of it against+ 16.4 MB at 128.--rdadvise <s> Read-advice policy: off, default, bounded, or adaptive(default off).--help Show this help.@@ -56,7 +62,8 @@ public struct ServerArguments: Equatable, Sendable {guard RuntimeConfiguration.allowedPrefillChunkTokens.contains(prefillChunkTokens) else {throw ServerArgumentError.notAllowed(flag: "--prefill-chunk-tokens",- allowed: RuntimeConfiguration.allowedPrefillChunkTokens)+ allowed: RuntimeConfiguration.allowedPrefillChunkTokens,+ alsoAccepting: ["auto"])}guard prefillPolicy == .off|| expertCacheSlots >= RuntimeConfiguration.minimumExpertCacheSlotsForChunkedPrefill@@ -154,11 +161,25 @@ public struct ServerArguments: Equatable, Sendable {default: throw ServerArgumentError.invalid("--prefill must be on or off")}case "--prefill-chunk-tokens":+ // `auto` is an alias for the cap here, and nothing downstream+ // learns it was spelled that way. A per-request size is the+ // smallest allowed size that covers the span, so the cap+ // prefills every prompt in exactly the spans that size would,+ // and the KV ring is sized from the cap either way. The prefill+ // scratch is the one thing a per-request size changes: it is+ // allocated from the chunk, about 125.5 KB per token over a+ // fixed 328 KB, and the+ // server would reallocate it on every size change.+ if value == "auto" {+ prefillChunkTokens = PrefillRuntimeConfig.maxChunkTokens+ break+ }guard let parsed = Int(value),RuntimeConfiguration.allowedPrefillChunkTokens.contains(parsed) else {throw ServerArgumentError.notAllowed(flag: flag,- allowed: RuntimeConfiguration.allowedPrefillChunkTokens)+ allowed: RuntimeConfiguration.allowedPrefillChunkTokens,+ alsoAccepting: ["auto"])}prefillChunkTokens = parsedcase "--rdadvise":@@ -188,23 +209,6 @@ public struct ServerArguments: Equatable, Sendable {}}-extension ServerArguments {- /// The one rendering shared by the help text and every rejection, so neither- /// can name a value the guard does not accept: the hardcoded- /// "32, 64, or 128" outlived the widening of the allowed set and told users- /// 256 was illegal while the guard accepted it.- static func allowedValueList(_ values: [Int]) -> String {- let words = values.map(String.init)- switch words.count {- case 0: return ""- case 1: return words[0]- case 2: return "\(words[0]) or \(words[1])"- default:- return words.dropLast().joined(separator: ", ") + ", or " + words[words.count - 1]- }- }-}-public enum ServerArgumentError: Error, Equatable, CustomStringConvertible {case helpcase invalid(String)@@ -218,7 +222,10 @@ public enum ServerArgumentError: Error, Equatable, CustomStringConvertible {}extension ServerArgumentError {- static func notAllowed(flag: String, allowed: [Int]) -> ServerArgumentError {- .invalid("\(flag) must be \(ServerArguments.allowedValueList(allowed))")+ static func notAllowed(flag: String,+ allowed: [Int],+ alsoAccepting aliases: [String] = []) -> ServerArgumentError {+ .invalid("\(flag) must be "+ + RuntimeConfiguration.allowedValueList(allowed, alsoAccepting: aliases))}}diff --git a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swiftindex 9f12369b..8e54658d 100644--- a/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift+++ b/Tests/TurboFieldfare/Core/CLI/CLIArgumentsTests.swift@@ -24,6 +24,50 @@ import TurboFieldfare#expect(runtime == RuntimeConfiguration.production)}+ /// `auto` only resolves a size where a chunked prefill will run at it.+ /// Under `--prefill off` the config is `.off` and the size is inert, and an+ /// image turn there is coerced to the runtime's own chunked default, so the+ /// resolved number would be announced on stderr and then used by nothing.+ @Test(arguments: [+ (prefill: "on", auto: true, resolves: true),+ (prefill: "off", auto: true, resolves: false),+ (prefill: "on", auto: false, resolves: false),+ (prefill: "off", auto: false, resolves: false),+ ])+ func autoResolvesOnlyWhenChunkedPrefillWillRun(+ testCase: (prefill: String, auto: Bool, resolves: Bool)+ ) throws {+ let arguments = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi",+ "--prefill", testCase.prefill,+ "--prefill-chunk-tokens", testCase.auto ? "auto" : "64",+ ])+ #expect(arguments.prefillChunkTokensAuto == testCase.auto)+ #expect(arguments.resolvesPrefillChunkAuto == testCase.resolves)+ }++ /// A repeated `--prefill-chunk-tokens` is last-one-wins in both orderings.+ /// Without the clear on the integer branch, `auto` survives a later+ /// explicit size and the run resolves its own size over the one asked for.+ @Test func lastPrefillChunkTokensFlagWinsInBothOrderings() throws {+ let explicitLast = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi",+ "--prefill-chunk-tokens", "auto",+ "--prefill-chunk-tokens", "64",+ ])+ #expect(explicitLast.prefillChunkTokens == 64)+ #expect(explicitLast.prefillChunkTokensAuto == false)+ #expect(explicitLast.resolvesPrefillChunkAuto == false)++ let autoLast = try Args.parse([+ "--model", "m.gturbo", "--prompt", "hi",+ "--prefill-chunk-tokens", "64",+ "--prefill-chunk-tokens", "auto",+ ])+ #expect(autoLast.prefillChunkTokensAuto)+ #expect(autoLast.resolvesPrefillChunkAuto)+ }+@Test func generationOptionsParseAndStopsRepeat() throws {let arguments = try Args.parse(["--model", "m.gturbo", "--prompt", "hi",diff --git a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swiftindex b3205e56..1321703f 100644--- a/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift+++ b/Tests/TurboFieldfare/Core/Runtime/Prefill/PrefillChunkScratchTests.swift@@ -111,6 +111,20 @@ import Metal#expect(scratch.routeWeights.storageMode == MTLStorageMode.shared)}+ /// The server help, `docs/RUNTIME_CONTROLS.md`, and `docs/OPENAI_SERVER.md`+ /// quote these two sizes, rounded, as the cost of `--prefill-chunk-tokens+ /// auto` against the default. A layout change that moves them has to move+ /// the prose too; the earlier prose was computed by hand and was off.+ @Test func documentedScratchSizesMatchTheLayout() {+ let at128 = PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 128)+ let at256 = PrefillChunkScratchLayout(config: .gemma4_26B_A4B, chunkTokens: 256)+ let perToken = at256.totalPersistentBytes - at128.totalPersistentBytes+ #expect(at128.totalPersistentBytes == 16_390_528)+ #expect(at256.totalPersistentBytes == 32_452_992)+ #expect(perToken == 128 * 125_488)+ #expect(at128.totalPersistentBytes - 128 * 125_488 == 328_064)+ }+@Test func multimodalBlockScratchStaysInsideBoundedBudget() {let tokens = VisionConfig().maximumPooledTokenslet layout = PrefillChunkScratchLayout(diff --git a/Tests/TurboFieldfareServer/HTTPServerTests.swift b/Tests/TurboFieldfareServer/HTTPServerTests.swiftindex 08f6d761..a06a12c5 100644--- a/Tests/TurboFieldfareServer/HTTPServerTests.swift+++ b/Tests/TurboFieldfareServer/HTTPServerTests.swift@@ -897,6 +897,108 @@ struct HTTPServerTests {try await server.shutdown()}+ @Test func unknownFieldReturns400WithTheFieldName() async throws {+ // Pre-fix this returned 200: the decoder dropped `max_token` and the+ // request generated with the server's default maximum, so the caller+ // never learned the option had not applied.+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"hi"}],+ "max_token":4}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ let text = String(decoding: data, as: UTF8.self)+ #expect((response as? HTTPURLResponse)?.statusCode == 400)+ #expect(text.contains(#""code":"unknown_parameter""#))+ #expect(text.contains("max_token"))+ #expect(!text.contains("malformed JSON request"))++ try await server.shutdown()+ }++ @Test func unknownFieldOnAStreamingRequestFailsBeforeSSEStarts() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"hi"}],+ "max_token":4,"stream":true}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ let http = response as? HTTPURLResponse+ #expect(http?.statusCode == 400)+ // An SSE body cannot carry a status, so the refusal has to land before+ // the event stream opens.+ #expect(http?.value(forHTTPHeaderField: "content-type") == "application/json")+ #expect(String(decoding: data, as: UTF8.self)+ .contains(#""code":"unknown_parameter""#))++ try await server.shutdown()+ }++ @Test func responseFormatJSONObjectReturns400() async throws {+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"emit json"}],+ "response_format":{"type":"json_object"}}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ let text = String(decoding: data, as: UTF8.self)+ #expect((response as? HTTPURLResponse)?.statusCode == 400)+ #expect(text.contains(#""code":"unsupported_value""#))+ #expect(text.contains(#""param":"response_format""#))++ try await server.shutdown()+ }++ @Test func wrongTypedDeclaredValueStillReadsAsInvalidJSON() async throws {+ // A declared key carrying the wrong type is not an unknown field, and+ // keeps the invalid_json class the unknown-key path must not swallow.+ let server = TurboFieldfareHTTPServer(+ modelID: "test-model",+ queueLimit: 1,+ backend: ScriptedServerBackend())+ let channel = try await server.start(port: 0)+ let port = try #require(channel.localAddress?.port)+ var request = URLRequest(+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions")!)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "content-type")+ request.httpBody = Data(#"""+ {"model":"test-model","messages":[{"role":"user","content":"hi"}],+ "temperature":"not-a-number"}+ """#.utf8)+ let (data, response) = try await URLSession.shared.data(for: request)+ #expect((response as? HTTPURLResponse)?.statusCode == 400)+ #expect(String(decoding: data, as: UTF8.self).contains(#""code":"invalid_json""#))++ try await server.shutdown()+ }}private enum RawSocketError: Error {diff --git a/Tests/TurboFieldfareServer/OpenAIRequestDecodingTests.swift b/Tests/TurboFieldfareServer/OpenAIRequestDecodingTests.swiftnew file mode 100644index 00000000..1d8cd106--- /dev/null+++ b/Tests/TurboFieldfareServer/OpenAIRequestDecodingTests.swift@@ -0,0 +1,188 @@+import Foundation+import Testing+@testable import TurboFieldfare+@testable import TurboFieldfareServerCore++@Suite("OpenAI request decoding")+struct OpenAIRequestDecodingTests {+ private typealias Rejection = (message: String, param: String?, code: String)++ private func decode(_ body: String) throws -> OpenAIChatRequest {+ try JSONDecoder().decode(OpenAIChatRequest.self, from: Data(body.utf8))+ }++ private func request(_ fields: String) -> String {+ """+ {"model":"m","messages":[{"role":"user","content":"x"}],\(fields)}+ """+ }++ private func decodeRejection(_ body: String) -> Rejection? {+ do {+ _ = try decode(body)+ Issue.record("request decoded instead of failing")+ return nil+ } catch ServerRequestError.invalid(let message, let param, let code) {+ return (message, param, code)+ } catch {+ Issue.record("decoding threw \(error) rather than a ServerRequestError")+ return nil+ }+ }++ private func validationRejection(_ body: String) -> Rejection? {+ do {+ _ = try OpenAIRequestValidator.validate(try decode(body), modelID: "m")+ Issue.record("request validated instead of failing")+ return nil+ } catch ServerRequestError.invalid(let message, let param, let code) {+ return (message, param, code)+ } catch {+ Issue.record("validation threw \(error) rather than a ServerRequestError")+ return nil+ }+ }++ // A `response_format` that is not an object used to fail the typed decode,+ // so the caller was answered "malformed JSON request" instead of being told+ // which field the server could not read.+ @Test(arguments: [#""json_object""#, "[]", "7", "true"])+ func nonObjectResponseFormatNamesTheFieldInsteadOfReadingAsMalformedJSON(+ _ value: String+ ) throws {+ let refusal = try #require(+ validationRejection(request(#""response_format":\#(value)"#)))+ #expect(refusal.message.contains("must be an object"))+ #expect(refusal.param == "response_format")+ #expect(refusal.code == "invalid_value")+ }++ @Test(arguments: ["7", "[]", #"{"name":"s"}"#])+ func responseFormatTypeThatIsNotAStringIsInvalid(_ value: String) throws {+ let refusal = try #require(+ validationRejection(request(#""response_format":{"type":\#(value)}"#)))+ #expect(refusal.message.contains("response_format.type must be a string"))+ #expect(refusal.param == "response_format")+ #expect(refusal.code == "invalid_value")+ }++ @Test(arguments: ["{}", #"{"type":null}"#])+ func responseFormatWithoutATypeStillReportsItAsRequired(_ value: String) throws {+ let refusal = try #require(+ validationRejection(request(#""response_format":\#(value)"#)))+ #expect(refusal.message.contains("response_format.type is required"))+ #expect(refusal.param == "response_format")+ #expect(refusal.code == "invalid_value")+ }++ @Test func responseFormatTextStillValidatesAfterTheShapeChange() throws {+ let validated = try OpenAIRequestValidator.validate(+ try decode(request(#""response_format":{"type":"text"}"#)), modelID: "m")+ #expect(validated.messages.count == 1)+ }++ @Test func responseFormatJSONObjectIsStillUnsupportedAfterTheShapeChange() throws {+ let refusal = try #require(+ validationRejection(request(#""response_format":{"type":"json_object"}"#)))+ #expect(refusal.message.contains("structured output"))+ #expect(refusal.param == "response_format")+ #expect(refusal.code == "unsupported_value")+ }++ // The key sweep runs before the typed decode, so the answer names the key+ // the caller misspelled rather than whatever DecodingError another field+ // raises first.+ @Test func unknownKeyIsNamedEvenBesideAMistypedDeclaredField() throws {+ let refusal = try #require(+ decodeRejection(request(#""max_token":4,"temperature":"hot""#)))+ #expect(refusal.message.contains("max_token"))+ #expect(refusal.param == "max_token")+ #expect(refusal.code == "unknown_parameter")+ }++ @Test func unsupportedKeyIsNamedEvenBesideAMistypedDeclaredField() throws {+ let refusal = try #require(+ decodeRejection(request(#""logit_bias":{"1":2},"temperature":"hot""#)))+ #expect(refusal.message == "logit_bias is not supported")+ #expect(refusal.param == "logit_bias")+ #expect(refusal.code == "unsupported_value")+ }++ // openai-python serializes an option the caller never set as an explicit+ // `null`, which asks for nothing and must not be refused on presence.+ @Test(arguments: [+ #""logit_bias":null"#,+ #""web_search_options":null"#,+ #""foo":null"#,+ #""n":null"#,+ #""response_format":null"#,+ ])+ func aKeySetToNullIsTreatedAsAbsent(_ field: String) throws {+ let validated = try OpenAIRequestValidator.validate(+ try decode(request(field)), modelID: "m")+ #expect(validated.messages.count == 1)+ }++ @Test func anUnsupportedKeyCarryingAValueIsStillRefused() throws {+ let refusal = try #require(decodeRejection(request(#""logit_bias":{}"#)))+ #expect(refusal.param == "logit_bias")+ #expect(refusal.code == "unsupported_value")+ }++ // A Character-counted bound is no bound: one base scalar plus combining+ // marks is a single Character however many bytes it carries, so the whole+ // key came back in `param` and, quoted, in `message`. Bounded in bytes,+ // the echo stays within the 64-byte limit plus the ellipsis.+ @Test func aKeyMadeOfCombiningMarksIsBoundedInBytes() throws {+ let key = "a" + String(repeating: "\u{0301}", count: 100_000)+ let refusal = try #require(decodeRejection(request(#""\#(key)":1"#)))+ #expect(refusal.code == "unknown_parameter")+ let param = try #require(refusal.param)+ #expect(param.hasSuffix("..."))+ #expect(param.utf8.count <= 64 + 3, "param is \(param.utf8.count) bytes")+ #expect(refusal.message.utf8.count < 1_024,+ "message is \(refusal.message.utf8.count) bytes")+ }++ @Test func legacyFunctionsAreNamedEvenBesideAMistypedDeclaredField() throws {+ let refusal = try #require(+ decodeRejection(request(#""functions":[{"name":"f"}],"temperature":"hot""#)))+ #expect(refusal.message == "legacy functions are not supported; use tools")+ #expect(refusal.param == "functions")+ #expect(refusal.code == "unsupported_value")+ }++ // The body cap is 5 MiB, so no rejection may echo an arbitrary slice of it.+ @Test func responseFormatTypeIsBoundedInTheRejection() throws {+ let long = String(repeating: "t", count: 200)+ let refusal = try #require(+ validationRejection(request(#""response_format":{"type":"\#(long)"}"#)))+ #expect(refusal.message.contains(String(repeating: "t", count: 64) + "..."))+ #expect(!refusal.message.contains(String(repeating: "t", count: 65)))+ #expect(refusal.code == "invalid_value")+ }++ @Test func toolNameIsBoundedInTheRejection() throws {+ let long = String(repeating: "z", count: 200)+ let refusal = try #require(validationRejection(request(#"""+ "tools":[{"type":"function",+ "function":{"name":"\#(long)","parameters":{"type":"object"}}}]+ """#)))+ #expect(refusal.message.contains(String(repeating: "z", count: 64) + "..."))+ #expect(!refusal.message.contains(String(repeating: "z", count: 65)))+ #expect(refusal.code == "invalid_tool_name")+ }++ // The key sweep must not swallow the wrong-typed-value class: HTTPServer+ // answers a DecodingError with `invalid_json`, and a declared key carrying+ // the wrong type is not an unknown field.+ @Test func aWrongTypedDeclaredValueAloneStillThrowsADecodingError() {+ do {+ _ = try decode(request(#""temperature":"not-a-number""#))+ Issue.record("a wrong-typed temperature decoded")+ } catch is DecodingError {+ } catch {+ Issue.record("decoding threw \(error) rather than a DecodingError")+ }+ }+}diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swiftindex 2b107517..aedfe67f 100644--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift@@ -529,6 +529,243 @@ struct OpenAIValidationTests {}}+ @Test func unknownTopLevelFieldIsAServerRequestErrorNotMalformedJSON() {+ // Regression for issue 168: the synthesized decoder discarded+ // `max_token`, so this body decoded cleanly and the request generated+ // with the default 4096-token maximum under a 200. The error class is+ // half the fix — a plain decoding failure reaches the HTTP layer as+ // "malformed JSON request", which still hides the typo.+ let data = Data(#"""+ {"model":"m","messages":[{"role":"user","content":"x"}],"max_token":4}+ """#.utf8)+ do {+ _ = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ Issue.record("unknown top-level field decoded instead of failing")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ #expect(message.contains("max_token"))+ #expect(param == "max_token")+ #expect(code == "unknown_parameter")+ } catch {+ Issue.record("decoding threw \(error) rather than a ServerRequestError")+ }+ }++ @Test func unknownFieldsAreNamedSortedAndTheFirstIsTheParam() {+ let data = Data(#"""+ {"model":"m","messages":[{"role":"user","content":"x"}],"zeta":1,"alpha":2}+ """#.utf8)+ do {+ _ = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ Issue.record("unknown top-level fields decoded instead of failing")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ // Sorted rather than in body order, so two callers sending the same+ // typos in different orders get the same answer.+ #expect(message.contains(#""alpha", "zeta""#))+ #expect(param == "alpha")+ #expect(code == "unknown_parameter")+ } catch {+ Issue.record("decoding threw \(error) rather than a ServerRequestError")+ }+ }++ @Test(arguments: [+ ("user", #""user":"caller-1""#),+ ("store", #""store":false"#),+ ("metadata", #""metadata":{"run":"7"}"#),+ ("service_tier", #""service_tier":"auto""#),+ ("prompt_cache_key", #""prompt_cache_key":"cache-1""#),+ ("safety_identifier", #""safety_identifier":"user-hash""#),+ ])+ func toleratedBookkeepingFieldsDecode(_ key: String, _ field: String) throws {+ let data = Data("""+ {"model":"m","messages":[{"role":"user","content":"x"}],\(field)}+ """.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")+ #expect(validated.messages.count == 1)+ // Tolerated means ignored: the decoded request keeps no representation+ // of the key, so nothing downstream can act on it.+ let encoded = String(decoding: try JSONEncoder().encode(request), as: UTF8.self)+ #expect(!encoded.contains("\"\(key)\":"))+ }++ @Test func responseFormatTextValidates() throws {+ let data = Data(#"""+ {"model":"m","messages":[{"role":"user","content":"x"}],+ "response_format":{"type":"text"}}+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")+ #expect(validated.messages.count == 1)+ }++ @Test(arguments: ["json_object", "json_schema"])+ func responseFormatStructuredIsUnsupported(_ type: String) throws {+ // Pre-fix this decoded and generated free text while the caller+ // believed JSON was enforced; that silence is what issue 168 reports.+ let data = Data("""+ {"model":"m","messages":[{"role":"user","content":"x"}],+ "response_format":{"type":"\(type)",+ "json_schema":{"name":"s","schema":{"type":"object"}}}}+ """.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ do {+ _ = try OpenAIRequestValidator.validate(request, modelID: "m")+ Issue.record("response_format \(type) validated")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ #expect(message.contains("structured output"))+ #expect(param == "response_format")+ #expect(code == "unsupported_value")+ }+ }++ @Test func responseFormatUnknownTypeIsInvalid() throws {+ let data = Data(#"""+ {"model":"m","messages":[{"role":"user","content":"x"}],+ "response_format":{"type":"yaml"}}+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ do {+ _ = try OpenAIRequestValidator.validate(request, modelID: "m")+ Issue.record("unknown response_format type validated")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ #expect(message.contains("yaml"))+ #expect(param == "response_format")+ #expect(code == "invalid_value")+ }+ }++ @Test func responseFormatWithoutTypeIsInvalid() throws {+ // An object of the right shape missing its one required value is a+ // request error, not malformed JSON.+ let data = Data(#"""+ {"model":"m","messages":[{"role":"user","content":"x"}],+ "response_format":{}}+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ do {+ _ = try OpenAIRequestValidator.validate(request, modelID: "m")+ Issue.record("response_format without a type validated")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ #expect(message.contains("response_format.type is required"))+ #expect(param == "response_format")+ #expect(code == "invalid_value")+ }+ }++ @Test(arguments: [+ "logit_bias", "top_logprobs", "reasoning_effort", "verbosity", "modalities",+ "audio", "prediction", "web_search_options",+ ])+ func knownUnsupportedFieldsAreRefusedAsUnsupportedNotUnknown(_ key: String) {+ // These are real OpenAI parameters the server cannot honour. Answering+ // "unrecognized" would send the caller hunting for a typo that is not+ // there.+ let data = Data("""+ {"model":"m","messages":[{"role":"user","content":"x"}],"\(key)":{}}+ """.utf8)+ do {+ _ = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ Issue.record("\(key) decoded instead of failing")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ #expect(message == "\(key) is not supported")+ #expect(param == key)+ #expect(code == "unsupported_value")+ } catch {+ Issue.record("decoding threw \(error) rather than a ServerRequestError")+ }+ }++ @Test func unknownKeyNamesAreBoundedAndQuoted() {+ // The body cap is 5 MiB, so a caller must not be able to have an+ // arbitrary slice of its own keys quoted back, and a key carrying a+ // quote must not be able to render as two keys.+ func rejection(_ extraKeys: String) -> (message: String, param: String?)? {+ let data = Data("""+ {"model":"m","messages":[{"role":"user","content":"x"}],\(extraKeys)}+ """.utf8)+ do {+ _ = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ Issue.record("unknown fields decoded instead of failing")+ return nil+ } catch ServerRequestError.invalid(let message, let param, _) {+ return (message, param)+ } catch {+ Issue.record("decoding threw \(error) rather than a ServerRequestError")+ return nil+ }+ }++ let long = String(repeating: "k", count: 200)+ if let cut = rejection("\"\(long)\":1") {+ #expect(cut.message.contains(String(repeating: "k", count: 64) + "..."))+ #expect(!cut.message.contains(String(repeating: "k", count: 65)))+ // The param is echoed straight out of the body, so it is bounded+ // the same way the message is, unquoted because it names a field.+ #expect(cut.param == String(repeating: "k", count: 64) + "...")+ #expect(cut.param?.contains(String(repeating: "k", count: 65)) == false)+ }++ // Sorted lexicographically, so the first eight are 1, 10, 11, 12, 2-5.+ let twelve = (1...12).map { "\"unknown\($0)\":1" }.joined(separator: ",")+ if let many = rejection(twelve) {+ #expect(many.message.contains(#""unknown1""#))+ #expect(many.message.contains(#""unknown12""#))+ #expect(!many.message.contains(#""unknown9""#))+ #expect(many.message.contains("and 4 more"))+ }++ if let quoted = rejection(#""ba\"d":1"#) {+ #expect(quoted.message.contains(#""ba\"d""#))+ #expect(quoted.param == #"ba"d"#)+ }+ }++ @Test(arguments: [+ ("functions", #""functions":[{"name":"f","parameters":{"type":"object"}}]"#),+ ("function_call", #""function_call":{"name":"f"}"#),+ ])+ func legacyFunctionsAreUnsupported(_ key: String, _ field: String) {+ // Refused at decode time like every other unsupported key, so the+ // answer names the legacy field even beside a mistyped declared one;+ // a validator-side refusal lost to that field's DecodingError.+ let data = Data("""+ {"model":"m","messages":[{"role":"user","content":"x"}],\(field),"temperature":"hot"}+ """.utf8)+ do {+ _ = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ Issue.record("legacy \(key) decoded instead of failing")+ } catch ServerRequestError.invalid(let message, let param, let code) {+ #expect(message.contains("use tools"))+ #expect(param == key)+ #expect(code == "unsupported_value")+ } catch {+ Issue.record("decoding threw \(error) rather than a ServerRequestError")+ }+ }++ @Test func nestedExtrasStayTolerated() throws {+ // Strictness is the top level only: clients routinely add keys inside+ // messages, tool definitions, and stream_options, and the nested+ // decoding here is deliberately structural.+ let data = Data(#"""+ {+ "model":"m",+ "messages":[{"role":"user","content":"x","annotations":[]}],+ "stream_options":{"include_usage":true,"continuous_usage_stats":true},+ "tools":[{"type":"function","function":{+ "name":"probe",+ "strict":true,+ "parameters":{"type":"object","properties":{}}+ }}]+ }+ """#.utf8)+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")+ #expect(validated.tools.count == 1)+ #expect(validated.includeUsage)+ }+private func fixture(_ name: String) throws -> OpenAIChatRequest {let url = try #require(Bundle.module.url(forResource: name, withExtension: nil, subdirectory: "Fixtures"))@@ -688,6 +925,65 @@ struct ServerArgumentTests {#expect(arguments.rdadvisePolicy == .off)}+ /// The server rejected `--prefill-chunk-tokens auto` while the CLI accepted+ /// it and `RUNTIME_CONTROLS.md` promised both took the same values, so this+ /// throws on the pre-fix parser. On the server the word is an alias for the+ /// cap and nothing past the parser can tell the two spellings apart: a+ /// per-request size is the smallest allowed size covering the span, so the+ /// cap prefills every prompt in those same spans, and the KV ring is sized+ /// from the cap either way. Only the prefill scratch is sized from the+ /// chunk, and sizing it per request means reallocating it whenever the+ /// chosen size moves.+ @Test func parsesAutoPrefillChunkTokens() throws {+ let arguments = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prefill-chunk-tokens", "auto",+ ])+ #expect(arguments.prefillChunkTokens == PrefillRuntimeConfig.maxChunkTokens)++ // Indistinguishable from the explicit cap, which is the whole claim:+ // the runtime identity is taken from the configuration, so a prefix+ // built under `auto` is reusable by a run started at 256.+ let explicitCap = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prefill-chunk-tokens", "256",+ ])+ #expect(try arguments.resolvedRuntimeConfiguration()+ == (try explicitCap.resolvedRuntimeConfiguration()))++ // Last flag wins in both directions, as in the CLI: a later integer is+ // a fixed size rather than an integer layered on a mode still on, and a+ // later `auto` replaces the integer rather than being ignored because+ // one was already set.+ let integerLast = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prefill-chunk-tokens", "auto",+ "--prefill-chunk-tokens", "64",+ ])+ #expect(integerLast.prefillChunkTokens == 64)++ let autoLast = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prefill-chunk-tokens", "64",+ "--prefill-chunk-tokens", "auto",+ ])+ #expect(autoLast.prefillChunkTokens == PrefillRuntimeConfig.maxChunkTokens)+ }++ /// `auto` reaches the resolve guard as the cap, so the guard that tests+ /// membership of `allowedPrefillChunkTokens` never sees the word and never+ /// has to learn it.+ @Test func autoSurvivesTheResolveGuard() throws {+ let arguments = try ServerArguments.parse([+ "--model", "model.gturbo",+ "--prefill-chunk-tokens", "auto",+ ])+ let configuration = try arguments.resolvedRuntimeConfiguration()+ #expect(configuration.prefillPolicy == .chunked)+ #expect(configuration.prefillConfig.chunkTokens+ == PrefillRuntimeConfig.maxChunkTokens)+ }+@Test func parsesSinglePrefixModeAndRejectsUnknownMode() throws {let arguments = try ServerArguments.parse(["--model", "model.gturbo",@@ -757,6 +1053,7 @@ struct ServerArgumentTests {["--expert-cache-policy", "mru"],["--prefill", "maybe"],["--prefill-chunk-tokens", "512"],+ ["--prefill-chunk-tokens", "automatic"],["--rdadvise", "eager"],])func rejectsUnsupportedRuntimeValues(flag: [String]) throws {@@ -774,10 +1071,11 @@ struct ServerArgumentTests {}@Test func allowedValueListRendersChoices() {- #expect(ServerArguments.allowedValueList([8]) == "8")- #expect(ServerArguments.allowedValueList([8, 16]) == "8 or 16")- #expect(ServerArguments.allowedValueList([8, 16, 24, 32]) == "8, 16, 24, or 32")- #expect(ServerArguments.allowedValueList([]) == "")+ #expect(RuntimeConfiguration.allowedValueList([8]) == "8")+ #expect(RuntimeConfiguration.allowedValueList([8, 16]) == "8 or 16")+ #expect(RuntimeConfiguration.allowedValueList([8, 16, 24, 32])+ == "8, 16, 24, or 32")+ #expect(RuntimeConfiguration.allowedValueList([]) == "")}/// Public 0.5.0 through 0.7.1 printed "--prefill-chunk-tokens must be 32,@@ -788,19 +1086,23 @@ struct ServerArgumentTests {@Test(arguments: [(flag: "--expert-cache-slots",allowed: RuntimeConfiguration.allowedExpertCacheSlots,- badValue: "12"),+ badValue: "12",+ namesAuto: false),(flag: "--expert-cache-slots",allowed: RuntimeConfiguration.allowedExpertCacheSlots,- badValue: "many"),+ badValue: "many",+ namesAuto: false),(flag: "--prefill-chunk-tokens",allowed: RuntimeConfiguration.allowedPrefillChunkTokens,- badValue: "512"),+ badValue: "512",+ namesAuto: true),(flag: "--prefill-chunk-tokens",allowed: RuntimeConfiguration.allowedPrefillChunkTokens,- badValue: "many"),+ badValue: "many",+ namesAuto: true),])func parseRejectionNamesExactlyTheAllowedValues(- testCase: (flag: String, allowed: [Int], badValue: String)+ testCase: (flag: String, allowed: [Int], badValue: String, namesAuto: Bool)) {do {_ = try ServerArguments.parse([@@ -813,13 +1115,21 @@ struct ServerArgumentTests {"the rejection does not lead with \(testCase.flag): \(error)")#expect(named == testCase.allowed,"\(testCase.flag) rejection names \(named), guard accepts \(testCase.allowed)")+ // The word is not in the integer array, so nothing above would+ // notice a rejection that kept calling `auto` illegal - which is+ // exactly what the pre-fix parser printed.+ #expect(error.description.contains("auto") == testCase.namesAuto,+ "\(testCase.flag) rejection: \(error)")} catch {Issue.record("unexpected error for \(testCase.flag): \(error)")}}@Test func resolveRejectionNamesExactlyTheAllowedValues() {- let cases: [(flag: String, arguments: ServerArguments, allowed: [Int])] = [+ let cases: [(flag: String,+ arguments: ServerArguments,+ allowed: [Int],+ namesAuto: Bool)] = [(flag: "--expert-cache-slots",arguments: ServerArguments(model: "model.gturbo",port: 8080,@@ -834,7 +1144,8 @@ struct ServerArgumentTests {rdadvisePolicy: .off,visionPack: nil,visionResidency: .onDemand),- allowed: RuntimeConfiguration.allowedExpertCacheSlots),+ allowed: RuntimeConfiguration.allowedExpertCacheSlots,+ namesAuto: false),(flag: "--prefill-chunk-tokens",arguments: ServerArguments(model: "model.gturbo",port: 8080,@@ -849,7 +1160,8 @@ struct ServerArgumentTests {rdadvisePolicy: .off,visionPack: nil,visionResidency: .onDemand),- allowed: RuntimeConfiguration.allowedPrefillChunkTokens),+ allowed: RuntimeConfiguration.allowedPrefillChunkTokens,+ namesAuto: true),]for testCase in cases {do {@@ -861,6 +1173,10 @@ struct ServerArgumentTests {"the rejection does not lead with \(testCase.flag): \(error)")#expect(named == testCase.allowed,"\(testCase.flag) rejection names \(named), guard accepts \(testCase.allowed)")+ // One sentence for both doors: a flag rejected here must offer+ // the same values it offers when `parse` rejects it.+ #expect(error.description.contains("auto") == testCase.namesAuto,+ "\(testCase.flag) rejection: \(error)")} catch {Issue.record("unexpected error for \(testCase.flag): \(error)")}@@ -874,10 +1190,17 @@ struct ServerArgumentTests {let defaultSlots = try ServerArguments.parse(["--model", "model.gturbo"]).expertCacheSlots#expect(namedSlots == RuntimeConfiguration.allowedExpertCacheSlots + [defaultSlots],"the --expert-cache-slots help line names \(namedSlots)")- let chunkLine = try #require(lines.first { $0.contains("--prefill-chunk-tokens") })+ #expect(!slotsLine.contains("auto"),+ "the --expert-cache-slots help line offers auto: \(slotsLine)")+ let flagLine = try #require(lines.first { $0.contains("--prefill-chunk-tokens") })+ #expect(flagLine.contains("<n|auto>"),+ "the --prefill-chunk-tokens placeholder does not admit auto: \(flagLine)")+ let chunkLine = try #require(lines.first { $0.contains("Prefill chunk size:") })let namedChunks = integers(in: String(chunkLine))#expect(namedChunks == RuntimeConfiguration.allowedPrefillChunkTokens,"the --prefill-chunk-tokens help line names \(namedChunks)")+ #expect(chunkLine.contains("auto"),+ "the --prefill-chunk-tokens help line omits auto: \(chunkLine)")}@Test func imageDataURLPreservesOrderedMultimodalParts() throws {diff --git a/docs/COMMUNITY_BENCHMARKS.md b/docs/COMMUNITY_BENCHMARKS.mdindex 7d7a5b69..323dd5db 100644--- a/docs/COMMUNITY_BENCHMARKS.md+++ b/docs/COMMUNITY_BENCHMARKS.md@@ -189,6 +189,15 @@ all affect decode speed.| [nxexcelsior](https://github.com/nxexcelsior) · [issue #111](https://github.com/drumih/turbo-fieldfare/issues/111) | M5 MacBook Air | 24 GB | Internal SSD | 61 / 497 | 11.982 tok/s | One submitted run || [nxexcelsior](https://github.com/nxexcelsior) · [issue #111](https://github.com/drumih/turbo-fieldfare/issues/111) | M5 MacBook Air | 24 GB | Internal SSD | 430 / 721 | 12.429 tok/s | One submitted run || [nxexcelsior](https://github.com/nxexcelsior) · [issue #111](https://github.com/drumih/turbo-fieldfare/issues/111) | M5 MacBook Air | 24 GB | Internal SSD | 3,015 / 610 | 9.783 tok/s | One submitted run |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 61 / 497 | 36.2 tok/s | Median of 3 runs, default 16 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 430 / 721 | 34.0 tok/s | Median of 3 runs, default 16 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 3,015 / 610 | 29.5 tok/s | Median of 3 runs, default 16 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 61 / 497 | 38.9 tok/s | Median of 3 runs, 24 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 430 / 721 | 36.5 tok/s | Median of 3 runs, 24 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 3,015 / 610 | 31.5 tok/s | Median of 3 runs, 24 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 61 / 497 | 40.8 tok/s | Median of 3 runs, 32 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 430 / 721 | 38.5 tok/s | Median of 3 runs, 32 expert-cache slots |+| [chongdlh-pixel](https://github.com/chongdlh-pixel) · [issue #170](https://github.com/drumih/turbo-fieldfare/issues/170) | M5 Pro MacBook Pro | 24 GB | Not reported | 3,015 / 610 | 33.3 tok/s | Median of 3 runs, 32 expert-cache slots || [Matt Skipton](https://github.com/mattskipton) · [issue #97](https://github.com/drumih/turbo-fieldfare/issues/97) | M5 Pro MacBook Pro | 64 GB | Not reported | 61 / 497 | 37.426 tok/s | One submitted run || [Matt Skipton](https://github.com/mattskipton) · [issue #97](https://github.com/drumih/turbo-fieldfare/issues/97) | M5 Pro MacBook Pro | 64 GB | Not reported | 430 / 721 | 34.194 tok/s | One submitted run || [Matt Skipton](https://github.com/mattskipton) · [issue #97](https://github.com/drumih/turbo-fieldfare/issues/97) | M5 Pro MacBook Pro | 64 GB | Not reported | 3,015 / 610 | 31.485 tok/s | One submitted run |diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.mdindex 8728460a..6b95df30 100644--- a/docs/OPENAI_SERVER.md+++ b/docs/OPENAI_SERVER.md@@ -64,8 +64,12 @@ defaults. See [Runtime controls](RUNTIME_CONTROLS.md) for what each one does.Without these flags the server runs the production defaults: 16 expert-cacheslots, LFU eviction, chunked prefill on with 128-token chunks, and read advice-off. Values are validated before the model loads, so an unsupported one exits-with the usage text rather than failing partway through startup. Chunked+off. `--prefill-chunk-tokens auto` runs at the cap,+256, on the server: a per-request size is the smallest allowed size covering the+span being prefilled, so the cap prefills every prompt in exactly those spans,+and it costs about 32.5 MB of prefill scratch against about 16.4 MB at the 128+default. Values are validated before the model loads, so an unsupported one+exits with the usage text rather than failing partway through startup. Chunkedprefill needs at least 16 expert-cache slots, so `--expert-cache-slots 8`requires `--prefill off`.@@ -222,6 +226,20 @@ Supported options include `temperature`, `top_p`, `top_k`,`repetition_penalty`, `seed`, `stop`, `max_tokens`,`max_completion_tokens`, and function-tool fields.+Unknown top-level request fields return HTTP 400 with `code`+`unknown_parameter` and the field name in `param`, so a misspelled option is+refused rather than silently ignored. `response_format` is accepted only as+`{"type": "text"}`; `json_object` and `json_schema` return+`unsupported_value`, as do `logit_bias`, `top_logprobs`, `reasoning_effort`,+`verbosity`, `modalities`, `audio`, `prediction`, `web_search_options`, and+the legacy `functions` and `function_call`. `response_format` must be an object; any+other JSON value returns `invalid_value`. `user`, `store`, `metadata`,+`service_tier`, `prompt_cache_key`, and `safety_identifier` are accepted and+ignored. A top-level field set to `null` is treated as absent. Fields inside+`messages`, `tools`, and `stream_options` are not checked for extras. Inside+`stream_options` only `include_usage` is read, so a misspelled key there is+ignored rather than refused.+The server supports one model and one choice. It does not support the ResponsesAPI, legacy Completions, embeddings, structured output,batching, log probabilities, or remote model switching.diff --git a/docs/RUNTIME_CONTROLS.md b/docs/RUNTIME_CONTROLS.mdindex 0f910e12..ee8de4a8 100644--- a/docs/RUNTIME_CONTROLS.md+++ b/docs/RUNTIME_CONTROLS.md@@ -35,7 +35,7 @@ model, so an unsupported combination fails immediately with the usage text.| Expert-cache slots | 8, 16, 24, 32 | `--expert-cache-slots` | 16 | More slots can retain more routed experts and reduce later reads, but values above 16 use more RAM. Chunked prefill requires at least 16 slots. || Expert-cache policy | LFU | `--expert-cache-policy lfu\|lru` | LFU | Chooses which expert is evicted when the cache is full. || Prompt prefill | On, off | `--prefill on\|off` | On | On processes known prompt tokens through the chunked prefill path. Off disables that path. |-| Prefill chunk size | 128 | `--prefill-chunk-tokens 32\|64\|128\|256\|auto` | 128 | Sets the number of prompt tokens processed by each chunked-prefill step, and has no effect while prefill is off. Chunks loop outside layers, so each one re-reads that layer's routed experts: fewer, larger chunks read less. `auto` picks the smallest size that covers the prompt. On a 7,019-token prompt, 256 measured 16% faster than 128 with byte-identical output. |+| Prefill chunk size | 128 | `--prefill-chunk-tokens 32\|64\|128\|256\|auto` | 128 | Sets the number of prompt tokens processed by each chunked-prefill step, and has no effect while prefill is off. Chunks loop outside layers, so each one re-reads that layer's routed experts: fewer, larger chunks read less. `auto` picks the smallest size that covers the prompt. On the server `auto` is the cap, 256: a per-request size is the smallest allowed size covering the span, so the cap prefills every prompt in exactly those spans, and the KV ring is sized from the cap either way. Only the prefill scratch is sized from the chunk, at about 125.5 KB per token over a fixed 328 KB, so the cap holds about 32.5 MB of it against 16.4 MB at 128, and a per-request size would reallocate it whenever the chosen size moved. On a 7,019-token prompt, 256 measured 16% faster than 128 with byte-identical output. || RDADVISE | Off, Default, Bounded, Adaptive | `--rdadvise off\|default\|bounded\|adaptive` | Off | Applies experimental read advice. Its effect depends on the workload; it may help a short decode and slow a long one. |In the app, changing context length, expert-cache slots, or RDADVISE requires a@@ -45,7 +45,9 @@ each turn and do not require a reload. A reload ends the retained KV lineage;the app preserves the visible transcript and marks where the model's newcontext begins. Each CLI invocation loads a new model process, so its selectedruntime settings apply immediately. The server fixes its runtime settings at-startup, so changing one means restarting the process.+startup, so changing one means restarting the process;+`--prefill-chunk-tokens auto` resolves to the cap, 256, there, which allocates+about 32.5 MB of prefill scratch against about 16.4 MB at the 128 default.### macOS interactivity mitigation