Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Docs9// File : Packages/ORIXDocsAI/Tests/DocLocalModelsTests/LocalModelLibraryTests.swift10// Description : Tests of the on-device model library with a fake server11// and a scripted runtime: the bundled catalogue, categories12// and metadata, downloads (progress, pause, resume, cancel,13// retry, checksum failure, atomic install), verification,14// repair, removal, loading under the memory governor,15// streaming generation, cancellation, unloading on memory16// pressure, and the registration of the on-device providers17// in the hub.18// Module : DocLocalModelsTests19// Repository : https://git.spboucher.ai/orix-docs20// Created : 2026-11-2221// Last Modified : 2026-11-2222//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import AstraCore96@testable import AstraLocal97import DocAI98@testable import DocLocalModels99import Foundation100import Testing101102private func request(_ id: String = "tiny", _ text: String = "Hello") -> GenerationRequest {103 GenerationRequest(model: ModelRef(provider: .mlx, modelID: id), messages: [.user(text)])104}105private func collect(_ stream: AsyncThrowingStream<StreamEvent, Error>) async -> (text: String, events: [StreamEvent], error: AstraError?) {106 var text = "", events: [StreamEvent] = []107 do {108 for try await event in stream { events.append(event); if case .textDelta(let t) = event { text += t } }109 return (text, events, nil)110 } catch { return (text, events, AstraError.wrap(error)) }111}112113@Suite struct BundledCatalogTests {114 @Test func theBundledCatalogueIsAstrasCatalogueByteForByte() throws {115 let package = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()116 let vendor = try Data(contentsOf: package.appendingPathComponent("Vendor/docs/catalog/catalog.json"))117 let resource = try Data(contentsOf: package.appendingPathComponent("Sources/DocLocalModels/Resources/catalog.json"))118 #expect(resource == vendor)119 // and what the built library really loads from its bundle is that same catalogue120 #expect(try LocalModelLibrary.bundledCatalog() == ModelCatalog.decode(vendor, origin: .bundled))121 }122123 @Test func itDecodesValidatesAndCoversEveryCategory() throws {124 let catalog = try LocalModelLibrary.bundledCatalog()125 #expect(catalog.models.count >= 30)126 // every file of every model is pinned by a SHA-256 and a commit: nothing can be downloaded unverified127 for card in catalog.models {128 #expect(card.revision.count == 40)129 let pinned = card.files.allSatisfy { $0.hasSHA256 }130 #expect(pinned, "\(card.id) has a file without a SHA-256")131 #expect(!card.licenseID.isEmpty && !card.publisher.isEmpty && card.totalBytes > 0)132 // Weights, tokenizers, templates and JSON. No pickle, no binary, no shell script. Two Phi repositories also list133 // Python files (their upstream `trust_remote_code` sources): they are stored as inert, checksummed data and nothing in134 // this stack can run them (see `downloadVerifiesEveryFileAndInstallsAtomically`).135 for file in card.files {136 let ext = (file.path as NSString).pathExtension.lowercased()137 #expect(["safetensors", "json", "txt", "jinja", "model", "md", "py"].contains(ext), "\(card.id) lists \(file.path)")138 }139 }140 for category in LocalModelCategory.allCases {141 let n = catalog.models.filter { LocalModelCategory.categories(of: $0).contains(category) }.count142 #expect(n > 0, "no model in \(category.title)")143 }144 }145146 @Test func categoriesComeFromTagsAndStatus() {147 #expect(LocalModelCategory.categories(of: Tiny.card(tags: [ModelTag.general, ModelTag.math])) == [.writing, .mathematics])148 #expect(LocalModelCategory.categories(of: Tiny.card(tags: [ModelTag.coding], status: .experimental)) == [.coding, .experimental])149 #expect(LocalModelCategory.categories(of: Tiny.card(tags: ["a-tag-from-the-future"])) == [])150 #expect(LocalModelCategory.allCases.map(\.title) == ["Lightweight", "Writing", "Reasoning", "Coding", "Mathematics", "Multilingual", "Vision", "Experimental"])151 }152153 @Test func theDefaultFolderIsUnderApplicationSupportORIXDocs() throws {154 let root = try LocalModelLibrary.defaultRoot()155 #expect(root.path.hasSuffix("/Library/Application Support/ORIX Docs/Models"))156 }157}158159@Suite struct LibraryCatalogTests {160 @Test func entriesCarryTheMetadataAndThisMacsVerdict() async throws {161 let folder = TempFolder()162 let big = Tiny.card(id: "huge", tags: [ModelTag.reasoning], files: [("config.json", Data("{}".utf8)), ("model.safetensors", Data())], parameters: 70_000_000_000)163 var huge = big; huge.files[1].size = 60 << 30; huge.totalBytes = 60 << 30164 let library = try Tiny.library(folder, cards: [Tiny.card(), huge])165 let entries = await library.entries()166 #expect(entries.map(\.id).sorted() == ["huge", "tiny"])167 let tiny = try #require(entries.first { $0.id == "tiny" })168 #expect(tiny.publisher == "acme" && tiny.quantization == "4-bit" && tiny.parameterCount == 600_000_000 && tiny.contextLength == 2_048)169 #expect(tiny.downloadBytes == 1_540_000 + Int64(Tiny.contents[0].1.count))170 #expect(tiny.licenseID == "apache-2.0" && tiny.capabilities == [.text] && tiny.categories == [.lightweight, .writing])171 #expect(!tiny.isInstalled && !tiny.isLoaded && tiny.download == nil && tiny.bytesOnDisk == 0)172 #expect(tiny.estimatedMemoryBytes > tiny.card.weightsBytes)173 #expect(tiny.loadDecision.verdict == .allow && tiny.compatibility.compatibility.isRecommendable)174 // 60 GB of weights on a 48 GB Mac: unsupported for Astra, refused by the governor175 let hugeEntry = try #require(entries.first { $0.id == "huge" })176 #expect(hugeEntry.compatibility.compatibility == .unsupported)177 #expect(hugeEntry.loadDecision.verdict == .refuse)178 // filters179 #expect(await library.entries(category: .reasoning).map(\.id) == ["huge"])180 #expect(await library.entries(search: "HUGE acme").map(\.id) == ["huge"])181 #expect(await library.entries(installedOnly: true).isEmpty)182 #expect(await library.entry(id: "nope") == nil)183 }184185 @Test func theAdvisorMarksRecommendedModels() async throws {186 let folder = TempFolder()187 let library = try Tiny.library(folder, cards: [Tiny.card(), Tiny.card(id: "coder", tags: [ModelTag.coding])])188 let recommended = await library.recommended()189 #expect(recommended.contains { $0.id == "coder" && $0.recommendedFor.contains(.coding) })190 #expect(recommended.contains { $0.id == "tiny" && $0.recommendedFor.contains(.writing) })191 let answer = try #require(await library.recommendation(for: .coding))192 #expect(answer.primary?.id == "coder")193 #expect(await library.recommendation(for: .experimental) == nil)194 // nothing suitable is said, not papered over195 let vision = try #require(await library.recommendation(for: .vision))196 #expect(vision.isNothingSuitable)197 }198199 @Test func refreshKeepsTheBuiltInCatalogueWhenTheSiteFailsAndRefusesChangedBytes() async throws {200 let folder = TempFolder()201 let http = FakeHTTP()202 let library = try Tiny.library(folder, http: http)203 let offline = await library.refreshCatalog()204 #expect(offline.failure != nil && offline.modelCount == 1)205 // the site now lists a new model, and the built-in one with other bytes206 var tampered = Tiny.card(); tampered.files[2].sha256 = String(repeating: "a", count: 64)207 let online = Tiny.catalog([tampered, Tiny.card(id: "newer")])208 http.respond("https://catalog.test/v1/catalog.json", try online.encoded())209 let refreshed = await library.refreshCatalog()210 #expect(refreshed.failure == nil && refreshed.modelCount == 2)211 #expect(refreshed.rejected.map(\.id) == ["tiny"])212 #expect(await library.currentCatalog().card(id: "tiny") == Tiny.card())213 }214}215216@Suite struct LibraryDownloadTests {217 @Test func downloadVerifiesEveryFileAndInstallsAtomically() async throws {218 let folder = TempFolder(), server = FakeServer()219 let library = try Tiny.library(folder, server: server)220 Tiny.publish(server)221 let started = try await library.download("tiny")222 #expect(started.bytesTotal == Tiny.card().totalBytes)223 let final = try #require(await library.waitForDownload("tiny"))224 #expect(final.phase == .completed && final.fraction == 1 && final.filesDone == 3)225 // SHA-256 of every file, computed locally, equals the catalogue's226 for file in Tiny.card().files { #expect(final.sha256[file.path] == file.sha256) }227 let entry = try #require(await library.entry(id: "tiny"))228 #expect(entry.isInstalled && entry.download == nil && entry.bytesOnDisk >= Tiny.card().totalBytes)229 #expect(library.store.loadableDirectory(for: "tiny") != nil)230 #expect(!FileManager.default.fileExists(atPath: library.store.stagingRoot.appendingPathComponent("tiny").path))231 #expect(await library.verifyInstalled("tiny").isIntact)232 let storage = await library.storage()233 #expect(storage.installedCount == 1 && storage.usedBytes >= Tiny.card().totalBytes && storage.root.lastPathComponent == "Models")234 // installed files are plain data: none carries an execute bit, whatever its name235 for file in Tiny.card().files {236 let url = try library.store.fileURL(modelID: "tiny", path: file.path)237 let mode = try #require(try FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)238 #expect(mode.intValue & 0o111 == 0, "\(file.path) is executable")239 }240 // the mirror was used; Hugging Face was not needed241 #expect(server.requests.allSatisfy { $0.url.hasPrefix(Tiny.mirror) })242 }243244 @Test func aFileWithTheWrongBytesNeverBecomesAnInstalledModel() async throws {245 let folder = TempFolder(), server = FakeServer()246 let library = try Tiny.library(folder, server: server)247 // same size, other content, on the mirror and on the fallback248 var poisoned = Tiny.contents; poisoned[2].1 = bytes(1_500_000, seed: 666)249 Tiny.publish(server, files: poisoned); Tiny.publish(server, base: Tiny.hub, files: poisoned)250 try await library.download("tiny")251 let final = try #require(await library.waitForDownload("tiny"))252 #expect(final.phase == .failed(.hashMismatch(file: "model.safetensors")))253 #expect(!library.store.isInstalled("tiny"))254 #expect(library.store.loadableDirectory(for: "tiny") == nil)255 #expect(await library.entry(id: "tiny")?.isInstalled == false)256 await #expect(throws: LocalModelLibraryError.notInstalled("tiny")) { try await library.load("tiny") }257 // the right bytes appear: retry completes258 Tiny.publish(server)259 try await library.retryDownload("tiny")260 #expect(await library.waitForDownload("tiny")?.phase == .completed)261 }262263 @Test func theFallbackSourceIsUsedWhenTheMirrorFails() async throws {264 let folder = TempFolder(), server = FakeServer()265 let library = try Tiny.library(folder, server: server)266 Tiny.publish(server, base: Tiny.hub) // nothing on the mirror: 404267 try await library.download("tiny")268 let final = try #require(await library.waitForDownload("tiny"))269 #expect(final.phase == .completed && final.usedFallback)270 }271272 @Test func pauseKeepsThePartialFileAndResumeContinuesWithARange() async throws {273 let folder = TempFolder(), server = FakeServer()274 server.chunkSize = 8 << 10275 let library = try Tiny.library(folder, server: server)276 Tiny.publish(server)277 server.script(Tiny.mirror + "model.safetensors", [.stall(400_000)])278 try await library.download("tiny")279 for _ in 0..<2_000 { if let s = await library.downloadStatus("tiny"), s.bytesDone >= 400_000 { break }; try await Task.sleep(nanoseconds: 2_000_000) }280 await library.pauseDownload("tiny")281 let paused = try #require(await library.downloadStatus("tiny"))282 #expect(paused.phase == .paused && paused.bytesDone >= 400_000 && paused.bytesDone < paused.bytesTotal)283 #expect(await library.entry(id: "tiny")?.download?.phase == .paused)284 #expect(!library.store.isInstalled("tiny"))285 try await library.resumeDownload("tiny")286 #expect(await library.waitForDownload("tiny")?.phase == .completed)287 let ranged = server.requests.filter { $0.url.hasSuffix("model.safetensors") && $0.range != nil }288 #expect(ranged.count == 1 && ranged[0].range == "bytes=400000-")289 #expect(await library.verifyInstalled("tiny").isIntact)290 }291292 @Test func aDroppedConnectionIsRetriedFromWhereItStopped() async throws {293 let folder = TempFolder(), server = FakeServer()294 let library = try Tiny.library(folder, server: server)295 Tiny.publish(server)296 server.script(Tiny.mirror + "model.safetensors", [.dropAfter(300_000)])297 try await library.download("tiny")298 let final = try #require(await library.waitForDownload("tiny"))299 #expect(final.phase == .completed && final.retries >= 1)300 #expect(server.requests.contains { $0.range == "bytes=300000-" })301 }302303 @Test func cancelDeletesWhatWasWritten() async throws {304 let folder = TempFolder(), server = FakeServer()305 let library = try Tiny.library(folder, server: server)306 Tiny.publish(server)307 server.script(Tiny.mirror + "model.safetensors", [.stall(200_000)])308 try await library.download("tiny")309 for _ in 0..<2_000 { if let s = await library.downloadStatus("tiny"), s.bytesDone >= 200_000 { break }; try await Task.sleep(nanoseconds: 2_000_000) }310 await library.cancelDownload("tiny")311 #expect(await library.downloadStatus("tiny")?.phase == .cancelled)312 #expect(library.store.bytesOnDisk(id: "tiny") == 0)313 #expect(await library.entry(id: "tiny")?.download == nil)314 }315316 @Test func unknownModelsAndDoubleStartsAreRefused() async throws {317 let folder = TempFolder(), server = FakeServer()318 let library = try Tiny.library(folder, server: server)319 await #expect(throws: LocalModelLibraryError.unknownModel("nope")) { try await library.download("nope") }320 Tiny.publish(server)321 server.script(Tiny.mirror + "model.safetensors", [.stall(1_000)])322 try await library.download("tiny")323 await #expect(throws: DownloadError.alreadyInProgress("tiny")) { try await library.download("tiny") }324 await library.cancelDownload("tiny")325 }326327 @Test func repairReplacesADamagedFileAndRemoveFreesEverything() async throws {328 let folder = TempFolder(), server = FakeServer(), world = World()329 let library = try Tiny.library(folder, server: server, world: world)330 try await Tiny.install(library, server)331 // damage one file in place, same size332 let weights = try library.store.fileURL(modelID: "tiny", path: "model.safetensors")333 try bytes(1_500_000, seed: 9).write(to: weights)334 let check = await library.verifyInstalled("tiny")335 #expect(!check.isIntact && check.damagedFiles == ["model.safetensors"])336 try await library.repair("tiny")337 #expect(await library.waitForDownload("tiny")?.phase == .completed)338 #expect(await library.verifyInstalled("tiny").isIntact)339 // intact files were reused: after the repair only the weights were fetched again340 let refetched = server.requests.filter { $0.url.hasSuffix("tokenizer.json") }341 #expect(refetched.count == 1)342 // removal: unloads, deletes, frees343 try await library.load("tiny")344 let freed = try await library.remove("tiny")345 #expect(freed >= Tiny.card().totalBytes)346 #expect(world.runtime("tiny")?.unloaded == true)347 #expect(await library.loadedModels().isEmpty && !library.store.isInstalled("tiny") && library.store.totalBytesOnDisk() < 100_000)348 }349350 @Test func interruptedDownloadsComeBackAfterARestart() async throws {351 let folder = TempFolder(), server = FakeServer()352 server.chunkSize = 8 << 10353 do {354 let library = try Tiny.library(folder, server: server)355 Tiny.publish(server)356 server.script(Tiny.mirror + "model.safetensors", [.stall(500_000)])357 try await library.download("tiny")358 for _ in 0..<2_000 { if let s = await library.downloadStatus("tiny"), s.bytesDone >= 500_000 { break }; try await Task.sleep(nanoseconds: 2_000_000) }359 await library.pauseDownload("tiny")360 }361 let reopened = try Tiny.library(folder, server: server)362 await reopened.start()363 // paused by the user: found again, still paused, with its progress364 let found = try #require(await reopened.downloadStatus("tiny"))365 #expect(found.phase == .paused && found.bytesDone >= 500_000)366 try await reopened.resumeDownload("tiny")367 #expect(await reopened.waitForDownload("tiny")?.phase == .completed)368 await reopened.governor.stopMonitoring(); await reopened.engine.stopMonitoring()369 }370}371372@Suite struct LibraryRuntimeTests {373 @Test func loadGenerateStreamAndUnload() async throws {374 let folder = TempFolder(), server = FakeServer(), world = World()375 let library = try Tiny.library(folder, server: server, world: world)376 try await Tiny.install(library, server)377 let info = try await library.load("tiny")378 #expect(info.modelID == "tiny" && world.loads == 1)379 #expect(try await library.load("tiny").modelID == "tiny" && world.loads == 1) // loading twice loads once380 #expect(await library.entry(id: "tiny")?.isLoaded == true)381 let result = await collect(library.generate(request()))382 #expect(result.error == nil && result.text == "w0 w1 w2 w3 w4 ")383 #expect(result.events.first == .messageStarted(MessageStart(reportedModel: "tiny")))384 #expect(result.events.last == .messageCompleted(.endOfTurn))385 #expect(library.generationMetrics.count == 1)386 // the speed measured in this session shows on the entry and in the router candidate387 #expect(await library.entry(id: "tiny")?.measurement?.tokensPerSecond == 123)388 await library.unload("tiny")389 #expect(world.runtime("tiny")?.unloaded == true)390 #expect(await library.loadedModels().isEmpty)391 }392393 @Test func generationLoadsOnFirstUseThroughTheGovernor() async throws {394 let folder = TempFolder(), server = FakeServer(), world = World()395 let library = try Tiny.library(folder, server: server, world: world)396 try await Tiny.install(library, server)397 let result = await collect(library.generate(request()))398 #expect(result.error == nil && world.loads == 1)399 // critical pressure: everything is unloaded and the next implicit load is refused with the reason400 await library.start()401 await library.governor.handlePressure(.critical)402 #expect(world.runtime("tiny")?.unloaded == true)403 #expect(await library.loadedModels().isEmpty)404 let refused = await collect(library.generate(request()))405 #expect(refused.error == .local("The Mac is critically low on memory. No model is loaded until the pressure is gone."))406 #expect(refused.events.isEmpty && world.loads == 1)407 await library.governor.handlePressure(.normal)408 #expect(await collect(library.generate(request())).error == nil)409 await library.governor.stopMonitoring(); await library.engine.stopMonitoring()410 }411412 @Test func cancellingMidGenerationStopsPromptlyAndTheEngineKeepsWorking() async throws {413 let folder = TempFolder(), server = FakeServer(), world = World()414 world.words = 2_000; world.delayMs = 5415 let library = try Tiny.library(folder, server: server, world: world)416 try await Tiny.install(library, server)417 let started = Date()418 let task = Task { () -> (Int, AstraError?) in419 var n = 0420 do { for try await event in library.generate(request()) { if case .textDelta = event { n += 1; if n == 5 { withUnsafeCurrentTask { $0?.cancel() } } } } }421 catch { return (n, AstraError.wrap(error)) }422 return (n, nil)423 }424 let (chunks, error) = await task.value425 #expect(chunks >= 5 && chunks < 100)426 #expect(error == .cancelled || error == nil) // a cancelled consumer may simply see the stream end427 #expect(Date().timeIntervalSince(started) < 5)428 await library.cancelGeneration()429 #expect(await library.engine.snapshot().active == nil)430 world.words = 3431 // the model is still loaded and answers the next request432 #expect(await library.loadedModels().map(\.modelID) == ["tiny"])433 }434435 @Test func aModelTheEditorCannotAffordIsRefusedWithTheNumbersUnlessForced() async throws {436 let folder = TempFolder(), server = FakeServer(), world = World()437 let library = try Tiny.library(folder, server: server, world: world)438 try await Tiny.install(library, server)439 world.memory = MemoryReading(physicalBytes: 48 << 30, availableBytes: 5 << 30) // (5 − 4.8) × 0.85 ≈ 170 MB usable440 do { try await library.load("tiny"); Issue.record("expected a refusal") }441 catch let LocalModelLibraryError.memory(decision) {442 #expect(decision.verdict == .refuse && decision.reason.contains("is kept for it"))443 }444 #expect(world.loads == 0)445 #expect(await library.entry(id: "tiny")?.loadDecision.verdict == .refuse)446 let forced = try await library.load("tiny", force: true)447 #expect(forced.modelID == "tiny" && world.loads == 1)448 }449450 @Test func heavyDocumentWorkDefersALoadUntilItEnds() async throws {451 let folder = TempFolder(), server = FakeServer(), world = World()452 let library = try Tiny.library(folder, server: server, world: world)453 try await Tiny.install(library, server)454 // budget: (7.2 − 4.8) × 0.85 ≈ 2.0 GB idle, (7.2 − 6.8) × 0.85 ≈ 0.34 GB during an export; the model needs ≈ 0.43 GB455 world.memory = MemoryReading(physicalBytes: 48 << 30, availableBytes: Int64(7.2 * Double(1 << 30)))456 let big = Tiny.card()457 #expect(await library.governor.decision(for: big).verdict == .allow)458 let token = await library.governor.noteHeavyDocumentWork(.begin, label: "PDF export")459 #expect(await library.governor.decision(for: big).verdict == .deferUntilDocumentWorkEnds)460 do { try await library.load("tiny", whenBusy: .fail); Issue.record("expected a deferral") }461 catch let LocalModelLibraryError.memory(decision) { #expect(decision.verdict == .deferUntilDocumentWorkEnds) }462 let waiting = Task { try await library.load("tiny") }463 try await Task.sleep(nanoseconds: 50_000_000)464 #expect(world.loads == 0)465 await library.governor.noteHeavyDocumentWork(.end, token: token)466 #expect(try await waiting.value.modelID == "tiny")467 #expect(world.loads == 1)468 }469470 @Test func aMemoryWarningReleasesIdleModels() async throws {471 let folder = TempFolder(), server = FakeServer(), world = World()472 let library = try Tiny.library(folder, server: server, world: world)473 try await Tiny.install(library, server)474 await library.start()475 try await library.load("tiny")476 await library.governor.handlePressure(.warning)477 #expect(world.runtime("tiny")?.unloaded == true)478 #expect(await library.engine.snapshot().lastAutomaticUnload == "memory warning")479 await library.governor.stopMonitoring(); await library.engine.stopMonitoring()480 }481482 @Test func requestsForAnotherProviderAreRefused() async throws {483 let folder = TempFolder()484 let library = try Tiny.library(folder)485 let wrong = await collect(library.generate(GenerationRequest(model: ModelRef(provider: .openAI, modelID: "gpt"), messages: [.user("x")])))486 #expect(wrong.error == .invalidRequest("This request is not for an on-device MLX model."))487 let missing = await collect(library.generate(request("tiny")))488 #expect(missing.error == .local("“tiny” is not downloaded."))489 }490}491492@Suite struct OnDeviceProviderTests {493 @Test func theHubListsBothOnDeviceProvidersWithTheirRealState() async throws {494 let folder = TempFolder(), server = FakeServer(), world = World()495 let library = try Tiny.library(folder, server: server, world: world)496 try await Tiny.install(library, server)497 let hub = ProviderHub(configuration: .init(credentials: InMemoryCredentialStore(), transport: FakeHTTP(), storageDirectory: nil))498 await OnDeviceProviders.register(in: hub, library: library, appleAvailability: { .appleIntelligenceOff })499 let rows = await hub.providers().filter(\.isOnDevice)500 #expect(rows.map(\.id.kind) == [.appleFoundation, .mlx])501 let apple = rows[0], mlx = rows[1]502 #expect(apple.state == .unavailable && apple.detail?.contains("turned off") == true && apple.modelCount == 0)503 #expect(mlx.state == .verified && mlx.modelCount == 1 && !mlx.hasKey)504 // generation through the hub reaches the library; usage is on-device and free505 let outcome = await hub.generate(request())506 #expect(outcome.error == nil && outcome.text == "w0 w1 w2 w3 w4 ")507 let totals = await hub.usageSnapshot().total508 #expect(totals.onDeviceRequests == 1 && totals.costUSD == 0)509 // Apple Intelligence off: the request fails with the system's reason. Nothing else answers in its place.510 let off = await hub.generate(GenerationRequest(model: AppleFoundationProvider.modelRef, messages: [.user("x")]))511 #expect(off.error == .unsupported("Apple Intelligence is turned off. Turn it on in Settings › Apple Intelligence & Siri."))512 #expect(off.text.isEmpty)513 }514515 @Test func appleIntelligenceDeclaresTextOnlyAndRefusesToolsAndImages() async throws {516 let provider = OnDeviceProviders.appleIntelligence(availability: { .available })517 let tool = ToolDefinition(name: "t", summary: "s", parameters: ["type": "object"])518 var error: AstraError?519 do { for try await _ in provider.stream(GenerationRequest(model: AppleFoundationProvider.modelRef, messages: [.user("x")], tools: [tool])) {} }520 catch let e { error = AstraError.wrap(e) }521 #expect(error == .unsupported("Tool calling is not available with the Apple system model in this app."))522 error = nil523 do { for try await _ in provider.stream(GenerationRequest(model: AppleFoundationProvider.modelRef, messages: [.user("x", images: [ImageInput(data: Data([1]))])])) {} }524 catch let e { error = AstraError.wrap(e) }525 #expect(error == .unsupported("The Apple system model does not read images in this app."))526 // unavailable: no model is listed at all527 #expect(try await OnDeviceProviders.appleIntelligence(availability: { .deviceNotEligible }).listModels().isEmpty)528 #expect(try await OnDeviceProviders.appleIntelligence(availability: { .osTooOld }).verify().ok == false)529 }530531 @Test func routerCandidatesDescribeOnDeviceModelsHonestly() async throws {532 let folder = TempFolder(), server = FakeServer(), world = World()533 let library = try Tiny.library(folder, server: server, world: world, cards: [Tiny.card(tags: [ModelTag.general]), Tiny.card(id: "multi", tags: [ModelTag.multilingual])])534 try await Tiny.install(library, server)535 let candidates = await library.routeCandidates()536 #expect(candidates.map(\.id) == ["mlx||tiny"]) // only what is installed537 let tiny = candidates[0]538 #expect(tiny.isOnDevice && !tiny.isLoaded && tiny.tier == .small && tiny.languages == ["en"])539 #expect((tiny.requiredMemoryBytes ?? 0) > 0 && tiny.unavailableReason == nil)540 let off = await OnDeviceProviders.appleRouteCandidate(availability: .appleIntelligenceOff)541 #expect(off.unavailableReason?.contains("turned off") == true && off.model.capabilities == [.text] && off.tier == .small)542 // end to end: Local Only picks the installed model; with nothing usable on-device it picks nothing, even with a cloud model offered543 let cloud = RouteCandidate(model: ModelInfo(ref: ModelRef(provider: .openAI, modelID: "gpt"), displayName: "GPT", contextLength: 1_000_000, capabilities: Set(Capability.allCases)))544 let task = TaskDescriptor(estimatedInputTokens: 500, expectedOutputTokens: 200, language: "en")545 let budget = await library.governor.modelBudgetBytes()546 let picked = ModelRouter.route(RoutingRequest(mode: .localOnly, task: task, candidates: candidates + [off, cloud], availableMemoryBytes: budget))547 #expect(picked.chosen?.ref.modelID == "tiny" && picked.location == .onDevice)548 let french = ModelRouter.route(RoutingRequest(mode: .privacyFirst, task: TaskDescriptor(language: "fr-CA"), candidates: candidates + [off, cloud], availableMemoryBytes: budget))549 #expect(french.chosen == nil)550 #expect(french.rejected.first { $0.model.provider == .openAI }?.code == .modeIsOnDeviceOnly)551 }552}553