Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Harden OpenAI client recovery and Unicode streaming (#43)

Andrey Mikhaylovb230bfa7362c
diff --git a/Sources/TurboFieldfare/Tokenization/Detokenizer.swift b/Sources/TurboFieldfare/Tokenization/Detokenizer.swift
index dac93db8..6d967dd7 100644
--- a/Sources/TurboFieldfare/Tokenization/Detokenizer.swift
+++ b/Sources/TurboFieldfare/Tokenization/Detokenizer.swift
@@ -59,14 +59,22 @@ struct GFDetokenizer {
@usableFromInline
mutating func commitDelta(_ current: String) -> String {
- guard current.hasPrefix(emitted) else {
- // Decoder altered the prefix — extremely rare in append-only streams.
- // Resync rather than emit garbage; the user-visible loss is bounded
- // to whatever was retokenized.
- emitted = current
- return ""
+ // A combining mark can extend the last emitted grapheme, so compare the
+ // append-only prefix without using Character boundaries.
+ let currentUTF8 = current.utf8
+ var boundary = currentUTF8.startIndex
+ for byte in emitted.utf8 {
+ guard boundary != currentUTF8.endIndex,
+ currentUTF8[boundary] == byte else {
+ // Decoder altered the prefix — extremely rare in append-only streams.
+ // Resync rather than emit garbage; the user-visible loss is bounded
+ // to whatever was retokenized.
+ emitted = current
+ return ""
+ }
+ currentUTF8.formIndex(after: &boundary)
}
- let delta = String(current.dropFirst(emitted.count))
+ let delta = String(current[boundary...])
emitted = current
return delta
}
diff --git a/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift b/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift
new file mode 100644
index 00000000..590f04dd
--- /dev/null
+++ b/Sources/TurboFieldfareServer/Core/GemmaToolSchema.swift
@@ -0,0 +1,216 @@
+import TurboFieldfare
+
+enum GemmaToolSchema {
+ private static let types: Set<String> = [
+ "array", "boolean", "integer", "null", "number", "object", "string",
+ ]
+ private static let annotations: Set<String> = [
+ "$comment", "default", "deprecated", "description", "examples", "readOnly",
+ "title", "writeOnly",
+ ]
+
+ static func adapted(_ schema: JSONValue, toolName: String) throws -> JSONValue {
+ let value = try adapt(schema, toolName: toolName, path: "parameters")
+ guard value.objectValue?["type"] == .string("object"),
+ value.objectValue?["nullable"] != .bool(true) else {
+ throw invalid(toolName, "parameters", "top-level type must be a non-null object")
+ }
+ return value
+ }
+
+ private static func adapt(_ schema: JSONValue,
+ toolName: String,
+ path: String) throws -> JSONValue {
+ guard case .object(var object) = schema else {
+ throw invalid(toolName, path, "schema must be an object")
+ }
+ if object["allOf"] != nil {
+ throw invalid(toolName, path, "allOf is not representable by the Gemma template")
+ }
+ if object["anyOf"] != nil || object["oneOf"] != nil {
+ object = try adaptUnion(object, toolName: toolName, path: path)
+ }
+
+ let type: String
+ switch object["type"] {
+ case .string(let name):
+ type = try validatedType(name, toolName: toolName, path: path)
+ case .array(let values):
+ type = try adaptNullableTypeArray(
+ values, object: &object, toolName: toolName, path: path)
+ case nil:
+ throw invalid(toolName, path, "type is required")
+ default:
+ throw invalid(toolName, path, "type must be a string or a nullable type array")
+ }
+
+ if let properties = object["properties"] {
+ guard type == "object", case .object(let definitions) = properties else {
+ throw invalid(toolName, path, "properties requires an object type and object value")
+ }
+ var adapted: [String: JSONValue] = [:]
+ adapted.reserveCapacity(definitions.count)
+ for key in definitions.keys.sorted() {
+ adapted[key] = try adapt(
+ definitions[key]!,
+ toolName: toolName,
+ path: "\(path).properties.\(key)")
+ }
+ object["properties"] = .object(adapted)
+ }
+
+ if let items = object["items"] {
+ guard type == "array" else {
+ throw invalid(toolName, path, "items requires an array type")
+ }
+ guard case .object = items else {
+ throw invalid(toolName, "\(path).items", "tuple and boolean item schemas are unsupported")
+ }
+ object["items"] = try adapt(
+ items, toolName: toolName, path: "\(path).items")
+ }
+ return .object(object)
+ }
+
+ private static func adaptNullableTypeArray(
+ _ values: [JSONValue],
+ object: inout [String: JSONValue],
+ toolName: String,
+ path: String
+ ) throws -> String {
+ let names = try values.map { value -> String in
+ guard case .string(let name) = value else {
+ throw invalid(toolName, path, "type array must contain only strings")
+ }
+ return try validatedType(name, toolName: toolName, path: path)
+ }
+ let unique = Set(names)
+ let concrete = unique.subtracting(["null"])
+ guard unique.count == 2, unique.contains("null"), concrete.count == 1,
+ let type = concrete.first else {
+ throw invalid(toolName, path, "only one concrete type plus null is representable")
+ }
+ if let nullable = object["nullable"], nullable != .bool(true) {
+ throw invalid(toolName, path, "nullable union conflicts with nullable keyword")
+ }
+ object["type"] = .string(type)
+ object["nullable"] = .bool(true)
+ return type
+ }
+
+ private static func adaptUnion(
+ _ source: [String: JSONValue],
+ toolName: String,
+ path: String
+ ) throws -> [String: JSONValue] {
+ if let result = try adaptStringConstantUnion(
+ source, toolName: toolName, path: path) {
+ return result
+ }
+ return try adaptNullableUnion(source, toolName: toolName, path: path)
+ }
+
+ private static func adaptStringConstantUnion(
+ _ source: [String: JSONValue],
+ toolName: String,
+ path: String
+ ) throws -> [String: JSONValue]? {
+ guard !(source["anyOf"] != nil && source["oneOf"] != nil) else { return nil }
+ let keyword = source["anyOf"] != nil ? "anyOf" : "oneOf"
+ guard case .array(let branches)? = source[keyword], branches.count >= 2 else {
+ return nil
+ }
+
+ var values: [JSONValue] = []
+ for branch in branches {
+ guard case .object(let object) = branch,
+ Set(object.keys).isSubset(of: ["const", "type"]),
+ object["type"] == .string("string"),
+ case .string = object["const"] else {
+ return nil
+ }
+ let value = object["const"]!
+ if keyword == "oneOf", values.contains(value) {
+ throw invalid(toolName, path, "oneOf constant branches overlap")
+ }
+ if !values.contains(value) { values.append(value) }
+ }
+
+ let allowedSiblings = annotations.union([keyword])
+ guard Set(source.keys).isSubset(of: allowedSiblings) else {
+ throw invalid(
+ toolName, path,
+ "constant union conflicts with sibling schema keywords")
+ }
+ var result = source
+ result[keyword] = nil
+ result["type"] = .string("string")
+ result["enum"] = .array(values)
+ return result
+ }
+
+ private static func adaptNullableUnion(
+ _ source: [String: JSONValue],
+ toolName: String,
+ path: String
+ ) throws -> [String: JSONValue] {
+ let keyword = source["anyOf"] != nil ? "anyOf" : "oneOf"
+ guard !(source["anyOf"] != nil && source["oneOf"] != nil),
+ case .array(let branches)? = source[keyword], branches.count == 2 else {
+ throw invalid(toolName, path, "only a two-branch nullable union is representable")
+ }
+ let nullIndexes = branches.indices.filter { index in
+ branches[index] == .object(["type": .string("null")])
+ }
+ guard nullIndexes.count == 1 else {
+ throw invalid(toolName, path, "union must contain one exact null branch")
+ }
+ let concreteIndex = nullIndexes[0] == 0 ? 1 : 0
+ guard case .object(let concreteSource) = branches[concreteIndex] else {
+ throw invalid(toolName, path, "non-null union branch must be an object schema")
+ }
+ let concreteValue = try adapt(
+ .object(concreteSource), toolName: toolName, path: path)
+ guard case .object(let concrete) = concreteValue,
+ concrete["type"] != .string("null") else {
+ throw invalid(toolName, path, "union requires one non-null typed branch")
+ }
+ if keyword == "oneOf", concrete["nullable"] == .bool(true) {
+ throw invalid(toolName, path, "oneOf branches overlap on null")
+ }
+
+ var result = source
+ result[keyword] = nil
+ if let nullable = result["nullable"], nullable != .bool(true) {
+ throw invalid(toolName, path, "nullable union conflicts with nullable keyword")
+ }
+ for (key, value) in concrete {
+ if let existing = result[key], existing != value,
+ !annotations.contains(key) {
+ throw invalid(toolName, path, "union branch conflicts with sibling keyword \(key)")
+ }
+ if result[key] == nil || annotations.contains(key) {
+ result[key] = result[key] ?? value
+ }
+ }
+ result["nullable"] = .bool(true)
+ return result
+ }
+
+ private static func validatedType(_ name: String,
+ toolName: String,
+ path: String) throws -> String {
+ guard types.contains(name) else {
+ throw invalid(toolName, path, "unknown JSON Schema type \(name)")
+ }
+ return name
+ }
+
+ private static func invalid(_ toolName: String,
+ _ path: String,
+ _ reason: String) -> ServerRequestError {
+ .invalid(message: "tool \(toolName) schema at \(path): \(reason)",
+ param: "tools",
+ code: "invalid_tool_schema")
+ }
+}
diff --git a/Sources/TurboFieldfareServer/Core/HTTPServer.swift b/Sources/TurboFieldfareServer/Core/HTTPServer.swift
index 998a3009..7bb7a5b7 100644
--- a/Sources/TurboFieldfareServer/Core/HTTPServer.swift
+++ b/Sources/TurboFieldfareServer/Core/HTTPServer.swift
@@ -170,7 +170,9 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
private func route(head: HTTPRequestHead,
body: ByteBuffer,
context: ChannelHandlerContext) {
- switch (head.method, head.uri) {
+ let path = head.uri.split(separator: "?", maxSplits: 1,
+ omittingEmptySubsequences: false).first.map(String.init) ?? head.uri
+ switch (head.method, path) {
case (.GET, "/health"):
writeJSON(context, status: .ok, object: ["status": "ok"])
case (.GET, "/v1/models"):
@@ -211,6 +213,7 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
let created = Int(Date().timeIntervalSince1970)
let contextBox = SendableContext(context)
let streamState = StreamState()
+ let phaseState = RequestPhaseState()
let startStream: @Sendable () -> Void = {
guard request.stream,
streamState.start(eventLoop: contextBox.value.eventLoop,
@@ -218,37 +221,62 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
ping: {
self.writeHeartbeat(contextBox.value)
}) else { return }
- self.beginStream(contextBox.value)
- self.writeStreamChunk(
+ let future = self.beginStream(
contextBox.value,
self.chunk(id: responseID, created: created,
delta: ["role": "assistant"],
finishReason: nil))
+ streamState.setStartFuture(future)
+ }
+ let onQueued: @Sendable () -> Void = {
+ phaseState.set("queued")
+ ServerLog.queued(id: responseID)
+ startStream()
}
activeTask = childChannels.startTask {
defer { streamState.stop() }
+ let started = ContinuousClock.now
+ ServerLog.accepted(id: responseID, streaming: request.stream)
do {
- let completion = try await self.coordinator.run(onQueued: startStream) {
- startStream()
- return try await self.backend.generate(request) { event in
- guard request.stream else { return }
- switch event {
- case .content(let text):
- self.writeStreamChunk(
- contextBox.value,
- self.chunk(id: responseID, created: created,
- delta: ["content": text],
- finishReason: nil))
- case .toolCall(let call):
- self.writeToolCall(contextBox.value,
- id: responseID,
- created: created,
- toolIndex: streamState.nextToolIndex(),
- call: call)
+ let completion = try await self.coordinator.runPreparing(
+ onQueued: onQueued,
+ prepare: {
+ let prepared = try await self.backend.prepare(request)
+ phaseState.set("prepared")
+ ServerLog.prepared(id: responseID,
+ promptTokens: prepared.promptTokenCount)
+ return prepared
+ },
+ operation: { prepared in
+ try Task.checkCancellation()
+ startStream()
+ try await streamState.waitUntilStarted()
+ try Task.checkCancellation()
+ phaseState.set("generating")
+ ServerLog.generating(id: responseID)
+ return try await self.backend.generate(prepared) { event in
+ guard request.stream else { return }
+ switch event {
+ case .content(let text):
+ self.writeStreamChunk(
+ contextBox.value,
+ self.chunk(id: responseID, created: created,
+ delta: ["content": text],
+ finishReason: nil))
+ case .toolCall(let call):
+ self.writeToolCall(contextBox.value,
+ id: responseID,
+ created: created,
+ toolIndex: streamState.nextToolIndex(),
+ call: call)
+ }
}
- }
- }
+ })
+ ServerLog.completed(id: responseID,
+ duration: started.duration(to: .now),
+ completion: completion)
if request.stream {
+ streamState.stop()
self.finishStream(contextBox.value,
id: responseID,
created: created,
@@ -261,8 +289,11 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
completion: completion)
}
} catch {
+ streamState.stop()
self.handleAsyncError(error,
context: contextBox.value,
+ id: responseID,
+ phase: phaseState.value,
stream: streamState.isStarted)
}
}
@@ -307,18 +338,35 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
writeJSON(context, status: .ok, object: object)
}
- private func beginStream(_ context: ChannelHandlerContext) {
+ private func beginStream(
+ _ context: ChannelHandlerContext,
+ _ initialChunk: [String: Any]
+ ) -> EventLoopFuture<Void> {
+ guard let data = try? JSONSerialization.data(withJSONObject: initialChunk) else {
+ return context.eventLoop.makeFailedFuture(ServerRequestError.invalid(
+ message: "stream response could not be encoded",
+ param: nil,
+ code: "internal_error"))
+ }
var headers = HTTPHeaders()
headers.add(name: "content-type", value: "text/event-stream")
headers.add(name: "cache-control", value: "no-cache")
headers.add(name: "connection", value: "keep-alive")
let head = HTTPResponseHead(version: .http1_1, status: .ok, headers: headers)
let contextBox = SendableContext(context)
+ let promise = context.eventLoop.makePromise(of: Void.self)
context.eventLoop.execute {
contextBox.value.write(self.wrapOutboundOut(.head(head)),
promise: nil)
- contextBox.value.flush()
+ var buffer = contextBox.value.channel.allocator.buffer(capacity: data.count + 8)
+ buffer.writeString("data: ")
+ buffer.writeBytes(data)
+ buffer.writeString("\n\n")
+ contextBox.value.writeAndFlush(
+ self.wrapOutboundOut(.body(.byteBuffer(buffer))),
+ promise: promise)
}
+ return promise.futureResult
}
private func writeToolCall(_ context: ChannelHandlerContext,
@@ -413,21 +461,46 @@ private final class ServerHTTPHandler: ChannelInboundHandler, @unchecked Sendabl
private func handleAsyncError(_ error: Error,
context: ChannelHandlerContext,
+ id: String,
+ phase: String,
stream: Bool) {
+ let envelope: OpenAIErrorEnvelope
+ let status: HTTPResponseStatus
+ if let requestError = error as? ServerRequestError {
+ status = requestError == .queueFull ? .tooManyRequests : .badRequest
+ envelope = requestError.envelope
+ } else {
+ status = .internalServerError
+ envelope = OpenAIErrorEnvelope(
+ message: "generation failed; see TurboFieldfareServer stderr",
+ code: "internal_error",
+ type: "server_error")
+ }
+ if !(error is CancellationError) {
+ ServerLog.failed(id: id, phase: phase, status: status.code, error: error)
+ }
if stream {
- let contextBox = SendableContext(context)
- context.eventLoop.execute {
- contextBox.value.close(promise: nil)
- }
+ finishStreamWithError(context, envelope: envelope)
return
}
- if let requestError = error as? ServerRequestError {
- let status: HTTPResponseStatus = requestError == .queueFull ? .tooManyRequests : .badRequest
- writeError(context, status: status, requestError.envelope)
- } else {
- writeError(context, status: .internalServerError,
- OpenAIErrorEnvelope(message: "generation failed",
- code: "internal_error"))
+ writeError(context, status: status, envelope)
+ }
+
+ private func finishStreamWithError(_ context: ChannelHandlerContext,
+ envelope: OpenAIErrorEnvelope) {
+ guard let data = try? JSONEncoder().encode(envelope) else { return }
+ let contextBox = SendableContext(context)
+ context.eventLoop.execute {
+ guard contextBox.value.channel.isActive else { return }
+ var buffer = contextBox.value.channel.allocator.buffer(
+ capacity: data.count + 32)
+ buffer.writeString("data: ")
+ buffer.writeBytes(data)
+ buffer.writeString("\n\ndata: [DONE]\n\n")
+ contextBox.value.write(
+ self.wrapOutboundOut(.body(.byteBuffer(buffer))), promise: nil)
+ contextBox.value.writeAndFlush(
+ self.wrapOutboundOut(.end(nil)), promise: nil)
}
}
@@ -588,11 +661,22 @@ private final class SendableContext: @unchecked Sendable {
}
}
+private final class RequestPhaseState: Sendable {
+ private let state = Mutex("accepted")
+
+ var value: String { state.withLock { $0 } }
+
+ func set(_ value: String) {
+ state.withLock { $0 = value }
+ }
+}
+
private final class StreamState: @unchecked Sendable {
private let lock = NSLock()
private var started = false
private var stopped = false
private var heartbeat: RepeatedTask?
+ private var startFuture: EventLoopFuture<Void>?
private var toolIndex = 0
var isStarted: Bool {
@@ -606,6 +690,7 @@ private final class StreamState: @unchecked Sendable {
guard !started else { return false }
started = true
stopped = false
+ startFuture = nil
heartbeat = eventLoop.scheduleRepeatedTask(
initialDelay: interval,
delay: interval) { [weak self] _ in
@@ -616,6 +701,17 @@ private final class StreamState: @unchecked Sendable {
}
}
+ func setStartFuture(_ future: EventLoopFuture<Void>) {
+ lock.withLock { startFuture = future }
+ }
+
+ func waitUntilStarted() async throws {
+ let future = lock.withLock { startFuture }
+ if let future {
+ try await future.get()
+ }
+ }
+
private var shouldPing: Bool {
lock.withLock { started && !stopped }
}
diff --git a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
index f2c33ac2..e6dfe64b 100644
--- a/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
+++ b/Sources/TurboFieldfareServer/Core/OpenAIModels.swift
@@ -11,9 +11,10 @@ public struct OpenAIErrorEnvelope: Codable, Equatable, Sendable {
public let error: Detail
- public init(message: String, param: String? = nil, code: String) {
+ public init(message: String, param: String? = nil, code: String,
+ type: String = "invalid_request_error") {
error = Detail(message: message,
- type: "invalid_request_error",
+ type: type,
param: param,
code: code)
}
@@ -343,13 +344,15 @@ public enum OpenAIRequestValidator {
"tools", "invalid_tool_schema")
}
try validateSchemaKeys(tool.function.parameters)
- guard (try? tool.function.parameters.jinjaSendableValue()) != nil else {
+ let parameters = try GemmaToolSchema.adapted(
+ tool.function.parameters, toolName: name)
+ guard (try? parameters.jinjaSendableValue()) != nil else {
throw invalid("tool schema contains a number that cannot be represented exactly",
"tools", "invalid_tool_schema")
}
return GFTokenizer.FunctionDefinition(name: name,
description: tool.function.description ?? "",
- parameters: tool.function.parameters)
+ parameters: parameters)
}
private static func validateSchemaKeys(_ schema: JSONValue) throws {
diff --git a/Sources/TurboFieldfareServer/Core/ServerInference.swift b/Sources/TurboFieldfareServer/Core/ServerInference.swift
index da852bb8..bd276158 100644
--- a/Sources/TurboFieldfareServer/Core/ServerInference.swift
+++ b/Sources/TurboFieldfareServer/Core/ServerInference.swift
@@ -24,9 +24,37 @@ public struct ServerCompletion: Equatable, Sendable {
}
}
+public struct ServerPreparedRequest: Sendable {
+ public let request: ValidatedChatRequest
+ fileprivate let promptIDs: [Int32]?
+
+ public var promptTokenCount: Int? { promptIDs?.count }
+
+ init(request: ValidatedChatRequest, promptIDs: [Int32]? = nil) {
+ self.request = request
+ self.promptIDs = promptIDs
+ }
+}
+
public protocol ServerInferenceBackend: Sendable {
+ func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest
func generate(_ request: ValidatedChatRequest,
onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void) async throws -> ServerCompletion
+ func generate(_ prepared: ServerPreparedRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void) async throws -> ServerCompletion
+}
+
+public extension ServerInferenceBackend {
+ func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest {
+ ServerPreparedRequest(request: request)
+ }
+
+ func generate(
+ _ prepared: ServerPreparedRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ try await generate(prepared.request, onEvent: onEvent)
+ }
}
public actor ServerCoordinator {
@@ -36,6 +64,7 @@ public actor ServerCoordinator {
}
private let queueLimit: Int
+ private var admittedCount = 0
private var active = false
private var waiters: [Waiter] = []
private var shuttingDown = false
@@ -48,9 +77,28 @@ public actor ServerCoordinator {
onQueued: @escaping @Sendable () -> Void = {},
_ operation: @escaping @Sendable () async throws -> T
) async throws -> T {
+ try await runPreparing(
+ onQueued: onQueued,
+ prepare: { () },
+ operation: { _ in try await operation() })
+ }
+
+ func runPreparing<Prepared: Sendable, T: Sendable>(
+ onQueued: @escaping @Sendable () -> Void = {},
+ prepare: @escaping @Sendable () async throws -> Prepared,
+ operation: @escaping @Sendable (Prepared) async throws -> T
+ ) async throws -> T {
+ try Task.checkCancellation()
+ guard !shuttingDown else { throw CancellationError() }
+ guard admittedCount <= queueLimit else { throw ServerRequestError.queueFull }
+ admittedCount += 1
+ defer { admittedCount -= 1 }
+
+ let prepared = try await prepare()
+ try Task.checkCancellation()
try await acquire(onQueued: onQueued)
defer { release() }
- return try await operation()
+ return try await operation(prepared)
}
private func acquire(onQueued: @escaping @Sendable () -> Void) async throws {
@@ -197,6 +245,19 @@ public actor ServerModelSession: ServerInferenceBackend {
_ request: ValidatedChatRequest,
onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
) async throws -> ServerCompletion {
+ let prepared = try await prepare(request)
+ return try await generate(prepared, onEvent: onEvent)
+ }
+
+ public func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest {
+ ServerPreparedRequest(request: request, promptIDs: try renderPrompt(request))
+ }
+
+ public func generate(
+ _ prepared: ServerPreparedRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ let request = prepared.request
var completed = false
defer {
if !completed {
@@ -204,23 +265,8 @@ public actor ServerModelSession: ServerInferenceBackend {
runner.reset()
}
}
- let needsToolTemplate = !request.tools.isEmpty
- || request.messages.contains {
- $0.role == .developer || $0.role == .tool || !$0.toolCalls.isEmpty
- }
- let promptIDs: [Int32]
- if needsToolTemplate {
- promptIDs = try tokenizer.encodeToolChat(messages: request.messages, tools: request.tools)
- } else {
- let rendered = try tokenizer.applyChatTemplate(request.messages)
- promptIDs = tokenizer.encode(rendered, addBOS: false)
- }
- guard promptIDs.count < maxContext else {
- throw ServerRequestError.invalid(
- message: "prompt exceeds the configured context",
- param: "messages",
- code: "context_length_exceeded")
- }
+ let needsToolTemplate = usesToolTemplate(request)
+ let promptIDs = try prepared.promptIDs ?? renderPrompt(request)
let effectivePromptIDs: [Int32]
let completionStart: RawCompletionStart
@@ -351,4 +397,29 @@ public actor ServerModelSession: ServerInferenceBackend {
totalTokens: result.prefillTokens + result.newTokens,
cachedTokens: result.cachedPromptTokens))
}
+
+ private func renderPrompt(_ request: ValidatedChatRequest) throws -> [Int32] {
+ let promptIDs: [Int32]
+ if usesToolTemplate(request) {
+ promptIDs = try tokenizer.encodeToolChat(
+ messages: request.messages,
+ tools: request.tools)
+ } else {
+ let rendered = try tokenizer.applyChatTemplate(request.messages)
+ promptIDs = tokenizer.encode(rendered, addBOS: false)
+ }
+ guard promptIDs.count < maxContext else {
+ throw ServerRequestError.invalid(
+ message: "prompt exceeds the configured context",
+ param: "messages",
+ code: "context_length_exceeded")
+ }
+ return promptIDs
+ }
+
+ private func usesToolTemplate(_ request: ValidatedChatRequest) -> Bool {
+ !request.tools.isEmpty || request.messages.contains {
+ $0.role == .developer || $0.role == .tool || !$0.toolCalls.isEmpty
+ }
+ }
}
diff --git a/Sources/TurboFieldfareServer/Core/ServerLog.swift b/Sources/TurboFieldfareServer/Core/ServerLog.swift
new file mode 100644
index 00000000..c29fdcb4
--- /dev/null
+++ b/Sources/TurboFieldfareServer/Core/ServerLog.swift
@@ -0,0 +1,50 @@
+import Foundation
+
+enum ServerLog {
+ static func accepted(id: String, streaming: Bool) {
+ write("request \(id) accepted streaming=\(streaming)")
+ }
+
+ static func prepared(id: String, promptTokens: Int?) {
+ let count = promptTokens.map(String.init) ?? "backend-managed"
+ write("request \(id) prepared prompt=\(count)")
+ }
+
+ static func queued(id: String) {
+ write("request \(id) queued")
+ }
+
+ static func generating(id: String) {
+ write("request \(id) generating")
+ }
+
+ static func completed(id: String,
+ duration: Duration,
+ completion: ServerCompletion) {
+ let usage = completion.usage
+ write("request \(id) completed in \(format(duration)) "
+ + "prompt=\(usage.promptTokens) "
+ + "cached=\(usage.promptTokensDetails.cachedTokens) "
+ + "completion=\(usage.completionTokens) "
+ + "finish=\(completion.finishReason)")
+ }
+
+ static func failed(id: String,
+ phase: String,
+ status: UInt,
+ error: Error) {
+ write("request \(id) failed phase=\(phase) status=\(status) "
+ + "error=\(String(reflecting: error))")
+ }
+
+ private static func format(_ duration: Duration) -> String {
+ let seconds = Double(duration.components.seconds)
+ + Double(duration.components.attoseconds) / 1e18
+ return String(format: "%.3fs", seconds)
+ }
+
+ private static func write(_ message: String) {
+ let line = "[\(Date().formatted(.iso8601))] \(message)\n"
+ FileHandle.standardError.write(Data(line.utf8))
+ }
+}
diff --git a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift
index d22cba64..df4e9379 100644
--- a/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift
+++ b/Tests/TurboFieldfare/Core/Tokenization/TokenizerTests.swift
@@ -97,6 +97,10 @@ struct TokenizerTests {
"🦝🦝🦝",
"mixed 漢 and 🦝",
"Здравствуй мир",
+ "ห้ามใช้ในสัปดาห์นี้",
+ "नमस्ते दुनिया",
+ "مَرْحَبًا",
+ "\u{1F469}\u{200D}\u{1F4BB} works with \u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}",
"ends with emoji 🦝",
"🦝 starts with emoji",
"🦝 middle 漢 end",
@@ -118,6 +122,65 @@ struct TokenizerTests {
#expect(!tail.unicodeScalars.contains("\u{FFFD}"))
}
+ @Test("Streaming delta preserves graphemes extended by later scalars")
+ func streamingExtendedGraphemes() {
+ let cases = [
+ ("ห", "ห้าม", "้าม"),
+ ("e", "e\u{301}", "\u{301}"),
+ ("ا", "ا\u{64E}", "\u{64E}"),
+ ("ש", "ש\u{5B8}", "\u{5B8}"),
+ ("क", "क्ष", "्ष"),
+ ("\u{1100}", "\u{1100}\u{1161}", "\u{1161}"),
+ ("\u{263A}", "\u{263A}\u{FE0F}", "\u{FE0F}"),
+ ("\u{1F44D}", "\u{1F44D}\u{1F3FD}", "\u{1F3FD}"),
+ ("1", "1\u{FE0F}\u{20E3}", "\u{FE0F}\u{20E3}"),
+ ("\u{1F1EC}", "\u{1F1EC}\u{1F1E7}", "\u{1F1E7}"),
+ ("\u{1F469}", "\u{1F469}\u{200D}\u{1F4BB}", "\u{200D}\u{1F4BB}"),
+ ]
+ for (prefix, current, expectedDelta) in cases {
+ var detok = GFDetokenizer(tokenizer: tok)
+ #expect(detok.commitDelta(prefix) == prefix)
+ #expect(detok.commitDelta(current) == expectedDelta)
+ }
+ }
+
+ @Test("Streaming delta resynchronizes after a rewritten prefix")
+ func streamingPrefixResync() {
+ var detok = GFDetokenizer(tokenizer: tok)
+ #expect(detok.commitDelta("abc") == "abc")
+ #expect(detok.commitDelta("ax") == "")
+ #expect(detok.commitDelta("axy") == "y")
+ }
+
+ @Test("Streaming detokenizer matches full decode for complex Unicode", arguments: [
+ "English العَرَبِيَّةُ ١٢٣ ثم English",
+ "left \u{2067}العَرَبِيَّةُ ١٢٣\u{2069} right",
+ "English עברית מְנֻּקֶדֶת 42",
+ "فارسی می\u{200C}خواهم English",
+ "क्\u{200D}ष क्\u{200C}ष English",
+ "ພາສາລາວ English",
+ "ខ្ញុំសរសេរភាសាខ្មែរ English",
+ "မြန်မာစာ English",
+ "বাংলা ভাষা English",
+ "සිංහල භාෂාව English",
+ "བོད་ཡིག English",
+ "\u{1100}\u{1161}\u{11A8} 한글 English",
+ "a\u{301}\u{323}\u{304} e\u{308}\u{301}",
+ "\u{1F44D}\u{1F3FD} \u{263A}\u{FE0F} 1\u{FE0F}\u{20E3} \u{1F1EC}\u{1F1E7} \u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}",
+ ])
+ func streamingComplexUnicode(_ text: String) {
+ let ids = tok.encode(text, addBOS: false)
+ let expected = tok.decode(ids)
+ var detok = GFDetokenizer(tokenizer: tok)
+ var assembled = ""
+ for id in ids {
+ assembled += detok.push(id)
+ }
+ assembled += detok.flush()
+ #expect(assembled == expected)
+ #expect(!assembled.unicodeScalars.contains("\u{FFFD}"))
+ }
+
@Test("Streaming detokenizer preserves long mixed output", arguments: [
"The quick brown fox jumps over the lazy dog. 0123456789\n",
"\u{E000}\u{E001}\u{E002}\u{E003}\u{E004}\u{E005}\u{E006}\u{E007}",
diff --git a/Tests/TurboFieldfareServer/HTTPServerTests.swift b/Tests/TurboFieldfareServer/HTTPServerTests.swift
index bea9ff91..379eddac 100644
--- a/Tests/TurboFieldfareServer/HTTPServerTests.swift
+++ b/Tests/TurboFieldfareServer/HTTPServerTests.swift
@@ -123,6 +123,150 @@ private actor CancellableServerBackend: ServerInferenceBackend {
}
}
+private actor QueueHeartbeatBackend: ServerInferenceBackend {
+ private var firstContinuation: CheckedContinuation<Void, Never>?
+ private(set) var startedCount = 0
+
+ var firstIsWaiting: Bool { firstContinuation != nil }
+
+ func releaseFirst() {
+ firstContinuation?.resume()
+ firstContinuation = nil
+ }
+
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ startedCount += 1
+ if startedCount == 1 {
+ await withCheckedContinuation { firstContinuation = $0 }
+ }
+ onEvent(.content("hello"))
+ return ServerCompletion(
+ content: "hello",
+ toolCalls: [],
+ finishReason: "stop",
+ usage: OpenAIUsage(promptTokens: 3, completionTokens: 1, totalTokens: 4))
+ }
+}
+
+private actor CancellationIgnoringPreparationBackend: ServerInferenceBackend {
+ let delay: Duration
+ private(set) var preparationStarted = false
+ private(set) var cancellationCount = 0
+ private(set) var generationCount = 0
+
+ init(delay: Duration = .seconds(30)) {
+ self.delay = delay
+ }
+
+ func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest {
+ preparationStarted = true
+ do {
+ try await Task.sleep(for: delay)
+ } catch is CancellationError {
+ cancellationCount += 1
+ }
+ return ServerPreparedRequest(request: request)
+ }
+
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ generationCount += 1
+ return ServerCompletion(
+ content: "unexpected",
+ toolCalls: [],
+ finishReason: "stop",
+ usage: OpenAIUsage(promptTokens: 1, completionTokens: 1, totalTokens: 2))
+ }
+}
+
+private actor InvalidRequestServerBackend: ServerInferenceBackend {
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ throw ServerRequestError.invalid(
+ message: "prompt exceeds the configured context",
+ param: "messages",
+ code: "context_length_exceeded")
+ }
+}
+
+private actor PreflightRejectingServerBackend: ServerInferenceBackend {
+ private(set) var generationCount = 0
+
+ func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest {
+ throw ServerRequestError.invalid(
+ message: "prompt exceeds the configured context",
+ param: "messages",
+ code: "context_length_exceeded")
+ }
+
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ generationCount += 1
+ return ServerCompletion(
+ content: "unexpected",
+ toolCalls: [],
+ finishReason: "stop",
+ usage: OpenAIUsage(promptTokens: 1, completionTokens: 1, totalTokens: 2))
+ }
+}
+
+private actor AdmissionBlockingPreparationBackend: ServerInferenceBackend {
+ private var continuations: [CheckedContinuation<Void, Never>] = []
+ private var released = false
+ private(set) var preparationCount = 0
+
+ func prepare(_ request: ValidatedChatRequest) async throws -> ServerPreparedRequest {
+ preparationCount += 1
+ if !released {
+ await withCheckedContinuation { continuations.append($0) }
+ }
+ try Task.checkCancellation()
+ return ServerPreparedRequest(request: request)
+ }
+
+ func releaseAll() {
+ released = true
+ let waiting = continuations
+ continuations.removeAll()
+ for continuation in waiting {
+ continuation.resume()
+ }
+ }
+
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ ServerCompletion(
+ content: "ready",
+ toolCalls: [],
+ finishReason: "stop",
+ usage: OpenAIUsage(promptTokens: 1, completionTokens: 1, totalTokens: 2))
+ }
+}
+
+private enum TestGenerationError: Error, Sendable {
+ case sensitiveFailure
+}
+
+private actor FailingServerBackend: ServerInferenceBackend {
+ func generate(
+ _ request: ValidatedChatRequest,
+ onEvent: @escaping @Sendable (ServerInferenceEvent) -> Void
+ ) async throws -> ServerCompletion {
+ throw TestGenerationError.sensitiveFailure
+ }
+}
+
@Suite("OpenAI HTTP server", .serialized)
struct HTTPServerTests {
@Test func healthModelsAndNonStreamingCompletion() async throws {
@@ -190,6 +334,147 @@ struct HTTPServerTests {
try await server.shutdown()
}
+ @Test func queryStringDoesNotChangeRoute() 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)
+
+ let models = try await URLSession.shared.data(
+ from: URL(string: "http://127.0.0.1:\(port)/v1/models?xcode=1")!)
+ #expect((models.1 as? HTTPURLResponse)?.statusCode == 200)
+ #expect(String(decoding: models.0, as: UTF8.self).contains("test-model"))
+
+ var request = URLRequest(
+ url: URL(string: "http://127.0.0.1:\(port)/v1/chat/completions?client=xcode")!)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ request.httpBody = Data(#"""
+ {"model":"test-model","messages":[{"role":"user","content":"hi"}]}
+ """#.utf8)
+ let completion = try await URLSession.shared.data(for: request)
+ #expect((completion.1 as? HTTPURLResponse)?.statusCode == 200)
+ #expect(String(decoding: completion.0, as: UTF8.self).contains("hello"))
+
+ try await server.shutdown()
+ }
+
+ @Test func streamingPreflightErrorUsesHTTPStatusBeforeSSEStarts() async throws {
+ let backend = PreflightRejectingServerBackend()
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: backend)
+ 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"}],
+ "stream":true}
+ """#.utf8)
+
+ let (data, response) = try await URLSession.shared.data(for: request)
+ #expect((response as? HTTPURLResponse)?.statusCode == 400)
+ #expect((response as? HTTPURLResponse)?.value(
+ forHTTPHeaderField: "content-type") == "application/json")
+ #expect(String(decoding: data, as: UTF8.self).contains(
+ #""code":"context_length_exceeded""#))
+ #expect(await backend.generationCount == 0)
+
+ try await server.shutdown()
+ }
+
+ @Test func unsupportedToolSchemaReturnsHTTP400BeforeSSEStarts() 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"}],
+ "stream":true,
+ "tools":[{"type":"function","function":{
+ "name":"unsafe",
+ "parameters":{"type":"object","properties":{
+ "value":{"anyOf":[{"type":"string"},{"type":"object"}]}
+ }}
+ }}]
+ }
+ """#.utf8)
+ let (data, response) = try await URLSession.shared.data(for: request)
+ #expect((response as? HTTPURLResponse)?.statusCode == 400)
+ let text = String(decoding: data, as: UTF8.self)
+ #expect(text.contains(#""code":"invalid_tool_schema""#))
+ #expect(text.contains(#""param":"tools""#))
+ #expect(!text.contains("data:"))
+
+ try await server.shutdown()
+ }
+
+ @Test func streamingRequestErrorUsesEnvelopeAndCompletesTransport() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: InvalidRequestServerBackend())
+ 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"}],
+ "stream":true}
+ """#.utf8)
+
+ let (data, response) = try await URLSession.shared.data(for: request)
+ #expect((response as? HTTPURLResponse)?.statusCode == 200)
+ let text = String(decoding: data, as: UTF8.self)
+ #expect(text.contains(#""code":"context_length_exceeded""#))
+ #expect(text.contains(#""param":"messages""#))
+ #expect(text.hasSuffix("data: [DONE]\n\n"))
+
+ try await server.shutdown()
+ }
+
+ @Test func streamingInternalErrorIsMaskedAndCompletesTransport() async throws {
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: FailingServerBackend())
+ 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"}],
+ "stream":true}
+ """#.utf8)
+
+ let data = try await URLSession.shared.data(for: request).0
+ let text = String(decoding: data, as: UTF8.self)
+ #expect(text.contains(#""type":"server_error""#))
+ #expect(text.contains(#""code":"internal_error""#))
+ #expect(!text.contains("sensitiveFailure"))
+ #expect(text.hasSuffix("data: [DONE]\n\n"))
+
+ try await server.shutdown()
+ }
+
@Test func wrongModelUsesOpenAIErrorEnvelope() async throws {
let server = TurboFieldfareHTTPServer(
modelID: "test-model",
@@ -232,6 +517,172 @@ struct HTTPServerTests {
try await server.shutdown()
}
+ @Test func queuedStreamingRequestReceivesHeartbeatBeforeItsTurn() async throws {
+ let backend = QueueHeartbeatBackend()
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: backend,
+ heartbeatInterval: .milliseconds(100))
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let firstSocket = try connectedSocket(port: port)
+ let secondSocket = try connectedSocket(port: port)
+ defer {
+ Darwin.close(firstSocket)
+ Darwin.close(secondSocket)
+ }
+
+ let blockingBody =
+ #"{"model":"test-model","messages":[{"role":"user","content":"first"}]}"#
+ let streamingBody =
+ #"{"model":"test-model","messages":[{"role":"user","content":"second"}],"stream":true}"#
+ try writeAll(socket: firstSocket, text: httpRequest(
+ port: port, body: blockingBody, connection: "keep-alive"))
+ let activeDeadline = ContinuousClock.now + .seconds(2)
+ while await !backend.firstIsWaiting, ContinuousClock.now < activeDeadline {
+ await Task.yield()
+ }
+ #expect(await backend.firstIsWaiting)
+
+ try writeAll(socket: secondSocket, text: httpRequest(
+ port: port, body: streamingBody, connection: "close"))
+ let queuedDeadline = ContinuousClock.now + .seconds(2)
+ while await server.queuedRequestCount != 1, ContinuousClock.now < queuedDeadline {
+ await Task.yield()
+ }
+ #expect(await server.queuedRequestCount == 1)
+
+ let queuedResponse: String
+ do {
+ queuedResponse = try readUntil(
+ socket: secondSocket,
+ timeoutMilliseconds: 1_000,
+ condition: { $0.contains(": ping\n\n") })
+ } catch {
+ await backend.releaseFirst()
+ try? await server.shutdown()
+ throw error
+ }
+ #expect(queuedResponse.contains("HTTP/1.1 200 OK"))
+ #expect(queuedResponse.contains(#""role":"assistant""#))
+ #expect(queuedResponse.contains(": ping\n\n"))
+ #expect(await backend.startedCount == 1)
+
+ await backend.releaseFirst()
+ let completed = queuedResponse + (try readUntil(
+ socket: secondSocket,
+ timeoutMilliseconds: 2_000,
+ condition: { $0.contains("data: [DONE]\n\n") }))
+ #expect(completed.contains("data: [DONE]\n\n"))
+ #expect(await backend.startedCount == 2)
+
+ try await server.shutdown()
+ }
+
+ @Test func queueLimitBoundsRequestsBeforePreparation() async throws {
+ let backend = AdmissionBlockingPreparationBackend()
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: backend)
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let sockets = try (0..<3).map { _ in try connectedSocket(port: port) }
+ defer { sockets.forEach { _ = Darwin.close($0) } }
+ let body = #"{"model":"test-model","messages":[{"role":"user","content":"wait"}]}"#
+
+ try writeAll(socket: sockets[0], text: httpRequest(
+ port: port, body: body, connection: "close"))
+ try writeAll(socket: sockets[1], text: httpRequest(
+ port: port, body: body, connection: "close"))
+ let preparationDeadline = ContinuousClock.now + .seconds(2)
+ while await backend.preparationCount != 2,
+ ContinuousClock.now < preparationDeadline {
+ await Task.yield()
+ }
+ #expect(await backend.preparationCount == 2)
+
+ try writeAll(socket: sockets[2], text: httpRequest(
+ port: port, body: body, connection: "close"))
+ let rejected = try readUntil(
+ socket: sockets[2],
+ timeoutMilliseconds: 1_000,
+ condition: { $0.contains(#""code":"queue_full""#) })
+ #expect(rejected.contains("HTTP/1.1 429 Too Many Requests"))
+ #expect(await backend.preparationCount == 2)
+
+ await backend.releaseAll()
+ for socket in sockets.prefix(2) {
+ _ = try readUntil(
+ socket: socket,
+ timeoutMilliseconds: 2_000,
+ condition: { $0.contains(#""content":"ready""#) })
+ }
+ try await server.shutdown()
+ }
+
+ @Test func disconnectDuringPreparationNeverStartsGeneration() async throws {
+ let backend = CancellationIgnoringPreparationBackend(delay: .milliseconds(100))
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: backend)
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ let body = #"{"model":"test-model","messages":[{"role":"user","content":"wait"}],"stream":true}"#
+ try writeAll(socket: socket, text: httpRequest(
+ port: port, body: body, connection: "close"))
+
+ let preparationDeadline = ContinuousClock.now + .seconds(2)
+ while await !backend.preparationStarted,
+ ContinuousClock.now < preparationDeadline {
+ await Task.yield()
+ }
+ #expect(await backend.preparationStarted)
+ abortSocket(socket)
+
+ let completionDeadline = ContinuousClock.now + .seconds(2)
+ while await server.acceptedConnectionCount != 0,
+ ContinuousClock.now < completionDeadline {
+ await Task.yield()
+ }
+ #expect(await backend.generationCount == 0)
+ #expect(await server.acceptedConnectionCount == 0)
+
+ try await server.shutdown()
+ #expect(await !server.hasActiveRequest)
+ }
+
+ @Test func shutdownDuringPreparationNeverStartsGeneration() async throws {
+ let backend = CancellationIgnoringPreparationBackend()
+ let server = TurboFieldfareHTTPServer(
+ modelID: "test-model",
+ queueLimit: 1,
+ backend: backend)
+ let channel = try await server.start(port: 0)
+ let port = try #require(channel.localAddress?.port)
+ let socket = try connectedSocket(port: port)
+ defer { Darwin.close(socket) }
+ let body = #"{"model":"test-model","messages":[{"role":"user","content":"wait"}],"stream":true}"#
+ try writeAll(socket: socket, text: httpRequest(
+ port: port, body: body, connection: "keep-alive"))
+
+ let preparationDeadline = ContinuousClock.now + .seconds(2)
+ while await !backend.preparationStarted,
+ ContinuousClock.now < preparationDeadline {
+ await Task.yield()
+ }
+ #expect(await backend.preparationStarted)
+
+ try await server.shutdown()
+ #expect(await backend.cancellationCount == 1)
+ #expect(await backend.generationCount == 0)
+ #expect(await !server.hasActiveRequest)
+ try await server.shutdown()
+ }
+
@Test func streamingMultipleToolsUseDistinctIndexes() async throws {
let server = TurboFieldfareHTTPServer(
modelID: "test-model",
@@ -462,6 +913,25 @@ private func writeAll(socket: Int32, text: String) throws {
}
}
+private func httpRequest(port: Int, body: String, connection: String) -> String {
+ "POST /v1/chat/completions HTTP/1.1\r\n"
+ + "Host: 127.0.0.1:\(port)\r\n"
+ + "Content-Type: application/json\r\n"
+ + "Content-Length: \(body.utf8.count)\r\n"
+ + "Connection: \(connection)\r\n"
+ + "\r\n"
+ + body
+}
+
+private func abortSocket(_ socket: Int32) {
+ var option = linger(l_onoff: 1, l_linger: 0)
+ withUnsafePointer(to: &option) {
+ _ = Darwin.setsockopt(socket, SOL_SOCKET, SO_LINGER, $0,
+ socklen_t(MemoryLayout<linger>.size))
+ }
+ Darwin.close(socket)
+}
+
private func readAvailable(socket: Int32, timeoutMilliseconds: Int32) throws -> String {
var result: [UInt8] = []
var descriptor = pollfd(fd: socket, events: Int16(POLLIN), revents: 0)
diff --git a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
index f4e7b4d1..b39b14f4 100644
--- a/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
+++ b/Tests/TurboFieldfareServer/OpenAIValidationTests.swift
@@ -198,6 +198,143 @@ struct OpenAIValidationTests {
#expect(parsed.arguments.objectValue?["file-path"] == .string("/tmp/x"))
}
+ @Test func stringConstantUnionAdaptsToEnumAndRenders() async throws {
+ let data = Data(#"""
+ {
+ "model":"m",
+ "messages":[{"role":"user","content":"search"}],
+ "tools":[{
+ "type":"function",
+ "function":{
+ "name":"vcc_recall",
+ "description":"",
+ "parameters":{
+ "type":"object",
+ "properties":{
+ "scope":{
+ "anyOf":[
+ {"type":"string","const":"lineage"},
+ {"type":"string","const":"all"}
+ ],
+ "description":""
+ }
+ }
+ }
+ }
+ }]
+ }
+ """#.utf8)
+ let request = try JSONDecoder().decode(OpenAIChatRequest.self, from: data)
+ let validated = try OpenAIRequestValidator.validate(request, modelID: "m")
+ let tool = try #require(validated.tools.first)
+ let properties = try #require(tool.parameters.objectValue?["properties"]?.objectValue)
+ let scope = try #require(properties["scope"]?.objectValue)
+ #expect(scope["type"] == .string("string"))
+ #expect(scope["enum"] == .array([.string("lineage"), .string("all")]))
+ #expect(scope["anyOf"] == nil)
+
+ let tokenizer = try await GFTokenizer.load()
+ let rendered = tokenizer.decode(
+ try tokenizer.encodeToolChat(
+ messages: validated.messages,
+ tools: validated.tools),
+ skipSpecialTokens: false)
+ #expect(rendered.contains("lineage"))
+ #expect(rendered.contains("all"))
+ }
+
+ @Test func nullableToolSchemasAdaptWithoutChangingConstraints() throws {
+ let typeArray = try JSONDecoder().decode(JSONValue.self, from: Data(#"""
+ {
+ "type":"object",
+ "properties":{
+ "name":{"type":["null","string"],"minLength":2}
+ }
+ }
+ """#.utf8))
+ let adapted = try GemmaToolSchema.adapted(typeArray, toolName: "lookup")
+ let name = adapted.objectValue?["properties"]?.objectValue?["name"]?.objectValue
+ #expect(name?["type"] == .string("string"))
+ #expect(name?["nullable"] == .bool(true))
+ #expect(name?["minLength"] == .integer(2))
+ #expect(try GemmaToolSchema.adapted(adapted, toolName: "lookup") == adapted)
+
+ let anyOf = try JSONDecoder().decode(JSONValue.self, from: Data(#"""
+ {
+ "type":"object",
+ "properties":{
+ "limit":{"description":"limit","anyOf":[
+ {"type":"integer","minimum":1},
+ {"type":"null"}
+ ]}
+ }
+ }
+ """#.utf8))
+ let anyOfAdapted = try GemmaToolSchema.adapted(anyOf, toolName: "lookup")
+ let limit = anyOfAdapted.objectValue?["properties"]?.objectValue?["limit"]?.objectValue
+ #expect(limit?["type"] == .string("integer"))
+ #expect(limit?["nullable"] == .bool(true))
+ #expect(limit?["minimum"] == .integer(1))
+ #expect(limit?["description"] == .string("limit"))
+ #expect(limit?["anyOf"] == nil)
+
+ let nestedOneOf = try JSONDecoder().decode(JSONValue.self, from: Data(#"""
+ {
+ "type":"object",
+ "properties":{
+ "names":{"type":"array","items":{"oneOf":[
+ {"type":"null"},
+ {"type":"string","minLength":1}
+ ]}}
+ }
+ }
+ """#.utf8))
+ let nestedAdapted = try GemmaToolSchema.adapted(nestedOneOf, toolName: "lookup")
+ let item = nestedAdapted.objectValue?["properties"]?.objectValue?["names"]?
+ .objectValue?["items"]?.objectValue
+ #expect(item?["type"] == .string("string"))
+ #expect(item?["nullable"] == .bool(true))
+ #expect(item?["minLength"] == .integer(1))
+ #expect(item?["oneOf"] == nil)
+ }
+
+ @Test func unsupportedToolSchemaUnionsFailClosed() throws {
+ let schemas = [
+ #"{"type":"object","properties":{"v":{"anyOf":[{"type":"string"},{"type":"object"}]}}}"#,
+ #"{"type":"object","properties":{"args":{"anyOf":[{"type":"string"},{"type":"object","properties":{},"additionalProperties":true}]}}}"#,
+ #"{"type":"object","properties":{"v":{"oneOf":[{"type":"integer"},{"type":"number"}]}}}"#,
+ #"{"type":"object","properties":{"v":{"allOf":[{"type":"string"}]}}}"#,
+ #"{"type":"object","properties":{"v":{"description":"missing"}}}"#,
+ #"{"type":"object","properties":{"v":{"type":["string","number"]}}}"#,
+ #"{"type":"object","properties":{"v":{"type":["string","null"],"nullable":false}}}"#,
+ #"{"type":"object","properties":{"v":true}}"#,
+ ]
+ for encoded in schemas {
+ let schema = try JSONDecoder().decode(JSONValue.self, from: Data(encoded.utf8))
+ do {
+ _ = try GemmaToolSchema.adapted(schema, toolName: "unsafe")
+ Issue.record("unsupported schema was accepted: \(encoded)")
+ } catch let error as ServerRequestError {
+ #expect(error.envelope.error.code == "invalid_tool_schema")
+ #expect(error.envelope.error.param == "tools")
+ }
+ }
+ }
+
+ @Test func semanticsChangingNullableSchemasFailClosed() throws {
+ let schemas = [
+ #"{"type":["object","null"],"properties":{}}"#,
+ #"{"type":"object","properties":{"v":{"oneOf":[{"type":["string","null"]},{"type":"null"}]}}}"#,
+ #"{"type":"object","properties":{"v":{"oneOf":[{"type":"string","const":"same"},{"type":"string","const":"same"}]}}}"#,
+ ]
+ for encoded in schemas {
+ let schema = try JSONDecoder().decode(JSONValue.self, from: Data(encoded.utf8))
+ #expect(throws: ServerRequestError.self) {
+ try GemmaToolSchema.adapted(schema, toolName: "unsafe")
+ }
+ }
+ }
+
@Test func ambiguousParameterKeysFailValidation() throws {
let data = Data(#"""
{
diff --git a/docs/OPENAI_SERVER.md b/docs/OPENAI_SERVER.md
index 3633c3b3..d2bf4ebb 100644
--- a/docs/OPENAI_SERVER.md
+++ b/docs/OPENAI_SERVER.md
@@ -42,8 +42,10 @@ curl --silent --show-error http://127.0.0.1:8080/v1/chat/completions \
}'
```
-By default, the server runs one generation and queues up to four requests. Use
-`--queue-limit` to change the queue size. Press Control-C to stop the server.
+By default, the server runs one generation and admits up to four additional
+requests for preparation or queueing. The limit is enforced before prompt
+rendering and tokenization. Use `--queue-limit` to change it. Press Control-C
+to stop the server.
## Connect a client
@@ -78,7 +80,11 @@ OpenCode:
},
"models": {
"gemma-4-26b-a4b-it": {
- "name": "Gemma 4 26B-A4B IT"
+ "name": "Gemma 4 26B-A4B IT",
+ "limit": {
+ "context": 16384,
+ "output": 4096
+ }
}
}
}
@@ -88,6 +94,34 @@ OpenCode:
Select `turbofieldfare/gemma-4-26b-a4b-it` in OpenCode.
+Pi uses its `openai-completions` adapter:
+
+```json
+{
+ "providers": {
+ "turbofieldfare": {
+ "baseUrl": "http://127.0.0.1:8080/v1",
+ "api": "openai-completions",
+ "apiKey": "local",
+ "compat": {
+ "supportsReasoningEffort": false,
+ "supportsStrictMode": false,
+ "supportsUsageInStreaming": true
+ },
+ "models": [{
+ "id": "gemma-4-26b-a4b-it",
+ "name": "Gemma 4 26B-A4B IT",
+ "reasoning": false,
+ "contextWindow": 16384,
+ "maxTokens": 4096
+ }]
+ }
+ }
+}
+```
+
+Keep the client context setting at or below the server's `--max-context`.
+
## Prompt reuse
Single-prefix KV reuse is on by default. Send the complete message history with
@@ -119,6 +153,14 @@ The server accepts only function tools. Omit `tool_choice` or set it to `auto`
to allow calls. Set it to `none` to disable them. The server does not support
`required`, named tool selection, or `parallel_tool_calls: false`.
+Tool schemas need a non-null object at the top level and explicit JSON Schema
+types. Nested properties and items may use nullable forms with one concrete
+type plus `null`, including equivalent two-branch `anyOf` and disjoint `oneOf`
+forms. Unions of string constants are also supported. Overlapping `oneOf`,
+mixed-type unions such as `string | object`, and `allOf` return HTTP 400 with
+`invalid_tool_schema`; the server does not guess which branch the model should
+use.
+
## Supported API
Endpoints:
@@ -143,3 +185,7 @@ batching, log probabilities, or remote model switching.
Context length can be 4K, 8K, 16K, 32K, or 64K. The default is 16K. Larger FP16
KV contexts use more memory. On an 8 GB Mac, run one model process at a time and
watch memory pressure.
+
+For long requests, stderr reports the request lifecycle as prepared, queued,
+generating, completed, or failed. It includes token counts and timing, but not
+prompt text, tool arguments, headers, or request bodies.