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/ModelRouterTests.swift10// Description : Tests of the model router: every mode, every rejection11// reason, the restrictions, determinism, and an exhaustive12// sweep (all modes × thousands of generated candidate sets,13// tasks and restrictions) of the invariants: Local Only and14// Privacy First never return a cloud model, a restriction is15// never bypassed, the choice always satisfies the task.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 Foundation95import Testing96@testable import DocAI9798private func cloud(_ provider: ProviderKind, _ id: String, context: Int? = 128_000, caps: Set<Capability> = [.text, .tools], price: (Double, Double)? = (1, 3),99 speed: Double? = nil, ttft: Double? = nil, tier: ModelTier? = nil, unavailable: String? = nil, endpoint: String? = nil, languages: Set<String>? = nil) -> RouteCandidate {100 RouteCandidate(model: ModelInfo(ref: ModelRef(provider: provider, modelID: id, endpointID: endpoint), displayName: id, contextLength: context, capabilities: caps,101 pricing: price.map { Pricing(inputPerMTok: $0.0, outputPerMTok: $0.1, asOf: "2026-11-22") }),102 unavailableReason: unavailable, tokensPerSecond: speed, timeToFirstToken: ttft, tier: tier, languages: languages)103}104private func local(_ id: String, context: Int? = 32_768, caps: Set<Capability> = [.text], memory: Int64? = 2 << 30, loaded: Bool = false, speed: Double? = nil,105 tier: ModelTier? = .small, languages: Set<String>? = nil, provider: ProviderKind = .mlx, unavailable: String? = nil) -> RouteCandidate {106 RouteCandidate(model: ModelInfo(ref: ModelRef(provider: provider, modelID: id), displayName: id, contextLength: context, capabilities: caps, source: .runtime),107 unavailableReason: unavailable, tokensPerSecond: speed, requiredMemoryBytes: memory, isLoaded: loaded, tier: tier, languages: languages)108}109private let apple = local("apple.system-language-model", context: 4_096, memory: nil, tier: .small, provider: .appleFoundation)110private func route(_ mode: RoutingMode, _ candidates: [RouteCandidate], task: TaskDescriptor = TaskDescriptor(estimatedInputTokens: 1_000), memory: Int64? = 16 << 30,111 restrictions: RoutingRestrictions = .none, manual: ModelRef? = nil) -> RoutingDecision {112 ModelRouter.route(RoutingRequest(mode: mode, task: task, candidates: candidates, availableMemoryBytes: memory, restrictions: restrictions, manualSelection: manual))113}114115@Suite struct RouterModeTests {116 let mixed = [cloud(.mistral, "big", caps: [.text, .tools, .reasoning], price: (3, 15), speed: 60, tier: .large), cloud(.cerebras, "fast", price: (0.5, 1), speed: 900, tier: .medium),117 cloud(.deepSeek, "cheap", price: (0.1, 0.2), speed: 30, tier: .medium), local("qwen-4b", caps: [.text, .tools, .reasoning], speed: 80, tier: .medium),118 local("smol", memory: 400 << 20, speed: 300, tier: .small), apple]119120 @Test func manualUsesThePickOrNothing() {121 let pick = ModelRef(provider: .deepSeek, modelID: "cheap")122 let d = route(.manual, mixed, manual: pick)123 #expect(d.chosen?.ref == pick && d.location == .cloud(provider: "DeepSeek"))124 #expect(d.reason.contains("you picked"))125 #expect(d.alternatives.isEmpty)126 #expect(d.rejected.count == mixed.count - 1 && d.rejected.allSatisfy { $0.code == .notTheManualSelection })127 // no selection, or a selection that is gone: nothing, never a substitute128 #expect(route(.manual, mixed).chosen == nil)129 #expect(route(.manual, mixed).reason.contains("No model is selected"))130 let gone = route(.manual, mixed, manual: ModelRef(provider: .openAI, modelID: "gone"))131 #expect(gone.chosen == nil && gone.reason.contains("not available any more"))132 }133134 @Test func manualStillObeysTheTaskAndTheRestrictions() {135 let pick = ModelRef(provider: .deepSeek, modelID: "cheap")136 let needsVision = route(.manual, mixed, task: TaskDescriptor(needsVision: true), manual: pick)137 #expect(needsVision.chosen == nil && needsVision.reason.contains("does not read images"))138 let noCloud = route(.manual, mixed, restrictions: RoutingRestrictions(allowCloud: false), manual: pick)139 #expect(noCloud.chosen == nil && noCloud.rejected.contains { $0.model == pick && $0.code == .cloudDisabled })140 // but a hand-picked small model is not second-guessed on a complex task141 let small = route(.manual, mixed, task: TaskDescriptor(complexity: .complex), manual: ModelRef(provider: .mlx, modelID: "smol"))142 #expect(small.chosen?.ref.modelID == "smol")143 }144145 @Test func localOnlyTakesTheMostCapableOnDeviceModel() {146 let d = route(.localOnly, mixed)147 #expect(d.chosen?.ref.modelID == "qwen-4b" && d.location == .onDevice && d.estimatedCostUSD == 0)148 #expect(d.reason.contains("never uses a cloud model"))149 #expect(Set(d.rejected.map(\.model.modelID)) == ["big", "fast", "cheap"])150 #expect(d.rejected.allSatisfy { $0.code == .modeIsOnDeviceOnly })151 #expect(d.alternatives.allSatisfy { $0.provider.isLocal })152 }153154 @Test func privacyFirstPrefersWhatIsLoadedThenTheSystemModel() {155 #expect(route(.privacyFirst, mixed).chosen?.ref.provider == .appleFoundation)156 var loaded = mixed; loaded[4].isLoaded = true157 let d = route(.privacyFirst, loaded)158 #expect(d.chosen?.ref.modelID == "smol" && d.reason.contains("already in memory"))159 // without the system model and nothing loaded: the most capable on-device model160 #expect(route(.privacyFirst, Array(mixed.dropLast())).chosen?.ref.modelID == "qwen-4b")161 }162163 @Test func onDeviceModesNeverFallBack() {164 let onlyCloud = Array(mixed.prefix(3))165 for mode in [RoutingMode.localOnly, .privacyFirst] {166 let d = route(mode, onlyCloud)167 #expect(d.chosen == nil && d.location == nil)168 #expect(d.reason.contains("Nothing was sent to the cloud"))169 // on-device models exist but none can do the task: still nothing170 let tools = route(mode, mixed, task: TaskDescriptor(needsVision: true))171 #expect(tools.chosen == nil && tools.reason.contains("never falls back to the cloud"))172 }173 }174175 @Test func fastestCompatibleUsesMeasuredSpeed() {176 let d = route(.fastestCompatible, mixed)177 #expect(d.chosen?.ref.modelID == "fast" && d.reason.contains("900 tokens per second"))178 #expect(d.alternatives.first?.modelID == "smol")179 // with tools needed the fastest model that has them wins180 let tools = route(.fastestCompatible, mixed, task: TaskDescriptor(needsTools: true))181 #expect(tools.chosen?.ref.modelID == "fast")182 // nothing measured: says so, takes the most capable183 let unmeasured = mixed.map { c -> RouteCandidate in var c = c; c.tokensPerSecond = nil; return c }184 let u = route(.fastestCompatible, unmeasured)185 #expect(u.chosen?.ref.modelID == "big" && u.reason.contains("no speed has been measured"))186 // equal speed: lower time to first token wins187 let tie = [cloud(.mistral, "a", speed: 100, ttft: 0.9), cloud(.mistral, "b", speed: 100, ttft: 0.2)]188 #expect(route(.fastestCompatible, tie).chosen?.ref.modelID == "b")189 }190191 @Test func lowestCostPrefersOnDeviceThenTheCheapestPrice() {192 let d = route(.lowestEstimatedCost, mixed)193 #expect(d.chosen?.isOnDevice == true && d.estimatedCostUSD == 0 && d.chosen?.ref.modelID == "qwen-4b")194 let cloudOnly = Array(mixed.prefix(3)) + [cloud(.moonshot, "unpriced", price: nil)]195 let c = route(.lowestEstimatedCost, cloudOnly, task: TaskDescriptor(estimatedInputTokens: 10_000, expectedOutputTokens: 1_000))196 #expect(c.chosen?.ref.modelID == "cheap")197 #expect(abs((c.estimatedCostUSD ?? 0) - (10_000 * 0.1 + 1_000 * 0.2) / 1_000_000) < 1e-15)198 #expect(c.alternatives.last?.modelID == "unpriced") // an unknown price ranks after every known one199 let unknown = route(.lowestEstimatedCost, [cloud(.moonshot, "unpriced", price: nil)])200 #expect(unknown.chosen != nil && unknown.estimatedCostUSD == nil && unknown.reason.contains("not published"))201 }202203 @Test func bestCapabilityTakesTheLargestReasoningModel() {204 let d = route(.bestAvailableCapability, mixed, task: TaskDescriptor(complexity: .complex))205 #expect(d.chosen?.ref.modelID == "big")206 // complex work keeps small models out, with a reason207 #expect(d.rejected.contains { $0.model.modelID == "smol" && $0.code == .tooSmallForTask })208 #expect(d.rejected.contains { $0.model.provider == .appleFoundation && $0.code == .tooSmallForTask })209 }210211 @Test func cloudPreferredFallsBackOnDeviceOnlyWhenNoCloudModelQualifies() {212 #expect(route(.cloudPreferred, mixed).chosen?.ref.modelID == "big")213 let restricted = route(.cloudPreferred, mixed, restrictions: RoutingRestrictions(neverSendDocumentContentToCloud: true))214 #expect(restricted.chosen?.ref.modelID == "qwen-4b" && restricted.location == .onDevice)215 #expect(restricted.reason.contains("no cloud model can do this task"))216 // the same task without document content may go to the cloud217 let free = route(.cloudPreferred, mixed, task: TaskDescriptor(containsDocumentContent: false), restrictions: RoutingRestrictions(neverSendDocumentContentToCloud: true))218 #expect(free.chosen?.ref.modelID == "big")219 }220221 @Test func everyModeHasATitleAndOnlyTwoAreOnDeviceOnly() {222 #expect(RoutingMode.allCases.count == 7)223 #expect(RoutingMode.allCases.map(\.title) == ["Manual", "Local Only", "Privacy First", "Fastest Compatible", "Lowest Estimated Cost", "Best Available Capability", "Cloud Preferred"])224 #expect(RoutingMode.allCases.filter(\.isOnDeviceOnly) == [.localOnly, .privacyFirst])225 }226}227228@Suite struct RouterRejectionTests {229 func code(_ candidate: RouteCandidate, task: TaskDescriptor = TaskDescriptor(), memory: Int64? = 16 << 30, restrictions: RoutingRestrictions = .none,230 mode: RoutingMode = .bestAvailableCapability) -> RoutingDecision.RejectionCode? {231 route(mode, [candidate], task: task, memory: memory, restrictions: restrictions).rejected.first?.code232 }233234 @Test func eachRequirementHasItsOwnReason() {235 #expect(code(cloud(.mistral, "m", unavailable: "Mistral has no API key.")) == .unavailable)236 #expect(code(cloud(.mistral, "m", caps: [.text]), task: TaskDescriptor(needsTools: true)) == .noToolCalling)237 #expect(code(cloud(.mistral, "m"), task: TaskDescriptor(needsStructuredOutput: true)) == .noStructuredOutput)238 #expect(code(cloud(.mistral, "m"), task: TaskDescriptor(needsVision: true)) == .noVision)239 #expect(code(cloud(.mistral, "m", context: 8_000), task: TaskDescriptor(estimatedInputTokens: 7_800, expectedOutputTokens: 512)) == .contextTooSmall)240 #expect(code(cloud(.mistral, "m", context: 8_000), task: TaskDescriptor(estimatedInputTokens: 7_000, expectedOutputTokens: 512)) == nil)241 #expect(code(cloud(.mistral, "m", context: nil), task: TaskDescriptor(estimatedInputTokens: 5_000)) == .contextUnknown)242 #expect(code(cloud(.mistral, "m", context: nil), task: TaskDescriptor(estimatedInputTokens: 1_000)) == nil)243 #expect(code(local("m", memory: 20 << 30)) == .notEnoughMemory)244 #expect(code(local("m", memory: 20 << 30, loaded: true)) == nil) // already in memory: needs nothing more245 #expect(code(local("m", memory: 20 << 30), memory: nil) == nil) // unknown available memory is not a reason246 #expect(code(local("m", languages: ["en"]), task: TaskDescriptor(language: "fr-CA")) == .languageNotSupported)247 #expect(code(local("m", languages: ["en", "fr"]), task: TaskDescriptor(language: "fr_CA")) == nil)248 #expect(code(local("m", languages: nil), task: TaskDescriptor(language: "ja")) == nil)249 #expect(code(local("m", tier: .small), task: TaskDescriptor(complexity: .complex)) == .tooSmallForTask)250 #expect(code(local("m", tier: nil), task: TaskDescriptor(complexity: .complex)) == nil)251 #expect(code(local("m", tier: .small), task: TaskDescriptor(complexity: .moderate)) == nil)252 }253254 @Test func restrictionsApplyInEveryMode() {255 let blocked = RoutingRestrictions(blockedProviders: [ProviderID(.mistral)])256 let custom = cloud(.custom, "m", endpoint: "e1")257 for mode in RoutingMode.allCases where !mode.isOnDeviceOnly {258 let manual = mode == .manual259 func decide(_ c: RouteCandidate, _ r: RoutingRestrictions, _ t: TaskDescriptor = TaskDescriptor()) -> RoutingDecision {260 route(mode, [c], task: t, restrictions: r, manual: manual ? c.ref : nil)261 }262 #expect(decide(cloud(.mistral, "m"), RoutingRestrictions(allowCloud: false)).rejected.first?.code == .cloudDisabled)263 #expect(decide(cloud(.mistral, "m"), RoutingRestrictions(neverSendDocumentContentToCloud: true)).rejected.first?.code == .documentContentRestricted)264 #expect(decide(cloud(.mistral, "m"), blocked).rejected.first?.code == .providerBlocked)265 #expect(decide(cloud(.cerebras, "m"), blocked).chosen != nil)266 // a custom endpoint is a cloud destination for the router, wherever it is hosted267 #expect(decide(custom, RoutingRestrictions(allowCloud: false)).chosen == nil)268 #expect(decide(custom, RoutingRestrictions(blockedProviders: [ProviderID(kind: .custom, endpointID: "e2")])).chosen != nil)269 #expect(decide(custom, RoutingRestrictions(blockedProviders: [ProviderID(kind: .custom, endpointID: "e1")])).chosen == nil)270 // cost limit: over → rejected; unknown price → rejected; on-device → never concerned271 let big = TaskDescriptor(estimatedInputTokens: 1_000_000, expectedOutputTokens: 0)272 #expect(decide(cloud(.mistral, "m", context: 2_000_000), RoutingRestrictions(maxEstimatedCostUSD: 0.5), big).rejected.first?.code == .overCostLimit)273 #expect(decide(cloud(.mistral, "m", context: 2_000_000), RoutingRestrictions(maxEstimatedCostUSD: 1.0), big).chosen != nil)274 #expect(decide(cloud(.mistral, "m", price: nil), RoutingRestrictions(maxEstimatedCostUSD: 1.0)).rejected.first?.code == .costUnknown)275 #expect(decide(local("m"), RoutingRestrictions(allowCloud: false, neverSendDocumentContentToCloud: true, maxEstimatedCostUSD: 0)).chosen != nil)276 }277 }278279 @Test func restrictionsFromTheHubPolicy() {280 #expect(RoutingRestrictions(.onDeviceOnly) == RoutingRestrictions(allowCloud: false, neverSendDocumentContentToCloud: true))281 #expect(RoutingRestrictions(.unrestricted) == RoutingRestrictions.none)282 #expect(RoutingRestrictions(DataPolicy(allowCloud: true, allowDocumentContentInCloud: false)).neverSendDocumentContentToCloud)283 }284285 @Test func noCandidateAtAllExplainsWhatToDo() {286 let d = route(.bestAvailableCapability, [])287 #expect(d.chosen == nil && d.reason.contains("No model is set up yet"))288 let all = route(.fastestCompatible, [cloud(.mistral, "a", unavailable: "Mistral has no API key."), cloud(.mistral, "b", unavailable: "Mistral has no API key."), local("c", memory: 99 << 30)])289 #expect(all.chosen == nil && all.reason.contains("Mistral has no API key.")) // the most frequent reason is the one shown290 #expect(all.rejected.map(\.model.modelID) == ["a", "b", "c"])291 }292293 @Test func rejectedCandidatesKeepTheInputOrderAndDuplicatesCountOnce() {294 let a = cloud(.mistral, "a", unavailable: "x"), b = cloud(.mistral, "b")295 let d = route(.bestAvailableCapability, [a, b, a, b])296 #expect(d.rejected.map(\.model.modelID) == ["a"] && d.chosen?.ref.modelID == "b" && d.alternatives.isEmpty)297 }298299 @Test func costEstimateIsExactAndOverflowSafe() {300 let c = cloud(.mistral, "m", price: (2, 8))301 #expect(ModelRouter.estimatedCost(of: TaskDescriptor(estimatedInputTokens: 500_000, expectedOutputTokens: 250_000), on: c) == 3.0)302 #expect(ModelRouter.estimatedCost(of: TaskDescriptor(), on: cloud(.mistral, "m", price: nil)) == nil)303 #expect(ModelRouter.estimatedCost(of: TaskDescriptor(estimatedInputTokens: 9_999_999), on: local("l")) == 0)304 let huge = TaskDescriptor(estimatedInputTokens: Int.max, expectedOutputTokens: Int.max)305 #expect(huge.totalTokens == Int.max)306 #expect(TaskDescriptor(estimatedInputTokens: -5, expectedOutputTokens: -1).totalTokens == 0)307 #expect(route(.bestAvailableCapability, [c], task: huge).rejected.first?.code == .contextTooSmall)308 }309310 @Test func tiersFromParameterCounts() {311 #expect(ModelTier.forParameters(nil) == nil && ModelTier.forParameters(0) == nil)312 #expect(ModelTier.forParameters(600_000_000) == .small)313 #expect(ModelTier.forParameters(4_000_000_000) == .medium)314 #expect(ModelTier.forParameters(8_000_000_000) == .large)315 }316}317318/// Deterministic generator (SplitMix64): the sweep is the same on every run.319struct Generator {320 var state: UInt64321 mutating func next() -> UInt64 {322 state &+= 0x9E37_79B9_7F4A_7C15323 var z = state324 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9325 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB326 return z ^ (z >> 31)327 }328 mutating func int(_ n: Int) -> Int { Int(next() % UInt64(n)) }329 mutating func bool(_ oneIn: Int = 2) -> Bool { int(oneIn) == 0 }330 mutating func pick<T>(_ items: [T]) -> T { items[int(items.count)] }331}332333@Suite struct RouterInvariantSweep {334 static let kinds: [ProviderKind] = [.openAI, .anthropic, .mistral, .cerebras, .openRouter, .custom, .mlx, .mlx, .appleFoundation]335336 static func candidate(_ g: inout Generator, _ index: Int) -> RouteCandidate {337 let kind = g.pick(kinds)338 var caps: Set<Capability> = [.text]339 for c in [Capability.tools, .vision, .reasoning, .structuredOutput] where g.bool() { caps.insert(c) }340 let ref = ModelRef(provider: kind, modelID: "m\(index % 7)", endpointID: kind == .custom ? "e\(g.int(2))" : nil)341 let info = ModelInfo(ref: ref, displayName: "M\(index)", contextLength: g.pick([nil, 2_048, 4_096, 32_768, 200_000]), capabilities: caps,342 pricing: kind.isLocal || g.bool(4) ? nil : Pricing(inputPerMTok: Double(g.int(50)) / 10, outputPerMTok: Double(g.int(200)) / 10, asOf: "2026-11-22"))343 return RouteCandidate(model: info, unavailableReason: g.bool(6) ? "unavailable" : nil, tokensPerSecond: g.bool() ? Double(g.int(500) + 1) : nil,344 timeToFirstToken: g.bool() ? Double(g.int(30)) / 10 : nil, requiredMemoryBytes: kind.isLocal && g.bool(3) == false ? Int64(g.int(40)) << 30 : nil,345 isLoaded: kind.isLocal && g.bool(4), tier: g.pick([nil, .small, .medium, .large]), languages: g.pick([nil, nil, ["en"], ["en", "fr"]]))346 }347348 static func request(_ g: inout Generator, mode: RoutingMode) -> RoutingRequest {349 let candidates = (0..<g.int(9)).map { candidate(&g, $0) }350 let task = TaskDescriptor(needsTools: g.bool(3), needsStructuredOutput: g.bool(5), needsVision: g.bool(5), estimatedInputTokens: g.pick([0, 500, 3_000, 30_000, 150_000]),351 expectedOutputTokens: g.pick([0, 256, 2_048]), language: g.pick([nil, "en", "fr-CA", "ja"]), complexity: g.pick(TaskComplexity.allCases),352 containsDocumentContent: g.bool())353 var blocked: Set<ProviderID> = []354 if g.bool(4) { blocked.insert(ProviderID(g.pick([.mistral, .mlx, .openAI]))) }355 let restrictions = RoutingRestrictions(allowCloud: !g.bool(4), neverSendDocumentContentToCloud: g.bool(3), blockedProviders: blocked,356 maxEstimatedCostUSD: g.pick([nil, nil, 0, 0.01, 1]))357 let manual: ModelRef? = mode == .manual && !candidates.isEmpty && !g.bool(5) ? g.pick(candidates).ref : nil358 return RoutingRequest(mode: mode, task: task, candidates: candidates, availableMemoryBytes: g.pick([nil, 4 << 30, 24 << 30]), restrictions: restrictions, manualSelection: manual)359 }360361 @Test func invariantsHoldForEveryModeOverGeneratedInputs() {362 var g = Generator(state: 20_261_122)363 var chosenCount = 0, cases = 0364 for mode in RoutingMode.allCases {365 for _ in 0..<4_000 {366 let r = Self.request(&g, mode: mode)367 let d = ModelRouter.route(r)368 cases += 1369 // 1. Deterministic, and independent of the order of the candidates.370 #expect(ModelRouter.route(r) == d)371 var shuffled = r; shuffled.candidates.reverse()372 let again = ModelRouter.route(shuffled)373 // (when the same model id is listed twice with different facts, the first listed wins: order matters only then)374 let unique = Set(r.candidates.map(\.id)).count == r.candidates.count375 if unique { #expect(again.chosen == d.chosen && again.alternatives == d.alternatives && again.reason == d.reason) }376 // 2. Every distinct candidate is either chosen, an alternative, or rejected with a reason: nothing disappears.377 let ids = Set(r.candidates.map(\.id))378 let accounted = Set(d.rejected.map(\.model.id)).union(d.alternatives.map(\.id)).union(d.chosen.map { [$0.id] } ?? [])379 #expect(accounted == ids)380 #expect(d.rejected.allSatisfy { !$0.reason.isEmpty })381 #expect(!d.reason.isEmpty)382 #expect((d.chosen == nil) == (d.location == nil))383 guard let c = d.chosen else { #expect(d.alternatives.isEmpty); continue }384 chosenCount += 1385 // 3. The on-device modes never leave this Mac. Neither do their alternatives.386 if mode.isOnDeviceOnly {387 #expect(c.ref.provider.isLocal && d.location == .onDevice)388 #expect(d.alternatives.allSatisfy { $0.provider.isLocal })389 }390 #expect(d.location == (c.isOnDevice ? .onDevice : .cloud(provider: c.providerName)))391 // 4. Restrictions are never bypassed, in any mode.392 if !c.isOnDevice {393 #expect(r.restrictions.allowCloud)394 #expect(!(r.task.containsDocumentContent && r.restrictions.neverSendDocumentContentToCloud))395 if let limit = r.restrictions.maxEstimatedCostUSD { #expect((d.estimatedCostUSD ?? .infinity) <= limit) }396 }397 #expect(!r.restrictions.blockedProviders.contains(ProviderID(model: c.ref)))398 // 5. The choice can do the task.399 #expect(c.unavailableReason == nil)400 if r.task.needsTools { #expect(c.model.capabilities.contains(.tools)) }401 if r.task.needsVision { #expect(c.model.capabilities.contains(.vision)) }402 if r.task.needsStructuredOutput { #expect(c.model.capabilities.contains(.structuredOutput)) }403 if let context = c.model.contextLength { #expect(r.task.totalTokens <= context) } else { #expect(r.task.totalTokens <= ModelRouter.unknownContextAllowance) }404 if c.isOnDevice, !c.isLoaded, let need = c.requiredMemoryBytes, let available = r.availableMemoryBytes { #expect(need <= available) }405 if let language = r.task.language, let supported = c.languages { #expect(supported.contains(ModelRouter.primaryLanguage(language))) }406 // 6. Manual never substitutes.407 if mode == .manual { #expect(c.ref == r.manualSelection && d.alternatives.isEmpty) }408 // 7. On-device is free; the estimate matches the published price.409 #expect(d.estimatedCostUSD == ModelRouter.estimatedCost(of: r.task, on: c))410 if c.isOnDevice { #expect(d.estimatedCostUSD == 0) }411 }412 }413 // the sweep is not vacuous: a good share of the cases ends with a choice414 #expect(cases == 28_000)415 #expect(chosenCount > 3_000, "only \(chosenCount) of \(cases) generated cases chose a model")416 }417418 @Test func aCloudModelCannotComeOutOfTheOnDeviceModesEvenWhenItIsTheOnlyPerfectFit() {419 // Adversarial: the cloud model is flawless, every on-device model is flawed in a different way.420 let perfect = cloud(.openAI, "perfect", context: 1_000_000, caps: Set(Capability.allCases), price: (0, 0), speed: 10_000, ttft: 0.01, tier: .large)421 let flawed = [local("no-memory", memory: 900 << 30), local("gone", unavailable: "not installed"), local("tiny-context", context: 512),422 local("apple", context: 4_096, provider: .appleFoundation, unavailable: "Apple Intelligence is turned off.")]423 let task = TaskDescriptor(needsTools: true, estimatedInputTokens: 3_000, complexity: .complex)424 for mode in [RoutingMode.localOnly, .privacyFirst] {425 for candidates in [[perfect] + flawed, flawed + [perfect], [perfect]] {426 let d = route(mode, candidates, task: task)427 #expect(d.chosen == nil && d.location == nil && d.alternatives.isEmpty)428 #expect(d.rejected.first { $0.model.modelID == "perfect" }?.code == .modeIsOnDeviceOnly)429 }430 // a "manual selection" smuggled into an on-device mode changes nothing431 let smuggled = ModelRouter.route(RoutingRequest(mode: mode, task: TaskDescriptor(), candidates: [perfect], manualSelection: perfect.ref))432 #expect(smuggled.chosen == nil)433 }434 }435}436