SPB Git

Repository Public

RegistryTests.swift 18.5 KB 298 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/RegistryTests.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@Suite struct RegistryCompatibilityTests {94    /// A card that uses every field added after build 2.95    static func newStyleCard() throws -> LocalModelCard {96        try RecordedFixture.card("Qwen3-0.6B-4bit").with {97            $0.tags = ["general", "reasoning", "multilingual", "lightweight"]98            $0.status = .experimental99            $0.statusNote = "Not run on an iPhone."100            $0.thinking = ThinkingSupport(supported: true, toggleable: true, defaultOn: true)101            $0.modelFamily = "Qwen3"; $0.minimumOS = "18.0"; $0.requiredRuntime = "mlx-swift-lm 3.33+"; $0.promptTemplate = "chatml"; $0.tokenizer = "BPE (tokenizer.json)"102            $0.validation = ValidationRecord(downloaded: true, loaded: true, generated: true, cancelled: true, reloaded: true, toolCall: true, thinking: true, image: nil, notes: "Mac only")103            $0.maxImages = 1; $0.supportsMultipleImages = false104        }105    }106107    @Test func theBuild2CatalogueDecodesWithTheNewCode() throws {108        let catalog = try ModelCatalog.decode(try RecordedFixture.build2Catalog())109        #expect(catalog.models.count == 13)110        // Every entry of that catalogue was verified, and none carried the later fields: they read as their defaults.111        for card in catalog.models {112            #expect(card.status == .verified && card.tags.isEmpty && card.thinking == nil && card.validation == nil && card.statusNote == nil)113            #expect(card.modelFamily == nil && card.effectiveFamily == card.family && card.minimumOS == nil && card.maxImages == nil)114            #expect(card.verified != nil)115        }116        // And nothing an old entry said was lost on the way.117        let old = try JSONDecoder().decode(Build2Catalog.self, from: try RecordedFixture.build2Catalog())118        #expect(old.models.map(\.id) == catalog.models.map(\.id))119        for (a, b) in zip(old.models, catalog.models) {120            #expect(a.revision == b.revision && a.totalBytes == b.totalBytes && a.capabilities == b.capabilities && a.baseURL == b.baseURL)121            #expect(a.files.map(\.sha256) == b.files.map(\.sha256) && a.contextLength == b.contextLength && a.redistributable == b.redistributable)122        }123    }124125    @Test func aNewStyleCatalogueIsStillReadableByBuild2() throws {126        var cards = try RecordedFixture.build2Cards()127        cards[0] = try Self.newStyleCard()128        let catalog = ModelCatalog(generatedAt: Date(timeIntervalSince1970: 1_800_000_000), entries: cards.map { .init(card: $0, origin: .bundled) })129        let encoded = try catalog.encoded()130        let json = try #require(JSONValue.parse(encoded))131        #expect(json["schema"]?.intValue == 1)132133        // 1. The frozen copy of build 2's decoder accepts it as is: unknown keys are ignored, every required key is still there.134        let old = try JSONDecoder().decode(Build2Catalog.self, from: encoded)135        #expect(old.schema == 1 && old.models.count == 13)136        #expect(old.models[0].id == "Qwen3-0.6B-4bit" && old.models[0].capabilities == [.text, .reasoning, .tools])137138        // 2. With the new fields stripped (all an old build ever sees), the new code reads the same entry with defaults.139        var stripped = json140        guard case .object(var top) = stripped, case .array(var models)? = top["models"] else { Issue.record("unexpected shape"); return }141        var present = Set<String>()142        models = models.map { model in143            guard case .object(var fields) = model else { return model }144            for key in LocalModelCard.additiveKeys where fields[key] != nil { present.insert(key); fields[key] = nil }145            return .object(fields)146        }147        #expect(present == LocalModelCard.additiveKeys)   // the test card really exercised every added field148        top["models"] = .array(models); stripped = .object(top)149        let reread = try ModelCatalog.decode(try JSONEncoder().encode(stripped))150        #expect(reread.models[0] == (try RecordedFixture.card("Qwen3-0.6B-4bit")))151        #expect(reread.models == (try RecordedFixture.build2Cards()))152153        // 3. Round trip with the new code keeps everything.154        #expect(try ModelCatalog.decode(encoded).models[0] == (try Self.newStyleCard()))155    }156157    /// The catalogue in the source tree (the one that gets bundled and published) must itself obey the rule.158    @Test func theCurrentCatalogueIsReadableByBuild2AndByThisBuild() throws {159        let url = RecordedFixture.directory.deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("docs/catalog/catalog.json")160        let data = try Data(contentsOf: url)161        let old = try JSONDecoder().decode(Build2Catalog.self, from: data)162        #expect(old.schema == 1 && !old.models.isEmpty)163        let current = try ModelCatalog.decode(data)164        #expect(current.models.map(\.id) == old.models.map(\.id))165        for card in current.models {166            #expect(card.files.allSatisfy { $0.hasSHA256 && $0.gitBlobSHA1 == nil }, "\(card.id)")167            #expect(card.tags.allSatisfy(ModelTag.all.contains), "\(card.id) uses a tag outside the documented set: \(card.tags)")168            #expect(RuntimeSupport.installed.supports(card.architecture, needsVision: card.capabilities.contains(.vision)) || card.status == .unsupported, "\(card.id)")169        }170    }171172    @Test func noPublishedValueCanBreakAnOldDecoder() throws {173        // Capabilities are decoded strictly by old builds: the set of raw values must stay the one build 2 knew.174        #expect(Set(Capability.allCases.map(\.rawValue)) == ["text", "vision", "tools", "reasoning", "structuredOutput", "promptCaching", "audioInput", "documents"])175        #expect(ModelCatalog.schema == 1)176        // The build 2 field names are still the wire names.177        let data = try JSONEncoder().encode(try Self.newStyleCard())178        let keys = Set(try #require(JSONValue.parse(data)?.objectValue).keys)179        let build2: Set<String> = ["id", "displayName", "family", "publisher", "repo", "revision", "architecture", "quantization", "parameterCount", "licenseID",180                                   "licenseURL", "redistributable", "totalBytes", "files", "contextLength", "capabilities", "minimumDeviceMemoryGB",181                                   "estimatedRuntimeMemoryBytes", "supportedTasks", "verified", "notes", "baseURL", "fallbackBaseURL"]182        #expect(build2.isSubset(of: keys))183        #expect(keys.subtracting(build2) == LocalModelCard.additiveKeys)184        // A catalogue entry without a SHA-256 would be rejected by old builds: the catalogue validation refuses it too.185        var card = try Self.newStyleCard()186        card.files[0].sha256 = ""; card.files[0].gitBlobSHA1 = String(repeating: "a", count: 40)187        #expect(throws: CatalogError.self) { try card.validate() }188        #expect(throws: Never.self) { try card.validate(allowGitBlobChecksums: true) }189    }190191    @Test func unknownStatusOrTagFromANewerCatalogueDoesNotRejectIt() throws {192        var json = try #require(JSONValue.parse(try JSONEncoder().encode(try Self.newStyleCard()))?.objectValue)193        json["status"] = "deprecated"; json["tags"] = ["general", "audio-future"]; json["someFutureField"] = ["x": 1]194        let card = try JSONDecoder().decode(LocalModelCard.self, from: try JSONEncoder().encode(JSONValue.object(json)))195        #expect(card.status == .experimental)   // unknown = not vouched for196        #expect(card.tags == ["general", "audio-future"])197        try card.validate()198    }199200    @Test func invalidOptionalFieldsAreRejected() throws {201        let base = try Self.newStyleCard()202        #expect(throws: CatalogError.self) { try base.with { $0.thinking = ThinkingSupport(supported: false, toggleable: true, defaultOn: false) }.validate() }203        #expect(throws: CatalogError.self) { try base.with { $0.maxImages = 0 }.validate() }204        #expect(throws: CatalogError.self) { try base.with { $0.minimumOS = "eighteen" }.validate() }205        #expect(throws: CatalogError.self) { try base.with { $0.tags = [""] }.validate() }206        #expect(VersionNumber("18.0")! < VersionNumber("18.0.1")! && VersionNumber("27")! == VersionNumber("27.0")! && VersionNumber("9.9")! < VersionNumber("10")!)207    }208}209210@Suite struct RegistryTests {211    static func catalog() throws -> ModelCatalog {212        let cards = try RecordedFixture.build2Cards().map { card in213            card.with {214                if $0.family == "Qwen3" { $0.tags = ["general", "reasoning", "multilingual"]; $0.modelFamily = "Qwen3"; $0.thinking = .init(supported: true, toggleable: true, defaultOn: true) }215                if $0.family == "SmolLM2" { $0.tags = ["lightweight"] }216                if $0.id == "Phi-4-mini-instruct-4bit" { $0.tags = ["general", "math", "coding"] }217                if $0.id == "gemma-3-1b-it-qat-4bit" { $0.status = .experimental; $0.statusNote = "test" }218            }219        }220        return ModelCatalog(entries: cards.map { .init(card: $0, origin: .bundled) })221    }222    static func installed(_ card: LocalModelCard) -> InstalledModel {223        InstalledModel(card: card, directory: URL(fileURLWithPath: "/tmp/\(card.id)"), bytesOnDisk: card.totalBytes, installedAt: Date(), isComplete: true)224    }225226    @Test func lookupsByIDFamilyAndTag() throws {227        let registry = ModelRegistry(catalog: try Self.catalog())228        #expect(registry.entries.count == 13 && registry.models.count == 13)229        #expect(registry.model(id: "Qwen3-4B-4bit")?.displayName == "Qwen3 4B" && registry.model(id: "nope") == nil)230        #expect(registry.models(inFamily: "qwen3").map(\.id) == ["Qwen3-0.6B-4bit", "Qwen3-1.7B-4bit", "Qwen3-4B-4bit"])231        #expect(registry.families.contains("SmolLM2") && registry.families.contains("Llama 3.2"))232        #expect(registry.models(tagged: "math").map(\.id) == ["Phi-4-mini-instruct-4bit"])233        #expect(registry.models(tagged: "LIGHTWEIGHT").count == 5)234        #expect(registry.tags == ["general", "reasoning", "coding", "lightweight", "multilingual", "math"])235        #expect(registry.models(status: .experimental).map(\.id) == ["gemma-3-1b-it-qat-4bit"])236        #expect(registry.models(with: .tools).count == 5)237    }238239    @Test func installedFirstUpdatesAndDeviceOnlyModels() throws {240        let catalog = try Self.catalog()241        let phi = try #require(catalog.card(id: "Phi-4-mini-instruct-4bit"))242        let oldQwen = try #require(catalog.card(id: "Qwen3-1.7B-4bit")).with { $0.revision = String(repeating: "1", count: 40) }243        let sideloaded = Fixture.card(id: "from-the-hub").with { $0.status = .experimental }244        let unfinished = InstalledModel(card: try #require(catalog.card(id: "Qwen3-4B-4bit")), directory: URL(fileURLWithPath: "/tmp/x"), bytesOnDisk: 1, installedAt: nil, isComplete: false)245        let registry = ModelRegistry(catalog: catalog, installed: [Self.installed(phi), Self.installed(oldQwen), Self.installed(sideloaded), unfinished])246        #expect(registry.installedFirst.prefix(3).map(\.id) == ["Qwen3-1.7B-4bit", "Phi-4-mini-instruct-4bit", "from-the-hub"])247        #expect(registry.installedFirst.count == 14)248        #expect(registry.entry(id: "Qwen3-4B-4bit")?.isInstalled == false)   // an unfinished download is not installed249        #expect(registry.updatesAvailable.map(\.id) == ["Qwen3-1.7B-4bit"])250        #expect(registry.entry(id: "Qwen3-1.7B-4bit")?.installedRevision == String(repeating: "1", count: 40))251        #expect(registry.entry(id: "Phi-4-mini-instruct-4bit")?.updateAvailable == false)252        #expect(registry.entry(id: "from-the-hub")?.origin == nil && registry.entry(id: "Phi-4-mini-instruct-4bit")?.origin == .bundled)253    }254255    @Test func searchMatchesNamePublisherFamilyAndTag() throws {256        let registry = ModelRegistry(catalog: try Self.catalog())257        #expect(registry.search("").count == 13)258        #expect(registry.search("qwen3 1.7b").map(\.id) == ["Qwen3-1.7B-4bit"])   // every word must match259        #expect(registry.search("alibaba").count == 4)            // publisher260        #expect(registry.search("smollm2").count == 5)            // family261        #expect(registry.search("math").map(\.id) == ["Phi-4-mini-instruct-4bit"])   // tag262        #expect(registry.search("zzz").isEmpty)263    }264265    @Test func sortsByNameSizeParametersAndMeasuredSpeed() throws {266        let registry = ModelRegistry(catalog: try Self.catalog())267        #expect(registry.sorted(by: .size).first?.id == "SmolLM2-135M-Instruct-8bit")268        #expect(registry.sorted(by: .size, ascending: false).first?.id == "SmolLM2-1.7B-Instruct")269        #expect(registry.sorted(by: .parameters, ascending: false).first?.id == "Qwen3-4B-4bit")270        #expect(registry.sorted(by: .name).map(\.card.displayName) == registry.models.map(\.displayName).sorted { $0.lowercased() < $1.lowercased() })271        #expect(registry.sorted(by: .measuredSpeed, ascending: false).first?.id == "Qwen2.5-0.5B-Instruct-4bit")   // 562 tok/s in the catalogue272        // A speed measured on this device takes precedence; an entry without any measurement goes last in both directions.273        let local = [ModelMeasurement(modelID: "SmolLM2-1.7B-Instruct", tokensPerSecond: 900, deviceModelIdentifier: "iPhone18,2", platform: "iOS")]274        #expect(registry.sorted(by: .measuredSpeed, ascending: false, measurements: local).first?.id == "SmolLM2-1.7B-Instruct")275        let unmeasured = Fixture.card(id: "unmeasured")276        let extended = ModelRegistry(catalog: ModelCatalog(entries: (try Self.catalog()).entries + [.init(card: unmeasured, origin: .onlineCatalog)]))277        #expect(extended.sorted(by: .measuredSpeed).last?.id == "unmeasured" && extended.sorted(by: .measuredSpeed, ascending: false).last?.id == "unmeasured")278    }279280    @Test func filtersByStatusCapabilityTagInstallAndDeviceFit() throws {281        let catalog = try Self.catalog()282        let registry = ModelRegistry(catalog: catalog, installed: [Self.installed(try #require(catalog.card(id: "Qwen3-0.6B-4bit")))])283        #expect(registry.filtered(by: .init(statuses: [.verified])).count == 12)284        #expect(registry.filtered(by: .init(statuses: [.experimental])).map(\.id) == ["gemma-3-1b-it-qat-4bit"])285        #expect(registry.filtered(by: .init(capabilities: [.reasoning, .tools])).count == 3)286        #expect(registry.filtered(by: .init(tags: ["general", "math"])).map(\.id) == ["Phi-4-mini-instruct-4bit"])287        #expect(registry.filtered(by: .init(installedOnly: true)).map(\.id) == ["Qwen3-0.6B-4bit"])288        let small = FakeDevice.iPhone(4), large = FakeDevice.iPhone(16)289        let onSmall = registry.filtered(by: .init(fitsDevice: .init(device: small.device, memory: small.memory))).map(\.id)290        let onLarge = registry.filtered(by: .init(fitsDevice: .init(device: large.device, memory: large.memory))).map(\.id)291        #expect(onLarge.count == 13)292        #expect(!onSmall.contains("Qwen3-4B-4bit") && !onSmall.contains("SmolLM2-1.7B-Instruct") && onSmall.contains("Qwen3-0.6B-4bit"))293        #expect(Set(onSmall).isSubset(of: Set(onLarge)))294        #expect(registry.query(search: "qwen", filter: .init(capabilities: [.reasoning]), sort: .size, ascending: false).map(\.id)295                == ["Qwen3-4B-4bit", "Qwen3-1.7B-4bit", "Qwen3-0.6B-4bit"])296    }297}298
Files main
Menu

Theme