SPB Git

Repository Public

V2RegressionTests.swift 12.2 KB 227 lines swift

1import AstraCore2import Foundation3import Testing4@testable import AstraLocal56// Regression tests for the defects confirmed by the pre-V2 source audit (docs/v2/FINDINGS_REGISTER.md, LOCAL-n).78extension LifecycleTests {9    /// LOCAL-1: a generation that auto-loads a model whose load is already in flight could return from `load` before the10    /// runtime was registered, then force-unwrap nil.11    @Test func generatingWhileTheSameModelLoadsNeverCrashes() async throws {12        for _ in 0..<40 {13            let engine = try await makeEngine()14            log.delayMs = 515            async let explicit = engine.load("a")16            await waitUntil { await engine.snapshot().loading?.modelID == "a" }17            let error = await drain(engine.generate(request("a")))18            _ = try await explicit19            #expect(error == nil)20        }21    }2223    /// LOCAL-2: unloading the model that is generating reported its slot free while its weights were still in use.24    @Test func unloadingTheGeneratingModelStopsTheGenerationFirst() async throws {25        log.gated = true26        let engine = try await makeEngine(maxLoaded: 1)27        let stream = engine.generate(request("a"))28        let consumer = Task { await drain(stream) }29        await waitUntil { log.last("a")?.started == true }30        await engine.unload("a")31        // the generation has really ended before the model counts as unloaded32        #expect(await engine.snapshot().active == nil)33        #expect(await consumer.value == .cancelled)34        #expect(log.last("a")?.unloaded == true)35        _ = try await engine.load("b")36        #expect(await engine.snapshot().models.map(\.id) == ["b"])37    }3839    /// LOCAL-3: the context ceiling was computed after the weights were resident, counting them twice; and "nothing fits"40    /// meant "no limit". The reading taken before the load decides, and there is always a ceiling.41    @Test func theContextCeilingUsesTheReadingTakenBeforeTheLoad() async throws {42        let engine = try await makeEngine()43        let roomy = readings.memory44        log.delayMs = 2045        async let loading = engine.load("a")46        await waitUntil { await engine.snapshot().loading?.modelID == "a" }47        // while the weights are being read, what the system reports as available collapses48        readings.memory = MemoryReading(physicalBytes: roomy.physicalBytes, availableBytes: 40 << 20)49        _ = try await loading50        let ceiling = try #require(await engine.loadedState("a")?.contextCeiling)51        #expect(ceiling == 8192)52    }5354    @Test func aModelThatBarelyFitsStillGetsACeiling() async throws {55        readings.memory = MemoryReading(physicalBytes: 4 << 30, availableBytes: 30 << 20)56        let engine = try await makeEngine()57        _ = try await engine.load("a", force: true)58        let ceiling = await engine.loadedState("a")?.contextCeiling59        #expect(ceiling == 1024)60        #expect(await engine.contextDecision(modelID: "a", requested: nil).effective == 1024)61    }6263    /// LOCAL-10: critical pressure stopped the running generation, but the ones waiting behind it then reloaded the model.64    @Test func criticalPressureAlsoEndsQueuedGenerations() async throws {65        log.gated = true66        let engine = try await makeEngine()67        let first = Task { await drain(engine.generate(request("a"))) }68        await waitUntil { log.last("a")?.started == true }69        let second = Task { await drain(engine.generate(request("a"))) }70        await waitUntil { await engine.snapshot().queued == 1 }71        await engine.handleMemoryPressure(critical: true)72        #expect(await first.value == .cancelled)73        let queuedError = await second.value74        if case .local(let message)? = queuedError { #expect(message.contains("memory")) } else { Issue.record("expected a memory-pressure error, got \(String(describing: queuedError))") }75        #expect(log.instances("a").count == 1, "the queued generation did not load the model again")76        #expect(await engine.snapshot().models.isEmpty)77    }78}7980@Suite struct V2StopFilterTests {81    /// LOCAL-8: a stop sequence split across chunks leaked its beginning to the consumer.82    @Test func aStopSequenceSplitAcrossChunksLeaksNothing() {83        var filter = StopFilter(stops: ["END", "</done>"])84        var out = ""85        for piece in ["ab", "E", "N", "D", "tail"] {86            let step = filter.consume(piece)87            out += step.emit88            if step.stopped { break }89        }90        #expect(out == "ab")91        #expect(filter.text == "ab")92    }9394    @Test func textThatOnlyLooksLikeAStopIsReleased() {95        var filter = StopFilter(stops: ["END"])96        var out = ""97        for piece in ["the E", "N", "gine ", "E"] { out += filter.consume(piece).emit }98        out += filter.finish()99        #expect(out == "the ENgine E")100        #expect(filter.text == "the ENgine E")101    }102103    @Test func splittingNeverChangesTheResult() {104        let source = "one two <stop> three"105        for cut in 1..<source.count {106            var filter = StopFilter(stops: ["<stop>"])107            var out = ""; var stopped = false108            for piece in [String(source.prefix(cut)), String(source.dropFirst(cut))] where !stopped {109                let step = filter.consume(piece); out += step.emit; stopped = step.stopped110            }111            if !stopped { out += filter.finish() }112            #expect(out == "one two ", "cut at \(cut)")113        }114    }115116    @Test func withoutStopsEverythingPassesThrough() {117        var filter = StopFilter(stops: ["", ""])118        #expect(filter.consume("abc").emit == "abc")119        #expect(filter.finish() == "")120    }121}122123@Suite struct V2CatalogueHonestyTests {124    /// LOCAL-5: "Verified" named no platform, and an online entry that said nothing about its status was shown as verified.125    @Test func theVerificationLabelNamesWhereTheModelWasRun() throws {126        var card = Fixture.card(id: "x")127        card.status = .verified128        card.verified = VerifiedRecord(date: "2026-11-21", machine: "Mac17,2", platform: "macOS", osVersion: "27.0", tokensPerSecond: 100, timeToFirstToken: 0.2, peakMemoryBytes: 1)129        #expect(card.verificationLabel == "Verified on Mac")130        #expect(!card.isVerifiedOnIPhone)131        card.verified?.platform = "iOS"132        #expect(card.verificationLabel == "Verified on iPhone")133        #expect(card.isVerifiedOnIPhone)134        card.verified = nil135        #expect(card.verificationLabel == "Not measured")136        card.status = .experimental137        #expect(card.verificationLabel == "Experimental")138    }139140    @Test func anOnlineEntryWithoutEvidenceIsNotVerified() throws {141        var card = Fixture.card(id: "x")142        card.status = .verified; card.verified = nil; card.validation = nil143        let data = try ModelCatalog(generatedAt: Date(), entries: [.init(card: card, origin: .onlineCatalog)]).encoded()144        #expect(try ModelCatalog.decode(data, origin: .onlineCatalog).models[0].status == .experimental)145        // the bundled catalogue is the app's own and keeps what it says146        #expect(try ModelCatalog.decode(data, origin: .bundled).models[0].status == .verified)147    }148149    /// No entry of the catalogue this build ships may claim an iPhone verification: none was ever run on one.150    @Test func theBundledCatalogueClaimsNoIPhoneVerification() throws {151        let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()152            .appendingPathComponent("Packages/AstraUI/Sources/Resources/catalog.json")153        let catalog = try ModelCatalog.decode(try Data(contentsOf: url))154        #expect(!catalog.models.isEmpty)155        #expect(catalog.models.allSatisfy { !$0.isVerifiedOnIPhone })156        #expect(catalog.models.filter { $0.status == .verified }.allSatisfy { $0.verificationLabel == "Verified on Mac" })157    }158}159160@Suite struct V2InstallRecoveryTests {161    /// LOCAL-6: a crash between the atomic swap and deleting the old folder made the next launch swap the old version back.162    @Test func aCrashAfterTheSwapKeepsTheNewVersion() throws {163        let dir = TempDirectory()164        let store = try ModelStore(root: dir.url)165        let fm = FileManager.default166        func stage(_ marker: String) throws {167            let staging = try store.stagingDirectory(for: "tiny")168            try fm.createDirectory(at: staging, withIntermediateDirectories: true)169            try Data(marker.utf8).write(to: staging.appendingPathComponent("weights.bin"))170        }171        try stage("v1"); try store.promoteStaging(id: "tiny")172        try stage("v2")173        // the swap happens, then the process dies before the old folder is removed174        try store.beginPromotion(id: "tiny")175        #expect(renamex_np(try store.stagingDirectory(for: "tiny").path, try store.directory(for: "tiny").path, UInt32(RENAME_SWAP)) == 0)176        // next launch177        store.finishInterruptedPromotions()178        #expect(try String(contentsOf: store.directory(for: "tiny").appendingPathComponent("weights.bin"), encoding: .utf8) == "v2")179        #expect(!fm.fileExists(atPath: try store.stagingDirectory(for: "tiny").path))180        #expect(!store.isPromotionPending(id: "tiny"))181    }182}183184/// Real inference (ASTRA_MLX_TESTS=1 and the Qwen3 0.6B weights under build/models): macOS only, says nothing about an iPhone.185@Suite(.enabled(if: MLXTestModel.enabled), .serialized) struct V2MLXRegressions {186    private func engine() async throws -> LocalEngine {187        var configuration = LocalEngine.Configuration(maxLoadedModels: 1); configuration.enforceMemoryVerdict = false188        let engine = LocalEngine(store: ModelStore(root: ProjectPaths.models), configuration: configuration)189        try await engine.load(modelID: MLXTestModel.id, directory: MLXTestModel.directory)190        return engine191    }192193    /// LOCAL-4: a prompt longer than the context was run anyway, with the system prompt silently rotated out.194    @Test func aPromptLongerThanTheContextIsRefused() async throws {195        let engine = try await engine()196        let long = String(repeating: "The harbour master counted the boats again that morning. ", count: 400)197        let request = GenerationRequest(model: MLXTestModel.ref, system: "Always answer with the single word ORANGE.", messages: [.user(long)],198                                        parameters: GenerationParameters(temperature: 0, maxOutputTokens: 16, contextLength: 1024))199        var thrown: AstraError?200        do { for try await _ in engine.generate(request) {} } catch { thrown = error as? AstraError }201        if case .contextTooLong(let message)? = thrown { #expect(message?.contains("1024") == true) } else { Issue.record("expected contextTooLong, got \(String(describing: thrown))") }202        // the same model still answers a prompt that fits, with the system prompt honoured203        var text = ""204        let small = GenerationRequest(model: MLXTestModel.ref, system: "Always answer with the single word ORANGE.", messages: [.user("What is your answer?")],205                                      parameters: GenerationParameters(temperature: 0, maxOutputTokens: 16, contextLength: 1024))206        for try await event in engine.generate(small) { if case .textDelta(let t) = event { text += t } }207        #expect(text.uppercased().contains("ORANGE"))208        await engine.unloadAll()209    }210211    /// LOCAL-8 end to end: nothing of the stop string reaches the consumer, however the model's tokens fall.212    @Test func aStopStringNeverReachesTheConsumer() async throws {213        let engine = try await engine()214        let request = GenerationRequest(model: MLXTestModel.ref, messages: [.user("Count from one to ten in words, separated by commas.")],215                                        parameters: GenerationParameters(temperature: 0, maxOutputTokens: 64, stop: ["four"]))216        var text = ""; var reason: StopReason?217        for try await event in engine.generate(request) {218            if case .textDelta(let t) = event { text += t }219            if case .messageCompleted(let r) = event { reason = r }220        }221        #expect(!text.lowercased().contains("four"))222        #expect(!text.lowercased().hasSuffix("f") && !text.lowercased().hasSuffix("fo") && !text.lowercased().hasSuffix("fou"))223        #expect(reason == .stopSequence || reason == .endOfTurn || reason == .maxTokens)224        await engine.unloadAll()225    }226}227
Files main
Menu

Theme