Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Tests/DocAITests/ProviderHubTests.swift10// Description : Tests of the provider hub with a fake transport: provider11// list and status, keys, connection test, model catalogue12// and capabilities, custom endpoints, streaming passthrough,13// usage and cost accounting, data policy, persistence and14// the absence of secrets in everything the hub writes or15// returns.16// Module : DocAITests17// Repository : https://git.spboucher.ai/orix-docs18// Created : 2026-11-2219// Last Modified : 2026-11-2220//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import AstraCore94import AstraProviders95import Foundation96import Testing97@testable import DocAI9899@Suite struct ProviderListTests {100 @Test func listsEveryAstraCloudProviderInOrderAndNothingIsConfiguredAtFirst() async {101 let hub = makeHub()102 let list = await hub.providers()103 #expect(list.map(\.id.kind) == [.openAI, .anthropic, .google, .xAI, .mistral, .deepSeek, .moonshot, .cerebras, .deepInfra, .openRouter])104 #expect(list.allSatisfy { $0.state == .notConfigured && !$0.hasKey && $0.keyHint == nil && !$0.isOnDevice })105 #expect(list.map(\.displayName).contains("Kimi (Moonshot AI)"))106 }107108 @Test func providerIDRoundTrips() {109 for kind in ProviderKind.allCases where kind != .custom {110 #expect(ProviderID(rawValue: ProviderID(kind).rawValue) == ProviderID(kind))111 }112 let custom = ProviderID(kind: .custom, endpointID: "abc:def")113 #expect(custom.rawValue == "custom:abc:def")114 #expect(ProviderID(rawValue: custom.rawValue) == custom)115 #expect(ProviderID(rawValue: "custom") == nil)116 #expect(ProviderID(rawValue: "openAI:x") == nil)117 #expect(ProviderID(rawValue: "nope") == nil)118 // an endpoint id on a keyed provider is meaningless and dropped119 #expect(ProviderID(kind: .openAI, endpointID: "x").endpointID == nil)120 #expect(ProviderID(.mlx).credentialAccount == nil)121 #expect(ProviderID(.mistral).credentialAccount == "provider.mistral")122 #expect(custom.credentialAccount == "endpoint.abc:def")123 }124125 @Test func settingAKeyMakesTheProviderConfiguredAndShowsOnlyAMask() async throws {126 let store = InMemoryCredentialStore()127 let hub = makeHub(credentials: store)128 try await hub.setKey(" \(fakeKey)\n", for: ProviderID(.cerebras))129 let row = try await hub.provider(ProviderID(.cerebras))130 #expect(row.state == .configured && row.hasKey)131 #expect(row.keyHint == "csk-••••••••mnop")132 #expect(try store.secret(for: "provider.cerebras") == fakeKey) // trimmed, stored under Astra's account name133 #expect(await hub.hasKey(for: ProviderID(.cerebras)))134 #expect(await hub.hasKey(for: ProviderID(.mistral)) == false)135 }136137 @Test func anEmptyKeyIsRefused() async {138 let hub = makeHub()139 await #expect(throws: CredentialError.empty) { try await hub.setKey(" ", for: ProviderID(.openAI)) }140 #expect(await hub.providers().first { $0.id.kind == .openAI }?.state == .notConfigured)141 }142143 @Test func onDeviceProvidersTakeNoKey() async {144 let hub = makeHub()145 await hub.registerOnDeviceProvider(StubLocalProvider(kind: .mlx, ok: true))146 await #expect(throws: ProviderHubError.noKeyNeeded("On-device (MLX)")) { try await hub.setKey("x", for: ProviderID(.mlx)) }147 }148149 @Test func removingAKeyForgetsTheTestAndTheCatalogue() async throws {150 let store = InMemoryCredentialStore()151 let hub = makeHub(credentials: store)152 let id = ProviderID(.cerebras)153 try await hub.setKey(fakeKey, for: id)154 _ = try await hub.verify(id)155 _ = try await hub.models(for: id)156 try await hub.removeKey(for: id)157 let row = try await hub.provider(id)158 #expect(row.state == .notConfigured && !row.hasKey && row.detail == nil && row.modelCount == nil && row.lastCheckedAt == nil)159 #expect(try store.secret(for: "provider.cerebras") == nil)160 #expect(await hub.knownModels().isEmpty)161 }162163 @Test func replacingAKeyResetsTheVerification() async throws {164 let hub = makeHub()165 let id = ProviderID(.cerebras)166 try await hub.setKey(fakeKey, for: id)167 #expect(try await hub.verify(id).state == .verified)168 try await hub.setKey("csk-ANOTHERKEY0123456789abcdefghijWXYZ", for: id)169 let row = try await hub.provider(id)170 #expect(row.state == .configured)171 #expect(row.keyHint == "csk-••••••••WXYZ")172 }173}174175@Suite struct ConnectionTestTests {176 @Test func aWorkingKeyIsVerifiedWithTheModelCount() async throws {177 let transport = standardTransport()178 let hub = makeHub(transport)179 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))180 let row = try await hub.verify(ProviderID(.cerebras))181 #expect(row.state == .verified)182 #expect(row.modelCount == 2)183 #expect(row.detail?.contains("2") == true)184 #expect(row.lastCheckedAt == Date(timeIntervalSince1970: 1_795_000_000))185 // the key went out in the Authorization header of the keyed call, and nowhere else186 let keyed = transport.requests(containing: "api.cerebras.ai/v1/models")187 #expect(keyed.first?.value(forHTTPHeaderField: "Authorization") == "Bearer \(fakeKey)")188 #expect(transport.requests(containing: "/public/").allSatisfy { $0.value(forHTTPHeaderField: "Authorization") == nil })189 }190191 @Test func aRejectedKeyIsAnErrorStateNotAThrow() async throws {192 let transport = FakeTransport()193 transport.on("api.mistral.ai/v1/models", .json(401, #"{"message":"Unauthorized","request_id":"abc"}"#))194 let hub = makeHub(transport)195 try await hub.setKey("mstrl_BADKEY0123456789abcdef", for: ProviderID(.mistral))196 let row = try await hub.verify(ProviderID(.mistral))197 #expect(row.state == .error)198 #expect(row.errorTitle == "Key rejected")199 #expect(row.detail?.isEmpty == false)200 #expect(row.detail?.contains("BADKEY") == false)201 }202203 @Test func aNetworkFailureIsAnErrorState() async throws {204 let transport = FakeTransport()205 transport.on("api.mistral.ai", .fail(.network("The server could not be reached.")))206 let hub = makeHub(transport)207 try await hub.setKey("mstrl_KEY0123456789abcdefgh", for: ProviderID(.mistral))208 let row = try await hub.verify(ProviderID(.mistral))209 #expect(row.state == .error && row.errorTitle == "Network problem")210 }211212 @Test func verifyingWithoutAKeySendsNothing() async throws {213 let transport = standardTransport()214 let hub = makeHub(transport)215 let row = try await hub.verify(ProviderID(.cerebras))216 #expect(row.state == .notConfigured)217 #expect(transport.requests.isEmpty)218 }219220 @Test func verifyAllTestsOnlyWhatCanBeTested() async throws {221 let transport = standardTransport()222 let hub = makeHub(transport)223 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))224 try await hub.setKey("mstrl_KEY0123456789abcdefgh", for: ProviderID(.mistral))225 let rows = await hub.verifyAll()226 #expect(rows.filter { $0.state == .verified }.map(\.id.kind) == [.mistral, .cerebras])227 #expect(rows.filter { $0.state == .notConfigured }.count == 8)228 #expect(transport.requests.allSatisfy { $0.url!.host == "api.cerebras.ai" || $0.url!.host == "api.mistral.ai" })229 }230231 @Test func onDeviceProvidersAreVerifiedOrUnavailable() async throws {232 let hub = makeHub()233 await hub.registerOnDeviceProvider(StubLocalProvider(kind: .mlx, ok: true))234 await hub.registerOnDeviceProvider(StubLocalProvider(kind: .appleFoundation, ok: false))235 #expect(await hub.providers().suffix(2).map(\.id.kind) == [.appleFoundation, .mlx])236 #expect(try await hub.provider(ProviderID(.mlx)).state == .configured)237 #expect(try await hub.verify(ProviderID(.mlx)).state == .verified)238 let apple = try await hub.verify(ProviderID(.appleFoundation))239 #expect(apple.state == .unavailable && apple.detail == "stub says no" && apple.isOnDevice)240 }241242 @Test func anUnregisteredOnDeviceProviderIsUnknown() async {243 let hub = makeHub()244 await #expect(throws: ProviderHubError.unknownProvider("mlx")) { try await hub.verify(ProviderID(.mlx)) }245 }246}247248@Suite struct ModelCatalogueTests {249 @Test func modelsCarryCapabilitiesLimitsAndPricesFromTheProvider() async throws {250 let hub = makeHub()251 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))252 let models = try await hub.models(for: ProviderID(.cerebras))253 #expect(models.map(\.ref.modelID).sorted() == ["gpt-oss-120b", "qwen-3.8-27b"])254 let oss = try #require(models.first { $0.ref.modelID == "gpt-oss-120b" })255 let caps = oss.docCapabilities256 #expect(caps.pricing?.inputPerMTok == 0.35 && caps.pricing?.outputPerMTok == 0.75)257 #expect(caps.contextLength != nil)258 #expect(caps.sourceLabel == "Provider API")259 #expect(await hub.capabilities(of: oss.ref) == caps)260 #expect(await hub.modelInfo(oss.ref) == oss)261 }262263 @Test func theCatalogueIsCachedUntilRefreshed() async throws {264 let transport = standardTransport()265 let hub = makeHub(transport)266 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))267 _ = try await hub.models(for: ProviderID(.cerebras))268 let after1 = transport.requests.count269 _ = try await hub.models(for: ProviderID(.cerebras))270 #expect(transport.requests.count == after1)271 _ = try await hub.models(for: ProviderID(.cerebras), refresh: true)272 #expect(transport.requests.count > after1)273 #expect(await hub.catalogueDate(for: ProviderID(.cerebras)) != nil)274 #expect(try await hub.provider(ProviderID(.cerebras)).modelCount == 2)275 }276277 @Test func curatedCatalogueAnswersForModelsNeverListed() async {278 let hub = makeHub()279 // ORIX Astra's curated table (documentation figures) is the fallback: nothing is fetched, nothing is invented.280 let known = await hub.capabilities(of: ModelRef(provider: .openAI, modelID: "gpt-6-luna"))281 #expect(known?.pricing?.inputPerMTok == 0.10)282 #expect(known?.toolCalling == true && known?.vision == true)283 #expect(await hub.capabilities(of: ModelRef(provider: .openAI, modelID: "no-such-model")) == nil)284 }285286 @Test func listingWithoutAKeyFailsWithMissingCredential() async {287 let hub = makeHub()288 await #expect(throws: AstraError.missingCredential(.cerebras)) { _ = try await hub.models(for: ProviderID(.cerebras)) }289 }290291 @Test func mistralCapabilitiesComeFromItsAPI() async throws {292 let hub = makeHub()293 try await hub.setKey("mstrl_KEY0123456789abcdefgh", for: ProviderID(.mistral))294 let models = try await hub.models(for: ProviderID(.mistral))295 #expect(!models.isEmpty)296 #expect(models.contains { $0.docCapabilities.toolCalling })297 // no per-model price is published by that API: none is claimed298 #expect(models.allSatisfy { $0.pricing == nil })299 }300}301302@Suite struct CustomEndpointTests {303 @Test func anEndpointIsAddedListedVerifiedAndUsed() async throws {304 let transport = FakeTransport()305 transport.on("llm.example.com/v1/models", .json(200, AstraFixtures.text("custom_models.json")))306 transport.on("llm.example.com/v1/chat/completions", .sse(AstraFixtures.text("custom_text.sse")))307 let store = InMemoryCredentialStore()308 let hub = makeHub(transport, credentials: store)309 let row = try await hub.addEndpoint(name: "My server", baseURL: " https://llm.example.com/v1 ", key: "sk-custom-0123456789abcdef")310 #expect(row.displayName == "My server" && row.state == .configured && row.hasKey && row.baseURL == "https://llm.example.com/v1")311 let endpointID = try #require(row.id.endpointID)312 #expect(try store.secret(for: "endpoint.\(endpointID)") == "sk-custom-0123456789abcdef")313 #expect(await hub.providers().map(\.id).contains(row.id))314 #expect(try await hub.verify(row.id).state == .verified)315 let models = try await hub.models(for: row.id)316 let first = try #require(models.first)317 #expect(first.ref.provider == .custom && first.ref.endpointID == endpointID)318 let outcome = await hub.generate(GenerationRequest(model: first.ref, messages: [.user("Hello")]))319 #expect(outcome.error == nil && !outcome.text.isEmpty && outcome.stopReason == .endOfTurn)320 #expect(transport.requests(containing: "chat/completions").first?.value(forHTTPHeaderField: "Authorization") == "Bearer sk-custom-0123456789abcdef")321 }322323 @Test func insecureAndMalformedEndpointsAreRefusedByAstrasPolicy() async {324 let hub = makeHub()325 await #expect(throws: AstraError.self) { try await hub.addEndpoint(name: "Plain", baseURL: "http://llm.example.com/v1") }326 await #expect(throws: AstraError.self) { try await hub.addEndpoint(name: "Junk", baseURL: "not a url") }327 await #expect(throws: AstraError.self) { try await hub.addEndpoint(name: "Hdr", baseURL: "https://a.example/v1", extraHeaders: ["Authorization": "Bearer x"]) }328 await #expect(throws: AstraError.self) { try await hub.addEndpoint(name: " ", baseURL: "https://a.example/v1") }329 #expect(await hub.endpoints().isEmpty)330 }331332 @Test func localPlainHTTPNeedsTheExplicitSwitch() async throws {333 let hub = makeHub()334 await #expect(throws: AstraError.self) { try await hub.addEndpoint(name: "LM Studio", baseURL: "http://localhost:1234/v1") }335 let row = try await hub.addEndpoint(name: "LM Studio", baseURL: "http://localhost:1234/v1", allowInsecureHTTP: true)336 // a keyless endpoint is configured as soon as it exists337 #expect(row.state == .configured && !row.hasKey)338 }339340 @Test func namesAreUniqueAndUpdatesResetTheState() async throws {341 let transport = FakeTransport()342 transport.on("a.example/v1/models", .json(200, AstraFixtures.text("custom_models.json")))343 let hub = makeHub(transport)344 let row = try await hub.addEndpoint(name: "A", baseURL: "https://a.example/v1")345 await #expect(throws: ProviderHubError.duplicateEndpointName("a")) { try await hub.addEndpoint(name: "a", baseURL: "https://b.example/v1") }346 #expect(try await hub.verify(row.id).state == .verified)347 var profile = try #require(await hub.endpoints().first)348 profile.name = "Renamed"; profile.baseURL = "https://c.example/v1"349 try await hub.updateEndpoint(profile)350 let updated = try await hub.provider(row.id)351 #expect(updated.displayName == "Renamed" && updated.baseURL == "https://c.example/v1" && updated.state == .configured)352 profile.baseURL = "ftp://nope"353 await #expect(throws: AstraError.self) { try await hub.updateEndpoint(profile) }354 }355356 @Test func removingAnEndpointRemovesItsKey() async throws {357 let store = InMemoryCredentialStore()358 let hub = makeHub(credentials: store)359 let row = try await hub.addEndpoint(name: "A", baseURL: "https://a.example/v1", key: "sk-custom-0123456789abcdef")360 let endpointID = try #require(row.id.endpointID)361 try await hub.removeEndpoint(id: endpointID)362 #expect(await hub.endpoints().isEmpty)363 #expect(try store.accounts().isEmpty)364 await #expect(throws: ProviderHubError.unknownProvider("custom:\(endpointID)")) { try await hub.provider(row.id) }365 // a request for a removed endpoint ends with a clean error, not a crash and not another provider366 let outcome = await hub.generate(GenerationRequest(model: ModelRef(provider: .custom, modelID: "m", endpointID: endpointID), messages: [.user("x")]))367 #expect(outcome.error != nil && outcome.text.isEmpty)368 }369}370371@Suite struct StreamingTests {372 @Test func eventsPassThroughNormalizedWithOneStartAndOneEnd() async throws {373 let hub = makeHub()374 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))375 var events: [StreamEvent] = []376 for await event in hub.stream(cerebrasRequest()) { events.append(event) }377 guard case .messageStarted(let start)? = events.first else { Issue.record("no start"); return }378 #expect(start.reportedModel == "qwen-3.8-27b")379 #expect(events.filter { if case .messageStarted = $0 { true } else { false } }.count == 1)380 #expect(events.last == .messageCompleted(.endOfTurn))381 #expect(events.filter(\.isTerminal).count == 1)382 let text = events.compactMap { if case .textDelta(let t) = $0 { t } else { nil } }.joined()383 #expect(text == "ASTRA-OK")384 #expect(events.contains { if case .usage(let u) = $0 { u.inputTokens == 20 && u.outputTokens == 5 } else { false } })385 }386387 @Test func toolCallsArriveAsTypedEvents() async throws {388 let transport = standardTransport()389 transport.on("api.cerebras.ai/v1/chat/completions", .sse(AstraFixtures.text("cerebras_tool.sse")))390 let hub = makeHub(transport)391 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))392 let outcome = await hub.generate(cerebrasRequest("What is the weather in Paris?", tools: [weatherTool]))393 #expect(outcome.error == nil && outcome.stopReason == .toolCalls)394 // the recorded answer calls the tool twice, in parallel (Paris and Tokyo)395 #expect(outcome.toolCalls.map(\.name) == ["get_weather", "get_weather"])396 #expect(outcome.toolCalls.first?.arguments["city"]?.stringValue == "Paris")397 // the tool definition went out in the provider's wire format (Astra's adapter did the translation)398 let body = try #require(transport.requests(containing: "chat/completions").first?.httpBody.flatMap(JSONValue.parse))399 #expect(body["tools"]?.arrayValue?.count == 1)400 }401402 @Test func aMissingKeyEndsWithOneCleanError() async {403 let hub = makeHub()404 var events: [StreamEvent] = []405 for await event in hub.stream(cerebrasRequest()) { events.append(event) }406 #expect(events.last == .error(.missingCredential(.cerebras)))407 #expect(events.filter(\.isTerminal).count == 1)408 }409410 @Test func aProviderErrorIsRedactedAndTerminal() async throws {411 let transport = standardTransport()412 transport.on("api.cerebras.ai/v1/chat/completions", .json(401, #"{"message":"Wrong API Key","type":"invalid_request_error","code":"wrong_api_key"}"#))413 let hub = makeHub(transport)414 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))415 let outcome = await hub.generate(cerebrasRequest())416 guard case .unauthorized? = outcome.error else { Issue.record("expected unauthorized, got \(String(describing: outcome.error))"); return }417 #expect(outcome.stopReason == .error)418 }419420 @Test func cancellingTheConsumerCancelsTheRequest() async throws {421 let transport = standardTransport()422 var hanging = FakeTransport.Reply.sse(String(AstraFixtures.text("cerebras_text.sse").components(separatedBy: "\n\n").prefix(3).joined(separator: "\n\n")))423 hanging.hangs = true424 transport.on("api.cerebras.ai/v1/chat/completions", hanging)425 let hub = makeHub(transport)426 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))427 let task = Task { () -> Int in428 var n = 0429 for await _ in hub.stream(cerebrasRequest()) { n += 1 }430 return n431 }432 // wait until the request is really open, then cancel433 for _ in 0..<400 where transport.requests(containing: "chat/completions").isEmpty { try await Task.sleep(nanoseconds: 5_000_000) }434 try await Task.sleep(nanoseconds: 50_000_000)435 task.cancel()436 _ = await task.value437 for _ in 0..<400 where transport.cancelledStreams == 0 { try await Task.sleep(nanoseconds: 5_000_000) }438 #expect(transport.cancelledStreams == 1)439 // the cancelled request is accounted as cancelled, not as a failure440 for _ in 0..<400 { if await hub.usageSnapshot().total.requests == 1 { break }; try await Task.sleep(nanoseconds: 5_000_000) }441 let totals = await hub.usageSnapshot().total442 #expect(totals.requests == 1 && totals.cancellations == 1 && totals.failures == 0)443 }444445 @Test func onDeviceRequestsGoToTheRegisteredProviderOnly() async throws {446 let transport = standardTransport()447 let hub = makeHub(transport)448 await hub.registerOnDeviceProvider(StubLocalProvider(kind: .mlx, ok: true))449 let outcome = await hub.generate(GenerationRequest(model: ModelRef(provider: .mlx, modelID: "tiny"), messages: [.user("hi")]))450 #expect(outcome.text == "local answer" && outcome.error == nil)451 #expect(transport.requests.isEmpty)452 let totals = await hub.usageSnapshot().total453 #expect(totals.onDeviceRequests == 1 && totals.costUSD == 0)454 }455456 @Test func anOnDeviceFailureNeverFallsBackToTheCloud() async throws {457 let transport = standardTransport()458 let hub = makeHub(transport)459 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))460 await hub.registerOnDeviceProvider(StubLocalProvider(kind: .appleFoundation, ok: false))461 let outcome = await hub.generate(GenerationRequest(model: ModelRef(provider: .appleFoundation, modelID: "apple.system-language-model"), messages: [.user("hi")]))462 #expect(outcome.error == .unsupported("stub says no"))463 #expect(outcome.text.isEmpty)464 #expect(transport.requests.isEmpty)465 // and an on-device provider that is not registered at all is an error, not a reroute466 let none = await hub.generate(GenerationRequest(model: ModelRef(provider: .mlx, modelID: "tiny"), messages: [.user("hi")]))467 #expect(none.error != nil && transport.requests.isEmpty)468 }469}470471@Suite struct DataPolicyTests {472 @Test func cloudOffSendsNothing() async throws {473 let transport = standardTransport()474 let hub = makeHub(transport)475 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))476 await hub.setDataPolicy(.onDeviceOnly)477 let outcome = await hub.generate(cerebrasRequest(), containsDocumentContent: false)478 guard case .forbidden(let message)? = outcome.error else { Issue.record("expected forbidden"); return }479 #expect(message?.contains("not sent") == true)480 #expect(transport.requests.isEmpty)481 // a request that was never sent is not usage482 #expect(await hub.usageSnapshot().total.requests == 0)483 }484485 @Test func documentContentIsHeldBackButOtherRequestsPass() async throws {486 let transport = standardTransport()487 let hub = makeHub(transport)488 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))489 await hub.setDataPolicy(DataPolicy(allowCloud: true, allowDocumentContentInCloud: false))490 let refused = await hub.generate(cerebrasRequest(), containsDocumentContent: true)491 #expect(refused.error != nil && transport.requests.isEmpty)492 let allowed = await hub.generate(cerebrasRequest(), containsDocumentContent: false)493 #expect(allowed.error == nil && allowed.text == "ASTRA-OK")494 }495496 @Test func thePolicyNeverBlocksOnDeviceModels() {497 for kind in ProviderKind.allCases {498 for doc in [true, false] {499 let refusal = DataPolicy.onDeviceOnly.refusal(for: kind, containsDocumentContent: doc)500 #expect((refusal == nil) == kind.isLocal)501 #expect(DataPolicy.unrestricted.refusal(for: kind, containsDocumentContent: doc) == nil)502 }503 }504 }505506 @Test func documentContentIsTreatedAsPresentByDefault() async throws {507 let transport = standardTransport()508 let hub = makeHub(transport)509 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))510 await hub.setDataPolicy(DataPolicy(allowCloud: true, allowDocumentContentInCloud: false))511 // a caller that says nothing is assumed to carry document content: the safe default512 let outcome = await hub.generate(cerebrasRequest())513 #expect(outcome.error != nil && transport.requests.isEmpty)514 }515}516517@Suite struct AccountingAndPersistenceTests {518 @Test func usageAndCostAreRecordedPerProviderAndModel() async throws {519 let hub = makeHub()520 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))521 _ = try await hub.models(for: ProviderID(.cerebras)) // brings the published prices522 let outcome = await hub.generate(cerebrasRequest())523 _ = await hub.generate(cerebrasRequest())524 let snapshot = await hub.usageSnapshot()525 let model = try #require(snapshot.usage(for: ModelRef(provider: .cerebras, modelID: "qwen-3.8-27b")))526 #expect(model.requests == 2 && model.inputTokens == 40 && model.outputTokens == 10 && model.failures == 0)527 // qwen-3.8-27b: 0.99 $/M input, 1.49 $/M output → (20 × 0.99 + 5 × 1.49) / 1e6 per request528 let expected = 2 * (20 * 0.99 + 5 * 1.49) / 1_000_000529 #expect(abs(model.costUSD - expected) < 1e-12)530 #expect(model.costedRequests == 2 && model.costIsComplete)531 #expect(snapshot.usage(for: ProviderID(.cerebras))?.requests == 2)532 #expect(snapshot.providers.count == 1 && snapshot.days.count == 1)533 let cost = await hub.cost(of: outcome, model: cerebrasRequest().model)534 #expect(cost.basis == .estimatedFromUsage && abs((cost.amountUSD ?? 0) - expected / 2) < 1e-12)535 let preflight = await hub.preflightCost(inputTokens: 1_000_000, maxOutputTokens: 0, model: cerebrasRequest().model)536 #expect(abs((preflight.amountUSD ?? 0) - 0.99) < 1e-9)537 }538539 @Test func withoutAPublishedPriceTheCostIsUnavailableNotGuessed() async throws {540 let hub = makeHub()541 try await hub.setKey("mstrl_KEY0123456789abcdefgh", for: ProviderID(.mistral))542 _ = try await hub.models(for: ProviderID(.mistral))543 let request = GenerationRequest(model: ModelRef(provider: .mistral, modelID: "ministral-3b-latest"), messages: [.user("x")])544 let outcome = await hub.generate(request)545 #expect(outcome.error == nil)546 #expect(await hub.cost(of: outcome, model: request.model) == .unavailable)547 let totals = try #require(await hub.usageSnapshot().usage(for: request.model))548 #expect(totals.requests == 1 && totals.costedRequests == 0 && totals.costUSD == 0 && !totals.costIsComplete)549 #expect(totals.inputTokens == 11 && totals.outputTokens == 5)550 }551552 @Test func recordingCanBeTurnedOff() async throws {553 let hub = makeHub()554 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))555 _ = await hub.generate(cerebrasRequest(), recordUsage: false)556 #expect(await hub.usageSnapshot().total.requests == 0)557 }558559 @Test func stateSurvivesARestartAndNoSecretOrContentIsWritten() async throws {560 let folder = TempFolder()561 let store = InMemoryCredentialStore()562 let secretPrompt = "CONFIDENTIAL-DOCUMENT-SENTENCE-7731"563 do {564 let hub = makeHub(credentials: store, storage: folder.url)565 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))566 _ = try await hub.verify(ProviderID(.cerebras))567 _ = try await hub.models(for: ProviderID(.cerebras))568 _ = try await hub.addEndpoint(name: "My server", baseURL: "https://llm.example.com/v1", key: "sk-custom-SECRET0123456789abcdef")569 await hub.setDataPolicy(DataPolicy(allowCloud: true, allowDocumentContentInCloud: false))570 _ = await hub.generate(cerebrasRequest(secretPrompt), containsDocumentContent: false)571 }572 let files = try FileManager.default.contentsOfDirectory(atPath: folder.url.path).sorted()573 #expect(files == ["providers.json", "usage.json"])574 for file in files {575 let text = try String(contentsOf: folder.url.appendingPathComponent(file), encoding: .utf8)576 #expect(!text.contains(fakeKey) && !text.contains("SECRET0123456789") && !text.contains("FAKEKEY"), "\(file) holds a key")577 #expect(!text.contains(secretPrompt) && !text.contains("ASTRA-OK"), "\(file) holds content")578 #expect(!text.lowercased().contains("authorization") && !text.lowercased().contains("bearer"))579 }580 let reopened = makeHub(credentials: store, storage: folder.url)581 let row = try await reopened.provider(ProviderID(.cerebras))582 #expect(row.state == .verified && row.modelCount == 2)583 #expect(await reopened.endpoints().map(\.name) == ["My server"])584 #expect(await reopened.dataPolicy == DataPolicy(allowCloud: true, allowDocumentContentInCloud: false))585 #expect(await reopened.knownModels().count == 2)586 #expect(await reopened.usageSnapshot().total.requests == 1)587 }588589 @Test func providerUpdatesAreBroadcast() async throws {590 let hub = makeHub()591 var iterator = await hub.providerUpdates().makeAsyncIterator()592 let first = await iterator.next()593 #expect(first?.first { $0.id.kind == .cerebras }?.state == .notConfigured)594 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))595 let second = await iterator.next()596 #expect(second?.first { $0.id.kind == .cerebras }?.state == .configured)597 }598599 @Test func routeCandidatesCarryAvailabilityAndMeasuredSpeed() async throws {600 let hub = makeHub()601 try await hub.setKey(fakeKey, for: ProviderID(.cerebras))602 _ = try await hub.models(for: ProviderID(.cerebras))603 var candidates = await hub.routeCandidates()604 #expect(candidates.count == 2 && candidates.allSatisfy { $0.unavailableReason == nil && $0.providerName == "Cerebras" && !$0.isOnDevice })605 // a failed connection test makes its models unavailable, with the reason606 let transport = FakeTransport()607 transport.on("api.mistral.ai/v1/models", .json(200, AstraFixtures.text("mistral_models.json")), .json(401, "{}"))608 let hub2 = makeHub(transport)609 try await hub2.setKey("mstrl_KEY0123456789abcdefgh", for: ProviderID(.mistral))610 _ = try await hub2.models(for: ProviderID(.mistral))611 _ = try await hub2.verify(ProviderID(.mistral))612 candidates = await hub2.routeCandidates()613 #expect(!candidates.isEmpty && candidates.allSatisfy { $0.unavailableReason?.contains("Key rejected") == true })614 }615}616617/// A scripted on-device provider.618struct StubLocalProvider: ChatProvider {619 let kind: ProviderKind620 var ok: Bool621 func listModels() async throws -> [ModelInfo] { ok ? [ModelInfo(ref: ModelRef(provider: kind, modelID: "tiny"), displayName: "Tiny", contextLength: 4_096, source: .runtime)] : [] }622 func verify() async throws -> ConnectionStatus { ConnectionStatus(ok: ok, detail: ok ? "ready" : "stub says no", modelCount: ok ? 1 : 0) }623 func stream(_ request: GenerationRequest) -> AsyncThrowingStream<StreamEvent, Error> {624 AsyncThrowingStream { continuation in625 guard ok else { continuation.finish(throwing: AstraError.unsupported("stub says no")); return }626 continuation.yield(.messageStarted(MessageStart(reportedModel: "tiny")))627 continuation.yield(.textDelta("local answer"))628 continuation.yield(.usage(TokenUsage(inputTokens: 3, outputTokens: 2)))629 continuation.yield(.messageCompleted(.endOfTurn))630 continuation.finish()631 }632 }633}634