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/CredentialAndLedgerTests.swift10// Description : Tests of the macOS credential store (query attributes11// checked without touching the Keychain; one real round trip12// that runs only when ORIXDOCS_KEYCHAIN_TESTS=1) and of the13// usage ledger (sums, cost completeness, days, persistence,14// recovery).15// Module : DocAITests16// Repository : https://git.spboucher.ai/orix-docs17// Created : 2026-11-2218// Last Modified : 2026-11-2219//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author : Simon-Pierre Boucher25// Position : Professor of Finance26// Institution : Université du Québec en Outaouais (UQO)27// Department : Département des sciences administratives28// Organization : SP Boucher29//30// Website : https://spboucher.ai31// Git : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General : info@spboucher.ai38// Professional : contact@spboucher.ai39// Direct : simon@spboucher.ai40// Research : research@spboucher.ai41// Development : dev@spboucher.ai42// Support : support@spboucher.ai43// Security/Admin : admin@spboucher.ai44// Notifications : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification : Public71// Distribution : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License : None specified (no license file in this repository)85// Maintainer : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import AstraCore93import Foundation94import Security95import Testing96@testable import DocAI9798@Suite struct CredentialStoreTests {99 @Test func theServiceNameIsTheOneOfORIXDocs() {100 #expect(DocCredentials.service == "ai.spboucher.orix.docs.providers")101 #expect(DocCredentials.keychain().service == DocCredentials.service)102 #expect(DocCredentials.keychain().backend == .automatic)103 }104105 @Test func everyQueryIsScopedToOurServiceAndNeverSynchronised() {106 for dataProtection in [true, false] {107 let q = MacKeychainCredentialStore.baseQuery(service: "svc", account: "provider.openAI", dataProtection: dataProtection)108 #expect(q[kSecClass as String] as? String == kSecClassGenericPassword as String)109 #expect(q[kSecAttrService as String] as? String == "svc")110 #expect(q[kSecAttrAccount as String] as? String == "provider.openAI")111 // never synchronised: stated on the data protection keychain; the login keychain has no such notion (and must not be asked)112 #expect(q[kSecAttrSynchronizable as String] as? Bool == (dataProtection ? false : nil))113 #expect((q[kSecUseDataProtectionKeychain as String] as? Bool ?? false) == dataProtection)114 }115 // listing: still one service, never "all items"116 let all = MacKeychainCredentialStore.baseQuery(service: "svc", account: nil, dataProtection: true)117 #expect(all[kSecAttrService as String] as? String == "svc" && all[kSecAttrAccount as String] == nil)118 }119120 @Test func newItemsAreUnlockedOnlyAndThisDeviceOnly() {121 let a = MacKeychainCredentialStore.addAttributes(data: Data("k".utf8), label: "ORIX Docs: provider.openAI", dataProtection: true)122 #expect(a[kSecAttrAccessible as String] as? String == kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String)123 #expect(MacKeychainCredentialStore.addAttributes(data: Data(), label: "x", dataProtection: false)[kSecAttrAccessible as String] == nil)124 #expect(a[kSecValueData as String] as? Data == Data("k".utf8))125 // the label names the account, never the secret126 #expect(a[kSecAttrLabel as String] as? String == "ORIX Docs: provider.openAI")127 }128129 @Test func theInMemoryStoreFollowsTheSameContract() throws {130 let store = DocCredentials.inMemory()131 #expect(try store.secret(for: "provider.openAI") == nil)132 try store.setSecret(" sk-test-0123456789abcdef ", for: "provider.openAI")133 #expect(try store.secret(for: "provider.openAI") == "sk-test-0123456789abcdef")134 #expect(throws: CredentialError.empty) { try store.setSecret("\n", for: "provider.openAI") }135 try store.setSecret("sk-other-0123456789abcdef", for: "endpoint.x")136 #expect(try store.accounts() == ["endpoint.x", "provider.openAI"])137 try store.removeSecret(for: "provider.openAI")138 try store.removeSecret(for: "provider.openAI") // removing twice is not an error139 #expect(try store.accounts() == ["endpoint.x"])140 }141142 /// The real Keychain, under a throwaway service name, cleaned up afterwards. Opt-in: `ORIXDOCS_KEYCHAIN_TESTS=1`.143 @Test(.enabled(if: ProcessInfo.processInfo.environment["ORIXDOCS_KEYCHAIN_TESTS"] == "1"))144 func realKeychainRoundTrip() throws {145 let store = MacKeychainCredentialStore(service: "ai.spboucher.orix.docs.providers.tests." + UUID().uuidString)146 defer { try? store.removeAll() }147 #expect(try store.secret(for: "provider.mistral") == nil)148 #expect(try store.accounts().isEmpty)149 try store.setSecret(" test-value-one ", for: "provider.mistral")150 #expect(try store.secret(for: "provider.mistral") == "test-value-one")151 try store.setSecret("test-value-two", for: "provider.mistral") // replace152 #expect(try store.secret(for: "provider.mistral") == "test-value-two")153 try store.setSecret("test-value-three", for: "endpoint.abc")154 #expect(try store.accounts() == ["endpoint.abc", "provider.mistral"])155 #expect(throws: CredentialError.empty) { try store.setSecret(" ", for: "provider.mistral") }156 // another service sees nothing of this one157 #expect(try MacKeychainCredentialStore(service: store.service + ".other", backend: store.effectiveBackend).accounts().isEmpty)158 try store.removeSecret(for: "provider.mistral")159 #expect(try store.secret(for: "provider.mistral") == nil)160 try store.removeAll()161 #expect(try store.accounts().isEmpty)162 print("KEYCHAIN backend used by this unsigned test process: \(store.effectiveBackend.rawValue)")163 }164}165166@Suite struct UsageLedgerTests {167 let model = ModelRef(provider: .cerebras, modelID: "qwen-3.8-27b")168 static let pricing = Pricing(inputPerMTok: 1, outputPerMTok: 2, cachedInputPerMTok: 0.1, asOf: "2026-11-22")169 func record(_ m: ModelRef? = nil, input: Int? = 1_000, output: Int? = 500, cached: Int? = nil, reported: Double? = nil, pricing: Pricing? = UsageLedgerTests.pricing,170 stop: StopReason = .endOfTurn, at: Date = Date(timeIntervalSince1970: 1_795_000_000), ttft: Double? = 0.2, total: Double? = 1.2, speed: Double? = 50) -> UsageRecord {171 let m = m ?? model172 let usage: TokenUsage? = input == nil && output == nil ? nil : TokenUsage(inputTokens: input, outputTokens: output, cachedInputTokens: cached, reportedCostUSD: reported)173 return UsageRecord(model: m, at: at, usage: usage, cost: UsageAccounting.cost(usage: usage, pricing: pricing, provider: m.provider), stopReason: stop,174 timeToFirstToken: ttft, totalTime: total, tokensPerSecond: speed)175 }176177 @Test func sumsTokensCostAndLatency() async {178 let ledger = UsageLedger(fileURL: nil)179 await ledger.record(record())180 await ledger.record(record(input: 2_000, output: 0, cached: 1_000, ttft: 0.4, speed: 100))181 let t = await ledger.snapshot().total182 #expect(t.requests == 2 && t.inputTokens == 3_000 && t.outputTokens == 500 && t.cachedInputTokens == 1_000)183 // 1000 in + 500 out = 0.002 ; 1000 fresh + 1000 cached = 0.001 + 0.0001184 #expect(abs(t.costUSD - 0.0031) < 1e-12)185 #expect(t.costedRequests == 2 && t.costIsComplete && t.providerReportedCostUSD == 0)186 #expect(abs((t.meanTimeToFirstToken ?? 0) - 0.3) < 1e-12 && t.meanTokensPerSecond == 75 && t.meanTotalTime == 1.2)187 }188189 @Test func providerReportedCostWinsAndIsTracked() async {190 let ledger = UsageLedger(fileURL: nil)191 let or = ModelRef(provider: .openRouter, modelID: "openai/gpt-6-luna")192 await ledger.record(record(or, reported: 0.5))193 let t = await ledger.snapshot().total194 #expect(t.costUSD == 0.5 && t.providerReportedCostUSD == 0.5)195 }196197 @Test func missingUsageOrPriceIsCountedNotInvented() async {198 let ledger = UsageLedger(fileURL: nil)199 await ledger.record(record(input: nil, output: nil))200 await ledger.record(record(pricing: nil))201 let t = await ledger.snapshot().total202 #expect(t.requests == 2 && t.requestsWithoutUsage == 1 && t.costedRequests == 0 && t.costUSD == 0)203 #expect(!t.costIsComplete)204 #expect(t.inputTokens == 1_000)205 }206207 @Test func failuresAndCancellationsAreCountedApart() async {208 let ledger = UsageLedger(fileURL: nil)209 await ledger.record(record(input: nil, output: nil, stop: .error, ttft: nil, total: 0.1, speed: nil))210 await ledger.record(record(input: nil, output: nil, stop: .cancelled, ttft: nil, total: 0.1, speed: nil))211 await ledger.record(record())212 let t = await ledger.snapshot().total213 #expect(t.requests == 3 && t.failures == 1 && t.cancellations == 1)214 #expect(t.costIsComplete) // the one request that reached the end has a cost215 #expect(t.meanTokensPerSecond == 50)216 }217218 @Test func onDeviceRequestsCostNothing() async {219 let ledger = UsageLedger(fileURL: nil)220 await ledger.record(record(ModelRef(provider: .mlx, modelID: "Qwen3-0.6B-4bit")))221 let t = await ledger.snapshot().total222 #expect(t.onDeviceRequests == 1 && t.costUSD == 0 && t.costIsComplete)223 }224225 @Test func groupsByProviderEndpointAndDay() async {226 let ledger = UsageLedger(fileURL: nil)227 let day2 = Date(timeIntervalSince1970: 1_795_000_000 + 86_400)228 await ledger.record(record())229 await ledger.record(record(ModelRef(provider: .cerebras, modelID: "gpt-oss-120b"), at: day2))230 await ledger.record(record(ModelRef(provider: .custom, modelID: "m", endpointID: "e1")))231 await ledger.record(record(ModelRef(provider: .custom, modelID: "m", endpointID: "e2")))232 let s = await ledger.snapshot()233 #expect(s.providers.map(\.id) == ["cerebras", "custom:e1", "custom:e2"])234 #expect(s.providers[0].models.map(\.model.modelID) == ["gpt-oss-120b", "qwen-3.8-27b"])235 #expect(s.providers[0].totals.requests == 2)236 #expect(s.days.count == 2)237 #expect(s.days.map(\.totals.requests) == [3, 1])238 #expect(s.days[0].day == UsageLedger.day(Date(timeIntervalSince1970: 1_795_000_000)))239 #expect(UsageLedger.day(Date(timeIntervalSince1970: 0)) == "1970-01-01")240 #expect(s.total.lastUsedAt == day2)241 await ledger.forget(provider: ProviderID(kind: .custom, endpointID: "e1"))242 #expect(await ledger.snapshot().providers.map(\.id) == ["cerebras", "custom:e2"])243 }244245 @Test func absurdCountsSaturateInsteadOfTrapping() async {246 let ledger = UsageLedger(fileURL: nil)247 for _ in 0..<3 { await ledger.record(record(input: Int.max, output: Int.max, pricing: nil)) }248 let t = await ledger.snapshot().total249 #expect(t.inputTokens == 3 * TokenUsage.maxCount) // Astra caps each report; our sums cannot overflow250 var totals = UsageTotals(); totals.inputTokens = Int.max - 1251 var other = UsageTotals(); other.inputTokens = 10252 totals.merge(other)253 #expect(totals.inputTokens == Int.max)254 }255256 @Test func oldDaysAreDropped() async {257 let ledger = UsageLedger(fileURL: nil)258 for i in 0..<(UsageLedger.keptDays + 5) {259 await ledger.record(record(at: Date(timeIntervalSince1970: 1_700_000_000 + Double(i) * 86_400)))260 }261 let s = await ledger.snapshot()262 #expect(s.days.count == UsageLedger.keptDays)263 #expect(s.total.requests == UsageLedger.keptDays + 5) // per-model totals keep everything264 }265266 @Test func persistsAtomicallyAndReloads() async throws {267 let folder = TempFolder()268 let url = folder.url.appendingPathComponent("nested/usage.json")269 let ledger = UsageLedger(fileURL: url)270 await ledger.record(record())271 let reloaded = UsageLedger(fileURL: url)272 #expect(await reloaded.snapshot().total == ledger.snapshot().total)273 #expect(await reloaded.recoveredFrom == nil)274 await reloaded.reset()275 #expect(await UsageLedger(fileURL: url).snapshot().total.requests == 0)276 }277278 @Test func anUnreadableFileIsSetAsideAndAccountingContinues() async throws {279 let folder = TempFolder()280 let url = folder.url.appendingPathComponent("usage.json")281 try Data("{ not json".utf8).write(to: url)282 let ledger = UsageLedger(fileURL: url)283 #expect(await ledger.recoveredFrom == "unreadable file")284 #expect(FileManager.default.fileExists(atPath: url.path + ".unreadable"))285 await ledger.record(record())286 #expect(await UsageLedger(fileURL: url).snapshot().total.requests == 1)287 // a file of a future schema is not overwritten blindly either288 try? FileManager.default.removeItem(atPath: url.path + ".unreadable")289 try Data(#"{"schema":99,"since":"2026-11-22T00:00:00Z","models":[],"days":{}}"#.utf8).write(to: url)290 #expect(await UsageLedger(fileURL: url).recoveredFrom == "unsupported schema 99")291 #expect(FileManager.default.fileExists(atPath: url.path + ".unreadable"))292 }293}294