Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraLocalTests/DownloadInstallTests.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/// Atomic installation, integrity, version tracking, the on-disk layout of earlier builds, and whole-piece (background-style) transfers.94@Suite struct DownloadInstallTests {95 let dir = TempDirectory()96 let server = FakeServer()97 static let weights = Fixture.mirror + "model.safetensors"9899 private func exists(_ url: URL) -> Bool { FileManager.default.fileExists(atPath: url.path) }100 private func stagingPartial(_ store: ModelStore, id: String = "tiny") throws -> URL {101 URL(fileURLWithPath: try store.stagingFileURL(modelID: id, path: "model.safetensors").path + ".partial")102 }103 private func install(_ coordinator: DownloadCoordinator, _ card: LocalModelCard = Fixture.card()) async throws {104 try await coordinator.start(DownloadPlan(card: card))105 #expect(await coordinator.waitUntilSettled(id: card.id)?.phase == .completed)106 }107 /// A second version of the fixture model: another commit, other weights.108 static func version2() -> (card: LocalModelCard, files: [(String, Data)]) {109 var files = Fixture.contents; files[2].1 = bytes(2_500_000, seed: 42)110 var card = Fixture.card(files: files); card.revision = String(repeating: "9", count: 40)111 card.baseURL = "https://mirror.test/astra/models/v1/tiny-v2/"; card.fallbackBaseURL = "https://huggingface.co/acme/tiny/resolve/\(card.revision)/"112 return (card, files)113 }114115 // MARK: Atomic installation116117 @Test func nothingAppearsInTheModelFolderBeforeEveryFileIsVerified() async throws {118 Fixture.publish(server, base: Fixture.mirror)119 server.script(Self.weights, [.stall(1_500_000)])120 let (coordinator, store) = Fixture.coordinator(dir, server)121 try await coordinator.start(DownloadPlan(card: Fixture.card()))122 let partial = try stagingPartial(store)123 try await waitFor { (ModelStore.fileSize(partial) ?? 0) >= 1_500_000 }124 // Two files are already complete and verified, the third is half way: the model folder does not exist at all.125 #expect(!exists(try store.directory(for: "tiny")))126 #expect(!store.isInstalled("tiny") && store.installed().isEmpty && store.loadableDirectory(for: "tiny") == nil && store.installInfo(id: "tiny") == nil)127 #expect(exists(try store.stagingFileURL(modelID: "tiny", path: "config.json")))128 #expect(store.models().map(\.isComplete) == [false])129 await coordinator.pause(id: "tiny")130 #expect(!exists(try store.directory(for: "tiny")))131 try await coordinator.resume(id: "tiny")132 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .completed)133 // One step later everything is there, verified, and the staging area is gone.134 #expect(store.isInstalled("tiny") && !exists(store.stagingRoot))135 for (path, data) in Fixture.contents { #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: path)) == data) }136 let info = try #require(store.installInfo(id: "tiny"))137 #expect(info.revision == Fixture.revision && info.verifiedAt != nil)138 #expect(try FileManager.default.contentsOfDirectory(atPath: store.root.path).sorted() == ["tiny"])139 }140141 @Test func aFailedDownloadLeavesNoModelFolder() async throws {142 var wrong = Fixture.contents; wrong[2].1 = bytes(3_000_000, seed: 77)143 Fixture.publish(server, base: Fixture.mirror, files: wrong); Fixture.publish(server, base: Fixture.hub, files: wrong)144 let (coordinator, store) = Fixture.coordinator(dir, server)145 try await coordinator.start(DownloadPlan(card: Fixture.card()))146 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .failed(.hashMismatch(file: "model.safetensors")))147 #expect(!exists(try store.directory(for: "tiny")) && !store.isInstalled("tiny"))148 }149150 @Test func anInstallInterruptedBeforeTheMoveIsFinishedAtTheNextLaunch() async throws {151 // The state a crash leaves between the last verification and the rename: a complete staging folder with its install record.152 let store = ModelStore(root: dir.url.appendingPathComponent("Models")); try store.prepare()153 let card = Fixture.card()154 for (path, data) in Fixture.contents {155 let url = try store.stagingFileURL(modelID: "tiny", path: path)156 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true); try data.write(to: url)157 }158 try ModelStore.writeCard(card, metaDirectory: try store.stagingMeta("tiny"))159 try ModelStore.writeInstallRecord(.init(installedAt: Date(), revision: card.revision, verifiedAt: Date()), metaDirectory: try store.stagingMeta("tiny"))160 #expect(!store.isInstalled("tiny"))161 let coordinator = DownloadCoordinator(store: store, transport: server)162 #expect(await coordinator.restore().isEmpty)163 #expect(store.isInstalled("tiny") && !exists(store.stagingRoot) && server.requests.isEmpty)164 }165166 // MARK: Version tracking167168 @Test func updateIsOfferedButNothingChangesUntilAsked() async throws {169 Fixture.publish(server, base: Fixture.mirror)170 let (coordinator, store) = Fixture.coordinator(dir, server)171 try await install(coordinator)172 #expect(store.installedRevision(id: "tiny") == Fixture.revision)173 #expect(store.availableUpdate(for: Fixture.card()) == nil) // same commit, same files174 #expect(store.availableUpdate(for: Fixture.card(id: "absent")) == nil) // not installed: nothing to update175176 let v2 = Self.version2()177 let update = try #require(store.availableUpdate(for: v2.card))178 #expect(update.installedRevision == Fixture.revision && update.availableRevision == v2.card.revision && update.card == v2.card)179 #expect(update.installedBytes == Fixture.card().totalBytes && update.availableBytes == v2.card.totalBytes)180 #expect(update.summary.contains("keeps working until you update"))181 let catalog = ModelCatalog(entries: [.init(card: v2.card, origin: .onlineCatalog), .init(card: Fixture.card(id: "absent"), origin: .bundled)])182 #expect(coordinator.availableUpdates(in: catalog).map(\.id) == ["tiny"])183 #expect(ModelRegistry(catalog: catalog, installed: store.installed()).updatesAvailable.map(\.id) == ["tiny"])184 // Detecting an update touched nothing.185 #expect(store.isInstalled("tiny") && store.installedRevision(id: "tiny") == Fixture.revision && !exists(store.stagingRoot))186 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)187 // Same commit but another file list is an update too.188 var refiled = Fixture.contents; refiled[1].1 = bytes(40_000, seed: 91)189 #expect(store.availableUpdate(for: Fixture.card(files: refiled)) != nil)190 }191192 @Test func theInstalledVersionStaysUsableUntilTheNewOneIsVerifiedThenIsReplacedInOneStep() async throws {193 Fixture.publish(server, base: Fixture.mirror)194 let (coordinator, store) = Fixture.coordinator(dir, server)195 try await install(coordinator)196 let v2 = Self.version2()197 Fixture.publish(server, base: v2.card.baseURL!, files: v2.files)198 let newWeights = v2.card.baseURL! + "model.safetensors"199 server.script(newWeights, [.stall(1_000_000)])200201 let update = try #require(store.availableUpdate(for: v2.card))202 let status = try await coordinator.start(update: update)203 #expect(status.replacesInstalled)204 let partial = try stagingPartial(store)205 try await waitFor { (ModelStore.fileSize(partial) ?? 0) >= 1_000_000 }206 // Mid-update: the old version is intact, installed and loadable.207 #expect(store.isInstalled("tiny") && store.installedRevision(id: "tiny") == Fixture.revision && store.loadableDirectory(for: "tiny") != nil)208 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)209 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact)210211 // Cancelling the update removes only the update.212 await coordinator.cancel(id: "tiny")213 #expect(!exists(store.stagingRoot))214 #expect(store.isInstalled("tiny") && store.installedRevision(id: "tiny") == Fixture.revision)215 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)216217 // Run to the end: the new version takes the place of the old one.218 try await coordinator.start(update: update)219 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .completed)220 #expect(store.isInstalled("tiny") && store.installedRevision(id: "tiny") == v2.card.revision && store.availableUpdate(for: v2.card) == nil)221 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == v2.files[2].1)222 #expect(!exists(store.stagingRoot) && store.installedCard(id: "tiny") == v2.card)223 // Unchanged files (config, tokenizer) were taken from the installed copy, not downloaded again.224 #expect(server.requests(to: v2.card.baseURL! + "config.json").isEmpty && server.requests(to: v2.card.baseURL! + "tokenizer.json").isEmpty)225 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact)226 }227228 @Test func aFailedUpdateKeepsTheInstalledVersion() async throws {229 Fixture.publish(server, base: Fixture.mirror)230 let (coordinator, store) = Fixture.coordinator(dir, server)231 try await install(coordinator)232 let v2 = Self.version2()233 var corrupt = v2.files; corrupt[2].1 = bytes(2_500_000, seed: 1234) // right size, wrong bytes, on every source234 Fixture.publish(server, base: v2.card.baseURL!, files: corrupt); Fixture.publish(server, base: v2.card.fallbackBaseURL!, files: corrupt)235 try await coordinator.start(DownloadPlan(card: v2.card))236 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .failed(.hashMismatch(file: "model.safetensors")))237 #expect(store.isInstalled("tiny") && store.installedRevision(id: "tiny") == Fixture.revision)238 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)239 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact)240 }241242 @Test func cancellingACompletedDownloadDoesNotDeleteTheModel() async throws {243 Fixture.publish(server, base: Fixture.mirror)244 let (coordinator, store) = Fixture.coordinator(dir, server)245 try await install(coordinator)246 await coordinator.cancel(id: "tiny")247 #expect(await coordinator.status(id: "tiny")?.phase == .completed && store.isInstalled("tiny"))248 }249250 // MARK: Integrity of an installed model251252 @Test func corruptedAndMissingFilesAreDetectedNeverDeletedAndRepaired() async throws {253 Fixture.publish(server, base: Fixture.mirror)254 let (coordinator, store) = Fixture.coordinator(dir, server)255 try await install(coordinator)256 let intact = await coordinator.verifyInstalled(id: "tiny")257 #expect(intact.state == .intact && intact.bytesChecked == Fixture.card().totalBytes && intact.damagedFiles.isEmpty && intact.missingFiles.isEmpty)258 #expect(await coordinator.verifyInstalled(id: "nope").state == .notInstalled)259260 // Flip one byte in the weights (same size) and remove the tokenizer.261 let weights = try store.fileURL(modelID: "tiny", path: "model.safetensors")262 let handle = try FileHandle(forWritingTo: weights); try handle.seek(toOffset: 1_234_567); try handle.write(contentsOf: Data([0xFF, 0x00, 0xFF])); try handle.close()263 try FileManager.default.removeItem(at: try store.fileURL(modelID: "tiny", path: "tokenizer.json"))264 let damaged = await coordinator.verifyInstalled(id: "tiny")265 #expect(damaged.state == .damaged && damaged.damagedFiles == ["model.safetensors"] && damaged.missingFiles == ["tokenizer.json"])266 #expect(damaged.summary.contains("Nothing was deleted"))267 let folder = try store.directory(for: "tiny")268 #expect(exists(weights) && exists(folder)) // reported, not removed269 #expect(!store.isInstalled("tiny")) // a missing file already makes it not loadable270271 // Repair fetches the two bad files only and swaps the folder once everything verifies.272 let before = server.requests.count273 try await coordinator.repair(id: "tiny")274 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .completed)275 let fetched = server.requests.dropFirst(before).map(\.url)276 #expect(Set(fetched) == [Fixture.mirror + "model.safetensors", Fixture.mirror + "tokenizer.json"])277 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact && store.isInstalled("tiny"))278 #expect(try Data(contentsOf: weights) == Fixture.contents[2].1)279 }280281 // MARK: Disk exhaustion282283 @Test func volumeFillingUpMidDownloadIsReportedAndThePartialIsKept() async throws {284 Fixture.publish(server, base: Fixture.mirror)285 let store = ModelStore(root: dir.url.appendingPathComponent("Models"))286 var config = DownloadCoordinator.Configuration()287 config.retryDelay = { _ in 0 }; config.sleep = { _ in await Task.yield() }; config.safetyMarginBytes = 1 << 20; config.freeSpace = { _ in 1 << 40 }288 let written = ByteMeter(0)289 config.write = { handle, chunk in290 // The volume accepts 1.2 MB of weights, then is full.291 if written.read() + Int64(chunk.count) > 1_200_000 { throw CocoaError(.fileWriteOutOfSpace) }292 try handle.write(contentsOf: chunk); written.set(written.read() + Int64(chunk.count))293 }294 let full = DownloadCoordinator(store: store, transport: server, configuration: config)295 try await full.start(DownloadPlan(card: Fixture.card()))296 let status = try #require(await full.waitUntilSettled(id: "tiny"))297 guard case .failed(.insufficientDisk) = status.phase else { Issue.record("expected insufficientDisk, got \(status.phase)"); return }298 let modelFolder = try store.directory(for: "tiny")299 #expect(!store.isInstalled("tiny") && !exists(modelFolder))300 // What was written is kept (config.json and tokenizer.json verified, part of the weights), nothing was retried on the fallback.301 let kept = ModelStore.fileSize(try stagingPartial(store)) ?? 0302 #expect(kept > 1_000_000 && kept <= 1_200_000 && status.bytesDone >= kept)303 #expect(server.requests.allSatisfy { $0.url.hasPrefix(Fixture.mirror) } && server.requests(to: Self.weights).count == 1)304305 // Space was freed: a new launch resumes from the partial file.306 let (second, _) = Fixture.coordinator(dir, server)307 #expect(await second.restore().map(\.phase) == [.paused])308 try await second.resume(id: "tiny")309 #expect(await second.waitUntilSettled(id: "tiny")?.phase == .completed)310 #expect(server.requests(to: Self.weights).last?.range == "bytes=\(kept)-")311 #expect(store.isInstalled("tiny"))312 }313314 // MARK: The layout written by builds 1 and 2315316 /// The card.json of build 2: only the fields that build knew.317 private func build2CardJSON(_ card: LocalModelCard) throws -> Data {318 var fields = try #require(JSONValue.parse(try JSONEncoder().encode(card))?.objectValue)319 for key in LocalModelCard.additiveKeys { fields[key] = nil }320 return try JSONEncoder().encode(JSONValue.object(fields))321 }322323 @Test func modelsInstalledByEarlierBuildsKeepWorkingUntouched() async throws {324 // Exactly what build 2 left on disk: <root>/<id>/<files> + .astra/card.json + .astra/installed.json {installedAt, revision}.325 let store = ModelStore(root: dir.url.appendingPathComponent("Models")); try store.prepare()326 let card = Fixture.card()327 let folder = try store.directory(for: "tiny"), meta = folder.appendingPathComponent(".astra")328 try FileManager.default.createDirectory(at: meta, withIntermediateDirectories: true)329 for (path, data) in Fixture.contents { try data.write(to: folder.appendingPathComponent(path)) }330 try build2CardJSON(card).write(to: meta.appendingPathComponent("card.json"))331 try Data(#"{"installedAt":"2026-11-21T22:00:00Z","revision":"\#(card.revision)"}"#.utf8).write(to: meta.appendingPathComponent("installed.json"))332 let before = try FileManager.default.attributesOfItem(atPath: folder.appendingPathComponent("model.safetensors").path)[.modificationDate] as? Date333334 #expect(store.isInstalled("tiny") && store.loadableDirectory(for: "tiny") == folder)335 #expect(store.installed().map(\.id) == ["tiny"] && store.installedCard(id: "tiny") == card)336 #expect(store.installedCard(id: "tiny")?.status == .verified)337 let info = try #require(store.installInfo(id: "tiny"))338 #expect(info.revision == card.revision && info.installedAt == ISO8601DateFormatter().date(from: "2026-11-21T22:00:00Z"))339340 // A new launch: restore finds nothing to do and moves nothing.341 let (coordinator, _) = Fixture.coordinator(dir, server)342 #expect(await coordinator.restore().isEmpty)343 #expect(store.removeOrphans() == 0)344 #expect(store.isInstalled("tiny") && !exists(store.stagingRoot) && server.requests.isEmpty)345 #expect(try FileManager.default.attributesOfItem(atPath: folder.appendingPathComponent("model.safetensors").path)[.modificationDate] as? Date == before)346 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact)347 #expect(store.availableUpdate(for: card) == nil && store.availableUpdate(for: Self.version2().card) != nil)348 #expect(ModelRegistry(catalog: ModelCatalog(entries: [.init(card: card, origin: .bundled)]), installed: store.installed()).entry(id: "tiny")?.isInstalled == true)349 }350351 @Test func aDownloadLeftUnfinishedByAnEarlierBuildIsResumedFromItsPartialFile() async throws {352 // Build 2 downloaded straight into the model folder: complete files, a .partial file and .astra/download.json side by side.353 Fixture.publish(server, base: Fixture.mirror)354 let store = ModelStore(root: dir.url.appendingPathComponent("Models")); try store.prepare()355 let card = Fixture.card()356 let folder = try store.directory(for: "tiny"), meta = folder.appendingPathComponent(".astra")357 try FileManager.default.createDirectory(at: meta, withIntermediateDirectories: true)358 try Fixture.contents[0].1.write(to: folder.appendingPathComponent("config.json"))359 try Fixture.contents[1].1.write(to: folder.appendingPathComponent("tokenizer.json"))360 try Fixture.contents[2].1.prefix(1_000_000).write(to: folder.appendingPathComponent("model.safetensors.partial"))361 try build2CardJSON(card).write(to: meta.appendingPathComponent("card.json"))362 let plan: JSONValue = ["id": "tiny", "sources": [.string(Fixture.mirror), .string(Fixture.hub)], "card": try #require(JSONValue.parse(try build2CardJSON(card))),363 "files": .array(card.files.map { ["path": .string($0.path), "size": .number(Double($0.size)), "sha256": .string($0.sha256)] })]364 let state: JSONValue = ["plan": plan, "usedFallback": false,365 "verified": ["config.json": .string(card.files[0].sha256), "tokenizer.json": .string(card.files[1].sha256)]]366 try JSONEncoder().encode(state).write(to: meta.appendingPathComponent("download.json"))367 #expect(!store.isInstalled("tiny"))368369 let (coordinator, _) = Fixture.coordinator(dir, server)370 let restored = await coordinator.restore()371 #expect(restored.count == 1 && restored[0].phase == .paused && restored[0].bytesDone == card.totalBytes - 2_000_000 && restored[0].filesDone == 2)372 // The unfinished download now lives in the staging area; the model folder is absent until it is complete.373 let movedPartial = try stagingPartial(store)374 #expect(!exists(folder) && (ModelStore.fileSize(movedPartial) ?? 0) == 1_000_000)375 // It was cut short by the app going away, not paused by the user: it may be continued without asking.376 #expect(await coordinator.continueInterrupted() == ["tiny"])377 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .completed)378 #expect(server.requests.map(\.url) == [Self.weights] && server.requests[0].range == "bytes=1000000-")379 #expect(store.isInstalled("tiny") && !exists(store.stagingRoot))380 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)381 }382383 @Test func aDownloadPausedByTheUserIsNotContinuedBehindTheirBack() async throws {384 Fixture.publish(server, base: Fixture.mirror)385 server.script(Self.weights, [.stall(500_000)])386 let (first, store) = Fixture.coordinator(dir, server)387 try await first.start(DownloadPlan(card: Fixture.card()))388 let partial = try stagingPartial(store)389 try await waitFor { (ModelStore.fileSize(partial) ?? 0) >= 500_000 }390 await first.pause(id: "tiny")391 let (second, _) = Fixture.coordinator(dir, server)392 #expect(await second.restore().map(\.phase) == [.paused])393 #expect(await second.continueInterrupted().isEmpty)394 #expect(await second.status(id: "tiny")?.phase == .paused)395 try await second.resume(id: "tiny") // the user's own decision still works396 #expect(await second.waitUntilSettled(id: "tiny")?.phase == .completed && store.isInstalled("tiny"))397 }398399 // MARK: Cards built from the Hub400401 @Test func hubCardPinnedByGitBlobIdsIsVerifiedAndGetsItsSHA256AtInstall() async throws {402 Fixture.publish(server, base: Fixture.hub)403 let (coordinator, store) = Fixture.coordinator(dir, server)404 var card = Fixture.card(redistributable: false)405 card.status = .experimental406 card.files = card.files.enumerated().map { i, f in407 f.path.hasSuffix(".safetensors") ? f : LocalModelFile(path: f.path, size: f.size, sha256: "", gitBlobSHA1: gitBlobHex(Fixture.contents[i].1))408 }409 try card.validate(allowGitBlobChecksums: true)410 try await install(coordinator, card)411 let installed = try #require(store.installedCard(id: "tiny"))412 #expect(installed.files.map(\.sha256) == Fixture.contents.map { sha256Hex($0.1) }) // computed locally, so the model can be re-verified413 #expect(installed.status == .experimental && installed.redistributable == false)414 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact)415 #expect(server.requests.allSatisfy { $0.url.hasPrefix(Fixture.hub) })416 // A wrong git blob id is a checksum failure like any other.417 let other = TempDirectory()418 let (second, secondStore) = Fixture.coordinator(other, server)419 card.files[0].gitBlobSHA1 = String(repeating: "0", count: 40)420 try await second.start(DownloadPlan(card: card))421 #expect(await second.waitUntilSettled(id: "tiny")?.phase == .failed(.hashMismatch(file: "config.json")))422 #expect(!secondStore.isInstalled("tiny"))423 }424425 // MARK: Whole-piece transfers (the shape of iOS background sessions)426427 private func pieceCoordinator(_ transport: FakePieceTransport, mode: DownloadCoordinator.TransferMode = .automatic) -> (DownloadCoordinator, ModelStore) {428 let store = ModelStore(root: dir.url.appendingPathComponent("Models"))429 var config = DownloadCoordinator.Configuration()430 config.retryDelay = { _ in 0 }; config.sleep = { _ in await Task.yield() }; config.safetyMarginBytes = 1 << 20; config.freeSpace = { _ in 1 << 40 }431 config.transferMode = mode432 return (DownloadCoordinator(store: store, transport: transport, configuration: config), store)433 }434435 @Test func piecesLandOnDiskAndAreVerifiedBeforeInstall() async throws {436 Fixture.publish(server, base: Fixture.mirror)437 let transport = FakePieceTransport(server: server)438 let (coordinator, store) = pieceCoordinator(transport)439 try await coordinator.start(DownloadPlan(card: Fixture.card()))440 let status = try #require(await coordinator.waitUntilSettled(id: "tiny"))441 #expect(status.phase == .completed && status.usesBackgroundSession && status.bytesDone == Fixture.card().totalBytes)442 #expect(transport.pieceRequests.map(\.path) == ["config.json", "tokenizer.json", "model.safetensors"] && transport.pieceRequests.allSatisfy { $0.offset == 0 })443 #expect(store.isInstalled("tiny") && !exists(store.stagingRoot))444 #expect(await coordinator.verifyInstalled(id: "tiny").isIntact)445 }446447 @Test func aPieceThatLandedWhileTheAppWasNotRunningIsAdoptedAtResume() async throws {448 Fixture.publish(server, base: Fixture.mirror)449 server.script(Self.weights, [.stall(100_000)])450 let transport = FakePieceTransport(server: server)451 let (first, store) = pieceCoordinator(transport)452 try await first.start(DownloadPlan(card: Fixture.card()))453 try await waitFor { transport.pieceRequests.contains { $0.path == "model.safetensors" } }454 await first.pause(id: "tiny") // stands for the process being killed while the system keeps the transfer going455 // The system finishes the transfer on its own and the relaunched app's delegate lands the file.456 let landed = try store.stagingMeta("tiny").appendingPathComponent("landed")457 let temporary = dir.url.appendingPathComponent("system-temp-file"); try Fixture.contents[2].1.write(to: temporary)458 try LandedPiece.land(temporary, as: LandedPiece(path: "model.safetensors", offset: 0, status: 200), in: landed)459460 let before = transport.pieceRequests.count461 let (second, _) = pieceCoordinator(transport)462 #expect(await second.restore().map(\.phase) == [.paused])463 try await second.resume(id: "tiny")464 #expect(await second.waitUntilSettled(id: "tiny")?.phase == .completed)465 #expect(transport.pieceRequests.count == before) // nothing was requested again: the landed file was verified and used466 #expect(store.isInstalled("tiny") && !exists(store.stagingRoot))467 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)468 }469470 @Test func aPartialFileIsContinuedWithARangePieceAndCorruptPiecesAreRejected() async throws {471 Fixture.publish(server, base: Fixture.mirror)472 let transport = FakePieceTransport(server: server)473 let (coordinator, store) = pieceCoordinator(transport)474 // 1 MB already on disk from a streaming run.475 let partial = try stagingPartial(store)476 try FileManager.default.createDirectory(at: partial.deletingLastPathComponent(), withIntermediateDirectories: true)477 try Fixture.contents[2].1.prefix(1_000_000).write(to: partial)478 // A stale piece for another offset is lying around: it must be dropped, not appended.479 let landed = try store.stagingMeta("tiny").appendingPathComponent("landed")480 let stale = dir.url.appendingPathComponent("stale"); try bytes(5_000, seed: 3).write(to: stale)481 try LandedPiece.land(stale, as: LandedPiece(path: "model.safetensors", offset: 2_000_000, status: 206), in: landed)482483 try await coordinator.start(DownloadPlan(card: Fixture.card()))484 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .completed)485 #expect(transport.pieceRequests.last?.offset == 1_000_000)486 #expect(server.requests(to: Self.weights).map(\.range) == ["bytes=1000000-"])487 #expect(try Data(contentsOf: store.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)488489 // A server that ignores the range sends the whole file: it replaces the partial instead of being appended to it.490 let other = TempDirectory()491 let ignoring = FakePieceTransport(server: server, mode: .ignoreRange)492 let otherStore = ModelStore(root: other.url.appendingPathComponent("Models"))493 let otherPartial = URL(fileURLWithPath: try otherStore.stagingFileURL(modelID: "tiny", path: "model.safetensors").path + ".partial")494 try FileManager.default.createDirectory(at: otherPartial.deletingLastPathComponent(), withIntermediateDirectories: true)495 try Fixture.contents[2].1.prefix(700_000).write(to: otherPartial)496 var config = DownloadCoordinator.Configuration(); config.retryDelay = { _ in 0 }; config.sleep = { _ in await Task.yield() }; config.freeSpace = { _ in 1 << 40 }497 let third = DownloadCoordinator(store: otherStore, transport: ignoring, configuration: config)498 try await third.start(DownloadPlan(card: Fixture.card()))499 #expect(await third.waitUntilSettled(id: "tiny")?.phase == .completed)500 #expect(try Data(contentsOf: otherStore.fileURL(modelID: "tiny", path: "model.safetensors")) == Fixture.contents[2].1)501 }502503 @Test func oversizeAndWrongPiecesNeverBecomeAModel() async throws {504 // A piece larger than the declared size is refused; a piece with wrong bytes fails the checksum; neither installs anything.505 var bigger = Fixture.contents; bigger[2].1 = bytes(3_400_000, seed: 3)506 Fixture.publish(server, base: Fixture.mirror, files: bigger)507 let transport = FakePieceTransport(server: server)508 let (coordinator, store) = pieceCoordinator(transport)509 var card = Fixture.card(); card.fallbackBaseURL = Fixture.mirror510 try await coordinator.start(DownloadPlan(card: card))511 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .failed(.oversize(file: "model.safetensors")))512 let modelFolder = try store.directory(for: "tiny")513 #expect(!store.isInstalled("tiny") && !exists(modelFolder))514 #expect(store.bytesOnDisk(id: "tiny") < 3_000_000)515516 var wrong = Fixture.contents; wrong[2].1 = bytes(3_000_000, seed: 5)517 Fixture.publish(server, base: Fixture.mirror, files: wrong)518 try await coordinator.retry(id: "tiny")519 #expect(await coordinator.waitUntilSettled(id: "tiny")?.phase == .failed(.hashMismatch(file: "model.safetensors")))520 #expect(!store.isInstalled("tiny"))521 }522523 @Test func fallsBackToStreamingWhenPiecesAreUnavailableOrSwitchedOff() async throws {524 Fixture.publish(server, base: Fixture.mirror)525 let unavailable = FakePieceTransport(server: server, mode: .unavailable)526 let (coordinator, store) = pieceCoordinator(unavailable)527 try await coordinator.start(DownloadPlan(card: Fixture.card()))528 let status = try #require(await coordinator.waitUntilSettled(id: "tiny"))529 #expect(status.phase == .completed && !status.usesBackgroundSession && status.retries == 0)530 #expect(unavailable.pieceRequests.count == 1) // asked once, then streamed everything531 #expect(store.isInstalled("tiny"))532533 let other = TempDirectory()534 let off = FakePieceTransport(server: server)535 var config = DownloadCoordinator.Configuration(); config.transferMode = .foregroundOnly; config.freeSpace = { _ in 1 << 40 }536 let foreground = DownloadCoordinator(store: ModelStore(root: other.url.appendingPathComponent("Models")), transport: off, configuration: config)537 try await foreground.start(DownloadPlan(card: Fixture.card()))538 #expect(await foreground.waitUntilSettled(id: "tiny")?.phase == .completed)539 #expect(off.pieceRequests.isEmpty)540 }541542 @Test func platformDefaultsAndBackgroundHook() {543 // On macOS (where these tests run) and in the simulator the streaming transport is the default; the background one is for iOS devices.544 #expect(!BackgroundDownloadTransport.isPreferredOnThisPlatform)545 let store = ModelStore(root: dir.url.appendingPathComponent("Models"))546 #expect(DownloadCoordinator.defaultTransport(store: store) is URLSessionDownloadTransport)547 #expect(DownloadCoordinator.defaultTransport(store: store, mode: .foregroundOnly) is URLSessionDownloadTransport)548 #expect(BackgroundDownloadTransport.defaultIdentifier.hasSuffix(".model-downloads"))549 // An identifier that is not ours is left to the caller, and its completion handler is not consumed.550 let handled = BackgroundDownloadTransport.handleEventsForBackgroundURLSession(identifier: "com.example.other", completionHandler: {})551 #expect(!handled)552 }553}554