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/Support.swift10// Description : Test support for the on-device model library: a fake11// download server (Range, scripted failures), a scripted12// model runtime, a tiny catalogue card with real SHA-25613// checksums and a library wired to them. Same seams as ORIX14// Astra's own local tests, so nothing here touches the15// network, MLX or the real Application Support folder.16// Module : DocLocalModelsTests17// 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 AstraCore94@testable import AstraLocal95import CryptoKit96@testable import DocLocalModels97import Foundation9899func sha256Hex(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }100101/// Deterministic pseudo-random bytes.102func bytes(_ count: Int, seed: UInt64) -> Data {103 var state = seed &* 6364136223846793005 &+ 1442695040888963407104 var out = Data(capacity: count)105 for _ in 0..<count { state = state &* 6364136223846793005 &+ 1442695040888963407; out.append(UInt8(truncatingIfNeeded: state >> 33)) }106 return out107}108109/// A folder removed when the object goes away. `@unchecked Sendable`: immutable after init.110final class TempFolder: @unchecked Sendable {111 let url: URL112 init() {113 url = FileManager.default.temporaryDirectory.appendingPathComponent("orixdocs-local-tests-" + UUID().uuidString, isDirectory: true)114 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)115 }116 deinit { try? FileManager.default.removeItem(at: url) }117}118119/// Serves bytes by URL with Range support. `@unchecked Sendable`: all mutable state is read and written under `lock`.120final class FakeServer: DownloadTransport, @unchecked Sendable {121 enum Behaviour { case ok, status(Int), dropAfter(Int), stall(Int) }122 private let lock = NSLock()123 private var files: [String: Data] = [:]124 private var scripts: [String: [Behaviour]] = [:]125 private var log: [(url: String, range: String?)] = []126 var chunkSize = 32 << 10127128 func serve(_ url: String, _ data: Data) { lock.withLock { files[url] = data } }129 /// Behaviours consumed one per request for this URL; once exhausted, `.ok`.130 func script(_ url: String, _ behaviours: [Behaviour]) { lock.withLock { scripts[url] = behaviours } }131 var requests: [(url: String, range: String?)] { lock.withLock { log } }132133 func open(_ request: URLRequest) async throws -> DownloadResponse {134 let url = request.url!.absoluteString135 let range = request.value(forHTTPHeaderField: "Range")136 let (data, behaviour) = lock.withLock { () -> (Data?, Behaviour) in137 log.append((url, range))138 var b = Behaviour.ok139 if var s = scripts[url], !s.isEmpty { b = s.removeFirst(); scripts[url] = s }140 return (files[url], b)141 }142 if case .status(let code) = behaviour { return DownloadResponse(status: code, body: AsyncThrowingStream { $0.finish() }) }143 guard let data else { return DownloadResponse(status: 404, body: AsyncThrowingStream { $0.finish() }) }144 var offset = 0145 if let range, range.hasPrefix("bytes="), let start = Int(range.dropFirst(6).split(separator: "-").first ?? "") { offset = start }146 if offset > data.count { return DownloadResponse(status: 416, body: AsyncThrowingStream { $0.finish() }) }147 var payload = data.subdata(in: offset..<data.count)148 var headers = ["Content-Length": String(payload.count)]149 if offset > 0 { headers["Content-Range"] = "bytes \(offset)-\(data.count - 1)/\(data.count)" }150 var fails = false, stalls = false151 switch behaviour {152 case .dropAfter(let n): payload = payload.prefix(n); fails = true153 case .stall(let n): payload = payload.prefix(n); stalls = true154 default: break155 }156 let chunk = chunkSize157 let (bytes, failsAtEnd, stallsAtEnd) = (payload, fails, stalls)158 let body = AsyncThrowingStream<Data, Error> { continuation in159 let task = Task {160 var i = bytes.startIndex161 while i < bytes.endIndex {162 if Task.isCancelled { continuation.finish(throwing: CancellationError()); return }163 let end = min(bytes.endIndex, i + chunk)164 continuation.yield(bytes.subdata(in: i..<end)); i = end165 await Task.yield()166 }167 if stallsAtEnd {168 while !Task.isCancelled { try? await Task.sleep(nanoseconds: 5_000_000) }169 continuation.finish(throwing: CancellationError()); return170 }171 if failsAtEnd { continuation.finish(throwing: URLError(.networkConnectionLost)) } else { continuation.finish() }172 }173 continuation.onTermination = { _ in task.cancel() }174 }175 return DownloadResponse(status: offset > 0 ? 206 : 200, headers: headers, body: body)176 }177}178179/// HTTP seam of the catalogue client: canned responses by URL. `@unchecked Sendable`: state under `lock`.180final class FakeHTTP: HTTPTransport, @unchecked Sendable {181 private let lock = NSLock()182 private var responses: [String: (Int, Data)] = [:]183 func respond(_ url: String, status: Int = 200, _ data: Data) { lock.withLock { responses[url] = (status, data) } }184 func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {185 let url = request.url!.absoluteString186 guard let (status, data) = lock.withLock({ responses[url] }) else { throw AstraError.network("no route for \(url)") }187 return (data, HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: [:])!)188 }189 func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) { throw AstraError.unsupported("not used") }190}191192/// A model runtime that emits words. `@unchecked Sendable`: mutable state under `lock`.193final class ScriptedRuntime: LocalModelRuntime, @unchecked Sendable {194 let info: LoadedModelInfo195 let words: Int196 let delay: UInt64197 private let lock = NSLock()198 private var didUnload = false199 var unloaded: Bool { lock.withLock { didUnload } }200201 init(id: String, directory: URL, words: Int, delayMs: UInt64) {202 info = LoadedModelInfo(modelID: id, directory: directory, architecture: "scripted", contextLength: 2_048, hasVision: false, hasChatTemplate: true,203 templateSupportsTools: false, weightsMemoryBytes: 1 << 20, loadTime: 0.01, loadedAt: Date())204 self.words = words; delay = delayMs * 1_000_000205 }206 func perform(_ request: GenerationRequest, emit: @Sendable (StreamEvent) -> Void) async -> LocalGenerationResult {207 var metrics = LocalGenerationMetrics(modelID: info.modelID)208 emit(.messageStarted(MessageStart(reportedModel: info.modelID)))209 var produced = 0210 for i in 0..<words {211 if Task.isCancelled { metrics.stopReason = .cancelled; metrics.completionTokens = produced; return LocalGenerationResult(metrics: metrics, error: .cancelled) }212 emit(.textDelta("w\(i) ")); produced += 1213 try? await Task.sleep(nanoseconds: delay)214 }215 metrics.stopReason = .endOfTurn; metrics.completionTokens = produced; metrics.promptTokens = 3; metrics.decodeTokensPerSecond = 123216 emit(.usage(TokenUsage(inputTokens: 3, outputTokens: produced)))217 emit(.messageCompleted(.endOfTurn))218 return LocalGenerationResult(metrics: metrics)219 }220 func countTokens(_ text: String) async -> Int? { text.split(separator: " ").count }221 func resetSession(_ key: String?) async {}222 func unload() async { lock.withLock { didUnload = true } }223}224225/// Readings and runtimes shared between a test and the library it drives. `@unchecked Sendable`: state under `lock`.226final class World: @unchecked Sendable {227 private let lock = NSLock()228 private var _memory = MemoryReading(physicalBytes: 48 << 30, availableBytes: 30 << 30)229 private var _runtimes: [String: ScriptedRuntime] = [:]230 private var _loads = 0231 var words = 5232 var delayMs: UInt64 = 2233 var memory: MemoryReading { get { lock.withLock { _memory } } set { lock.withLock { _memory = newValue } } }234 var loads: Int { lock.withLock { _loads } }235 func runtime(_ id: String) -> ScriptedRuntime? { lock.withLock { _runtimes[id] } }236 func makeRuntime(_ id: String, _ directory: URL) -> ScriptedRuntime {237 let runtime = ScriptedRuntime(id: id, directory: directory, words: words, delayMs: delayMs)238 lock.withLock { _runtimes[id] = runtime; _loads += 1 }239 return runtime240 }241}242243enum Tiny {244 static let mirror = "https://mirror.test/models/v1/tiny/"245 static let revision = "0123456789abcdef0123456789abcdef01234567"246 static let hub = "https://huggingface.co/acme/tiny/resolve/\(revision)/"247 static let contents: [(String, Data)] = [248 ("config.json", Data(#"{"model_type":"qwen3","max_position_embeddings":2048}"#.utf8)),249 ("tokenizer.json", bytes(40_000, seed: 2)),250 ("model.safetensors", bytes(1_500_000, seed: 3)),251 ]252253 static func card(id: String = "tiny", tags: [String] = [ModelTag.general, ModelTag.lightweight], status: ModelStatus = .verified, capabilities: [Capability] = [.text],254 files: [(String, Data)] = contents, parameters: Int64 = 600_000_000) -> LocalModelCard {255 let list = files.map { LocalModelFile(path: $0.0, size: Int64($0.1.count), sha256: sha256Hex($0.1)) }256 var card = LocalModelCard(id: id, displayName: "Tiny \(id)", family: "Tiny", publisher: "acme", repo: "acme/tiny", revision: revision, architecture: "qwen3",257 quantization: "4-bit", parameterCount: parameters, licenseID: "apache-2.0", licenseURL: "https://www.apache.org/licenses/LICENSE-2.0",258 redistributable: true, totalBytes: list.reduce(0) { $0 + $1.size }, files: list, contextLength: 2_048,259 minimumDeviceMemoryGB: 4, estimatedRuntimeMemoryBytes: 500 << 20, baseURL: mirror, fallbackBaseURL: hub)260 card.capabilities = capabilities; card.tags = tags; card.status = status261 return card262 }263264 static func publish(_ server: FakeServer, base: String = mirror, files: [(String, Data)] = contents) {265 for (path, data) in files { server.serve(base + path, data) }266 }267268 static func catalog(_ cards: [LocalModelCard]) -> ModelCatalog {269 ModelCatalog(generatedAt: Date(timeIntervalSince1970: 1_795_000_000), entries: cards.map { .init(card: $0, origin: .bundled) })270 }271272 /// A library on a temp folder with a fake server, a scripted loader and scripted memory.273 static func library(_ folder: TempFolder, server: FakeServer = FakeServer(), world: World = World(), cards: [LocalModelCard] = [card()], http: FakeHTTP = FakeHTTP(),274 governor: EditorMemoryGovernor? = nil) throws -> LocalModelLibrary {275 var config = LocalModelLibrary.Configuration(root: folder.url.appendingPathComponent("Models"))276 config.catalog = catalog(cards)277 config.catalogBase = URL(string: "https://catalog.test/v1")!278 config.http = http279 config.downloadTransport = server280 config.download.retryDelay = { _ in 0 }281 config.download.sleep = { _ in await Task.yield() }282 config.download.maxAttemptsPerSource = 2283 config.download.safetyMarginBytes = 1 << 20284 config.download.freeSpace = { _ in 1 << 40 }285 config.environment.memory = { world.memory }286 config.environment.thermal = { .nominal }287 config.environment.mlxMemory = { nil }288 config.environment.loader = { id, directory, progress in progress(1); return world.makeRuntime(id, directory) }289 config.device = DeviceFacts(platform: .macOS, modelIdentifier: "Mac17,6", osVersion: "27.0.0", physicalMemoryBytes: 48 << 30)290 return try LocalModelLibrary(configuration: config, governor: governor)291 }292293 /// Downloads and installs the tiny model, and fails the test's precondition loudly if that did not work.294 static func install(_ library: LocalModelLibrary, _ server: FakeServer, id: String = "tiny") async throws {295 publish(server)296 try await library.download(id)297 let status = await library.waitForDownload(id)298 guard status?.phase == .completed else { throw AstraError.local("test setup: the tiny model did not install (\(String(describing: status?.phase)))") }299 }300}301