SPB Git

Repository Public

LifecycleTests.swift 25.0 KB 502 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/LifecycleTests.swift10// Module           : AstraLocalTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2213// Last Modified    : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import Foundation90import Testing91@testable import AstraLocal9293/// A runtime whose generation runs until released (or cancelled), with a configurable context window.94final class GatedRuntime: LocalModelRuntime, @unchecked Sendable {95    let info: LoadedModelInfo96    private let lock = NSLock()97    private var _unloaded = false98    private var _requests: [GenerationRequest] = []99    private var _resets: [String?] = []100    private var _released: Bool101    private var _started = false102103    init(id: String, context: Int = 8192, gated: Bool = false) {104        info = LoadedModelInfo(modelID: id, directory: URL(fileURLWithPath: "/dev/null"), architecture: "scripted", contextLength: context, hasVision: false,105                               hasChatTemplate: true, templateSupportsTools: false, weightsMemoryBytes: 1 << 20, loadTime: 0.01, loadedAt: Date())106        _released = !gated107    }108    var unloaded: Bool { lock.withLock { _unloaded } }109    var requests: [GenerationRequest] { lock.withLock { _requests } }110    var resets: [String?] { lock.withLock { _resets } }111    var started: Bool { lock.withLock { _started } }112    func release() { lock.withLock { _released = true } }113114    func perform(_ request: GenerationRequest, emit: @Sendable (StreamEvent) -> Void) async -> LocalGenerationResult {115        lock.withLock { _requests.append(request); _started = true }116        var metrics = LocalGenerationMetrics(modelID: info.modelID)117        emit(.messageStarted(MessageStart(reportedModel: info.modelID)))118        emit(.textDelta("a"))119        while !lock.withLock({ _released }) {120            if Task.isCancelled { metrics.stopReason = .cancelled; return LocalGenerationResult(metrics: metrics, error: .cancelled) }121            try? await Task.sleep(nanoseconds: 1_000_000)122        }123        metrics.stopReason = .endOfTurn; metrics.completionTokens = 1124        emit(.messageCompleted(.endOfTurn))125        return LocalGenerationResult(metrics: metrics)126    }127    func countTokens(_ text: String) async -> Int? { text.count }128    func resetSession(_ key: String?) async { lock.withLock { _resets.append(key) } }129    func unload() async { lock.withLock { _unloaded = true } }130}131132final class LoaderLog: @unchecked Sendable {133    private let lock = NSLock()134    private var _runtimes: [String: [GatedRuntime]] = [:]135    private var _inFlight = 0136    private var _maxInFlight = 0137    private var _order: [String] = []138    var gated = false139    var context = 8192140    var delayMs: UInt64 = 0141    var failing: Set<String> = []142    func begin(_ id: String) { lock.withLock { _inFlight += 1; _maxInFlight = max(_maxInFlight, _inFlight); _order.append(id) } }143    func end(_ id: String, _ runtime: GatedRuntime?) { lock.withLock { _inFlight -= 1; if let runtime { _runtimes[id, default: []].append(runtime) } } }144    var maxInFlight: Int { lock.withLock { _maxInFlight } }145    var order: [String] { lock.withLock { _order } }146    func instances(_ id: String) -> [GatedRuntime] { lock.withLock { _runtimes[id] ?? [] } }147    func last(_ id: String) -> GatedRuntime? { instances(id).last }148}149150@Suite struct LifecycleTests {151    let dir = TempDirectory()152    let readings = Readings()153    let log = LoaderLog()154155    /// Installed models "a", "b", "c" (small weights, cards declaring an 8 192-token window) over gated runtimes.156    func makeEngine(maxLoaded: Int = 1, defaultContext: Int? = nil) async throws -> LocalEngine {157        let server = FakeServer()158        let (coordinator, store) = Fixture.coordinator(dir, server)159        for id in ["a", "b", "c"] {160            var files = Fixture.contents; files[2].1 = bytes(200_000, seed: UInt64(id.utf8.first!))161            let base = "https://mirror.test/m/\(id)/"162            Fixture.publish(server, base: base, files: files)163            var card = Fixture.card(id: id, files: files); card.baseURL = base; card.contextLength = 8192164            try await coordinator.start(DownloadPlan(card: card))165            #expect(await coordinator.waitUntilSettled(id: id)?.phase == .completed)166        }167        var environment = LocalEngine.Environment()168        let readings = readings, log = log169        environment.memory = { readings.memory }170        environment.thermal = { readings.thermal }171        environment.mlxMemory = { nil }172        environment.loader = { id, _, progress in173            log.begin(id)174            progress(0.5)175            if log.delayMs > 0 { try? await Task.sleep(nanoseconds: log.delayMs * 1_000_000) }176            if log.failing.contains(id) { log.end(id, nil); throw AstraError.local("scripted load failure") }177            progress(1)178            let runtime = GatedRuntime(id: id, context: log.context, gated: log.gated)179            log.end(id, runtime)180            return runtime181        }182        var configuration = LocalEngine.Configuration(maxLoadedModels: maxLoaded)183        configuration.defaultContextLength = defaultContext184        return LocalEngine(store: store, configuration: configuration, memoryGovernor: MemoryGovernor(platform: .iOS), environment: environment)185    }186187    func request(_ id: String, context: Int? = nil) -> GenerationRequest {188        GenerationRequest(model: ModelRef(provider: .mlx, modelID: id), messages: [.user("hi")], parameters: GenerationParameters(contextLength: context), sessionKey: "s")189    }190191    func drain(_ stream: AsyncThrowingStream<StreamEvent, Error>) async -> AstraError? {192        do { for try await _ in stream {}; return nil } catch { return error as? AstraError }193    }194195    func waitUntil(_ condition: @Sendable () async -> Bool) async {196        for _ in 0..<2_000 { if await condition() { return }; try? await Task.sleep(nanoseconds: 1_000_000) }197        Issue.record("condition was never met")198    }199200    // MARK: Identity201202    @Test func loadedIdentityIncludesTheRevision() async throws {203        let engine = try await makeEngine()204        let info = try await engine.load("a")205        #expect(info.revision == Fixture.revision)206        let state = try #require(await engine.loadedState("a"))207        #expect(state.revision == Fixture.revision && state.id == "a" && !state.isGenerating && state.contextCeiling == 8192)208        let snapshot = await engine.snapshot()209        #expect(snapshot.phase == .idle && snapshot.models.map(\.id) == ["a"] && snapshot.loaded.first?.revision == Fixture.revision)210        #expect(await engine.loadedInfo("a")?.revision == Fixture.revision)211    }212213    // MARK: Loading214215    @Test func concurrentLoadsOfTheSameModelCreateOneInstance() async throws {216        log.delayMs = 30217        let engine = try await makeEngine()218        async let first = engine.load("a")219        async let second = engine.load("a")220        async let third = engine.load("a")221        let infos = try await [first, second, third]222        #expect(infos.allSatisfy { $0.modelID == "a" })223        #expect(log.instances("a").count == 1, "the loader ran once")224        #expect(log.order == ["a"])225        #expect(await engine.snapshot().models.count == 1)226    }227228    @Test func loadsOfDifferentModelsNeverOverlapAndRespectTheLimit() async throws {229        log.delayMs = 30230        let engine = try await makeEngine(maxLoaded: 1)231        async let a: LoadedModelInfo = engine.load("a")232        async let b: LoadedModelInfo = engine.load("b")233        async let c: LoadedModelInfo = engine.load("c")234        _ = try await (a, b, c)235        #expect(log.maxInFlight == 1, "two loaders were never running at once")236        #expect(Set(log.order) == ["a", "b", "c"] && log.order.count == 3)237        let loaded = await engine.snapshot().models.map(\.id)238        #expect(loaded.count == 1, "with a limit of one, only the last load remains: \(loaded)")239        #expect(loaded == [log.order.last!])240        for id in log.order.dropLast() { #expect(log.last(id)?.unloaded == true) }241    }242243    @Test func aFailedLoadLeavesTheEngineUsable() async throws {244        log.failing = ["a"]245        let engine = try await makeEngine()246        await #expect(throws: AstraError.local("scripted load failure")) { try await engine.load("a") }247        let snapshot = await engine.snapshot()248        #expect(snapshot.models.isEmpty && snapshot.loading == nil && snapshot.phase == .idle)249        try await engine.load("b")   // the gate was released250        #expect(await engine.snapshot().isLoaded("b"))251    }252253    // MARK: Switching254255    @Test func switchUnloadsThenLoadsAndReportsThePhase() async throws {256        log.delayMs = 40257        let engine = try await makeEngine(maxLoaded: 2)258        try await engine.load("a"); try await engine.load("b")259        let phases = Task { () -> [LocalEngine.Phase] in260            var seen: [LocalEngine.Phase] = []261            for await s in await engine.snapshots() {262                if seen.last != s.phase { seen.append(s.phase) }263                if s.phase == .idle, s.models.map(\.id) == ["c"] { break }264            }265            return seen266        }267        try? await Task.sleep(nanoseconds: 5_000_000)268        let info = try await engine.switchActive(to: "c")269        #expect(info.modelID == "c")270        let seen = await phases.value271        #expect(seen.contains(.switching(from: ["a", "b"], to: "c")), "\(seen)")272        #expect(seen.last == .idle)273        #expect(await engine.snapshot().models.map(\.id) == ["c"])274        #expect(log.last("a")?.unloaded == true && log.last("b")?.unloaded == true)275    }276277    @Test func switchToTheLoadedModelIsANoOp() async throws {278        let engine = try await makeEngine()279        try await engine.load("a")280        try await engine.switchActive(to: "a")281        #expect(log.instances("a").count == 1 && log.last("a")?.unloaded == false)282        // With another model beside it, the target stays and the other goes.283        await engine.setMaxLoadedModels(2)284        try await engine.load("b")285        try await engine.switchActive(to: "a")286        #expect(await engine.snapshot().models.map(\.id) == ["a"])287        #expect(log.instances("a").count == 1, "the target was not reloaded")288    }289290    @Test func switchRefusesWhileGeneratingByDefault() async throws {291        log.gated = true292        let engine = try await makeEngine()293        try await engine.load("a")294        let runtime = try #require(log.last("a"))295        let generation = Task { await drain(engine.generate(request("a"))) }296        await waitUntil { runtime.started }297        await #expect(throws: LocalEngineError.generationInProgress(modelID: "a")) { try await engine.switchActive(to: "b") }298        let during = await engine.snapshot()299        #expect(during.phase == .generating(modelID: "a") && during.models.map(\.id) == ["a"] && during.models.first?.isGenerating == true)300        #expect(!runtime.unloaded, "the running model was not touched")301        runtime.release()302        #expect(await generation.value == nil, "the generation finished normally")303        #expect(LocalEngineError.generationInProgress(modelID: "a").astraError == .local("“a” is generating. Stop it or wait for it to finish before switching models."))304    }305306    @Test func switchCanCancelTheRunningGenerationAndWait() async throws {307        log.gated = true308        let engine = try await makeEngine()309        try await engine.load("a")310        let runtime = try #require(log.last("a"))311        let generation = Task { await drain(engine.generate(request("a"))) }312        await waitUntil { runtime.started }313        log.gated = false314        let info = try await engine.switchActive(to: "b", whileGenerating: .cancelRunningGeneration)315        #expect(info.modelID == "b")316        #expect(await generation.value == .cancelled, "the stream ended with .cancelled")317        #expect(runtime.unloaded)318        let after = await engine.snapshot()319        #expect(after.models.map(\.id) == ["b"] && after.active == nil && after.phase == .idle)320        #expect(engine.monitor.lastMetrics?.stopReason == .cancelled)321    }322323    @Test func switchRefusalsThatAreKnownInAdvanceKeepTheCurrentModel() async throws {324        let engine = try await makeEngine()325        try await engine.load("a")326        await #expect(throws: LocalEngineError.notInstalled(modelID: "zzz")) { try await engine.switchActive(to: "zzz") }327        readings.thermal = .critical328        do { try await engine.switchActive(to: "b"); Issue.record("should refuse") }329        catch let e as LocalEngineError { if case .tooHot = e {} else { Issue.record("\(e)") } }330        readings.thermal = .nominal331        readings.memory = MemoryReading(physicalBytes: 256 << 20, availableBytes: 200 << 20)   // 350 MB of overhead alone exceeds 80 % of this332        do { try await engine.switchActive(to: "b"); Issue.record("should refuse") }333        catch let e as LocalEngineError { if case .doesNotFit(let id, _) = e { #expect(id == "b") } else { Issue.record("\(e)") } }334        #expect(await engine.snapshot().models.map(\.id) == ["a"], "nothing was unloaded by a refused switch")335        #expect(log.last("a")?.unloaded == false)336    }337338    @Test func aSwitchWhoseLoadFailsLeavesNothingLoaded() async throws {339        let engine = try await makeEngine()340        try await engine.load("a")341        log.failing = ["b"]342        await #expect(throws: AstraError.local("scripted load failure")) { try await engine.switchActive(to: "b") }343        let s = await engine.snapshot()344        #expect(s.models.isEmpty && s.phase == .idle)345    }346347    // MARK: Generation state348349    @Test func generationStateIsVisibleAndClearsAfterwards() async throws {350        log.gated = true351        let engine = try await makeEngine()352        try await engine.load("a")353        let runtime = try #require(log.last("a"))354        #expect(await engine.snapshot().phase == .idle)355        let generation = Task { await drain(engine.generate(request("a"))) }356        await waitUntil { runtime.started }357        let s = await engine.snapshot()358        #expect(s.phase == .generating(modelID: "a") && s.active?.modelID == "a" && s.active?.sessionKey == "s")359        runtime.release()360        _ = await generation.value361        #expect(await engine.snapshot().phase == .idle)362    }363364    // MARK: Context365366    @Test func aContextThatDoesNotFitIsReducedAndReported() async throws {367        // 1 GB phone: budget ≈ 500 MB, overhead 350 MB, 24 KB of KV cache per token: 8 192 tokens do not fit, 4 096 do.368        readings.memory = MemoryReading(physicalBytes: 1 << 30, availableBytes: 600 << 20)369        let engine = try await makeEngine()370        try await engine.load("a")371        #expect(await engine.loadedState("a")?.contextCeiling == 4096)372        #expect(await engine.contextDecision(modelID: "a", requested: 8192) == .init(modelID: "a", requested: 8192, effective: 4096, reason: "memory"))373        #expect(await drain(engine.generate(request("a", context: 8192))) == nil)374        #expect(log.last("a")?.requests.last?.parameters.contextLength == 4096, "the runtime ran with the reduced window")375        let m = try #require(engine.monitor.lastMetrics)376        #expect(m.requestedContextLength == 8192 && m.effectiveContextLength == 4096 && m.contextReduction == "memory")377        let decision = try #require(await engine.snapshot().lastContextDecision)378        #expect(decision.wasReduced && decision.effective == 4096 && decision.requested == 8192)379380        // A window that fits is left alone.381        #expect(await drain(engine.generate(request("a", context: 2048))) == nil)382        #expect(log.last("a")?.requests.last?.parameters.contextLength == 2048)383        #expect(engine.monitor.lastMetrics?.contextReduction == nil && engine.monitor.lastMetrics?.effectiveContextLength == 2048)384385        // Nothing requested: the ceiling still applies, because the model's own window (8 192) would not fit.386        #expect(await drain(engine.generate(request("a"))) == nil)387        #expect(log.last("a")?.requests.last?.parameters.contextLength == 4096)388        #expect(engine.monitor.lastMetrics?.requestedContextLength == nil && engine.monitor.lastMetrics?.contextReduction == "memory")389    }390391    @Test func aRequestLargerThanTheModelWindowIsClamped() async throws {392        log.context = 2048393        let engine = try await makeEngine()394        try await engine.load("a")395        #expect(await drain(engine.generate(request("a", context: 6000))) == nil)396        #expect(log.last("a")?.requests.last?.parameters.contextLength == 2048)397        #expect(engine.monitor.lastMetrics?.contextReduction == "model" && engine.monitor.lastMetrics?.effectiveContextLength == 2048)398    }399400    @Test func nothingRequestedAndEverythingFitsMeansNoLimitIsImposed() async throws {401        let engine = try await makeEngine()402        try await engine.load("a")403        #expect(await drain(engine.generate(request("a"))) == nil)404        #expect(log.last("a")?.requests.last?.parameters.contextLength == nil)405        let m = try #require(engine.monitor.lastMetrics)406        #expect(m.requestedContextLength == nil && m.effectiveContextLength == 8192 && m.contextReduction == nil)407    }408409    @Test func aHotDeviceHalvesTheContextAndSaysWhy() async throws {410        let engine = try await makeEngine()411        try await engine.load("a")412        readings.thermal = .serious413        #expect(await drain(engine.generate(request("a", context: 4096))) == nil)414        #expect(log.last("a")?.requests.last?.parameters.contextLength == 2048)415        #expect(engine.monitor.lastMetrics?.contextReduction == "thermal" && engine.monitor.lastMetrics?.requestedContextLength == 4096)416    }417418    @Test func theEngineDefaultContextIsUsedWhenTheRequestHasNone() async throws {419        let engine = try await makeEngine(defaultContext: 1024)420        try await engine.load("a")421        #expect(await drain(engine.generate(request("a"))) == nil)422        #expect(log.last("a")?.requests.last?.parameters.contextLength == 1024)423        #expect(engine.monitor.lastMetrics?.requestedContextLength == 1024 && engine.monitor.lastMetrics?.contextReduction == nil)424    }425426    // MARK: Preload427428    @Test func preloadLoadsOnlyWhenComfortable() async throws {429        let engine = try await makeEngine()430        #expect(await engine.preload("zzz") == .skipped("The model is not downloaded."))431        readings.thermal = .serious432        #expect(await engine.preload("a") == .skipped("The device is warm."))433        readings.thermal = .nominal434        readings.memory = MemoryReading(physicalBytes: 1 << 30, availableBytes: 600 << 20)   // fits, but only tightly435        if case .skipped(let why) = await engine.preload("a") { #expect(why.hasPrefix("Memory is not comfortable")) } else { Issue.record("should skip") }436        #expect(log.order.isEmpty, "nothing was loaded by a skipped preload")437        readings.memory = MemoryReading(physicalBytes: 8 << 30, availableBytes: 5 << 30)438        if case .loaded(let info) = await engine.preload("a") { #expect(info.modelID == "a") } else { Issue.record("should load") }439        #expect(await engine.preload("a") == .alreadyLoaded)440        // The slot is taken: preloading never evicts another model.441        #expect(await engine.preload("b") == .skipped("Another model is loaded."))442        #expect(await engine.snapshot().models.map(\.id) == ["a"])443    }444445    @Test func preloadIsSkippedWhileGenerating() async throws {446        log.gated = true447        let engine = try await makeEngine(maxLoaded: 2)448        try await engine.load("a")449        let runtime = try #require(log.last("a"))450        let generation = Task { await drain(engine.generate(request("a"))) }451        await waitUntil { runtime.started }452        #expect(await engine.preload("b") == .skipped("A generation is running."))453        runtime.release(); _ = await generation.value454    }455456    // MARK: Releasing457458    @Test func releaseUnusedResourcesKeepsTheMostRecentModel() async throws {459        let engine = try await makeEngine(maxLoaded: 3)460        try await engine.load("a"); try await engine.load("b"); try await engine.load("c")461        #expect(await drain(engine.generate(request("b"))) == nil)   // "b" is now the most recently used462        let released = await engine.releaseUnusedResources()463        #expect(Set(released.unloadedModels) == ["a", "c"] && released.sessionsReset.isEmpty)464        #expect(await engine.snapshot().models.map(\.id) == ["b"])465        #expect(log.last("a")?.unloaded == true && log.last("c")?.unloaded == true && log.last("b")?.unloaded == false)466        #expect(log.last("b")?.resets.isEmpty == true, "KV sessions are kept by default")467        let again = await engine.releaseUnusedResources(keepSessions: false)468        #expect(again.unloadedModels.isEmpty && again.sessionsReset == ["b"])469        #expect(log.last("b")?.resets.count == 1)470    }471472    @Test func releaseUnusedResourcesNeverTouchesARunningGeneration() async throws {473        log.gated = true474        let engine = try await makeEngine(maxLoaded: 2)475        try await engine.load("a"); try await engine.load("b")476        let runtime = try #require(log.last("a"))477        let generation = Task { await drain(engine.generate(request("a"))) }478        await waitUntil { runtime.started }479        let released = await engine.releaseUnusedResources(keepSessions: false)480        #expect(released.unloadedModels == ["b"] && released.sessionsReset.isEmpty)481        #expect(!runtime.unloaded && runtime.resets.isEmpty)482        runtime.release()483        #expect(await generation.value == nil)484    }485486    // MARK: Pressure (unchanged behaviour, new state)487488    @Test func criticalHeatStopsAndUnloadsAsBefore() async throws {489        log.gated = true490        let engine = try await makeEngine()491        try await engine.load("a")492        let runtime = try #require(log.last("a"))493        let generation = Task { await drain(engine.generate(request("a"))) }494        await waitUntil { runtime.started }495        readings.thermal = .critical496        await engine.handleThermal(.critical)497        #expect(await generation.value == .cancelled)498        let s = await engine.snapshot()499        #expect(s.models.isEmpty && s.lastAutomaticUnload == "device too hot" && s.phase == .idle)500    }501}502
Files main
Menu

Theme