Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Sources/DocAI/UsageLedger.swift10// Description : Usage and cost accounting per provider and model,11// persisted as one JSON file in Application Support. It12// stores counts, durations and amounts only: never a prompt,13// an answer, a document name, a key or a header. Costs come14// from ORIX Astra's `UsageAccounting` (provider-reported15// cost, or usage × published price, or "unavailable");16// nothing is guessed.17// Module : DocAI18// Repository : https://git.spboucher.ai/orix-docs19// Created : 2026-11-2220// Last Modified : 2026-11-2221//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author : Simon-Pierre Boucher27// Position : Professor of Finance28// Institution : Université du Québec en Outaouais (UQO)29// Department : Département des sciences administratives30// Organization : SP Boucher31//32// Website : https://spboucher.ai33// Git : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General : info@spboucher.ai40// Professional : contact@spboucher.ai41// Direct : simon@spboucher.ai42// Research : research@spboucher.ai43// Development : dev@spboucher.ai44// Support : support@spboucher.ai45// Security/Admin : admin@spboucher.ai46// Notifications : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification : Public73// Distribution : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License : None specified (no license file in this repository)87// Maintainer : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import AstraCore95import Foundation9697/// Totals for one model (or one day). Every field is a sum of what providers reported or the app measured.98public struct UsageTotals: Sendable, Codable, Hashable {99 public var requests = 0100 public var failures = 0101 public var cancellations = 0102 public var inputTokens = 0103 public var outputTokens = 0104 public var cachedInputTokens = 0105 public var reasoningTokens = 0106 /// Requests whose provider reported no token usage at all (their tokens are not in the sums above).107 public var requestsWithoutUsage = 0108 /// Sum of the costs that could be established (see `costedRequests`).109 public var costUSD = 0.0110 /// Requests that contributed to `costUSD`. When smaller than `requests`, the total is a lower bound and the UI must say so.111 public var costedRequests = 0112 /// Part of `costUSD` that the provider itself reported (the rest is usage × published price).113 public var providerReportedCostUSD = 0.0114 public var onDeviceRequests = 0115 // Latency, for the router and the diagnostics screen.116 public var timeToFirstTokenSum = 0.0117 public var timeToFirstTokenSamples = 0118 public var tokensPerSecondSum = 0.0119 public var tokensPerSecondSamples = 0120 public var totalTimeSum = 0.0121 public var totalTimeSamples = 0122 public var lastUsedAt: Date?123124 public init() {}125126 public var meanTimeToFirstToken: TimeInterval? { timeToFirstTokenSamples > 0 ? timeToFirstTokenSum / Double(timeToFirstTokenSamples) : nil }127 public var meanTokensPerSecond: Double? { tokensPerSecondSamples > 0 ? tokensPerSecondSum / Double(tokensPerSecondSamples) : nil }128 public var meanTotalTime: TimeInterval? { totalTimeSamples > 0 ? totalTimeSum / Double(totalTimeSamples) : nil }129 /// True when every request that reached the provider has a cost: `costUSD` is then the whole estimate, not a lower bound.130 public var costIsComplete: Bool { costedRequests + onDeviceRequests >= requests - cancellations - failures }131132 mutating func add(_ r: UsageRecord) {133 requests += 1134 switch r.stopReason {135 case .error: failures += 1136 case .cancelled: cancellations += 1137 default: break138 }139 if let u = r.usage, u.inputTokens != nil || u.outputTokens != nil {140 inputTokens = Self.saturating(inputTokens, u.inputTokens)141 outputTokens = Self.saturating(outputTokens, u.outputTokens)142 cachedInputTokens = Self.saturating(cachedInputTokens, u.cachedInputTokens)143 reasoningTokens = Self.saturating(reasoningTokens, u.reasoningTokens)144 } else {145 requestsWithoutUsage += 1146 }147 switch r.cost.basis {148 case .onDevice: onDeviceRequests += 1149 case .reportedByProvider, .estimatedFromUsage, .estimatedFromText:150 if let amount = r.cost.amountUSD, amount.isFinite, amount >= 0 {151 costUSD += amount; costedRequests += 1152 if r.cost.basis == .reportedByProvider { providerReportedCostUSD += amount }153 }154 case .unavailable: break155 }156 if let t = r.timeToFirstToken, t.isFinite, t >= 0 { timeToFirstTokenSum += t; timeToFirstTokenSamples += 1 }157 if let s = r.tokensPerSecond, s.isFinite, s > 0 { tokensPerSecondSum += s; tokensPerSecondSamples += 1 }158 if let t = r.totalTime, t.isFinite, t >= 0 { totalTimeSum += t; totalTimeSamples += 1 }159 lastUsedAt = max(lastUsedAt ?? r.at, r.at)160 }161162 mutating func merge(_ o: UsageTotals) {163 requests += o.requests; failures += o.failures; cancellations += o.cancellations164 inputTokens = Self.saturating(inputTokens, o.inputTokens); outputTokens = Self.saturating(outputTokens, o.outputTokens)165 cachedInputTokens = Self.saturating(cachedInputTokens, o.cachedInputTokens); reasoningTokens = Self.saturating(reasoningTokens, o.reasoningTokens)166 requestsWithoutUsage += o.requestsWithoutUsage167 costUSD += o.costUSD; costedRequests += o.costedRequests; providerReportedCostUSD += o.providerReportedCostUSD168 onDeviceRequests += o.onDeviceRequests169 timeToFirstTokenSum += o.timeToFirstTokenSum; timeToFirstTokenSamples += o.timeToFirstTokenSamples170 tokensPerSecondSum += o.tokensPerSecondSum; tokensPerSecondSamples += o.tokensPerSecondSamples171 totalTimeSum += o.totalTimeSum; totalTimeSamples += o.totalTimeSamples172 if let d = o.lastUsedAt { lastUsedAt = max(lastUsedAt ?? d, d) }173 }174175 /// Counts come from servers: a sum saturates instead of trapping.176 static func saturating(_ a: Int, _ b: Int?) -> Int {177 let (sum, overflow) = a.addingReportingOverflow(max(0, b ?? 0))178 return overflow ? Int.max : sum179 }180}181182/// One finished request, as handed to the ledger. No content.183public struct UsageRecord: Sendable, Hashable {184 public var model: ModelRef185 public var at: Date186 public var usage: TokenUsage?187 public var cost: CostEstimate188 public var stopReason: StopReason189 public var timeToFirstToken: TimeInterval?190 public var totalTime: TimeInterval?191 public var tokensPerSecond: Double?192 public init(model: ModelRef, at: Date = Date(), usage: TokenUsage?, cost: CostEstimate, stopReason: StopReason,193 timeToFirstToken: TimeInterval? = nil, totalTime: TimeInterval? = nil, tokensPerSecond: Double? = nil) {194 self.model = model; self.at = at; self.usage = usage; self.cost = cost; self.stopReason = stopReason195 self.timeToFirstToken = timeToFirstToken; self.totalTime = totalTime; self.tokensPerSecond = tokensPerSecond196 }197198 /// Builds the record of a finished generation. `pricing` is the model's published price when the catalogue has one.199 public init(model: ModelRef, outcome: GenerationOutcome, pricing: Pricing?, at: Date = Date()) {200 self.init(model: model, at: at, usage: outcome.usage,201 cost: UsageAccounting.cost(usage: outcome.usage, pricing: pricing, provider: model.provider),202 stopReason: outcome.stopReason, timeToFirstToken: outcome.timing.timeToFirstToken, totalTime: outcome.timing.totalTime,203 tokensPerSecond: outcome.timing.tokensPerSecond(outputTokens: outcome.usage?.outputTokens, reasoningTokens: outcome.usage?.reasoningTokens))204 }205}206207/// Totals of one model.208public struct ModelUsage: Sendable, Codable, Hashable, Identifiable {209 public var model: ModelRef210 public var totals: UsageTotals211 public var id: String { model.id }212}213214/// Totals of one provider (a custom endpoint counts as its own provider).215public struct ProviderUsage: Sendable, Hashable, Identifiable {216 public var provider: ProviderKind217 public var endpointID: String?218 public var totals: UsageTotals219 public var models: [ModelUsage]220 public var id: String { ProviderID(kind: provider, endpointID: endpointID).rawValue }221}222223/// Everything the ledger knows, as a value.224public struct UsageSnapshot: Sendable, Hashable {225 public var since: Date226 public var total: UsageTotals227 public var providers: [ProviderUsage]228 /// Per calendar day (UTC, "yyyy-MM-dd"), oldest first. At most `UsageLedger.keptDays` days are kept.229 public var days: [(day: String, totals: UsageTotals)] { dayTotals.sorted { $0.key < $1.key }.map { ($0.key, $0.value) } }230 var dayTotals: [String: UsageTotals]231232 public func usage(for model: ModelRef) -> UsageTotals? { providers.lazy.flatMap(\.models).first { $0.model == model }?.totals }233 public func usage(for provider: ProviderID) -> UsageTotals? { providers.first { $0.id == provider.rawValue }?.totals }234}235236/// The persisted ledger. An actor: records arrive from generation tasks, reads from the UI.237public actor UsageLedger {238 public static let keptDays = 400239 static let schema = 1240241 struct File: Codable {242 var schema = UsageLedger.schema243 var since: Date244 var models: [ModelUsage] = []245 var days: [String: UsageTotals] = [:]246 }247248 /// nil = memory only (tests, previews).249 public nonisolated let fileURL: URL?250 private var file: File251 private var loadFailure: String?252 private let now: @Sendable () -> Date253254 /// - Parameter fileURL: where the JSON lives; its folder is created on the first write. A file that cannot be read is kept aside255 /// (`usage.json.unreadable`) and a new ledger starts: accounting never blocks generation.256 public init(fileURL: URL?, now: @escaping @Sendable () -> Date = { Date() }) {257 self.fileURL = fileURL; self.now = now258 var loaded: File?259 var failure: String?260 if let fileURL, let data = try? Data(contentsOf: fileURL) {261 do {262 let decoded = try Self.decoder.decode(File.self, from: data)263 if decoded.schema == Self.schema { loaded = decoded } else { failure = "unsupported schema \(decoded.schema)" }264 } catch { failure = "unreadable file" }265 if failure != nil { try? FileManager.default.moveItem(at: fileURL, to: fileURL.appendingPathExtension("unreadable")) }266 }267 file = loaded ?? File(since: now())268 loadFailure = failure269 }270271 /// Why the previous file was set aside, when it was.272 public var recoveredFrom: String? { loadFailure }273274 static let encoder: JSONEncoder = {275 let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.sortedKeys, .prettyPrinted]; return e276 }()277 static let decoder: JSONDecoder = { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }()278279 static func day(_ date: Date) -> String {280 var calendar = Calendar(identifier: .gregorian); calendar.timeZone = TimeZone(identifier: "UTC") ?? .gmt281 let c = calendar.dateComponents([.year, .month, .day], from: date)282 return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)283 }284285 public func record(_ record: UsageRecord) {286 if let i = file.models.firstIndex(where: { $0.model == record.model }) { file.models[i].totals.add(record) }287 else { var t = UsageTotals(); t.add(record); file.models.append(ModelUsage(model: record.model, totals: t)) }288 let day = Self.day(record.at)289 var totals = file.days[day] ?? UsageTotals(); totals.add(record); file.days[day] = totals290 if file.days.count > Self.keptDays {291 for key in file.days.keys.sorted().dropLast(Self.keptDays) { file.days[key] = nil }292 }293 persist()294 }295296 public func snapshot() -> UsageSnapshot {297 var total = UsageTotals()298 var groups: [String: ProviderUsage] = [:]299 for entry in file.models {300 total.merge(entry.totals)301 let key = ProviderID(kind: entry.model.provider, endpointID: entry.model.endpointID).rawValue302 var group = groups[key] ?? ProviderUsage(provider: entry.model.provider, endpointID: entry.model.endpointID, totals: UsageTotals(), models: [])303 group.totals.merge(entry.totals); group.models.append(entry)304 groups[key] = group305 }306 let providers = groups.values.map { g -> ProviderUsage in307 var g = g; g.models.sort { $0.model.modelID < $1.model.modelID }; return g308 }.sorted { $0.id < $1.id }309 return UsageSnapshot(since: file.since, total: total, providers: providers, dayTotals: file.days)310 }311312 /// Erases the accounting ("Reset usage"). The file is rewritten empty.313 public func reset() {314 file = File(since: now()); persist()315 }316317 /// Forgets one provider (used when a custom endpoint is removed and the user asks to forget its usage too).318 public func forget(provider: ProviderID) {319 file.models.removeAll { ProviderID(kind: $0.model.provider, endpointID: $0.model.endpointID) == provider }320 persist()321 }322323 private func persist() {324 guard let fileURL else { return }325 do {326 try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)327 try Self.encoder.encode(file).write(to: fileURL, options: .atomic)328 } catch {329 // Accounting is best effort: a full disk must not fail a generation. The in-memory totals stay correct for this run.330 }331 }332}333