From d43651cc08e7db8d3e91017e51151e0e8938648a Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:03:53 +0100 Subject: [PATCH 1/6] fix(selfedit): address #797 review and SelfRewrite HIGH defects (A-C2, A-C3, A-C7, A-S5, A-S7) --- Sources/BasaltCloud/GeminiCloudEditor.swift | 24 ++- Sources/BasaltCore/EditProgramValidator.swift | 4 +- Sources/BasaltCore/MathAnswerGrader.swift | 3 +- .../BasaltCore/SelfRewriteSessionCore.swift | 40 +++-- .../SelfRewrite/SelfRewriteSession.swift | 32 +++- .../BasaltServer/MCP/MCPServer+SelfEdit.swift | 56 +++++- Tests/BasaltTests/SelfRewritingP2Tests.swift | 6 + .../SelfRewritingP3HarnessTests.swift | 29 +++- .../SelfRewritingP3RunnerTests.swift | 164 +++++++++++++++++- 9 files changed, 305 insertions(+), 53 deletions(-) diff --git a/Sources/BasaltCloud/GeminiCloudEditor.swift b/Sources/BasaltCloud/GeminiCloudEditor.swift index 4dd274ed3..054686efb 100644 --- a/Sources/BasaltCloud/GeminiCloudEditor.swift +++ b/Sources/BasaltCloud/GeminiCloudEditor.swift @@ -74,19 +74,27 @@ public actor GeminiCloudEditor: EditSessionEditor { } let cleanEntries = try CloudPrivacyFence.sanitizeAndValidate(transcript, privateStrings: privateStrings) let messages = Self.buildMessages(entries: cleanEntries, budget: remainingBudget) - let body = try JSONEncoder().encode(OpenRouterClient.ChatRequest( + var chatRequest = OpenRouterClient.ChatRequest( model: config.model, messages: messages, temperature: 0.2, maxTokens: config.maxTokensPerTurn, stream: false - )) + ) + if config.baseURL.host?.lowercased().contains("openrouter") == true { + chatRequest.usage = .init(include: true) + } + let body = try JSONEncoder().encode(chatRequest) let response = try await performChat(body: body) let cost = Self.resolvedCostUSD(response.usage) - try recordSpend(cost: cost) + let remainingBefore = max(0, config.maxSessionUSD - sessionSpentUSD) + sessionSpentUSD += cost if let cloudGate, cost > 0 { await cloudGate.record(config.model, cost: cost) } + if sessionSpentUSD > config.maxSessionUSD + 1e-12 { + throw SelfRewriteBudgetError.cloudCostBudgetExceeded(requested: cost, remaining: remainingBefore) + } guard let content = response.choices.first?.message.content else { throw SelfRewriteSessionError.invalidEditorTurn("cloud model returned empty message content") } @@ -110,16 +118,6 @@ public actor GeminiCloudEditor: EditSessionEditor { } } - private func recordSpend(cost: Double) throws { - if sessionSpentUSD + cost > config.maxSessionUSD + 1e-12 { - throw SelfRewriteBudgetError.cloudCostBudgetExceeded( - requested: cost, - remaining: max(0, config.maxSessionUSD - sessionSpentUSD) - ) - } - sessionSpentUSD += cost - } - public func spentUSD() -> Double { sessionSpentUSD } private static func resolvedCostUSD(_ usage: OpenRouterClient.ChatResponse.Usage?) -> Double { diff --git a/Sources/BasaltCore/EditProgramValidator.swift b/Sources/BasaltCore/EditProgramValidator.swift index b9c2e8b4f..c7c88b25c 100644 --- a/Sources/BasaltCore/EditProgramValidator.swift +++ b/Sources/BasaltCore/EditProgramValidator.swift @@ -46,7 +46,9 @@ public enum EditValidationError: Error, Sendable, Equatable, CustomStringConvert case .invalidClipFactor(let tensor, let factor): return "clip factor on '\(tensor)' must be finite and positive, got \(factor)" case .invalidSlice(let tensor, let start, let count, let limit): - return "invalid slice [\(start)..<\(start + count)] on '\(tensor)'" + (limit.map { " of size \($0)" } ?? "") + let (end, overflow) = start.addingReportingOverflow(count) + let range = overflow ? "start=\(start), count=\(count)" : "[\(start)..<\(end)]" + return "invalid slice \(range) on '\(tensor)'" + (limit.map { " of size \($0)" } ?? "") case .invalidRowIndices(let tensor, let reason): return "invalid row indices on '\(tensor)': \(reason)" case .missingTensor(let key): diff --git a/Sources/BasaltCore/MathAnswerGrader.swift b/Sources/BasaltCore/MathAnswerGrader.swift index 870db9db8..0eae62587 100644 --- a/Sources/BasaltCore/MathAnswerGrader.swift +++ b/Sources/BasaltCore/MathAnswerGrader.swift @@ -369,10 +369,9 @@ extension MathAnswerGrader { static func lastLabeledAnswer(in text: String) -> String? { let markers = ["final answer:", "answer:", "the answer is"] - let lower = text.lowercased() var bestRange: Range? for marker in markers { - if let range = lower.range(of: marker, options: .backwards) { + if let range = text.range(of: marker, options: [.backwards, .caseInsensitive]) { if bestRange == nil || range.lowerBound > bestRange!.lowerBound { bestRange = range } diff --git a/Sources/BasaltCore/SelfRewriteSessionCore.swift b/Sources/BasaltCore/SelfRewriteSessionCore.swift index 29e78e380..b7b278925 100644 --- a/Sources/BasaltCore/SelfRewriteSessionCore.swift +++ b/Sources/BasaltCore/SelfRewriteSessionCore.swift @@ -127,7 +127,7 @@ public struct EditEditorTurn: Sendable, Codable, Equatable { if ch == "\\" { escaped = true } else if ch == "\"" { inString = false } continue } - if ch == "\"" { + if depth > 0, ch == "\"" { inString = true } else if ch == "{" { if depth == 0 { startIndex = idx } @@ -379,7 +379,7 @@ public enum CloudPrivacyFence { _ text: String, privateStrings: Set ) throws(SelfRewriteSessionError) { - for forbidden in forbiddenPathSubstrings where text.contains(forbidden) { + for forbidden in forbiddenPathSubstrings where text.range(of: forbidden, options: .caseInsensitive) != nil { throw .privacyFenceViolation("outbound text contains forbidden path or checkpoint token '\(forbidden)'") } for secret in privateStrings where secret.count >= 16 && text.contains(secret) { @@ -391,25 +391,25 @@ public enum CloudPrivacyFence { } private static func exceedsInlineFloatLimit(_ text: String) -> Bool { - var inBracket = false + var depth = 0 var numericRun = 0 var token = "" for ch in text { if ch == "[" { - inBracket = true - numericRun = 0 - token.removeAll(keepingCapacity: true) + if depth == 0 { + numericRun = 0 + token.removeAll(keepingCapacity: true) + } else if flushNumericToken(&token, run: &numericRun) { + return true + } + depth += 1 } else if ch == "]" { - if inBracket, isNumericToken(token) { numericRun += 1 } - if numericRun > maxInlineNumericTokens { return true } - inBracket = false - numericRun = 0 - token.removeAll(keepingCapacity: true) - } else if inBracket { + if depth > 0, flushNumericToken(&token, run: &numericRun) { return true } + depth = max(0, depth - 1) + if depth == 0 { numericRun = 0 } + } else if depth > 0 { if ch == "," || ch.isWhitespace { - if isNumericToken(token) { numericRun += 1 } - if numericRun > maxInlineNumericTokens { return true } - token.removeAll(keepingCapacity: true) + if flushNumericToken(&token, run: &numericRun) { return true } } else { token.append(ch) } @@ -418,8 +418,14 @@ public enum CloudPrivacyFence { return false } - private static func isNumericToken(_ token: String) -> Bool { + private static func flushNumericToken(_ token: inout String, run: inout Int) -> Bool { + defer { token.removeAll(keepingCapacity: true) } guard !token.isEmpty else { return false } - return Double(token) != nil + if Double(token) != nil { + run += 1 + return run > maxInlineNumericTokens + } + run = 0 + return false } } diff --git a/Sources/BasaltInference/SelfRewrite/SelfRewriteSession.swift b/Sources/BasaltInference/SelfRewrite/SelfRewriteSession.swift index 72b467d1d..cda59c6c8 100644 --- a/Sources/BasaltInference/SelfRewrite/SelfRewriteSession.swift +++ b/Sources/BasaltInference/SelfRewrite/SelfRewriteSession.swift @@ -151,13 +151,23 @@ public enum SelfRewriteSessionDriver { return try generateLocalTurn(state: state, turnIndex: turnCount) } - private static func isRecoverableActionError(_ error: any Error) -> Bool { - if error is WeightCopyError || error is EditValidationError || error is TensorRegistryError { return true } + static func isRecoverableActionError(_ error: any Error) -> Bool { + if let weightError = error as? WeightCopyError { + switch weightError { + case .invalidOperation, .sharedHandleMutationBlocked: return true + case .originalFingerprintMismatch, .copyReleased, .unsupportedModel, .budgetExceeded: return false + } + } + if error is EditValidationError || error is TensorRegistryError { return true } if let sessionError = error as? SelfRewriteSessionError, sessionError == .noCandidateEdit { return true } if case .invalidRequestStructure = error as? BasaltError { return true } return false } + private static func errorObservation(_ message: String) -> String { + (try? encodeJSON(["error": message])) ?? "{\"error\":\"action rejected\"}" + } + private static func runLoop( state: inout SessionRunState, copy: inout WeightCopy, @@ -177,7 +187,7 @@ public enum SelfRewriteSessionDriver { } catch let error as SelfRewriteSessionError { consecutiveErrors += 1 guard case .invalidEditorTurn(let detail) = error, consecutiveErrors < maxConsecutiveErrors else { throw error } - state.core.appendObservation("{\"error\":\"invalid JSON turn: \(detail). Reply ONLY with one valid EditEditorTurn JSON object.\"}") + state.core.appendObservation(errorObservation("invalid JSON turn: \(detail). Reply ONLY with one valid EditEditorTurn JSON object.")) continue } summary.turnCount += 1 @@ -199,9 +209,11 @@ public enum SelfRewriteSessionDriver { break } catch { consecutiveErrors += 1 - guard isRecoverableActionError(error), consecutiveErrors < maxConsecutiveErrors else { throw error } + guard !state.core.phase.isTerminal, isRecoverableActionError(error), consecutiveErrors < maxConsecutiveErrors else { + throw error + } let extra = error is TensorRegistryError ? " (registered keys: \(state.registry.keys))" : "" - state.core.appendObservation("{\"error\":\"action rejected: \(error)\(extra)\"}") + state.core.appendObservation(errorObservation("action rejected: \(error)\(extra)")) } } return summary @@ -309,11 +321,17 @@ extension SelfRewriteSessionDriver { state.core.appendObservation(try encodeJSON(summary)) return ActionOutcome() case .submit(let rationale): + guard epoch == state.core.epoch, case .running = state.core.phase else { + return ActionOutcome() + } + guard let candidate = state.core.mergedCandidateProgram() else { + throw SelfRewriteSessionError.noCandidateEdit + } + let operands = try state.registry.resolveOperands(for: candidate) + let adapter = try EditAdapter(program: candidate, tensors: operands) guard let merged = try state.core.completeSubmit(rationale: rationale, expectedEpoch: epoch) else { return ActionOutcome() } - let operands = try state.registry.resolveOperands(for: merged) - let adapter = try EditAdapter(program: merged, tensors: operands) if let dir = state.config.outputDirectory { try adapter.save(to: dir) } diff --git a/Sources/BasaltServer/MCP/MCPServer+SelfEdit.swift b/Sources/BasaltServer/MCP/MCPServer+SelfEdit.swift index 9eb4212f8..a983c164f 100644 --- a/Sources/BasaltServer/MCP/MCPServer+SelfEdit.swift +++ b/Sources/BasaltServer/MCP/MCPServer+SelfEdit.swift @@ -82,20 +82,25 @@ extension MCPServer { } } + private static let maxSelfEditDatasetBytes = 32 * 1024 * 1024 + func selfEditStart(_ args: [String: Any]?) async throws(MCPFailure) -> ToolResult { - guard (args?["experimentalSelfRewrite"] as? Bool) == true else { + guard (try MCPArguments.optionalBoolean("experimentalSelfRewrite", in: args)) == true else { throw .invalidParams("selfedit_start requires experimentalSelfRewrite=true") } let practicePath = try MCPArguments.required("practicePath", MCPArguments.string("practicePath", in: args)) let editor = (try MCPArguments.string("editor", in: args)) ?? "local" - let allowCloud = (args?["allowCloudEditor"] as? Bool) ?? false + let allowCloud = (try MCPArguments.optionalBoolean("allowCloudEditor", in: args)) ?? false let taskRaw = (try MCPArguments.string("task", in: args)) ?? "improve" let scopeRaw = (try MCPArguments.string("scope", in: args)) ?? EditTargetScope.textBackboneOnly.rawValue let decontamPath = try MCPArguments.string("decontaminatePath", in: args) let practiceCount = try MCPArguments.integer("practiceCount", in: args, 1 ... 100_000) let maxPasses = (try MCPArguments.integer("maxForwardPasses", in: args, 1 ... 10_000)) ?? 20 let maxTools = (try MCPArguments.integer("maxToolCalls", in: args, 1 ... 100_000)) ?? 200 - let maxCloudUSD = (args?["maxCloudUSD"] as? Double) ?? 2.0 + let maxCloudUSD = (try MCPArguments.double("maxCloudUSD", in: args)) ?? 2.0 + guard maxCloudUSD.isFinite, maxCloudUSD >= 0 else { + throw .invalidParams("maxCloudUSD must be a finite non-negative number") + } try Self.validateSelfEditEditor(editor, allowCloud: allowCloud) guard EditTargetScope(rawValue: scopeRaw) != nil else { @@ -103,9 +108,16 @@ extension MCPServer { } let taskMode = try Self.parseSelfEditTask(taskRaw) _ = try Self.validateSelfEditBudget(passes: maxPasses, tools: maxTools, editor: editor, maxCloudUSD: maxCloudUSD) + let allowedRoots = harnessRoots + [selfEditDirectory] + let practiceURL = try Self.validatedSelfEditFile(practicePath, label: "practicePath", allowedRoots: allowedRoots) + let decontamURL: URL? = if let decontamPath { + try Self.validatedSelfEditFile(decontamPath, label: "decontaminatePath", allowedRoots: allowedRoots) + } else { + nil + } let splitInfo = try Self.loadSelfEditSplit( - practicePath: practicePath, - decontamPath: decontamPath, + practiceURL: practiceURL, + decontamURL: decontamURL, practiceCount: practiceCount ) let sessionId = "selfedit-\(UUID().uuidString.prefix(8))" @@ -178,16 +190,42 @@ extension MCPServer { throw .invalidParams(error.description) } } +} + +extension MCPServer { + static func validatedSelfEditFile( + _ rawPath: String, + label: String, + allowedRoots: [URL] + ) throws(MCPFailure) -> URL { + let resolved = URL(fileURLWithPath: rawPath).resolvingSymlinksInPath().standardizedFileURL + let allowed = allowedRoots.map { $0.resolvingSymlinksInPath().standardizedFileURL.path } + let insideAllowed = allowed.contains { root in + let prefix = root.hasSuffix("/") ? root : root + "/" + return resolved.path.hasPrefix(prefix) + } + guard insideAllowed else { + throw .invalidParams("\(label) must reside inside an allowed root") + } + guard let values = try? resolved.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]), + values.isRegularFile == true else { + throw .invalidParams("\(label) must refer to a readable regular file") + } + if let bytes = values.fileSize, bytes > maxSelfEditDatasetBytes { + throw .invalidParams("\(label) exceeds \(maxSelfEditDatasetBytes) byte limit") + } + return resolved + } private static func loadSelfEditSplit( - practicePath: String, - decontamPath: String?, + practiceURL: URL, + decontamURL: URL?, practiceCount: Int? ) throws(MCPFailure) -> (split: PairedDatasetSplit, removedDuplicates: Int) { do { return try SelfRewriteDatasetLoader.buildSplit( - practiceURL: URL(fileURLWithPath: practicePath), - decontaminateURL: decontamPath.map { URL(fileURLWithPath: $0) }, + practiceURL: practiceURL, + decontaminateURL: decontamURL, practiceCount: practiceCount ) } catch { diff --git a/Tests/BasaltTests/SelfRewritingP2Tests.swift b/Tests/BasaltTests/SelfRewritingP2Tests.swift index 75bcb3b5d..23a711fb8 100644 --- a/Tests/BasaltTests/SelfRewritingP2Tests.swift +++ b/Tests/BasaltTests/SelfRewritingP2Tests.swift @@ -192,6 +192,12 @@ extension SelfRewritingP2Tests { await #expect(throws: SelfRewriteBudgetError.self) { _ = try await editor.nextTurn(transcript: [], remainingBudget: budget) } + #expect(abs(await editor.spentUSD() - 0.30) < 1e-6) + #expect(abs(await gate.spent("gemini-2.5-pro") - 0.30) < 1e-6) + await #expect(throws: SelfRewriteBudgetError.self) { + _ = try await editor.nextTurn(transcript: [], remainingBudget: budget) + } + #expect(StubURLProtocol.requests(for: host).count == 2) } @Test("Scripted editor drives SelfRewriteSessionDriver through full toolset and submit on tiny Gemma 4 MoE") diff --git a/Tests/BasaltTests/SelfRewritingP3HarnessTests.swift b/Tests/BasaltTests/SelfRewritingP3HarnessTests.swift index 89123eabb..030b847e3 100644 --- a/Tests/BasaltTests/SelfRewritingP3HarnessTests.swift +++ b/Tests/BasaltTests/SelfRewritingP3HarnessTests.swift @@ -100,11 +100,13 @@ extension SelfRewritingP3HarnessTests { extension SelfRewritingP3HarnessTests { @Test("MCP selfedit_start and selfedit_status require --research-tools, enforce experimental & cloud opt-ins, and report persisted transcripts") func mcpSelfEditToolsGatingAndStatus() async throws { - let practiceURL = try Self.writeJSONL(Self.sampleDatasetLines(), name: "mcp_practice.jsonl") let sessionDir = FileManager.default.temporaryDirectory.appending(path: "selfedit-mcp-dir-\(UUID().uuidString)") try FileManager.default.createDirectory(at: sessionDir, withIntermediateDirectories: true) + let practiceURL = sessionDir.appending(path: "mcp_practice.jsonl") + try Data((Self.sampleDatasetLines().joined(separator: "\n") + "\n").utf8).write(to: practiceURL) + let outsideURL = try Self.writeJSONL(Self.sampleDatasetLines(), name: "outside.jsonl") defer { - try? FileManager.default.removeItem(at: practiceURL.deletingLastPathComponent()) + try? FileManager.default.removeItem(at: outsideURL.deletingLastPathComponent()) try? FileManager.default.removeItem(at: sessionDir) } let persisted = sessionDir.appending(path: "prior-session.jsonl") @@ -122,19 +124,40 @@ extension SelfRewritingP3HarnessTests { .withResearchTools(true) .withSelfEditDirectory(sessionDir) + let subdirURL = sessionDir.appending(path: "not_a_file") + try FileManager.default.createDirectory(at: subdirURL, withIntermediateDirectories: true) + let hugeURL = sessionDir.appending(path: "huge.jsonl") + FileManager.default.createFile(atPath: hugeURL.path, contents: Data()) + let handle = try FileHandle(forWritingTo: hugeURL) + try handle.truncate(atOffset: 33 * 1024 * 1024) + try handle.close() + await server.dispatch(#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#) await server.dispatch(#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":false,"practicePath":"\#(practiceURL.path)"}}}"#) await server.dispatch(#"{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(practiceURL.path)","editor":"cloud:gemini/gemini-2.5-pro","allowCloudEditor":false}}}"#) await server.dispatch(#"{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(practiceURL.path)","practiceCount":2,"task":"repair:\#(Self.textOProj).weight:0,1:5.0"}}}"#) await server.dispatch(#"{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"selfedit_status","arguments":{}}}"#) + await server.dispatch(#"{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(practiceURL.path)","editor":"cloud:gemini/gemini-2.5-pro","allowCloudEditor":true,"maxCloudUSD":-1}}}"#) + await server.dispatch(#"{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(practiceURL.path)","editor":"cloud:gemini/gemini-2.5-pro","allowCloudEditor":1}}}"#) + await server.dispatch(#"{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(outsideURL.path)"}}}"#) + await server.dispatch(#"{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(subdirURL.path)"}}}"#) + await server.dispatch(#"{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(hugeURL.path)"}}}"#) + await server.dispatch(#"{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"selfedit_start","arguments":{"experimentalSelfRewrite":true,"practicePath":"\#(practiceURL.path)","editor":"cloud:gemini/gemini-2.5-pro","allowCloudEditor":true,"maxCloudUSD":0}}}"#) let lines = capturer.lines - #expect(lines.count == 5) + #expect(lines.count == 11) #expect(lines[0].contains("selfedit_start") && lines[0].contains("selfedit_status")) #expect(lines[1].contains("-32602") && lines[1].contains("experimentalSelfRewrite=true")) #expect(lines[2].contains("-32602") && lines[2].contains("--allow-cloud-editor")) #expect(lines[3].contains("\"result\"") && lines[3].contains("practiceCount") && !lines[3].contains("\"error\"")) #expect(lines[4].contains("\"result\"") && lines[4].contains("prior-session") && lines[4].contains("selfedit-")) + #expect(lines[5].contains("-32602") && lines[5].contains("non-negative")) + #expect(lines[6].contains("-32602")) + #expect(lines[7].contains("-32602") && lines[7].contains("allowed root")) + #expect(lines[8].contains("-32602") && lines[8].contains("regular file")) + #expect(lines[9].contains("-32602") && lines[9].contains("exceeds")) + #expect(lines[10].contains("\"result\"") && !lines[10].contains("\"error\"")) + #expect(try MCPArguments.double("maxCloudUSD", in: ["maxCloudUSD": 0]) == 0.0) } @Test("SelfEditCommand.prepareHarness wires --practice, --decontaminate, --task repair, and --transcript cleanly") diff --git a/Tests/BasaltTests/SelfRewritingP3RunnerTests.swift b/Tests/BasaltTests/SelfRewritingP3RunnerTests.swift index b17d8b680..251a6ddfd 100644 --- a/Tests/BasaltTests/SelfRewritingP3RunnerTests.swift +++ b/Tests/BasaltTests/SelfRewritingP3RunnerTests.swift @@ -286,7 +286,7 @@ extension SelfRewritingP3RunnerTests { #expect(result.phase == .withdrawn(rationale: "recovered after errors") && result.turnCount == 5) } - @Test("WeightCopy.makeSync clones wrapped MLXLLM.Qwen35Model preserving model_type and sharing weights without copying (#676)") + @Test("WeightCopy.makeSync clones wrapped MLXLLM.Qwen35Model and Qwen35MoEModel preserving model_type and sharing weights (#676)") func weightCopyClonesWrappedQwen35Model() throws { let wrappedJSON = "{\"model_type\":\"qwen3_5\",\"text_config\":\(TinyModel.Family.qwen35.config)}" let cfg = try JSONDecoder().decode(MLXLLM::Qwen35Configuration.self, from: Data(wrappedJSON.utf8)) @@ -294,5 +294,167 @@ extension SelfRewritingP3RunnerTests { let copy = try WeightCopy.makeSync(from: original) #expect(copy.accounting.totalExtraBytes == 0) try copy.release(verifying: original) + + let moeJSON = "{\"model_type\":\"qwen3_5_moe\",\"text_config\":\(TinyModel.Family.qwen35Moe.config)}" + let moeCfg = try JSONDecoder().decode(MLXLLM::Qwen35Configuration.self, from: Data(moeJSON.utf8)) + let moeOriginal = MLXLLM::Qwen35MoEModel(moeCfg) + let moeCopy = try WeightCopy.makeSync(from: moeOriginal) + #expect(moeCopy.accounting.totalExtraBytes == 0) + try moeCopy.release(verifying: moeOriginal) + } +} + +extension SelfRewritingP3RunnerTests { + @Test("EditEditorTurn.parseJSON handles odd quotes in prose before the JSON payload (A-C2)") + func parseJSONHandlesOddProseQuote() throws { + let oddQuote = "Don't use \"odd quotes before {\"rationale\":\"ok\",\"action\":{\"describeModel\":{}}}" + #expect(try EditEditorTurn.parseJSON(from: oddQuote).action == .describeModel) + } + + @Test("EditValidationError.invalidSlice formats without Int overflow on Int.max start (A-C3)") + func invalidSliceDescriptionAvoidsOverflow() { + let overflowDesc = EditValidationError.invalidSlice(tensor: "w", start: Int.max, count: 1, limit: 16).description + #expect(overflowDesc.contains("start=\(Int.max)") && overflowDesc.contains("count=1")) + } + + @Test("MathAnswerGrader preserves UTF-16 alignment when text contains Turkish dotted I (#797)") + func mathAnswerGraderHandlesTurkishDottedI() { + #expect(MathAnswerGrader().extractAnswer(from: "İİİ Answer: 42") == "42") + } + + @Test("SelfRewriteSessionDriver classifies WeightCopyError recoverability exhaustively (#797)") + func isRecoverableActionErrorClassifiesWeightCopyErrors() { + #expect(!SelfRewriteSessionDriver.isRecoverableActionError(WeightCopyError.originalFingerprintMismatch([]))) + #expect(!SelfRewriteSessionDriver.isRecoverableActionError(WeightCopyError.copyReleased)) + #expect(!SelfRewriteSessionDriver.isRecoverableActionError(WeightCopyError.unsupportedModel("x"))) + #expect(!SelfRewriteSessionDriver.isRecoverableActionError(WeightCopyError.budgetExceeded(required: 10, budget: 5))) + #expect(SelfRewriteSessionDriver.isRecoverableActionError(WeightCopyError.invalidOperation("bad"))) + #expect(SelfRewriteSessionDriver.isRecoverableActionError(WeightCopyError.sharedHandleMutationBlocked(tensor: "w"))) + } + + @Test("CloudPrivacyFence blocks nested numeric arrays and case-variant paths while allowing a 150-layer EditModelSummary (A-C7)") + func privacyFenceNestedArraysAndLargeDescribeModel() throws { + let nestedBypass = "[[0], " + (1 ... 80).map(String.init).joined(separator: ", ") + "]" + let twoRows = "[" + "[" + (1 ... 40).map(String.init).joined(separator: ", ") + "], [" + (41 ... 80).map(String.init).joined(separator: ", ") + "]]" + for bad in [nestedBypass, twoRows, "path /users/alice/m", "file WEIGHTS.SAFETENSORS"] { + let entry = [EditSessionTranscriptEntry(turnIndex: 0, role: "tool", content: bad)] + #expect(throws: SelfRewriteSessionError.self) { + _ = try CloudPrivacyFence.sanitizeAndValidate(entry) + } + } + + let layers = (0 ..< 150).map { idx in + EditEditableLayerSummary(path: "language_model.model.layers.\(idx).self_attn.o_proj", shape: [2048, 512], format: "quantized4", blastRadiusWarning: nil) + } + let summary = EditModelSummary(modelType: "gemma4", topology: nil, editableLayers: layers, totalParameterCount: 26_000_000_000) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let summaryJSON = String(decoding: try encoder.encode(summary), as: UTF8.self) + let summaryEntry = [EditSessionTranscriptEntry(turnIndex: 0, role: "tool", content: summaryJSON)] + let sanitized = try CloudPrivacyFence.sanitizeAndValidate(summaryEntry) + #expect(sanitized.count == 1 && sanitized[0].content.contains("layers.149")) + } +} + +extension SelfRewritingP3RunnerTests { + @Test("Three consecutive invalid JSON turns abort and emit valid JSON error observations escaping quotes (#797)") + func threeInvalidJSONTurnsAbortWithValidJSONObservation() async throws { + actor ThreeFailJSONEditor: EditSessionEditor { + let editorLabel = "bad-json" + var calls = 0 + var seenTranscript: [EditSessionTranscriptEntry] = [] + func nextTurn(transcript: [EditSessionTranscriptEntry], remainingBudget: SelfRewriteBudget) async throws -> EditEditorTurn { + seenTranscript = transcript + calls += 1 + guard calls <= 5 else { return EditEditorTurn(rationale: "stop", action: .withdraw(rationale: "cap regressed")) } + throw SelfRewriteSessionError.invalidEditorTurn("has \"quoted\" text") + } + } + let model = try TinyModel.make(.gemma4) + let config = SelfRewriteSessionConfig(sessionId: "sess-cap-json", budget: try SelfRewriteBudget(maxForwardPasses: 6, maxToolCalls: 12)) + let editor = ThreeFailJSONEditor() + await #expect(throws: SelfRewriteSessionError.self) { + _ = try await SelfRewriteSessionDriver.run( + config: config, split: Self.makeSplit(), evalSpec: Self.makeSpec(), editor: editor, original: model + ) + } + #expect(await editor.calls == 3) + let transcript = await editor.seenTranscript + let errors = transcript.filter { $0.role == "tool" && $0.content.contains("quoted") } + #expect(errors.count == 2) + for obs in errors { + let parsed = try JSONSerialization.jsonObject(with: Data(obs.content.utf8)) as? [String: String] + #expect(parsed?["error"]?.contains("has \"quoted\" text") == true) + } + } + + @Test("Three consecutive rejected tool actions abort and emit valid JSON error observations escaping quotes (#797)") + func threeRejectedActionsAbortWithValidJSONObservation() async throws { + actor ThreeFailActionEditor: EditSessionEditor { + let editorLabel = "bad-action" + var calls = 0 + var seenTranscript: [EditSessionTranscriptEntry] = [] + func nextTurn(transcript: [EditSessionTranscriptEntry], remainingBudget: SelfRewriteBudget) async throws -> EditEditorTurn { + seenTranscript = transcript + calls += 1 + guard calls <= 5 else { return EditEditorTurn(rationale: "stop", action: .withdraw(rationale: "cap regressed")) } + return EditEditorTurn(rationale: "bad", action: .inspectTensor(name: "missing\"quote.weight")) + } + } + let model = try TinyModel.make(.gemma4) + let config = SelfRewriteSessionConfig(sessionId: "sess-cap-action", budget: try SelfRewriteBudget(maxForwardPasses: 6, maxToolCalls: 12)) + let editor = ThreeFailActionEditor() + await #expect(throws: BasaltError.self) { + _ = try await SelfRewriteSessionDriver.run( + config: config, split: Self.makeSplit(), evalSpec: Self.makeSpec(), editor: editor, original: model + ) + } + #expect(await editor.calls == 3) + let transcript = await editor.seenTranscript + let errors = transcript.filter { $0.role == "tool" && $0.content.contains("action rejected") } + #expect(errors.count == 2) + for obs in errors { + let parsed = try JSONSerialization.jsonObject(with: Data(obs.content.utf8)) as? [String: String] + #expect(parsed?["error"]?.contains("quote.weight") == true && parsed?["error"]?.contains("\"") == true) + } + } + + @Test("Submitting a merged program exceeding 64 ops does not falsely mark session .submitted and returns a recoverable JSON error observation (#797)") + func submitOver64MergedOpsStaysRunning() async throws { + let op = EditOp.clip(tensor: Self.textOProj + ".weight", factor: 1.0) + let fortyOps = EditProgram(ops: Array(repeating: op, count: 40)) + actor OverLimitSubmitEditor: EditSessionEditor { + let editorLabel = "overlimit" + let batch: EditProgram + var step = 0 + var seenTranscript: [EditSessionTranscriptEntry] = [] + init(batch: EditProgram) { self.batch = batch } + func nextTurn(transcript: [EditSessionTranscriptEntry], remainingBudget: SelfRewriteBudget) async throws -> EditEditorTurn { + seenTranscript = transcript + defer { step += 1 } + switch step { + case 0, 1: return EditEditorTurn(rationale: "apply 40", action: .applyEdit(batch)) + case 2: return EditEditorTurn(rationale: "submit 80", action: .submit(rationale: "too many")) + default: return EditEditorTurn(rationale: "give up", action: .withdraw(rationale: "validated before submit")) + } + } + } + let model = try TinyModel.make(.gemma4) + let config = SelfRewriteSessionConfig(sessionId: "sess-overlimit", budget: try SelfRewriteBudget(maxForwardPasses: 6, maxToolCalls: 12)) + let editor = OverLimitSubmitEditor(batch: fortyOps) + let result = try await SelfRewriteSessionDriver.run( + config: config, + split: Self.makeSplit(), + evalSpec: Self.makeSpec(), + editor: editor, + original: model + ) + #expect(result.phase == .withdrawn(rationale: "validated before submit")) + #expect(result.submittedProgram == nil && result.savedAdapterURL == nil) + let transcript = await editor.seenTranscript + let toolErrors = transcript.filter { $0.role == "tool" && $0.content.contains("action rejected") } + #expect(toolErrors.count == 1) + let parsed = try JSONSerialization.jsonObject(with: Data(toolErrors[0].content.utf8)) as? [String: String] + #expect(parsed?["error"] != nil) } } From 0d6042ec46cad8b1393613937ed729514bef937c Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:08:01 +0100 Subject: [PATCH 2/6] fix(server): validate /generate maxTokens, gate admin routes from virtual keys, fix hf: adapter & 413/SSE/auth-rate-limit (A-S1, A-S2, A-S3, A-S8, A-S9, A-S12) --- Sources/BasaltCloud/ModelRouterCore.swift | 12 +- .../BasaltServer/MCP/MCPToolArguments.swift | 8 +- .../REST/GenerateController.swift | 62 +++-- .../REST/Middleware/APIKeyAuthenticator.swift | 26 +- .../JSONNestingLimitMiddleware.swift | 26 +- .../REST/Middleware/RateLimitMiddleware.swift | 2 +- .../Middleware/RequestGuardMiddleware.swift | 3 +- .../REST/ModelsController+Convert.swift | 2 +- .../BasaltServer/REST/OpenAIController.swift | 4 +- Sources/BasaltServer/REST/RESTServer.swift | 11 +- Tests/BasaltTests/PEFTFusedExportTests.swift | 2 +- Tests/BasaltTests/RESTServerTests.swift | 2 +- .../ServerSecurityDefectRegressionTests.swift | 260 ++++++++++++++++++ 13 files changed, 371 insertions(+), 49 deletions(-) create mode 100644 Tests/BasaltTests/ServerSecurityDefectRegressionTests.swift diff --git a/Sources/BasaltCloud/ModelRouterCore.swift b/Sources/BasaltCloud/ModelRouterCore.swift index ced82afba..dc6e80436 100644 --- a/Sources/BasaltCloud/ModelRouterCore.swift +++ b/Sources/BasaltCloud/ModelRouterCore.swift @@ -143,18 +143,20 @@ struct ModelCatalog: Sendable { } func estimateCost(model: String, promptTokens: Int, completionTokens: Int) -> Double { + let prompt = Double(max(0, promptTokens)) + let completion = Double(max(0, completionTokens)) let mappedId = Self.cloudModels(for: model).first ?? model if let price = pricingByModel[mappedId] { - let inputCost = Double(promptTokens) / 1_000_000.0 * price.input - let outputCost = Double(completionTokens) / 1_000_000.0 * price.output + let inputCost = prompt / 1_000_000.0 * price.input + let outputCost = completion / 1_000_000.0 * price.output return inputCost + outputCost } if let cost = models[mappedId]?.costPer1MTokens { - return (Double(promptTokens + completionTokens) / 1_000_000.0) * cost + return ((prompt + completion) / 1_000_000.0) * cost } guard let price = Self.fallbackPricing[mappedId] else { return 0.0 } - let inputCost = Double(promptTokens) / 1_000_000.0 * price.input - let outputCost = Double(completionTokens) / 1_000_000.0 * price.output + let inputCost = prompt / 1_000_000.0 * price.input + let outputCost = completion / 1_000_000.0 * price.output return inputCost + outputCost } diff --git a/Sources/BasaltServer/MCP/MCPToolArguments.swift b/Sources/BasaltServer/MCP/MCPToolArguments.swift index 9fab9551f..934902cc0 100644 --- a/Sources/BasaltServer/MCP/MCPToolArguments.swift +++ b/Sources/BasaltServer/MCP/MCPToolArguments.swift @@ -85,9 +85,15 @@ enum MCPArguments { let (regex, grammar) = (try MCPArguments.string("regex", in: args), try MCPArguments.string("grammar", in: args)) guard regex == nil || grammar == nil else { throw .invalidParams("give regex or grammar, not both") } request.responseFormat = regex.map(ResponseFormat.regex) ?? grammar.map(ResponseFormat.grammar) - return request.withSpeculativeLookup(speculativeLookup) + let built = request.withSpeculativeLookup(speculativeLookup) .withGrammarJumpForward(grammarJumpForward) .withOrigin(RequestOrigin(source: "mcp", endpoint: "tools/call generate", stream: false)) + do { + _ = try built.validated() + } catch { + throw MCPFailure(error) + } + return built } static func optionalBoolean(_ key: String, in args: [String: Any]?) throws(MCPFailure) -> Bool? { diff --git a/Sources/BasaltServer/REST/GenerateController.swift b/Sources/BasaltServer/REST/GenerateController.swift index 05d5c5006..3c9c11671 100644 --- a/Sources/BasaltServer/REST/GenerateController.swift +++ b/Sources/BasaltServer/REST/GenerateController.swift @@ -17,11 +17,14 @@ struct GenerateController: Sendable { let buffer = try await request.body.collect(upTo: 1024 * 1024) let data = Data(buffer.readableBytesView) dto = PromptCacheKey.scoped(try JSONDecoder().decode(GenerationRequest.self, from: data), headers: request.headers).routed(by: request.headers).withOrigin(RequestOrigin(source: "generate", endpoint: "/api/v1/generate", stream: false)) + } catch let httpError as any HTTPResponseError where httpError.status == .contentTooLarge { + return ProviderErrorResponse.response(status: .contentTooLarge, message: "Request body too large.", path: "/api/v1/generate") } catch { return errorResponse(status: .badRequest, message: "Invalid JSON: \(error.localizedDescription)", code: 400) } do { + _ = try dto.validated() let result = try await orchestrator.generate(request: dto) return try jsonResponse(status: .ok, body: result) } catch { @@ -29,23 +32,34 @@ struct GenerateController: Sendable { } } - // MARK: — POST /api/v1/generate/stream - @Sendable func generateStream(request: Request, context: BasicRequestContext) async throws -> Response { logger.trace("Handling POST /api/v1/generate/stream") - + let dto: GenerationRequest do { let buffer = try await request.body.collect(upTo: 1024 * 1024) let data = Data(buffer.readableBytesView) dto = PromptCacheKey.scoped(try JSONDecoder().decode(GenerationRequest.self, from: data), headers: request.headers).routed(by: request.headers).withOrigin(RequestOrigin(source: "generate", endpoint: "/api/v1/generate/stream", stream: true)) + } catch let httpError as any HTTPResponseError where httpError.status == .contentTooLarge { + return ProviderErrorResponse.response(status: .contentTooLarge, message: "Request body too large.", path: "/api/v1/generate/stream") } catch { return errorResponse(status: .badRequest, message: "Invalid JSON: \(error.localizedDescription)", code: 400) } + do { + _ = try dto.validated() + } catch { + return ProviderErrorResponse.response(for: error, path: "/api/v1/generate/stream") + } if let refusal = await orchestrator.admissionRefusal(for: dto) { return ProviderErrorResponse.response(for: refusal, path: "/api/v1/generate/stream") } + let stream: AsyncStream + do { + stream = try await orchestrator.generateStream(request: dto) + } catch { + return ProviderErrorResponse.response(for: error, path: "/api/v1/generate/stream") + } let response = Response( status: .ok, @@ -55,49 +69,43 @@ struct GenerateController: Sendable { .connection: "keep-alive" ] ) - let body = ResponseBody(asyncSequence: sseStream(dto: dto)) + let body = ResponseBody(asyncSequence: sseStream(stream: stream)) return Response(status: response.status, headers: response.headers, body: body) } - private func sseStream(dto: GenerationRequest) -> AsyncStream { + private func sseStream(stream: AsyncStream) -> AsyncStream { AsyncStream { continuation in let task = Task { - do { - let stream = try await orchestrator.generateStream(request: dto) - for await chunk in stream { - let event = formatSSE(chunk: chunk) - var buffer = ByteBuffer() - buffer.writeString(event) - continuation.yield(buffer) + var failed = false + for await chunk in stream { + if case .metadata(let meta) = chunk, meta.finishReason == .error { + failed = true + var errorBuffer = ByteBuffer() + errorBuffer.writeString("event: error\ndata: {\"error\":\"generation failed\"}\n\n") + continuation.yield(errorBuffer) + continue } + let event = formatSSE(chunk: chunk) + var buffer = ByteBuffer() + buffer.writeString(event) + continuation.yield(buffer) + } + if !failed && !Task.isCancelled { var doneBuffer = ByteBuffer() doneBuffer.writeString("data: [DONE]\n\n") continuation.yield(doneBuffer) - continuation.finish() - } catch { - let errPayload: [String: Any] = ["error": ModelsController.publicMessage(for: error)] - if let json = try? JSONSerialization.data(withJSONObject: errPayload), - let str = String(data: json, encoding: .utf8) { - var errorBuffer = ByteBuffer() - errorBuffer.writeString("event: error\n") - errorBuffer.writeString("data: \(str)\n\n") - continuation.yield(errorBuffer) - } - continuation.finish() } + continuation.finish() } continuation.onTermination = { _ in task.cancel() } } } - + private func formatSSE(chunk: StreamChunk) -> String { - // Convert chunk to JSON guard let data = try? JSONEncoder().encode(chunk), let json = String(data: data, encoding: .utf8) else { return "data: {\"error\": \"encoding failed\"}\n\n" } - - // SSE format: "data: \n\n" return "data: \(json)\n\n" } diff --git a/Sources/BasaltServer/REST/Middleware/APIKeyAuthenticator.swift b/Sources/BasaltServer/REST/Middleware/APIKeyAuthenticator.swift index 54ca2a312..380c18d44 100644 --- a/Sources/BasaltServer/REST/Middleware/APIKeyAuthenticator.swift +++ b/Sources/BasaltServer/REST/Middleware/APIKeyAuthenticator.swift @@ -23,6 +23,21 @@ public struct APIKeyAuthenticator: RouterMiddleware { self.virtualKeyDigests = virtualKeys.map { (SHA256.hash(data: Data($0.key.utf8)), $0.id) } } + static func normalizedPath(_ path: String) -> String { + let joined = path.split(separator: "/").joined(separator: "/") + return joined.isEmpty ? "/" : "/\(joined)" + } + + static func isAdminRequest(_ request: Request) -> Bool { + let path = normalizedPath(request.uri.path) + if request.method == .delete && (path == "/v1/models" || path.hasPrefix("/v1/models/")) { return true } + if path == "/v1/models/load" || path == "/v1/models/download" || path == "/v1/models/publish" { return true } + if path.hasPrefix("/v1/models/convert") || path.hasPrefix("/api/v1/models/convert") { return true } + if path == "/v1/compose" || path.hasPrefix("/v1/compose/") { return true } + if path == "/v1/mcp/approvals" || path.hasPrefix("/v1/mcp/approvals/") { return true } + return false + } + static func request(_ request: Request, budgetKey: String?, rateKey: String? = nil) -> Request { guard budgetKey != nil || rateKey != nil || request.headers[budgetKeyHeader] != nil || request.headers[rateKeyHeader] != nil else { return request @@ -54,7 +69,7 @@ public struct APIKeyAuthenticator: RouterMiddleware { next: (Request, Context) async throws -> Response ) async throws -> Response { let request = Self.request(request, budgetKey: nil) - if Self.publicPaths.contains(request.uri.path) { + if Self.publicPaths.contains(Self.normalizedPath(request.uri.path)) { return try await next(request, context) } @@ -73,7 +88,14 @@ public struct APIKeyAuthenticator: RouterMiddleware { return try await next(Self.request(request, budgetKey: nil, rateKey: "master"), context) } if let id = virtualKeyId(for: candidate) { - return try await next(Self.request(request, budgetKey: id, rateKey: id), context) + if Self.isAdminRequest(request) { + return ProviderErrorResponse.response( + status: .forbidden, + message: "Forbidden: virtual keys cannot access admin or control routes.", + path: request.uri.path + ) + } + return try await next(Self.request(request, budgetKey: id, rateKey: "vk:\(id)"), context) } } diff --git a/Sources/BasaltServer/REST/Middleware/JSONNestingLimitMiddleware.swift b/Sources/BasaltServer/REST/Middleware/JSONNestingLimitMiddleware.swift index 54d2e46f9..d25981809 100644 --- a/Sources/BasaltServer/REST/Middleware/JSONNestingLimitMiddleware.swift +++ b/Sources/BasaltServer/REST/Middleware/JSONNestingLimitMiddleware.swift @@ -17,16 +17,17 @@ public struct JSONNestingLimitMiddleware: RouterMiddlew context: Context, next: (Request, Context) async throws -> Response ) async throws -> Response { + let normalized = APIKeyAuthenticator.normalizedPath(request.uri.path) guard request.method == .post || request.method == .put, - request.uri.path != TranscriptionsController.path, + normalized != TranscriptionsController.path, !RequestGuardMiddleware.has(.multipartForm, request) else { return try await next(request, context) } var request = request let buffer: ByteBuffer do { - buffer = try await request.collectBody(upTo: Self.bodyLimit(for: request.uri.path)) - } catch let error as HTTPError where error.status == .contentTooLarge { + buffer = try await request.collectBody(upTo: Self.bodyLimit(for: normalized)) + } catch let error as any HTTPResponseError where error.status == .contentTooLarge { return ProviderErrorResponse.response(status: .contentTooLarge, message: "Request body too large.", path: request.uri.path) } let bytes = buffer.readableBytesSpan @@ -41,10 +42,23 @@ public struct JSONNestingLimitMiddleware: RouterMiddlew ["/v1/chat/completions", "/api/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/ocr"] } + private static var smallControlPaths: Set { + ["/v1/models/download", "/v1/models/publish"] + } + + private static var oneMBPaths: Set { + ["/api/v1/generate", "/api/v1/generate/stream", "/v1/models/load"] + } + static func bodyLimit(for path: String) -> Int { - if path.hasPrefix("/v1/images/") { return ImagesController.bodyLimit } - if path.hasPrefix("/v1/pipeline") || path == "/v1/systemone" { return PipelineController.bodyLimit } - if mediaBodyPaths.contains(path) { return Self.bodyLimit } + let normalized = APIKeyAuthenticator.normalizedPath(path) + if normalized.hasPrefix("/v1/images/") { return ImagesController.bodyLimit } + if normalized.hasPrefix("/v1/pipeline") || normalized == "/v1/systemone" { return PipelineController.bodyLimit } + if mediaBodyPaths.contains(normalized) { return Self.bodyLimit } + if smallControlPaths.contains(normalized) || normalized.hasPrefix("/v1/mcp/approvals") { return ModelsHubController.bodyLimit } + if normalized == "/v1/models/convert" || normalized == "/api/v1/models/convert" { return ModelsConvertController.bodyLimit } + if normalized == "/v1/compose/apply" || normalized == "/v1/compose/diff" { return ComposeController.bodyLimit } + if oneMBPaths.contains(normalized) { return 1024 * 1024 } return 4 * 1024 * 1024 } diff --git a/Sources/BasaltServer/REST/Middleware/RateLimitMiddleware.swift b/Sources/BasaltServer/REST/Middleware/RateLimitMiddleware.swift index 2bcb61b6a..f2c70933c 100644 --- a/Sources/BasaltServer/REST/Middleware/RateLimitMiddleware.swift +++ b/Sources/BasaltServer/REST/Middleware/RateLimitMiddleware.swift @@ -130,7 +130,7 @@ public struct RateLimitMiddleware: RouterMiddleware { context: Context, next: (Request, Context) async throws -> Response ) async throws -> Response { - if APIKeyAuthenticator.publicPaths.contains(request.uri.path) { + if APIKeyAuthenticator.publicPaths.contains(APIKeyAuthenticator.normalizedPath(request.uri.path)) { return try await next(request, context) } let now = clock() diff --git a/Sources/BasaltServer/REST/Middleware/RequestGuardMiddleware.swift b/Sources/BasaltServer/REST/Middleware/RequestGuardMiddleware.swift index 9437e3169..03a29ef9b 100644 --- a/Sources/BasaltServer/REST/Middleware/RequestGuardMiddleware.swift +++ b/Sources/BasaltServer/REST/Middleware/RequestGuardMiddleware.swift @@ -81,7 +81,8 @@ public struct RequestGuardMiddleware: RouterMiddleware { if let mediaFailure = Self.validatePostMediaType(request) { return mediaFailure } - return try await next(request, context) + let sanitized = APIKeyAuthenticator.request(request, budgetKey: nil, rateKey: nil) + return try await next(sanitized, context) } private static func validatePostMediaType(_ request: Request) -> Response? { diff --git a/Sources/BasaltServer/REST/ModelsController+Convert.swift b/Sources/BasaltServer/REST/ModelsController+Convert.swift index e94f7ef23..5dc7b53b7 100644 --- a/Sources/BasaltServer/REST/ModelsController+Convert.swift +++ b/Sources/BasaltServer/REST/ModelsController+Convert.swift @@ -125,7 +125,7 @@ struct ModelsConvertController: Sendable { return ProviderErrorResponse.response( status: .badRequest, message: "Local adapter paths are not permitted over REST; pass a Hugging Face repo id (org/repo) or use `basalt models convert --adapter`.", shape: .openAI) } - normalized.adapter = adapterId + normalized.adapter = ServedAdapterSource.repositoryPrefix + adapterId } guard let jobId = await operations.conversionCoordinator.tryBegin() else { return ProviderErrorResponse.response( diff --git a/Sources/BasaltServer/REST/OpenAIController.swift b/Sources/BasaltServer/REST/OpenAIController.swift index c919e0ce2..1449dfefa 100644 --- a/Sources/BasaltServer/REST/OpenAIController.swift +++ b/Sources/BasaltServer/REST/OpenAIController.swift @@ -31,12 +31,14 @@ extension OpenAIController { let data = Data(buffer.readableBytesView) let dto: GenerationRequest do { - dto = PromptCacheKey.scoped(try JSONDecoder().decode(GenerationRequest.self, from: data), headers: request.headers).routed(by: request.headers) + let decoded = try JSONDecoder().decode(GenerationRequest.self, from: data) + dto = PromptCacheKey.scoped(decoded, headers: request.headers).routed(by: request.headers) .withOrigin(RequestOrigin(source: "generate", endpoint: "/v1/generate", stream: false)) } catch { return ProviderErrorResponse.response(status: .badRequest, message: ModelsController.publicMessage(for: error), error: error, shape: .openAI) } do { + _ = try dto.validated() let result = try await orchestrator.generate(request: dto) let encoded = try JSONEncoder().encode(result) return makeDataResponse(encoded) diff --git a/Sources/BasaltServer/REST/RESTServer.swift b/Sources/BasaltServer/REST/RESTServer.swift index dacbf6f2c..5e6e0e0ed 100644 --- a/Sources/BasaltServer/REST/RESTServer.swift +++ b/Sources/BasaltServer/REST/RESTServer.swift @@ -114,10 +114,17 @@ package struct RESTServer: Sendable { try await group.run() } + private var hasAuth: Bool { + !(config.apiKey ?? "").isEmpty || !config.virtualKeys.isEmpty + } + private func logStartup() { log("Listening on http://\(config.host):\(config.restPort)") - if let key = config.apiKey, !key.isEmpty { + if hasAuth { log("API key protection: ENABLED (bearer token required)") + if (config.apiKey ?? "").isEmpty, !config.virtualKeys.isEmpty { + log("Admin routes require --api-key (virtual keys alone cannot access control endpoints)") + } } else { log("API key protection: DISABLED (loopback open access)") } @@ -149,7 +156,7 @@ package struct RESTServer: Sendable { private func addMiddleware(to router: Router) { router.add(middleware: LogRequestsMiddleware(.info)) router.add(middleware: RequestGuardMiddleware(bindHost: config.host, bindPort: config.restPort, allowedOrigins: config.allowedOrigins)) - let hasAuth = !(config.apiKey ?? "").isEmpty || !config.virtualKeys.isEmpty + let hasAuth = self.hasAuth if hasAuth { router.add(middleware: APIKeyAuthenticator(apiKey: config.apiKey ?? "", virtualKeys: config.virtualKeys)) } diff --git a/Tests/BasaltTests/PEFTFusedExportTests.swift b/Tests/BasaltTests/PEFTFusedExportTests.swift index 172fe205c..8944a5269 100644 --- a/Tests/BasaltTests/PEFTFusedExportTests.swift +++ b/Tests/BasaltTests/PEFTFusedExportTests.swift @@ -241,7 +241,7 @@ extension PEFTFusedExportTests { ) { $0.status } #expect(repoStatus == .ok) } - #expect(await service.lastRequest?.adapter == "harness-hub/Qwen3.8-27B-pi-adapted") + #expect(await service.lastRequest?.adapter == "hf:harness-hub/Qwen3.8-27B-pi-adapted") var draft = ConversionDraft(sourceId: "org/base", sourceBytes: 4096) #expect(draft.toRequest().adapter == nil) diff --git a/Tests/BasaltTests/RESTServerTests.swift b/Tests/BasaltTests/RESTServerTests.swift index 2bdae89f7..9eb1df4ef 100644 --- a/Tests/BasaltTests/RESTServerTests.swift +++ b/Tests/BasaltTests/RESTServerTests.swift @@ -418,7 +418,7 @@ struct RESTServerTests { try await failing.app.test(.router) { client in try await client.execute(uri: "/api/v1/generate/stream", method: .post, headers: [.contentType: "application/json"], body: ByteBuffer(string: #"{"prompt": "hi"}"#)) { res in let raw = String(buffer: res.body) - #expect(raw.hasPrefix("event: error\n")) + #expect(res.status == .serviceUnavailable) #expect(!raw.contains("[DONE]")) } } diff --git a/Tests/BasaltTests/ServerSecurityDefectRegressionTests.swift b/Tests/BasaltTests/ServerSecurityDefectRegressionTests.swift new file mode 100644 index 000000000..0a074d78e --- /dev/null +++ b/Tests/BasaltTests/ServerSecurityDefectRegressionTests.swift @@ -0,0 +1,260 @@ +import Foundation +import HTTPTypes +import Hummingbird +import HummingbirdTesting +import NIOCore +import Synchronization +import Testing +@testable import BasaltCloud +@testable import BasaltCore +@testable import BasaltInference +@testable import BasaltServer + +@Suite("Server security and protocol defect regressions (A-S1, A-S2, A-S3, A-S8, A-S9, A-S12)") +struct ServerSecurityDefectRegressionTests { + private actor StubConversionService: ModelConversionService { + private(set) var lastRequest: ModelConversionRequest? + + func plan( + source: String, + target: QuantizationTarget, + budgetGB: Double?, + pvTune: Bool, + cacheRoot: URL + ) async throws -> ModelConversionPlan { + ModelConversionPlan(sourceId: source, sourceFormat: "mlx", target: target.specString, supportsPVTune: false) + } + + func convert( + _ request: ModelConversionRequest, + cacheRoot: URL, + onProgress: @escaping @Sendable (ModelConversionProgress) -> Void + ) async throws -> ModelConversionResult { + lastRequest = request + return ModelConversionResult(outputId: request.outputId, bytesBefore: 100, bytesAfter: 50, shards: 1) + } + } + + private actor ErrorFinishEngine: InferenceEngine { + var isLoaded: Bool { true } + var throwOnStream = false + + func setThrowOnStream(_ value: Bool) { throwOnStream = value } + func load(modelPath: String) async throws(BasaltError) {} + func generate(request: GenerationRequest) async throws(BasaltError) -> GenerationResponse { + GenerationResponse( + generatedText: "ok", promptTokens: 1, completionTokens: 1, + tokensPerSecond: 10, generationTime: 0.1, timeToFirstToken: 0.05, + memory: .init(peakBytes: 0, activeBytes: 0, cacheBytes: 0), + finishReason: .stop + ) + } + + func generateStream(request: GenerationRequest) async throws(BasaltError) -> AsyncStream { + if throwOnStream { throw .modelNotLoaded } + let (stream, continuation) = AsyncStream.makeStream() + continuation.yield(.text("partial")) + continuation.yield(.metadata(GenerationResponse( + generatedText: "partial", promptTokens: 1, completionTokens: 1, + tokensPerSecond: 10, generationTime: 0.1, timeToFirstToken: 0.05, + memory: .init(peakBytes: 0, activeBytes: 0, cacheBytes: 0), + finishReason: .error + ))) + continuation.finish() + return stream + } + } + + private actor SpyCloudFallback: CloudFallback { + private(set) var assessCalls = 0 + var routingBias: [String: [String: Double]]? { nil } + + func assess(_ request: GenerationRequest, localModel: String) async -> CloudAssessment? { + assessCalls += 1 + return CloudAssessment(capabilityGap: 0.9, estimatedCost: 0.01, remainingBudget: 10.0, latencySeconds: 0.5) + } + + func recordLocalOutcome(_ request: GenerationRequest, response: GenerationResponse, localModel: String) async {} + + func generate(_ request: GenerationRequest) async throws -> GenerationResponse { + GenerationResponse( + generatedText: "cloud", promptTokens: 1, completionTokens: 1, + tokensPerSecond: 10, generationTime: 0.1, timeToFirstToken: 0.05, + memory: .init(peakBytes: 0, activeBytes: 0, cacheBytes: 0), + finishReason: .stop + ) + } + + func generateStream(_ request: GenerationRequest) async throws -> AsyncThrowingStream { + AsyncThrowingStream { $0.finish() } + } + } + + static func makeServer( + apiKey: String? = nil, + access: ServerConfig.Access = .init(), + engine: E = MockInferenceEngine(), + conversion: (any ModelConversionService)? = nil, + cloudFallback: (any CloudFallback)? = nil + ) async throws -> Application> { + let orchestrator = ModelOrchestratorActor(engine: engine, telemetry: TelemetryTracker()) + if let cloudFallback { + await orchestrator.configureCloudFallback(cloudFallback, arbiter: HybridArbiter()) { 8 << 30 } + } + var config = try ServerConfig(modelPath: "org/model", host: "127.0.0.1", apiKey: apiKey, access: access) + config.modelId = "org/model" + var server = RESTServer(orchestrator: orchestrator, config: config) + if let conversion { + let hub = ModelHubOperations(converter: conversion) { _, _ in URL(fileURLWithPath: "/tmp") } + server = server.withModelHub(hub) + } + return Application(router: server.makeRouter()) + } +} + +extension ServerSecurityDefectRegressionTests { + @Test("A-S1: /v1/generate, /api/v1/generate, /api/v1/generate/stream, and MCP basalt_generate reject invalid maxTokens before cloud fallback; estimateCost never overflows") + func generateEndpointsValidateMaxTokensAndCostNeverOverflows() async throws { + let catalog = ModelCatalog() + #expect(catalog.estimateCost(model: "gpt-4", promptTokens: 100, completionTokens: Int.max).isFinite) + #expect(catalog.estimateCost(model: "openai/gpt-4-turbo", promptTokens: -50, completionTokens: -1000) == 0.0) + + #expect(throws: MCPFailure.self) { + _ = try MCPArguments.generation(["prompt": "hi", "maxTokens": Int.max]) + } + #expect(throws: MCPFailure.self) { + _ = try MCPArguments.generation(["prompt": "hi", "maxTokens": 1_000_000]) + } + + let spy = SpyCloudFallback() + let app = try await Self.makeServer(cloudFallback: spy) + let jsonHeaders: HTTPFields = [.contentType: "application/json"] + try await app.test(.router) { client in + for path in ["/v1/generate", "/api/v1/generate", "/api/v1/generate/stream"] { + for badMax in [Int.max, -100, 1_000_000] { + let body = ByteBuffer(string: #"{"prompt":"hi","maxTokens":\#(badMax)}"#) + try await client.execute(uri: path, method: .post, headers: jsonHeaders, body: body) { res in + #expect(res.status == .contentTooLarge, "\(path) maxTokens=\(badMax) got \(res.status)") + } + } + } + } + #expect(await spy.assessCalls == 0) + } + + @Test("A-S2: virtual keys are forbidden on canonical, trailing-slash, and double-slash admin routes; master key retains access and rate isolation") + func virtualKeysBlockedFromAdminRoutesAndRateIsolated() async throws { + let vkMaster = VirtualKey(key: "vk-impersonate-master-1234", id: "master", maxBudget: 0) + let stub = StubConversionService() + let app = try await Self.makeServer( + apiKey: "real-master-secret-key", + access: .init(rateLimitPerMinute: 60, rateBurst: 1, virtualKeys: [vkMaster]), + conversion: stub + ) + let vkAuth: HTTPFields = [.authorization: "Bearer vk-impersonate-master-1234", .contentType: "application/json"] + let masterAuth: HTTPFields = [.authorization: "Bearer real-master-secret-key", .contentType: "application/json"] + let blocked: [(HTTPRequest.Method, String)] = [ + (.delete, "/v1/models/org/model"), (.delete, "//v1/models/org/model"), + (.post, "/v1/models/load"), (.post, "/v1/models/load/"), + (.post, "/v1/models/download"), (.post, "/v1/models/publish"), (.post, "/v1//models/publish"), + (.post, "/v1/models/convert"), (.post, "/v1/models/convert/"), (.post, "/api/v1/models/convert"), + (.get, "/v1/compose"), (.post, "/v1/compose/apply"), (.post, "/v1/compose/apply/"), (.post, "/v1/compose/diff"), + (.post, "/v1/mcp/approvals/req-1/approve"), (.post, "/v1//mcp/approvals/req-1/approve"), + ] + try await app.test(.router) { client in + for (method, path) in blocked { + let body = method == .post ? ByteBuffer(string: "{}") : nil + try await client.execute(uri: path, method: method, headers: vkAuth, body: body) { res in + #expect(res.status == .forbidden, "\(method) \(path) returned \(res.status)") + } + } + let convertBody = ByteBuffer(bytes: try JSONEncoder().encode( + ModelConversionRequest(source: "org/base", outputId: "org/out", target: .affine(bits: 4, groupSize: 64), stream: false) + )) + try await client.execute(uri: "/v1/models/convert", method: .post, headers: masterAuth, body: convertBody) { res in + #expect(res.status == .ok) + } + try await client.execute(uri: "/v1/models", method: .get, headers: vkAuth) { res in #expect(res.status == .ok) } + try await client.execute(uri: "/v1/models", method: .get, headers: vkAuth) { res in #expect(res.status == .tooManyRequests) } + try await client.execute(uri: "/api/v1/health/", method: .get, headers: vkAuth) { res in #expect(res.status == .ok) } + } + } +} + +extension ServerSecurityDefectRegressionTests { + @Test("A-S3: REST /v1/models/convert preserves hf: prefix on adapter so CWD directories cannot be loaded") + func restConvertPreservesHFAdapterPrefix() async throws { + let stub = StubConversionService() + let app = try await Self.makeServer(conversion: stub) + var convReq = ModelConversionRequest( + source: "org/base", + outputId: "org/out", + target: .affine(bits: 4, groupSize: 64), + stream: false + ) + convReq.adapter = "hf:org/lora" + let body = ByteBuffer(bytes: try JSONEncoder().encode(convReq)) + try await app.test(.router) { client in + try await client.execute(uri: "/v1/models/convert", method: .post, headers: [.contentType: "application/json"], body: body) { res in + #expect(res.status == .ok) + } + } + let recorded = await stub.lastRequest + #expect(recorded?.adapter == "hf:org/lora") + } + + @Test("A-S8, A-S9, A-S12: oversized JSON (including /v1/chat/completions & trailing slashes) returns JSON 413, stream errors omit [DONE], no-auth strips budget/rate headers") + func middleware413StreamErrorAndHeaderSanitization() async throws { + typealias Limit = JSONNestingLimitMiddleware + #expect(Limit.bodyLimit(for: "/v1/models/publish/") == ModelsHubController.bodyLimit) + #expect(Limit.bodyLimit(for: "/v1//models/convert/") == ModelsConvertController.bodyLimit) + #expect(Limit.bodyLimit(for: "/v1/compose/apply/") == ComposeController.bodyLimit) + #expect(Limit.bodyLimit(for: "/v1/models/load/") == 1024 * 1024) + + let errorEngine = ErrorFinishEngine() + let app = try await Self.makeServer(engine: errorEngine) + let headers: HTTPFields = [.contentType: "application/json"] + let tooBig = ByteBuffer(string: #"{"prompt":""# + String(repeating: "a", count: 1_100_000) + #""}"#) + let chatTooBig = ByteBuffer(repeating: UInt8(ascii: " "), count: ChatPipeline.bodyLimit + 16) + try await app.test(.router) { client in + try await client.execute(uri: "/api/v1/generate", method: .post, headers: headers, body: tooBig) { res in + #expect(res.status == .contentTooLarge && res.headers[.contentType]?.contains("application/json") == true) + } + try await client.execute(uri: "/v1/chat/completions", method: .post, headers: headers, body: chatTooBig) { res in + #expect(res.status == .contentTooLarge && res.headers[.contentType]?.contains("application/json") == true) + } + try await client.execute( + uri: "/api/v1/generate/stream", method: .post, headers: headers, + body: ByteBuffer(string: #"{"prompt":"hi","maxTokens":8}"#) + ) { res in + let text = String(buffer: res.body) + #expect(res.status == .ok && text.contains("event: error") && !text.contains("data: [DONE]")) + } + await errorEngine.setThrowOnStream(true) + try await client.execute( + uri: "/api/v1/generate/stream", method: .post, headers: headers, + body: ByteBuffer(string: #"{"prompt":"hi","maxTokens":8}"#) + ) { res in + #expect(res.status == .serviceUnavailable) + } + } + + let seen = Mutex<(String?, String?)>((nil, nil)) + let guardRouter = Router() + guardRouter.add(middleware: RequestGuardMiddleware(bindHost: "127.0.0.1", bindPort: 8080)) + guardRouter.get("/probe") { request, _ in + seen.withLock { + $0 = (request.headers[APIKeyAuthenticator.budgetKeyHeader], + request.headers[APIKeyAuthenticator.rateKeyHeader]) + } + return Response(status: .ok) + } + try await Application(router: guardRouter).test(.router) { client in + var spoof = HTTPFields() + spoof[APIKeyAuthenticator.budgetKeyHeader] = "spoof-tenant" + spoof[APIKeyAuthenticator.rateKeyHeader] = "master" + try await client.execute(uri: "/probe", method: .get, headers: spoof) { res in #expect(res.status == .ok) } + } + #expect(seen.withLock { $0.0 == nil && $0.1 == nil }) + } +} From 788cb24a5736f38bc428587793864a38c5d8dfa7 Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:14:35 +0100 Subject: [PATCH 3/6] fix(cloud): record provider usage.cost, re-check budget across await with in-flight reservations, fix assess side-effects & cascade stream metadata (A-S4, A-S6, A-S10, A-S11) --- Sources/BasaltCloud/CascadeRouting.swift | 11 +- Sources/BasaltCloud/CloudGate.swift | 72 ++++- Sources/BasaltCloud/CostTracker.swift | 34 ++- .../ModelRouter+FallbackTiers.swift | 60 +++-- Sources/BasaltCloud/ModelRouter.swift | 100 +++++-- Sources/BasaltCloud/ModelRouterCore.swift | 4 + .../CloudBudgetDefectRegressionTests.swift | 252 ++++++++++++++++++ Tests/BasaltTests/RetroWave2Tests.swift | 2 +- 8 files changed, 486 insertions(+), 49 deletions(-) create mode 100644 Tests/BasaltTests/Cloud/CloudBudgetDefectRegressionTests.swift diff --git a/Sources/BasaltCloud/CascadeRouting.swift b/Sources/BasaltCloud/CascadeRouting.swift index 383612afb..174994361 100644 --- a/Sources/BasaltCloud/CascadeRouting.swift +++ b/Sources/BasaltCloud/CascadeRouting.swift @@ -229,8 +229,17 @@ extension ModelRouter { let cloudStream = try await routeCloudChainStream( modelId: cascade.cloudModel, request: cloudRequest, context: context, localFallback: localPath ) + var yieldedMetadata = false for try await chunk in cloudStream { - continuation.yield(chunk) + if case .metadata(let cloudMeta) = chunk { + yieldedMetadata = true + continuation.yield(.metadata(acc.mergedResponse(cloud: cloudMeta))) + } else { + continuation.yield(chunk) + } + } + if !yieldedMetadata { + continuation.yield(.metadata(acc.mergedResponse())) } continuation.finish() return diff --git a/Sources/BasaltCloud/CloudGate.swift b/Sources/BasaltCloud/CloudGate.swift index 4bfaab8b7..c5e1b97e2 100644 --- a/Sources/BasaltCloud/CloudGate.swift +++ b/Sources/BasaltCloud/CloudGate.swift @@ -76,6 +76,8 @@ public actor CloudGate { private var core: CloudGateCore private let storage: URL? private let now: @Sendable () -> Date + private var reservations: [UUID: (model: String, amount: Double)] = [:] + private var peakCallCost: [String: Double] = [:] public init(limits: [String: Double], storage: URL?, now: @escaping @Sendable () -> Date = { Date() }) { let today = CloudGateCore.day(of: now()) @@ -86,14 +88,52 @@ public actor CloudGate { (self.core, self.storage, self.now) = (core, storage, now) } - public func refusal(_ model: String) -> CloudGateCore.Refusal? { + private func reservedAmount(for key: String) -> Double { + if key == CloudGateCore.total { + return reservations.values.reduce(0) { $0 + $1.amount } + } + return reservations.values.reduce(0) { $0 + ($1.model == key ? $1.amount : 0) } + } + + public func refusal(_ model: String, estimatedCost: Double = 0) -> CloudGateCore.Refusal? { core.roll(to: CloudGateCore.day(of: now())) - return core.refusal(model, now: now()) + if let base = core.refusal(model, now: now()) { return base } + let add = estimatedCost.isFinite && estimatedCost > 0 ? estimatedCost : 0 + for key in [model, CloudGateCore.total] { + if let limit = core.limits[key] { + let committed = core.spent[key, default: 0] + reservedAmount(for: key) + if committed >= limit || (add > 0 && committed + add > limit + 1e-12) { + return .budget(spent: committed, limit: limit) + } + } + } + return nil + } + + private func activeLimit(for model: String) -> Double? { + [core.limits[model], core.limits[CloudGateCore.total]].compactMap { $0 }.min() + } + + public func reserve(_ model: String, estimatedCost: Double = 0) -> (token: UUID?, refusal: CloudGateCore.Refusal?) { + let estimate = estimatedCost.isFinite && estimatedCost > 0 ? estimatedCost : 0 + let floor = estimate > 0 ? estimate : (peakCallCost[model] ?? activeLimit(for: model) ?? 0) + let checkAdd = (estimate > 0 || !reservations.isEmpty) ? floor : 0 + if let refused = refusal(model, estimatedCost: checkAdd) { return (nil, refused) } + let token = UUID() + reservations[token] = (model, floor) + return (token, nil) + } + + public func release(_ token: UUID) { + reservations.removeValue(forKey: token) } public func record(_ model: String, cost: Double) { core.roll(to: CloudGateCore.day(of: now())) core.record(model, cost: cost) + if cost.isFinite, cost > 0 { + peakCallCost[model] = max(peakCallCost[model, default: 0], cost) + } guard let storage, let data = try? JSONEncoder().encode(core) else { return } try? FileManager.default.createDirectory(at: storage.deletingLastPathComponent(), withIntermediateDirectories: true) try? data.write(to: storage, options: .atomic) @@ -111,6 +151,10 @@ public actor CloudGate { core.roll(to: CloudGateCore.day(of: now())) return core.spent[model, default: 0] } + + static func estimatedCost(model: String, promptTokens: Int, completionTokens: Int) -> Double { + ModelCatalog().estimateCost(model: model, promptTokens: promptTokens, completionTokens: completionTokens) + } } public struct GuardedDecisionEngine: DecisionEngine { @@ -131,7 +175,16 @@ public struct GuardedDecisionEngine: DecisionEngine { } public func decide(_ request: SystemOneRequest) async throws(BasaltError) -> SystemOneResponse { - if let refusal = await gate.refusal(modelID) { throw .modelInferenceError(details: "cloud decisions: \(refusal.reason)") } + let promptTokens = max(1, request.state.utf8.count / 4 + request.questions.count * 32) + let completionTokens = max(16, request.questions.count * 24) + let estimated = CloudGate.estimatedCost(model: modelID, promptTokens: promptTokens, completionTokens: completionTokens) + let claim = await gate.reserve(modelID, estimatedCost: estimated) + if let refusal = claim.refusal { throw .modelInferenceError(details: "cloud decisions: \(refusal.reason)") } + defer { + if let token = claim.token { + await withTaskCancellationShield { await gate.release(token) } + } + } do { let response = try await inner.decide(request) await gate.record(modelID, cost: response.usage.cost ?? 0) @@ -156,9 +209,20 @@ public struct CloudAnswer: AnswerTarget { public func unavailable() async -> String? { await gate.refusal(model)?.reason } public func answer(_ request: GenerationRequest) async throws(BasaltError) -> AnswerReply { - if let refusal = await gate.refusal(model) { + let estimated = CloudGate.estimatedCost( + model: model, + promptTokens: ModelRouter.estimatedPromptTokens(request), + completionTokens: request.maxTokens ?? 1_024 + ) + let claim = await gate.reserve(model, estimatedCost: estimated) + if let refusal = claim.refusal { throw .modelInferenceError(details: "cloud answer: \(refusal.reason)") } + defer { + if let token = claim.token { + await withTaskCancellationShield { await gate.release(token) } + } + } let turns = request.messages ?? [ChatMessageInput(role: .user, text: request.prompt)] var chat = OpenRouterClient.ChatRequest( model: model, messages: turns.map { .init(role: $0.role.rawValue, content: SecretRedactor.redact($0.text)) }, diff --git a/Sources/BasaltCloud/CostTracker.swift b/Sources/BasaltCloud/CostTracker.swift index 29220fffb..a052adf4b 100644 --- a/Sources/BasaltCloud/CostTracker.swift +++ b/Sources/BasaltCloud/CostTracker.swift @@ -58,6 +58,7 @@ public actor CostTracker: Sendable { static let maxTrackedSessions = 4_096 private var sessionUsage: [String: (cost: Double, tick: UInt64)] = [:] private var sessionTick: UInt64 = 0 + private var reservations: [UUID: (amount: Double, scopes: Set)] = [:] private let logger = Logger() @@ -119,18 +120,43 @@ public actor CostTracker: Sendable { } } + private var totalReserved: Double { + reservations.values.reduce(0) { $0 + $1.amount } + } + + private func reserved(in scope: BudgetScope) -> Double { + reservations.values.reduce(0) { $0 + ($1.scopes.contains(scope) ? $1.amount : 0) } + } + public func isExhausted(scopes: [BudgetScope]) -> Bool { resetCountersIfNeeded() - if stats.dailyUsage >= budget.dailyLimit || stats.monthlyUsage >= budget.monthlyLimit { return true } + if stats.dailyUsage + totalReserved >= budget.dailyLimit || stats.monthlyUsage + totalReserved >= budget.monthlyLimit { + return true + } return scopes.contains { scope in - limit(for: scope).map { spent(in: scope) >= $0 } ?? false + limit(for: scope).map { spent(in: scope) + reserved(in: scope) >= $0 } ?? false } } public func remaining(scopes: [BudgetScope]) -> Double { resetCountersIfNeeded() - let scoped = scopes.compactMap { scope in limit(for: scope).map { $0 - spent(in: scope) } } - return ([budget.dailyLimit - stats.dailyUsage, budget.monthlyLimit - stats.monthlyUsage] + scoped).min()! + let scoped = scopes.compactMap { scope in limit(for: scope).map { $0 - spent(in: scope) - reserved(in: scope) } } + let global = [budget.dailyLimit - stats.dailyUsage - totalReserved, budget.monthlyLimit - stats.monthlyUsage - totalReserved] + return (global + scoped).min()! + } + + public func reserve(estimatedCost: Double, scopes: [BudgetScope] = []) -> UUID? { + resetCountersIfNeeded() + let amount = estimatedCost.isFinite && estimatedCost > 0 ? estimatedCost : 0 + if isExhausted(scopes: scopes) { return nil } + if amount > 0 && amount > remaining(scopes: scopes) + 1e-12 { return nil } + let token = UUID() + reservations[token] = (amount, Set(scopes)) + return token + } + + public func release(reservation token: UUID) { + reservations.removeValue(forKey: token) } public func recordUsage(model: String, cost: Double, scopes: [BudgetScope] = []) throws { diff --git a/Sources/BasaltCloud/ModelRouter+FallbackTiers.swift b/Sources/BasaltCloud/ModelRouter+FallbackTiers.swift index 6d988c75d..b455873fc 100644 --- a/Sources/BasaltCloud/ModelRouter+FallbackTiers.swift +++ b/Sources/BasaltCloud/ModelRouter+FallbackTiers.swift @@ -28,30 +28,40 @@ extension ModelRouter { ) -> Double? { if tier.isFree { return 0 } guard !exhausted else { return nil } - let text = (request.messages?.isEmpty == false) - ? ChatMessageInput.plainText(request.messages ?? []) - : request.prompt - let promptTokens = text.utf8.count / 4 + let promptTokens = Self.estimatedPromptTokens(request) let completionTokens = request.maxTokens ?? 1_024 let cost = estimateCost(model: tier.model, promptTokens: promptTokens, completionTokens: completionTokens) if let remaining, cost > remaining { return nil } return cost } + private func reservePaidTier(_ tier: FallbackTier, request: GenerationRequest, context: RoutingContext) async -> (allowed: Bool, token: UUID?) { + if tier.isFree { return (true, nil) } + guard let costTracker else { return (true, nil) } + let exhausted = await costTracker.isExhausted(scopes: context.budgetScopes) + let remaining = await costTracker.remaining(scopes: context.budgetScopes) + guard let cost = tierEstimatedCost(tier, request: request, exhausted: exhausted, remaining: remaining) else { + return (false, nil) + } + guard let token = await costTracker.reserve(estimatedCost: cost, scopes: context.budgetScopes) else { + return (false, nil) + } + return (true, token) + } + func assessFallbackTiers(_ request: GenerationRequest, localModel: String) async -> CloudAssessment? { guard Self.isFallbackEligible(request) else { return nil } let context = RoutingContext(request) let completionTokens = request.maxTokens ?? 1_024 - let exhausted = if let costTracker { await costTracker.isExhausted(scopes: context.budgetScopes) } else { false } - let remaining = await costTracker?.remaining(scopes: context.budgetScopes) for tier in state.fallback.orderedTiers(sessionId: context.sessionId) { + let exhausted = if let costTracker { await costTracker.isExhausted(scopes: context.budgetScopes) } else { false } + let remaining = await costTracker?.remaining(scopes: context.budgetScopes) guard let estimatedCost = tierEstimatedCost(tier, request: request, exhausted: exhausted, remaining: remaining) else { continue } let tierRemaining: Double? = tier.isFree ? nil : remaining guard await isTierHealthy(tier) else { continue } let choice = state.cost?.stickyTier(request, sessionId: context.sessionId, localModel: localModel, at: Date()) - if let choice { state = .reduce(state, .tierChosen(choice.tier, sessionId: context.sessionId, request: request)) } return CloudAssessment( capabilityGap: choice?.capabilityGap ?? 0, estimatedCost: estimatedCost, @@ -61,23 +71,29 @@ extension ModelRouter { } return nil } +} +extension ModelRouter { func generateFromFallbackTiers(_ request: GenerationRequest) async throws -> GenerationResponse { let context = RoutingContext(request) - let exhausted = if let costTracker { await costTracker.isExhausted(scopes: context.budgetScopes) } else { false } - let remaining = await costTracker?.remaining(scopes: context.budgetScopes) var lastError: Error? for tier in state.fallback.orderedTiers(sessionId: context.sessionId) { - guard tierEstimatedCost(tier, request: request, exhausted: exhausted, remaining: remaining) != nil else { continue } guard await isTierHealthy(tier) else { if Task.isCancelled { throw CancellationError() } continue } + let claim = await reservePaidTier(tier, request: request, context: context) + guard claim.allowed else { continue } do { - let response = try await routeToCloud(client: tier.client, model: tier.model, request: request) + defer { + if let token = claim.token { + await withTaskCancellationShield { await costTracker?.release(reservation: token) } + } + } + let (response, reportedCost) = try await routeToCloudWithCost(client: tier.client, model: tier.model, request: request) state = .reduce(state, .fallback(.sessionBound(sessionId: context.sessionId, tierId: tier.id))) if !tier.isFree { - await recordCloudCost(model: tier.model, response: response, context: context) + await recordCloudCost(model: tier.model, response: response, context: context, reportedCost: reportedCost) } return response } catch { @@ -92,26 +108,32 @@ extension ModelRouter { func generateStreamFromFallbackTiers(_ request: GenerationRequest) async throws -> AsyncThrowingStream { let context = RoutingContext(request) - let exhausted = if let costTracker { await costTracker.isExhausted(scopes: context.budgetScopes) } else { false } - let remaining = await costTracker?.remaining(scopes: context.budgetScopes) var lastError: Error? for tier in state.fallback.orderedTiers(sessionId: context.sessionId) { - guard tierEstimatedCost(tier, request: request, exhausted: exhausted, remaining: remaining) != nil else { continue } guard await isTierHealthy(tier) else { if Task.isCancelled { throw CancellationError() } continue } + let claim = await reservePaidTier(tier, request: request, context: context) + guard claim.allowed else { continue } do { let startTime = ContinuousClock.now let source = try await tier.client.chatStream(request: Self.chatRequest(request, model: tier.model, stream: true)) state = .reduce(state, .fallback(.sessionBound(sessionId: context.sessionId, tierId: tier.id))) let isFree = tier.isFree let model = tier.model - return Self.relayCloudStream(source, startTime: startTime) { [weak self] metadata in - guard !isFree else { return } - await self?.recordCloudCost(model: model, response: metadata, context: context) - } + let tracker = costTracker + let token = claim.token + return Self.relayCloudStream(source, startTime: startTime, onUsageWithCost: { [weak self] metadata, cost in + if !isFree { + await self?.recordCloudCost(model: model, response: metadata, context: context, reportedCost: cost) + } + if let token { await tracker?.release(reservation: token) } + }, onFinish: { + if let token { await tracker?.release(reservation: token) } + }) } catch { + if let token = claim.token { await costTracker?.release(reservation: token) } if Self.isCancellation(error) { throw error } lastError = error let instant = state.fallback.probeConfig.now() diff --git a/Sources/BasaltCloud/ModelRouter.swift b/Sources/BasaltCloud/ModelRouter.swift index f4b05e69e..17c56783e 100644 --- a/Sources/BasaltCloud/ModelRouter.swift +++ b/Sources/BasaltCloud/ModelRouter.swift @@ -86,9 +86,7 @@ public actor ModelRouter: Sendable { } return try await self.localOrchestrator.generate(request: request, modelId: path) } cloud: { client, model in - let response = try await self.routeToCloud(client: client, model: model, request: request) - await self.recordCloudCost(model: model, response: response, context: context) - return response + try await self.routeToCloudReserved(client: client, model: model, request: request, context: context) } } @@ -114,6 +112,9 @@ public actor ModelRouter: Sendable { } public func recordLocalOutcome(_ request: GenerationRequest, response: GenerationResponse, localModel: String) { + if state.cost != nil { + state = .reduce(state, .tierChosen(.weak, sessionId: request.sessionId, request: request)) + } let before = state.cost?.outcomeBias state = .reduce(state, .outcome(request, response, localModel: localModel, at: Date())) guard let cost = state.cost, cost.outcomeBias != before, let url = cost.routing.outcomeBiasURL else { return } @@ -124,6 +125,10 @@ public actor ModelRouter: Sendable { } } + func sessionTier(for sessionId: String) -> StickyRoutingPolicy.Tier? { + state.cost?.sessionTier(for: sessionId) + } + public var routingBias: [String: [String: Double]]? { state.cost?.outcomeBias.snapshot(at: Date()) } @@ -242,9 +247,7 @@ extension ModelRouter { try await callCloudChain(ModelCatalog.cloudModels(for: modelId), context: context, localFallback: localFallback) { path in try await self.localOrchestrator.generate(request: request, modelId: path) } cloud: { client, model in - let (response, reportedCost) = try await self.routeToCloudWithCost(client: client, model: model, request: request) - await self.recordCloudCost(model: model, response: response, context: context, reportedCost: reportedCost) - return response + try await self.routeToCloudReserved(client: client, model: model, request: request, context: context) } } @@ -269,13 +272,7 @@ extension ModelRouter { } } - func routeToCloud( - client: OpenRouterClient, model: String, request: GenerationRequest - ) async throws -> GenerationResponse { - try await routeToCloudWithCost(client: client, model: model, request: request).0 - } - - private func routeToCloudWithCost( + func routeToCloudWithCost( client: OpenRouterClient, model: String, request: GenerationRequest ) async throws -> (GenerationResponse, Double?) { let startTime = ContinuousClock.now @@ -294,16 +291,59 @@ extension ModelRouter { return (reply, chatResponse.usage?.cost) } + private func reserveCloudBudget( + model: String, request: GenerationRequest, context: RoutingContext + ) async throws(BasaltError) -> UUID? { + guard let costTracker else { return nil } + let estimated = estimateCost( + model: model, + promptTokens: Self.estimatedPromptTokens(request), + completionTokens: request.maxTokens ?? 1_024 + ) + guard let token = await costTracker.reserve(estimatedCost: estimated, scopes: context.budgetScopes) else { + throw .invalidRequestStructure(details: "Cloud budget exhausted for \(model)") + } + return token + } + + private func routeToCloudReserved( + client: OpenRouterClient, model: String, request: GenerationRequest, context: RoutingContext + ) async throws -> GenerationResponse { + let reservation = try await reserveCloudBudget(model: model, request: request, context: context) + defer { + if let reservation { + await withTaskCancellationShield { await costTracker?.release(reservation: reservation) } + } + } + let (response, reportedCost) = try await routeToCloudWithCost(client: client, model: model, request: request) + await recordCloudCost(model: model, response: response, context: context, reportedCost: reportedCost) + return response + } + private func routeToCloudStream( client: OpenRouterClient, model: String, request: GenerationRequest, context: RoutingContext ) async throws -> AsyncThrowingStream { + let reservation = try await reserveCloudBudget(model: model, request: request, context: context) let startTime = ContinuousClock.now - let sourceStream = try await client.chatStream(request: Self.chatRequest(request, model: model, stream: true)) + let sourceStream: AsyncThrowingStream + do { + sourceStream = try await client.chatStream(request: Self.chatRequest(request, model: model, stream: true)) + } catch { + if let reservation { + await withTaskCancellationShield { await costTracker?.release(reservation: reservation) } + } + throw error + } + let tracker = costTracker return Self.relayCloudStream(sourceStream, startTime: startTime, onUsageWithCost: { [weak self] metadata, cost in await self?.recordCloudCost(model: model, response: metadata, context: context, reportedCost: cost) + }, onFinish: { + if let reservation { await tracker?.release(reservation: reservation) } }) } +} +extension ModelRouter { static func chatRequest(_ request: GenerationRequest, model: String, stream: Bool) -> OpenRouterClient.ChatRequest { var req = OpenRouterClient.ChatRequest( model: model, @@ -312,7 +352,7 @@ extension ModelRouter { maxTokens: request.maxTokens, stream: stream ) - if stream { req.usage = .init(include: true) } + req.usage = .init(include: true) return req } @@ -320,10 +360,16 @@ extension ModelRouter { _ source: AsyncThrowingStream, startTime: ContinuousClock.Instant, onUsage: @escaping @Sendable (GenerationResponse) async -> Void = { _ in }, - onUsageWithCost: (@Sendable (GenerationResponse, Double?) async -> Void)? = nil + onUsageWithCost: (@Sendable (GenerationResponse, Double?) async -> Void)? = nil, + onFinish: (@Sendable () async -> Void)? = nil ) -> AsyncThrowingStream { AsyncThrowingStream { continuation in let task = Task { + defer { + if let onFinish { + await withTaskCancellationShield { await onFinish() } + } + } do { var finishReason: String? var usage: OpenRouterClient.ChatResponse.Usage? @@ -403,27 +449,41 @@ extension ModelRouter: CloudFallback { if let costTracker, await costTracker.isExhausted(scopes: context.budgetScopes) { return nil } let completionTokens = request.maxTokens ?? 1_024 let choice = state.cost?.stickyTier(request, sessionId: context.sessionId, localModel: localModel, at: Date()) - if let choice { state = .reduce(state, .tierChosen(choice.tier, sessionId: context.sessionId, request: request)) } let gap = choice?.capabilityGap ?? 0 return CloudAssessment( capabilityGap: gap, - estimatedCost: estimateCost(model: cloudModel, promptTokens: request.prompt.utf8.count / 4, completionTokens: completionTokens), + estimatedCost: estimateCost(model: cloudModel, promptTokens: Self.estimatedPromptTokens(request), completionTokens: completionTokens), remainingBudget: await costTracker?.remaining(scopes: context.budgetScopes), latencySeconds: Double(completionTokens) / Self.assumedCloudTokensPerSecond ) } + static func estimatedPromptTokens(_ request: GenerationRequest) -> Int { + let text = (request.messages?.isEmpty == false) + ? ChatMessageInput.plainText(request.messages ?? []) + : request.prompt + return text.utf8.count / 4 + } + public func generate(_ request: GenerationRequest) async throws -> GenerationResponse { + let context = RoutingContext(request) + if state.cost != nil { + state = .reduce(state, .tierChosen(.strong, sessionId: context.sessionId, request: request)) + } if state.fallback.isMultiTier { return try await generateFromFallbackTiers(request) } - return try await route(request: request, preferredModel: fallbackCloudModel, context: RoutingContext(request)) + return try await route(request: request, preferredModel: fallbackCloudModel, context: context) } public func generateStream(_ request: GenerationRequest) async throws -> AsyncThrowingStream { + let context = RoutingContext(request) + if state.cost != nil { + state = .reduce(state, .tierChosen(.strong, sessionId: context.sessionId, request: request)) + } if state.fallback.isMultiTier { return try await generateStreamFromFallbackTiers(request) } - return try await routeStream(request: request, preferredModel: fallbackCloudModel, context: RoutingContext(request)) + return try await routeStream(request: request, preferredModel: fallbackCloudModel, context: context) } } diff --git a/Sources/BasaltCloud/ModelRouterCore.swift b/Sources/BasaltCloud/ModelRouterCore.swift index dc6e80436..3acec6e58 100644 --- a/Sources/BasaltCloud/ModelRouterCore.swift +++ b/Sources/BasaltCloud/ModelRouterCore.swift @@ -221,6 +221,10 @@ struct CostRoutingState: Sendable { var trackedSessionCount: Int { sessions.count } + func sessionTier(for sessionId: String) -> StickyRoutingPolicy.Tier? { + sessions[sessionId]?.tier + } + func warmPrefixTokens(sessionId: String?) -> Int { sessionId.flatMap { sessions[$0]?.promptTokens } ?? 0 } diff --git a/Tests/BasaltTests/Cloud/CloudBudgetDefectRegressionTests.swift b/Tests/BasaltTests/Cloud/CloudBudgetDefectRegressionTests.swift new file mode 100644 index 000000000..00b07293c --- /dev/null +++ b/Tests/BasaltTests/Cloud/CloudBudgetDefectRegressionTests.swift @@ -0,0 +1,252 @@ +import Foundation +import HTTPTypes +import Hummingbird +import NIOCore +import Testing +@testable import BasaltCloud +@testable import BasaltCore + +@Suite("Cloud budget, reservation, assess side-effect, and cascade stream metadata regressions (A-S4, A-S6, A-S10, A-S11)") +struct CloudBudgetDefectRegressionTests { + actor RequestGate { + private var entered = 0 + private var enteredWaiter: CheckedContinuation? + private var releaseWaiters: [CheckedContinuation] = [] + private var released = false + + var hits: Int { entered } + + func arriveAndHold() async { + entered += 1 + if let waiter = enteredWaiter { + enteredWaiter = nil + waiter.resume() + } + guard !released else { return } + await withCheckedContinuation { releaseWaiters.append($0) } + } + + func waitForFirstArrival() async { + guard entered == 0 else { return } + await withCheckedContinuation { enteredWaiter = $0 } + } + + func releaseAll() { + released = true + let waiters = releaseWaiters + releaseWaiters.removeAll() + waiters.forEach { $0.resume() } + } + } + + private actor SegmentedLocalEngine: InferenceEngine { + var isLoaded: Bool { true } + private var turn = 0 + + func load(modelPath: String) async throws(BasaltError) {} + func generateStream(request: GenerationRequest) async throws(BasaltError) -> AsyncStream { + AsyncStream { $0.finish() } + } + + func generate(request: GenerationRequest) async throws(BasaltError) -> GenerationResponse { + defer { turn += 1 } + let confident = turn == 0 + let text = confident ? "part1 " : "unsure" + let resp = GenerationResponse( + generatedText: text, promptTokens: 12, completionTokens: 6, + tokensPerSecond: 30, generationTime: 0.2, timeToFirstToken: 0.08, + memory: .init(peakBytes: 0, activeBytes: 0, cacheBytes: 0), + finishReason: .length + ) + return resp.withConfidence(ResponseConfidence(min: confident ? 0.92 : 0.1, mean: confident ? 0.95 : 0.2)) + } + } + + static func makeTracker(daily: Double = 1.0) throws -> (CostTracker, URL) { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cloud-defects-\(UUID().uuidString)") + let file = dir.appendingPathComponent("cost.json") + return (try CostTracker(storageURL: file, budget: CostTracker.Budget(dailyLimit: daily, monthlyLimit: daily * 10)), dir) + } + + static func makeClient(host: String) throws -> OpenRouterClient { + let config = OpenRouterClient.Config( + apiKey: "k", baseURL: try #require(URL(string: "http://\(host)/api/v1")), timeout: 5, maxRetries: 0 + ) + return try OpenRouterClient(config: config, configuration: StubURLProtocol.configuration) + } + + static func withGatedCloudClient( + _ body: (OpenRouterClient, RequestGate) async throws -> Void + ) async throws { + let gate = RequestGate() + let okPayload = #"{"id":"c1","model":"openai/gpt-4-turbo","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":10,"total_tokens":20,"cost":0.01}}"# + let router = Router() + router.post("/api/v1/chat/completions") { _, _ in + await gate.arriveAndHold() + return Response(status: .ok, headers: [.contentType: "application/json"], body: .init(byteBuffer: ByteBuffer(string: okPayload))) + } + let portReady = AsyncStream.makeStream(of: Int.self) + let app = Application( + router: router, + configuration: .init(address: .hostname("127.0.0.1", port: 0)), + onServerRunning: { channel in portReady.continuation.yield(channel.localAddress?.port ?? 0) } + ) + let serverTask = Task { try await app.runService() } + defer { serverTask.cancel() } + var portIter = portReady.stream.makeAsyncIterator() + let port = try #require(await portIter.next()) + let client = try OpenRouterClient( + config: .init(apiKey: "k", baseURL: try #require(URL(string: "http://127.0.0.1:\(port)/api/v1")), timeout: 10, maxRetries: 0) + ) + try await body(client, gate) + } +} + +extension CloudBudgetDefectRegressionTests { + @Test("A-S4: ModelRouter includes usage.include on non-streaming requests and records provider-reported usage.cost") + func nonStreamingChatIncludesUsageAndRecordsReportedCost() async throws { + let req = ModelRouter.chatRequest(GenerationRequest(prompt: "hi", maxTokens: 16), model: "unlisted/model", stream: false) + #expect(req.usage?.include == true) + + let payload: [String: Any] = [ + "id": "cmpl-cost", + "model": "unlisted/model", + "choices": [["message": ["role": "assistant", "content": "hello"], "finish_reason": "stop"]], + "usage": ["prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, "cost": 0.25], + ] + let data = try JSONSerialization.data(withJSONObject: payload) + let host = StubURLProtocol.host { _, _ in (200, ["Content-Type": "application/json"], data) } + let client = try Self.makeClient(host: host) + let (tracker, dir) = try Self.makeTracker(daily: 5.0) + defer { try? FileManager.default.removeItem(at: dir) } + + let router = ModelRouter( + localOrchestrator: ModelOrchestratorActor(engine: MockInferenceEngine()), + cloudClient: client, + options: ModelRouter.Options(strategy: .cloudOnly, costTracker: tracker) + ) + _ = try await router.route(request: GenerationRequest(prompt: "hi", maxTokens: 16), preferredModel: "unlisted/model") + #expect(abs(await tracker.getStats().dailyUsage - 0.25) < 1e-6) + } + + @Test("A-S6: CostTracker and CloudGate reservations prevent concurrent budget overspend and release cleanly") + func budgetReservationsPreventConcurrentOverspend() async throws { + let (tracker, dir) = try Self.makeTracker(daily: 0.10) + defer { try? FileManager.default.removeItem(at: dir) } + + let t1 = try #require(await tracker.reserve(estimatedCost: 0.08, scopes: [.session("s1")])) + #expect(await tracker.reserve(estimatedCost: 0.05, scopes: [.session("s1")]) == nil) + #expect(abs(await tracker.remaining(scopes: [.session("s1")]) - 0.02) < 1e-9) + await tracker.release(reservation: t1) + let t2 = try #require(await tracker.reserve(estimatedCost: 0.08, scopes: [.session("s1")])) + await tracker.release(reservation: t2) + + let gate = CloudGate(limits: ["m": 0.10], storage: nil) + let c1 = await gate.reserve("m", estimatedCost: 0.08) + #expect(c1.token != nil && c1.refusal == nil) + let c2 = await gate.reserve("m", estimatedCost: 0.05) + #expect(c2.token == nil && c2.refusal != nil) + if let tok = c1.token { await gate.release(tok) } + let c3 = await gate.reserve("m", estimatedCost: 0.08) + #expect(c3.token != nil && c3.refusal == nil) + } + + @Test("A-S6: concurrent CloudAnswer (priced & unpriced) and single-tier ModelRouter.route block overspend", .timeLimit(.minutes(1))) + func concurrentCloudAnswerAndSingleTierRouteBlockOverspend() async throws { + let req = GenerationRequest(prompt: "hi", maxTokens: 2_000) + for model in ["openai/gpt-4-turbo", "custom/unpriced-model"] { + try await Self.withGatedCloudClient { liveClient, gate in + let cloudGate = CloudGate(limits: [model: 0.08], storage: nil) + let answer = CloudAnswer(client: liveClient, model: model, gate: cloudGate) + let first = Task { try await answer.answer(req) } + await gate.waitForFirstArrival() + await #expect(throws: BasaltError.self) { _ = try await answer.answer(req) } + #expect(await gate.hits == 1) + await gate.releaseAll() + _ = try await first.value + } + } + try await Self.withGatedCloudClient { liveClient, gate in + let (tracker, dir) = try Self.makeTracker(daily: 0.08) + defer { try? FileManager.default.removeItem(at: dir) } + let modelRouter = ModelRouter( + localOrchestrator: ModelOrchestratorActor(engine: MockInferenceEngine()), + cloudClient: liveClient, + options: ModelRouter.Options(strategy: .cloudOnly, costTracker: tracker) + ) + let first = Task { try await modelRouter.route(request: req, preferredModel: "openai/gpt-4-turbo") } + await gate.waitForFirstArrival() + await #expect(throws: (any Error).self) { _ = try await modelRouter.route(request: req, preferredModel: "openai/gpt-4-turbo") } + #expect(await gate.hits == 1) + await gate.releaseAll() + _ = try await first.value + } + } +} + +extension CloudBudgetDefectRegressionTests { + + @Test("A-S10: assess is read-only & counts message prompt tokens; generate saves .strong and recordLocalOutcome saves .weak") + func assessIsReadOnlyAndSessionTierTracksBothSides() async throws { + let okPayload = #"{"id":"c1","model":"openai/gpt-4-turbo","choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":10,"total_tokens":20,"cost":0.01}}"# + let host = StubURLProtocol.host { _, _ in (200, ["Content-Type": "application/json"], Data(okPayload.utf8)) } + let client = try Self.makeClient(host: host) + let costRouting = ModelRouter.CostRouting( + policy: StickyRoutingPolicy(strongModel: "gpt-4", weakModel: "local", threshold: 0.5, cacheStickinessPenalty: 1.0), + scorer: try BradleyTerryRouterTests.scorer() + ) + let router = ModelRouter( + localOrchestrator: ModelOrchestratorActor(engine: MockInferenceEngine()), + cloudClient: client, + options: ModelRouter.Options(strategy: .hybrid, costRouting: costRouting, fallbackCloudModel: "gpt-4") + ) + let bigMessage = Array(repeating: BradleyTerryRouterTests.hardWord, count: 200).joined(separator: " ") + let req = GenerationRequest( + prompt: "", + maxTokens: 64, + messages: [ChatMessageInput(role: .user, text: bigMessage)] + ).withRouting(sessionId: "sess-ro", budgetKey: nil) + let completionOnlyCost = await router.estimateCost(model: "gpt-4", promptTokens: 0, completionTokens: 64) + let assessment = try #require(await router.assess(req, localModel: "local")) + #expect(assessment.estimatedCost > completionOnlyCost) + #expect(await router.sessionTier(for: "sess-ro") == nil) + let dummyLocal = GenerationResponse( + generatedText: "ok", promptTokens: 10, completionTokens: 5, tokensPerSecond: 20, generationTime: 0.1, + timeToFirstToken: 0.05, memory: .init(peakBytes: 0, activeBytes: 0, cacheBytes: 0), finishReason: .stop + ) + await router.recordLocalOutcome(req, response: dummyLocal, localModel: "local") + #expect(await router.sessionTier(for: "sess-ro") == .weak) + _ = try await router.generate(req) + #expect(await router.sessionTier(for: "sess-ro") == .strong) + await router.recordLocalOutcome(req, response: dummyLocal, localModel: "local") + #expect(await router.sessionTier(for: "sess-ro") == .weak) + } + + @Test("A-S11: CascadeRouting.runCascadeStream merges locally accepted tokens and TTFT into cloud stream metadata") + func cascadeStreamMergesLocalTokensAndTTFT() async throws { + let sse = """ + data: {"id":"1","model":"gpt-4","choices":[{"delta":{"content":"part2"},"finish_reason":null}]} + + data: {"id":"1","model":"gpt-4","choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":4,"total_tokens":24}} + + data: [DONE] + + """ + let host = StubURLProtocol.host { _, _ in (200, ["Content-Type": "text/event-stream"], Data(sse.utf8)) } + let client = try Self.makeClient(host: host) + let cascade = CascadeExecutionMode(segmentTokens: 6, alpha: 0.2, referenceBudget: 10.0, cloudModel: "gpt-4") + let router = ModelRouter( + localOrchestrator: ModelOrchestratorActor(engine: SegmentedLocalEngine()), + cloudClient: client, + options: ModelRouter.Options(strategy: .localOnly).withCascade(cascade) + ) + let stream = try await router.routeStream(request: GenerationRequest(prompt: "hi", maxTokens: 20), preferredModel: "local") + var finalMeta: GenerationResponse? + for try await chunk in stream { + if case .metadata(let m) = chunk { finalMeta = m } + } + let meta = try #require(finalMeta) + #expect(meta.completionTokens == 10) + #expect(meta.timeToFirstToken >= 0.08 - 1e-6) + } +} diff --git a/Tests/BasaltTests/RetroWave2Tests.swift b/Tests/BasaltTests/RetroWave2Tests.swift index 28effa4c8..eb09abe58 100644 --- a/Tests/BasaltTests/RetroWave2Tests.swift +++ b/Tests/BasaltTests/RetroWave2Tests.swift @@ -136,6 +136,6 @@ struct RetroWave2Tests { let req = ModelRouter.chatRequest(GenerationRequest(prompt: "hi"), model: "openai/gpt-4o-mini", stream: true) #expect(req.usage?.include == true) let nonStream = ModelRouter.chatRequest(GenerationRequest(prompt: "hi"), model: "openai/gpt-4o-mini", stream: false) - #expect(nonStream.usage == nil) + #expect(nonStream.usage?.include == true) } } From d28267b08a0f53a7f54a29c8f9416e97b3405a3c Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:11:42 +0100 Subject: [PATCH 4/6] fix(bench): fix metricx24 comparator, real TTFT/perplexity scoring, multi-task metrics, gateless pass, and explicit dataset errors (A-B5, A-B6, A-B7, A-B8, A-B12) --- Sources/BasaltBench/BenchmarkAdapter.swift | 16 +- Sources/BasaltBench/BenchmarkEndpoint.swift | 62 +++++ Sources/BasaltBench/BenchmarkRunner.swift | 44 ++- Sources/BasaltBench/BenchmarkSubmitter.swift | 2 +- .../BasaltBench/NativeBenchmarkAdapters.swift | 56 ++-- .../BasaltBench/NativePipelineAdapters.swift | 2 +- .../TranslationBenchmarkAdapter.swift | 20 +- Sources/BasaltCore/ModelLab+Distill.swift | 10 +- .../MLXInferenceEngine+Score.swift | 50 +++- .../BenchMetricsDefectRegressionTests.swift | 251 ++++++++++++++++++ 10 files changed, 450 insertions(+), 63 deletions(-) create mode 100644 Tests/BasaltTests/BenchMetricsDefectRegressionTests.swift diff --git a/Sources/BasaltBench/BenchmarkAdapter.swift b/Sources/BasaltBench/BenchmarkAdapter.swift index 1d2199931..4881ae1b1 100644 --- a/Sources/BasaltBench/BenchmarkAdapter.swift +++ b/Sources/BasaltBench/BenchmarkAdapter.swift @@ -99,11 +99,17 @@ public struct ExternalHarnessAdapter: BenchmarkAdapter { } public func run(context: BenchmarkTaskContext) async throws -> BenchmarkAdapterOutput { - if let dataset = context.task.dataset, - FileManager.default.fileExists(atPath: dataset), - let data = try? Data(contentsOf: URL(fileURLWithPath: dataset)), - let imported = try? JSONDecoder().decode([BenchmarkSampleRecord].self, from: data), - !imported.isEmpty { + if let dataset = context.task.dataset, !dataset.isEmpty { + let data: Data + do { + data = try Data(contentsOf: URL(fileURLWithPath: dataset)) + } catch { + throw BenchmarkError.invalidResponse("failed to read dataset '\(dataset)': \(error.localizedDescription)") + } + guard let imported = try? JSONDecoder().decode([BenchmarkSampleRecord].self, from: data), + !imported.isEmpty else { + throw BenchmarkError.invalidResponse("dataset '\(dataset)' is empty or malformed JSON") + } let accuracy = Double(imported.filter(\.passed).count) / Double(imported.count) let p50 = BenchmarkStats.percentile(imported.map(\.latencyMs), 0.5) return BenchmarkAdapterOutput(samples: imported, metrics: ["accuracy": accuracy, "p50_ms": p50]) diff --git a/Sources/BasaltBench/BenchmarkEndpoint.swift b/Sources/BasaltBench/BenchmarkEndpoint.swift index e02716104..315ee081a 100644 --- a/Sources/BasaltBench/BenchmarkEndpoint.swift +++ b/Sources/BasaltBench/BenchmarkEndpoint.swift @@ -93,6 +93,9 @@ public struct BenchmarkEndpoint: Sendable { if let apiKey, !apiKey.isEmpty { urlReq.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") } for (k, v) in req.headers { urlReq.setValue(v, forHTTPHeaderField: k) } let start = ContinuousClock.now + if Self.requestsStreaming(req.body) { + return try await Self.sendStreaming(urlReq, started: start) + } let (data, response) = try await URLSession.shared.data(for: urlReq) let elapsed = start.duration(to: ContinuousClock.now) let ms = Double(elapsed.components.seconds) * 1000.0 + Double(elapsed.components.attoseconds) * 1e-15 @@ -105,6 +108,65 @@ public struct BenchmarkEndpoint: Sendable { } } + private static func requestsStreaming(_ body: Data?) -> Bool { + guard let body, + let json = try? JSONSerialization.jsonObject(with: body) as? [String: Any], + let stream = json["stream"] as? Bool else { + return false + } + return stream + } + + private static func elapsedMs(since start: ContinuousClock.Instant) -> Double { + let elapsed = start.duration(to: ContinuousClock.now) + return max(0.01, Double(elapsed.components.seconds) * 1000.0 + Double(elapsed.components.attoseconds) * 1e-15) + } + + private static func sendStreaming( + _ urlReq: URLRequest, + started: ContinuousClock.Instant + ) async throws -> BenchmarkHTTPResponse { + let (bytes, response) = try await URLSession.shared.bytes(for: urlReq) + let http = response as? HTTPURLResponse + let status = http?.statusCode ?? 0 + var headers: [String: String] = [:] + for (key, value) in http?.allHeaderFields ?? [:] { + if let k = key as? String, let v = value as? String { headers[k] = v } + } + guard (200 ... 299).contains(status) else { + var raw = Data() + for try await byte in bytes { raw.append(byte) } + return BenchmarkHTTPResponse(statusCode: status, headers: headers, body: raw, totalMs: elapsedMs(since: started)) + } + var content = "" + var usage: [String: Any] = [:] + var ttftMs: Double? + for try await line in bytes.lines { + guard line.hasPrefix("data:") else { continue } + let payload = String(line.dropFirst(5)).trimmingCharacters(in: .whitespaces) + if payload.isEmpty || payload == "[DONE]" { continue } + guard let chunk = try? JSONSerialization.jsonObject(with: Data(payload.utf8)) as? [String: Any] else { continue } + if let chunkUsage = chunk["usage"] as? [String: Any] { usage = chunkUsage } + let delta = Self.extractStreamDelta(chunk) + if ttftMs == nil, delta.hasToken { ttftMs = elapsedMs(since: started) } + if !delta.content.isEmpty { content += delta.content } + } + var assembled: [String: Any] = ["choices": [["message": ["role": "assistant", "content": content]]]] + if !usage.isEmpty { assembled["usage"] = usage } + let body = try JSONSerialization.data(withJSONObject: assembled, options: [.sortedKeys]) + return BenchmarkHTTPResponse(statusCode: status, headers: headers, body: body, ttftMs: ttftMs, totalMs: elapsedMs(since: started)) + } + + private static func extractStreamDelta(_ chunk: [String: Any]) -> (content: String, hasToken: Bool) { + guard let choices = chunk["choices"] as? [[String: Any]], + let delta = choices.first?["delta"] as? [String: Any] else { + return ("", false) + } + let text = delta["content"] as? String ?? "" + let reasoning = (delta["reasoning_content"] as? String) ?? (delta["reasoning"] as? String) ?? "" + return (text, !text.isEmpty || !reasoning.isEmpty) + } + public func postJSON(_ path: String, payload: Any) async throws -> (json: [String: Any], response: BenchmarkHTTPResponse) { let body = try JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) let reply = try await send(BenchmarkHTTPRequest(method: "POST", path: path, body: body)) diff --git a/Sources/BasaltBench/BenchmarkRunner.swift b/Sources/BasaltBench/BenchmarkRunner.swift index ce202b81a..32daad6b9 100644 --- a/Sources/BasaltBench/BenchmarkRunner.swift +++ b/Sources/BasaltBench/BenchmarkRunner.swift @@ -62,26 +62,20 @@ public struct BenchmarkRunner: Sendable { let started = ContinuousClock.now var allSamples: [BenchmarkSampleRecord] = [] var mergedMetrics: [String: Double] = [:] + var metricSums: [String: Double] = [:] + var metricCounts: [String: Int] = [:] var allGateResults: [BenchmarkGateResult] = [] var totalExtraCost = 0.0 for (index, task) in suite.tasks.enumerated() { try Task.checkCancellation() try checkSuiteBudget(suite.budget, started: started, samples: allSamples, extraCost: totalExtraCost) - guard let adapter = registry.adapter(for: task.adapter) else { - throw BenchmarkError.unknownAdapter(task.adapter) - } - let context = BenchmarkTaskContext( - spec: request.spec, suiteName: request.suiteName, - task: task, defaults: defaults, endpoint: request.endpoint - ) + guard let adapter = registry.adapter(for: task.adapter) else { throw BenchmarkError.unknownAdapter(task.adapter) } + let context = BenchmarkTaskContext(spec: request.spec, suiteName: request.suiteName, task: task, defaults: defaults, endpoint: request.endpoint) let output = try await adapter.run(context: context) allSamples += Self.taggedSamples(output.samples, index: index, multiTask: suite.tasks.count > 1) totalExtraCost += output.extraCostUSD - for (k, v) in output.metrics { mergedMetrics[k] = v } - let taskCard = BenchmarkScorecard.evaluate( - metrics: output.metrics, gates: task.gates, - samples: output.samples, extraCostUSD: output.extraCostUSD - ) + Self.mergeMetrics(output.metrics, index: index, multiTask: suite.tasks.count > 1, sums: &metricSums, counts: &metricCounts, into: &mergedMetrics) + let taskCard = BenchmarkScorecard.evaluate(metrics: output.metrics, gates: task.gates, samples: output.samples, extraCostUSD: output.extraCostUSD) allGateResults += taskCard.gates.map { gate in var tagged = gate if suite.tasks.count > 1 { tagged.gate = "task[\(index)].\(gate.gate)" } @@ -145,14 +139,20 @@ public struct BenchmarkRunner: Sendable { ) -> BenchmarkRunArtifact { var finalMetrics = summary.metrics if !summary.samples.isEmpty { - finalMetrics["pass_rate"] = Double(summary.samples.filter(\.passed).count) / Double(summary.samples.count) + let passRate = Double(summary.samples.filter(\.passed).count) / Double(summary.samples.count) + finalMetrics["pass_rate"] = passRate + if suite.tasks.count > 1, finalMetrics["accuracy"] != nil { + finalMetrics["accuracy"] = passRate + } finalMetrics["p50_ms"] = BenchmarkStats.percentile(summary.samples.map(\.latencyMs), 0.5) } var scorecard = BenchmarkScorecard.evaluate( metrics: finalMetrics, gates: nil, samples: summary.samples, extraCostUSD: summary.extraCost ) scorecard.gates = summary.gates - scorecard.passed = summary.gates.allSatisfy(\.passed) + scorecard.passed = summary.gates.isEmpty + ? (!summary.samples.isEmpty && summary.samples.allSatisfy(\.passed)) + : summary.gates.allSatisfy(\.passed) var manifest = BenchmarkManifest( runID: request.runID, composeName: request.spec.name, suite: request.suiteName, seed: defaults.seed ?? 42, temperature: defaults.temperature ?? 0.0, @@ -199,4 +199,20 @@ private extension BenchmarkRunner { return tagged } } + + static func mergeMetrics( + _ metrics: [String: Double], + index: Int, + multiTask: Bool, + sums: inout [String: Double], + counts: inout [String: Int], + into merged: inout [String: Double] + ) { + for (key, value) in metrics { + if multiTask { merged["task[\(index)].\(key)"] = value } + sums[key, default: 0] += value + counts[key, default: 0] += 1 + merged[key] = sums[key, default: 0] / Double(counts[key, default: 1]) + } + } } diff --git a/Sources/BasaltBench/BenchmarkSubmitter.swift b/Sources/BasaltBench/BenchmarkSubmitter.swift index 6651aba4b..44f8f2964 100644 --- a/Sources/BasaltBench/BenchmarkSubmitter.swift +++ b/Sources/BasaltBench/BenchmarkSubmitter.swift @@ -122,7 +122,7 @@ public struct BenchmarkComparisonReport: Sendable, Equatable, Codable { public enum BenchmarkComparator { static let lowerIsBetter: Set = [ "ttft_ms", "p50_ms", "p95_ms", "peak_gb", "ppl", "ece", - "cost_usd", "cost_per_1k_usd", "abstain_rate", + "cost_usd", "cost_per_1k_usd", "abstain_rate", "metricx24", ] private static func metricDelta( diff --git a/Sources/BasaltBench/NativeBenchmarkAdapters.swift b/Sources/BasaltBench/NativeBenchmarkAdapters.swift index bce3e835b..dda82e0e1 100644 --- a/Sources/BasaltBench/NativeBenchmarkAdapters.swift +++ b/Sources/BasaltBench/NativeBenchmarkAdapters.swift @@ -81,15 +81,18 @@ public struct BasaltThroughputAdapter: BenchmarkAdapter { "max_tokens": maxTokens, "temperature": context.temperature, "seed": context.seed, + "stream": true, + "stream_options": ["include_usage": true], ] let (json, reply) = try await context.endpoint.postJSON("/v1/chat/completions", payload: payload) let content = BenchmarkStats.extractChatContent(json) let usage = BenchmarkStats.extractUsage(json) let completion = max(1, usage.completion > 0 ? usage.completion : max(1, content.split(separator: " ").count)) - let tps = (json["decode_tps"] as? Double) ?? (Double(completion) / max(0.001, reply.totalMs / 1000.0)) - let ttft = reply.ttftMs ?? (json["ttft_ms"] as? Double) ?? (reply.totalMs * 0.15) + let ttft = reply.ttftMs ?? (json["ttft_ms"] as? Double) + let decodeMs = max(1.0, reply.totalMs - (ttft ?? 0.0)) + let tps = (json["decode_tps"] as? Double) ?? (Double(completion) / (decodeMs / 1000.0)) tpsValues.append(tps) - ttfts.append(ttft) + if let ttft { ttfts.append(ttft) } var record = BenchmarkSampleRecord( id: "throughput-\(idx)", adapter: id, model: context.resolvedModelName, prompt: basePrompt, answer: content, score: content.isEmpty ? 0 : 1 @@ -105,11 +108,13 @@ public struct BasaltThroughputAdapter: BenchmarkAdapter { } var metrics: [String: Double] = [ "decode_tps": BenchmarkStats.percentile(tpsValues, 0.5), - "ttft_ms": BenchmarkStats.percentile(ttfts, 0.5), "p50_ms": BenchmarkStats.percentile(samples.map(\.latencyMs), 0.5), "p95_ms": BenchmarkStats.percentile(samples.map(\.latencyMs), 0.95), "accuracy": Double(samples.filter(\.passed).count) / Double(max(1, samples.count)), ] + if !ttfts.isEmpty { + metrics["ttft_ms"] = BenchmarkStats.percentile(ttfts, 0.5) + } if let peakGB = await fetchPeakGB(endpoint: context.endpoint) { metrics["peak_gb"] = peakGB } @@ -166,7 +171,7 @@ public struct BasaltSystemOneAdapter: BenchmarkAdapter { ] public func run(context: BenchmarkTaskContext) async throws -> BenchmarkAdapterOutput { - let probes = loadProbes(path: context.task.dataset) + let probes = try loadProbes(path: context.task.dataset) var samples: [BenchmarkSampleRecord] = [] var calibrationPairs: [(confidence: Double, correct: Bool)] = [] var abstains = 0 @@ -215,10 +220,16 @@ public struct BasaltSystemOneAdapter: BenchmarkAdapter { return BenchmarkAdapterOutput(samples: samples, metrics: metrics) } - func loadProbes(path: String?) -> [ProbeItem] { - guard let path, let data = try? Data(contentsOf: URL(fileURLWithPath: path)), - let decoded = try? JSONDecoder().decode([ProbeItem].self, from: data), !decoded.isEmpty else { - return Self.defaultProbes + func loadProbes(path: String?) throws -> [ProbeItem] { + guard let path, !path.isEmpty else { return Self.defaultProbes } + let data: Data + do { + data = try Data(contentsOf: URL(fileURLWithPath: path)) + } catch { + throw BenchmarkError.invalidResponse("failed to read system-one dataset '\(path)': \(error.localizedDescription)") + } + guard let decoded = try? JSONDecoder().decode([ProbeItem].self, from: data), !decoded.isEmpty else { + throw BenchmarkError.invalidResponse("system-one dataset '\(path)' is empty or malformed JSON") } return decoded } @@ -232,17 +243,17 @@ public struct BasaltPerplexityAdapter: BenchmarkAdapter { public init() {} public func run(context: BenchmarkTaskContext) async throws -> BenchmarkAdapterOutput { + let prompt = context.task.params["prompt"]?.stringValue ?? "Continue:" let text = context.task.params["text"]?.stringValue ?? "Apple Silicon unified memory shares physical DRAM pages between CPU, Metal GPU, and the Neural Engine." let payload: [String: Any] = [ - "model": context.resolvedModelName, - "messages": [["role": "user", "content": text]], - "max_tokens": context.task.params["max_tokens"]?.intValue ?? 16, - "temperature": 0.0, - "logprobs": true, + "messages": [["role": "user", "content": prompt]], + "completion": [] as [Int], + "completion_text": text, + "top_logprobs": 1, ] - let (json, reply) = try await context.endpoint.postJSON("/v1/chat/completions", payload: payload) - let nll = Self.extractMeanNLL(json) + let (json, reply) = try await context.endpoint.postJSON("/v1/score", payload: payload) + let nll = try Self.extractMeanNLL(json) let ppl = exp(min(20.0, max(0.0, nll))) var sample = BenchmarkSampleRecord( id: "ppl-0", adapter: id, model: context.resolvedModelName, @@ -253,15 +264,10 @@ public struct BasaltPerplexityAdapter: BenchmarkAdapter { return BenchmarkAdapterOutput(samples: [sample], metrics: ["ppl": ppl, "p50_ms": reply.totalMs]) } - static func extractMeanNLL(_ json: [String: Any]) -> Double { - if let direct = json["nll"] as? Double, direct >= 0 { return direct } - guard let choices = json["choices"] as? [[String: Any]], - let logprobs = choices.first?["logprobs"] as? [String: Any], - let content = logprobs["content"] as? [[String: Any]], !content.isEmpty else { - return 1.5 + static func extractMeanNLL(_ json: [String: Any]) throws -> Double { + if let direct = (json["mean_nll"] as? Double) ?? (json["nll"] as? Double), direct.isFinite, direct >= 0 { + return direct } - let values = content.compactMap { $0["logprob"] as? Double } - guard !values.isEmpty else { return 1.5 } - return -values.reduce(0, +) / Double(values.count) + throw BenchmarkError.invalidResponse("perplexity /v1/score response missing finite non-negative mean_nll") } } diff --git a/Sources/BasaltBench/NativePipelineAdapters.swift b/Sources/BasaltBench/NativePipelineAdapters.swift index 02670d404..dc47a61ed 100644 --- a/Sources/BasaltBench/NativePipelineAdapters.swift +++ b/Sources/BasaltBench/NativePipelineAdapters.swift @@ -79,7 +79,7 @@ public struct BasaltMoMAdapter: BenchmarkAdapter { let cost = stages.reduce(0.0) { $0 + (($1["cost"] as? Double) ?? 0.0) } let tokens = stages.reduce(0) { $0 + (($1["tokens"] as? Int) ?? 0) } let system2 = (json["system2"] as? [String: Any])?["text"] as? String ?? label - let matched = label.isEmpty ? !system2.isEmpty : (label == expectedLabel) + let matched = !label.isEmpty && label == expectedLabel var sample = BenchmarkSampleRecord( id: "mom-0", adapter: id, model: context.task.target, prompt: promptText, answer: system2, score: matched ? 1.0 : 0.0 diff --git a/Sources/BasaltBench/TranslationBenchmarkAdapter.swift b/Sources/BasaltBench/TranslationBenchmarkAdapter.swift index 80069e919..700fef726 100644 --- a/Sources/BasaltBench/TranslationBenchmarkAdapter.swift +++ b/Sources/BasaltBench/TranslationBenchmarkAdapter.swift @@ -222,7 +222,7 @@ public struct TranslationBenchmarkAdapter: BenchmarkAdapter { let isFull = mode == "full" let qeMode = context.task.params["qe_mode"]?.stringValue ?? (isFull ? "llm_judge" : "proxy") let judgeModel = context.task.params["judge_model"]?.stringValue ?? context.resolvedModelName - let items = loadItems(context: context, isFull: isFull) + let items = try loadItems(context: context, isFull: isFull) var samples: [BenchmarkSampleRecord] = [] var chrfValues: [Double] = [] @@ -275,11 +275,15 @@ public struct TranslationBenchmarkAdapter: BenchmarkAdapter { return BenchmarkAdapterOutput(samples: samples, metrics: metrics) } - private func loadItems(context: BenchmarkTaskContext, isFull: Bool) -> [TranslationProbeItem] { + private func loadItems(context: BenchmarkTaskContext, isFull: Bool) throws -> [TranslationProbeItem] { var items: [TranslationProbeItem] = [] - if let path = context.task.dataset, - FileManager.default.fileExists(atPath: path), - let raw = try? String(contentsOfFile: path, encoding: .utf8) { + if let path = context.task.dataset, !path.isEmpty { + let raw: String + do { + raw = try String(contentsOfFile: path, encoding: .utf8) + } catch { + throw BenchmarkError.invalidResponse("failed to read translation dataset '\(path)': \(error.localizedDescription)") + } let decoder = JSONDecoder() for line in raw.split(separator: "\n") { if let data = String(line).data(using: .utf8), @@ -287,8 +291,12 @@ public struct TranslationBenchmarkAdapter: BenchmarkAdapter { items.append(decoded) } } + guard !items.isEmpty else { + throw BenchmarkError.invalidResponse("translation dataset '\(path)' contained no valid JSONL entries") + } + } else { + items = Self.builtinProbes } - if items.isEmpty { items = Self.builtinProbes } if let filterRaw = context.task.params["locales"]?.stringValue { let allowed = Set(filterRaw.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }) if !allowed.isEmpty { items = items.filter { allowed.contains($0.targetLang) } } diff --git a/Sources/BasaltCore/ModelLab+Distill.swift b/Sources/BasaltCore/ModelLab+Distill.swift index 605085604..38580f389 100644 --- a/Sources/BasaltCore/ModelLab+Distill.swift +++ b/Sources/BasaltCore/ModelLab+Distill.swift @@ -90,16 +90,19 @@ public struct ScoreRequest: Sendable, Codable, Equatable { public var messages: [[String: String]] public var completion: [Int] public var topLogprobs: Int + public var completionText: String? enum CodingKeys: String, CodingKey { case messages, completion case topLogprobs = "top_logprobs" + case completionText = "completion_text" } - public init(messages: [[String: String]], completion: [Int], topLogprobs: Int) { + public init(messages: [[String: String]], completion: [Int], topLogprobs: Int, completionText: String? = nil) { self.messages = messages self.completion = completion self.topLogprobs = topLogprobs + self.completionText = completionText } } @@ -117,15 +120,18 @@ public struct ScoreReport: Sendable, Codable, Equatable { public var tokenizer: String public var promptTokens: Int public var positions: [TopLogprobs] + public var meanNLL: Double? enum CodingKeys: String, CodingKey { case tokenizer, positions case promptTokens = "prompt_tokens" + case meanNLL = "mean_nll" } - public init(tokenizer: String, promptTokens: Int, positions: [TopLogprobs]) { + public init(tokenizer: String, promptTokens: Int, positions: [TopLogprobs], meanNLL: Double? = nil) { self.tokenizer = tokenizer self.promptTokens = promptTokens self.positions = positions + self.meanNLL = meanNLL } } diff --git a/Sources/BasaltInference/MLXInferenceEngine+Score.swift b/Sources/BasaltInference/MLXInferenceEngine+Score.swift index 6a1b7b431..05e018549 100644 --- a/Sources/BasaltInference/MLXInferenceEngine+Score.swift +++ b/Sources/BasaltInference/MLXInferenceEngine+Score.swift @@ -22,36 +22,68 @@ extension MLXInferenceEngine { guard !request.messages.isEmpty, request.messages.allSatisfy({ $0["role"] != nil && $0["content"] != nil }) else { throw refused("messages must be a non-empty array of {\"role\": …, \"content\": …}") } - guard scoreTokens.contains(request.completion.count) else { throw refused("completion must hold \(scoreTokens) token ids") } + let hasText = !(request.completionText ?? "").isEmpty + guard scoreTokens.contains(request.completion.count) || (request.completion.isEmpty && hasText) else { + throw refused("completion must hold \(scoreTokens) token ids (or provide completion_text)") + } guard scoreTopK.contains(request.topLogprobs) else { throw refused("top_logprobs must be in \(scoreTopK)") } } static func score(_ request: ScoreRequest, model: any LanguageModel, tokenizer: any Tokenizer) throws -> ScoreReport { + let completion: [Int] + if !request.completion.isEmpty { + completion = request.completion + } else if let text = request.completionText, !text.isEmpty { + completion = tokenizer.encode(text: text, addSpecialTokens: false) + guard scoreTokens.contains(completion.count) else { + throw BasaltError.invalidRequestStructure(details: "score: completion_text tokenized to \(completion.count) tokens, expected \(scoreTokens)") + } + } else { + throw BasaltError.invalidRequestStructure(details: "score: completion or completion_text is required") + } let vocabulary = 0 ..< vocabularySize(model) - guard request.completion.allSatisfy(vocabulary.contains), request.topLogprobs <= vocabulary.count else { + guard completion.allSatisfy(vocabulary.contains), request.topLogprobs <= vocabulary.count else { throw BasaltError.invalidRequestStructure(details: "score: completion ids and top_logprobs must be below the vocabulary size \(vocabulary.upperBound)") } let prompt = try labPrompt(messages: request.messages, tokenizer) guard !prompt.isEmpty else { throw BasaltError.invalidRequestStructure(details: "score: the chat template rendered the messages to no tokens") } - let positions = try topLogprobs(prompt: prompt, completion: request.completion, k: request.topLogprobs, model: model) - return ScoreReport(tokenizer: tokenizerFingerprint(tokenizer), promptTokens: prompt.count, positions: positions) + let scored = try scorePositions(prompt: prompt, completion: completion, k: request.topLogprobs, model: model) + return ScoreReport(tokenizer: tokenizerFingerprint(tokenizer), promptTokens: prompt.count, positions: scored.positions, meanNLL: scored.meanNLL) } static func topLogprobs(prompt: [Int], completion: [Int], k: Int, model: any LanguageModel, chunk: Int = scoreChunk) throws -> [TopLogprobs] { + try scorePositions(prompt: prompt, completion: completion, k: k, model: model, chunk: chunk).positions + } + + static func scorePositions( + prompt: [Int], completion: [Int], k: Int, model: any LanguageModel, chunk: Int = scoreChunk + ) throws -> (positions: [TopLogprobs], meanNLL: Double) { let cache = try model.newCache(parameters: nil) if prompt.count > 1 { _ = model(MLXArray(prompt.dropLast().map(Int32.init))[.newAxis], cache: cache) } let inputs = [prompt[prompt.count - 1]] + completion.dropLast() - return stride(from: 0, to: inputs.count, by: chunk).flatMap { start in - let ids = inputs[start ..< min(start + chunk, inputs.count)].map(Int32.init) - return topK(model(MLXArray(ids)[.newAxis], cache: cache)[0].asType(.float32), k: k) + var positions: [TopLogprobs] = [] + positions.reserveCapacity(inputs.count) + var nllSum = 0.0 + for start in stride(from: 0, to: inputs.count, by: chunk) { + let end = min(start + chunk, inputs.count) + let ids = inputs[start ..< end].map(Int32.init) + let logits = model(MLXArray(ids)[.newAxis], cache: cache)[0].asType(.float32) + let logprobs = logits - logSumExp(logits, axis: -1, keepDims: true) + let targets = MLXArray(completion[start ..< end].map(Int32.init))[0..., .newAxis] + nllSum -= Double(takeAlong(logprobs, targets, axis: -1).sum().item(Float.self)) + positions.append(contentsOf: topK(fromLogprobs: logprobs, k: k)) } + return (positions, nllSum / Double(max(1, completion.count))) } static func topK(_ logits: MLXArray, k: Int) -> [TopLogprobs] { - let logprobs = logits - logSumExp(logits, axis: -1, keepDims: true) + topK(fromLogprobs: logits - logSumExp(logits, axis: -1, keepDims: true), k: k) + } + + static func topK(fromLogprobs logprobs: MLXArray, k: Int) -> [TopLogprobs] { let candidates = argPartition(-logprobs, kth: k - 1, axis: -1)[0..., .. (values[$1], -ids[$1]) } return TopLogprobs(ids: ranked.map { Int(ids[$0]) }, logprobs: ranked.map { values[$0] }) } diff --git a/Tests/BasaltTests/BenchMetricsDefectRegressionTests.swift b/Tests/BasaltTests/BenchMetricsDefectRegressionTests.swift new file mode 100644 index 000000000..10fb91dfa --- /dev/null +++ b/Tests/BasaltTests/BenchMetricsDefectRegressionTests.swift @@ -0,0 +1,251 @@ +import Foundation +import Hummingbird +import HummingbirdTesting +import MLX +import MLXLMCommon +import NIOCore +import Testing +@testable import BasaltBench +@testable import BasaltCore +@testable import BasaltInference + +@Suite("BasaltBench metric, comparator, runner, and dataset regressions (A-B5, A-B6, A-B7, A-B8, A-B12)") +struct BenchMetricsDefectRegressionTests { + static func makeSpec() -> ComposeSpec { + ComposeSpec(name: "bench-defects", models: ["chat": ComposeSpec.Model(source: .local("org/m"))], answer: "chat") + } + + static func makeProvenance() -> BasaltProvenance { + BasaltProvenance(gitCommit: "a", composeSHA256: "b", chip: "M4", unifiedMemoryGB: 24, timestampISO8601: "2026-11-25T00:00:00Z") + } + + @Test("A-B5: basalt:throughput streams for real TTFT, excludes prefill from decode_tps, and never fabricates 0.15 * totalMs") + func throughputDoesNotFabricateTTFTAndExcludesPrefill() async throws { + let endpoint = BenchmarkEndpoint.mock { req in + if req.path.hasSuffix("/stats") { + return BenchmarkHTTPResponse(statusCode: 404, body: Data()) + } + let reqJSON = try #require(req.body.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }) + #expect(reqJSON["stream"] as? Bool == true) + let payload: [String: Any] = [ + "choices": [["message": ["role": "assistant", "content": "ok"]]], + "usage": ["prompt_tokens": 100, "completion_tokens": 20], + ] + let body = try JSONSerialization.data(withJSONObject: payload) + return BenchmarkHTTPResponse(body: body, ttftMs: nil, totalMs: 500.0) + } + let task = BenchmarkTaskSpec(adapter: "basalt:throughput", target: "model:chat", params: ["iterations": .int(1)]) + let ctx = BenchmarkTaskContext(spec: Self.makeSpec(), suiteName: "s", task: task, defaults: BenchmarkDefaultsSpec(), endpoint: endpoint) + let out = try await BasaltThroughputAdapter().run(context: ctx) + #expect(out.metrics["ttft_ms"] == nil) + #expect(out.samples.first?.ttftMs == nil) + + let timedEndpoint = BenchmarkEndpoint.mock { req in + if req.path.hasSuffix("/stats") { return BenchmarkHTTPResponse(statusCode: 404, body: Data()) } + let payload: [String: Any] = [ + "choices": [["message": ["role": "assistant", "content": "ok"]]], + "usage": ["prompt_tokens": 100, "completion_tokens": 20], + ] + return BenchmarkHTTPResponse(body: try JSONSerialization.data(withJSONObject: payload), ttftMs: 800.0, totalMs: 1000.0) + } + let timedCtx = BenchmarkTaskContext(spec: Self.makeSpec(), suiteName: "s", task: task, defaults: BenchmarkDefaultsSpec(), endpoint: timedEndpoint) + let timedOut = try await BasaltThroughputAdapter().run(context: timedCtx) + #expect(timedOut.metrics["ttft_ms"] == 800.0) + #expect(abs((timedOut.metrics["decode_tps"] ?? 0) - 100.0) < 1e-6) + } + + @Test("A-B5: BenchmarkEndpoint.live streaming TTFT fires on first reasoning_content or content delta") + func streamingTTFTStartsAtReasoningOrContentDelta() async throws { + let router = Router() + router.post("/v1/chat/completions") { _, _ in + let sse = """ + data: {"choices":[{"delta":{"reasoning_content":"step 1"}}]} + + data: {"choices":[{"delta":{"content":"hello "}}]} + + data: {"choices":[{"delta":{"content":"world"}}],"usage":{"prompt_tokens":10,"completion_tokens":2}} + + data: [DONE] + + """ + return Response(status: .ok, headers: [.contentType: "text/event-stream"], body: .init(byteBuffer: ByteBuffer(string: sse))) + } + router.post("/v1/reasoning-only") { _, _ in + let sse = "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"only reasoning\"}}]}\n\ndata: [DONE]\n\n" + return Response(status: .ok, headers: [.contentType: "text/event-stream"], body: .init(byteBuffer: ByteBuffer(string: sse))) + } + try await Application(router: router).test(.live) { client in + let port = try #require(client.port) + let live = BenchmarkEndpoint.live(baseURL: try #require(URL(string: "http://localhost:\(port)"))) + let (json, reply) = try await live.postJSON("/v1/chat/completions", payload: ["model": "m", "stream": true]) + #expect(reply.ttftMs != nil && (reply.ttftMs ?? 0) > 0) + #expect(BenchmarkStats.extractChatContent(json) == "hello world") + #expect(BenchmarkStats.extractUsage(json).completion == 2) + let (_, reasoningReply) = try await live.postJSON("/v1/reasoning-only", payload: ["model": "m", "stream": true]) + #expect(reasoningReply.ttftMs != nil && (reasoningReply.ttftMs ?? 0) > 0) + } + } + + @Test("A-B6: basalt:perplexity scores held-out text via /v1/score mean_nll and fails when mean_nll is absent") + func perplexityScoresHeldOutTextViaScoreEndpoint() async throws { + let scoring = BenchmarkEndpoint.mock { req in + #expect(req.path == "/v1/score") + let body = try #require(req.body.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }) + #expect(body["completion_text"] as? String == "held-out text") + return BenchmarkHTTPResponse(body: try JSONSerialization.data(withJSONObject: ["mean_nll": 2.0]), totalMs: 12.0) + } + let task = BenchmarkTaskSpec(adapter: "basalt:perplexity", target: "model:chat", params: ["text": .string("held-out text")]) + let ctx = BenchmarkTaskContext(spec: Self.makeSpec(), suiteName: "s", task: task, defaults: BenchmarkDefaultsSpec(), endpoint: scoring) + let out = try await BasaltPerplexityAdapter().run(context: ctx) + #expect(abs((out.metrics["ppl"] ?? 0) - exp(2.0)) < 1e-6) + + let missing = BenchmarkEndpoint.mock { _ in + BenchmarkHTTPResponse(body: try JSONSerialization.data(withJSONObject: ["positions": []]), totalMs: 10.0) + } + let missingCtx = BenchmarkTaskContext(spec: Self.makeSpec(), suiteName: "s", task: task, defaults: BenchmarkDefaultsSpec(), endpoint: missing) + await #expect(throws: BenchmarkError.self) { + _ = try await BasaltPerplexityAdapter().run(context: missingCtx) + } + + let model = try TinyModel.make(.qwen3) + let tokenizer = ByteTokenizer() + let text = "abcdef" + let ids = tokenizer.encode(text: text, addSpecialTokens: false) + let prompt = try MLXInferenceEngine.labPrompt(messages: [["role": "user", "content": "hi"]], tokenizer) + let fullSeq = prompt + ids + let fullLogits = model(MLXArray(fullSeq.dropLast().map(Int32.init))[.newAxis], cache: nil)[0].asType(.float32) + let slice = fullLogits[(prompt.count - 1)...] + let logProbs = slice - logSumExp(slice, axis: -1, keepDims: true) + let targets = MLXArray(ids.map(Int32.init))[0..., .newAxis] + let refNLL = -Double(takeAlong(logProbs, targets, axis: -1).mean().item(Float.self)) + + let report = try MLXInferenceEngine.score( + ScoreRequest(messages: [["role": "user", "content": "hi"]], completion: ids, topLogprobs: 2), + model: model, + tokenizer: tokenizer + ) + let textReport = try MLXInferenceEngine.score( + ScoreRequest(messages: [["role": "user", "content": "hi"]], completion: [], topLogprobs: 2, completionText: text), + model: model, + tokenizer: tokenizer + ) + let chunked = try MLXInferenceEngine.scorePositions(prompt: prompt, completion: ids, k: 2, model: model, chunk: 2) + #expect(abs((report.meanNLL ?? 0) - refNLL) < 1e-4) + #expect(abs((textReport.meanNLL ?? 0) - refNLL) < 1e-4) + #expect(abs(chunked.meanNLL - refNLL) < 1e-4) + } +} + +extension BenchMetricsDefectRegressionTests { + + @Test("A-B7: BenchmarkComparator treats metricx24 as lower-is-better") + func metricX24IsLowerIsBetter() { + let prov = Self.makeProvenance() + let base = BenchmarkRunArtifact( + manifest: BenchmarkManifest(runID: "base", composeName: "c", suite: "s", endpoint: "http://127.0.0.1"), + provenance: prov, + scorecard: BenchmarkScorecard(metrics: ["metricx24": 2.0], passed: true), + samples: [] + ) + let worse = BenchmarkRunArtifact( + manifest: BenchmarkManifest(runID: "worse", composeName: "c", suite: "s", endpoint: "http://127.0.0.1"), + provenance: prov, + scorecard: BenchmarkScorecard(metrics: ["metricx24": 4.0], passed: true), + samples: [] + ) + let regressed = BenchmarkComparator.compare(baseline: base, candidate: worse) + #expect(regressed.deltas.first?.regressed == true && regressed.deltas.first?.improved == false) + + let better = BenchmarkRunArtifact( + manifest: BenchmarkManifest(runID: "better", composeName: "c", suite: "s", endpoint: "http://127.0.0.1"), + provenance: prov, + scorecard: BenchmarkScorecard(metrics: ["metricx24": 1.0], passed: true), + samples: [] + ) + let improved = BenchmarkComparator.compare(baseline: base, candidate: better) + #expect(improved.deltas.first?.improved == true && improved.deltas.first?.regressed == false) + } + + @Test("A-B8 & A-B12: multi-task suites preserve per-task metrics, gateless failing suites fail, explicit missing datasets throw, and basalt:mom fails on empty route") + func multiTaskMetricsGatelessFailAndExplicitDatasetValidation() async throws { + var spec = Self.makeSpec() + spec.benchmarks = ComposeBenchmarksSpec( + defaults: BenchmarkDefaultsSpec(gpuLock: false), + suites: [ + "multi": BenchmarkSuiteSpec( + tasks: [ + BenchmarkTaskSpec(adapter: "basalt:mom", target: "pipeline"), + BenchmarkTaskSpec(adapter: "basalt:system-one", target: "pipeline"), + ] + ), + ] + ) + let failingEndpoint = BenchmarkEndpoint.mock { req in + if req.path == "/v1/systemone" { + let body = try JSONSerialization.data(withJSONObject: ["answers": ["route": ["choice": "wrong", "confidence": 0.9]]]) + return BenchmarkHTTPResponse(body: body, totalMs: 5.0) + } + let body = try JSONSerialization.data(withJSONObject: ["answers": [:], "system2": ["text": "answered without route"]]) + return BenchmarkHTTPResponse(body: body, totalMs: 5.0) + } + let req = BenchmarkSuiteRunRequest(spec: spec, composeYAML: "", suiteName: "multi", endpoint: failingEndpoint, runID: "r1") + let artifact = try await BenchmarkRunner().run(req) + #expect(!artifact.scorecard.passed) + #expect(artifact.scorecard.metrics["task[0].accuracy"] == 0.0) + #expect(artifact.scorecard.metrics["task[1].accuracy"] == 0.0) + + let mixedEndpoint = BenchmarkEndpoint.mock { req in + if req.path == "/v1/systemone" { + let body = try JSONSerialization.data(withJSONObject: ["answers": ["route": ["choice": "wrong", "confidence": 0.9]]]) + return BenchmarkHTTPResponse(body: body, totalMs: 30.0) + } + let body = try JSONSerialization.data(withJSONObject: ["answers": ["route": ["choice": "code", "confidence": 0.9]], "system2": ["text": "ok"]]) + return BenchmarkHTTPResponse(body: body, totalMs: 10.0) + } + let mixed = try await BenchmarkRunner().run( + BenchmarkSuiteRunRequest(spec: spec, composeYAML: "", suiteName: "multi", endpoint: mixedEndpoint, runID: "r2") + ) + #expect(mixed.scorecard.metrics["task[0].accuracy"] == 1.0) + #expect(mixed.scorecard.metrics["task[1].accuracy"] == 0.0) + #expect(abs((mixed.scorecard.metrics["accuracy"] ?? -1) - (1.0 / 3.0)) < 1e-9) + #expect(abs((mixed.scorecard.metrics["p50_ms"] ?? -1) - 30.0) < 1e-9) + } + + @Test("A-B8 & A-B12: multi-task perplexity averages flat ppl across tasks and missing explicit datasets throw") + func multiTaskPerplexityAverageAndMissingDatasetsThrow() async throws { + var pplSpec = Self.makeSpec() + pplSpec.benchmarks = ComposeBenchmarksSpec( + defaults: BenchmarkDefaultsSpec(gpuLock: false), + suites: [ + "ppl-multi": BenchmarkSuiteSpec(tasks: [ + BenchmarkTaskSpec(adapter: "basalt:perplexity", target: "model:chat", params: ["text": .string("a")]), + BenchmarkTaskSpec(adapter: "basalt:perplexity", target: "model:chat", params: ["text": .string("b")]), + ]), + ] + ) + let pplEndpoint = BenchmarkEndpoint.mock { req in + let body = try #require(req.body.flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] }) + let nll = (body["completion_text"] as? String) == "a" ? 1.0 : 2.0 + return BenchmarkHTTPResponse(body: try JSONSerialization.data(withJSONObject: ["mean_nll": nll]), totalMs: 10.0) + } + let pplRun = try await BenchmarkRunner().run( + BenchmarkSuiteRunRequest(spec: pplSpec, composeYAML: "", suiteName: "ppl-multi", endpoint: pplEndpoint, runID: "r3") + ) + #expect(abs((pplRun.scorecard.metrics["task[0].ppl"] ?? 0) - exp(1.0)) < 1e-6) + #expect(abs((pplRun.scorecard.metrics["task[1].ppl"] ?? 0) - exp(2.0)) < 1e-6) + #expect(abs((pplRun.scorecard.metrics["ppl"] ?? 0) - (exp(1.0) + exp(2.0)) / 2.0) < 1e-6) + + let missingPath = "/nonexistent-\(UUID().uuidString).jsonl" + let missingTask = BenchmarkTaskSpec(adapter: "basalt:system-one", dataset: missingPath, target: "pipeline") + let ctx = BenchmarkTaskContext(spec: pplSpec, suiteName: "ppl-multi", task: missingTask, defaults: BenchmarkDefaultsSpec(), endpoint: pplEndpoint) + await #expect(throws: BenchmarkError.self) { + _ = try await BasaltSystemOneAdapter().run(context: ctx) + } + await #expect(throws: BenchmarkError.self) { + _ = try await TranslationBenchmarkAdapter().run(context: ctx) + } + await #expect(throws: BenchmarkError.self) { + _ = try await ExternalHarnessAdapter(id: "arc-agi", summary: "s").run(context: ctx) + } + } +} From e1671edd14ca0fe341c4690fd410e312b4f84053 Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:18:16 +0100 Subject: [PATCH 5/6] fix(appcore,fm,speech): fix FM thinking/SSE EOF/tool_call index, EngineSupervisor stopAdopted reentrancy, VoiceReducer race, Library fit retry, and speech bounds (A-A2, A-A4, A-A5, A-A6, A-A8, A-A9, A-A12) --- .../Audio/AudioSessionController.swift | 2 + Sources/BasaltAppCore/Chat/ChatReducer.swift | 12 +- Sources/BasaltAppCore/Chat/VoiceReducer.swift | 11 +- .../BasaltAppCore/Engine/EngineClient.swift | 3 +- .../Engine/EngineSupervisor.swift | 38 +++- .../BasaltAppCore/Library/LibraryClient.swift | 13 +- .../Library/LibraryReducer.swift | 5 + Sources/BasaltAppCore/Stream/ChatDelta.swift | 23 ++- .../BasaltFoundationTransport.swift | 11 +- .../BasaltSpeech/AppleSpeechSynthesizer.swift | 19 +- ...AppCoreFMSpeechDefectRegressionTests.swift | 173 ++++++++++++++++++ 11 files changed, 289 insertions(+), 21 deletions(-) create mode 100644 Tests/BasaltTests/App/AppCoreFMSpeechDefectRegressionTests.swift diff --git a/Sources/BasaltApp/Audio/AudioSessionController.swift b/Sources/BasaltApp/Audio/AudioSessionController.swift index 9ade4cd96..fc20624a7 100644 --- a/Sources/BasaltApp/Audio/AudioSessionController.swift +++ b/Sources/BasaltApp/Audio/AudioSessionController.swift @@ -90,6 +90,7 @@ public actor AudioCaptureActor { audioEngine.stop() (self.engine, self.captured) = (nil, nil) let recorded = sink.state.withLock { $0 } + guard !recorded.samples.isEmpty else { return Data() } return Self.encodeMono16kWAV(samples: recorded.samples, sourceRate: recorded.rate) } @@ -139,6 +140,7 @@ public actor AudioCaptureActor { } public nonisolated static func encodeMono16kWAV(samples: [Float], sourceRate: Double) -> Data { + guard !samples.isEmpty else { return Data() } let resampled = resample(samples: samples, from: sourceRate, to: Double(targetSampleRate)) return WAVEncoder.encode(samples: resampled, sampleRate: targetSampleRate) } diff --git a/Sources/BasaltAppCore/Chat/ChatReducer.swift b/Sources/BasaltAppCore/Chat/ChatReducer.swift index da09cd050..96415c25c 100644 --- a/Sources/BasaltAppCore/Chat/ChatReducer.swift +++ b/Sources/BasaltAppCore/Chat/ChatReducer.swift @@ -1,3 +1,4 @@ +import BasaltCore import Foundation public struct ChatState: Sendable, Equatable { @@ -252,7 +253,16 @@ public enum ChatReducer { message.parts[index] = .reasoning(text) case (.text(let piece), _): message.parts.append(.text(piece)) case (.reasoning(let piece), _): message.parts.append(.reasoning(piece)) - case (.toolCall(let call), _): message.parts.append(.toolCall(call)) + case (.toolCall(let call), _): + if !call.id.isEmpty, let idx = message.parts.firstIndex(where: { + if case .toolCall(let existing) = $0 { return existing.id == call.id } + return false + }), case .toolCall(let existing) = message.parts[idx] { + let mergedName = existing.name.isEmpty ? call.name : existing.name + message.parts[idx] = .toolCall(ToolCallOutput(id: existing.id, name: mergedName, arguments: existing.arguments + call.arguments)) + } else { + message.parts.append(.toolCall(call)) + } case (.usage(let prompt, let completion), _): message.receipt?.promptTokens = prompt message.receipt?.completionTokens = completion diff --git a/Sources/BasaltAppCore/Chat/VoiceReducer.swift b/Sources/BasaltAppCore/Chat/VoiceReducer.swift index 1d89c340e..1b642b261 100644 --- a/Sources/BasaltAppCore/Chat/VoiceReducer.swift +++ b/Sources/BasaltAppCore/Chat/VoiceReducer.swift @@ -159,10 +159,8 @@ public enum VoiceReducer { private static func beginSynthesis(_ state: inout VoiceSessionState, id: MessageID, raw: String) -> [VoiceEffect] { let text = raw.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty else { return [] } - let stopFirst = state.isSpeaking (state.synthesizingMessage, state.speakingMessage, state.error) = (id, nil, nil) - let synth = VoiceEffect.synthesize(id, text: text, voice: state.voice, speed: state.speed) - return stopFirst ? [.stopPlayback, synth] : [synth] + return [.synthesize(id, text: text, voice: state.voice, speed: state.speed)] } } @@ -222,7 +220,10 @@ public enum VoiceEffects { case .playAudio(let id, let wav): return .run(id: playbackID) { send in await play(id, wav: wav, environment, send) } case .stopPlayback: - return .run(id: playbackID) { _ in await environment.stopPlayback() } + return .run(id: playbackID) { _ in + guard !Task.isCancelled else { return } + await environment.stopPlayback() + } } } } @@ -243,6 +244,8 @@ public enum VoiceEffects { _ id: MessageID, text: String, voice: String, speed: Double, _ environment: VoiceEnvironment, _ send: @escaping @Sendable (VoiceAction) async -> Void ) async { + await environment.stopPlayback() + guard !Task.isCancelled else { return } guard let engine = await environment.engine() else { return await send(.failed("the engine is not running")) } do { let wav = try await engine.synthesizeSpeech(SpeechSynthesisCall(input: text, voice: voice, speed: speed)) diff --git a/Sources/BasaltAppCore/Engine/EngineClient.swift b/Sources/BasaltAppCore/Engine/EngineClient.swift index 8f54276a3..b4213ae6c 100644 --- a/Sources/BasaltAppCore/Engine/EngineClient.swift +++ b/Sources/BasaltAppCore/Engine/EngineClient.swift @@ -121,11 +121,12 @@ extension EngineClient { static func relay(_ bytes: URLSession.AsyncBytes, to continuation: AsyncThrowingStream.Continuation) async throws { var parser = SSEParser() var pending: [UInt8] = [] + var toolCallIDs: [Int: String] = [:] for try await byte in bytes { pending.append(byte) guard byte == UInt8(ascii: "\n") else { continue } for event in parser.feed(pending) { - switch try ChatDeltaDecoder.decode(event) { + switch try ChatDeltaDecoder.decode(event, toolCallIDs: &toolCallIDs) { case .done: return case .deltas(let deltas): for delta in deltas { continuation.yield(delta) } } diff --git a/Sources/BasaltAppCore/Engine/EngineSupervisor.swift b/Sources/BasaltAppCore/Engine/EngineSupervisor.swift index 8107c5eb3..6a31200b3 100644 --- a/Sources/BasaltAppCore/Engine/EngineSupervisor.swift +++ b/Sources/BasaltAppCore/Engine/EngineSupervisor.swift @@ -26,6 +26,8 @@ public actor EngineSupervisor { private let environment: EngineEnvironment private var process: Process? private var adoptedPID: Int32? + private var adoptedStopTask: Task? + var onAdoptedStopWait: (@Sendable () -> Void)? private var stoppingPID: Int32? private var graceKillTasks: [Int32: Task] = [:] private var ended: Set = [] @@ -77,6 +79,11 @@ public actor EngineSupervisor { public func shutdown() async { await withTaskCancellationShield { + if let existing = adoptedStopTask { + onAdoptedStopWait?() + await existing.value + return + } if process == nil, let adopted = adoptedPID { return await stopAdopted(adopted) } if process == nil, let pid = stoppingPID { await end(of: pid) @@ -93,12 +100,17 @@ public actor EngineSupervisor { func stopAdopted(_ pid: Int32) async { adoptedPID = nil - kill(pid, SIGINT) - let deadline = environment.now() + HelperLaunch.stopGrace - while environment.isAlive(pid), environment.now() < deadline { _ = try? await environment.sleep(.milliseconds(100)) } - if environment.isAlive(pid) { kill(pid, SIGKILL) } - environment.records.remove() - send(.stop) + let epoch = state.epoch + let env = environment + let task = Task { [weak self] in + kill(pid, SIGINT) + let deadline = env.now() + HelperLaunch.stopGrace + while env.isAlive(pid), env.now() < deadline { _ = try? await env.sleep(.milliseconds(100)) } + if env.isAlive(pid) { kill(pid, SIGKILL) } + await self?.finishAdoptedStop(epoch: epoch) + } + adoptedStopTask = task + await task.value } func end(of pid: Int32) async { @@ -234,3 +246,17 @@ extension EngineSupervisor { } } } + +extension EngineSupervisor { + func setOnAdoptedStopWait(_ hook: (@Sendable () -> Void)?) { + onAdoptedStopWait = hook + } + + func finishAdoptedStop(epoch: Int) { + adoptedStopTask = nil + if state.epoch == epoch { + environment.records.remove() + send(.stop) + } + } +} diff --git a/Sources/BasaltAppCore/Library/LibraryClient.swift b/Sources/BasaltAppCore/Library/LibraryClient.swift index b01e23014..ff390d30c 100644 --- a/Sources/BasaltAppCore/Library/LibraryClient.swift +++ b/Sources/BasaltAppCore/Library/LibraryClient.swift @@ -178,10 +178,13 @@ public enum LibraryEffects { static func call(_ effect: LibraryEffect, _ environment: LibraryEnvironment, _ send: @escaping @Sendable (LibraryAction) async -> Void) async { guard let client = await environment.client() else { - if case .load = effect { - await send(.listFailed("the engine is not running")) - } else if case .delete = effect { + switch effect { + case .fit(let id): + await send(.fitFailed(id, "the engine is not running")) + case .load, .delete: await send(.listFailed("the engine is not running")) + default: + break } return } @@ -200,7 +203,9 @@ public enum LibraryEffects { } } catch { switch effect { - case .list, .fit: + case .fit(let id): + await send(.fitFailed(id, Self.describe(error))) + case .list: await send(.listFailed(Self.describe(error))) default: await send(.failed(Self.describe(error))) diff --git a/Sources/BasaltAppCore/Library/LibraryReducer.swift b/Sources/BasaltAppCore/Library/LibraryReducer.swift index 10054fb9d..fff552865 100644 --- a/Sources/BasaltAppCore/Library/LibraryReducer.swift +++ b/Sources/BasaltAppCore/Library/LibraryReducer.swift @@ -57,6 +57,7 @@ public enum LibraryAction: Sendable { case appeared case listed([LibraryModel]) case fitted(String, ModelFit) + case fitFailed(String, String) case load(String) case loaded(String) case download(String) @@ -126,6 +127,10 @@ public enum LibraryReducer { case .fitted(let id, let fit): state.fits[id] = fit return [] + case .fitFailed(let id, let message): + state.fitAttempted.remove(id) + state.problem = message + return [] case .load(let id): return load(&state, id) case .loaded: diff --git a/Sources/BasaltAppCore/Stream/ChatDelta.swift b/Sources/BasaltAppCore/Stream/ChatDelta.swift index b74036439..7884bc754 100644 --- a/Sources/BasaltAppCore/Stream/ChatDelta.swift +++ b/Sources/BasaltAppCore/Stream/ChatDelta.swift @@ -24,6 +24,7 @@ public enum ChatDeltaDecoder { var arguments: String? } + var index: Int? var id: String? var function: Function? } @@ -67,6 +68,11 @@ public enum ChatDeltaDecoder { } public static func decode(_ event: SSEEvent) throws(EngineError) -> Decoded { + var ids: [Int: String] = [:] + return try decode(event, toolCallIDs: &ids) + } + + public static func decode(_ event: SSEEvent, toolCallIDs: inout [Int: String]) throws(EngineError) -> Decoded { guard event.data != "[DONE]" else { return .done } let frame: Frame do { @@ -80,11 +86,26 @@ public enum ChatDeltaDecoder { if let reasoning = choice.delta?.reasoning, !reasoning.isEmpty { deltas.append(.reasoning(reasoning)) } if let text = choice.delta?.content, !text.isEmpty { deltas.append(.text(text)) } for call in choice.delta?.toolCalls ?? [] { - deltas.append(.toolCall(ToolCallOutput(id: call.id ?? "", name: call.function?.name ?? "", arguments: call.function?.arguments ?? ""))) + let resolvedID = resolveToolCallID(call, in: &toolCallIDs) + deltas.append(.toolCall(ToolCallOutput(id: resolvedID, name: call.function?.name ?? "", arguments: call.function?.arguments ?? ""))) } if let reason = choice.finishReason { deltas.append(.finish(reason)) } } if let usage = frame.usage { deltas.append(.usage(prompt: usage.promptTokens, completion: usage.completionTokens)) } return .deltas(deltas) } + + private static func resolveToolCallID(_ call: Frame.Choice.Delta.ToolCall, in map: inout [Int: String]) -> String { + if let rawID = call.id, !rawID.isEmpty { + if let idx = call.index { map[idx] = rawID } + return rawID + } + if let idx = call.index { + if let known = map[idx] { return known } + let generated = "call_\(idx)" + map[idx] = generated + return generated + } + return "" + } } diff --git a/Sources/BasaltFoundationModels/BasaltFoundationTransport.swift b/Sources/BasaltFoundationModels/BasaltFoundationTransport.swift index f4af2d09a..ca2dafcd6 100644 --- a/Sources/BasaltFoundationModels/BasaltFoundationTransport.swift +++ b/Sources/BasaltFoundationModels/BasaltFoundationTransport.swift @@ -62,7 +62,10 @@ public struct BasaltFoundationRequest: Sendable, Equatable { if let topK { payload["top_k"] = topK } if let seed { payload["seed"] = seed } if let maxTokens { payload["max_tokens"] = maxTokens } - if let enableThinking { payload["enable_thinking"] = enableThinking } + if let enableThinking { + payload["enable_thinking"] = enableThinking + if !enableThinking { payload["reasoning_effort"] = "none" } + } if !tools.isEmpty { payload["tools"] = try tools.map(Self.serializeTool) } @@ -322,12 +325,13 @@ extension BasaltFoundationTransport { ) async throws { var parser = SSEParser() var pending: [UInt8] = [] + var toolCallIDs: [Int: String] = [:] for try await byte in bytes { try Task.checkCancellation() pending.append(byte) guard byte == UInt8(ascii: "\n") else { continue } for event in parser.feed(pending) { - switch try ChatDeltaDecoder.decode(event) { + switch try ChatDeltaDecoder.decode(event, toolCallIDs: &toolCallIDs) { case .done: return case .deltas(let deltas): for delta in deltas { continuation.yield(delta) } @@ -340,12 +344,13 @@ extension BasaltFoundationTransport { } pending.append(UInt8(ascii: "\n")) for event in parser.feed(pending) { - switch try ChatDeltaDecoder.decode(event) { + switch try ChatDeltaDecoder.decode(event, toolCallIDs: &toolCallIDs) { case .done: return case .deltas(let deltas): for delta in deltas { continuation.yield(delta) } } } + throw Task.isCancelled ? EngineError.cancelled : EngineError.transport("chat stream ended before [DONE]") } private static func inProcessStream( diff --git a/Sources/BasaltSpeech/AppleSpeechSynthesizer.swift b/Sources/BasaltSpeech/AppleSpeechSynthesizer.swift index a06bbe974..7531ab23c 100644 --- a/Sources/BasaltSpeech/AppleSpeechSynthesizer.swift +++ b/Sources/BasaltSpeech/AppleSpeechSynthesizer.swift @@ -151,7 +151,9 @@ private final class StreamSink: Sendable { let channel = source.floatChannelData?[0] { return Array(UnsafeBufferPointer(start: channel, count: Int(source.frameLength))) } - let capacity = AVAudioFrameCount(Double(source.frameLength) * target.sampleRate / source.format.sampleRate + 512) + let capacity = try AppleSpeechSynthesizer.validatedConversionCapacity( + frameLength: source.frameLength, sourceRate: source.format.sampleRate, targetRate: target.sampleRate + ) guard let converter = AVAudioConverter(from: source.format, to: target), let output = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: max(capacity, 512)) else { throw .inferenceError("apple-speech could not convert audio from \(Int(source.format.sampleRate)) Hz") @@ -226,3 +228,18 @@ private final class SynthesisSession { delegate = nil } } + +extension AppleSpeechSynthesizer { + static func validatedConversionCapacity( + frameLength: AVAudioFrameCount, sourceRate: Double, targetRate: Double + ) throws(BasaltError) -> AVAudioFrameCount { + guard sourceRate.isFinite, sourceRate > 0 else { + throw .inferenceError("apple-speech received invalid source sample rate \(sourceRate)") + } + let rawCapacity = Double(frameLength) * targetRate / sourceRate + 512 + guard rawCapacity.isFinite, rawCapacity >= 0, rawCapacity <= Double(AVAudioFrameCount.max) else { + throw .inferenceError("apple-speech output buffer capacity overflow") + } + return AVAudioFrameCount(rawCapacity) + } +} diff --git a/Tests/BasaltTests/App/AppCoreFMSpeechDefectRegressionTests.swift b/Tests/BasaltTests/App/AppCoreFMSpeechDefectRegressionTests.swift new file mode 100644 index 000000000..e320604c0 --- /dev/null +++ b/Tests/BasaltTests/App/AppCoreFMSpeechDefectRegressionTests.swift @@ -0,0 +1,173 @@ +import Foundation +import Synchronization +import Testing +@testable import BasaltApp +@testable import BasaltAppCore +@testable import BasaltCore +@testable import BasaltFoundationModels +@testable import BasaltSpeech + +@Suite("AppCore, FoundationModels, and Speech defect regressions (A-A2, A-A4, A-A5, A-A6, A-A8, A-A9, A-A12)") +struct AppCoreFMSpeechDefectRegressionTests { + @Test("A-A2: BasaltFoundationRequest.openAIJSONBody emits reasoning_effort=none when enableThinking is false") + func foundationRequestDisablesThinkingViaReasoningEffort() throws { + var req = BasaltFoundationRequest(messages: [ChatMessageInput(role: .user, text: "hi")]) + req.enableThinking = false + let obj = try #require(JSONSerialization.jsonObject(with: try req.openAIJSONBody()) as? [String: Any]) + #expect(obj["enable_thinking"] as? Bool == false) + #expect(obj["reasoning_effort"] as? String == "none") + + req.enableThinking = true + let enabledObj = try #require(JSONSerialization.jsonObject(with: try req.openAIJSONBody()) as? [String: Any]) + #expect(enabledObj["reasoning_effort"] == nil) + } + + @Test("A-A8: BasaltFoundationTransport throws transport error on truncated SSE stream missing [DONE]") + func foundationTransportRejectsTruncatedSSEWithoutDone() async throws { + let truncated = "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n" + let host = StubURLProtocol.host { _, _ in (200, ["Content-Type": "text/event-stream"], Data(truncated.utf8)) } + let url = try #require(URL(string: "http://\(host)")) + let endpoint = EngineEndpoint(base: url, token: nil) + let session = URLSession(configuration: StubURLProtocol.configuration) + let transport = BasaltFoundationTransport.rest(endpoint: endpoint, session: session) + let req = BasaltFoundationRequest(messages: [ChatMessageInput(role: .user, text: "hi")]) + await #expect(throws: EngineError.self) { + _ = try await transport.collect(req) + } + } + + @Test("A-A9: ChatDeltaDecoder preserves tool_calls[].index across interleaved deltas and ChatReducer merges by id") + func interleavedToolCallDeltasMergeByIndexAndId() throws { + var map: [Int: String] = [:] + let events = [ + SSEEvent(data: #"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_a","function":{"name":"first","arguments":"{\"x\":"}}]}}]}"#), + SSEEvent(data: #"{"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_b","function":{"name":"second","arguments":"{\"y\":"}}]}}]}"#), + SSEEvent(data: #"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"1}"}}]}}]}"#), + SSEEvent(data: #"{"choices":[{"delta":{"tool_calls":[{"index":1,"function":{"arguments":"2}"}}]}}]}"#), + ] + var msg = MessageSnapshot(id: MessageID(), role: .assistant, parts: []) + for event in events { + if case .deltas(let deltas) = try ChatDeltaDecoder.decode(event, toolCallIDs: &map) { + for delta in deltas { ChatReducer.apply(delta, to: &msg) } + } + } + #expect(msg.parts == [ + .toolCall(ToolCallOutput(id: "call_a", name: "first", arguments: "{\"x\":1}")), + .toolCall(ToolCallOutput(id: "call_b", name: "second", arguments: "{\"y\":2}")), + ]) + } + + @Test("A-A5: VoiceReducer switching read-aloud emits only .synthesize without racing .stopPlayback") + func voiceReducerSwitchReadAloudDoesNotRaceStopPlayback() { + let msgA = MessageID() + let msgB = MessageID() + var state = VoiceSessionState() + state.speakingMessage = msgA + let effects = VoiceReducer.reduce(&state, .readAloud(msgB, "Second message")) + #expect(effects == [.synthesize(msgB, text: "Second message", voice: state.voice, speed: state.speed)]) + #expect(state.synthesizingMessage == msgB && state.speakingMessage == nil) + } + + @Test("A-A6: LibraryReducer retries fit on next listing after transient fitFailed") + func libraryReducerRetriesFitAfterTransientFailure() { + var state = LibraryState() + let m = LibraryModel(id: "org/m", sizeBytes: 100, isLoaded: false) + let first = LibraryReducer.reduce(&state, .listed([m])) + #expect(first == [.fit("org/m")]) + #expect(state.fitAttempted.contains("org/m")) + + _ = LibraryReducer.reduce(&state, .fitFailed("org/m", "temporary error")) + #expect(!state.fitAttempted.contains("org/m")) + #expect(!state.canLoad("org/m")) + + let retry = LibraryReducer.reduce(&state, .listed([m])) + #expect(retry == [.fit("org/m")]) + } + + private actor SleepHoldGate { + private var entered = 0 + private var enterWaiter: CheckedContinuation? + private var resumeWaiter: CheckedContinuation? + private var released = false + + var count: Int { entered } + + func hold() async { + entered += 1 + if let waiter = enterWaiter { + enterWaiter = nil + waiter.resume() + } + guard !released else { return } + await withCheckedContinuation { resumeWaiter = $0 } + } + + func waitForEntry() async { + guard entered == 0 else { return } + await withCheckedContinuation { enterWaiter = $0 } + } + + func release() { + released = true + let waiter = resumeWaiter + resumeWaiter = nil + waiter?.resume() + } + } + + @Test("A-A4: EngineSupervisor concurrent relaunch during stopAdopted finishes cleanup before spawning and never leaves engine idle", .timeLimit(.minutes(1))) + func engineSupervisorConcurrentStopAdoptedAndRelaunch() async throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("sup-adopt-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + let store = EngineRecords.file(dir.appendingPathComponent("engine.json")) + store.save(EngineRecord(pid: 999_999, port: 18_999, token: "tok", arguments: ["serve"])) + + let alive = Mutex(true) + let sleepGate = SleepHoldGate() + let joined = AsyncStream.makeStream(of: Void.self) + let initial = HelperLaunch(executable: URL(fileURLWithPath: "/usr/bin/true"), arguments: ["serve"]) + let next = HelperLaunch(executable: URL(fileURLWithPath: "/bin/sh"), arguments: ["-c", "exec sleep 30"]) + let env = EngineEnvironment( + now: { .seconds(0) }, + sleep: { _ in + await sleepGate.hold() + alive.withLock { $0 = false } + }, + probe: { _ in true }, + records: store, + isAlive: { _ in alive.withLock { $0 } } + ) + let supervisor = EngineSupervisor(launch: initial, environment: env, token: "tok") + await supervisor.setOnAdoptedStopWait { joined.continuation.yield() } + await supervisor.start() + #expect(await supervisor.state.port == 18_999) + + let stopTask = Task { await supervisor.shutdown() } + await sleepGate.waitForEntry() + let relaunchTask = Task { await supervisor.relaunch(next) } + var joinedIter = joined.stream.makeAsyncIterator() + _ = await joinedIter.next() + await sleepGate.release() + _ = await (stopTask.value, relaunchTask.value) + + #expect(await supervisor.launch == next) + #expect(await supervisor.state.phase == .spawning) + #expect(await sleepGate.count == 1) + await supervisor.shutdown() + } + + @Test("A-A12: AudioCaptureActor.encodeMono16kWAV returns empty Data for zero samples and AppleSpeechSynthesizer rejects 0 Hz / overflow") + func emptyRecordingAndInvalidSampleRateGuards() { + #expect(AudioCaptureActor.encodeMono16kWAV(samples: [], sourceRate: 48_000).isEmpty) + #expect(throws: BasaltError.self) { + _ = try AppleSpeechSynthesizer.validatedConversionCapacity(frameLength: 1024, sourceRate: 0, targetRate: 24_000) + } + #expect(throws: BasaltError.self) { + _ = try AppleSpeechSynthesizer.validatedConversionCapacity(frameLength: 1024, sourceRate: .nan, targetRate: 24_000) + } + #expect(throws: BasaltError.self) { + _ = try AppleSpeechSynthesizer.validatedConversionCapacity(frameLength: 1024, sourceRate: 1e-12, targetRate: 24_000) + } + } +} From 47917b43f54b40eead8ea695f17317c3ca8fa341 Mon Sep 17 00:00:00 2001 From: Aleksei Boklag <146362331+goodmai@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:21:33 +0100 Subject: [PATCH 6/6] fix(app,l10n): preserve BASALT_METALLIB & refresh CloudKeys on relaunch, sync model switches, pre-check attachment sizes, fix image regen I/O & EN/RU Localizable.strings parity (A-A1, A-A3, A-A10, A-A11, A-A13) --- Localization/en.lproj/Localizable.strings | 10 +- Localization/ru.lproj/Localizable.strings | 12 +- .../App/AppModel+ComposeProfiles.swift | 15 +- Sources/BasaltApp/App/AppModel+Features.swift | 84 +++++-- Sources/BasaltApp/App/AppModel.swift | 33 ++- Sources/BasaltApp/Chat/ComposerGlassBar.swift | 10 +- .../Chat/InlineVideoPlayerCard.swift | 23 +- Sources/BasaltAppCore/Chat/Attachments.swift | 28 +++ Sources/BasaltAppCore/Chat/ChatEffects.swift | 53 +++- .../Chat/ChatReducer+Images.swift | 34 ++- .../Chat/GeneratedImagePart.swift | 3 +- Sources/BasaltMac/BasaltMacApp.swift | 2 +- Sources/BasaltMac/Intents.swift | 4 +- Sources/BasaltMac/SystemServices.swift | 17 +- .../BasaltTests/App/AppImageCanvasTests.swift | 2 +- ...ppLifecycleL10nDefectRegressionTests.swift | 235 ++++++++++++++++++ Tests/BasaltTests/App/AppShipTests.swift | 24 +- 17 files changed, 511 insertions(+), 78 deletions(-) create mode 100644 Tests/BasaltTests/App/AppLifecycleL10nDefectRegressionTests.swift diff --git a/Localization/en.lproj/Localizable.strings b/Localization/en.lproj/Localizable.strings index a82e90236..255578b3d 100644 --- a/Localization/en.lproj/Localizable.strings +++ b/Localization/en.lproj/Localizable.strings @@ -164,14 +164,13 @@ "Activate" = "Activate"; "Activate Profile" = "Activate Profile"; "Adaptive thinking budgets tuned for multi-step math and logic." = "Adaptive thinking budgets tuned for multi-step math and logic."; -"All 91" = "All 91"; +"All %lld" = "All %lld"; "Belnap" = "Belnap"; "Bundled Profile" = "Bundled Profile"; "CLI Command" = "CLI Command"; "Chat" = "Chat"; "Choose any hardware-tuned multi-model profile on the left." = "Choose any hardware-tuned multi-model profile on the left."; "Cloud Cap" = "Cloud Cap"; -"Code" = "Code"; "Coding Agent & MCP" = "Coding Agent & MCP"; "Compose Profiles" = "Compose Profiles"; "Compose Specification (YAML)" = "Compose Specification (YAML)"; @@ -229,7 +228,6 @@ "Speech" = "Speech"; "Targets %@ Macs; may exceed this Mac's memory" = "Targets %@ Macs; may exceed this Mac's memory"; "TeaCache" = "TeaCache"; -"Thinking" = "Thinking"; "TTS 44.1 kHz" = "TTS 44.1 kHz"; "Upsample" = "Upsample"; "Vision" = "Vision"; @@ -270,7 +268,6 @@ "Estimating output footprint…" = "Estimating output footprint…"; "PV-Tuning (Teacher KL Code & Scale Refinement)" = "PV-Tuning (Teacher KL Code & Scale Refinement)"; "Preset" = "Preset"; -"Fast" = "Fast"; "Balanced" = "Balanced"; "Thorough" = "Thorough"; "Teacher Model" = "Teacher Model"; @@ -352,3 +349,8 @@ "Merge LoRA Adapter (Optional)" = "Merge LoRA Adapter (Optional)"; "org/adapter-repo" = "org/adapter-repo"; "Fuses a PEFT or mlx-lm LoRA repository into the converted weights." = "Fuses a PEFT or mlx-lm LoRA repository into the converted weights."; +"Target Budget: %@ bpw" = "Target Budget: %@ bpw"; +"%lld-bit" = "%lld-bit"; +"Estimated Size: %@ → %@" = "Estimated Size: %@ → %@"; +"Peak Conversion RAM: %@" = "Peak Conversion RAM: %@"; +"%@ of %@" = "%@ of %@"; diff --git a/Localization/ru.lproj/Localizable.strings b/Localization/ru.lproj/Localizable.strings index 691211244..6d8f38116 100644 --- a/Localization/ru.lproj/Localizable.strings +++ b/Localization/ru.lproj/Localizable.strings @@ -164,14 +164,13 @@ "Activate" = "Включить"; "Activate Profile" = "Активировать профиль"; "Adaptive thinking budgets tuned for multi-step math and logic." = "Адаптивный бюджет размышлений для многошаговой логики и математики."; -"All 91" = "Все 91"; +"All %lld" = "Все %lld"; "Belnap" = "Белнап"; "Bundled Profile" = "Встроенный профиль"; "CLI Command" = "Команда CLI"; "Chat" = "Чат"; "Choose any hardware-tuned multi-model profile on the left." = "Выберите любой аппаратный профиль многомодельной системы слева."; "Cloud Cap" = "Лимит облака"; -"Code" = "Код"; "Coding Agent & MCP" = "Кодинг-агент и MCP"; "Compose Profiles" = "Профили Compose"; "Compose Specification (YAML)" = "Спецификация Compose (YAML)"; @@ -186,7 +185,7 @@ "Epistemic" = "Эпистемика"; "Epistemic Grounded Research" = "Верифицированный поиск и факты"; "Estimated Resident RAM" = "Оценка резидентной памяти"; -"Fast" = "Быстро"; +"Fast" = "Быстрый"; "Fast everyday chat, Apple Vision attachments, and local speech input." = "Быстрый чат на каждый день, вложения через Apple Vision и голосовой ввод."; "Filter profiles or models" = "Поиск профилей или моделей"; "Frontier MoE Engine" = "Флагманский MoE-движок"; @@ -229,7 +228,6 @@ "Speech" = "Речь"; "Targets %@ Macs; may exceed this Mac's memory" = "Рассчитан на Mac с %@; может превысить память этого Mac"; "TeaCache" = "TeaCache"; -"Thinking" = "Мышление"; "TTS 44.1 kHz" = "TTS 44,1 кГц"; "Upsample" = "Апсемпл"; "Vision" = "Зрение"; @@ -270,7 +268,6 @@ "Estimating output footprint…" = "Оценка размера выходной модели…"; "PV-Tuning (Teacher KL Code & Scale Refinement)" = "PV-тюнинг (доводка кодов и шкал по KL учителя)"; "Preset" = "Профиль"; -"Fast" = "Быстрый"; "Balanced" = "Сбалансированный"; "Thorough" = "Тщательный"; "Teacher Model" = "Модель-учитель"; @@ -352,3 +349,8 @@ "Merge LoRA Adapter (Optional)" = "Влить LoRA-адаптер (необязательно)"; "org/adapter-repo" = "org/adapter-repo"; "Fuses a PEFT or mlx-lm LoRA repository into the converted weights." = "Вливает PEFT или mlx-lm LoRA-репозиторий в конвертируемые веса."; +"Target Budget: %@ bpw" = "Целевой бюджет: %@ бит/вес"; +"%lld-bit" = "%lld бит"; +"Estimated Size: %@ → %@" = "Оценка размера: %@ → %@"; +"Peak Conversion RAM: %@" = "Пиковое ОЗУ конвертации: %@"; +"%@ of %@" = "%@ из %@"; diff --git a/Sources/BasaltApp/App/AppModel+ComposeProfiles.swift b/Sources/BasaltApp/App/AppModel+ComposeProfiles.swift index dc43d01f6..2b58b09db 100644 --- a/Sources/BasaltApp/App/AppModel+ComposeProfiles.swift +++ b/Sources/BasaltApp/App/AppModel+ComposeProfiles.swift @@ -5,7 +5,8 @@ import Foundation extension AppModel { static func makeComposeProfilesStore( initialCompose: String, - supervisor: EngineSupervisor + supervisor: EngineSupervisor, + cloudEnvironment: @escaping @Sendable () -> [String: String] = { CloudKeys.environment(defaults: .standard, keychain: .live()) } ) -> ComposeProfilesStore { Store( ComposeProfilesState(activeCompose: initialCompose), @@ -18,7 +19,9 @@ extension AppModel { await send(.failed("Unknown compose profile: \(id)")) return } - if let endpoint = await supervisor.endpoint { + let current = await supervisor.launch + let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment()) + if freshEnv == current.environment, let endpoint = await supervisor.endpoint { do { let diff = try await EngineClient.http(endpoint).applyCompose(ComposeApplyCall(yaml: yaml)) if let refusal = diff.refusal { @@ -37,13 +40,13 @@ extension AppModel { } catch {} } guard !Task.isCancelled else { return } - let current = await supervisor.launch - let freshEnv = CloudKeys.environment(defaults: .standard, keychain: .live()) + let latest = await supervisor.launch + let relaunchEnv = Self.refreshedEnvironment(preserving: latest.environment, cloud: cloudEnvironment()) await supervisor.relaunch( HelperLaunch( - executable: current.executable, + executable: latest.executable, arguments: ["serve", "--compose", id], - environment: freshEnv + environment: relaunchEnv ) ) guard !Task.isCancelled else { return } diff --git a/Sources/BasaltApp/App/AppModel+Features.swift b/Sources/BasaltApp/App/AppModel+Features.swift index 7cdd9db1c..67c993a09 100644 --- a/Sources/BasaltApp/App/AppModel+Features.swift +++ b/Sources/BasaltApp/App/AppModel+Features.swift @@ -23,36 +23,76 @@ extension AppModel { matchedConversationIDs = Set(ids) } - public func switchEngine(_ arguments: [String]) async { + nonisolated static func refreshedEnvironment( + preserving current: [String: String], + cloud: [String: String] + ) -> [String: String] { + var merged = cloud + for (key, value) in current where key.hasPrefix("BASALT_") && !value.isEmpty && merged[key] == nil { + merged[key] = value + } + return merged + } + + public func switchEngine(_ arguments: [String], forceRestart: Bool = false) async { if let index = arguments.firstIndex(of: "--model"), arguments.indices.contains(index + 1) { configuredModel = arguments[index + 1] } let current = await supervisor.launch + let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment()) + let fallback = HelperLaunch(executable: current.executable, arguments: arguments, environment: freshEnv) + if forceRestart || freshEnv != current.environment { + await supervisor.relaunch(fallback) + syncComposeProfileIfNeeded(arguments) + return + } let isReady = if case .ready = engine.phase { true } else { false } switch HotSwitchPlan.plan(from: current.arguments, to: arguments, isReady: isReady) { case .noop: await supervisor.start() case .hotLoadModel(let id): if (try? await hotSwitchModel(id)) != nil { return } - await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: arguments, environment: current.environment)) + await supervisor.relaunch(fallback) case .hotApplyCompose(let path): - do { - if let bundled = ComposeProfileCatalog.bundledYAML[path] { - _ = try await applyComposeYAML(bundled, filePath: path) - } else { - _ = try await applyComposeFile(URL(fileURLWithPath: path)) - } - composeProfiles.send(.syncActive(path)) - return - } catch EngineError.refused { - return - } catch { - composeProfiles.send(.syncActive(path)) - await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: arguments, environment: current.environment)) - } + await hotApplyCompose(path, fallback: fallback) case .relaunch: - await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: arguments, environment: current.environment)) + await supervisor.relaunch(fallback) + } + } + + private func hotApplyCompose(_ path: String, fallback: HelperLaunch) async { + do { + if let bundled = ComposeProfileCatalog.bundledYAML[path] { + _ = try await applyComposeYAML(bundled, filePath: path) + } else { + _ = try await applyComposeFile(URL(fileURLWithPath: path)) + } + composeProfiles.send(.syncActive(path)) + } catch EngineError.refused { + return + } catch { + composeProfiles.send(.syncActive(path)) + await supervisor.relaunch(fallback) + } + } + + private func syncComposeProfileIfNeeded(_ arguments: [String]) { + if let index = arguments.firstIndex(of: "--compose"), arguments.indices.contains(index + 1) { + composeProfiles.send(.syncActive(arguments[index + 1])) + } + } + + public func recordLoadedModel(_ id: String) async { + configuredModel = id + await supervisor.updateLaunchArguments(["serve", "--model", id]) + UserDefaults.standard.set(id, forKey: EngineChoice.modelKey) + if !library.state.models.isEmpty { + let updated = library.state.models.map { + LibraryModel(id: $0.id, sizeBytes: $0.sizeBytes, isLoaded: $0.id == id) + } + library.send(.listed(updated)) } + library.send(.appeared) } @discardableResult @@ -67,13 +107,12 @@ extension AppModel { } guard let client = resolved else { throw EngineError.notRunning } let loaded = try await client.loadModel(id) - configuredModel = loaded - await supervisor.updateLaunchArguments(["serve", "--model", loaded]) - UserDefaults.standard.set(loaded, forKey: EngineChoice.modelKey) - library.send(.appeared) + await recordLoadedModel(loaded) return loaded } +} +extension AppModel { @discardableResult public func applyComposeFile(_ url: URL, client override: EngineClient? = nil) async throws -> Bool { let accessed = url.startAccessingSecurityScopedResource() @@ -112,8 +151,9 @@ extension AppModel { } guard let filePath else { return false } let current = await supervisor.launch + let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment()) UserDefaults.standard.set(filePath, forKey: EngineChoice.composeKey) - await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: ["serve", "--compose", filePath], environment: current.environment)) + await supervisor.relaunch(HelperLaunch(executable: current.executable, arguments: ["serve", "--compose", filePath], environment: freshEnv)) return false } diff --git a/Sources/BasaltApp/App/AppModel.swift b/Sources/BasaltApp/App/AppModel.swift index a2b19042d..aa4fa4772 100644 --- a/Sources/BasaltApp/App/AppModel.swift +++ b/Sources/BasaltApp/App/AppModel.swift @@ -7,6 +7,11 @@ public typealias ChatStore = Store public typealias MonitorStore = Store public typealias LibraryStore = Store +@MainActor +private final class MainActorCallback { + var invoke: (@MainActor (Value) -> Void)? +} + @Observable @MainActor public final class AppModel { public static let defaultModel = "mlx-community/gemma-4-12B-it-qat-4bit" @@ -29,6 +34,7 @@ public final class AppModel { public let drafts: DraftStore @ObservationIgnored let supervisor: EngineSupervisor @ObservationIgnored let repository: ConversationRepository + @ObservationIgnored let cloudEnvironment: @Sendable () -> [String: String] public internal(set) var configuredModel: String public var model: String { library.state.models.first(where: \.isLoaded)?.id ?? configuredModel } @ObservationIgnored private var listening = false @@ -36,9 +42,16 @@ public final class AppModel { @ObservationIgnored public var answered: @MainActor (ConversationSnapshot) -> Void = { _ in } - public init(launch: HelperLaunch, model: String, storeURL: URL?, environment: EngineEnvironment = .live, drafts: DraftStore = .defaults()) throws { + public init( + launch: HelperLaunch, + model: String, + storeURL: URL?, + environment: EngineEnvironment = .live, + drafts: DraftStore = .defaults(), + cloudEnvironment: @escaping @Sendable () -> [String: String] = { CloudKeys.environment(defaults: .standard, keychain: .live()) } + ) throws { let supervisor = EngineSupervisor(launch: launch, environment: environment) - (self.supervisor, self.configuredModel, self.drafts) = (supervisor, model, drafts) + (self.supervisor, self.configuredModel, self.drafts, self.cloudEnvironment) = (supervisor, model, drafts, cloudEnvironment) repository = ConversationRepository(modelContainer: try ConversationRepository.container(at: storeURL)) monitor = Store(MonitorState(), reduce: MonitorReducer.reduce, handle: MonitorReducer.handler( stats: { @@ -49,14 +62,24 @@ public final class AppModel { guard let endpoint = await supervisor.endpoint else { return nil } return try await EngineClient.http(endpoint).compose() })) + let onChosen = MainActorCallback() library = Store(LibraryState(pending: UserDefaults.standard.stringArray(forKey: Self.pendingKey) ?? []), reduce: LibraryReducer.reduce, handle: LibraryEffects.handler( LibraryEnvironment( client: { await supervisor.endpoint.map { LibraryClient.live($0) } }, savePending: { UserDefaults.standard.set($0, forKey: AppModel.pendingKey) }, - chose: { id in UserDefaults.standard.set(id, forKey: "model") }))) + chose: { id in + UserDefaults.standard.set(id, forKey: EngineChoice.modelKey) + await supervisor.updateLaunchArguments(["serve", "--model", id]) + await MainActor.run { onChosen.invoke?(id) } + }))) let initialCompose = UserDefaults.standard.string(forKey: EngineChoice.composeKey) ?? "" - composeProfiles = Self.makeComposeProfilesStore(initialCompose: initialCompose, supervisor: supervisor) + composeProfiles = Self.makeComposeProfilesStore( + initialCompose: initialCompose, + supervisor: supervisor, + cloudEnvironment: cloudEnvironment + ) voice = AudioSessionController(engine: { await supervisor.endpoint.map { EngineClient.http($0) } }) + onChosen.invoke = { [weak self] id in self?.configuredModel = id } voice.onSubmitTranscript = { [weak self] text in self?.submitVoiceTranscript(text) } } @@ -111,7 +134,7 @@ public final class AppModel { public func restart() async { let current = await supervisor.launch - let freshEnv = CloudKeys.environment(defaults: .standard, keychain: .live()) + let freshEnv = Self.refreshedEnvironment(preserving: current.environment, cloud: cloudEnvironment()) await supervisor.relaunch( HelperLaunch(executable: current.executable, arguments: current.arguments, environment: freshEnv) ) diff --git a/Sources/BasaltApp/Chat/ComposerGlassBar.swift b/Sources/BasaltApp/Chat/ComposerGlassBar.swift index 0a6a90fef..ccc53c886 100644 --- a/Sources/BasaltApp/Chat/ComposerGlassBar.swift +++ b/Sources/BasaltApp/Chat/ComposerGlassBar.swift @@ -133,11 +133,11 @@ struct ComposerGlassBar: View { } static func attach(_ url: URL, to store: ChatStore) { - let scoped = url.startAccessingSecurityScopedResource() - defer { if scoped { url.stopAccessingSecurityScopedResource() } } - if let data = try? Data(contentsOf: url), - let attachment = ChatAttachment(name: url.lastPathComponent, data: data, sourcePath: url.path) { - store.send(.attach(attachment)) + guard url.isFileURL, ChatAttachment.accepts(url.lastPathComponent) else { return } + Task { + if let attachment = await ChatAttachment.loadAsync(from: url) { + store.send(.attach(attachment)) + } } } } diff --git a/Sources/BasaltApp/Chat/InlineVideoPlayerCard.swift b/Sources/BasaltApp/Chat/InlineVideoPlayerCard.swift index 8598231b3..96fc1ff57 100644 --- a/Sources/BasaltApp/Chat/InlineVideoPlayerCard.swift +++ b/Sources/BasaltApp/Chat/InlineVideoPlayerCard.swift @@ -396,14 +396,31 @@ enum InlineVideoIO { } static func exportMP4WithPanel(part: GeneratedVideoPart) { - guard let path = part.filePath, - let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { return } + guard let path = part.filePath, FileManager.default.fileExists(atPath: path) else { return } + let sourceURL = URL(fileURLWithPath: path) let panel = NSSavePanel() panel.allowedContentTypes = [.mpeg4Movie, .quickTimeMovie] panel.canCreateDirectories = true panel.nameFieldStringValue = part.assetID.isEmpty ? "basalt-video.mp4" : part.assetID if panel.runModal() == .OK, let outURL = panel.url { - try? data.write(to: outURL, options: .atomic) + Task { try? await copyFile(from: sourceURL, to: outURL) } + } + } + + @concurrent + static func copyFile(from source: URL, to destination: URL) async throws { + let resolvedSource = source.resolvingSymlinksInPath() + let resolvedDestination = destination.resolvingSymlinksInPath() + guard resolvedSource != resolvedDestination else { return } + let fm = FileManager.default + let tempURL = destination.deletingLastPathComponent() + .appending(path: ".\(destination.lastPathComponent).\(UUID().uuidString).tmp") + defer { try? fm.removeItem(at: tempURL) } + try fm.copyItem(at: resolvedSource, to: tempURL) + if fm.fileExists(atPath: destination.path) { + _ = try fm.replaceItemAt(destination, withItemAt: tempURL) + } else { + try fm.moveItem(at: tempURL, to: destination) } } } diff --git a/Sources/BasaltAppCore/Chat/Attachments.swift b/Sources/BasaltAppCore/Chat/Attachments.swift index 2e08f835f..74601546b 100644 --- a/Sources/BasaltAppCore/Chat/Attachments.swift +++ b/Sources/BasaltAppCore/Chat/Attachments.swift @@ -21,7 +21,35 @@ public struct ChatAttachment: Sendable, Equatable, Identifiable { (self.id, self.name, self.kind, self.format, self.data, self.sourcePath) = (id, name, kind, format, data, sourcePath) } + private init(id: UUID, name: String, kind: String, format: String, data: Data, sourcePath: String?) { + (self.id, self.name, self.kind, self.format, self.data, self.sourcePath) = (id, name, kind, format, data, sourcePath) + } + + public static func deferredReference(name: String, sourcePath: String, id: UUID = UUID()) -> ChatAttachment? { + let format = (name as NSString).pathExtension.lowercased() + guard let kind = Self.kinds[format], !sourcePath.isEmpty else { return nil } + return ChatAttachment(id: id, name: name, kind: kind, format: format, data: Data(), sourcePath: sourcePath) + } + public static func accepts(_ name: String) -> Bool { kinds[(name as NSString).pathExtension.lowercased()] != nil } + + public static func load(from url: URL) -> ChatAttachment? { + guard url.isFileURL, accepts(url.lastPathComponent) else { return nil } + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + let target = url.resolvingSymlinksInPath() + guard let values = try? target.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]), + values.isRegularFile == true, + let size = values.fileSize, + size > 0, size <= byteLimit else { return nil } + guard let data = try? Data(contentsOf: url) else { return nil } + return ChatAttachment(name: url.lastPathComponent, data: data, sourcePath: url.path) + } + + @concurrent + public static func loadAsync(from url: URL) async -> ChatAttachment? { + load(from: url) + } } public struct PipelineCall: Sendable, Equatable { diff --git a/Sources/BasaltAppCore/Chat/ChatEffects.swift b/Sources/BasaltAppCore/Chat/ChatEffects.swift index 10062bbae..17696a076 100644 --- a/Sources/BasaltAppCore/Chat/ChatEffects.swift +++ b/Sources/BasaltAppCore/Chat/ChatEffects.swift @@ -61,9 +61,10 @@ extension ChatEffects { static func perceive(_ run: RunID, _ call: PipelineCall, _ environment: ChatEnvironment, _ send: @escaping @Sendable (ChatAction) async -> Void) async { guard let engine = await environment.engine() else { return await send(.failed(run, .notRunning)) } do { - let response = try await engine.pipeline(call) + let resolved = try await resolvePipelineCall(call) + let response = try await engine.pipeline(resolved) guard !Task.isCancelled else { return } - await send(.perceived(run, PipelineResult(response, count: call.attachments.count))) + await send(.perceived(run, PipelineResult(response, count: resolved.attachments.count))) } catch { guard !Task.isCancelled else { return } await send(.failed(run, error as? EngineError ?? .transport(error.localizedDescription))) @@ -79,18 +80,19 @@ extension ChatEffects { guard let engine = await environment.engine() else { return await send(.failed(run, .notRunning)) } var completed = false do { - for try await event in engine.streamImageGeneration(call) { + let resolved = try await resolveReferenceImages(call) + for try await event in engine.streamImageGeneration(resolved) { switch event { case .partial(let step, let totalSteps, let png, let width, let height): await send(.imagePartial(run, step: step, totalSteps: totalSteps, png: png, width: width, height: height)) case .completed(var part, let imageBytes, let elapsedMs): - let savedPath = try environment.mediaStore.store(imageBytes, format: call.outputFormat) + let savedPath = try environment.mediaStore.store(imageBytes, format: resolved.outputFormat) part.filePath = savedPath if part.assetID.isEmpty { part.assetID = URL(fileURLWithPath: savedPath).lastPathComponent } if part.beforeFilePath == nil { - part.beforeFilePath = call.beforeFilePath + part.beforeFilePath = resolved.beforeFilePath } part.previewPNG = nil completed = true @@ -106,6 +108,47 @@ extension ChatEffects { await send(.failed(run, error as? EngineError ?? .transport(error.localizedDescription))) } } + + static func resolveReferenceImages(_ call: ImageGenerationCall) async throws(EngineError) -> ImageGenerationCall { + guard !call.referenceImagePaths.isEmpty else { return call } + var resolved = call + var loaded = call.referenceImages + for path in call.referenceImagePaths { + guard let bytes = await readBoundedFile(at: path) else { + throw .refused(status: 400, message: "Reference image could not be read: \(URL(fileURLWithPath: path).lastPathComponent)") + } + loaded.append(bytes) + } + resolved.referenceImages = loaded + resolved.referenceImagePaths = [] + return resolved + } + + private static func resolvePipelineCall(_ call: PipelineCall) async throws(EngineError) -> PipelineCall { + guard call.attachments.contains(where: { $0.data.isEmpty }) else { return call } + var resolved: [ChatAttachment] = [] + for item in call.attachments { + if !item.data.isEmpty { + resolved.append(item) + } else if let path = item.sourcePath, let bytes = await readBoundedFile(at: path), + let loaded = ChatAttachment(name: item.name, data: bytes, id: item.id, sourcePath: path) { + resolved.append(loaded) + } else { + throw .refused(status: 400, message: "Attachment could not be read: \(item.name)") + } + } + return PipelineCall(attachments: resolved, task: call.task) + } + + @concurrent + private static func readBoundedFile(at path: String) async -> Data? { + let url = URL(fileURLWithPath: path).resolvingSymlinksInPath() + guard let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]), + values.isRegularFile == true, + let size = values.fileSize, + size > 0, size <= ChatAttachment.byteLimit else { return nil } + return try? Data(contentsOf: url) + } } extension ChatDelta { diff --git a/Sources/BasaltAppCore/Chat/ChatReducer+Images.swift b/Sources/BasaltAppCore/Chat/ChatReducer+Images.swift index ff731522d..25c7731c1 100644 --- a/Sources/BasaltAppCore/Chat/ChatReducer+Images.swift +++ b/Sources/BasaltAppCore/Chat/ChatReducer+Images.swift @@ -1,8 +1,6 @@ import Foundation enum ImageTurnPlanner { - static let pngHeader = Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]) - static func parseCommand(_ text: String) -> String? { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) let lower = trimmed.lowercased() @@ -34,24 +32,25 @@ enum ImageTurnPlanner { return nil } guard let previous = conversation.messages[forkIndex].images.first else { return nil } - var refs: [Data] = [] + var refPaths: [String] = [] if let beforePath = previous.beforeFilePath { - let bytes = (try? Data(contentsOf: URL(fileURLWithPath: beforePath))) ?? pngHeader - refs.append(bytes) + refPaths.append(beforePath) } else if forkIndex > 0 { - refs = conversation.messages[forkIndex - 1].attachments.compactMap { item in + refPaths = conversation.messages[forkIndex - 1].attachments.compactMap { item in guard item.kind == "image", let path = item.filePath else { return nil } - return (try? Data(contentsOf: URL(fileURLWithPath: path))) ?? pngHeader + return path } } - return ImageGenerationCall( + var call = ImageGenerationCall( prompt: previous.prompt, model: conversation.model ?? previous.model, size: "\(previous.width)x\(previous.height)", steps: max(previous.totalSteps, 1), - referenceImages: refs, + referenceImages: [], beforeFilePath: previous.beforeFilePath ) + call.referenceImagePaths = refPaths + return call } } @@ -86,12 +85,15 @@ extension ChatReducer { } guard !resolvedPrompt.isEmpty else { return [] } let before = state.beforeFilePath ?? imageAttachments.first?.sourcePath - let call = ImageGenerationCall( + let inlineRefs = imageAttachments.compactMap { $0.data.isEmpty ? nil : $0.data } + let pathRefs = imageAttachments.compactMap { $0.data.isEmpty ? $0.sourcePath : nil } + var call = ImageGenerationCall( prompt: resolvedPrompt, model: state.conversation.model, - referenceImages: imageAttachments.map(\.data), + referenceImages: inlineRefs, beforeFilePath: before ) + call.referenceImagePaths = pathRefs let attached = state.attachments.map { MessagePart.attachment(AttachmentPart(name: $0.name, kind: $0.kind, filePath: $0.sourcePath)) } @@ -150,7 +152,9 @@ extension ChatReducer { return [] } } +} +extension ChatReducer { private static func applyImagePartial( _ message: inout MessageSnapshot, step: Int, @@ -189,8 +193,12 @@ extension ChatReducer { guard let path = part.filePath, !path.isEmpty else { return } let rawName = URL(fileURLWithPath: path).lastPathComponent let validName = ChatAttachment.accepts(rawName) ? rawName : "\(rawName.isEmpty ? "reference" : rawName).png" - let data = (try? Data(contentsOf: URL(fileURLWithPath: path))) ?? part.previewPNG ?? ImageTurnPlanner.pngHeader - guard let attachment = ChatAttachment(name: validName, data: data, sourcePath: path) else { return } + let attachment: ChatAttachment? = if let preview = part.previewPNG, !preview.isEmpty { + ChatAttachment(name: validName, data: preview, sourcePath: path) + } else { + ChatAttachment.deferredReference(name: validName, sourcePath: path) + } + guard let attachment else { return } state.attachments.removeAll { $0.sourcePath == path } let imageCount = state.attachments.filter { $0.kind == "image" }.count if imageCount >= 10, let oldestIdx = state.attachments.firstIndex(where: { $0.kind == "image" }) { diff --git a/Sources/BasaltAppCore/Chat/GeneratedImagePart.swift b/Sources/BasaltAppCore/Chat/GeneratedImagePart.swift index e76790d01..fbda33fb4 100644 --- a/Sources/BasaltAppCore/Chat/GeneratedImagePart.swift +++ b/Sources/BasaltAppCore/Chat/GeneratedImagePart.swift @@ -96,6 +96,7 @@ public struct ImageGenerationCall: Sendable, Equatable, Codable { public var reuseReferenceKV = true public var upscaleFactor: Int? public var referenceImages: [Data] + public var referenceImagePaths: [String] = [] public var beforeFilePath: String? public init( @@ -115,7 +116,7 @@ public struct ImageGenerationCall: Sendable, Equatable, Codable { } public var endpointPath: String { - referenceImages.isEmpty ? "v1/images/generations" : "v1/images/edits" + (referenceImages.isEmpty && referenceImagePaths.isEmpty) ? "v1/images/generations" : "v1/images/edits" } public func wireBody() throws -> Data { diff --git a/Sources/BasaltMac/BasaltMacApp.swift b/Sources/BasaltMac/BasaltMacApp.swift index 9e893d6f4..98887730d 100644 --- a/Sources/BasaltMac/BasaltMacApp.swift +++ b/Sources/BasaltMac/BasaltMacApp.swift @@ -99,7 +99,7 @@ struct BasaltMacApp: App { MenuBarLabel(delegate: delegate) } .menuBarExtraStyle(.window) - Settings { SettingsView(keychain: .live()) { arguments in await delegate.model?.switchEngine(arguments) } } + Settings { SettingsView(keychain: .live()) { arguments in await delegate.model?.switchEngine(arguments, forceRestart: true) } } } static func makeModel() -> AppModel? { diff --git a/Sources/BasaltMac/Intents.swift b/Sources/BasaltMac/Intents.swift index cc5817bc1..637344566 100644 --- a/Sources/BasaltMac/Intents.swift +++ b/Sources/BasaltMac/Intents.swift @@ -66,9 +66,9 @@ struct SwitchModelIntent: AppIntent { @MainActor func perform() async throws -> some IntentResult & ReturnsValue { - let (_, endpoint) = try await AppServices.engine() + let (appModel, endpoint) = try await AppServices.engine() let loaded = try await IntentActions.switchModel(model, library: .live(endpoint)) - UserDefaults.standard.set(loaded, forKey: "model") + await appModel.recordLoadedModel(loaded) return .result(value: loaded) } } diff --git a/Sources/BasaltMac/SystemServices.swift b/Sources/BasaltMac/SystemServices.swift index cce0c9f8c..6bb439ed6 100644 --- a/Sources/BasaltMac/SystemServices.swift +++ b/Sources/BasaltMac/SystemServices.swift @@ -31,10 +31,19 @@ final class ServiceProvider: NSObject { if let arguments = applyLaunch(urls) { Task { await model.switchEngine(arguments) } } - let attachments = urls.filter(\.isFileURL).compactMap { url in (try? Data(contentsOf: url)).flatMap { ChatAttachment(name: url.lastPathComponent, data: $0) } } - guard !attachments.isEmpty else { return } - model.startConversation(text: "", attachments: attachments) - show() + let fileURLs = urls.filter { $0.isFileURL && ChatAttachment.accepts($0.lastPathComponent) } + guard !fileURLs.isEmpty else { return } + Task { + var attachments: [ChatAttachment] = [] + for url in fileURLs { + if let attachment = await ChatAttachment.loadAsync(from: url) { + attachments.append(attachment) + } + } + guard !attachments.isEmpty else { return } + model.startConversation(text: "", attachments: attachments) + show() + } } } diff --git a/Tests/BasaltTests/App/AppImageCanvasTests.swift b/Tests/BasaltTests/App/AppImageCanvasTests.swift index a6faa0133..695a0fc43 100644 --- a/Tests/BasaltTests/App/AppImageCanvasTests.swift +++ b/Tests/BasaltTests/App/AppImageCanvasTests.swift @@ -149,7 +149,7 @@ struct AppImageCanvasReducerAndStoreTests { Issue.record("Expected .generateImage effect for I2I edit") return } - #expect(!editCall.referenceImages.isEmpty && editCall.beforeFilePath == "/tmp/basalt-second.png") + #expect(editCall.referenceImages.isEmpty && editCall.referenceImagePaths == ["/tmp/basalt-second.png"] && editCall.beforeFilePath == "/tmp/basalt-second.png") #expect(editCall.endpointPath == "v1/images/edits") } diff --git a/Tests/BasaltTests/App/AppLifecycleL10nDefectRegressionTests.swift b/Tests/BasaltTests/App/AppLifecycleL10nDefectRegressionTests.swift new file mode 100644 index 000000000..89f33260f --- /dev/null +++ b/Tests/BasaltTests/App/AppLifecycleL10nDefectRegressionTests.swift @@ -0,0 +1,235 @@ +import BasaltCore +import Foundation +import Synchronization +import Testing +@testable import BasaltApp +@testable import BasaltAppCore + +@Suite("App lifecycle, attachment I/O, image edit/regen, and localization defect regressions (A-A1, A-A3, A-A10, A-A11, A-A13)", .timeLimit(.minutes(1))) +struct AppLifecycleL10nDefectRegressionTests { + typealias Fixture = EngineSupervisorTests.Fixture + + private static func makeStubEngine() -> EngineClient { + EngineClient( + chat: { _ in AsyncThrowingStream { $0.finish() } }, + health: { true }, + stats: { ServerTelemetrySnapshot() } + ) + } + + @Test("refreshedEnvironment preserves BASALT_METALLIB while refreshing and dropping cloud keys (A-A1)") + func refreshedEnvironmentPreservesMetallib() { + let current = [ + "BASALT_METALLIB": "/Applications/Basalt.app/Contents/Resources/mlx.metallib", + "OPENROUTER_API_KEY": "old-key", + ] + let updated = AppModel.refreshedEnvironment( + preserving: current, + cloud: ["GEMINI_API_KEY": "new-key"] + ) + #expect(updated["BASALT_METALLIB"] == "/Applications/Basalt.app/Contents/Resources/mlx.metallib") + #expect(updated["GEMINI_API_KEY"] == "new-key") + #expect(updated["OPENROUTER_API_KEY"] == nil) + + let cleared = AppModel.refreshedEnvironment(preserving: current, cloud: [:]) + #expect(cleared == ["BASALT_METALLIB": "/Applications/Basalt.app/Contents/Resources/mlx.metallib"]) + } + + @MainActor + @Test("restart and switchEngine preserve BASALT_METALLIB and relaunch when cloud keys change or forceRestart is set (A-A1)") + func restartAndSwitchEngineRefreshEnvironment() async throws { + let fixture = try Fixture() + let baseLaunch = try fixture.script(EngineSupervisorTests.ready) + let launch = HelperLaunch( + executable: baseLaunch.executable, + arguments: baseLaunch.arguments, + environment: ["BASALT_METALLIB": "/app/mlx.metallib", "OLD_CLOUD_KEY": "stale"] + ) + let cloudBox = Mutex<[String: String]>(["OLD_CLOUD_KEY": "stale"]) + let app = try AppModel( + launch: launch, + model: "org/m", + storeURL: nil, + environment: fixture.environment(), + drafts: DraftStore(load: { _ in "" }, save: { _, _ in }), + cloudEnvironment: { cloudBox.withLock { $0 } } + ) + await app.start() + #expect(await app.readyEndpoint(within: .seconds(5)) != nil) + + cloudBox.withLock { $0 = ["OPENROUTER_API_KEY": "sk-fresh"] } + await app.switchEngine(launch.arguments) + let afterCloudSwitch = await app.supervisor.launch + #expect(afterCloudSwitch.environment["BASALT_METALLIB"] == "/app/mlx.metallib") + #expect(afterCloudSwitch.environment["OPENROUTER_API_KEY"] == "sk-fresh") + #expect(afterCloudSwitch.environment["OLD_CLOUD_KEY"] == nil) + + await app.restart() + let afterRestart = await app.supervisor.launch + #expect(afterRestart.environment["BASALT_METALLIB"] == "/app/mlx.metallib") + #expect(afterRestart.environment["OPENROUTER_API_KEY"] == "sk-fresh") + + await app.switchEngine(launch.arguments, forceRestart: true) + #expect(await app.readyEndpoint(within: .seconds(5)) != nil) + await app.stop() + } + + @MainActor + @Test("recordLoadedModel and hotSwitchModel sync configuredModel, supervisor launch args, and loaded library state (A-A3)") + func recordLoadedModelSyncsStateAndSupervisor() async throws { + let fixture = try Fixture() + let launch = try fixture.script(EngineSupervisorTests.ready) + let previousDefault = UserDefaults.standard.string(forKey: EngineChoice.modelKey) + defer { + if let previousDefault { + UserDefaults.standard.set(previousDefault, forKey: EngineChoice.modelKey) + } else { + UserDefaults.standard.removeObject(forKey: EngineChoice.modelKey) + } + } + let app = try AppModel( + launch: launch, + model: "org/initial", + storeURL: nil, + environment: fixture.environment(), + drafts: DraftStore(load: { _ in "" }, save: { _, _ in }) + ) + app.library.send(.listed([ + LibraryModel(id: "org/initial", sizeBytes: 100, isLoaded: true), + LibraryModel(id: "org/next", sizeBytes: 100, isLoaded: false), + ])) + #expect(app.model == "org/initial") + + await app.recordLoadedModel("org/next") + #expect(app.configuredModel == "org/next") + #expect(app.model == "org/next") + #expect(await app.supervisor.launch.arguments == ["serve", "--model", "org/next"]) + + var stubClient = Self.makeStubEngine() + stubClient.loadModel = { id in id } + let switched = try await app.hotSwitchModel("org/third", client: stubClient) + #expect(switched == "org/third") + #expect(app.configuredModel == "org/third") + #expect(await app.supervisor.launch.arguments == ["serve", "--model", "org/third"]) + } + + @Test("ChatAttachment.load rejects oversized, empty, unsupported, and directory URLs without reading and loads valid files async (A-A10)") + func attachmentPreCheckAndAsyncLoad() async throws { + let dir = FileManager.default.temporaryDirectory.appending(path: "attach-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + + #expect(ChatAttachment.load(from: dir) == nil) + + let unsupported = dir.appending(path: "clip.mp4") + try Data([0x00, 0x01]).write(to: unsupported) + #expect(ChatAttachment.load(from: unsupported) == nil) + + let emptyPNG = dir.appending(path: "empty.png") + try Data().write(to: emptyPNG) + #expect(ChatAttachment.load(from: emptyPNG) == nil) + + let hugePNG = dir.appending(path: "huge.png") + FileManager.default.createFile(atPath: hugePNG.path, contents: nil) + let handle = try FileHandle(forWritingTo: hugePNG) + try handle.truncate(atOffset: UInt64(ChatAttachment.byteLimit) + 1024) + try handle.close() + #expect(ChatAttachment.load(from: hugePNG) == nil) + + let validPNG = dir.appending(path: "ok.png") + let payload = Data([0x89, 0x50, 0x4E, 0x47, 0x01, 0x02]) + try payload.write(to: validPNG) + let loaded = await ChatAttachment.loadAsync(from: validPNG) + #expect(loaded?.name == "ok.png" && loaded?.kind == "image" && loaded?.data == payload) + } + + @Test("InlineVideoIO.copyFile copies atomically off MainActor and preserves source when destination matches (A-A10)") + func inlineVideoAtomicCopy() async throws { + let dir = FileManager.default.temporaryDirectory.appending(path: "video-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + + let src = dir.appending(path: "src.mp4") + let dst = dir.appending(path: "dst.mp4") + let bytes = Data(repeating: 0x5A, count: 4096) + try bytes.write(to: src) + + try await InlineVideoIO.copyFile(from: src, to: dst) + #expect(try Data(contentsOf: dst) == bytes) + + try Data([0x01]).write(to: dst) + try await InlineVideoIO.copyFile(from: src, to: dst) + #expect(try Data(contentsOf: dst) == bytes) + + try await InlineVideoIO.copyFile(from: src, to: src) + #expect(try Data(contentsOf: src) == bytes) + } + + @MainActor + @Test("Missing reference image during edit or regeneration fails cleanly instead of uploading an 8-byte PNG header (A-A11)") + func missingImageReferenceFailsCleanly() async throws { + let missingPath = "/tmp/nonexistent-basalt-ref-\(UUID().uuidString).png" + var state = ChatState(conversation: ConversationSnapshot(id: ConversationID(), model: "Tongyi-MAI/Z-Image-Turbo")) + var part = GeneratedImagePart(assetID: "gone.png", prompt: "Spire", width: 512, height: 512, totalSteps: 4) + part.filePath = missingPath + _ = ChatReducer.reduce(&state, .editGeneratedImage(part)) + #expect(state.attachments.count == 1 && state.attachments[0].data.isEmpty && state.attachments[0].sourcePath == missingPath) + + state.draft = "Make it purple" + let run = RunID() + let effects = ChatReducer.reduce(&state, .send(message: MessageID(), reply: MessageID(), run: run)) + guard effects.count == 2, case .generateImage(run, let call) = effects[1] else { + Issue.record("Expected .generateImage effect") + return + } + #expect(call.referenceImages.isEmpty && call.referenceImagePaths == [missingPath] && call.endpointPath == "v1/images/edits") + + let engineCalled = Mutex(false) + var stubEngine = Self.makeStubEngine() + stubEngine.streamImage = { _ in + engineCalled.withLock { $0 = true } + return AsyncThrowingStream { $0.finish() } + } + let frozenEngine = stubEngine + let env = ChatEnvironment(engine: { frozenEngine }, persist: { _ in }) + let store = Store( + ChatState(conversation: ConversationSnapshot(id: ConversationID(), model: "Tongyi-MAI/Z-Image-Turbo")), + reduce: ChatReducer.reduce, + handle: ChatEffects.handler(env) + ) + store.send(.editGeneratedImage(part)) + store.send(.draftChanged("Make it purple")) + store.send(.send(message: MessageID(), reply: MessageID(), run: RunID())) + await store.settle() + #expect(!engineCalled.withLock { $0 }) + if case .failed(.refused(let status, let message)) = store.state.run { + #expect(status == 400 && message.contains("Reference image could not be read")) + } else { + Issue.record("Expected .failed(.refused(400, ...)), got \(store.state.run)") + } + } + + @Test("Image regeneration builds path-based references and resolves real bytes asynchronously (A-A11)") + func regenerationResolvesRealReferenceBytes() async throws { + let dir = FileManager.default.temporaryDirectory.appending(path: "regen-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + + let refFile = dir.appending(path: "before.png") + let refBytes = Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xDE, 0xAD]) + try refBytes.write(to: refFile) + + var img = GeneratedImagePart(assetID: "out.png", prompt: "Sunset", width: 512, height: 512, totalSteps: 4) + img.beforeFilePath = refFile.path + let replyID = MessageID() + var conversation = ConversationSnapshot(id: ConversationID(), model: "Tongyi-MAI/Z-Image-Turbo") + conversation.messages = [ + MessageSnapshot(id: MessageID(), role: .user, parts: [.text("Sunset")]), + MessageSnapshot(id: replyID, role: .assistant, parts: [.image(img)]), + ] + let call = try #require(ChatReducer.imageRegenerationCall(in: conversation, target: replyID)) + #expect(call.referenceImages.isEmpty && call.referenceImagePaths == [refFile.path]) + let resolved = try await ChatEffects.resolveReferenceImages(call) + #expect(resolved.referenceImages == [refBytes] && resolved.referenceImagePaths.isEmpty) + } +} diff --git a/Tests/BasaltTests/App/AppShipTests.swift b/Tests/BasaltTests/App/AppShipTests.swift index 942e23fda..950dc8058 100644 --- a/Tests/BasaltTests/App/AppShipTests.swift +++ b/Tests/BasaltTests/App/AppShipTests.swift @@ -43,7 +43,10 @@ struct AppShipTests { @Test("Every static string in the app's views has a Russian translation") func russian() throws { let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() - let table = try #require(NSDictionary(contentsOf: root.appending(path: "Localization/ru.lproj/Localizable.strings")) as? [String: String]) + let enURL = root.appending(path: "Localization/en.lproj/Localizable.strings") + let ruURL = root.appending(path: "Localization/ru.lproj/Localizable.strings") + let en = try #require(NSDictionary(contentsOf: enURL) as? [String: String]) + let table = try #require(NSDictionary(contentsOf: ruURL) as? [String: String]) let untranslated: Set = ["Basalt", "GPU", "OPENROUTER_API_KEY"] let call = #/(?:Text|Button|Label|Toggle|TextField|Section|Tab|LabeledContent|Picker|SecureField|Window|WindowGroup|ContentUnavailableView|Link|DisclosureGroup|String\(localized:|accessibilityLabel\(Text|confirmationDialog)\(\s*"([^"\\]+)"/# var missing: [String] = [] @@ -56,5 +59,24 @@ struct AppShipTests { } #expect(missing.isEmpty, "untranslated: \(missing)") #expect(table.values.allSatisfy { !$0.isEmpty } && table.count >= 90) + #expect(Set(en.keys) == Set(table.keys)) + #expect(try Self.duplicateKeys(in: enURL).isEmpty) + #expect(try Self.duplicateKeys(in: ruURL).isEmpty) + for key in ["All %lld", "Target Budget: %@ bpw", "%lld-bit", "Estimated Size: %@ → %@", "Peak Conversion RAM: %@", "%@ of %@"] { + #expect(en[key] != nil && table[key] != nil, "missing interpolated key: \(key)") + } + } + + private static func duplicateKeys(in url: URL) throws -> [String] { + let raw = try String(contentsOf: url, encoding: .utf8) + let entry = #/^"((?:[^"\\]|\\.)*)"\s*=\s*"(?:[^"\\]|\\.)*";/# + var seen: Set = [] + var duplicates: [String] = [] + for line in raw.split(whereSeparator: \.isNewline) { + guard let match = String(line).firstMatch(of: entry) else { continue } + let key = String(match.1) + if !seen.insert(key).inserted { duplicates.append(key) } + } + return duplicates } }