SPB Git

Repository Public License

LocalModelTests.swift 11.3 KB 212 lines swift

1import Foundation2import Testing3@testable import ProviderKit45/// A runtime that generates canned text, for exercising the adapter protocol without a model.6final class FakeRuntime: LocalModelRuntime, @unchecked Sendable {7    let id: String8    let displayName = "Fake runtime"9    let state: LocalRuntimeAvailability10    let memory: UInt64?11    let events: [ChatEvent]12    let hangs: Bool13    let log = Locked<[String]>([])1415    init(id: String = "fake", state: LocalRuntimeAvailability = .available, memory: UInt64? = 2_000_000_000,16         events: [ChatEvent] = [.textDelta("Local "), .textDelta("answer")], hangs: Bool = false) {17        self.id = id; self.state = state; self.memory = memory; self.events = events; self.hangs = hangs18    }1920    func availability() async -> LocalRuntimeAvailability { state }21    func availableModels() async throws -> [LocalModelDescriptor] {22        [LocalModelDescriptor(id: "fake-small", displayName: "Fake Small", contextLength: 8_192, supportsTools: true)]23    }24    func memoryRequirement(for modelID: String) async -> UInt64? { memory }25    func load(modelID: String) async throws { log.mutate { $0.append("load \(modelID)") } }26    func unload(modelID: String) async { log.mutate { $0.append("unload \(modelID)") } }2728    func generate(_ request: ChatRequest) -> AsyncThrowingStream<ChatEvent, Error> {29        log.mutate { $0.append("generate \(request.model)") }30        let (stream, continuation) = AsyncThrowingStream<ChatEvent, Error>.makeStream()31        let log = log32        continuation.onTermination = { _ in log.mutate { $0.append("terminated") } }33        for event in events { continuation.yield(event) }34        if hangs { held.set(continuation) } else { continuation.finish() }35        return stream36    }3738    private let held = Locked<AsyncThrowingStream<ChatEvent, Error>.Continuation?>(nil)39}4041@Suite struct LocalModelTests {42    private let mac = DeviceCapability(physicalMemoryBytes: 64 * 1_073_741_824, platform: .macOS)43    private let smallPhone = DeviceCapability(physicalMemoryBytes: 6 * 1_073_741_824, platform: .iOS)44    private let request = ChatRequest(model: "fake-small", messages: [.user("Hi")])4546    // MARK: Device capability4748    @Test func deviceCapabilityDecidesWhetherLocalModelsAreOffered() {49        #expect(mac.offersLocalModels)50        #expect(mac.unavailabilityReason == nil)51        #expect(!smallPhone.offersLocalModels)52        #expect(smallPhone.unavailabilityReason?.contains("8 GB") == true)53        // A device sold as 8 GB reports a little less than 8 GiB.54        #expect(DeviceCapability(physicalMemoryBytes: 7_600_000_000, platform: .iOS).offersLocalModels)55        let simulator = DeviceCapability(physicalMemoryBytes: 64 * 1_073_741_824, platform: .iOS, isSimulator: true)56        #expect(!simulator.offersLocalModels)57        #expect(simulator.unavailabilityReason?.contains("Simulator") == true)58    }5960    @Test func memoryBudgetDependsOnThePlatform() {61        let phone = DeviceCapability(physicalMemoryBytes: 8 * 1_073_741_824, platform: .iOS)62        let laptop = DeviceCapability(physicalMemoryBytes: 8 * 1_073_741_824, platform: .macOS)63        #expect(phone.modelMemoryBudgetBytes < laptop.modelMemoryBudgetBytes)64        #expect(laptop.canLoad(memoryRequirementBytes: 4 * 1_073_741_824))65        #expect(!phone.canLoad(memoryRequirementBytes: 4 * 1_073_741_824))66        #expect(phone.canLoad(memoryRequirementBytes: nil))            // a system-managed model67        #expect(!smallPhone.canLoad(memoryRequirementBytes: 1))68        #expect(!smallPhone.canLoad(memoryRequirementBytes: nil))69    }7071    @Test func currentDeviceIsDescribed() {72        let device = DeviceCapability.current73        #expect(device.physicalMemoryBytes == ProcessInfo.processInfo.physicalMemory)74        #if os(macOS)75        #expect(device.platform == .macOS)76        #expect(!device.isSimulator)77        #endif78    }7980    // MARK: Capability report8182    @Test func reportSaysMLXIsNotInstalledWhenNoRuntimeWasProvided() async {83        let report = await LocalCapabilityReport.make(runtimes: [], device: mac)84        #expect(report.offersLocalModels)85        #expect(!report.hasUsableRuntime)86        let mlx = report.runtimes.first { $0.id == LocalRuntimeIdentifier.mlx }87        #expect(mlx?.message == "MLX runtime not installed")88        #expect(mlx?.isInstalled == false)89        #expect(mlx?.isAvailable == false)90        let apple = report.runtimes.first { $0.id == LocalRuntimeIdentifier.appleFoundationModels }91        #expect(apple?.isInstalled == false)92        #expect(apple?.isAvailable == false)93    }9495    @Test func reportReflectsEachRuntimeHonestly() async {96        let ready = FakeRuntime(id: LocalRuntimeIdentifier.mlx)97        let off = FakeRuntime(id: LocalRuntimeIdentifier.appleFoundationModels, state: .unavailable(reason: "Apple Intelligence is turned off in System Settings."))98        let report = await LocalCapabilityReport.make(runtimes: [off, ready], device: mac)99        #expect(report.hasUsableRuntime)100        #expect(report.runtimes.count == 2)101        #expect(report.runtimes.first { $0.id == LocalRuntimeIdentifier.mlx }?.isAvailable == true)102        let apple = report.runtimes.first { $0.id == LocalRuntimeIdentifier.appleFoundationModels }103        #expect(apple?.isInstalled == true)104        #expect(apple?.isAvailable == false)105        #expect(apple?.message == "Apple Intelligence is turned off in System Settings.")106    }107108    @Test func reportOnADeviceTooSmallOffersNothing() async {109        let report = await LocalCapabilityReport.make(runtimes: [FakeRuntime()], device: smallPhone)110        #expect(!report.offersLocalModels)111        #expect(!report.hasUsableRuntime)112        #expect(report.deviceMessage?.contains("8 GB") == true)113        #expect(report.runtimes.allSatisfy { !$0.isAvailable })114    }115116    @Test func appleRuntimeAvailabilityIsConsistentWithItsReason() async {117        // Whatever this machine supports, the two entry points must agree and the runtime must answer without crashing.118        let runtime = AppleOnDeviceModel.makeRuntime()119        #expect((runtime == nil) == (AppleOnDeviceModel.unavailableReason != nil))120        if let runtime {121            #expect(runtime.id == LocalRuntimeIdentifier.appleFoundationModels)122            switch await runtime.availability() {123            case .available: #expect(try! await runtime.availableModels().map(\.id) == [LocalModelIdentifier.appleSystemModel])124            case .unavailable(let reason):125                #expect(!reason.isEmpty)126                #expect(try! await runtime.availableModels().isEmpty)127            }128            #expect(await runtime.memoryRequirement(for: LocalModelIdentifier.appleSystemModel) == nil)129        }130    }131132    // MARK: Provider over a runtime133134    @Test func streamsThroughTheRuntimeAndCompletesTheProtocol() async throws {135        let runtime = FakeRuntime()136        let provider = LocalProvider(runtime: runtime, device: mac)137        let (events, error) = await collect(provider.stream(request))138        #expect(error == nil)139        // The runtime sent neither `started` nor `finished`: the provider adds them.140        #expect(events == [.started(ResponseStart(model: "fake-small")), .textDelta("Local "), .textDelta("answer"), .finished(.unknown)])141        #expect(runtime.log.get().prefix(2) == ["load fake-small", "generate fake-small"])142        // No usage was reported by the runtime, so none is invented.143        #expect(try await LocalProvider(runtime: FakeRuntime(), device: mac).complete(request).usage == nil)144    }145146    @Test func runtimeEventsPassThroughUnchanged() async {147        let call = ToolCall(id: "c1", name: "open_tab", arguments: ["url": "https://example.com"])148        let scripted: [ChatEvent] = [.started(ResponseStart(model: "x")), .toolCallStarted(id: "c1", name: "open_tab"), .toolCallCompleted(call),149                                     .usage(ProviderUsage(inputTokens: 9, outputTokens: 3)), .finished(.toolCalls)]150        let (events, error) = await collect(LocalProvider(runtime: FakeRuntime(events: scripted), device: mac).stream(request))151        #expect(error == nil)152        #expect(events == scripted)153    }154155    @Test func listsModelsAndTestsTheConnection() async throws {156        let provider = LocalProvider(runtime: FakeRuntime(), device: mac)157        let models = try await provider.listModels()158        #expect(models == [ModelInfo(id: "fake-small", displayName: "Fake Small", contextLength: 8_192, supportsTools: true, supportsImages: false)])159        let report = try await provider.testConnection()160        #expect(report.family == .local)161        #expect(report.modelCount == 1)162    }163164    @Test func unavailableRuntimeIsReportedAndNeverLoaded() async {165        let runtime = FakeRuntime(state: .unavailable(reason: "The on-device model is still downloading."))166        let provider = LocalProvider(runtime: runtime, device: mac)167        #expect(await collect(provider.stream(request)).error == .local("The on-device model is still downloading."))168        await #expect(throws: ProviderError.local("The on-device model is still downloading.")) { try await provider.testConnection() }169        #expect(runtime.log.get().isEmpty)170    }171172    @Test func modelTooLargeForTheDeviceIsRefusedBeforeLoading() async {173        let runtime = FakeRuntime(memory: 60 * 1_073_741_824)174        let (_, error) = await collect(LocalProvider(runtime: runtime, device: mac).stream(request))175        guard case .local(let message) = error else { Issue.record("expected local error, got \(String(describing: error))"); return }176        #expect(message.contains("60.0 GB"))177        #expect(runtime.log.get().isEmpty)178    }179180    @Test func deviceWithoutEnoughMemoryNeverReachesTheRuntime() async {181        let runtime = FakeRuntime()182        let provider = LocalProvider(runtime: runtime, device: smallPhone)183        guard case .local = await collect(provider.stream(request)).error else { Issue.record("expected local error"); return }184        await #expect(throws: ProviderError.self) { try await provider.listModels() }185        #expect(runtime.log.get().isEmpty)186    }187188    @Test func cancellingStopsGeneration() async {189        let runtime = FakeRuntime(hangs: true)190        let provider = LocalProvider(runtime: runtime, device: mac)191        let sawText = Locked(false)192        let request = request193        let consumer = Task {194            do { for try await event in provider.stream(request) { if case .textDelta = event { sawText.set(true) } } } catch {}195        }196        #expect(await eventually { sawText.get() })197        consumer.cancel()198        #expect(await eventually { runtime.log.get().contains("terminated") })199    }200201    @Test func registryReportsAMissingMLXRuntimeInsteadOfPretending() async throws {202        let test = TestEnvironment([])203        let registry = ProviderRegistry(store: InMemoryProviderConfigurationStore(), secrets: RecordingSecrets(), environment: test.environment,204                                        localRuntimes: [], device: mac)205        try await registry.upsert(ProviderConfiguration(id: "l", family: .local, model: "mlx-community/some-model", localRuntimeID: LocalRuntimeIdentifier.mlx))206        await #expect(throws: ProviderError.local("MLX runtime not installed.")) { try await registry.provider(for: "l") }207        let report = await registry.localCapabilityReport()208        #expect(report.runtimes.contains { $0.id == LocalRuntimeIdentifier.mlx && $0.message == "MLX runtime not installed" })209        #expect(test.transport.requests.isEmpty)210    }211}212
Files main
Menu

Theme