SPB Git

Repository Public License

PricingAndLedgerTests.swift 6.7 KB 120 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import ProviderKit56@Suite struct PricingTests {7    private let price = ModelPrice(inputPerMillion: 3, outputPerMillion: 15, cacheReadPerMillion: 0.3, cacheWritePerMillion: 3.75,8                                   source: .builtIn(asOf: "2026-11-03", url: "https://example.com/pricing"))910    @Test func estimateSeparatesCachedAndFreshInput() throws {11        // 1,000,000 input of which 400,000 cache reads and 100,000 cache writes; 200,000 output.12        let usage = ProviderUsage(inputTokens: 1_000_000, outputTokens: 200_000, cacheReadTokens: 400_000, cacheWriteTokens: 100_000)13        let estimate = try #require(CostEstimator.estimate(usage: usage, price: price))14        // 500k × 3 + 400k × 0.3 + 100k × 3.75 + 200k × 15, per million.15        #expect(abs(estimate.usd - (1.5 + 0.12 + 0.375 + 3.0)) < 1e-9)16        #expect(estimate.basis == .priceTable(price.source))17        #expect(estimate.label.contains("estimate"))18        #expect(estimate.label.contains("2026-11-03"))19    }2021    @Test func cachedTokensFallBackToTheInputPrice() throws {22        let plain = ModelPrice(inputPerMillion: 2, outputPerMillion: 10)23        let usage = ProviderUsage(inputTokens: 1_000_000, outputTokens: 0, cacheReadTokens: 500_000)24        #expect(try #require(CostEstimator.estimate(usage: usage, price: plain)).usd == 2)25    }2627    @Test func noEstimateWithoutUsageOrPrice() {28        #expect(CostEstimator.estimate(usage: nil, price: price) == nil)29        #expect(CostEstimator.estimate(usage: ProviderUsage(), price: price) == nil)              // provider reported nothing30        #expect(CostEstimator.estimate(usage: ProviderUsage(inputTokens: 10, outputTokens: 5), price: nil) == nil)31    }3233    @Test func providerReportedCostWinsAndIsStillLabelledAnEstimate() throws {34        let usage = ProviderUsage(inputTokens: 10, outputTokens: 5, reportedCostUSD: 0.0123)35        let estimate = try #require(CostEstimator.estimate(usage: usage, price: price))36        #expect(estimate.usd == 0.0123)37        #expect(estimate.basis == .providerReported)38        #expect(estimate.label.contains("estimate"))39        #expect(try #require(CostEstimator.estimate(usage: usage, price: nil)).usd == 0.0123)40    }4142    @Test func priceTableLookup() {43        var table = PriceTable.builtIn44        #expect(table.price(family: .anthropic, model: "claude-opus-5-5")?.inputPerMillion == 4)45        #expect(table.price(family: .anthropic, model: "Claude-Opus-5-5")?.outputPerMillion == 20)46        // A dated snapshot uses its alias; nothing else is matched loosely.47        #expect(table.price(family: .anthropic, model: "claude-haiku-4-5-20251001")?.inputPerMillion == 1)48        #expect(table.price(family: .anthropic, model: "claude-opus-5-5-preview") == nil)49        #expect(table.price(family: .anthropic, model: "claude-opus") == nil)50        #expect(table.price(family: .openAI, model: "claude-opus-5-5") == nil)51        #expect(table.price(family: .compatible, model: "llama3.2") == nil)52        #expect(table.price(family: .local, model: LocalModelIdentifier.appleSystemModel) == nil)5354        table.setPrice(ModelPrice(inputPerMillion: 0.5, outputPerMillion: 1), family: .compatible, model: "llama3.2")55        #expect(table.price(family: .compatible, model: "llama3.2")?.source == .user)56        table.setPrice(nil, family: .compatible, model: "llama3.2")57        #expect(table.price(family: .compatible, model: "llama3.2") == nil)58    }5960    @Test func livePricesAreMerged() {61        var table = PriceTable()62        let live = ModelPrice(inputPerMillion: 1, outputPerMillion: 2, source: .providerList(url: "u", fetchedAt: Date(timeIntervalSince1970: 0)))63        table.merge(liveModels: [ModelInfo(id: "vendor/a", price: live), ModelInfo(id: "vendor/b")], family: .openRouter)64        #expect(table.count == 1)65        #expect(table.price(family: .openRouter, model: "vendor/a") == live)66    }6768    @Test func priceTableSurvivesCoding() throws {69        let decoded = try JSONDecoder().decode(PriceTable.self, from: JSONEncoder().encode(PriceTable.builtIn))70        #expect(decoded == PriceTable.builtIn)71    }72}7374@Suite struct UsageLedgerTests {75    private func record(_ provider: String, space: SpaceID?, input: Int?, output: Int?, cost: Double?, at date: Date = Date(timeIntervalSince1970: 1_000)) -> UsageRecord {76        let usage: ProviderUsage? = input == nil && output == nil ? nil : ProviderUsage(inputTokens: input, outputTokens: output)77        return UsageRecord(date: date, providerID: provider, family: .openAI, model: "m", spaceID: space, usage: usage,78                           cost: cost.map { CostEstimate(usd: $0, basis: .priceTable(.user)) })79    }8081    @Test func totalsPerProviderAndPerSpace() async {82        let ledger = InMemoryUsageLedger()83        let work = SpaceID(), home = SpaceID()84        await ledger.record(record("p1", space: work, input: 100, output: 10, cost: 0.01))85        await ledger.record(record("p1", space: home, input: 200, output: 20, cost: 0.02))86        await ledger.record(record("p2", space: work, input: 1_000, output: 50, cost: nil))87        await ledger.record(record("p2", space: nil, input: nil, output: nil, cost: nil))8889        let all = await ledger.totals()90        #expect(all.requests == 4)91        #expect(all.inputTokens == 1_300)92        #expect(all.outputTokens == 80)93        #expect(all.requestsWithUnknownUsage == 1)94        #expect(all.requestsWithUnknownCost == 2)95        #expect(abs(all.estimatedCostUSD - 0.03) < 1e-12)9697        #expect(await ledger.totals(providerID: "p1").inputTokens == 300)98        #expect(await ledger.totals(spaceID: work).inputTokens == 1_100)99        #expect(await ledger.totals(providerID: "p2", spaceID: work).requests == 1)100        let byProvider = await ledger.totalsByProvider()101        #expect(byProvider["p2"]?.requests == 2)102        #expect(byProvider["p2"]?.tokenUsage.estimatedCostUSD == nil)   // no request of p2 had an estimate103        #expect(byProvider["p1"]?.tokenUsage == TokenUsage(inputTokens: 300, outputTokens: 30, estimatedCostUSD: byProvider["p1"]?.estimatedCostUSD))104        let bySpace = await ledger.totalsBySpace()105        #expect(Set(bySpace.keys) == [work, home])106        #expect(bySpace[home]?.outputTokens == 20)107    }108109    @Test func sinceFilterAndCapacity() async {110        let ledger = InMemoryUsageLedger(capacity: 3)111        for index in 0..<5 {112            await ledger.record(record("p", space: nil, input: 1, output: 1, cost: 1, at: Date(timeIntervalSince1970: Double(index) * 100)))113        }114        #expect(await ledger.allRecords().count == 3)115        #expect(await ledger.totals(since: Date(timeIntervalSince1970: 300)).requests == 2)116        await ledger.removeAll()117        #expect(await ledger.totals().requests == 0)118    }119}120
Files main
Menu

Theme