Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook
Swift apple-silicongemmagemma4gemma4-26b-a4bgpgpullmllm-inferencelocal-aimacosmetalon-device-aion-device-llmswift
Add slim resumable model downloads (#14)
Andrey Mikhaylov489f2d1fbc87
diff --git a/AGENTS.md b/AGENTS.mdindex 8fb2187a..ad731719 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -16,6 +16,7 @@ Mac app.```bashswift run -c release TurboFieldfareRepack --output scratch/gemma4.gturbo+swift run -c release TurboFieldfareRepack --output scratch/gemma4.gturbo --resumeswift build -c release.build/release/TurboFieldfareMacswift run -c release TurboFieldfareCLI \@@ -24,7 +25,7 @@ swift run -c release TurboFieldfareCLI \--max-new 64```-The installer streams the pinned model without staging the full source checkpoint. Set `HF_TOKEN` only if requested. The download is about 15 GB.+The installer streams the pinned model without staging the full source checkpoint. Set `HF_TOKEN` only if requested. The download is about 15 GB. Cancellation preserves verified completed ranges; continue them with `--resume` or remove them with `--discard-partial --output scratch/gemma4.gturbo`.## Local serverdiff --git a/README.md b/README.mdindex aba3277b..398ad5a7 100644--- a/README.md+++ b/README.md@@ -56,7 +56,7 @@ On the first run, Swift Package Manager downloads and builds the Swift packagesrequired by the tokenizer. The complete release build includes the foregroundMac app and its sibling decode-service executable.-When the app opens, choose **Install** and let TurboFieldfare fetch and repack+When the app opens, choose **Download** and let TurboFieldfare fetch and repackthe pinned model (about 15 GB). Once it is ready, choose **Load Model**, typeyour prompt, and press **Generate**.@@ -137,7 +137,7 @@ available. When launched from this checkout, the app stores the model in#### Install the modelOn first launch, the app checks the available storage and shows the download-and installed sizes. Choose **Install** to begin.+and installed sizes. Choose **Download** to begin.The installer never materializes the full source checkpoint. It streams therequired byte ranges from the pinned Hugging Face revision and repacks them@@ -176,6 +176,23 @@ swift run -c release TurboFieldfareRepack \--overwrite```+Continue a cancelled or interrupted download:++```bash+swift run -c release TurboFieldfareRepack \+ --output scratch/gemma4.gturbo \+ --overwrite \+ --resume+```++Remove saved download state:++```bash+swift run -c release TurboFieldfareRepack \+ --discard-partial \+ --output scratch/gemma4.gturbo+```+The runtime accepts only a completed `.gturbo` directory with a final`manifest.json`.diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swiftindex 1ecf0a33..35755de2 100644--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallState.swift@@ -1,4 +1,5 @@import Foundation+import TurboFieldfareRepackCorepublic enum AppModelInstallState: Equatable, Sendable {case idle@@ -6,20 +7,26 @@ public enum AppModelInstallState: Equatable, Sendable {case downloadingMetadatacase planningcase reservingOutput- case copyingPayload(doneBytes: UInt64, totalBytes: UInt64)+ case copyingPayload(+ reusedBytes: UInt64,+ downloadedThisRunBytes: UInt64,+ totalBytes: UInt64+ )case hashingOutput(String)case finalizingcase cancelling+ case discardingcase cancelled+ case recoverable(String)case installed(modelDirectory: URL)case failed(String)public var isInstalling: Bool {switch self {case .checking, .downloadingMetadata, .planning, .reservingOutput,- .copyingPayload, .hashingOutput, .finalizing, .cancelling:+ .copyingPayload, .hashingOutput, .finalizing, .cancelling, .discarding:return true- case .idle, .cancelled, .installed, .failed:+ case .idle, .cancelled, .recoverable, .installed, .failed:return false}}@@ -29,7 +36,7 @@ public enum AppModelInstallState: Equatable, Sendable {case .checking, .downloadingMetadata, .planning, .reservingOutput,.copyingPayload, .hashingOutput, .finalizing:return true- case .idle, .cancelling, .cancelled, .installed, .failed:+ case .idle, .cancelling, .discarding, .cancelled, .recoverable, .installed, .failed:return false}}@@ -40,7 +47,11 @@ public enum AppModelInstallEvent: Equatable, Sendable {case downloadingMetadatacase planningcase reservingOutput- case copyingPayload(doneBytes: UInt64, totalBytes: UInt64)+ case copyingPayload(+ reusedBytes: UInt64,+ downloadedThisRunBytes: UInt64,+ totalBytes: UInt64+ )case hashingOutput(String)case finalizingcase installed(URL)diff --git a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swift b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swiftindex acec028a..c6ba6675 100644--- a/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swift+++ b/Sources/TurboFieldfareApp/Core/Installation/AppModelInstallerClient.swift@@ -4,5 +4,6 @@ public protocol AppModelInstallerClient: Sendable {var descriptor: AppModelInstallDescriptor { get }func checkInstallRequirement(outputDirectory: URL) throws -> AppModelInstallRequirementfunc installDefaultModel(outputDirectory: URL) -> AsyncThrowingStream<AppModelInstallEvent, Error>+ func discardPartialInstall(outputDirectory: URL) async throwsfunc cancel()}diff --git a/Sources/TurboFieldfareApp/Core/Installation/DownloadETAEstimator.swift b/Sources/TurboFieldfareApp/Core/Installation/DownloadETAEstimator.swiftnew file mode 100644index 00000000..388e48a6--- /dev/null+++ b/Sources/TurboFieldfareApp/Core/Installation/DownloadETAEstimator.swift@@ -0,0 +1,118 @@+import Foundation++public enum DownloadETAPresentation: Equatable, Sendable {+ case hidden+ case estimating+ case remaining(seconds: Double)+}++public struct DownloadETAObservation: Equatable, Sendable {+ public let reusedBytes: UInt64+ public let downloadedThisRunBytes: UInt64+ public let totalBytes: UInt64++ public init(reusedBytes: UInt64,+ downloadedThisRunBytes: UInt64,+ totalBytes: UInt64) {+ self.reusedBytes = reusedBytes+ self.downloadedThisRunBytes = downloadedThisRunBytes+ self.totalBytes = totalBytes+ }+}++public struct DownloadETAEstimator: Sendable {+ private static let warmupSeconds = 10.0+ private static let warmupBytes: UInt64 = 32 * 1024 * 1024+ private static let updateSeconds = 30.0++ private var startTime: Double?+ private var startBytes: UInt64 = 0+ private var previousBytes: UInt64?+ private var lastUpdateTime: Double?+ private var lastETA: Double?++ public init() {}++ public mutating func reset() {+ self = Self()+ }++ public mutating func update(+ _ observation: DownloadETAObservation,+ timestamp: Double+ ) -> DownloadETAPresentation {+ guard timestamp.isFinite else { return .hidden }+ let downloaded = observation.downloadedThisRunBytes+ if let previousBytes, downloaded < previousBytes {+ self = Self()+ }+ previousBytes = downloaded++ if startTime == nil {+ startTime = timestamp+ startBytes = downloaded+ return .estimating+ }+ let useful = downloaded - min(downloaded, startBytes)+ let elapsed = timestamp - (startTime ?? timestamp)+ guard elapsed >= Self.warmupSeconds,+ useful >= Self.warmupBytes else {+ return .estimating+ }++ if let lastUpdateTime,+ timestamp - lastUpdateTime < Self.updateSeconds,+ let lastETA {+ return .remaining(seconds: lastETA)+ }+ let rate = Double(useful) / elapsed+ let completed = min(+ observation.totalBytes,+ observation.reusedBytes.addingReportingOverflow(downloaded).overflow+ ? UInt64.max+ : observation.reusedBytes + downloaded)+ guard completed < observation.totalBytes, rate > 0 else {+ return .hidden+ }+ let estimate = Double(observation.totalBytes - completed) / rate+ guard estimate.isFinite, estimate >= 0 else { return .estimating }++ if let lastETA,+ abs(estimate - lastETA) <= max(60, lastETA * 0.2) {+ return .remaining(seconds: lastETA)+ }+ lastETA = estimate+ lastUpdateTime = timestamp+ return .remaining(seconds: estimate)+ }+}++public enum DownloadETAFormatter {+ public static func string(for presentation: DownloadETAPresentation) -> String? {+ switch presentation {+ case .hidden:+ return nil+ case .estimating:+ return "Estimating time remaining…"+ case .remaining(let seconds):+ return remainingString(seconds)+ }+ }++ public static func remainingString(_ seconds: Double) -> String {+ guard seconds.isFinite, seconds >= 0 else {+ return "Estimating time remaining…"+ }+ if seconds >= 24 * 60 * 60 {+ return "More than a day remaining"+ }+ if seconds < 60 {+ return "Less than a minute remaining"+ }+ if seconds < 60 * 60 {+ return "About \(Int((seconds / 60).rounded())) min remaining"+ }+ let hours = Int((seconds / 3600).rounded())+ return "About \(hours) hr remaining"+ }+}diff --git a/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swift b/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swiftindex 9a06369f..38008a77 100644--- a/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swift+++ b/Sources/TurboFieldfareApp/Core/Installation/RepackModelInstallerClient.swift@@ -7,6 +7,7 @@ public final class RepackModelInstallerClient: AppModelInstallerClient, SendableURL,@escaping @Sendable (ModelInstallProgress) -> Void) async throws -> URL+ typealias DiscardRunner = @Sendable (URL) async throws -> Voidprivate struct ActiveInstall: Sendable {let id: UUID@@ -19,33 +20,70 @@ public final class RepackModelInstallerClient: AppModelInstallerClient, Sendablepublic let descriptor: AppModelInstallDescriptorprivate let runInstall: InstallRunner+ private let runDiscard: DiscardRunnerprivate let taskState = InstallTaskState()public init(descriptor: AppModelInstallDescriptor = .default) {self.descriptor = descriptorself.runInstall = { outputDirectory, progress in- let options = SupportedModelSource.installOptions(- outputDirectory: outputDirectory,- overwrite: true,+ let paths = try RemoteInstallPaths(outputDirectory: outputDirectory.path)+ let resume = FileManager.default.fileExists(atPath: paths.checkpointFile)+ let options = RemoteStreamingRepackOptions(+ repoID: descriptor.repoID,+ revision: descriptor.revision,+ outputDir: outputDirectory.path,token: ProcessInfo.processInfo.environment["HF_TOKEN"],- retainPartialOnFailure: false)+ requireKnownSource: true,+ minFreeReserveBytes: descriptor.reserveBytes,+ overwrite: true,+ resume: resume)let result = try await RemoteStreamingRepacker(options: options).run(progress: progress)return URL(fileURLWithPath: result.outputDir).standardizedFileURL}+ self.runDiscard = { outputDirectory in+ try RemoteStreamingRepacker.discardPartial(+ outputDirectory: outputDirectory.path)+ }}init(descriptor: AppModelInstallDescriptor = .default,- runInstall: @escaping InstallRunner) {+ runInstall: @escaping InstallRunner,+ runDiscard: @escaping DiscardRunner = { _ in }) {self.descriptor = descriptorself.runInstall = runInstall+ self.runDiscard = runDiscard}public func checkInstallRequirement(outputDirectory: URL) throws -> AppModelInstallRequirement {+ let saved = try RemoteStreamingRepacker.inspectPersistentInstall(+ outputDirectory: outputDirectory.path,+ repoID: descriptor.repoID,+ requestedRevision: descriptor.revision)+ let remainingBytes: UInt64+ if let saved {+ let checkpointPath = try RemoteInstallPaths(+ outputDirectory: outputDirectory.path).checkpointFile+ let reused = try saved.validatedDestinationBytes(+ maximum: descriptor.installedBytes,+ path: checkpointPath)+ remainingBytes = descriptor.installedBytes > reused+ ? descriptor.installedBytes - reused+ : 0+ } else {+ remainingBytes = descriptor.installedBytes+ }+ let requested = remainingBytes.addingReportingOverflow(+ descriptor.rangeStagingBytes)+ guard !requested.overflow else {+ throw RepackError.configurationInvalid(+ detail: "model install requirement overflows UInt64")+ }let requirement = try DiskSpaceChecker.assess(path: outputDirectory.path,- bytes: descriptor.installedBytes + descriptor.rangeStagingBytes,+ bytes: requested.partialValue,reserveBytes: descriptor.reserveBytes)- return AppModelInstallRequirement(requiredBytes: requirement.requiredBytes,+ return AppModelInstallRequirement(probePath: requirement.path,+ requiredBytes: requirement.requiredBytes,availableBytes: requirement.availableBytes)}@@ -94,6 +132,13 @@ public final class RepackModelInstallerClient: AppModelInstallerClient, Sendabletask?.cancel()}+ public func discardPartialInstall(outputDirectory: URL) async throws {+ let directory = outputDirectory.standardizedFileURL+ try await Task.detached(priority: .utility) { [runDiscard] in+ try await runDiscard(directory)+ }.value+ }+static func event(for progress: ModelInstallProgress) -> AppModelInstallEvent {switch progress {case .downloadingMetadata:@@ -104,8 +149,11 @@ public final class RepackModelInstallerClient: AppModelInstallerClient, Sendablereturn .checkingcase .reservingOutput:return .reservingOutput- case .copyingPayload(let downloaded, let total):- return .copyingPayload(doneBytes: downloaded, totalBytes: total)+ case .copyingPayload(let reused, let downloadedThisRun, let total):+ return .copyingPayload(+ reusedBytes: reused,+ downloadedThisRunBytes: downloadedThisRun,+ totalBytes: total)case .hashingOutput(let file):return .hashingOutput(file)case .finalizing:diff --git a/Sources/TurboFieldfareApp/Core/State/AppModel.swift b/Sources/TurboFieldfareApp/Core/State/AppModel.swiftindex f3fbf4c0..29f6a2cf 100644--- a/Sources/TurboFieldfareApp/Core/State/AppModel.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppModel.swift@@ -26,6 +26,8 @@ public final class AppModel {public var diagnostics: AppDiagnostics?public var error: AppInferenceError?public var installState: AppModelInstallState = .idle+ public private(set) var installETAPresentation: DownloadETAPresentation = .hidden+ public private(set) var installETAText: String?public private(set) var installReadiness: AppModelInstallReadiness = .checkingpublic private(set) var installationStatus: AppModelInstallationStatus@@ -53,6 +55,9 @@ public final class AppModel {private var hasHandledTerminalEvent = falseprivate let memorySampler: AppMemorySamplerprivate let settingsPersistenceEnabled: Bool+ private let installETAClock: SuspendingClock+ private let installETAOrigin: SuspendingClock.Instant+ private var installETAEstimator = DownloadETAEstimator()public init(modelDirectory: URL? = nil,client: any AppInferenceClient = RealInferenceClient(),@@ -60,6 +65,7 @@ public final class AppModel {memorySampler: AppMemorySampler = AppMemorySampler(),settingsPersistenceEnabled: Bool = false) {let directory = (modelDirectory ?? AppModelLocation.defaultURL()).standardizedFileURL+ let installETAClock = SuspendingClock()let settings = settingsPersistenceEnabled? MacAppSettingsFileStore.loadOrCreate(forModelDirectory: directory): MacAppSettings()@@ -78,6 +84,8 @@ public final class AppModel {self.installer = installerself.memorySampler = memorySamplerself.settingsPersistenceEnabled = settingsPersistenceEnabled+ self.installETAClock = installETAClock+ self.installETAOrigin = installETAClock.nowrefreshInstallReadiness()}@@ -128,19 +136,41 @@ public final class AppModel {public var canCancelInstall: Bool { installState.canCancel }public var installDownloadedBytes: UInt64? {- guard case .copyingPayload(let done, _) = installState else { return nil }- return done+ guard case .copyingPayload(let reused, let downloaded, let total) = installState else {+ return nil+ }+ let addition = reused.addingReportingOverflow(downloaded)+ return min(addition.overflow ? UInt64.max : addition.partialValue, total)}public var installTotalBytes: UInt64? {- guard case .copyingPayload(_, let total) = installState else { return nil }+ guard case .copyingPayload(_, _, let total) = installState else {+ return nil+ }return total}+ public var installReusedBytes: UInt64? {+ guard case .copyingPayload(let reused, _, _) = installState else {+ return nil+ }+ return reused+ }++ public var installDownloadedThisRunBytes: UInt64? {+ guard case .copyingPayload(_, let downloaded, _) = installState else {+ return nil+ }+ return downloaded+ }+public var installProgressFraction: Double? {- guard case .copyingPayload(let done, let total) = installState, total > 0 else {+ guard case .copyingPayload(let reused, let downloaded, let total) = installState,+ total > 0 else {return nil}+ let addition = reused.addingReportingOverflow(downloaded)+ let done = addition.overflow ? UInt64.max : addition.partialValuereturn min(max(Double(done) / Double(total), 0), 1)}@@ -155,7 +185,9 @@ public final class AppModel {case .hashingOutput(let file): return "Verifying \(file)"case .finalizing: return "Finalizing installation"case .cancelling: return "Cancelling"- case .cancelled: return "Installation cancelled"+ case .discarding: return "Discarding download"+ case .cancelled: return "Download paused"+ case .recoverable: return "Saved download needs attention"case .installed: return "Model installed"case .failed: return "Installation failed"}@@ -249,6 +281,7 @@ public final class AppModel {installTask?.cancel()installer.cancel()installTask = nil+ resetInstallETA()installState = .idlependingExplicitLoadRuntimeKey = nilactiveRunRuntimeKey = nil@@ -377,6 +410,7 @@ public final class AppModel {guard canInstallModel else { return }installTask?.cancel()installer.cancel()+ resetInstallETA()let outputDirectory = URL(fileURLWithPath: modelPathText)installGeneration &+= 1let generation = installGeneration@@ -400,7 +434,38 @@ public final class AppModel {guard canCancelInstall else { return }installState = .cancellinginstaller.cancel()- installTask?.cancel()+ }++ public var hasPartialModelDownload: Bool {+ guard let paths = try? RemoteInstallPaths(outputDirectory: modelPathText) else {+ return false+ }+ return FileManager.default.fileExists(atPath: paths.partialDirectory)+ || FileManager.default.fileExists(atPath: paths.checkpointFile)+ }++ public var canDiscardModelDownload: Bool {+ hasPartialModelDownload && !isInstallingModel && !isRunning+ }++ public func discardModelDownload() {+ guard canDiscardModelDownload else { return }+ let outputDirectory = URL(fileURLWithPath: modelPathText)+ installGeneration &+= 1+ let generation = installGeneration+ installState = .discarding+ installTask = Task { [weak self, installer] in+ do {+ try await installer.discardPartialInstall(+ outputDirectory: outputDirectory)+ guard let self, generation == self.installGeneration else { return }+ self.installTask = nil+ self.installState = .idle+ self.refreshInstallReadiness()+ } catch {+ self?.finishInstallFailure(error, generation: generation)+ }+ }}public func refreshInstallReadiness() {@@ -436,20 +501,34 @@ public final class AppModel {guard generation == installGeneration else { return }switch event {case .checking:+ resetInstallETA()installState = .checkingcase .downloadingMetadata:+ resetInstallETA()installState = .downloadingMetadatacase .planning:+ resetInstallETA()installState = .planningcase .reservingOutput:+ resetInstallETA()installState = .reservingOutput- case .copyingPayload(let done, let total):- installState = .copyingPayload(doneBytes: done, totalBytes: total)+ case .copyingPayload(let reused, let downloadedThisRun, let total):+ installState = .copyingPayload(+ reusedBytes: reused,+ downloadedThisRunBytes: downloadedThisRun,+ totalBytes: total)+ updateInstallETA(+ reusedBytes: reused,+ downloadedThisRunBytes: downloadedThisRun,+ totalBytes: total)case .hashingOutput(let file):+ resetInstallETA()installState = .hashingOutput(file)case .finalizing:+ resetInstallETA()installState = .finalizingcase .installed(let directory):+ resetInstallETA()let directory = directory.standardizedFileURLinstallationStatus = AppModelInstallationProbe.status(at: directory,@@ -482,9 +561,43 @@ public final class AppModel {guard generation == installGeneration else { return }installTask = nilinstallState = .cancelled+ resetInstallETA()refreshInstallReadiness()}+ private func updateInstallETA(+ reusedBytes: UInt64,+ downloadedThisRunBytes: UInt64,+ totalBytes: UInt64+ ) {+ let observation = DownloadETAObservation(+ reusedBytes: reusedBytes,+ downloadedThisRunBytes: downloadedThisRunBytes,+ totalBytes: totalBytes)+ let timestamp = installETATimestamp+ setInstallETAPresentation(+ installETAEstimator.update(observation, timestamp: timestamp))+ }++ private var installETATimestamp: Double {+ let components = installETAOrigin.duration(to: installETAClock.now).components+ return Double(components.seconds)+ + Double(components.attoseconds) / 1_000_000_000_000_000_000+ }++ private func resetInstallETA() {+ installETAEstimator.reset()+ installETAPresentation = .hidden+ installETAText = nil+ }++ private func setInstallETAPresentation(+ _ presentation: DownloadETAPresentation+ ) {+ installETAPresentation = presentation+ installETAText = DownloadETAFormatter.string(for: presentation)+ }+private func applyPersistedSettings(forModelDirectory modelDirectory: URL) {guard settingsPersistenceEnabled else { return }let settings = MacAppSettingsFileStore.loadOrCreate(@@ -520,7 +633,9 @@ public final class AppModel {private func finishInstallFailure(_ error: Error, generation: UInt64) {guard generation == installGeneration else { return }installTask = nil- installState = .failed("\(error)")+ resetInstallETA()+ let hasSavedDownload = hasPartialModelDownload+ installState = hasSavedDownload ? .recoverable("\(error)") : .failed("\(error)")if let repackError = error as? RepackError,case .diskSpaceInsufficient(let path, let required, let available) = repackError {let requirement = AppModelInstallRequirement(probePath: path,@@ -529,6 +644,9 @@ public final class AppModel {installReadiness = .insufficientSpace(requirement)} else {refreshInstallReadiness()+ if hasSavedDownload {+ installState = .recoverable("\(error)")+ }}}diff --git a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swiftindex a6071d08..c518ee7d 100644--- a/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift+++ b/Sources/TurboFieldfareApp/Core/State/AppPresentationState.swift@@ -84,18 +84,26 @@ public struct AppPresentationState: Equatable, Sendable {return Self(label: "Cancelling installation",severity: .active, showsActivity: true)}+ if case .discarding = snapshot.installState {+ return Self(label: "Discarding download",+ severity: .active, showsActivity: true)+ }return Self(label: installLabel(snapshot.installState),severity: .active, showsActivity: true,primaryAction: snapshot.installState.canCancel ? .cancelInstall : nil)}if snapshot.requiresInstallation {+ if case .recoverable(let message) = snapshot.installState {+ return Self(label: "Saved download needs attention", detail: message,+ severity: .warning)+ }if case .failed(let message) = snapshot.installState {return Self(label: "Installation failed", detail: message,severity: .error, primaryAction: .install)}if case .cancelled = snapshot.installState {- return Self(label: "Installation cancelled", severity: .warning,+ return Self(label: "Download paused", severity: .warning,primaryAction: .install)}if case .failed(let message) = snapshot.installReadiness {@@ -176,7 +184,8 @@ public struct AppPresentationState: Equatable, Sendable {case .hashingOutput(let file): return "Verifying \(file)"case .finalizing: return "Finalizing installation"case .cancelling: return "Cancelling installation"- case .idle, .cancelled, .installed, .failed:+ case .discarding: return "Discarding download"+ case .idle, .cancelled, .recoverable, .installed, .failed:return "Model required"}}diff --git a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swiftindex bef34e91..97f5ca39 100644--- a/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift+++ b/Sources/TurboFieldfareApp/Mac/Installation/ModelInstallView.swift@@ -4,6 +4,7 @@ import SwiftUIstruct ModelInstallView: View {let model: AppModel+ @State private var showingDiscardConfirmation = falsevar body: some View {ScrollView {@@ -18,6 +19,18 @@ struct ModelInstallView: View {.padding(.vertical, 48).frame(maxWidth: .infinity)}+ .confirmationDialog(+ "Discard the saved model download?",+ isPresented: $showingDiscardConfirmation,+ titleVisibility: .visible+ ) {+ Button("Discard Download", role: .destructive) {+ model.discardModelDownload()+ }+ Button("Keep Download", role: .cancel) {}+ } message: {+ Text("Downloaded ranges will be removed. The installed model, if any, is preserved.")+ }}private var identity: some View {@@ -94,13 +107,13 @@ struct ModelInstallView: View {@ViewBuilderprivate var progressArea: some View {if model.isInstallingModel {- VStack(spacing: 10) {+ VStack(alignment: .leading, spacing: 8) {if let fraction = model.installProgressFraction,let downloaded = model.installDownloadedBytes,let total = model.installTotalBytes {ProgressView(value: fraction).accessibilityLabel("Model download")- .accessibilityValue(Text(MetricFormat.percent(fraction * 100)))+ .accessibilityValue(Text(accessibleProgressValue(fraction: fraction)))HStack {Text("Downloaded \(MetricFormat.storage(downloaded)) of \(MetricFormat.storage(total))")Spacer()@@ -108,6 +121,19 @@ struct ModelInstallView: View {}.font(.caption.monospacedDigit()).foregroundStyle(.secondary)+ HStack(alignment: .firstTextBaseline, spacing: 16) {+ if let reused = model.installReusedBytes, reused > 0 {+ Text("Reused \(MetricFormat.storage(reused)) from the saved download")+ .font(.caption)+ }+ Spacer(minLength: 16)+ if let eta = model.installETAText {+ Text(eta)+ .font(.caption.monospacedDigit())+ }+ }+ .foregroundStyle(.secondary)+ .frame(maxWidth: .infinity)} else {Text(model.presentation.label).font(.callout)@@ -116,13 +142,18 @@ struct ModelInstallView: View {}.frame(maxWidth: .infinity)} else if case .cancelled = model.installState {- Label("Installation cancelled", systemImage: "xmark.circle")+ Label("Download paused", systemImage: "pause.circle").foregroundStyle(.secondary)} else if case .failed(let message) = model.installState {Label(message, systemImage: "exclamationmark.triangle.fill").font(.callout).foregroundStyle(.red).multilineTextAlignment(.center)+ } else if case .recoverable(let message) = model.installState {+ Label(message, systemImage: "exclamationmark.triangle")+ .font(.callout)+ .foregroundStyle(.orange)+ .multilineTextAlignment(.center)}}@@ -134,11 +165,20 @@ struct ModelInstallView: View {.keyboardShortcut(.cancelAction).disabled(!model.canCancelInstall)} else {+ if model.hasPartialModelDownload {+ Button("Discard Download", role: .destructive) {+ showingDiscardConfirmation = true+ }+ .buttonStyle(.bordered)+ .disabled(!model.canDiscardModelDownload)+ }+Button("Check Again", action: model.recheckModelAtCurrentLocation).buttonStyle(.bordered).disabled(model.isInstallingModel)- Button("Install", action: model.installModel)+ Button(model.hasPartialModelDownload ? "Resume" : "Download",+ action: model.installModel).buttonStyle(.borderedProminent).disabled(!model.canInstallModel)}@@ -156,6 +196,12 @@ struct ModelInstallView: View {return "Checking available space"}}++ private func accessibleProgressValue(fraction: Double) -> String {+ let percent = MetricFormat.percent(fraction * 100)+ guard let eta = model.installETAText else { return percent }+ return "\(percent), \(eta)"+ }}private struct StorageRow: View {diff --git a/Sources/TurboFieldfareRepack/Command/main.swift b/Sources/TurboFieldfareRepack/Command/main.swiftindex 836fe808..ccf5ad6f 100644--- a/Sources/TurboFieldfareRepack/Command/main.swift+++ b/Sources/TurboFieldfareRepack/Command/main.swift@@ -3,18 +3,22 @@ import TurboFieldfareRepackCoreprivate let usage = """Usage:- TurboFieldfareRepack --output <model.gturbo> [--overwrite]+ TurboFieldfareRepack --output <model.gturbo> [--overwrite] [--resume]+ TurboFieldfareRepack --discard-partial --output <model.gturbo>TurboFieldfareRepack --verify-install --input-gturbo <model.gturbo>TurboFieldfareRepack --helpThe installer streams the supported Gemma 4 checkpoint from Hugging Face andrepackages it without materializing the source checkpoint on disk. Set HF_TOKEN-only if Hugging Face requests authentication.+only if Hugging Face requests authentication. A cancelled or interrupted+download can be continued with --resume or removed with --discard-partial."""private struct Arguments {var output: String?var overwrite = false+ var resume = false+ var discardPartial = falsevar verifyInstall = falsevar inputGTurbo: String?@@ -29,6 +33,12 @@ private struct Arguments {case "--overwrite":parsed.overwrite = trueindex += 1+ case "--resume":+ parsed.resume = true+ index += 1+ case "--discard-partial":+ parsed.discardPartial = true+ index += 1case "--verify-install":parsed.verifyInstall = trueindex += 1@@ -47,11 +57,23 @@ private struct Arguments {}}+ guard !(parsed.resume && parsed.discardPartial) else {+ throw ParseError.invalidMode("--resume and --discard-partial are mutually exclusive")+ }+ if parsed.discardPartial {+ guard parsed.output != nil else {+ throw ParseError.missingRequired("--output")+ }+ guard parsed.inputGTurbo == nil, !parsed.overwrite, !parsed.verifyInstall else {+ throw ParseError.invalidMode("--discard-partial only accepts --output")+ }+ return parsed+ }if parsed.verifyInstall {guard parsed.inputGTurbo != nil else {throw ParseError.missingRequired("--input-gturbo")}- guard parsed.output == nil, !parsed.overwrite else {+ guard parsed.output == nil, !parsed.overwrite, !parsed.resume else {throw ParseError.invalidMode("verification accepts only --input-gturbo")}} else {@@ -100,6 +122,17 @@ private func run(_ values: [String]) async -> Int32 {return 2}+ if arguments.discardPartial, let output = arguments.output {+ do {+ try RemoteStreamingRepacker.discardPartial(outputDirectory: output)+ print("Discarded saved download for \(output)")+ return 0+ } catch {+ printError("discard failed: \(error)")+ return 1+ }+ }+if arguments.verifyInstall, let input = arguments.inputGTurbo {do {let result = try VerifiedInstallTool.run(@@ -117,7 +150,8 @@ private func run(_ values: [String]) async -> Int32 {let options = SupportedModelSource.installOptions(outputDirectory: URL(fileURLWithPath: output),overwrite: arguments.overwrite,- token: ProcessInfo.processInfo.environment["HF_TOKEN"])+ token: ProcessInfo.processInfo.environment["HF_TOKEN"],+ resume: arguments.resume)do {let result = try await RemoteStreamingRepacker(options: options).run()print("Installed \(SupportedModelSource.displayName)")diff --git a/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift b/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swiftindex 65db0fde..391e693d 100644--- a/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift+++ b/Sources/TurboFieldfareRepack/Core/Planning/RangeCopyPlanner.swift@@ -1,13 +1,13 @@import Foundation-struct RangeCopy: Sendable, Equatable {- let shardID: String- let sourceOffset: UInt64- let size: UInt64- let destinationPath: String- let destinationOffset: UInt64-- init(shardID: String,+public struct RangeCopy: Sendable, Equatable {+ public let shardID: String+ public let sourceOffset: UInt64+ public let size: UInt64+ public let destinationPath: String+ public let destinationOffset: UInt64++ public init(shardID: String,sourceOffset: UInt64,size: UInt64,destinationPath: String,@@ -20,21 +20,34 @@ struct RangeCopy: Sendable, Equatable {}}-struct CoalescedRangeCopy: Sendable, Equatable {- let shardID: String- let sourceOffset: UInt64- let size: UInt64- let destinations: [RangeCopy]+public struct CoalescedRangeCopy: Sendable, Equatable {+ public let id: String+ public let shardID: String+ public let sourceOffset: UInt64+ public let size: UInt64+ public let destinations: [RangeCopy]+}++public struct RemoteExpectedOutput: Codable, Sendable, Equatable {+ public let relativePath: String+ public let size: UInt64}-struct RangeCopyPlan: Sendable {- let coalescedCopies: [CoalescedRangeCopy]- let remoteBytesToDownload: UInt64+public struct RangeCopyPlan: Sendable {+ public let scalarCopies: [RangeCopy]+ public let coalescedCopies: [CoalescedRangeCopy]+ public let remoteBytesToDownload: UInt64+ public let remoteGapBytesDownloaded: UInt64+ public let canonicalFingerprint: String+ public let residentIndexSha256: String+ public let expectedOutputs: [RemoteExpectedOutput]}-enum RangeCopyPlanner {+public enum RangeCopyPlanner {static func plan(repackPlan: RepackPlan,- rangeChunkBytes: Int) throws -> RangeCopyPlan {+ rangeChunkBytes: Int,+ layoutMode: String = "identity",+ layoutOrderSha256: String? = nil) throws -> RangeCopyPlan {var copies: [RangeCopy] = []copies.reserveCapacity(repackPlan.resident.entries.count * 3)@@ -42,7 +55,7 @@ enum RangeCopyPlanner {copies.append(RangeCopy(shardID: entry.sourceWeight.shardPath,sourceOffset: entry.sourceWeight.absoluteOffset,size: entry.sizeBytes,- destinationPath: repackPlan.resident.path,+ destinationPath: entry.fileOffsetPath(in: repackPlan.resident),destinationOffset: entry.fileOffset))if let scales = entry.sourceScales {copies.append(RangeCopy(shardID: scales.shardPath,@@ -62,7 +75,7 @@ enum RangeCopyPlanner {for layer in repackPlan.layers where layer.expertsPerLayer > 0 {for expert in 0..<layer.expertsPerLayer {- let blobBase = UInt64(expert) * layer.expertStride+ let blobBase = UInt64(layer.physicalRank(for: expert)) * layer.expertStridefor slice in layer.subTensors {copies.append(RangeCopy(shardID: slice.sourceTensor.shardPath,@@ -75,13 +88,31 @@ enum RangeCopyPlanner {}}+ try validateDestinationIntervals(copies, outputRoot: outputRoot(for: repackPlan))let coalesced = try coalesce(copies: copies, rangeChunkBytes: rangeChunkBytes)+ let indexData = try ResidentWriter.encodeIndex(plan: repackPlan.resident)+ let indexSha = hashData(indexData)+ let expectedOutputs = expectedOutputList(for: repackPlan)+ let fingerprint = try canonicalFingerprint(+ copies: coalesced,+ outputRoot: outputRoot(for: repackPlan),+ rangeChunkBytes: rangeChunkBytes,+ layoutMode: layoutMode,+ layoutOrderSha256: layoutOrderSha256,+ residentIndexSha256: indexSha,+ expectedOutputs: expectedOutputs)let downloaded = coalesced.reduce(UInt64(0)) { $0 + $1.size }- return RangeCopyPlan(coalescedCopies: coalesced,- remoteBytesToDownload: downloaded)+ let copied = copies.reduce(UInt64(0)) { $0 + $1.size }+ return RangeCopyPlan(scalarCopies: copies,+ coalescedCopies: coalesced,+ remoteBytesToDownload: downloaded,+ remoteGapBytesDownloaded: downloaded - copied,+ canonicalFingerprint: fingerprint,+ residentIndexSha256: indexSha,+ expectedOutputs: expectedOutputs)}- static func coalesce(copies: [RangeCopy],+ public static func coalesce(copies: [RangeCopy],rangeChunkBytes: Int) throws -> [CoalescedRangeCopy] {guard rangeChunkBytes > 0 else {throw RepackError.configurationInvalid(detail: "rangeChunkBytes must be positive")@@ -98,7 +129,8 @@ enum RangeCopyPlanner {func flush() {guard let shard = currentShard else { return }- out.append(CoalescedRangeCopy(shardID: shard,+ out.append(CoalescedRangeCopy(id: "",+ shardID: shard,sourceOffset: currentStart,size: currentEnd - currentStart,destinations: currentDestinations))@@ -130,7 +162,14 @@ enum RangeCopyPlanner {}}flush()- return out+ return out.enumerated().map { index, copy in+ CoalescedRangeCopy(+ id: String(format: "range-%08d", index),+ shardID: copy.shardID,+ sourceOffset: copy.sourceOffset,+ size: copy.size,+ destinations: copy.destinations.sorted(by: destinationOrder))+ }}private static func splitLargeCopies(_ copies: [RangeCopy],@@ -155,4 +194,152 @@ enum RangeCopyPlanner {}return out}++ private static func outputRoot(for plan: RepackPlan) -> String {+ (plan.resident.path as NSString).deletingLastPathComponent+ }++ private static func expectedOutputList(for plan: RepackPlan) -> [RemoteExpectedOutput] {+ var outputs = [+ RemoteExpectedOutput(relativePath: "model_weights.bin",+ size: plan.resident.totalSize)+ ]+ outputs.append(contentsOf: plan.layers+ .filter { $0.expertsPerLayer > 0 }+ .map {+ RemoteExpectedOutput(+ relativePath: "packed_experts/" + ($0.path as NSString).lastPathComponent,+ size: $0.fileSize)+ })+ return outputs.sorted { $0.relativePath < $1.relativePath }+ }++ static func validateDestinationIntervals(_ copies: [RangeCopy],+ outputRoot: String) throws {+ let sorted = try copies.map { copy in+ (try normalizedRelativePath(copy.destinationPath, root: outputRoot), copy)+ }.sorted {+ if $0.0 != $1.0 { return $0.0 < $1.0 }+ return $0.1.destinationOffset < $1.1.destinationOffset+ }+ var previousPath: String?+ var previousEnd: UInt64 = 0+ for (path, copy) in sorted {+ guard copy.destinationOffset <= UInt64.max - copy.size else {+ throw RepackError.configurationInvalid(+ detail: "destination range overflows \(path)")+ }+ if previousPath == path, copy.destinationOffset < previousEnd {+ throw RepackError.configurationInvalid(+ detail: "overlapping destination ranges in \(path)")+ }+ previousPath = path+ previousEnd = copy.destinationOffset + copy.size+ }+ }++ static func canonicalFingerprint(+ copies: [CoalescedRangeCopy],+ outputRoot: String,+ rangeChunkBytes: Int,+ layoutMode: String,+ layoutOrderSha256: String?,+ residentIndexSha256: String,+ expectedOutputs: [RemoteExpectedOutput]+ ) throws -> String {+ var writer = FingerprintWriter(domain: "TurboFieldfare.RemoteInstallPlan.v1")+ writer.append(UInt64(GTurboJSON.versionMajor))+ writer.append(UInt64(GTurboJSON.versionMinor))+ writer.append(UInt64(rangeChunkBytes))+ writer.append(layoutMode)+ writer.append(layoutOrderSha256 ?? "")+ writer.append(residentIndexSha256)+ writer.append(UInt64(expectedOutputs.count))+ for output in expectedOutputs {+ writer.append(output.relativePath)+ writer.append(output.size)+ }+ writer.append(UInt64(copies.count))+ for copy in copies {+ writer.append(copy.id)+ writer.append(copy.shardID.precomposedStringWithCanonicalMapping)+ writer.append(copy.sourceOffset)+ writer.append(copy.size)+ writer.append(UInt64(copy.destinations.count))+ for destination in copy.destinations {+ writer.append(try normalizedRelativePath(+ destination.destinationPath,+ root: outputRoot))+ writer.append(destination.destinationOffset)+ writer.append(destination.sourceOffset - copy.sourceOffset)+ writer.append(destination.size)+ }+ }+ return writer.finalize()+ }++ static func normalizedRelativePath(_ path: String, root: String) throws -> String {+ let normalizedRoot = root.hasSuffix("/") ? String(root.dropLast()) : root+ let normalizedPath = path+ let prefix = normalizedRoot.hasSuffix("/") ? normalizedRoot : normalizedRoot + "/"+ guard normalizedPath.hasPrefix(prefix) else {+ throw RepackError.configurationInvalid(+ detail: "destination \(normalizedPath) is outside partial output \(normalizedRoot)")+ }+ let relative = String(normalizedPath.dropFirst(prefix.count))+ .precomposedStringWithCanonicalMapping+ let components = relative.split(separator: "/", omittingEmptySubsequences: false)+ guard !relative.isEmpty,+ !relative.hasPrefix("/"),+ components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else {+ throw RepackError.configurationInvalid(+ detail: "invalid relative destination path \(relative)")+ }+ return relative+ }++ private static func destinationOrder(_ lhs: RangeCopy, _ rhs: RangeCopy) -> Bool {+ if lhs.destinationPath != rhs.destinationPath {+ return lhs.destinationPath < rhs.destinationPath+ }+ if lhs.destinationOffset != rhs.destinationOffset {+ return lhs.destinationOffset < rhs.destinationOffset+ }+ return lhs.sourceOffset < rhs.sourceOffset+ }+}++private extension ResidentEntry {+ func fileOffsetPath(in plan: ResidentFilePlan) -> String {+ plan.path+ }+}++private struct FingerprintWriter {+ private var stream = Sha256Stream()++ init(domain: String) {+ append(domain)+ }++ mutating func append(_ value: UInt64) {+ var littleEndian = value.littleEndian+ withUnsafeBytes(of: &littleEndian) { stream.update($0) }+ }++ mutating func append(_ value: String) {+ let data = Data(value.utf8)+ append(UInt64(data.count))+ data.withUnsafeBytes { stream.update($0) }+ }++ func finalize() -> String {+ stream.finalizeHexString()+ }+}++private func hashData(_ data: Data) -> String {+ var stream = Sha256Stream()+ data.withUnsafeBytes { stream.update($0) }+ return stream.finalizeHexString()}diff --git a/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift b/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swiftindex 41aa86ac..3969a3cc 100644--- a/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift+++ b/Sources/TurboFieldfareRepack/Core/Planning/RepackPlanner.swift@@ -64,6 +64,10 @@ struct LayerFilePlan: Sendable {let subTensors: [PerExpertTensorSlice] // 9 entries: gate/up/down × {weights, scales, biases}var fileSize: UInt64 { UInt64(expertsPerLayer) * expertStride }+ func physicalRank(for logicalExpert: Int) -> Int {+ logicalExpert+ }+init(layerIndex: Int,path: String,expertsPerLayer: Int,@@ -85,6 +89,7 @@ struct RepackPlan: Sendable {let resident: ResidentFilePlanlet layers: [LayerFilePlan]let matchedModelID: String?+ let excludedMultimodalTensorNames: [String]}// MARK: - Planner@@ -151,8 +156,12 @@ enum RepackPlanner {let bitsOverrideCount = meta.bitsOverrides.countvar lmResidentBases: [String] = []+ var excludedMultimodalNames: [String] = []var routedByLayerAndRole: [Int: [String: String]] = [:]for (name, _) in registry {+ if isMultimodalTensorName(name) {+ excludedMultimodalNames.append(name)+ }if name.hasSuffix(".scales") || name.hasSuffix(".biases") { continue }let b = classify(name, numLayers: arch.numLayers)switch b {@@ -172,6 +181,7 @@ enum RepackPlanner {// Sort deterministically. The LM order follows a fixed template.lmResidentBases.sort(by: lmResidentOrdering())+ excludedMultimodalNames.sort()let residentPath = (outputDir as NSString).appendingPathComponent("model_weights.bin")let resident = try planResidentFile(path: residentPath,@@ -212,7 +222,8 @@ enum RepackPlanner {bitsOverrideCount: bitsOverrideCount,resident: resident,layers: layerPlans,- matchedModelID: matched)+ matchedModelID: matched,+ excludedMultimodalTensorNames: excludedMultimodalNames)}private static func isMultimodalTensorName(_ name: String) -> Bool {diff --git a/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swift b/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swiftindex ef59cb3f..26a6021c 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/HuggingFaceRemote.swift@@ -4,6 +4,8 @@ public struct RemoteFileInfo: Sendable, Hashable {public let filename: Stringpublic let resolvedCommit: Stringpublic let size: UInt64+ public let etag: String?+ public let xetHash: String?public let acceptsRanges: Bool}@@ -17,7 +19,7 @@ public struct HuggingFaceRemoteSource: Sendable {public let requestedRevision: Stringpublic let resolvedCommit: String?public let token: String?- public let session: URLSession+ public let downloadSession: RemoteDownloadSessionpublic let baseURL: URLpublic let tempDirectory: Stringpublic let retryPolicy: RemoteRetryPolicy@@ -26,7 +28,7 @@ public struct HuggingFaceRemoteSource: Sendable {requestedRevision: String,resolvedCommit: String? = nil,token: String? = nil,- session: URLSession = .shared,+ downloadSession: RemoteDownloadSession = RemoteDownloadSession(),baseURL: URL = URL(string: "https://huggingface.co")!,tempDirectory: String = NSTemporaryDirectory(),retryPolicy: RemoteRetryPolicy = RemoteRetryPolicy()) {@@ -34,7 +36,7 @@ public struct HuggingFaceRemoteSource: Sendable {self.requestedRevision = requestedRevisionself.resolvedCommit = resolvedCommitself.token = token- self.session = session+ self.downloadSession = downloadSessionself.baseURL = baseURLself.tempDirectory = tempDirectoryself.retryPolicy = retryPolicy@@ -45,7 +47,7 @@ public struct HuggingFaceRemoteSource: Sendable {requestedRevision: requestedRevision,resolvedCommit: commit,token: token,- session: session,+ downloadSession: downloadSession,baseURL: baseURL,tempDirectory: tempDirectory,retryPolicy: retryPolicy)@@ -70,6 +72,7 @@ public struct HuggingFaceRemoteSource: Sendable {public func resolveFileInfo(filename: String,audit: RepackAudit? = nil) async throws -> RemoteFileInfo {try await withRemoteRetries(retryPolicy,+ label: "resolveFileInfo:\(filename)",audit: audit) {try await resolveFileInfoOnce(filename: filename)}@@ -80,22 +83,29 @@ public struct HuggingFaceRemoteSource: Sendable {var request = URLRequest(url: url)request.httpMethod = "HEAD"applyHeaders(to: &request)- let (_, response) = try await session.data(for: request)+ let (_, response) = try await downloadSession.response(for: request)guard let http = response as? HTTPURLResponse else {throw RepackError.remoteProtocolInvalid(detail: "missing HTTP response for \(filename)")}guard (200..<400).contains(http.statusCode) else {- throw RepackError.remoteHTTPStatus(url: redact(url), status: http.statusCode)+ throw RepackError.remoteHTTPResponse(+ url: redactRemoteURL(url),+ status: http.statusCode,+ retryAfter: remoteHeader(http, "Retry-After"))}- let commit = header(http, "X-Repo-Commit") ?? resolvedCommit+ let commit = remoteHeader(http, "X-Repo-Commit") ?? resolvedCommitguard let commit, commit.count == 40 else {throw RepackError.remoteProtocolInvalid(detail: "missing full X-Repo-Commit for \(filename)")}let size = try remoteSize(http: http, filename: filename)+ let etag = remoteHeader(http, "X-Linked-ETag") ?? remoteHeader(http, "ETag")return RemoteFileInfo(filename: filename,resolvedCommit: commit,size: size,- acceptsRanges: (header(http, "Accept-Ranges") ?? "").lowercased().contains("bytes"))+ etag: etag,+ xetHash: remoteHeader(http, "X-Xet-Hash"),+ acceptsRanges: (remoteHeader(http, "Accept-Ranges") ?? "")+ .lowercased().contains("bytes"))}public func fetchSmallFile(filename: String,@@ -107,6 +117,7 @@ public struct HuggingFaceRemoteSource: Sendable {throw RepackError.remoteFileTooLarge(path: filename, size: info.size, cap: capBytes)}try await withRemoteRetries(retryPolicy,+ label: "fetchSmallFile:\(filename)",audit: audit) {let tmp = try await downloadRangeToTempFileOnce(filename: filename,info: info,@@ -114,10 +125,13 @@ public struct HuggingFaceRemoteSource: Sendable {length: Int(info.size))do {try Posix.mkdirP((outputPath as NSString).deletingLastPathComponent)- if FileManager.default.fileExists(atPath: outputPath) {- try FileManager.default.removeItem(atPath: outputPath)+ let kind = try Posix.entryKind(outputPath)+ guard kind == .absent || kind == .regular else {+ throw RepackError.installPathUnsafe(+ path: outputPath,+ detail: "metadata destination has the wrong entry type")}- try FileManager.default.moveItem(atPath: tmp.path, toPath: outputPath)+ try Posix.rename(from: tmp.path, to: outputPath)} catch {try? FileManager.default.removeItem(atPath: tmp.path)throw error@@ -129,28 +143,39 @@ public struct HuggingFaceRemoteSource: Sendable {info: RemoteFileInfo,offset: UInt64,length: Int,+ targetPath: String? = nil,+ progress: @escaping @Sendable (UInt64) -> Void = { _ in },audit: RepackAudit? = nil) async throws -> TemporaryRangeFile {try await withRemoteRetries(retryPolicy,+ label: "downloadRangeToTempFile:\(filename)",audit: audit) {- try await downloadRangeToTempFileOnce(filename: filename,- info: info,- offset: offset,- length: length)+ progress(0)+ return try await downloadRangeToTempFileOnce(+ filename: filename,+ info: info,+ offset: offset,+ length: length,+ targetPath: targetPath,+ progress: progress)}}private func downloadRangeToTempFileOnce(filename: String,info: RemoteFileInfo,offset: UInt64,- length: Int) async throws -> TemporaryRangeFile {+ length: Int,+ targetPath: String? = nil,+ progress: @escaping @Sendable (UInt64) -> Void = { _ in })+ async throws -> TemporaryRangeFile {guard length >= 0 else {throw RepackError.remoteProtocolInvalid(detail: "negative range length")}if length == 0 {- let path = (tempDirectory as NSString)+ let path = targetPath ?? (tempDirectory as NSString).appendingPathComponent("turbofieldfare-range-\(UUID().uuidString).tmp")FileManager.default.createFile(atPath: path, contents: Data())- return TemporaryRangeFile(path: path, byteCount: 0)+ return TemporaryRangeFile(path: path,+ byteCount: 0)}let end = offset + UInt64(length) - 1guard end < info.size else {@@ -162,40 +187,21 @@ public struct HuggingFaceRemoteSource: Sendable {request.setValue("bytes=\(offset)-\(end)", forHTTPHeaderField: "Range")request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")applyHeaders(to: &request)- let (downloadedURL, response) = try await session.download(for: request)- guard let http = response as? HTTPURLResponse else {- throw RepackError.remoteProtocolInvalid(detail: "missing HTTP response for range \(filename)")- }- guard http.statusCode == 206 else {- throw RepackError.remoteHTTPStatus(url: redact(url), status: http.statusCode)- }- try validateRangeResponse(http: http,- filename: filename,- offset: offset,- end: end,- total: info.size,- length: UInt64(length))-try Posix.mkdirP(tempDirectory)- let target = (tempDirectory as NSString)+ let target = targetPath ?? (tempDirectory as NSString).appendingPathComponent("turbofieldfare-range-\(UUID().uuidString).tmp")- if FileManager.default.fileExists(atPath: target) {- try FileManager.default.removeItem(atPath: target)- }- do {- try FileManager.default.moveItem(at: downloadedURL, to: URL(fileURLWithPath: target))- } catch {- try? FileManager.default.removeItem(at: downloadedURL)- throw error- }- let attrs = try FileManager.default.attributesOfItem(atPath: target)- let actual = (attrs[.size] as? NSNumber)?.uint64Value ?? 0- guard actual == UInt64(length) else {- try? FileManager.default.removeItem(atPath: target)- throw RepackError.remoteProtocolInvalid(detail:- "range \(filename) wrote \(actual), expected \(length)")- }- return TemporaryRangeFile(path: target, byteCount: actual)+ let result = try await downloadSession.transfer(+ request: request,+ targetPath: target,+ expectation: RemoteRangeExpectation(+ filename: filename,+ offset: offset,+ length: UInt64(length),+ totalSize: info.size,+ xetHash: info.xetHash),+ progress: progress)+ return TemporaryRangeFile(path: result.path,+ byteCount: result.byteCount)}private func applyHeaders(to request: inout URLRequest) {@@ -223,61 +229,14 @@ private func validateFilename(_ filename: String) throws {}}-private func header(_ response: HTTPURLResponse, _ name: String) -> String? {- for (k, v) in response.allHeaderFields {- if String(describing: k).caseInsensitiveCompare(name) == .orderedSame {- return String(describing: v)- }- }- return nil-}-private func remoteSize(http: HTTPURLResponse, filename: String) throws -> UInt64 {- if let linked = header(http, "X-Linked-Size"), let size = UInt64(linked) {+ if let linked = remoteHeader(http, "X-Linked-Size"), let size = UInt64(linked) {return size}- if let contentLength = header(http, "Content-Length"), let size = UInt64(contentLength) {+ if (200..<300).contains(http.statusCode),+ let contentLength = remoteHeader(http, "Content-Length"),+ let size = UInt64(contentLength) {return size}throw RepackError.remoteProtocolInvalid(detail: "missing remote size for \(filename)")}--private func validateRangeResponse(http: HTTPURLResponse,- filename: String,- offset: UInt64,- end: UInt64,- total: UInt64,- length: UInt64) throws {- guard (header(http, "Content-Encoding") ?? "identity").lowercased() == "identity" else {- throw RepackError.remoteProtocolInvalid(detail: "compressed range response for \(filename)")- }- guard let contentLength = header(http, "Content-Length"),- UInt64(contentLength) == length else {- throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Length for \(filename)")- }- guard let range = header(http, "Content-Range") else {- throw RepackError.remoteProtocolInvalid(detail: "missing Content-Range for \(filename)")- }- let prefix = "bytes "- guard range.hasPrefix(prefix) else {- throw RepackError.remoteProtocolInvalid(detail: "malformed Content-Range \(range)")- }- let rest = range.dropFirst(prefix.count)- let parts = rest.split(separator: "/", maxSplits: 1)- guard parts.count == 2,- UInt64(parts[1]) == total else {- throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Range total \(range)")- }- let bounds = parts[0].split(separator: "-", maxSplits: 1)- guard bounds.count == 2,- UInt64(bounds[0]) == offset,- UInt64(bounds[1]) == end else {- throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Range bounds \(range)")- }-}--private func redact(_ url: URL) -> String {- var components = URLComponents(url: url, resolvingAgainstBaseURL: false)- components?.query = nil- return components?.url?.absoluteString ?? url.absoluteString-}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swiftindex 457b467f..b071cf0c 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteChunkPolicy.swift@@ -2,4 +2,5 @@ import Foundationpublic enum RemoteChunkPolicy {public static let defaultBytes = 64 * 1024 * 1024+ public static let maxBytes = defaultBytes}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteDownloadSession.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteDownloadSession.swiftnew file mode 100644index 00000000..9da8e944--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteDownloadSession.swift@@ -0,0 +1,149 @@+import Foundation++public struct RemoteDownloadSessionPolicy: Sendable, Equatable {+ public var requestTimeoutSeconds: TimeInterval+ public var resourceTimeoutSeconds: TimeInterval+ public var waitsForConnectivity: Bool+ public var maximumConnectionsPerHost: Int+ public var maximumRedirects: Int++ public init(requestTimeoutSeconds: TimeInterval = 300,+ resourceTimeoutSeconds: TimeInterval = 7 * 24 * 60 * 60,+ waitsForConnectivity: Bool = true,+ maximumConnectionsPerHost: Int = 1,+ maximumRedirects: Int = 5) {+ self.requestTimeoutSeconds = requestTimeoutSeconds+ self.resourceTimeoutSeconds = resourceTimeoutSeconds+ self.waitsForConnectivity = waitsForConnectivity+ self.maximumConnectionsPerHost = maximumConnectionsPerHost+ self.maximumRedirects = maximumRedirects+ }+}++public final class RemoteDownloadSession: @unchecked Sendable {+ public let policy: RemoteDownloadSessionPolicy++ private let configuration: URLSessionConfiguration++ public init(policy: RemoteDownloadSessionPolicy = RemoteDownloadSessionPolicy(),+ protocolClasses: [AnyClass]? = nil) {+ self.policy = policy+ let configuration = URLSessionConfiguration.ephemeral+ configuration.timeoutIntervalForRequest = policy.requestTimeoutSeconds+ configuration.timeoutIntervalForResource = policy.resourceTimeoutSeconds+ configuration.waitsForConnectivity = policy.waitsForConnectivity+ configuration.httpMaximumConnectionsPerHost = policy.maximumConnectionsPerHost+ configuration.requestCachePolicy = .reloadIgnoringLocalCacheData+ configuration.urlCache = nil+ if let protocolClasses {+ configuration.protocolClasses = protocolClasses+ }+ self.configuration = configuration+ }++ public func response(for request: URLRequest) async throws -> (Data, URLResponse) {+ guard let configuration = configuration.copy() as? URLSessionConfiguration else {+ throw RepackError.configurationInvalid(detail:+ "could not copy remote metadata session configuration")+ }+ let delegate = MetadataRedirectDelegate(+ originalRequest: request,+ maximumRedirects: policy.maximumRedirects)+ let session = URLSession(configuration: configuration,+ delegate: delegate,+ delegateQueue: nil)+ defer { session.finishTasksAndInvalidate() }+ return try await session.data(for: request)+ }++ public func transfer(request: URLRequest,+ targetPath: String,+ expectation: RemoteRangeExpectation,+ progress: @escaping @Sendable (UInt64) -> Void = { _ in }) async throws+ -> RemoteRangeTransferResult {+ guard let configuration = configuration.copy() as? URLSessionConfiguration else {+ throw RepackError.configurationInvalid(detail:+ "could not copy remote download session configuration")+ }+ return try await RemoteRangeTransfer.run(+ configuration: configuration,+ request: request,+ targetPath: targetPath,+ expectation: expectation,+ maximumRedirects: policy.maximumRedirects,+ progress: progress)+ }++ var configurationSnapshot: RemoteDownloadSessionConfigurationSnapshot {+ RemoteDownloadSessionConfigurationSnapshot(+ requestTimeoutSeconds: configuration.timeoutIntervalForRequest,+ resourceTimeoutSeconds: configuration.timeoutIntervalForResource,+ waitsForConnectivity: configuration.waitsForConnectivity,+ maximumConnectionsPerHost: configuration.httpMaximumConnectionsPerHost,+ requestCachePolicy: configuration.requestCachePolicy,+ hasURLCache: configuration.urlCache != nil)+ }+}++struct RemoteDownloadSessionConfigurationSnapshot: Equatable {+ let requestTimeoutSeconds: TimeInterval+ let resourceTimeoutSeconds: TimeInterval+ let waitsForConnectivity: Bool+ let maximumConnectionsPerHost: Int+ let requestCachePolicy: URLRequest.CachePolicy+ let hasURLCache: Bool+}++private final class MetadataRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {+ private let lock = NSLock()+ private var policy: RemoteMetadataRedirectPolicy++ init(originalRequest: URLRequest, maximumRedirects: Int) {+ self.policy = RemoteMetadataRedirectPolicy(+ originalRequest: originalRequest,+ maximumRedirects: maximumRedirects)+ }++ func urlSession(_ session: URLSession,+ task: URLSessionTask,+ willPerformHTTPRedirection response: HTTPURLResponse,+ newRequest request: URLRequest,+ completionHandler: @escaping (URLRequest?) -> Void) {+ lock.lock()+ let redirected = policy.request(proposedRequest: request)+ lock.unlock()+ completionHandler(redirected)+ }+}++struct RemoteMetadataRedirectPolicy {+ private let sourceHost: String?+ private let originalMethod: String?+ private let originalAuthorization: String?+ private let maximumRedirects: Int+ private var redirectCount = 0++ init(originalRequest: URLRequest, maximumRedirects: Int) {+ self.sourceHost = originalRequest.url?.host?.lowercased()+ self.originalMethod = originalRequest.httpMethod+ self.originalAuthorization = originalRequest.value(+ forHTTPHeaderField: "Authorization")+ self.maximumRedirects = maximumRedirects+ }++ mutating func request(proposedRequest: URLRequest) -> URLRequest? {+ redirectCount += 1+ guard redirectCount <= maximumRedirects,+ proposedRequest.url?.scheme?.lowercased() == "https",+ proposedRequest.url?.host?.lowercased() == sourceHost else {+ return nil+ }+ var redirected = proposedRequest+ redirected.httpMethod = originalMethod+ redirected.setValue("identity", forHTTPHeaderField: "Accept-Encoding")+ redirected.setValue(+ originalAuthorization,+ forHTTPHeaderField: "Authorization")+ return redirected+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteInstallCheckpoint.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteInstallCheckpoint.swiftnew file mode 100644index 00000000..54a07592--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteInstallCheckpoint.swift@@ -0,0 +1,132 @@+import Foundation++public struct RemoteCompletedRange: Codable, Sendable, Equatable {+ public let id: String+ public let destinationDigest: String+ public let sourceBytes: UInt64+ public let destinationBytes: UInt64+}++public struct RemoteInstallCheckpoint: Codable, Sendable, Equatable {+ public static let schemaVersion = 1+ public static let maximumBytes: UInt64 = 8 * 1024 * 1024++ public let schema: Int+ public let repoID: String+ public let requestedRevision: String+ public let resolvedCommit: String+ public let sourceIndexSHA256: String+ public let planFingerprint: String+ public let totalSourceBytes: UInt64+ public var completedRanges: [RemoteCompletedRange]++ public init(repoID: String,+ requestedRevision: String,+ resolvedCommit: String,+ sourceIndexSHA256: String,+ planFingerprint: String,+ totalSourceBytes: UInt64,+ completedRanges: [RemoteCompletedRange] = []) {+ self.schema = Self.schemaVersion+ self.repoID = repoID+ self.requestedRevision = requestedRevision+ self.resolvedCommit = resolvedCommit+ self.sourceIndexSHA256 = sourceIndexSHA256+ self.planFingerprint = planFingerprint+ self.totalSourceBytes = totalSourceBytes+ self.completedRanges = completedRanges+ }++ public static func load(from path: String) throws -> Self {+ let data = try Posix.readBoundedData(path, maximumBytes: maximumBytes)+ do {+ let checkpoint = try JSONDecoder().decode(Self.self, from: data)+ try checkpoint.validate(path: path)+ return checkpoint+ } catch let error as RepackError {+ throw error+ } catch {+ throw RepackError.installStateCorrupt(path: path, detail: "\(error)")+ }+ }++ public func write(to path: String, parentDirectory: String) throws {+ try validate(path: path)+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ let data = try encoder.encode(self)+ guard data.count <= Self.maximumBytes else {+ throw RepackError.installStateCorrupt(+ path: path,+ detail: "checkpoint exceeds \(Self.maximumBytes)-byte cap")+ }+ try Posix.atomicWrite(data, to: path, durableIn: parentDirectory)+ }++ public func matches(repoID: String,+ requestedRevision: String,+ sourceIndexSHA256: String,+ planFingerprint: String) -> Bool {+ self.repoID == repoID+ && self.requestedRevision == requestedRevision+ && self.sourceIndexSHA256 == sourceIndexSHA256+ && self.planFingerprint == planFingerprint+ }++ public func validatedDestinationBytes(maximum: UInt64, path: String) throws -> UInt64 {+ try validate(path: path)+ var total: UInt64 = 0+ for range in completedRanges {+ let sum = total.addingReportingOverflow(range.destinationBytes)+ guard !sum.overflow, sum.partialValue <= maximum else {+ throw RepackError.installStateCorrupt(+ path: path,+ detail: "completed destination bytes exceed the installed model")+ }+ total = sum.partialValue+ }+ return total+ }++ private func validate(path: String) throws {+ guard schema == Self.schemaVersion,+ !repoID.isEmpty,+ !requestedRevision.isEmpty,+ resolvedCommit.count == 40,+ sourceIndexSHA256.count == 64,+ planFingerprint.count == 64,+ totalSourceBytes > 0 else {+ throw RepackError.installStateCorrupt(+ path: path,+ detail: "invalid checkpoint identity")+ }+ let ids = completedRanges.map(\.id)+ guard Set(ids).count == ids.count,+ completedRanges.allSatisfy({+ !$0.id.isEmpty+ && $0.destinationDigest.count == 64+ && $0.sourceBytes > 0+ && $0.destinationBytes > 0+ }) else {+ throw RepackError.installStateCorrupt(+ path: path,+ detail: "invalid completed range")+ }+ var sourceTotal: UInt64 = 0+ var destinationTotal: UInt64 = 0+ for range in completedRanges {+ let nextSource = sourceTotal.addingReportingOverflow(range.sourceBytes)+ let nextDestination = destinationTotal.addingReportingOverflow(+ range.destinationBytes)+ guard !nextSource.overflow,+ nextSource.partialValue <= totalSourceBytes,+ !nextDestination.overflow else {+ throw RepackError.installStateCorrupt(+ path: path,+ detail: "completed range byte totals are invalid")+ }+ sourceTotal = nextSource.partialValue+ destinationTotal = nextDestination.partialValue+ }+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteRangeTransfer.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteRangeTransfer.swiftnew file mode 100644index 00000000..4fd78985--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteRangeTransfer.swift@@ -0,0 +1,375 @@+import Darwin+import Foundation++public struct RemoteRangeExpectation: Sendable, Equatable {+ public let filename: String+ public let offset: UInt64+ public let length: UInt64+ public let totalSize: UInt64+ public let xetHash: String?++ public init(filename: String,+ offset: UInt64,+ length: UInt64,+ totalSize: UInt64,+ xetHash: String?) {+ self.filename = filename+ self.offset = offset+ self.length = length+ self.totalSize = totalSize+ self.xetHash = xetHash+ }+}++public struct RemoteRangeTransferResult: Sendable, Equatable {+ public let path: String+ public let byteCount: UInt64+}++public enum RemoteRangeTransfer {+ public static func run(configuration: URLSessionConfiguration,+ request: URLRequest,+ targetPath: String,+ expectation: RemoteRangeExpectation,+ maximumRedirects: Int,+ progress: @escaping @Sendable (UInt64) -> Void = { _ in })+ async throws -> RemoteRangeTransferResult {+ try Posix.mkdirP((targetPath as NSString).deletingLastPathComponent)+ let delegate = try RemoteRangeTransferDelegate(+ targetPath: targetPath,+ expectation: expectation,+ maximumRedirects: maximumRedirects,+ originalRequest: request,+ progress: progress)+ let queue = OperationQueue()+ queue.maxConcurrentOperationCount = 1+ queue.qualityOfService = .utility+ let session = URLSession(configuration: configuration,+ delegate: delegate,+ delegateQueue: queue)+ return try await withTaskCancellationHandler {+ defer { session.finishTasksAndInvalidate() }+ return try await delegate.start(session: session, request: request)+ } onCancel: {+ delegate.cancel()+ }+ }+}++private final class RemoteRangeTransferDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable {+ private let targetPath: String+ private let expectation: RemoteRangeExpectation+ private let fd: Int32+ private let progress: @Sendable (UInt64) -> Void+ private let lock = NSLock()++ private var continuation: CheckedContinuation<RemoteRangeTransferResult, Error>?+ private var task: URLSessionDataTask?+ private var terminal = false+ private var rejection: Error?+ private var receivedBytes: UInt64 = 0+ private var redirectPolicy: RemoteRedirectPolicy+ private var responseAccepted = false+ private var lastProgressNanoseconds: UInt64?++ init(targetPath: String,+ expectation: RemoteRangeExpectation,+ maximumRedirects: Int,+ originalRequest: URLRequest,+ progress: @escaping @Sendable (UInt64) -> Void) throws {+ self.targetPath = targetPath+ self.expectation = expectation+ self.redirectPolicy = RemoteRedirectPolicy(+ originalRequest: originalRequest,+ maximumRedirects: maximumRedirects)+ self.progress = progress+ let fd = open(targetPath, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ guard fd >= 0 else {+ throw RepackError.fileOpenFailed(path: targetPath, errno: errno)+ }+ self.fd = fd+ }++ func start(session: URLSession, request: URLRequest) async throws -> RemoteRangeTransferResult {+ try await withCheckedThrowingContinuation { continuation in+ lock.lock()+ self.continuation = continuation+ let task = session.dataTask(with: request)+ self.task = task+ let shouldCancel = terminal || rejection != nil+ lock.unlock()+ if shouldCancel {+ task.cancel()+ } else {+ task.resume()+ }+ }+ }++ func cancel() {+ lock.lock()+ let task = task+ if rejection == nil {+ rejection = CancellationError()+ }+ lock.unlock()+ task?.cancel()+ }++ func urlSession(_ session: URLSession,+ task: URLSessionTask,+ willPerformHTTPRedirection response: HTTPURLResponse,+ newRequest request: URLRequest,+ completionHandler: @escaping (URLRequest?) -> Void) {+ do {+ completionHandler(try redirectPolicy.request(+ response: response,+ proposedRequest: request))+ } catch {+ reject(error)+ completionHandler(nil)+ }+ }++ func urlSession(_ session: URLSession,+ dataTask: URLSessionDataTask,+ didReceive response: URLResponse,+ completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {+ do {+ if let cancellation = rejectionSnapshot() {+ throw cancellation+ }+ guard let http = response as? HTTPURLResponse else {+ throw RepackError.remoteProtocolInvalid(+ detail: "missing HTTP response for range \(expectation.filename)")+ }+ try validate(http)+ lock.lock()+ responseAccepted = true+ lock.unlock()+ completionHandler(.allow)+ } catch {+ reject(error)+ completionHandler(.cancel)+ }+ }++ func urlSession(_ session: URLSession,+ dataTask: URLSessionDataTask,+ didReceive data: Data) {+ lock.lock()+ let mayReceive = responseAccepted && rejection == nil+ lock.unlock()+ guard mayReceive else { return }+ let attempted = receivedBytes + UInt64(data.count)+ guard attempted <= expectation.length else {+ reject(RepackError.remoteBodyExceeded(+ path: expectation.filename,+ limit: expectation.length,+ attempted: attempted))+ dataTask.cancel()+ return+ }+ do {+ try data.withUnsafeBytes { raw in+ guard let base = raw.baseAddress else { return }+ try Posix.pwriteAll(fd: fd,+ path: targetPath,+ buf: base,+ count: raw.count,+ offset: receivedBytes)+ }+ receivedBytes = attempted+ emitProgressIfNeeded(force: receivedBytes == expectation.length)+ } catch {+ reject(error)+ dataTask.cancel()+ }+ }++ private func emitProgressIfNeeded(force: Bool) {+ let now = DispatchTime.now().uptimeNanoseconds+ if force+ || lastProgressNanoseconds == nil+ || now &- (lastProgressNanoseconds ?? now) >= 1_000_000_000 {+ lastProgressNanoseconds = now+ progress(receivedBytes)+ }+ }++ func urlSession(_ session: URLSession,+ task: URLSessionTask,+ didCompleteWithError error: Error?) {+ let result: Result<RemoteRangeTransferResult, Error>+ if let rejection = rejectionSnapshot() {+ result = .failure(rejection)+ } else if let error {+ result = .failure(error)+ } else if !responseAccepted {+ result = .failure(RepackError.remoteProtocolInvalid(+ detail: "range \(expectation.filename) completed without an accepted response"))+ } else if receivedBytes != expectation.length {+ result = .failure(RepackError.remoteBodyTruncated(+ path: expectation.filename,+ expected: expectation.length,+ actual: receivedBytes))+ } else {+ result = .success(RemoteRangeTransferResult(+ path: targetPath,+ byteCount: receivedBytes))+ }+ finish(result)+ }++ private func validate(_ response: HTTPURLResponse) throws {+ guard response.statusCode == 206 else {+ throw RepackError.remoteHTTPResponse(+ url: redactRemoteURL(response.url),+ status: response.statusCode,+ retryAfter: remoteHeader(response, "Retry-After"))+ }+ guard (remoteHeader(response, "Content-Encoding") ?? "identity").lowercased() == "identity" else {+ throw RepackError.remoteProtocolInvalid(+ detail: "compressed range response for \(expectation.filename)")+ }+ guard let contentLength = remoteHeader(response, "Content-Length"),+ UInt64(contentLength) == expectation.length else {+ throw RepackError.remoteProtocolInvalid(+ detail: "wrong Content-Length for \(expectation.filename)")+ }+ guard let range = remoteHeader(response, "Content-Range") else {+ throw RepackError.remoteProtocolInvalid(+ detail: "missing Content-Range for \(expectation.filename)")+ }+ let prefix = "bytes "+ let end = expectation.offset + expectation.length - 1+ guard range.hasPrefix(prefix) else {+ throw RepackError.remoteProtocolInvalid(detail: "malformed Content-Range \(range)")+ }+ let parts = range.dropFirst(prefix.count).split(separator: "/", maxSplits: 1)+ let bounds = parts.first?.split(separator: "-", maxSplits: 1) ?? []+ guard parts.count == 2,+ bounds.count == 2,+ UInt64(bounds[0]) == expectation.offset,+ UInt64(bounds[1]) == end,+ UInt64(parts[1]) == expectation.totalSize else {+ throw RepackError.remoteProtocolInvalid(detail: "wrong Content-Range \(range)")+ }+ if let xetHash = expectation.xetHash {+ guard normalizedStrongETag(remoteHeader(response, "ETag")) == xetHash.lowercased() else {+ throw RepackError.remoteProtocolInvalid(+ detail: "final ranged validator differs for \(expectation.filename)")+ }+ }+ }++ private func reject(_ error: Error) {+ lock.lock()+ if rejection == nil {+ rejection = error+ }+ lock.unlock()+ }++ private func rejectionSnapshot() -> Error? {+ lock.lock()+ defer { lock.unlock() }+ return rejection+ }++ private func finish(_ result: Result<RemoteRangeTransferResult, Error>) {+ lock.lock()+ guard !terminal else {+ lock.unlock()+ return+ }+ terminal = true+ let continuation = continuation+ self.continuation = nil+ self.task = nil+ lock.unlock()++ close(fd)+ if case .failure = result {+ try? FileManager.default.removeItem(atPath: targetPath)+ }+ continuation?.resume(with: result)+ }+}++struct RemoteRedirectPolicy {+ private let originalRange: String?+ private let originalAuthorization: String?+ private let sourceHost: String?+ private let maximumRedirects: Int+ private var redirectCount = 0+ private var authorizationMayBeForwarded = true++ init(originalRequest: URLRequest, maximumRedirects: Int) {+ self.originalRange = originalRequest.value(forHTTPHeaderField: "Range")+ self.originalAuthorization = originalRequest.value(+ forHTTPHeaderField: "Authorization")+ self.sourceHost = originalRequest.url?.host?.lowercased()+ self.maximumRedirects = maximumRedirects+ }++ mutating func request(+ response: HTTPURLResponse,+ proposedRequest: URLRequest+ ) throws -> URLRequest {+ redirectCount += 1+ guard redirectCount <= maximumRedirects else {+ throw RepackError.remoteRedirectRejected(+ url: redactRemoteURL(response.url),+ detail: "more than \(maximumRedirects) redirects")+ }+ guard proposedRequest.url?.scheme?.lowercased() == "https" else {+ throw RepackError.remoteRedirectRejected(+ url: redactRemoteURL(proposedRequest.url),+ detail: "only HTTPS redirects are allowed")+ }+ let targetHost = proposedRequest.url?.host?.lowercased()+ if targetHost != sourceHost {+ authorizationMayBeForwarded = false+ }+ var redirected = proposedRequest+ redirected.httpMethod = "GET"+ redirected.setValue(originalRange, forHTTPHeaderField: "Range")+ redirected.setValue("identity", forHTTPHeaderField: "Accept-Encoding")+ redirected.setValue(+ authorizationMayBeForwarded && targetHost == sourceHost+ ? originalAuthorization+ : nil,+ forHTTPHeaderField: "Authorization")+ return redirected+ }+}++func remoteHeader(_ response: HTTPURLResponse, _ name: String) -> String? {+ for (key, value) in response.allHeaderFields+ where String(describing: key).caseInsensitiveCompare(name) == .orderedSame {+ return String(describing: value)+ }+ return nil+}++func normalizedStrongETag(_ value: String?) -> String? {+ guard var value = value?.trimmingCharacters(in: .whitespacesAndNewlines),+ !value.isEmpty,+ !value.lowercased().hasPrefix("w/") else {+ return nil+ }+ if value.hasPrefix("\""), value.hasSuffix("\""), value.count >= 2 {+ value.removeFirst()+ value.removeLast()+ }+ return value.lowercased()+}++func redactRemoteURL(_ url: URL?) -> String {+ guard let url else { return "<unknown>" }+ var components = URLComponents(url: url, resolvingAgainstBaseURL: false)+ components?.query = nil+ components?.fragment = nil+ return components?.url?.absoluteString ?? "<redacted>"+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swiftindex 75d724da..4f2617c6 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteRetry.swift@@ -4,13 +4,16 @@ public struct RemoteRetryPolicy: Sendable {public var attempts: Intpublic var baseDelayNs: UInt64public var maxDelayNs: UInt64+ public var maxServerDelayNs: UInt64public init(attempts: Int = 4,baseDelayNs: UInt64 = 1_000_000_000,- maxDelayNs: UInt64 = 16_000_000_000) {+ maxDelayNs: UInt64 = 16_000_000_000,+ maxServerDelayNs: UInt64 = 60 * 60 * 1_000_000_000) {self.attempts = attemptsself.baseDelayNs = baseDelayNsself.maxDelayNs = maxDelayNs+ self.maxServerDelayNs = maxServerDelayNs}public static func isRetryable(_ error: Error) -> Bool {@@ -24,18 +27,50 @@ public struct RemoteRetryPolicy: Sendable {}}if case RepackError.remoteHTTPStatus(_, let status) = error {- return status == 429 || (500...599).contains(status)+ return retryableStatus(status)}- if case RepackError.remoteProtocolInvalid(let detail) = error,- detail.contains("wrote") {+ if case RepackError.remoteHTTPResponse(_, let status, _) = error {+ return retryableStatus(status)+ }+ if case RepackError.remoteBodyTruncated = error {return true}return false}++ public func retryDelayNs(error: Error,+ localDelayNs: UInt64,+ now: Date = Date()) throws -> UInt64 {+ let raw: String?+ if case RepackError.remoteHTTPResponse(_, _, let retryAfter) = error {+ raw = retryAfter+ } else {+ raw = nil+ }+ guard let raw else { return min(localDelayNs, maxServerDelayNs) }+ let server = try parseRetryAfterNs(raw, now: now)+ guard server <= maxServerDelayNs else {+ throw RepackError.remoteRetryDelayExceeded(+ value: raw,+ capSeconds: maxServerDelayNs / 1_000_000_000)+ }+ return max(min(localDelayNs, maxServerDelayNs), server)+ }}-func withRemoteRetries<T>(_ policy: RemoteRetryPolicy,+public typealias RemoteRetrySleeper = @Sendable (UInt64) async throws -> Void+public typealias RemoteRetryJitter = @Sendable () -> UInt64++public func withRemoteRetries<T>(_ policy: RemoteRetryPolicy,+ label: String,audit: RepackAudit?,+ now: @Sendable () -> Date = Date.init,+ jitter: @escaping RemoteRetryJitter = {+ UInt64.random(in: 0..<250_000_000)+ },+ sleeper: @escaping RemoteRetrySleeper = {+ try await Task.sleep(nanoseconds: $0)+ },op: () async throws -> T) async throws -> T {let attempts = max(policy.attempts, 1)var delay = policy.baseDelayNs@@ -50,13 +85,60 @@ func withRemoteRetries<T>(_ policy: RemoteRetryPolicy,RemoteRetryPolicy.isRetryable(error) else {throw error}- audit?.recordRemoteRetry()- if delay > 0 {- let jitter = UInt64.random(in: 0..<250_000_000)- try await Task.sleep(nanoseconds: delay &+ jitter)+ let localDelay = delay == 0 ? 0 : saturatingAdd(delay, jitter())+ let retryDelay = try policy.retryDelayNs(+ error: error,+ localDelayNs: localDelay,+ now: now())+ audit?.recordRemoteRetry(+ label: label,+ attempt: attempt,+ detail: String(describing: error))+ if retryDelay > 0 {+ try await sleeper(retryDelay)}- delay = min(delay &* 2, policy.maxDelayNs)+ let doubled = delay.multipliedReportingOverflow(by: 2)+ delay = min(doubled.overflow ? UInt64.max : doubled.partialValue,+ policy.maxDelayNs)}}throw lastError ?? RepackError.remoteProtocolInvalid(detail: "retry loop exited without an error")}++private func retryableStatus(_ status: Int) -> Bool {+ status == 408 || status == 429 || status == 500 || status == 502+ || status == 503 || status == 504+}++private func parseRetryAfterNs(_ raw: String, now: Date) throws -> UInt64 {+ let value = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ if let seconds = UInt64(value) {+ let (nanoseconds, overflow) = seconds.multipliedReportingOverflow(by: 1_000_000_000)+ return overflow ? UInt64.max : nanoseconds+ }+ let formats = [+ "EEE',' dd MMM yyyy HH':'mm':'ss zzz",+ "EEEE',' dd-MMM-yy HH':'mm':'ss zzz",+ "EEE MMM d HH':'mm':'ss yyyy",+ ]+ let date = formats.lazy.compactMap { format -> Date? in+ let formatter = DateFormatter()+ formatter.locale = Locale(identifier: "en_US_POSIX")+ formatter.timeZone = TimeZone(secondsFromGMT: 0)+ formatter.dateFormat = format+ return formatter.date(from: value)+ }.first+ guard let date else {+ throw RepackError.remoteProtocolInvalid(detail: "invalid Retry-After \(value)")+ }+ let seconds = max(date.timeIntervalSince(now), 0)+ guard seconds < Double(UInt64.max / 1_000_000_000) else {+ return UInt64.max+ }+ return UInt64(seconds * 1_000_000_000)+}++private func saturatingAdd(_ lhs: UInt64, _ rhs: UInt64) -> UInt64 {+ let result = lhs.addingReportingOverflow(rhs)+ return result.overflow ? UInt64.max : result.partialValue+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swiftindex 4282d5f5..71ea7d37 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteSnapshotLoader.swift@@ -11,9 +11,9 @@ struct RemoteSnapshot {enum RemoteSnapshotLoader {static func load(remote: HuggingFaceRemoteSource,- requireKnownSource: Bool,- metadataDirectory: String,- audit: RepackAudit? = nil) async throws -> RemoteSnapshot {+ requireKnownSource: Bool,+ metadataDirectory: String,+ audit: RepackAudit? = nil) async throws -> RemoteSnapshot {try Posix.mkdirP(metadataDirectory)let indexInfo = try await remote.resolveFileInfo(filename: "model.safetensors.index.json",diff --git a/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift b/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swiftindex 5fc40441..1e24b4b2 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/RemoteStreamingRepacker.swift@@ -1,44 +1,51 @@import Foundation-import Darwin-public struct RemoteStreamingRepackOptions: Sendable {+ public let repoID: String+ public let revision: Stringpublic let outputDir: String+ public let token: String?+ public let requireKnownSource: Bool+ public let copyAuditPath: String?+ public let rangeChunkBytes: Int+ public let writeTileBytes: Int+ public let minFreeReserveBytes: UInt64public let overwrite: Bool- let repoID: String- let revision: String- let token: String?- let requireKnownSource: Bool- let rangeChunkBytes: Int- let minFreeReserveBytes: UInt64- let retainPartialOnFailure: Bool- let session: URLSession- let baseURL: URL- let rangeRetryAttempts: Int- let retryBaseDelayNs: UInt64+ public let resume: Bool+ public let dryRunSpaceCheck: Bool+ public let downloadSession: RemoteDownloadSession+ public let baseURL: URL+ public let rangeRetryAttempts: Int+ public let retryBaseDelayNs: UInt64- init(outputDir: String,- overwrite: Bool,- repoID: String = SupportedModelSource.repoID,- revision: String = SupportedModelSource.revision,+ public init(repoID: String,+ revision: String,+ outputDir: String,token: String? = nil,- requireKnownSource: Bool = true,+ requireKnownSource: Bool = false,+ copyAuditPath: String? = nil,rangeChunkBytes: Int = RemoteChunkPolicy.defaultBytes,- minFreeReserveBytes: UInt64 = SupportedModelSource.reserveBytes,- retainPartialOnFailure: Bool = true,- session: URLSession = .shared,+ writeTileBytes: Int = WriterCore.tileBytes,+ minFreeReserveBytes: UInt64 = 1 * 1024 * 1024 * 1024,+ overwrite: Bool = false,+ resume: Bool = false,+ dryRunSpaceCheck: Bool = false,+ downloadSession: RemoteDownloadSession = RemoteDownloadSession(),baseURL: URL = URL(string: "https://huggingface.co")!,rangeRetryAttempts: Int = 4,retryBaseDelayNs: UInt64 = 1_000_000_000) {- self.outputDir = outputDir- self.overwrite = overwriteself.repoID = repoIDself.revision = revision+ self.outputDir = outputDirself.token = tokenself.requireKnownSource = requireKnownSource+ self.copyAuditPath = copyAuditPathself.rangeChunkBytes = rangeChunkBytes+ self.writeTileBytes = writeTileBytesself.minFreeReserveBytes = minFreeReserveBytes- self.retainPartialOnFailure = retainPartialOnFailure- self.session = session+ self.overwrite = overwrite+ self.resume = resume+ self.dryRunSpaceCheck = dryRunSpaceCheck+ self.downloadSession = downloadSessionself.baseURL = baseURLself.rangeRetryAttempts = rangeRetryAttemptsself.retryBaseDelayNs = retryBaseDelayNs@@ -48,12 +55,20 @@ public struct RemoteStreamingRepackOptions: Sendable {public struct RemoteStreamingRepackResult: Sendable {public let outputDir: Stringpublic let resolvedCommit: String+ let plan: RepackPlan+ public let rangeRequestCount: Intpublic let remoteBytesToDownload: UInt64+ public let remoteGapBytesDownloaded: UInt64+ public let remoteRetryCount: UInt64+ public let reusedBytes: UInt64+ public let downloadedThisRunBytes: UInt64+ public let dryRun: Bool}public final class RemoteStreamingRepacker {private let options: RemoteStreamingRepackOptionsprivate let audit: RepackAudit+ private let startTime = Date()public init(options: RemoteStreamingRepackOptions,audit: RepackAudit = RepackAudit()) {@@ -63,94 +78,237 @@ public final class RemoteStreamingRepacker {public func run(progress: @escaping @Sendable (ModelInstallProgress) -> Void = { _ in }) async throws-> RemoteStreamingRepackResult {- try Self.sweepStalePartials(outputDir: options.outputDir, audit: audit)- if FileManager.default.fileExists(atPath: options.outputDir), !options.overwrite {+ try validateOptions()+ let installLock = try InstallLock.acquire(outputDirectory: options.outputDir)+ defer { withExtendedLifetime(installLock) {} }+ let paths = installLock.paths+ if try Posix.entryKind(paths.finalDirectory) == .directory, !options.overwrite {throw RepackError.configurationInvalid(detail:- "output directory already exists: \(options.outputDir)")+ "output directory already exists: \(paths.finalDirectory)")+ }+ let hasPartial = try Posix.entryKind(paths.partialDirectory) == .directory+ let hasCheckpoint = try Posix.entryKind(paths.checkpointFile) == .regular+ guard hasPartial == hasCheckpoint else {+ throw RepackError.installStateCorrupt(+ path: paths.partialDirectory,+ detail: "partial directory and checkpoint must exist together")+ }+ if options.resume {+ guard hasPartial else {+ throw RepackError.installStateMissing(path: paths.checkpointFile)+ }+ } else if hasPartial {+ throw RepackError.installStateIncompatible(+ detail: "saved download exists; resume or discard it")}-- let partialDir = options.outputDir + ".partial.\(getpid())"- let metadataDir = (partialDir as NSString).appendingPathComponent(".remote-metadata")- let tempDir = (partialDir as NSString).appendingPathComponent(".range-tmp")- try? FileManager.default.removeItem(atPath: partialDir)-do {- return try await runPrepared(partialDir: partialDir,- metadataDir: metadataDir,- tempDir: tempDir,- progress: progress)+ return try await runPrepared(paths: paths, progress: progress)} catch {- if error is CancellationError || !options.retainPartialOnFailure {- try? FileManager.default.removeItem(atPath: partialDir)+ if !hasCheckpoint,+ (try? Posix.entryKind(paths.checkpointFile)) != .regular {+ try? FileManager.default.removeItem(atPath: paths.partialDirectory)}throw error}}- private func runPrepared(partialDir: String,- metadataDir: String,- tempDir: String,+ public static func inspectPersistentInstall(+ outputDirectory: String,+ repoID: String,+ requestedRevision: String+ ) throws -> RemoteInstallCheckpoint? {+ let lock = try InstallLock.acquire(outputDirectory: outputDirectory)+ defer { withExtendedLifetime(lock) {} }+ let paths = lock.paths+ let partial = try Posix.entryKind(paths.partialDirectory)+ let checkpoint = try Posix.entryKind(paths.checkpointFile)+ if partial == .absent, checkpoint == .absent { return nil }+ guard partial == .directory, checkpoint == .regular else {+ throw RepackError.installStateCorrupt(+ path: paths.partialDirectory,+ detail: "partial directory and checkpoint must exist together")+ }+ let value = try RemoteInstallCheckpoint.load(from: paths.checkpointFile)+ guard value.repoID == repoID, value.requestedRevision == requestedRevision else {+ throw RepackError.installStateIncompatible(+ detail: "saved download belongs to a different source")+ }+ return value+ }++ public static func discardPartial(outputDirectory: String) throws {+ let lock = try InstallLock.acquire(outputDirectory: outputDirectory)+ defer { withExtendedLifetime(lock) {} }+ let paths = lock.paths+ let hasPartial = try Posix.entryKind(paths.partialDirectory) != .absent+ let hasCheckpoint = try Posix.entryKind(paths.checkpointFile) != .absent+ guard hasPartial || hasCheckpoint else {+ throw RepackError.installStateMissing(path: paths.checkpointFile)+ }+ if hasPartial {+ try FileManager.default.removeItem(atPath: paths.partialDirectory)+ }+ if hasCheckpoint {+ try FileManager.default.removeItem(atPath: paths.checkpointFile)+ }+ try Posix.fsyncDirectory(paths.parentDirectory)+ }++ private func runPrepared(paths: RemoteInstallPaths,progress: @escaping @Sendable (ModelInstallProgress) -> Void) async throws-> RemoteStreamingRepackResult {try Task.checkCancellation()+ let saved = options.resume+ ? try RemoteInstallCheckpoint.load(from: paths.checkpointFile)+ : nil+ if let saved {+ guard saved.repoID == options.repoID,+ saved.requestedRevision == options.revision else {+ throw RepackError.installStateIncompatible(+ detail: "saved download belongs to a different source")+ }+ }let retryPolicy = RemoteRetryPolicy(attempts: options.rangeRetryAttempts,baseDelayNs: options.retryBaseDelayNs)let remote = HuggingFaceRemoteSource(repoID: options.repoID,requestedRevision: options.revision,+ resolvedCommit: saved?.resolvedCommit,token: options.token,- session: options.session,+ downloadSession: options.downloadSession,baseURL: options.baseURL,- tempDirectory: tempDir,+ tempDirectory: paths.partialDirectory,retryPolicy: retryPolicy)progress(.downloadingMetadata)let snapshot = try await RemoteSnapshotLoader.load(remote: remote,requireKnownSource: options.requireKnownSource,- metadataDirectory: metadataDir,+ metadataDirectory: paths.metadataDirectory,audit: audit)try Task.checkCancellation()let plan = try RepackPlanner.plan(meta: snapshot.metadata,arch: snapshot.arch,shardHeaders: snapshot.shardHeaders,- outputDir: partialDir)+ outputDir: paths.partialDirectory)let rangePlan = try RangeCopyPlanner.plan(repackPlan: plan,- rangeChunkBytes: options.rangeChunkBytes)+ rangeChunkBytes: options.rangeChunkBytes,+ layoutMode: "identity",+ layoutOrderSha256: nil)+ var checkpoint = saved ?? RemoteInstallCheckpoint(+ repoID: options.repoID,+ requestedRevision: options.revision,+ resolvedCommit: snapshot.resolvedCommit,+ sourceIndexSHA256: snapshot.metadata.indexSha256Hex,+ planFingerprint: rangePlan.canonicalFingerprint,+ totalSourceBytes: rangePlan.remoteBytesToDownload)+ if saved != nil {+ guard checkpoint.resolvedCommit == snapshot.resolvedCommit,+ checkpoint.totalSourceBytes == rangePlan.remoteBytesToDownload,+ checkpoint.matches(+ repoID: options.repoID,+ requestedRevision: options.revision,+ sourceIndexSHA256: snapshot.metadata.indexSha256Hex,+ planFingerprint: rangePlan.canonicalFingerprint) else {+ throw RepackError.installStateIncompatible(+ detail: "saved download source or copy plan changed")+ }+ if try outputFilesMatch(plan: plan, rangePlan: rangePlan) {+ checkpoint.completedRanges = try Self.validatedCompletedRanges(+ checkpoint.completedRanges,+ copies: rangePlan.coalescedCopies,+ partialDirectory: paths.partialDirectory)+ } else {+ checkpoint.completedRanges = []+ try FileManager.default.removeItem(atPath: paths.partialDirectory)+ try Posix.mkdirP(paths.partialDirectory)+ try createOutputFiles(plan: plan, paths: paths)+ }+ try checkpoint.write(+ to: paths.checkpointFile,+ parentDirectory: paths.parentDirectory)+ }let outputBytes = plan.resident.totalSize+ plan.layers.reduce(UInt64(0)) { $0 + $1.fileSize }progress(.planning(downloadBytes: rangePlan.remoteBytesToDownload,outputBytes: outputBytes))+ let reusedDestinationBytes = checkpoint.completedRanges.reduce(UInt64(0)) {+ $0 + $1.destinationBytes+ }+ let remainingOutputBytes = outputBytes > reusedDestinationBytes+ ? outputBytes - reusedDestinationBytes+ : 0let diskRequirement = try DiskSpaceChecker.requireAvailable(- path: partialDir,- bytes: outputBytes + UInt64(options.rangeChunkBytes),+ path: paths.parentDirectory,+ bytes: remainingOutputBytes + UInt64(options.rangeChunkBytes),reserveBytes: options.minFreeReserveBytes)progress(.checkingDisk(diskRequirement))try Task.checkCancellation()- progress(.reservingOutput(bytes: outputBytes))- try Task.checkCancellation()- try Posix.mkdirP((partialDir as NSString).appendingPathComponent("packed_experts"))- try Posix.mkdirP(tempDir)+ audit.remoteRepoID = options.repoID+ audit.remoteRequestedRevision = options.revision+ audit.remoteResolvedCommit = snapshot.resolvedCommit+ audit.remoteRangeStreamingSupported = true+ audit.remoteGapBytesDownloaded = rangePlan.remoteGapBytesDownloaded+ audit.sourceSnapshotSha256 = snapshot.metadata.indexSha256Hex+ audit.bitWidthOverridesHonored = snapshot.metadata.bitsOverrides.count+ audit.tensorsDroppedMultimodal = plan.excludedMultimodalTensorNames+ audit.packedExpertLayoutMode = "identity"- let residentFd = try ResidentWriter.createAndWriteIndex(plan: plan.resident, audit: audit)- try Posix.fsync(residentFd, path: plan.resident.path)- close(residentFd)- for layer in plan.layers where layer.expertsPerLayer > 0 {- try Task.checkCancellation()- try Posix.mkdirP((layer.path as NSString).deletingLastPathComponent)- let fd = try Posix.openCreateRW(layer.path)- try Posix.ftruncate(fd, path: layer.path, size: layer.fileSize)- try Posix.fsync(fd, path: layer.path)- close(fd)+ if options.dryRunSpaceCheck {+ if saved == nil {+ try? FileManager.default.removeItem(atPath: paths.partialDirectory)+ }+ return RemoteStreamingRepackResult(outputDir: options.outputDir,+ resolvedCommit: snapshot.resolvedCommit,+ plan: plan,+ rangeRequestCount: rangePlan.coalescedCopies.count,+ remoteBytesToDownload: rangePlan.remoteBytesToDownload,+ remoteGapBytesDownloaded: rangePlan.remoteGapBytesDownloaded,+ remoteRetryCount: audit.remoteRangeRetries,+ reusedBytes: checkpoint.completedRanges.reduce(0) {+ $0 + $1.sourceBytes+ },+ downloadedThisRunBytes: 0,+ dryRun: true)+ }++ if saved == nil {+ progress(.reservingOutput(bytes: outputBytes))+ try createOutputFiles(plan: plan, paths: paths)+ try checkpoint.write(+ to: paths.checkpointFile,+ parentDirectory: paths.parentDirectory)}let provider = HTTPRangeSourceByteProvider(remote: remote.pinned(commit: snapshot.resolvedCommit),files: snapshot.remoteFiles,- writeTileBytes: WriterCore.tileBytes)- progress(.copyingPayload(downloadedBytes: 0,- totalBytes: rangePlan.remoteBytesToDownload))- try await provider.copyBatch(rangePlan.coalescedCopies, audit: audit) { downloadedBytes in- progress(.copyingPayload(downloadedBytes: downloadedBytes,- totalBytes: rangePlan.remoteBytesToDownload))+ writeTileBytes: options.writeTileBytes)+ let reusedBytes = checkpoint.completedRanges.reduce(UInt64(0)) {+ $0 + $1.sourceBytes}+ let payloadDownloadStart = audit.remoteBytesDownloaded+ progress(.copyingPayload(+ reusedBytes: reusedBytes,+ downloadedThisRunBytes: 0,+ totalBytes: rangePlan.remoteBytesToDownload))+ try await provider.copyBatch(+ rangePlan.coalescedCopies,+ completedRangeIDs: Set(checkpoint.completedRanges.map(\.id)),+ partialDirectory: paths.partialDirectory,+ temporaryPath: paths.rangeTemporaryFile,+ audit: audit,+ progress: { downloadedBytes in+ progress(.copyingPayload(+ reusedBytes: reusedBytes,+ downloadedThisRunBytes: downloadedBytes,+ totalBytes: rangePlan.remoteBytesToDownload))+ },+ commit: { completed in+ checkpoint.completedRanges.removeAll { $0.id == completed.id }+ checkpoint.completedRanges.append(completed)+ checkpoint.completedRanges.sort { $0.id < $1.id }+ try checkpoint.write(+ to: paths.checkpointFile,+ parentDirectory: paths.parentDirectory)+ })try recordOutputFile(relativePath: "model_weights.bin",path: plan.resident.path,@@ -161,7 +319,8 @@ public final class RemoteStreamingRepacker {try recordOutputFile(relativePath: rel, path: layer.path, progress: progress)}- let layoutPath = ((partialDir as NSString).appendingPathComponent("packed_experts") as NSString)+ let layoutPath = ((paths.partialDirectory as NSString)+ .appendingPathComponent("packed_experts") as NSString).appendingPathComponent("layout.json")let expertStride = plan.layers.first(where: { $0.expertsPerLayer > 0 })?.expertStride ?? 0let layoutData = try GTurboJSON.encodeLayout(plan: plan, expertStride: expertStride)@@ -174,47 +333,148 @@ public final class RemoteStreamingRepacker {try Task.checkCancellation()try await copyRemoteMetadataSidecars(snapshot: snapshot,remote: remote,- partialDir: partialDir,+ partialDir: paths.partialDirectory,progress: progress)- try? FileManager.default.removeItem(atPath: tempDir)- try? FileManager.default.removeItem(atPath: metadataDir)+ try? FileManager.default.removeItem(atPath: paths.rangeTemporaryFile)+ try? FileManager.default.removeItem(atPath: paths.metadataDirectory)progress(.finalizing)try Task.checkCancellation()try writeManifest(plan: plan,- partialDir: partialDir,+ partialDir: paths.partialDirectory,metadata: snapshot.metadata,expertStride: expertStride,resolvedCommit: snapshot.resolvedCommit)try Task.checkCancellation()- if FileManager.default.fileExists(atPath: options.outputDir) {- try FileManager.default.removeItem(atPath: options.outputDir)+ if try Posix.entryKind(paths.finalDirectory) == .directory {+ try Posix.renameSwap(paths.partialDirectory, paths.finalDirectory)+ try Posix.fsyncDirectory(paths.parentDirectory)+ try? FileManager.default.removeItem(atPath: paths.partialDirectory)+ } else {+ try Posix.rename(from: paths.partialDirectory, to: paths.finalDirectory)+ try Posix.fsyncDirectory(paths.parentDirectory)+ }+ try? FileManager.default.removeItem(atPath: paths.checkpointFile)++ audit.wallTimeSeconds = Date().timeIntervalSince(startTime)+ audit.wholeFileHeapBuffers = false+ if let auditPath = options.copyAuditPath {+ let data = try audit.toJSONData(outputDir: options.outputDir)+ try Posix.mkdirP((auditPath as NSString).deletingLastPathComponent)+ try data.write(to: URL(fileURLWithPath: auditPath))}- try Posix.rename(from: partialDir, to: options.outputDir)return RemoteStreamingRepackResult(outputDir: options.outputDir,resolvedCommit: snapshot.resolvedCommit,- remoteBytesToDownload: rangePlan.remoteBytesToDownload)+ plan: plan,+ rangeRequestCount: rangePlan.coalescedCopies.count,+ remoteBytesToDownload: rangePlan.remoteBytesToDownload,+ remoteGapBytesDownloaded: rangePlan.remoteGapBytesDownloaded,+ remoteRetryCount: audit.remoteRangeRetries,+ reusedBytes: reusedBytes,+ downloadedThisRunBytes:+ audit.remoteBytesDownloaded - payloadDownloadStart,+ dryRun: false)+ }++ private func validateOptions() throws {+ guard options.rangeChunkBytes > 0,+ options.rangeChunkBytes <= RemoteChunkPolicy.maxBytes else {+ throw RepackError.configurationInvalid(detail: "bad range chunk bytes \(options.rangeChunkBytes)")+ }+ guard options.writeTileBytes > 0,+ options.writeTileBytes <= BoundedScratch.defaultLimitBytes else {+ throw RepackError.configurationInvalid(detail: "bad write tile bytes \(options.writeTileBytes)")+ }+ guard options.rangeRetryAttempts >= 0 else {+ throw RepackError.configurationInvalid(detail:+ "bad range retry attempts \(options.rangeRetryAttempts)")+ }+ }++ private func createOutputFiles(plan: RepackPlan,+ paths: RemoteInstallPaths) throws {+ try Posix.mkdirP((paths.partialDirectory as NSString)+ .appendingPathComponent("packed_experts"))+ let resident = try ResidentWriter.createAndWriteIndex(+ plan: plan.resident,+ audit: audit)+ try Posix.fsync(resident, path: plan.resident.path)+ close(resident)+ for layer in plan.layers where layer.expertsPerLayer > 0 {+ try Task.checkCancellation()+ let descriptor = try Posix.openCreateRW(layer.path)+ try Posix.ftruncate(descriptor, path: layer.path, size: layer.fileSize)+ try Posix.fsync(descriptor, path: layer.path)+ close(descriptor)+ }+ try Posix.fsyncDirectory(paths.partialDirectory)+ }++ private func outputFilesMatch(plan: RepackPlan,+ rangePlan: RangeCopyPlan) throws -> Bool {+ for output in rangePlan.expectedOutputs {+ let path = ((plan.resident.path as NSString).deletingLastPathComponent+ as NSString).appendingPathComponent(output.relativePath)+ guard try Posix.entryKind(path) == .regular else { return false }+ let descriptor = try Posix.openReadNoFollow(path)+ defer { close(descriptor) }+ guard try Posix.fileSize(fd: descriptor, path: path) == output.size else {+ return false+ }+ }++ let expectedIndex = try ResidentWriter.encodeIndex(plan: plan.resident)+ let descriptor = try Posix.openReadNoFollow(plan.resident.path)+ defer { close(descriptor) }+ let scratch = UnsafeMutableRawBufferPointer.allocate(+ byteCount: min(WriterCore.tileBytes, max(1, expectedIndex.count)),+ alignment: 16_384)+ defer { scratch.deallocate() }+ return try expectedIndex.withUnsafeBytes { expected in+ var offset = 0+ while offset < expected.count {+ let count = min(scratch.count, expected.count - offset)+ try Posix.preadAll(+ fd: descriptor,+ path: plan.resident.path,+ buf: scratch.baseAddress!,+ count: count,+ offset: UInt64(offset))+ guard memcmp(+ scratch.baseAddress!,+ expected.baseAddress!.advanced(by: offset),+ count) == 0 else { return false }+ offset += count+ }+ return true+ }}- static func sweepStalePartials(outputDir: String, audit: RepackAudit? = nil) throws {- let parent = (outputDir as NSString).deletingLastPathComponent- let searchDir = parent.isEmpty ? "." : parent- let prefix = (outputDir as NSString).lastPathComponent + ".partial."- let fm = FileManager.default- for entry in (try? fm.contentsOfDirectory(atPath: searchDir)) ?? []- where entry.hasPrefix(prefix) {- let path = (searchDir as NSString).appendingPathComponent(entry)- let suffix = String(entry.dropFirst(prefix.count))- if let pid = Int32(suffix),- kill(pid, 0) == 0 {- throw RepackError.configurationInvalid(detail:- "another repack (pid \(pid)) appears to own \(path); " +- "delete it manually if that process is not a repack")+ static func validatedCompletedRanges(+ _ completed: [RemoteCompletedRange],+ copies: [CoalescedRangeCopy],+ partialDirectory: String+ ) throws -> [RemoteCompletedRange] {+ let copiesByID = Dictionary(uniqueKeysWithValues: copies.map { ($0.id, $0) })+ var valid: [RemoteCompletedRange] = []+ for range in completed {+ guard let copy = copiesByID[range.id],+ range.sourceBytes == copy.size,+ range.destinationBytes+ == copy.destinations.reduce(UInt64(0), { $0 + $1.size }) else {+ throw RepackError.installStateCorrupt(+ path: partialDirectory,+ detail: "checkpoint contains an unknown range")+ }+ let digest = try HTTPRangeSourceByteProvider.destinationDigest(+ copy,+ partialDirectory: partialDirectory)+ if digest == range.destinationDigest {+ valid.append(range)}- try fm.removeItem(atPath: path)- audit?.stalePartialsRemoved.append(path)}+ return valid.sorted { $0.id < $1.id }}private func recordOutputFile(relativePath: String,@@ -272,7 +532,7 @@ public final class RemoteStreamingRepacker {do {info = try await pinned.resolveFileInfo(filename: file.name, audit: audit)} catch {- if file.required {+ if file.required || !isRemoteNotFound(error) {throw error}continue@@ -285,25 +545,44 @@ public final class RemoteStreamingRepacker {audit: audit)try recordOutputFile(relativePath: "tokenizer/\(file.name)",path: dst,- progress: progress)+ progress: progress)}}+ private func isRemoteNotFound(_ error: Error) -> Bool {+ if case RepackError.remoteHTTPStatus(_, 404) = error {+ return true+ }+ if case RepackError.remoteHTTPResponse(_, 404, _) = error {+ return true+ }+ return false+ }+private func writeManifest(plan: RepackPlan,partialDir: String,metadata: IndexLoader.SourceMetadata,expertStride: UInt64,resolvedCommit: String) throws {- var bits = GTurboJSON.QuantBitWidths(embedding: 4,- attention: 4,- router: 8,- sharedExpert: 8,- routedExpert: 4)+ var bits = GTurboJSON.QuantBitWidths(+ embedding: 4,+ attention: 4,+ router: 8,+ sharedExpert: 8,+ routedExpert: 4)for e in plan.resident.entries {- if e.name == "language_model.model.embed_tokens.weight", let s = e.quantSpec { bits.embedding = s.bits }- if e.name.hasSuffix(".self_attn.q_proj.weight"), let s = e.quantSpec { bits.attention = s.bits }- if e.name.hasSuffix(".router.proj.weight"), let s = e.quantSpec { bits.router = s.bits }- if e.name.hasSuffix(".mlp.gate_proj.weight"), let s = e.quantSpec { bits.sharedExpert = s.bits }+ if e.name == "language_model.model.embed_tokens.weight", let s = e.quantSpec {+ bits.embedding = s.bits+ }+ if e.name.hasSuffix(".self_attn.q_proj.weight"), let s = e.quantSpec {+ bits.attention = s.bits+ }+ if e.name.hasSuffix(".router.proj.weight"), let s = e.quantSpec {+ bits.router = s.bits+ }+ if e.name.hasSuffix(".mlp.gate_proj.weight"), let s = e.quantSpec {+ bits.sharedExpert = s.bits+ }}if let layer = plan.layers.first(where: { !$0.subTensors.isEmpty }),let routedBits = layer.subTensors.first?.bitsForWeights {diff --git a/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swift b/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swiftindex 80f43bb3..c288d17b 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/SourceByteProvider.swift@@ -1,12 +1,24 @@-import Foundationimport Darwin+import Foundation-final class HTTPRangeSourceByteProvider {+public protocol SourceByteProvider {+ func copyBatch(+ _ copies: [CoalescedRangeCopy],+ completedRangeIDs: Set<String>,+ partialDirectory: String,+ temporaryPath: String,+ audit: RepackAudit,+ progress: @escaping @Sendable (UInt64) -> Void,+ commit: (RemoteCompletedRange) throws -> Void+ ) async throws+}++public final class HTTPRangeSourceByteProvider: SourceByteProvider {private let remote: HuggingFaceRemoteSourceprivate let files: [String: RemoteFileInfo]private let writeTileBytes: Int- init(remote: HuggingFaceRemoteSource,+ public init(remote: HuggingFaceRemoteSource,files: [String: RemoteFileInfo],writeTileBytes: Int = WriterCore.tileBytes) {self.remote = remote@@ -14,101 +26,210 @@ final class HTTPRangeSourceByteProvider {self.writeTileBytes = writeTileBytes}- func copyBatch(_ copies: [CoalescedRangeCopy],- audit: RepackAudit,- progress: @Sendable (UInt64) -> Void) async throws {- let scratch = UnsafeMutableRawBufferPointer.allocate(byteCount: writeTileBytes,- alignment: 16_384)+ public func copyBatch(+ _ copies: [CoalescedRangeCopy],+ completedRangeIDs: Set<String>,+ partialDirectory: String,+ temporaryPath: String,+ audit: RepackAudit,+ progress: @escaping @Sendable (UInt64) -> Void,+ commit: (RemoteCompletedRange) throws -> Void+ ) async throws {+ let scratch = UnsafeMutableRawBufferPointer.allocate(+ byteCount: writeTileBytes,+ alignment: 16_384)defer { scratch.deallocate() }audit.largestScratchBytes = max(audit.largestScratchBytes, scratch.count)var outputFDs: [String: Int32] = [:]- defer {- for fd in outputFDs.values { close(fd) }- }+ defer { outputFDs.values.forEach { close($0) } }+ var downloaded: UInt64 = 0- var downloadedBytes: UInt64 = 0- for copy in copies {+ for copy in copies where !completedRangeIDs.contains(copy.id) {try Task.checkCancellation()guard let info = files[copy.shardID] else {- throw RepackError.configurationInvalid(detail: "missing remote info for \(copy.shardID)")+ throw RepackError.configurationInvalid(+ detail: "missing remote info for \(copy.shardID)")+ }+ if try Posix.entryKind(temporaryPath) != .absent {+ try FileManager.default.removeItem(atPath: temporaryPath)}- let temp = try await remote.downloadRangeToTempFile(filename: copy.shardID,- info: info,- offset: copy.sourceOffset,- length: Int(copy.size),- audit: audit)- defer { try? FileManager.default.removeItem(atPath: temp.path) }+ let base = downloaded+ let temporary = try await remote.downloadRangeToTempFile(+ filename: copy.shardID,+ info: info,+ offset: copy.sourceOffset,+ length: Int(copy.size),+ targetPath: temporaryPath,+ progress: { bytes in progress(base + bytes) },+ audit: audit)+audit.remoteRangeRequests += 1- audit.remoteBytesDownloaded += temp.byteCount- audit.largestRemoteTransferBytes = max(audit.largestRemoteTransferBytes, Int(temp.byteCount))- audit.largestRemotePayloadHeapBytes = max(audit.largestRemotePayloadHeapBytes, scratch.count)- downloadedBytes += temp.byteCount- progress(downloadedBytes)-- let srcFd = try Posix.openRead(temp.path)- defer { close(srcFd) }- for destination in copy.destinations {- try Task.checkCancellation()- let dstFd: Int32- if let cached = outputFDs[destination.destinationPath] {- dstFd = cached- } else {- dstFd = open(destination.destinationPath, O_RDWR)- if dstFd < 0 {- throw RepackError.fileOpenFailed(path: destination.destinationPath, errno: errno)+ audit.remoteBytesDownloaded += temporary.byteCount+ audit.largestRemoteTransferBytes = max(+ audit.largestRemoteTransferBytes,+ Int(temporary.byteCount))+ downloaded += temporary.byteCount+ progress(downloaded)++ let sourceFD = try Posix.openReadNoFollow(temporary.path)+ var touched = Set<String>()+ do {+ for destination in copy.destinations {+ let destinationFD: Int32+ if let existing = outputFDs[destination.destinationPath] {+ destinationFD = existing+ } else {+ destinationFD = try Posix.openExistingRW(+ destination.destinationPath)+ outputFDs[destination.destinationPath] = destinationFD}- outputFDs[destination.destinationPath] = dstFd+ touched.insert(destination.destinationPath)+ try copyBytes(+ sourceFD: sourceFD,+ sourcePath: temporary.path,+ destinationFD: destinationFD,+ destinationPath: destination.destinationPath,+ sourceOffset: destination.sourceOffset - copy.sourceOffset,+ destinationOffset: destination.destinationOffset,+ size: destination.size,+ scratch: scratch,+ audit: audit)}- let tempOffset = destination.sourceOffset - copy.sourceOffset- try copyTempRange(srcFd: srcFd,- srcPath: temp.path,- dstFd: dstFd,- dstPath: destination.destinationPath,- srcOffset: tempOffset,- dstOffset: destination.destinationOffset,- size: destination.size,- scratch: scratch,- audit: audit)+ close(sourceFD)+ } catch {+ close(sourceFD)+ throw error}- }- for (path, fd) in outputFDs {++ try Task.checkCancellation()+ for path in touched {+ if let descriptor = outputFDs[path] {+ try Posix.fsync(descriptor, path: path)+ }+ }+ let digest = try Self.destinationDigest(+ copy,+ partialDirectory: partialDirectory,+ scratch: scratch)+ try commit(RemoteCompletedRange(+ id: copy.id,+ destinationDigest: digest,+ sourceBytes: copy.size,+ destinationBytes: copy.destinations.reduce(0) { $0 + $1.size }))+ progress(downloaded)+ try? FileManager.default.removeItem(atPath: temporary.path)try Task.checkCancellation()- try Posix.fsync(fd, path: path)}}- private func copyTempRange(srcFd: Int32,- srcPath: String,- dstFd: Int32,- dstPath: String,- srcOffset: UInt64,- dstOffset: UInt64,- size: UInt64,- scratch: UnsafeMutableRawBufferPointer,- audit: RepackAudit) throws {+ public static func destinationDigest(+ _ copy: CoalescedRangeCopy,+ partialDirectory: String,+ scratch suppliedScratch: UnsafeMutableRawBufferPointer? = nil+ ) throws -> String {+ let scratch = suppliedScratch ?? UnsafeMutableRawBufferPointer.allocate(+ byteCount: WriterCore.tileBytes,+ alignment: 16_384)+ defer {+ if suppliedScratch == nil { scratch.deallocate() }+ }++ var digest = DestinationDigest(copy: copy)+ for destination in copy.destinations {+ digest.append(try RangeCopyPlanner.normalizedRelativePath(+ destination.destinationPath,+ root: partialDirectory))+ digest.append(destination.destinationOffset)+ digest.append(destination.sourceOffset - copy.sourceOffset)+ digest.append(destination.size)++ let descriptor = try Posix.openReadNoFollow(destination.destinationPath)+ defer { close(descriptor) }+ var remaining = destination.size+ var offset = destination.destinationOffset+ while remaining > 0 {+ let count = min(Int(remaining), scratch.count)+ try Posix.preadAll(+ fd: descriptor,+ path: destination.destinationPath,+ buf: scratch.baseAddress!,+ count: count,+ offset: offset)+ digest.append(UnsafeRawBufferPointer(+ start: scratch.baseAddress,+ count: count))+ remaining -= UInt64(count)+ offset += UInt64(count)+ }+ }+ return digest.finalize()+ }++ private func copyBytes(+ sourceFD: Int32,+ sourcePath: String,+ destinationFD: Int32,+ destinationPath: String,+ sourceOffset: UInt64,+ destinationOffset: UInt64,+ size: UInt64,+ scratch: UnsafeMutableRawBufferPointer,+ audit: RepackAudit+ ) throws {var remaining = size- var src = srcOffset- var dst = dstOffset+ var source = sourceOffset+ var destination = destinationOffsetwhile remaining > 0 {try Task.checkCancellation()- let n = min(Int(remaining), scratch.count)- try Posix.preadAll(fd: srcFd,- path: srcPath,- buf: scratch.baseAddress!,- count: n,- offset: src)- try Posix.pwriteAll(fd: dstFd,- path: dstPath,- buf: scratch.baseAddress!,- count: n,- offset: dst)- audit.recordTile(bytes: n)- audit.recordRead(bytes: n)- audit.recordWrite(bytes: n)- remaining -= UInt64(n)- src += UInt64(n)- dst += UInt64(n)+ let count = min(Int(remaining), scratch.count)+ try Posix.preadAll(+ fd: sourceFD,+ path: sourcePath,+ buf: scratch.baseAddress!,+ count: count,+ offset: source)+ try Posix.pwriteAll(+ fd: destinationFD,+ path: destinationPath,+ buf: scratch.baseAddress!,+ count: count,+ offset: destination)+ audit.recordTile(bytes: count)+ audit.recordRead(bytes: count)+ audit.recordWrite(bytes: count)+ remaining -= UInt64(count)+ source += UInt64(count)+ destination += UInt64(count)}}}++private struct DestinationDigest {+ private var stream = Sha256Stream()++ init(copy: CoalescedRangeCopy) {+ append("TurboFieldfare.RemoteRangeDestination.v1")+ append(copy.id)+ append(UInt64(copy.destinations.count))+ }++ mutating func append(_ value: UInt64) {+ var littleEndian = value.littleEndian+ withUnsafeBytes(of: &littleEndian) { stream.update($0) }+ }++ mutating func append(_ value: String) {+ let data = Data(value.utf8)+ append(UInt64(data.count))+ data.withUnsafeBytes { stream.update($0) }+ }++ mutating func append(_ bytes: UnsafeRawBufferPointer) {+ stream.update(bytes)+ }++ func finalize() -> String {+ stream.finalizeHexString()+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift b/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swiftindex f9e35c30..2e432d45 100644--- a/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift+++ b/Sources/TurboFieldfareRepack/Core/Remote/SupportedModelSource.swift@@ -13,12 +13,16 @@ public enum SupportedModelSource {public static func installOptions(outputDirectory: URL,overwrite: Bool,token: String?,- retainPartialOnFailure: Bool = false)+ resume: Bool = false)-> RemoteStreamingRepackOptions {RemoteStreamingRepackOptions(+ repoID: repoID,+ revision: revision,outputDir: outputDirectory.path,- overwrite: overwrite,token: token,- retainPartialOnFailure: retainPartialOnFailure)+ requireKnownSource: true,+ minFreeReserveBytes: reserveBytes,+ overwrite: overwrite,+ resume: resume)}}diff --git a/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swift b/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swiftindex 0b547101..5a88c1c5 100644--- a/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swift+++ b/Sources/TurboFieldfareRepack/Core/System/DiskSpaceChecker.swift@@ -53,7 +53,12 @@ public enum DiskSpaceChecker {throw RepackError.fileStatFailed(path: path, errno: errno)}let available = UInt64(st.f_bavail) * UInt64(st.f_bsize)- let required = bytes + reserveBytes+ let sum = bytes.addingReportingOverflow(reserveBytes)+ guard !sum.overflow else {+ throw RepackError.configurationInvalid(+ detail: "disk-space requirement overflows UInt64")+ }+ let required = sum.partialValuereturn DiskSpaceRequirement(path: path,requiredBytes: required,availableBytes: available)diff --git a/Sources/TurboFieldfareRepack/Core/System/InstallLock.swift b/Sources/TurboFieldfareRepack/Core/System/InstallLock.swiftnew file mode 100644index 00000000..56c219ea--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/System/InstallLock.swift@@ -0,0 +1,97 @@+import Darwin+import Foundation++public struct RemoteInstallPaths: Sendable, Equatable {+ public let parentDirectory: String+ public let finalDirectory: String+ public let partialDirectory: String+ public let lockFile: String+ public let checkpointFile: String+ public let rangeTemporaryFile: String+ public let metadataDirectory: String++ public init(outputDirectory: String) throws {+ let standardized = URL(fileURLWithPath: outputDirectory).standardizedFileURL+ let basename = standardized.lastPathComponent.precomposedStringWithCanonicalMapping+ guard !basename.isEmpty,+ basename != ".",+ basename != "..",+ !basename.contains("/") else {+ throw RepackError.installPathUnsafe(+ path: outputDirectory,+ detail: "invalid output basename")+ }+ let requestedParent = standardized.deletingLastPathComponent().path+ try Posix.mkdirP(requestedParent)+ let parent = try Posix.physicalPath(requestedParent)+ let final = (parent as NSString).appendingPathComponent(basename)+ let partial = final + ".partial"+ self.parentDirectory = parent+ self.finalDirectory = final+ self.partialDirectory = partial+ self.lockFile = final + ".install.lock"+ self.checkpointFile = final + ".resume.json"+ self.rangeTemporaryFile = (partial as NSString)+ .appendingPathComponent(".range.tmp")+ self.metadataDirectory = (partial as NSString)+ .appendingPathComponent(".remote-metadata")+ }++ public func validateEntryTypes() throws {+ try require(finalDirectory, kinds: [.absent, .directory])+ try require(partialDirectory, kinds: [.absent, .directory])+ try require(checkpointFile, kinds: [.absent, .regular])+ try require(lockFile, kinds: [.absent, .regular])+ }++ private func require(_ path: String, kinds: Set<Posix.EntryKind>) throws {+ let kind = try Posix.entryKind(path)+ guard kinds.contains(kind) else {+ throw RepackError.installPathUnsafe(+ path: path,+ detail: "unexpected \(kind) entry")+ }+ }+}++public final class InstallLock: @unchecked Sendable {+ public let paths: RemoteInstallPaths+ private let descriptor: Int32++ private init(paths: RemoteInstallPaths, descriptor: Int32) {+ self.paths = paths+ self.descriptor = descriptor+ }++ deinit {+ _ = flock(descriptor, LOCK_UN)+ close(descriptor)+ }++ public static func acquire(outputDirectory: String) throws -> InstallLock {+ let paths = try RemoteInstallPaths(outputDirectory: outputDirectory)+ try paths.validateEntryTypes()+ let descriptor = try Posix.openLock(paths.lockFile)+ guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else {+ let savedErrno = errno+ close(descriptor)+ if savedErrno == EWOULDBLOCK {+ throw RepackError.installBusy(path: paths.lockFile)+ }+ throw RepackError.fileOpenFailed(path: paths.lockFile, errno: savedErrno)+ }+ do {+ try paths.validateEntryTypes()+ guard try Posix.descriptorMatchesPath(descriptor, path: paths.lockFile) else {+ throw RepackError.installPathUnsafe(+ path: paths.lockFile,+ detail: "lock path was replaced during acquisition")+ }+ return InstallLock(paths: paths, descriptor: descriptor)+ } catch {+ _ = flock(descriptor, LOCK_UN)+ close(descriptor)+ throw error+ }+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/System/Posix.swift b/Sources/TurboFieldfareRepack/Core/System/Posix.swiftindex 452f3da7..4a9e19de 100644--- a/Sources/TurboFieldfareRepack/Core/System/Posix.swift+++ b/Sources/TurboFieldfareRepack/Core/System/Posix.swift@@ -4,26 +4,60 @@ import Darwin/// Thin POSIX helpers used by the writer hot path. The shapes here are picked/// so callers can stay inside tile-bounded scratch budgets without a/// Foundation `FileHandle` allocation per write.-enum Posix {- static func openRead(_ path: String) throws -> Int32 {+public enum Posix {+ public static let pageSize: Int = Int(getpagesize())++ public enum EntryKind: Hashable, Sendable {+ case absent+ case regular+ case directory+ case symlink+ case other+ }++ public static func openRead(_ path: String) throws -> Int32 {let fd = open(path, O_RDONLY)if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }return fd}- static func openCreateRW(_ path: String) throws -> Int32 {+ public static func openReadNoFollow(_ path: String) throws -> Int32 {+ let fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ return fd+ }++ public static func openCreateRW(_ path: String) throws -> Int32 {let fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0o644)if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }return fd}- static func ftruncate(_ fd: Int32, path: String, size: UInt64) throws {+ public static func openExistingRW(_ path: String) throws -> Int32 {+ let fd = open(path, O_RDWR | O_NOFOLLOW | O_CLOEXEC)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ return fd+ }++ public static func openDirectory(_ path: String) throws -> Int32 {+ let fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ return fd+ }++ public static func openLock(_ path: String) throws -> Int32 {+ let fd = open(path, O_RDWR | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ return fd+ }++ public static func ftruncate(_ fd: Int32, path: String, size: UInt64) throws {if Darwin.ftruncate(fd, off_t(size)) != 0 {throw RepackError.ftruncateFailed(path: path, errno: errno)}}- static func pwriteAll(fd: Int32, path: String,+ public static func pwriteAll(fd: Int32, path: String,buf: UnsafeRawPointer, count: Int,offset: UInt64) throws {var remaining = count@@ -41,7 +75,7 @@ enum Posix {}}- static func preadAll(fd: Int32, path: String,+ public static func preadAll(fd: Int32, path: String,buf: UnsafeMutableRawPointer, count: Int,offset: UInt64) throws {var remaining = count@@ -59,29 +93,202 @@ enum Posix {}}- static func fsync(_ fd: Int32, path: String) throws {+ public static func fsync(_ fd: Int32, path: String) throws {if Darwin.fsync(fd) != 0 {throw RepackError.fsyncFailed(path: path, errno: errno)}}- static func rename(from src: String, to dst: String) throws {+ public static func fsyncDirectory(_ path: String) throws {+ let fd = try openDirectory(path)+ defer { close(fd) }+ try fsync(fd, path: path)+ }++ public static func rename(from src: String, to dst: String) throws {if Darwin.rename(src, dst) != 0 {throw RepackError.renameFailed(from: src, to: dst, errno: errno)}}- static func mkdirP(_ path: String) throws {+ public static func renameSwap(_ first: String, _ second: String) throws {+ if renamex_np(first, second, UInt32(RENAME_SWAP)) != 0 {+ throw RepackError.promotionUnsupported(path: first, errno: errno)+ }+ }++ public static func mkdirP(_ path: String) throws {let url = URL(fileURLWithPath: path)try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)}- static func fileSize(fd: Int32, path: String) throws -> UInt64 {+ public static func physicalPath(_ path: String) throws -> String {+ guard let resolved = realpath(path, nil) else {+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ defer { free(resolved) }+ return String(cString: resolved)+ }++ public static func entryKind(_ path: String) throws -> EntryKind {+ var info = stat()+ if lstat(path, &info) != 0 {+ if errno == ENOENT { return .absent }+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ switch info.st_mode & S_IFMT {+ case S_IFREG: return .regular+ case S_IFDIR: return .directory+ case S_IFLNK: return .symlink+ default: return .other+ }+ }++ public static func atomicWrite(_ data: Data,+ to path: String,+ durableIn directory: String,+ afterRename: (() throws -> Void)? = nil) throws {+ let temporary = path + ".tmp"+ switch try entryKind(temporary) {+ case .absent:+ break+ case .regular:+ if unlink(temporary) != 0 {+ throw RepackError.fileOpenFailed(path: temporary, errno: errno)+ }+ try fsyncDirectory(directory)+ default:+ throw RepackError.installPathUnsafe(+ path: temporary,+ detail: "atomic-write temporary has the wrong type")+ }+ let fd = open(temporary, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600)+ if fd < 0 { throw RepackError.fileOpenFailed(path: temporary, errno: errno) }+ defer { close(fd) }+ do {+ try data.withUnsafeBytes { raw in+ guard let base = raw.baseAddress else { return }+ var offset = 0+ while offset < raw.count {+ let count = write(fd, base.advanced(by: offset), raw.count - offset)+ if count <= 0 {+ throw RepackError.pwriteShort(+ path: temporary,+ expected: raw.count,+ wrote: offset,+ errno: errno)+ }+ offset += count+ }+ }+ try fsync(fd, path: temporary)+ try rename(from: temporary, to: path)+ try afterRename?()+ try fsyncDirectory(directory)+ } catch {+ _ = unlink(temporary)+ throw error+ }+ }++ public static func readBoundedData(_ path: String, maximumBytes: UInt64) throws -> Data {+ let fd = open(path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)+ if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }+ defer { close(fd) }+ let size = try fileSize(fd: fd, path: path)+ guard size <= maximumBytes, size <= UInt64(Int.max) else {+ throw RepackError.installStateCorrupt(+ path: path,+ detail: "size \(size) exceeds \(maximumBytes)-byte cap")+ }+ var data = Data(count: Int(size))+ try data.withUnsafeMutableBytes { raw in+ guard let base = raw.baseAddress, !raw.isEmpty else { return }+ try preadAll(fd: fd, path: path, buf: base, count: raw.count, offset: 0)+ }+ return data+ }++ public static func fileSize(fd: Int32, path: String) throws -> UInt64 {var st = stat()if fstat(fd, &st) != 0 {throw RepackError.fileStatFailed(path: path, errno: errno)}+ guard st.st_size >= 0 else {+ throw RepackError.fileStatFailed(path: path, errno: EINVAL)+ }return UInt64(st.st_size)}+ public static func descriptorMatchesPath(_ fd: Int32, path: String) throws -> Bool {+ var descriptorInfo = stat()+ guard fstat(fd, &descriptorInfo) == 0 else {+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ var pathInfo = stat()+ guard lstat(path, &pathInfo) == 0 else {+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ return descriptorInfo.st_dev == pathInfo.st_dev+ && descriptorInfo.st_ino == pathInfo.st_ino+ && pathInfo.st_mode & S_IFMT == S_IFREG+ }++ public static func adviseDontNeed(fd: Int32, offset: UInt64, length: Int) {+ // posix_fadvise isn't available on Darwin. Use fcntl F_RDADVISE / F_NOCACHE+ // for similar hints; here we use F_NOCACHE on the fd as a coarse hint.+ // For per-range eviction we rely on madvise(MADV_DONTNEED) when the+ // range is mapped (handled in MmapHandle).+ _ = fd; _ = offset; _ = length+ }+}++/// Owns one MAP_PRIVATE, PROT_READ mapping of a file. Pages fault in on access+/// and can be evicted via `adviseDontNeed`. Designed for one shard at a time.+public final class MmapHandle {+ public let path: String+ public let fd: Int32+ public let base: UnsafeRawPointer+ public let length: Int++ public init(path: String) throws {+ self.path = path+ self.fd = try Posix.openRead(path)+ var st = stat()+ if fstat(fd, &st) != 0 {+ close(fd)+ throw RepackError.fileStatFailed(path: path, errno: errno)+ }+ let len = Int(st.st_size)+ guard let raw = mmap(nil, len, PROT_READ, MAP_PRIVATE, fd, 0),+ raw != MAP_FAILED else {+ close(fd)+ throw RepackError.mmapFailed(path: path, errno: errno)+ }+ self.base = UnsafeRawPointer(raw)+ self.length = len+ _ = posix_madvise(raw, len, POSIX_MADV_SEQUENTIAL)+ }++ deinit {+ munmap(UnsafeMutableRawPointer(mutating: base), length)+ close(fd)+ }++ public func slice(at offset: UInt64, count: Int) -> UnsafeRawBufferPointer {+ UnsafeRawBufferPointer(start: base.advanced(by: Int(offset)), count: count)+ }++ /// madvise(MADV_DONTNEED) on a region. Alignment is rounded outward so we+ /// only touch whole pages — the kernel ignores partial-page requests.+ public func adviseDontNeed(offset: UInt64, count: Int) {+ let page = UInt64(Posix.pageSize)+ let start = (offset / page) * page+ let endRaw = offset + UInt64(count)+ let end = ((endRaw + page - 1) / page) * page+ if end <= start { return }+ let len = Int(end - start)+ let addr = UnsafeMutableRawPointer(mutating: base.advanced(by: Int(start)))+ _ = posix_madvise(addr, len, POSIX_MADV_DONTNEED)+ }}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swift b/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swiftindex 7c7554d1..716d82d2 100644--- a/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swift+++ b/Sources/TurboFieldfareRepack/Core/Verification/RepackAudit.swift@@ -1,18 +1,43 @@import Foundation+import Darwin+import Darwin.Mach-/// Bounded-copy counters and file hashes used while creating a verified install.+/// Counters tracked during a repack run. Emitted to JSON via the+/// `--copy-audit` flag.public final class RepackAudit {public var sourceBytesRead: UInt64 = 0public var outputBytesWritten: UInt64 = 0public var intentionalCopyBytes: UInt64 = 0public var byteCopyTiles: UInt64 = 0public var largestScratchBytes: Int = 0+ public var wholeFileHeapBuffers: Bool = false+ public var platformMemmoveObserved: Bool = false+ public var mallocCountObserved: Int = 0+ public var bitWidthOverridesHonored: Int = 0+ public var sourceSnapshotSha256: String = ""+ public var tensorsDroppedMultimodal: [String] = []+ public var wallTimeSeconds: Double = 0+ public var peakRssBytes: UInt64 = 0public var outputFiles: [OutputFile] = []+ public var rssSamples: [UInt64] = []+ public var packedExpertLayoutMode: String = "identity"+ public var packedExpertLayoutOrderPath: String?+ public var packedExpertLayoutOrderSha256: String?+ public var packedExpertLayoutStrategy: String?+ public var packedExpertReorderedLayerCount: Int = 0+ public var packedExpertLayoutAuditLogicalIDCount: Int = 0+ public var packedExpertLayoutOffsetValidationPassed: Bool = falsepublic var remoteBytesDownloaded: UInt64 = 0+ public var remoteGapBytesDownloaded: UInt64 = 0public var remoteRangeRequests: UInt64 = 0public var remoteRangeRetries: UInt64 = 0+ public var remoteRangeStreamingSupported: Bool = falsepublic var largestRemoteTransferBytes: Int = 0public var largestRemotePayloadHeapBytes: Int = 0+ public var remoteRepoID: String?+ public var remoteRequestedRevision: String?+ public var remoteResolvedCommit: String?+ public var remoteRetries: [RemoteRetryRecord] = []public var stalePartialsRemoved: [String] = []public init() {}@@ -23,6 +48,12 @@ public final class RepackAudit {public let sha256: String}+ public struct RemoteRetryRecord {+ public let label: String+ public let attempt: Int+ public let detail: String+ }+public func recordTile(bytes: Int) {byteCopyTiles &+= 1intentionalCopyBytes &+= UInt64(bytes)@@ -36,8 +67,93 @@ public final class RepackAudit {sourceBytesRead &+= UInt64(bytes)}- public func recordRemoteRetry() {+ public func recordRemoteRetry(label: String, attempt: Int, detail: String) {remoteRangeRetries &+= 1+ remoteRetries.append(RemoteRetryRecord(label: label, attempt: attempt, detail: detail))}+ public func sampleRSS() {+ var info = task_vm_info_data_t()+ var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)+ let kr = withUnsafeMutablePointer(to: &info) {+ $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {+ task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count)+ }+ }+ if kr == KERN_SUCCESS {+ let phys = UInt64(info.phys_footprint)+ if phys > peakRssBytes { peakRssBytes = phys }+ rssSamples.append(phys)+ }+ }++ public func toJSONData(outputDir: String) throws -> Data {+ var filesArr: [[String: Any]] = []+ for f in outputFiles {+ filesArr.append([+ "path": f.relativePath,+ "size": f.size,+ "sha256": f.sha256+ ])+ }+ var retryArr: [[String: Any]] = []+ for retry in remoteRetries {+ retryArr.append([+ "label": retry.label,+ "attempt": retry.attempt,+ "detail": retry.detail+ ])+ }+ var dict: [String: Any] = [+ "output_dir": outputDir,+ "peak_rss_bytes": peakRssBytes,+ "rss_sample_count": rssSamples.count,+ "source_bytes_read": sourceBytesRead,+ "output_bytes_written": outputBytesWritten,+ "intentional_copy_bytes": intentionalCopyBytes,+ "byte_copy_tiles": byteCopyTiles,+ "largest_scratch_bytes": largestScratchBytes,+ "whole_file_heap_buffers": wholeFileHeapBuffers,+ "platform_memmove_observed": platformMemmoveObserved,+ "malloc_count_observed": mallocCountObserved,+ "bit_width_overrides_honored": bitWidthOverridesHonored,+ "source_snapshot_sha256": sourceSnapshotSha256,+ "tensors_dropped_multimodal": tensorsDroppedMultimodal,+ "wall_time_s": wallTimeSeconds,+ "packed_expert_layout_mode": packedExpertLayoutMode,+ "packed_expert_reordered_layer_count": packedExpertReorderedLayerCount,+ "packed_expert_layout_audit_logical_id_count": packedExpertLayoutAuditLogicalIDCount,+ "packed_expert_layout_offset_validation_passed": packedExpertLayoutOffsetValidationPassed,+ "remote_bytes_downloaded": remoteBytesDownloaded,+ "remote_gap_bytes_downloaded": remoteGapBytesDownloaded,+ "remote_range_requests": remoteRangeRequests,+ "remote_range_retries": remoteRangeRetries,+ "remote_range_streaming_supported": remoteRangeStreamingSupported,+ "largest_remote_transfer_bytes": largestRemoteTransferBytes,+ "largest_remote_payload_heap_bytes": largestRemotePayloadHeapBytes,+ "remote_retries": retryArr,+ "stale_partials_removed": stalePartialsRemoved,+ "output_files": filesArr+ ]+ if let packedExpertLayoutOrderPath {+ dict["packed_expert_layout_order_path"] = packedExpertLayoutOrderPath+ }+ if let packedExpertLayoutOrderSha256 {+ dict["packed_expert_layout_order_sha256"] = packedExpertLayoutOrderSha256+ }+ if let packedExpertLayoutStrategy {+ dict["packed_expert_layout_strategy"] = packedExpertLayoutStrategy+ }+ if let remoteRepoID {+ dict["remote_repo_id"] = remoteRepoID+ }+ if let remoteRequestedRevision {+ dict["remote_requested_revision"] = remoteRequestedRevision+ }+ if let remoteResolvedCommit {+ dict["remote_resolved_commit"] = remoteResolvedCommit+ }+ return try JSONSerialization.data(withJSONObject: dict,+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])+ }}diff --git a/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift b/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swiftindex 9b5187df..2b41e18f 100644--- a/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift+++ b/Sources/TurboFieldfareRepack/Core/Verification/Sha256Stream.swift@@ -22,8 +22,10 @@ struct Sha256Stream {/// for fingerprinting `model.safetensors.index.json`.static func hashFile(path: String,tileBytes: Int = 65_536,- noCache: Bool = false) throws -> String {- let fd = open(path, O_RDONLY)+ noCache: Bool = false,+ noFollow: Bool = false) throws -> String {+ let flags = O_RDONLY | (noFollow ? O_NOFOLLOW : 0)+ let fd = open(path, flags)if fd < 0 { throw RepackError.fileOpenFailed(path: path, errno: errno) }defer { close(fd) }if noCache {diff --git a/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swiftindex b548ee0d..fe3dba66 100644--- a/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift+++ b/Sources/TurboFieldfareRepack/Core/Verification/VerifiedInstallTool.swift@@ -65,6 +65,13 @@ public enum VerifiedInstallTool {unexpectedEntries: unexpectedEntries)}+ static func validatePackedExpertLayout(inputGTurbo: String) throws {+ let root = URL(fileURLWithPath: inputGTurbo).standardizedFileURL+ let manifest = try loadManifest(+ path: root.appendingPathComponent("manifest.json").path)+ try validatePackedExpertLayout(root: root, manifest: manifest)+ }+private struct ManifestFileEntry: Decodable {let size: UInt64let sha256: Stringdiff --git a/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift b/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swiftindex e52a5646..607e7bfc 100644--- a/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift+++ b/Sources/TurboFieldfareRepack/Core/Workflow/Errors.swift@@ -10,6 +10,12 @@ public enum RepackError: Error, CustomStringConvertible {case renameFailed(from: String, to: String, errno: Int32)case fsyncFailed(path: String, errno: Int32)case mkdirFailed(path: String, errno: Int32)+ case installBusy(path: String)+ case installPathUnsafe(path: String, detail: String)+ case installStateMissing(path: String)+ case installStateCorrupt(path: String, detail: String)+ case installStateIncompatible(detail: String)+ case promotionUnsupported(path: String, errno: Int32)case safetensorsHeaderTooLarge(path: String, size: UInt64)case safetensorsHeaderInvalid(path: String, detail: String)@@ -31,6 +37,11 @@ public enum RepackError: Error, CustomStringConvertible {case remoteProtocolInvalid(detail: String)case remoteHTTPStatus(url: String, status: Int)+ case remoteHTTPResponse(url: String, status: Int, retryAfter: String?)+ case remoteBodyTruncated(path: String, expected: UInt64, actual: UInt64)+ case remoteBodyExceeded(path: String, limit: UInt64, attempted: UInt64)+ case remoteRedirectRejected(url: String, detail: String)+ case remoteRetryDelayExceeded(value: String, capSeconds: UInt64)case remoteFileTooLarge(path: String, size: UInt64, cap: UInt64)case diskSpaceInsufficient(path: String, required: UInt64, available: UInt64)@@ -51,6 +62,18 @@ public enum RepackError: Error, CustomStringConvertible {case .renameFailed(let a, let b, let e):return "rename(\(a) -> \(b)) failed: errno \(e)"case .fsyncFailed(let p, let e): return "fsync(\(p)) failed: errno \(e)"case .mkdirFailed(let p, let e): return "mkdir(\(p)) failed: errno \(e)"+ case .installBusy(let p):+ return "another installer holds \(p)"+ case .installPathUnsafe(let p, let d):+ return "unsafe installer path \(p): \(d)"+ case .installStateMissing(let p):+ return "no resumable install state exists for \(p)"+ case .installStateCorrupt(let p, let d):+ return "install state at \(p) is corrupt: \(d)"+ case .installStateIncompatible(let d):+ return "install state is incompatible: \(d)"+ case .promotionUnsupported(let p, let e):+ return "atomic directory promotion is unsupported for \(p): errno \(e)"case .safetensorsHeaderTooLarge(let p, let s):return "safetensors header at \(p) size \(s) exceeds bound"case .safetensorsHeaderInvalid(let p, let d):@@ -75,6 +98,19 @@ public enum RepackError: Error, CustomStringConvertible {return "remote protocol invalid: \(d)"case .remoteHTTPStatus(let u, let s):return "remote HTTP \(s): \(u)"+ case .remoteHTTPResponse(let u, let s, let retryAfter):+ if let retryAfter {+ return "remote HTTP \(s): \(u), Retry-After \(retryAfter)"+ }+ return "remote HTTP \(s): \(u)"+ case .remoteBodyTruncated(let p, let e, let a):+ return "remote body for \(p) was truncated: expected \(e), received \(a)"+ case .remoteBodyExceeded(let p, let l, let a):+ return "remote body for \(p) exceeded \(l) bytes at \(a) bytes"+ case .remoteRedirectRejected(let u, let d):+ return "remote redirect rejected for \(u): \(d)"+ case .remoteRetryDelayExceeded(let v, let c):+ return "remote Retry-After \(v) exceeds \(c)-second cap"case .remoteFileTooLarge(let p, let s, let c):return "remote file \(p) size \(s) exceeds cap \(c)"case .diskSpaceInsufficient(let p, let r, let a):diff --git a/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swift b/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swiftindex 98a5d908..4835dc00 100644--- a/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swift+++ b/Sources/TurboFieldfareRepack/Core/Workflow/ModelInstallProgress.swift@@ -5,7 +5,11 @@ public enum ModelInstallProgress: Equatable, Sendable {case planning(downloadBytes: UInt64, outputBytes: UInt64)case checkingDisk(DiskSpaceRequirement)case reservingOutput(bytes: UInt64)- case copyingPayload(downloadedBytes: UInt64, totalBytes: UInt64)+ case copyingPayload(+ reusedBytes: UInt64,+ downloadedThisRunBytes: UInt64,+ totalBytes: UInt64+ )case hashingOutput(String)case finalizing}diff --git a/Sources/TurboFieldfareRepack/Core/Writing/BoundedScratch.swift b/Sources/TurboFieldfareRepack/Core/Writing/BoundedScratch.swiftnew file mode 100644index 00000000..c45be2ed--- /dev/null+++ b/Sources/TurboFieldfareRepack/Core/Writing/BoundedScratch.swift@@ -0,0 +1,53 @@+import Foundation++/// Per-worker scratch buffer with a hard upper bound. Calls beyond the bound+/// throw rather than silently grow — the M1a copy budget caps per-worker+/// staging well under 1 MB.+public final class BoundedScratch {+ public static let defaultLimitBytes: Int = 1_048_576 - 1 // strictly under 1 MB++ public let limitBytes: Int+ public private(set) var largestEverBytes: Int = 0++ private var buffer: UnsafeMutableRawBufferPointer++ public init(limitBytes: Int = BoundedScratch.defaultLimitBytes) {+ self.limitBytes = limitBytes+ // Page-aligned starting size for the all-zero buffer we keep around for+ // hashing gap regions. 16 KB is arm64 page size; reading zero bytes+ // straight from this static avoids touching the bigger working buffer.+ let initial = 16_384+ self.buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: initial,+ alignment: 16_384)+ self.buffer.initializeMemory(as: UInt8.self, repeating: 0)+ self.largestEverBytes = initial+ }++ deinit { buffer.deallocate() }++ /// Grow the scratch to at least `byteCount` if needed. Returns the+ /// guaranteed-zeroed buffer.+ @discardableResult+ public func ensure(_ byteCount: Int) throws -> UnsafeMutableRawBufferPointer {+ if byteCount > limitBytes {+ throw RepackError.scratchExceeded(requested: byteCount, limit: limitBytes)+ }+ if byteCount <= buffer.count { return buffer }+ let newCount = max(byteCount, buffer.count * 2)+ let bounded = min(newCount, limitBytes)+ if bounded < byteCount {+ throw RepackError.scratchExceeded(requested: byteCount, limit: limitBytes)+ }+ let newBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: bounded,+ alignment: 16_384)+ newBuf.initializeMemory(as: UInt8.self, repeating: 0)+ buffer.deallocate()+ buffer = newBuf+ if bounded > largestEverBytes { largestEverBytes = bounded }+ return buffer+ }++ public var zeroBuffer: UnsafeRawBufferPointer {+ UnsafeRawBufferPointer(start: buffer.baseAddress, count: buffer.count)+ }+}diff --git a/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swift b/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swiftindex a478352f..99935806 100644--- a/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swift+++ b/Sources/TurboFieldfareRepack/Core/Writing/ResidentWriter.swift@@ -1,12 +1,54 @@import Foundationimport Darwin-/// Creates the resident LM `.bin` file and writes its bounded binary index.+/// Writes the resident LM `.bin` file (`model_weights.bin`).+/// from a planned layout + a shard registry. Shards are mapped one at a time;+/// per-tensor writes go straight from mmap'd source memory through pwrite+/// tiles, with `madvise(MADV_DONTNEED)` after each tile.enum ResidentWriter {- private static let maxIndexBytes = 1_048_575++ static func write(plan: ResidentFilePlan,+ shardsByPath: inout [String: MmapHandle],+ audit: RepackAudit) throws -> RepackAudit.OutputFile {+ // 1. Create + size the output file.+ try Posix.mkdirP(((plan.path as NSString).deletingLastPathComponent))+ let fd = try Posix.openCreateRW(plan.path)+ defer { close(fd) }+ try Posix.ftruncate(fd, path: plan.path, size: plan.totalSize)++ // 2. Write the binary index page: header + entries + string table.+ try writeIndex(plan: plan, fd: fd, audit: audit)++ // 3. For each entry, copy the weight + scales + biases from the source+ // shards in tile-bounded pwrites.+ for e in plan.entries {+ try copyOne(srcTensor: e.sourceWeight, dstFd: fd, dstPath: plan.path,+ dstOffset: e.fileOffset, sizeBytes: e.sizeBytes,+ shardsByPath: &shardsByPath, audit: audit)+ if let scales = e.sourceScales {+ try copyOne(srcTensor: scales, dstFd: fd, dstPath: plan.path,+ dstOffset: e.scaleOffset, sizeBytes: e.scaleSize,+ shardsByPath: &shardsByPath, audit: audit)+ }+ if let biases = e.sourceBiases {+ try copyOne(srcTensor: biases, dstFd: fd, dstPath: plan.path,+ dstOffset: e.biasOffset, sizeBytes: e.biasSize,+ shardsByPath: &shardsByPath, audit: audit)+ }+ }++ try Posix.fsync(fd, path: plan.path)+ let size = try Posix.fileSize(fd: fd, path: plan.path)+ // 4. Hash the finished file by streaming.+ let sha = try WriterCore.hashEntireFile(path: plan.path, size: size, audit: audit)+ let rel = (plan.path as NSString).lastPathComponent+ let outFile = RepackAudit.OutputFile(relativePath: rel, size: size, sha256: sha)+ audit.outputFiles.append(outFile)+ return outFile+ }static func createAndWriteIndex(plan: ResidentFilePlan,- audit: RepackAudit) throws -> Int32 {+ audit: RepackAudit) throws -> Int32 {try Posix.mkdirP(((plan.path as NSString).deletingLastPathComponent))let fd = try Posix.openCreateRW(plan.path)do {@@ -19,30 +61,21 @@ enum ResidentWriter {}}- private static func writeIndex(plan: ResidentFilePlan,- fd: Int32,- audit: RepackAudit) throws {- // The header region size is bounded by indexSize (a few KB); allocate- // it once on the heap and pwrite once. Well under any reasonable budget.+ static func encodeIndex(plan: ResidentFilePlan) throws -> Data {let idxBytes = Int(plan.indexSize)+ guard idxBytes <= BoundedScratch.defaultLimitBytes else {+ throw RepackError.scratchExceeded(requested: idxBytes,+ limit: BoundedScratch.defaultLimitBytes)+ }let idxBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: idxBytes,alignment: 16_384)defer { idxBuf.deallocate() }idxBuf.initializeMemory(as: UInt8.self, repeating: 0)- if idxBytes > audit.largestScratchBytes {- // The index page is bounded by the planner; fail instead of- // allowing this one-shot allocation to reach 1 MiB.- if idxBytes > maxIndexBytes {- throw RepackError.scratchExceeded(requested: idxBytes,- limit: maxIndexBytes)- }- audit.largestScratchBytes = idxBytes- }GTurboBinary.writeIndexHeader(into: idxBuf.baseAddress!,indexSize: plan.indexSize,residentSize: plan.residentSize,entryCount: UInt64(plan.entries.count))- let entriesBase = GTurboBinary.indexHeaderBytes+ let entriesBase = 24let stringTableBase = entriesBase + plan.entries.count * GTurboBinary.indexEntryBytesfor i in 0..<plan.entries.count {let dst = idxBuf.baseAddress!.advanced(by: entriesBase + i * GTurboBinary.indexEntryBytes)@@ -53,9 +86,44 @@ enum ResidentWriter {let dst = idxBuf.baseAddress!.advanced(by: stringTableBase)memcpy(dst, src.baseAddress!, src.count)}- try Posix.pwriteAll(fd: fd, path: plan.path,- buf: idxBuf.baseAddress!, count: idxBytes, offset: 0)+ return Data(bytes: idxBuf.baseAddress!, count: idxBytes)+ }++ private static func writeIndex(plan: ResidentFilePlan,+ fd: Int32,+ audit: RepackAudit) throws {+ let data = try encodeIndex(plan: plan)+ let idxBytes = data.count+ if idxBytes > audit.largestScratchBytes {+ audit.largestScratchBytes = idxBytes+ }+ try data.withUnsafeBytes { raw in+ guard let base = raw.baseAddress else { return }+ try Posix.pwriteAll(fd: fd, path: plan.path,+ buf: base, count: idxBytes, offset: 0)+ }audit.recordWrite(bytes: idxBytes)}+ private static func copyOne(srcTensor: SourceTensor,+ dstFd: Int32, dstPath: String, dstOffset: UInt64,+ sizeBytes: UInt64,+ shardsByPath: inout [String: MmapHandle],+ audit: RepackAudit) throws {+ let shard = try mappedShard(path: srcTensor.shardPath, shardsByPath: &shardsByPath)+ try WriterCore.pwriteTensorRegion(srcShard: shard,+ srcAbsoluteOffset: srcTensor.absoluteOffset,+ size: sizeBytes,+ dstFd: dstFd, dstPath: dstPath,+ dstOffset: dstOffset,+ audit: audit)+ }++ private static func mappedShard(path: String,+ shardsByPath: inout [String: MmapHandle]) throws -> MmapHandle {+ if let h = shardsByPath[path] { return h }+ let h = try MmapHandle(path: path)+ shardsByPath[path] = h+ return h+ }}diff --git a/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swift b/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swiftindex 09dcf566..a00cddf8 100644--- a/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swift+++ b/Sources/TurboFieldfareRepack/Core/Writing/WriterCore.swift@@ -2,16 +2,44 @@ import Foundationimport Darwin/// Shared building blocks for the resident LM and routed-expert layer writers.-enum WriterCore {+public enum WriterCore {/// Tile size for pwrite (and the subsequent SHA-256 hashing pass). Chosen- /// so per-worker scratch and per-syscall payload both stay well under 1 MB.- static let tileBytes: Int = 512 * 1024+ /// so per-worker scratch and per-syscall payload both stay well under+ /// the 1 MB BoundedScratch budget.+ public static let tileBytes: Int = 512 * 1024++ /// Copy `size` bytes from `srcShard.base + srcOffset` to file `dstFd` at+ /// `dstOffset`, in pwrite-sized tiles. Pages consumed from the source map+ /// are evicted via madvise after each tile, capping the source-side RSS.+ public static func pwriteTensorRegion(srcShard: MmapHandle,+ srcAbsoluteOffset: UInt64,+ size: UInt64,+ dstFd: Int32, dstPath: String,+ dstOffset: UInt64,+ audit: RepackAudit) throws {+ var remaining = Int(size)+ var srcOff = srcAbsoluteOffset+ var dstOff = dstOffset+ let tile = WriterCore.tileBytes+ while remaining > 0 {+ let n = min(remaining, tile)+ let p = srcShard.base.advanced(by: Int(srcOff))+ try Posix.pwriteAll(fd: dstFd, path: dstPath, buf: p, count: n, offset: dstOff)+ audit.recordTile(bytes: n)+ audit.recordWrite(bytes: n)+ audit.recordRead(bytes: n)+ srcShard.adviseDontNeed(offset: srcOff, count: n)+ srcOff += UInt64(n)+ dstOff += UInt64(n)+ remaining -= n+ }+ }/// Compute SHA-256 of an entire (presumed-written) file by streaming it/// through `tileBytes` pread chunks. Drops pages with `F_NOCACHE` style/// behaviour via fcntl. Allocates one bounded scratch buffer.- static func hashEntireFile(path: String, size: UInt64,+ public static func hashEntireFile(path: String, size: UInt64,audit: RepackAudit,cancellationCheck: () throws -> Void = {}) throws -> String {let fd = try Posix.openRead(path)diff --git a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swiftindex bba3194d..e3889a1b 100644--- a/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/AppModelInstallTests.swift@@ -110,7 +110,10 @@ import TurboFieldfareRepackCorelet installer = MockModelInstallerClient(events: [.checking,- .copyingPayload(doneBytes: 4, totalBytes: 10),+ .copyingPayload(+ reusedBytes: 1,+ downloadedThisRunBytes: 3,+ totalBytes: 10),], holdOpen: true)let model = AppModel(modelDirectory: directory,@@ -118,7 +121,12 @@ import TurboFieldfareRepackCoreinstaller: installer)model.installModel()- try await waitUntil { model.installState == .copyingPayload(doneBytes: 4, totalBytes: 10) }+ try await waitUntil {+ model.installState == .copyingPayload(+ reusedBytes: 1,+ downloadedThisRunBytes: 3,+ totalBytes: 10)+ }#expect(model.installDownloadedBytes == 4)#expect(model.installTotalBytes == 10)#expect(model.installProgressFraction == 0.4)@@ -170,6 +178,91 @@ import TurboFieldfareRepackCore#expect(client.ensureLoadedCallCount() == 0)}+ @MainActor+ @Test func networkFailureWithSavedProgressLeavesResumeEnabled() async throws {+ struct NetworkFailure: Error {}+ let directory = temporaryInstallPath("network-resume")+ let paths = try makeSavedDownload(at: directory)+ defer { cleanUpSavedDownload(paths) }+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(failure: NetworkFailure()))++ model.installModel()+ try await waitUntil {+ if case .recoverable = model.installState { return true }+ return false+ }++ #expect(model.canInstallModel)+ #expect(model.canDiscardModelDownload)+ }++ @MainActor+ @Test func diskFailureCanResumeAfterSpaceRecheck() async throws {+ let directory = temporaryInstallPath("disk-resume")+ let paths = try makeSavedDownload(at: directory)+ defer { cleanUpSavedDownload(paths) }+ let error = RepackError.diskSpaceInsufficient(+ path: "/volume",+ required: 120,+ available: 45)+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: MockModelInstallerClient(failure: error))++ model.installModel()+ try await waitUntil {+ if case .recoverable = model.installState { return true }+ return false+ }+ #expect(!model.canInstallModel)++ model.recheckModelAtCurrentLocation()++ #expect(model.canInstallModel)+ #expect(model.canDiscardModelDownload)+ }++ @MainActor+ @Test func invalidSavedDownloadsRemainDiscardOnly() throws {+ let descriptor = AppModelInstallDescriptor.default+ for incompatible in [false, true] {+ let directory = temporaryInstallPath(+ incompatible ? "incompatible-checkpoint" : "corrupt-checkpoint")+ let paths = try makeSavedDownload(at: directory)+ defer { cleanUpSavedDownload(paths) }+ if incompatible {+ try RemoteInstallCheckpoint(+ repoID: "other/model",+ requestedRevision: descriptor.revision,+ resolvedCommit: String(repeating: "a", count: 40),+ sourceIndexSHA256: String(repeating: "b", count: 64),+ planFingerprint: String(repeating: "c", count: 64),+ totalSourceBytes: 1+ ).write(+ to: paths.checkpointFile,+ parentDirectory: paths.parentDirectory)+ } else {+ try Data("{}".utf8).write(+ to: URL(fileURLWithPath: paths.checkpointFile))+ }+ let model = AppModel(+ modelDirectory: directory,+ client: MockLifecycleInferenceClient(),+ installer: RepackModelInstallerClient(descriptor: descriptor))++ #expect(!model.canInstallModel)+ #expect(model.canDiscardModelDownload)+ guard case .failed = model.installReadiness else {+ Issue.record("invalid checkpoint did not fail readiness")+ continue+ }+ }+ }+@MainActor@Test func diskFailureKeepsExactRequirementAndShortfall() async throws {let error = RepackError.diskSpaceInsufficient(@@ -198,7 +291,10 @@ import TurboFieldfareRepackCore@MainActor@Test func cancelInstallWaitsForAcknowledgementAndAllowsRetry() async throws {- let installer = MockModelInstallerClient(events: [.downloadingMetadata], holdOpen: true)+ let installer = MockModelInstallerClient(+ events: [.downloadingMetadata],+ holdOpen: true,+ delayCancellationAcknowledgement: true)let model = AppModel(modelDirectory: temporaryInstallPath("cancel"),client: MockLifecycleInferenceClient(),@@ -208,7 +304,11 @@ import TurboFieldfareRepackCoremodel.cancelInstall()#expect(installer.cancelCalled)- #expect(model.installState == .cancelling || model.installState == .cancelled)+ try await waitUntil { installer.cancellationAcknowledgementPending }+ #expect(model.installState == .cancelling)+ #expect(!model.canInstallModel)++ await installer.releaseCancellationAcknowledgement()try await waitUntil { model.installState == .cancelled }#expect(model.loadState == .notLoaded)@@ -220,6 +320,25 @@ import TurboFieldfareRepackCore.appendingPathComponent("turbofieldfare-app-install-\(tag)-\(UUID().uuidString).gturbo")}+ private func makeSavedDownload(at directory: URL) throws -> RemoteInstallPaths {+ let paths = try RemoteInstallPaths(outputDirectory: directory.path)+ try FileManager.default.createDirectory(+ atPath: paths.partialDirectory,+ withIntermediateDirectories: true)+ return paths+ }++ private func cleanUpSavedDownload(_ paths: RemoteInstallPaths) {+ for path in [+ paths.finalDirectory,+ paths.partialDirectory,+ paths.checkpointFile,+ paths.lockFile,+ ] {+ try? FileManager.default.removeItem(atPath: path)+ }+ }+@MainActorprivate func waitUntil(_ predicate: @escaping @MainActor () -> Bool) async throws {for _ in 0..<200 {diff --git a/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swift b/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swiftnew file mode 100644index 00000000..d26fcdbb--- /dev/null+++ b/Tests/TurboFieldfareApp/Core/Installation/DownloadETAEstimatorTests.swift@@ -0,0 +1,45 @@+import Testing++@testable import TurboFieldfareAppCore++@Suite+struct DownloadETAEstimatorTests {+ @Test func warmsUpAndIgnoresReusedBytesForRate() {+ var estimator = DownloadETAEstimator()+ #expect(estimator.update(+ .init(reusedBytes: 500, downloadedThisRunBytes: 0, totalBytes: 1_000),+ timestamp: 0) == .estimating)++ let result = estimator.update(+ .init(+ reusedBytes: 500,+ downloadedThisRunBytes: 100 * 1024 * 1024,+ totalBytes: 500 + 200 * 1024 * 1024),+ timestamp: 10)+ guard case .remaining(let seconds) = result else {+ Issue.record("expected an ETA")+ return+ }+ #expect(seconds > 9 && seconds < 11)+ }++ @Test func smallChangesKeepTheVisibleEstimateStable() {+ var estimator = DownloadETAEstimator()+ let mib = UInt64(1024 * 1024)+ _ = estimator.update(+ .init(reusedBytes: 0, downloadedThisRunBytes: 0, totalBytes: 600 * mib),+ timestamp: 0)+ let first = estimator.update(+ .init(reusedBytes: 0, downloadedThisRunBytes: 100 * mib, totalBytes: 600 * mib),+ timestamp: 10)+ let second = estimator.update(+ .init(reusedBytes: 0, downloadedThisRunBytes: 210 * mib, totalBytes: 600 * mib),+ timestamp: 41)+ #expect(first == second)+ }++ @Test func formatterUsesCoarseMinuteBuckets() {+ #expect(DownloadETAFormatter.remainingString(390) == "About 7 min remaining")+ #expect(DownloadETAFormatter.remainingString(410) == "About 7 min remaining")+ }+}diff --git a/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swift b/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swiftindex aa87b95e..5b85c3f7 100644--- a/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swift+++ b/Tests/TurboFieldfareApp/Core/Installation/RepackModelInstallerClientTests.swift@@ -15,7 +15,10 @@ import TestingrequiredBytes: 30,availableBytes: 40)))progress(.reservingOutput(bytes: 20))- progress(.copyingPayload(downloadedBytes: 4, totalBytes: 10))+ progress(.copyingPayload(+ reusedBytes: 1,+ downloadedThisRunBytes: 3,+ totalBytes: 10))progress(.hashingOutput("model_weights.bin"))progress(.finalizing)return outputDirectory@@ -32,7 +35,10 @@ import Testing.planning,.checking,.reservingOutput,- .copyingPayload(doneBytes: 4, totalBytes: 10),+ .copyingPayload(+ reusedBytes: 1,+ downloadedThisRunBytes: 3,+ totalBytes: 10),.hashingOutput("model_weights.bin"),.finalizing,.installed(output.standardizedFileURL),@@ -63,6 +69,72 @@ import Testingtry await consume.value}}++ @Test func rejectsUInt64MaxCheckpointDestinationBytes() throws {+ try expectCorruptCheckpoint(destinationBytes: [UInt64.max])+ }++ @Test func rejectsCheckpointDestinationByteOverflow() throws {+ try expectCorruptCheckpoint(destinationBytes: [UInt64.max, 1])+ }++ @Test func rejectsCheckpointDestinationBytesAboveInstalledModel() throws {+ try expectCorruptCheckpoint(destinationBytes: [101])+ }++ private func expectCorruptCheckpoint(destinationBytes: [UInt64]) throws {+ let descriptor = AppModelInstallDescriptor(+ displayName: "Test",+ repoID: "owner/model",+ revision: "main",+ sourceIndexSHA256: String(repeating: "b", count: 64),+ approximateDownloadBytes: 100,+ installedBytes: 100,+ rangeStagingBytes: 0,+ reserveBytes: 0)+ let output = FileManager.default.temporaryDirectory+ .appendingPathComponent("checkpoint-bytes-\(UUID().uuidString).gturbo")+ let paths = try RemoteInstallPaths(outputDirectory: output.path)+ defer {+ for path in [+ paths.partialDirectory,+ paths.checkpointFile,+ paths.lockFile,+ ] {+ try? FileManager.default.removeItem(atPath: path)+ }+ }+ try FileManager.default.createDirectory(+ atPath: paths.partialDirectory,+ withIntermediateDirectories: true)+ let checkpoint = RemoteInstallCheckpoint(+ repoID: descriptor.repoID,+ requestedRevision: descriptor.revision,+ resolvedCommit: String(repeating: "a", count: 40),+ sourceIndexSHA256: descriptor.sourceIndexSHA256,+ planFingerprint: String(repeating: "c", count: 64),+ totalSourceBytes: UInt64(destinationBytes.count),+ completedRanges: destinationBytes.enumerated().map { index, bytes in+ RemoteCompletedRange(+ id: "range-\(index)",+ destinationDigest: String(repeating: "d", count: 64),+ sourceBytes: 1,+ destinationBytes: bytes)+ })+ try JSONEncoder().encode(checkpoint).write(+ to: URL(fileURLWithPath: paths.checkpointFile))+ let client = RepackModelInstallerClient(descriptor: descriptor)++ do {+ _ = try client.checkInstallRequirement(outputDirectory: output)+ Issue.record("invalid checkpoint byte total was accepted")+ } catch let error as RepackError {+ guard case .installStateCorrupt = error else {+ Issue.record("expected installStateCorrupt, got \(error)")+ return+ }+ }+ }}private final class Flag: Sendable {diff --git a/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift b/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swiftindex fc75a078..6a3bfb43 100644--- a/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift+++ b/Tests/TurboFieldfareApp/Core/State/AppPresentationStateTests.swift@@ -63,7 +63,7 @@ import Testingsnapshot.installState = .cancellingcases.append((snapshot, "Cancelling installation", true))snapshot.installState = .cancelled- cases.append((snapshot, "Installation cancelled", false))+ cases.append((snapshot, "Download paused", false))snapshot.installState = .failed("network")cases.append((snapshot, "Installation failed", false))diff --git a/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swift b/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swiftindex e5ebc5aa..d060d1bc 100644--- a/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swift+++ b/Tests/TurboFieldfareApp/Core/Support/MockModelInstallerClient.swift@@ -8,16 +8,24 @@ final class MockModelInstallerClient: AppModelInstallerClient, Sendable {let holdOpen: Boollet requirement: AppModelInstallRequirementlet descriptor: AppModelInstallDescriptor+ let delayCancellationAcknowledgement: Boolprivate struct State {var task: Task<Void, Never>?var cancelCalled = false+ var cancellationAcknowledgementPending = false+ var discardCalled = false}private final class TaskState: Sendable {let value = Mutex(State())}private let taskState = TaskState()+ private let cancellationAcknowledgementGate = MockAsyncGate()var cancelCalled: Bool { taskState.value.withLock { $0.cancelCalled } }+ var cancellationAcknowledgementPending: Bool {+ taskState.value.withLock { $0.cancellationAcknowledgementPending }+ }+ var discardCalled: Bool { taskState.value.withLock { $0.discardCalled } }init(events: [AppModelInstallEvent] = [],failure: Error? = nil,@@ -25,12 +33,14 @@ final class MockModelInstallerClient: AppModelInstallerClient, Sendable {requiredBytes: 1,availableBytes: UInt64.max),descriptor: AppModelInstallDescriptor = .default,- holdOpen: Bool = false) {+ holdOpen: Bool = false,+ delayCancellationAcknowledgement: Bool = false) {self.events = eventsself.failure = failureself.requirement = requirementself.descriptor = descriptorself.holdOpen = holdOpen+ self.delayCancellationAcknowledgement = delayCancellationAcknowledgement}func checkInstallRequirement(outputDirectory: URL) throws -> AppModelInstallRequirement {@@ -42,6 +52,8 @@ final class MockModelInstallerClient: AppModelInstallerClient, Sendable {let events = self.eventslet failure = self.failurelet holdOpen = self.holdOpen+ let delayCancellationAcknowledgement = self.delayCancellationAcknowledgement+ let cancellationAcknowledgementGate = self.cancellationAcknowledgementGatelet task = Task {do {for event in events {@@ -58,6 +70,15 @@ final class MockModelInstallerClient: AppModelInstallerClient, Sendable {continuation.finish()}} catch is CancellationError {+ if delayCancellationAcknowledgement {+ taskState.value.withLock {+ $0.cancellationAcknowledgementPending = true+ }+ await cancellationAcknowledgementGate.wait()+ taskState.value.withLock {+ $0.cancellationAcknowledgementPending = false+ }+ }continuation.finish(throwing: CancellationError())} catch {continuation.finish(throwing: error)@@ -81,4 +102,33 @@ final class MockModelInstallerClient: AppModelInstallerClient, Sendable {}task?.cancel()}++ func releaseCancellationAcknowledgement() async {+ await cancellationAcknowledgementGate.open()+ }++ func discardPartialInstall(outputDirectory: URL) async throws {+ taskState.value.withLock { $0.discardCalled = true }+ }+}++private actor MockAsyncGate {+ private var isOpen = false+ private var waiters: [CheckedContinuation<Void, Never>] = []++ func wait() async {+ guard !isOpen else { return }+ await withCheckedContinuation { continuation in+ waiters.append(continuation)+ }+ }++ func open() {+ isOpen = true+ let pending = waiters+ waiters.removeAll()+ for waiter in pending {+ waiter.resume()+ }+ }}diff --git a/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swift b/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swiftnew file mode 100644index 00000000..fec5a75e--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Command/RepackCLITests.swift@@ -0,0 +1,80 @@+import Foundation+import Testing++@Suite(.serialized)+struct RepackCLITests {+ @Test func resumeAndDiscardAreMutuallyExclusive() throws {+ let output = temporaryOutput("exclusive")+ defer { clean(output) }+ let result = try run([+ "--output", output,+ "--resume",+ "--discard-partial",+ ])++ #expect(result.status == 2)+ #expect(result.stderr.contains("mutually exclusive"))+ }++ @Test func resumeWithoutStateFailsBeforeNetwork() throws {+ let output = temporaryOutput("missing-resume")+ defer { clean(output) }+ let result = try run([+ "--output", output,+ "--resume",+ ])++ #expect(result.status == 1)+ #expect(result.stderr.contains("no resumable install state exists"))+ }++ @Test func discardWithoutStateReportsAnError() throws {+ let output = temporaryOutput("missing-discard")+ defer { clean(output) }+ let result = try run([+ "--discard-partial",+ "--output", output,+ ])++ #expect(result.status == 1)+ #expect(result.stderr.contains("no resumable install state exists"))+ }++ private func run(_ arguments: [String]) throws+ -> (status: Int32, stdout: String, stderr: String) {+ let executable = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)+ .appendingPathComponent(".build/debug/TurboFieldfareRepack")+ let process = Process()+ let stdout = Pipe()+ let stderr = Pipe()+ process.executableURL = executable+ process.arguments = arguments+ process.standardOutput = stdout+ process.standardError = stderr+ try process.run()+ process.waitUntilExit()+ let out = stdout.fileHandleForReading.readDataToEndOfFile()+ let err = stderr.fileHandleForReading.readDataToEndOfFile()+ return (+ process.terminationStatus,+ String(decoding: out, as: UTF8.self),+ String(decoding: err, as: UTF8.self))+ }++ private func temporaryOutput(_ tag: String) -> String {+ (NSTemporaryDirectory() as NSString)+ .appendingPathComponent("turbofieldfare-cli-\(tag)-\(UUID().uuidString).gturbo")+ }++ private func clean(_ output: String) {+ for path in [+ output,+ output + ".partial",+ output + ".install-state",+ output + ".install-state.cleanup",+ output + ".install.lock",+ ] {+ try? FileManager.default.removeItem(atPath: path)+ }+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swift b/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swiftnew file mode 100644index 00000000..9200a955--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Planning/RangeCopyPlannerTests.swift@@ -0,0 +1,121 @@+import Darwin+import Foundation+import Testing+@testable import TurboFieldfareRepackCore++@Suite+struct RangeCopyPlannerTests {+ @Test func canonicalFingerprintDoesNotDependOnAbsoluteOutputRoot() throws {+ let snapshotDirectory = temporaryRoot("snapshot")+ let firstOutput = temporaryRoot("first")+ let secondOutput = temporaryRoot("second")+ defer {+ try? FileManager.default.removeItem(atPath: snapshotDirectory)+ try? FileManager.default.removeItem(atPath: firstOutput)+ try? FileManager.default.removeItem(atPath: secondOutput)+ }+ let snapshot = try SyntheticSnapshot.build(+ at: snapshotDirectory,+ seed: 0x1020_3040)+ let metadata = try IndexLoader.load(snapshotDir: snapshotDirectory)+ let arch = try ArchInfo.load(+ configPath: (snapshotDirectory as NSString).appendingPathComponent("config.json"))+ let header = try parseHeader(path: snapshot.shardPath)+ let firstPlan = try RepackPlanner.plan(+ meta: metadata,+ arch: arch,+ shardHeaders: [header],+ outputDir: firstOutput)+ let secondPlan = try RepackPlanner.plan(+ meta: metadata,+ arch: arch,+ shardHeaders: [header],+ outputDir: secondOutput)++ let first = try RangeCopyPlanner.plan(+ repackPlan: firstPlan,+ rangeChunkBytes: 4096)+ let second = try RangeCopyPlanner.plan(+ repackPlan: secondPlan,+ rangeChunkBytes: 4096)++ #expect(first.canonicalFingerprint == second.canonicalFingerprint)+ #expect(first.coalescedCopies.map(\.id) == second.coalescedCopies.map(\.id))+ }++ @Test func overlappingDestinationIntervalsAreRejected() throws {+ let root = temporaryRoot("overlap")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let output = (root as NSString).appendingPathComponent("file.bin")+ let copies = [+ RangeCopy(+ shardID: "source.bin",+ sourceOffset: 0,+ size: 10,+ destinationPath: output,+ destinationOffset: 0),+ RangeCopy(+ shardID: "source.bin",+ sourceOffset: 20,+ size: 10,+ destinationPath: output,+ destinationOffset: 9),+ ]++ #expect(throws: RepackError.self) {+ try RangeCopyPlanner.validateDestinationIntervals(+ copies,+ outputRoot: root)+ }+ }++ @Test func normalizedRelativePathRejectsEscape() throws {+ let root = temporaryRoot("escape")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let outside = (root as NSString).deletingLastPathComponent+ + "/outside.bin"++ #expect(throws: RepackError.self) {+ _ = try RangeCopyPlanner.normalizedRelativePath(+ outside,+ root: root)+ }+ }++ private func temporaryRoot(_ tag: String) -> String {+ let path = (NSTemporaryDirectory() as NSString)+ .appendingPathComponent("turbofieldfare-range-plan-\(tag)-\(UUID().uuidString)")+ try? FileManager.default.createDirectory(+ atPath: path,+ withIntermediateDirectories: true)+ return path+ }++ private func parseHeader(path: String) throws -> Safetensors.Header {+ let fd = try Posix.openRead(path)+ defer { close(fd) }+ var headerSize: UInt64 = 0+ try withUnsafeMutableBytes(of: &headerSize) {+ try Posix.preadAll(+ fd: fd,+ path: path,+ buf: $0.baseAddress!,+ count: 8,+ offset: 0)+ }+ headerSize = UInt64(littleEndian: headerSize)+ var headerData = Data(count: Int(headerSize))+ try headerData.withUnsafeMutableBytes {+ try Posix.preadAll(+ fd: fd,+ path: path,+ buf: $0.baseAddress!,+ count: $0.count,+ offset: 8)+ }+ return try Safetensors.parseHeaderBytes(+ path: path,+ fileSize: try Posix.fileSize(fd: fd, path: path),+ headerBytes: headerData)+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemoteDownloadSessionTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemoteDownloadSessionTests.swiftnew file mode 100644index 00000000..cb51a903--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemoteDownloadSessionTests.swift@@ -0,0 +1,60 @@+import Foundation+import Testing+@testable import TurboFieldfareRepackCore++@Suite+struct RemoteDownloadSessionTests {+ @Test func typedSessionUsesStallTolerantSerialDefaults() {+ let session = RemoteDownloadSession()+ let configuration = session.configurationSnapshot++ #expect(session.policy.requestTimeoutSeconds == 300)+ #expect(session.policy.resourceTimeoutSeconds == 7 * 24 * 60 * 60)+ #expect(session.policy.waitsForConnectivity)+ #expect(session.policy.maximumConnectionsPerHost == 1)+ #expect(session.policy.maximumRedirects == 5)+ #expect(configuration.requestTimeoutSeconds == 300)+ #expect(configuration.resourceTimeoutSeconds == 7 * 24 * 60 * 60)+ #expect(configuration.waitsForConnectivity)+ #expect(configuration.maximumConnectionsPerHost == 1)+ #expect(configuration.requestCachePolicy == .reloadIgnoringLocalCacheData)+ #expect(!configuration.hasURLCache)+ }++ @Test func injectedPolicyIsAppliedToOwnedConfiguration() {+ let policy = RemoteDownloadSessionPolicy(+ requestTimeoutSeconds: 12,+ resourceTimeoutSeconds: 34,+ waitsForConnectivity: false,+ maximumConnectionsPerHost: 1,+ maximumRedirects: 2)+ let session = RemoteDownloadSession(policy: policy)+ let configuration = session.configurationSnapshot++ #expect(configuration.requestTimeoutSeconds == 12)+ #expect(configuration.resourceTimeoutSeconds == 34)+ #expect(!configuration.waitsForConnectivity)+ #expect(configuration.maximumConnectionsPerHost == 1)+ #expect(session.policy.maximumRedirects == 2)+ }++ @Test func metadataRedirectsFollowOnlyBoundedSameHostHTTPS() {+ var original = URLRequest(url: URL(string: "https://hf.test/model/file")!)+ original.httpMethod = "HEAD"+ original.setValue("Bearer secret", forHTTPHeaderField: "Authorization")+ var policy = RemoteMetadataRedirectPolicy(+ originalRequest: original,+ maximumRedirects: 2)++ let sameHost = policy.request(proposedRequest: URLRequest(+ url: URL(string: "https://hf.test/api/cache/file?etag=value")!))+ #expect(sameHost?.httpMethod == "HEAD")+ #expect(sameHost?.value(forHTTPHeaderField: "Accept-Encoding") == "identity")+ #expect(sameHost?.value(forHTTPHeaderField: "Authorization") == "Bearer secret")++ #expect(policy.request(proposedRequest: URLRequest(+ url: URL(string: "https://storage.test/signed?token=private")!)) == nil)+ #expect(policy.request(proposedRequest: URLRequest(+ url: URL(string: "https://hf.test/too-many")!)) == nil)+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemoteInstallCheckpointTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemoteInstallCheckpointTests.swiftnew file mode 100644index 00000000..991e96bb--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemoteInstallCheckpointTests.swift@@ -0,0 +1,147 @@+import Foundation+import Darwin+import Testing++@testable import TurboFieldfareRepackCore++@Suite+struct RemoteInstallCheckpointTests {+ @Test func roundTripsCompactCheckpoint() throws {+ let root = tmpDirForRemote("checkpoint")+ let path = (root as NSString).appendingPathComponent("resume.json")+ defer { cleanUpRemote([root]) }+ try Posix.mkdirP(root)+ let checkpoint = sampleCheckpoint()++ try checkpoint.write(to: path, parentDirectory: root)++ #expect(try RemoteInstallCheckpoint.load(from: path) == checkpoint)+ #expect(try Data(contentsOf: URL(fileURLWithPath: path)).count < 1024)+ #expect(!checkpoint.matches(+ repoID: checkpoint.repoID,+ requestedRevision: checkpoint.requestedRevision,+ sourceIndexSHA256: String(repeating: "e", count: 64),+ planFingerprint: checkpoint.planFingerprint))+ }++ @Test func oversizedCheckpointIsRejectedBeforeDecode() throws {+ let root = tmpDirForRemote("checkpoint-large")+ let path = (root as NSString).appendingPathComponent("resume.json")+ defer { cleanUpRemote([root]) }+ try Posix.mkdirP(root)+ let descriptor = try Posix.openCreateRW(path)+ try Posix.ftruncate(+ descriptor,+ path: path,+ size: RemoteInstallCheckpoint.maximumBytes + 1)+ close(descriptor)++ #expect(throws: RepackError.self) {+ _ = try RemoteInstallCheckpoint.load(from: path)+ }+ }++ @Test func destinationByteTotalRejectsOverflowAndValuesAboveBound() throws {+ #expect(try sampleCheckpoint().validatedDestinationBytes(+ maximum: 8,+ path: "resume.json") == 8)+ for values in [[UInt64.max], [UInt64.max, 1], [9]] {+ let checkpoint = RemoteInstallCheckpoint(+ repoID: "owner/model",+ requestedRevision: "main",+ resolvedCommit: String(repeating: "a", count: 40),+ sourceIndexSHA256: String(repeating: "b", count: 64),+ planFingerprint: String(repeating: "c", count: 64),+ totalSourceBytes: UInt64(values.count),+ completedRanges: values.enumerated().map { index, bytes in+ RemoteCompletedRange(+ id: "range-\(index)",+ destinationDigest: String(repeating: "d", count: 64),+ sourceBytes: 1,+ destinationBytes: bytes)+ })+ #expect(throws: RepackError.self) {+ _ = try checkpoint.validatedDestinationBytes(+ maximum: 8,+ path: "resume.json")+ }+ }+ }++ @Test func damagedDestinationInvalidatesItsRange() throws {+ let root = tmpDirForRemote("checkpoint-digest")+ let path = (root as NSString).appendingPathComponent("weights.bin")+ defer { cleanUpRemote([root]) }+ try Posix.mkdirP(root)+ let descriptor = try Posix.openCreateRW(path)+ var bytes = [UInt8](repeating: 7, count: 16)+ try bytes.withUnsafeBytes {+ try Posix.pwriteAll(+ fd: descriptor,+ path: path,+ buf: $0.baseAddress!,+ count: $0.count,+ offset: 0)+ }+ close(descriptor)++ let copy = CoalescedRangeCopy(+ id: "range-00000000",+ shardID: "source.bin",+ sourceOffset: 0,+ size: 16,+ destinations: [+ RangeCopy(+ shardID: "source.bin",+ sourceOffset: 0,+ size: 16,+ destinationPath: path,+ destinationOffset: 0),+ ])+ let digest = try HTTPRangeSourceByteProvider.destinationDigest(+ copy,+ partialDirectory: root)+ let completed = RemoteCompletedRange(+ id: copy.id,+ destinationDigest: digest,+ sourceBytes: 16,+ destinationBytes: 16)+ #expect(try RemoteStreamingRepacker.validatedCompletedRanges(+ [completed],+ copies: [copy],+ partialDirectory: root) == [completed])++ let writeDescriptor = try Posix.openExistingRW(path)+ bytes[0] = 8+ try bytes.withUnsafeBytes {+ try Posix.pwriteAll(+ fd: writeDescriptor,+ path: path,+ buf: $0.baseAddress!,+ count: 1,+ offset: 0)+ }+ close(writeDescriptor)+ #expect(try RemoteStreamingRepacker.validatedCompletedRanges(+ [completed],+ copies: [copy],+ partialDirectory: root).isEmpty)+ }+}++private func sampleCheckpoint() -> RemoteInstallCheckpoint {+ RemoteInstallCheckpoint(+ repoID: "owner/model",+ requestedRevision: "main",+ resolvedCommit: String(repeating: "a", count: 40),+ sourceIndexSHA256: String(repeating: "b", count: 64),+ planFingerprint: String(repeating: "c", count: 64),+ totalSourceBytes: 10,+ completedRanges: [+ RemoteCompletedRange(+ id: "range-00000000",+ destinationDigest: String(repeating: "d", count: 64),+ sourceBytes: 10,+ destinationBytes: 8),+ ])+}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swiftindex 37e26f7f..8fb07d09 100644--- a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swift+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Cleanup.swift@@ -1,48 +1,24 @@import Foundation-import Synchronizationimport Testing@testable import TurboFieldfareRepackCoreextension RemotePayloadCopyTests {- @Test func stalePartialSweepRemovesDeadPidAndPreservesUnrelatedSiblings() async throws {- let root = tmpDirForRemote("partial-root")- let output = (root as NSString).appendingPathComponent("out.gturbo")- let stale = (root as NSString).appendingPathComponent("out.gturbo.partial.999999")- let unrelatedA = (root as NSString).appendingPathComponent("out.gturbo.partial")- let unrelatedB = (root as NSString).appendingPathComponent("outX.gturbo.partial.1")+ @Test func discardRemovesOnlyOwnedResumeFiles() throws {+ let root = tmpDirForRemote("discard")+ let output = (root as NSString).appendingPathComponent("model.gturbo")+ let paths = try RemoteInstallPaths(outputDirectory: output)+ let unrelated = (root as NSString).appendingPathComponent("keep.txt")defer { cleanUpRemote([root]) }- try Posix.mkdirP(stale)- try Data("x".utf8).write(- to: URL(fileURLWithPath: (stale as NSString).appendingPathComponent("payload")))- try Posix.mkdirP(unrelatedA)- try Posix.mkdirP(unrelatedB)- let audit = RepackAudit()- try RemoteStreamingRepacker.sweepStalePartials(outputDir: output, audit: audit)+ try Posix.mkdirP(paths.partialDirectory)+ try Data("{}".utf8).write(to: URL(fileURLWithPath: paths.checkpointFile))+ try Data("keep".utf8).write(to: URL(fileURLWithPath: unrelated))- #expect(!FileManager.default.fileExists(atPath: stale))- #expect(FileManager.default.fileExists(atPath: unrelatedA))- #expect(FileManager.default.fileExists(atPath: unrelatedB))- #expect(audit.stalePartialsRemoved == [stale])- }-- @Test func stalePartialSweepRefusesLivePid() throws {- let root = tmpDirForRemote("partial-live-root")- let output = (root as NSString).appendingPathComponent("out.gturbo")- let live = (root as NSString).appendingPathComponent("out.gturbo.partial.\(getpid())")- defer { cleanUpRemote([root]) }- try Posix.mkdirP(live)+ try RemoteStreamingRepacker.discardPartial(outputDirectory: output)- #expect {- try RemoteStreamingRepacker.sweepStalePartials(outputDir: output)- } throws: { error in- guard case RepackError.configurationInvalid(let detail) = error else {- return false- }- return detail.contains("another repack")- }- #expect(FileManager.default.fileExists(atPath: live))+ #expect(!FileManager.default.fileExists(atPath: paths.partialDirectory))+ #expect(!FileManager.default.fileExists(atPath: paths.checkpointFile))+ #expect(FileManager.default.fileExists(atPath: unrelated))}-}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swiftindex 390b47f4..16118c77 100644--- a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swift+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Installation.swift@@ -5,176 +5,92 @@ import Testing@testable import TurboFieldfareRepackCoreextension RemotePayloadCopyTests {- @Test func remoteInstallProgressIsMonotonicAndComplete() async throws {- let snapshotDir = tmpDirForRemote("snap-progress")- let remoteOutput = tmpPathForRemote("remote-progress")+ @Test func remotePayloadCopyCompletes() async throws {+ let snapshotDir = tmpDirForRemote("snap")+ let remoteOutput = tmpPathForRemote("remote")defer { cleanUpRemote([snapshotDir, remoteOutput]) }- let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x10_2938_4756)+ let snapshot = try SyntheticSnapshot.build(+ at: snapshotDir,+ seed: 0x1020_3040_5060_7080)resetFakeHF()FakeHFURLProtocol.files = try remoteFiles(snapshotDir: snapshotDir,- snap: snap,+ snap: snapshot,includeRequiredTokenizer: true,- includeOptionalTokenizer: false)+ includeOptionalTokenizer: true)let recorder = InstallProgressRecorder()- _ = try await RemoteStreamingRepacker(- options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession())- )- .run { recorder.append($0) }-- let payload = recorder.values.compactMap { event -> (UInt64, UInt64)? in- guard case .copyingPayload(let downloaded, let total) = event else { return nil }- return (downloaded, total)+ let result = try await RemoteStreamingRepacker(+ options: remoteOptions(+ outputDir: remoteOutput,+ session: fakeHFSession())+ ).run { recorder.append($0) }++ #expect(result.reusedBytes == 0)+ #expect(result.downloadedThisRunBytes == result.remoteBytesToDownload)+ for relativePath in [+ "model_weights.bin",+ "packed_experts/layout.json",+ "packed_experts/layer_00.bin",+ "packed_experts/layer_01.bin",+ "manifest.json",+ ] {+ let remote = (remoteOutput as NSString).appendingPathComponent(relativePath)+ #expect(FileManager.default.fileExists(atPath: remote))}- #expect(payload.count > 2)- #expect(payload.first?.0 == 0)- #expect(payload.last?.0 == payload.last?.1)- #expect(- zip(payload, payload.dropFirst()).allSatisfy { pair in- pair.0.0 <= pair.1.0- })- #expect(payload.allSatisfy { $0.0 <= $0.1 })- #expect(- recorder.values.contains {- if case .planning = $0 { return true }- return false- })- #expect(- recorder.values.contains {- if case .hashingOutput = $0 { return true }- return false- })#expect(recorder.values.contains(.finalizing))+ try assertRemoteTokenizerFilesRecorded(+ outputDir: remoteOutput,+ expectsOptionalSpecialTokens: true)}- @Test func cancellationCleansPartialAndAllowsImmediateRetry() async throws {- let snapshotDir = tmpDirForRemote("snap-cancel")- let remoteOutput = tmpPathForRemote("remote-cancel")- defer { cleanUpRemote([snapshotDir, remoteOutput]) }- let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x56_4738_2910)+ @Test func cancellationPreservesCommittedRangesForResume() async throws {+ let snapshotDir = tmpDirForRemote("snap-resume")+ let output = tmpPathForRemote("remote-resume")+ defer { cleanUpRemote([snapshotDir, output]) }+ let snapshot = try SyntheticSnapshot.build(+ at: snapshotDir,+ seed: 0x56_4738_2910)resetFakeHF()FakeHFURLProtocol.files = try remoteFiles(snapshotDir: snapshotDir,- snap: snap,+ snap: snapshot,includeRequiredTokenizer: true,includeOptionalTokenizer: false)- let options = remoteOptions(- outputDir: remoteOutput,- session: fakeHFSession(),- retainPartialOnFailure: false)-- let cancelledInstall = Task {- try await RemoteStreamingRepacker(options: options).run { event in- if case .copyingPayload(let downloaded, _) = event, downloaded > 0 {+ let seen = Mutex<[UInt64: Int]>([:])+ let task = Task {+ try await RemoteStreamingRepacker(+ options: remoteOptions(outputDir: output, session: fakeHFSession())+ ).run { progress in+ guard case .copyingPayload(_, let downloaded, _) = progress,+ downloaded > 0 else { return }+ let count = seen.withLock {+ $0[downloaded, default: 0] += 1+ return $0[downloaded] ?? 0+ }+ if count == 3 {withUnsafeCurrentTask { $0?.cancel() }}}}await #expect(throws: CancellationError.self) {- _ = try await cancelledInstall.value+ _ = try await task.value}- #expect(!FileManager.default.fileExists(atPath: remoteOutput))- #expect(- !FileManager.default.fileExists(- atPath: remoteOutput + ".partial.\(getpid())"))+ let checkpoint = try RemoteInstallCheckpoint.load(from: output + ".resume.json")+ #expect(!checkpoint.completedRanges.isEmpty)- _ = try await RemoteStreamingRepacker(+ let result = try await RemoteStreamingRepacker(options: remoteOptions(- outputDir: remoteOutput,+ outputDir: output,session: fakeHFSession(),- retainPartialOnFailure: false)+ resume: true)).run()- #expect(- FileManager.default.fileExists(- atPath: (remoteOutput as NSString).appendingPathComponent("manifest.json")))- }-- @Test func remoteTokenizerOptionalSpecialTokensMissingStillInstalls() async throws {- let snapshotDir = tmpDirForRemote("snap-tokenizer-optional")- let remoteOutput = tmpDirForRemote("remote-tokenizer-optional")- defer { cleanUpRemote([snapshotDir, remoteOutput]) }- let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x6655_4433_2211)-- resetFakeHF()- FakeHFURLProtocol.files = try remoteFiles(- snapshotDir: snapshotDir,- snap: snap,- includeRequiredTokenizer: true,- includeOptionalTokenizer: false)- let session = fakeHFSession()-- _ = try await RemoteStreamingRepacker(- options: remoteOptions(outputDir: remoteOutput, session: session)- ).run()-- try assertRemoteTokenizerFilesRecorded(- outputDir: remoteOutput,- expectsOptionalSpecialTokens: false)-- let verification = try VerifiedInstallTool.run(- options: VerifyInstallOptions(inputGTurbo: remoteOutput))- #expect(FileManager.default.fileExists(atPath: verification.receiptPath))- #expect(verification.fileCount > 1)- #expect(verification.bytesVerified > 0)- #expect(verification.unexpectedEntries.isEmpty)- }-- @Test func remoteTokenizerMissingRequiredFileFailsInstall() async throws {- let snapshotDir = tmpDirForRemote("snap-tokenizer-required")- let remoteOutput = tmpPathForRemote("remote-tokenizer-required")- defer { cleanUpRemote([snapshotDir, remoteOutput]) }- let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x7766_5544_3322)-- resetFakeHF()- FakeHFURLProtocol.files = try remoteFiles(- snapshotDir: snapshotDir,- snap: snap,- includeRequiredTokenizer: false,- includeOptionalTokenizer: true)- let session = fakeHFSession()-- await #expect(throws: RepackError.self) {- _ = try await RemoteStreamingRepacker(- options: remoteOptions(outputDir: remoteOutput, session: session)- ).run()- }- #expect(!FileManager.default.fileExists(atPath: remoteOutput))- }-- @Test func remoteInstallRejectsPerTensorGroupSizeOverride() async throws {- let snapshotDir = tmpDirForRemote("snap-group-size")- let remoteOutput = tmpPathForRemote("remote-group-size")- defer { cleanUpRemote([snapshotDir, remoteOutput]) }- let snap = try SyntheticSnapshot.build(at: snapshotDir, seed: 0x65_726F_7570)-- resetFakeHF()- var files = try remoteFiles(- snapshotDir: snapshotDir,- snap: snap,- includeRequiredTokenizer: true,- includeOptionalTokenizer: false)- let configData = try #require(files["config.json"])- var config = try #require(- JSONSerialization.jsonObject(with: configData) as? [String: Any])- var quantization = try #require(config["quantization"] as? [String: Any])- let key = "language_model.model.layers.0.router.proj"- var override = try #require(quantization[key] as? [String: Any])- override["group_size"] = 32- quantization[key] = override- config["quantization"] = quantization- files["config.json"] = try JSONSerialization.data(withJSONObject: config)- FakeHFURLProtocol.files = files-- await #expect(throws: RepackError.self) {- _ = try await RemoteStreamingRepacker(- options: remoteOptions(outputDir: remoteOutput, session: fakeHFSession())- ).run()- }- #expect(!FileManager.default.fileExists(atPath: remoteOutput))+ #expect(result.reusedBytes > 0)+ #expect(result.downloadedThisRunBytes < result.remoteBytesToDownload)+ #expect(FileManager.default.fileExists(+ atPath: (output as NSString).appendingPathComponent("manifest.json")))}-}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swiftindex 951678f3..984ca695 100644--- a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swift+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests+Retries.swift@@ -32,7 +32,7 @@ extension RemotePayloadCopyTests {#expect(audit.remoteRangeRetries == 2)#expect((FakeHFURLProtocol.requestCounts["GET:model-00001-of-00001.safetensors"] ?? 0) >= 3)let payload = recorder.values.compactMap { event -> UInt64? in- guard case .copyingPayload(let downloaded, _) = event else { return nil }+ guard case .copyingPayload(_, let downloaded, _) = event else { return nil }return downloaded}#expect(payload.last == result.remoteBytesToDownload)diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swiftindex dda8528d..24683dda 100644--- a/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemotePayloadCopyTests.swift@@ -5,9 +5,12 @@ import Testingfinal class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {nonisolated(unsafe) static var files: [String: Data] = [:]- nonisolated(unsafe) static var commit = String(repeating: "a", count: 40)+ nonisolated(unsafe) static var commit = "cc499c86a958ea7f05cffaa91c7e7243240dabbe"nonisolated(unsafe) static var failures: [String: [FakeFailure]] = [:]nonisolated(unsafe) static var requestCounts: [String: Int] = [:]+ nonisolated(unsafe) static var requestedRanges: [String: [String]] = [:]+ nonisolated(unsafe) static var etagOverrides: [String: String] = [:]+ nonisolated(unsafe) static var xetHashOverrides: [String: String] = [:]override class func canInit(with request: URLRequest) -> Bool {request.url?.host == "hf.test"@@ -31,6 +34,9 @@ final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {let method = request.httpMethod ?? "GET"let key = "\(method):\(filename)"Self.requestCounts[key, default: 0] += 1+ if let range = request.value(forHTTPHeaderField: "Range") {+ Self.requestedRanges[filename, default: []].append(range)+ }let failure = Self.nextFailure(for: key)switch failure {case .url(let code):@@ -44,6 +50,16 @@ final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)client?.urlProtocolDidFinishLoading(self)return+ case .response(let status, let headers, let body):+ let response = HTTPURLResponse(+ url: url,+ statusCode: status,+ httpVersion: nil,+ headerFields: headers)!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: body)+ client?.urlProtocolDidFinishLoading(self)+ returncase .truncatedBody, nil:break}@@ -59,7 +75,8 @@ final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {}if method == "HEAD" {- let headers = baseHeaders(data: data,+ let headers = baseHeaders(filename: filename,+ data: data,contentLength: data.count)let response = HTTPURLResponse(url: url,statusCode: 200,@@ -87,7 +104,8 @@ final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {} else {body = Data(data[start...end])}- var headers = baseHeaders(data: data,+ var headers = baseHeaders(filename: filename,+ data: data,contentLength: expectedLength)headers["Content-Range"] = "bytes \(start)-\(end)/\(data.count)"let response = HTTPURLResponse(url: url,@@ -101,15 +119,22 @@ final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {override func stopLoading() {}- func baseHeaders(data: Data,+ func baseHeaders(filename: String,+ data: Data,contentLength: Int) -> [String: String] {- [+ var headers = ["X-Repo-Commit": Self.commit,"X-Linked-Size": "\(data.count)",+ "X-Linked-ETag": Self.etagOverrides[filename] ?? "\"\(filename)-etag\"","Accept-Ranges": "bytes","Content-Length": "\(contentLength)","Content-Encoding": "identity",]+ if let xetHash = Self.xetHashOverrides[filename] {+ headers["X-Xet-Hash"] = xetHash+ headers["ETag"] = "\"\(xetHash)\""+ }+ return headers}static func filename(from url: URL) -> String? {@@ -147,6 +172,7 @@ final class FakeHFURLProtocol: URLProtocol, @unchecked Sendable {enum FakeFailure: Equatable {case url(URLError.Code)case http(Int)+ case response(status: Int, headers: [String: String], body: Data)case truncatedBody}@@ -154,7 +180,6 @@ let remoteTokenizerJSON = Data(#"{"model":{"type":"BPE"}}"#.utf8)let remoteTokenizerConfigJSON = Data(#"{"tokenizer_class":"PreTrainedTokenizerFast"}"#.utf8)let remoteSpecialTokensMapJSON = Data(#"{"eos_token":"<eos>"}"#.utf8)let remoteChatTemplateJinja = Data("{{ bos_token }}".utf8)-let remoteChatTemplateJSON = Data(#"{"chat_template":"{{ bos_token }}"}"#.utf8)@Suite(.serialized)struct RemotePayloadCopyTests {@@ -179,7 +204,6 @@ func remoteFiles(snapshotDir: String,if includeOptionalTokenizer {files["special_tokens_map.json"] = remoteSpecialTokensMapJSONfiles["chat_template.jinja"] = remoteChatTemplateJinja- files["chat_template.json"] = remoteChatTemplateJSON}return files}@@ -188,28 +212,36 @@ func resetFakeHF() {FakeHFURLProtocol.files = [:]FakeHFURLProtocol.failures = [:]FakeHFURLProtocol.requestCounts = [:]+ FakeHFURLProtocol.requestedRanges = [:]+ FakeHFURLProtocol.etagOverrides = [:]+ FakeHFURLProtocol.xetHashOverrides = [:]+ FakeHFURLProtocol.commit = "cc499c86a958ea7f05cffaa91c7e7243240dabbe"}-func fakeHFSession() -> URLSession {- let config = URLSessionConfiguration.ephemeral- config.protocolClasses = [FakeHFURLProtocol.self]- return URLSession(configuration: config)+func fakeHFSession() -> RemoteDownloadSession {+ RemoteDownloadSession(protocolClasses: [FakeHFURLProtocol.self])}func remoteOptions(outputDir: String,- session: URLSession,+ session: RemoteDownloadSession,rangeRetryAttempts: Int = 4,- retainPartialOnFailure: Bool = true) -> RemoteStreamingRepackOptions {+ resume: Bool = false,+ overwrite: Bool = true,+ repoID: String = "owner/model",+ revision: String = "main",+ rangeChunkBytes: Int = 4096,+ copyAuditPath: String? = nil) -> RemoteStreamingRepackOptions {RemoteStreamingRepackOptions(+ repoID: repoID,+ revision: revision,outputDir: outputDir,- overwrite: true,- repoID: "owner/model",- revision: "main",requireKnownSource: false,- rangeChunkBytes: 4096,+ copyAuditPath: copyAuditPath,+ rangeChunkBytes: rangeChunkBytes,minFreeReserveBytes: 0,- retainPartialOnFailure: retainPartialOnFailure,- session: session,+ overwrite: overwrite,+ resume: resume,+ downloadSession: session,baseURL: URL(string: "https://hf.test")!,rangeRetryAttempts: rangeRetryAttempts,retryBaseDelayNs: 0)@@ -230,10 +262,8 @@ func assertRemoteTokenizerFilesRecorded(outputDir: String,(tokenizerDir as NSString).appendingPathComponent("tokenizer_config.json"))) == remoteTokenizerConfigJSON)let specialTokensPath = (tokenizerDir as NSString).appendingPathComponent("special_tokens_map.json")#expect(FileManager.default.fileExists(atPath: specialTokensPath) == expectsOptionalSpecialTokens)- let chatTemplateJinjaPath = (tokenizerDir as NSString).appendingPathComponent("chat_template.jinja")- #expect(FileManager.default.fileExists(atPath: chatTemplateJinjaPath) == expectsOptionalSpecialTokens)- let chatTemplateJSONPath = (tokenizerDir as NSString).appendingPathComponent("chat_template.json")- #expect(FileManager.default.fileExists(atPath: chatTemplateJSONPath) == expectsOptionalSpecialTokens)+ let chatTemplatePath = (tokenizerDir as NSString).appendingPathComponent("chat_template.jinja")+ #expect(FileManager.default.fileExists(atPath: chatTemplatePath) == expectsOptionalSpecialTokens)let manifestData = try Data(contentsOf: URL(fileURLWithPath:(outputDir as NSString).appendingPathComponent("manifest.json")))@@ -244,7 +274,6 @@ func assertRemoteTokenizerFilesRecorded(outputDir: String,#expect(manifestFiles["tokenizer/tokenizer_config.json"] != nil)#expect((manifestFiles["tokenizer/special_tokens_map.json"] != nil) == expectsOptionalSpecialTokens)#expect((manifestFiles["tokenizer/chat_template.jinja"] != nil) == expectsOptionalSpecialTokens)- #expect((manifestFiles["tokenizer/chat_template.json"] != nil) == expectsOptionalSpecialTokens)let receiptData = try Data(contentsOf: URL(fileURLWithPath:(outputDir as NSString).appendingPathComponent(VerifiedInstallReceiptWriter.fileName)))@@ -255,7 +284,6 @@ func assertRemoteTokenizerFilesRecorded(outputDir: String,#expect(receiptFiles["tokenizer/tokenizer_config.json"] != nil)#expect((receiptFiles["tokenizer/special_tokens_map.json"] != nil) == expectsOptionalSpecialTokens)#expect((receiptFiles["tokenizer/chat_template.jinja"] != nil) == expectsOptionalSpecialTokens)- #expect((receiptFiles["tokenizer/chat_template.json"] != nil) == expectsOptionalSpecialTokens)}func assertNoInternalRemoteDirs(outputDir: String) throws {@@ -282,5 +310,9 @@ func tmpPathForRemote(_ tag: String) -> String {func cleanUpRemote(_ paths: [String]) {for path in paths {try? FileManager.default.removeItem(atPath: path)+ try? FileManager.default.removeItem(atPath: path + ".partial")+ try? FileManager.default.removeItem(atPath: path + ".install-state")+ try? FileManager.default.removeItem(atPath: path + ".install-state.cleanup")+ try? FileManager.default.removeItem(atPath: path + ".install.lock")}}diff --git a/Tests/TurboFieldfareRepack/Core/Remote/RemoteRangeTransferTests.swift b/Tests/TurboFieldfareRepack/Core/Remote/RemoteRangeTransferTests.swiftnew file mode 100644index 00000000..0bf3847a--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/Remote/RemoteRangeTransferTests.swift@@ -0,0 +1,321 @@+import Foundation+import Synchronization+import Testing+@testable import TurboFieldfareRepackCore++extension RemotePayloadCopyTests {+ @Suite+ struct RemoteRangeTransferTests {+ @Test func exact206IsAcceptedAndWritten() async throws {+ resetFakeHF()+ FakeHFURLProtocol.files["file.bin"] = Data([1, 2, 3, 4])+ let target = tmpPathForRemote("range-exact")+ defer { cleanUpRemote([target]) }++ let result = try await fakeHFSession().transfer(+ request: rangeRequest(length: 4),+ targetPath: target,+ expectation: RemoteRangeExpectation(+ filename: "file.bin",+ offset: 0,+ length: 4,+ totalSize: 4,+ xetHash: nil))++ #expect(result.byteCount == 4)+ #expect(try Data(contentsOf: URL(fileURLWithPath: target)) == Data([1, 2, 3, 4]))+ }++ @Test func oversized200IsRejectedBeforeTargetGrowth() async throws {+ resetFakeHF()+ let body = Data(repeating: 0x7f, count: 2 * 1024 * 1024)+ FakeHFURLProtocol.files["file.bin"] = Data([1])+ FakeHFURLProtocol.failures["GET:file.bin"] = [+ .response(+ status: 200,+ headers: ["Content-Length": "\(body.count)"],+ body: body),+ ]+ let target = tmpPathForRemote("range-200")+ defer { cleanUpRemote([target]) }++ await #expect(throws: RepackError.self) {+ _ = try await fakeHFSession().transfer(+ request: rangeRequest(length: 1),+ targetPath: target,+ expectation: RemoteRangeExpectation(+ filename: "file.bin",+ offset: 0,+ length: 1,+ totalSize: 1,+ xetHash: nil))+ }+ #expect(!FileManager.default.fileExists(atPath: target))+ }++ @Test func lying206BodyCannotExceedRequestedRange() async throws {+ resetFakeHF()+ let body = Data(repeating: 0x55, count: 2 * 1024 * 1024)+ FakeHFURLProtocol.files["file.bin"] = Data([1])+ FakeHFURLProtocol.failures["GET:file.bin"] = [+ .response(+ status: 206,+ headers: [+ "Content-Length": "1",+ "Content-Range": "bytes 0-0/1",+ "Content-Encoding": "identity",+ ],+ body: body),+ ]+ let target = tmpPathForRemote("range-oversize")+ defer { cleanUpRemote([target]) }++ await #expect(throws: RepackError.self) {+ _ = try await fakeHFSession().transfer(+ request: rangeRequest(length: 1),+ targetPath: target,+ expectation: RemoteRangeExpectation(+ filename: "file.bin",+ offset: 0,+ length: 1,+ totalSize: 1,+ xetHash: nil))+ }+ #expect(!FileManager.default.fileExists(atPath: target))+ }++ @Test(arguments: [+ "content-length",+ "content-range",+ "content-encoding",+ "validator",+ ])+ func mismatchedRangeResponseIsRejectedBeforeWriting(_ mismatch: String) async throws {+ resetFakeHF()+ FakeHFURLProtocol.files["file.bin"] = Data([1])+ var headers = [+ "Content-Length": "1",+ "Content-Range": "bytes 0-0/1",+ "Content-Encoding": "identity",+ "ETag": "\"expected\"",+ ]+ switch mismatch {+ case "content-length":+ headers["Content-Length"] = "2"+ case "content-range":+ headers["Content-Range"] = "bytes 1-1/2"+ case "content-encoding":+ headers["Content-Encoding"] = "gzip"+ case "validator":+ headers["ETag"] = "\"different\""+ default:+ Issue.record("unknown mismatch \(mismatch)")+ }+ FakeHFURLProtocol.failures["GET:file.bin"] = [+ .response(status: 206, headers: headers, body: Data([1])),+ ]+ let target = tmpPathForRemote("range-mismatch-\(mismatch)")+ defer { cleanUpRemote([target]) }++ await #expect(throws: RepackError.self) {+ _ = try await fakeHFSession().transfer(+ request: rangeRequest(length: 1),+ targetPath: target,+ expectation: RemoteRangeExpectation(+ filename: "file.bin",+ offset: 0,+ length: 1,+ totalSize: 1,+ xetHash: "expected"))+ }+ #expect(!FileManager.default.fileExists(atPath: target))+ }++ @Test func retryAfterParsesSecondsAndHTTPDateAndRejectsCap() throws {+ let policy = RemoteRetryPolicy(maxServerDelayNs: 10 * 1_000_000_000)+ let error = RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: 429,+ retryAfter: "5")+ #expect(try policy.retryDelayNs(error: error, localDelayNs: 1) == 5_000_000_000)++ let now = Date(timeIntervalSince1970: 0)+ let dateError = RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: 503,+ retryAfter: "Thu, 01 Jan 1970 00:00:08 GMT")+ #expect(try policy.retryDelayNs(+ error: dateError,+ localDelayNs: 1,+ now: now) == 8_000_000_000)++ let capped = RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: 429,+ retryAfter: "11")+ #expect(throws: RepackError.self) {+ _ = try policy.retryDelayNs(error: capped, localDelayNs: 1)+ }++ let obsolete = RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: 503,+ retryAfter: "Sunday, 06-Nov-94 08:49:37 GMT")+ let obsoleteNow = Date(timeIntervalSince1970: 784_111_770)+ #expect(try policy.retryDelayNs(+ error: obsolete,+ localDelayNs: 1,+ now: obsoleteNow) == 7_000_000_000)++ let asctime = RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: 503,+ retryAfter: "Sun Nov 6 08:49:37 1994")+ #expect(try policy.retryDelayNs(+ error: asctime,+ localDelayNs: 1,+ now: obsoleteNow) == 7_000_000_000)+ }++ @Test func retryBackoffUsesInjectedJitterAndSleeper() async throws {+ let attempts = Mutex(0)+ let sleeps = Mutex<[UInt64]>([])+ let value: String = try await withRemoteRetries(+ RemoteRetryPolicy(+ attempts: 3,+ baseDelayNs: 100,+ maxDelayNs: 500,+ maxServerDelayNs: 1_000),+ label: "test",+ audit: nil,+ jitter: { 10 },+ sleeper: { delay in+ sleeps.withLock { $0.append(delay) }+ }) {+ let attempt = attempts.withLock { value -> Int in+ value += 1+ return value+ }+ if attempt < 3 {+ throw URLError(.timedOut)+ }+ return "done"+ }++ #expect(value == "done")+ #expect(sleeps.withLock { $0 } == [110, 210])+ }++ @Test func retryStatusMatrixIsExplicit() {+ for status in [408, 429, 500, 502, 503, 504] {+ #expect(RemoteRetryPolicy.isRetryable(+ RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: status,+ retryAfter: nil)))+ }+ for status in [200, 400, 401, 403, 404, 409, 412, 416, 501, 505] {+ #expect(!RemoteRetryPolicy.isRetryable(+ RepackError.remoteHTTPResponse(+ url: "https://hf.test/file",+ status: status,+ retryAfter: nil)))+ }+ }++ @Test func cancellationDuringBackoffStopsBeforeAnotherAttempt() async {+ let attempts = Mutex(0)+ await #expect(throws: CancellationError.self) {+ let _: Int = try await withRemoteRetries(+ RemoteRetryPolicy(+ attempts: 4,+ baseDelayNs: 1,+ maxDelayNs: 8),+ label: "cancel",+ audit: nil,+ jitter: { 0 },+ sleeper: { _ in throw CancellationError() }) {+ attempts.withLock { $0 += 1 }+ throw URLError(.timedOut)+ }+ }+ #expect(attempts.withLock { $0 } == 1)+ }++ @Test func redirectPolicyPermanentlyStripsAuthorizationAfterHostChange() throws {+ var original = rangeRequest(length: 4)+ original.setValue("Bearer secret", forHTTPHeaderField: "Authorization")+ var policy = RemoteRedirectPolicy(+ originalRequest: original,+ maximumRedirects: 3)+ let sourceResponse = HTTPURLResponse(+ url: original.url!,+ statusCode: 302,+ httpVersion: nil,+ headerFields: nil)!++ var storageRequest = URLRequest(+ url: URL(string: "https://storage.test/signed?token=private")!)+ storageRequest.httpMethod = "GET"+ let first = try policy.request(+ response: sourceResponse,+ proposedRequest: storageRequest)+ #expect(first.value(forHTTPHeaderField: "Authorization") == nil)+ #expect(first.value(forHTTPHeaderField: "Range") == "bytes=0-3")+ #expect(first.value(forHTTPHeaderField: "Accept-Encoding") == "identity")++ let storageResponse = HTTPURLResponse(+ url: storageRequest.url!,+ statusCode: 302,+ httpVersion: nil,+ headerFields: nil)!+ var backToSource = URLRequest(url: original.url!)+ backToSource.setValue("Bearer leaked", forHTTPHeaderField: "Authorization")+ let second = try policy.request(+ response: storageResponse,+ proposedRequest: backToSource)+ #expect(second.value(forHTTPHeaderField: "Authorization") == nil)+ #expect(second.value(forHTTPHeaderField: "Range") == "bytes=0-3")+ }++ @Test func redirectPolicyRejectsNonHTTPSAndExcessHops() throws {+ let original = rangeRequest(length: 1)+ let response = HTTPURLResponse(+ url: original.url!,+ statusCode: 302,+ httpVersion: nil,+ headerFields: nil)!++ var insecurePolicy = RemoteRedirectPolicy(+ originalRequest: original,+ maximumRedirects: 2)+ #expect(throws: RepackError.self) {+ _ = try insecurePolicy.request(+ response: response,+ proposedRequest: URLRequest(url: URL(string: "http://storage.test/file")!))+ }++ var boundedPolicy = RemoteRedirectPolicy(+ originalRequest: original,+ maximumRedirects: 1)+ _ = try boundedPolicy.request(+ response: response,+ proposedRequest: URLRequest(url: URL(string: "https://storage.test/file")!))+ #expect(throws: RepackError.self) {+ _ = try boundedPolicy.request(+ response: response,+ proposedRequest: URLRequest(url: URL(string: "https://storage-2.test/file")!))+ }+ }++ private func rangeRequest(length: Int) -> URLRequest {+ let commit = String(repeating: "a", count: 40)+ let url = URL(string: "https://hf.test/owner/model/resolve/\(commit)/file.bin")!+ var request = URLRequest(url: url)+ request.httpMethod = "GET"+ request.setValue("bytes=0-\(length - 1)", forHTTPHeaderField: "Range")+ request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")+ return request+ }+ }+}diff --git a/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swift b/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swiftindex 229bac36..b1535b67 100644--- a/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swift+++ b/Tests/TurboFieldfareRepack/Core/System/DiskSpaceCheckerTests.swift@@ -31,25 +31,23 @@ import Testing#expect(assessed.requiredBytes == required.requiredBytes)}- @Test func insufficientCheckReportsExactShortfall() throws {+ @Test func insufficientCheckReportsRequiredAndAvailableBytes() throws {let root = FileManager.default.temporaryDirectory.appendingPathComponent("turbofieldfare-space-\(UUID().uuidString)", isDirectory: true)try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)defer { try? FileManager.default.removeItem(at: root) }let target = root.appendingPathComponent("model.gturbo", isDirectory: true)- let available = try DiskSpaceChecker.assess(path: target.path,- bytes: 0,- reserveBytes: 0).availableBytes+ let required = UInt64.max#expect {_ = try DiskSpaceChecker.requireAvailable(path: target.path,- bytes: available,- reserveBytes: 1)+ bytes: required,+ reserveBytes: 0)} throws: { error in- guard case RepackError.diskSpaceInsufficient(_, let required, let actual) = error else {+ guard case RepackError.diskSpaceInsufficient(_, let reportedRequired, let actual) = error else {return false}- return required == available + 1 && actual == available+ return reportedRequired == required && actual < required}}}diff --git a/Tests/TurboFieldfareRepack/Core/System/InstallLockTests.swift b/Tests/TurboFieldfareRepack/Core/System/InstallLockTests.swiftnew file mode 100644index 00000000..4b66f8d2--- /dev/null+++ b/Tests/TurboFieldfareRepack/Core/System/InstallLockTests.swift@@ -0,0 +1,184 @@+import Darwin+import Foundation+import Synchronization+import Testing+@testable import TurboFieldfareRepackCore++@Suite struct InstallLockTests {+ @Test func twoContendersForCanonicalTargetCannotBothAcquire() throws {+ let root = temporaryRoot("contenders")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let output = (root as NSString).appendingPathComponent("model.gturbo")+ var first: InstallLock? = try InstallLock.acquire(outputDirectory: output)++ #expect(throws: RepackError.self) {+ _ = try InstallLock.acquire(outputDirectory: output)+ }++ first = nil+ _ = try InstallLock.acquire(outputDirectory: output)+ #expect(first == nil)+ }++ @Test func asyncInstallHoldsLockUntilOperationFinishes() async throws {+ let root = temporaryRoot("async-operation")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let output = (root as NSString).appendingPathComponent("model.gturbo")+ HangingInstallURLProtocol.reset()+ let task = Task {+ try await RemoteStreamingRepacker(+ options: RemoteStreamingRepackOptions(+ repoID: "owner/model",+ revision: "main",+ outputDir: output,+ minFreeReserveBytes: 0,+ overwrite: true,+ downloadSession: RemoteDownloadSession(+ protocolClasses: [HangingInstallURLProtocol.self]),+ baseURL: URL(string: "https://lock.test")!,+ rangeRetryAttempts: 0,+ retryBaseDelayNs: 0)+ ).run()+ }++ for _ in 0..<200 where !HangingInstallURLProtocol.started {+ try await Task.sleep(for: .milliseconds(5))+ }+ #expect(HangingInstallURLProtocol.started)+ do {+ _ = try InstallLock.acquire(outputDirectory: output)+ Issue.record("second contender acquired the active install lock")+ } catch let error as RepackError {+ guard case .installBusy = error else {+ Issue.record("expected installBusy, got \(error)")+ task.cancel()+ return+ }+ }++ task.cancel()+ await #expect(throws: (any Error).self) {+ _ = try await task.value+ }+ _ = try InstallLock.acquire(outputDirectory: output)+ }++ @Test func symlinkedParentAliasesContendOnOnePhysicalLock() throws {+ let root = temporaryRoot("alias")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let physical = (root as NSString).appendingPathComponent("physical")+ let alias = (root as NSString).appendingPathComponent("alias")+ try Posix.mkdirP(physical)+ try FileManager.default.createSymbolicLink(+ atPath: alias,+ withDestinationPath: physical)+ let first = try InstallLock.acquire(+ outputDirectory: (physical as NSString).appendingPathComponent("model.gturbo"))++ #expect(throws: RepackError.self) {+ _ = try InstallLock.acquire(+ outputDirectory: (alias as NSString).appendingPathComponent("model.gturbo"))+ }+ withExtendedLifetime(first) {}+ }++ @Test func symlinkedLockIsRejectedWithoutFollowingIt() throws {+ let root = temporaryRoot("lock-symlink")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let output = (root as NSString).appendingPathComponent("model.gturbo")+ let victim = (root as NSString).appendingPathComponent("victim")+ FileManager.default.createFile(atPath: victim, contents: Data())+ try FileManager.default.createSymbolicLink(+ atPath: output + ".install.lock",+ withDestinationPath: victim)++ #expect(throws: RepackError.self) {+ _ = try InstallLock.acquire(outputDirectory: output)+ }+ }++ @Test func lockIsReleasedWhenOwningProcessIsKilled() throws {+ let root = temporaryRoot("process-death")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let output = (root as NSString).appendingPathComponent("model.gturbo")+ let paths = try RemoteInstallPaths(outputDirectory: output)+ let holder = Process()+ holder.executableURL = URL(fileURLWithPath: "/usr/bin/lockf")+ holder.arguments = ["-k", paths.lockFile, "/bin/sleep", "30"]+ try holder.run()+ defer {+ if holder.isRunning {+ holder.terminate()+ holder.waitUntilExit()+ }+ }++ var observedContention = false+ for _ in 0..<100 {+ do {+ _ = try InstallLock.acquire(outputDirectory: output)+ } catch {+ observedContention = true+ break+ }+ Thread.sleep(forTimeInterval: 0.01)+ }+ #expect(observedContention)+ #expect(throws: RepackError.self) {+ _ = try InstallLock.acquire(outputDirectory: output)+ }++ #expect(kill(holder.processIdentifier, SIGKILL) == 0)+ holder.waitUntilExit()+ _ = try InstallLock.acquire(outputDirectory: output)+ }++ @Test func openedLockDescriptorDetectsPathReplacement() throws {+ let root = temporaryRoot("inode-replacement")+ defer { try? FileManager.default.removeItem(atPath: root) }+ let path = (root as NSString).appendingPathComponent("model.install.lock")+ let descriptor = try Posix.openLock(path)+ defer { close(descriptor) }++ #expect(try Posix.descriptorMatchesPath(descriptor, path: path))+ try FileManager.default.removeItem(atPath: path)+ FileManager.default.createFile(atPath: path, contents: Data())++ #expect(try !Posix.descriptorMatchesPath(descriptor, path: path))+ }++ private func temporaryRoot(_ tag: String) -> String {+ let path = (NSTemporaryDirectory() as NSString)+ .appendingPathComponent("turbofieldfare-lock-\(tag)-\(UUID().uuidString)")+ try? FileManager.default.createDirectory(+ atPath: path,+ withIntermediateDirectories: true)+ return path+ }+}++private final class HangingInstallURLProtocol: URLProtocol, @unchecked Sendable {+ private static let state = Mutex(false)++ static var started: Bool {+ state.withLock { $0 }+ }++ static func reset() {+ state.withLock { $0 = false }+ }++ override class func canInit(with request: URLRequest) -> Bool {+ true+ }++ override class func canonicalRequest(for request: URLRequest) -> URLRequest {+ request+ }++ override func startLoading() {+ Self.state.withLock { $0 = true }+ }++ override func stopLoading() {}+}diff --git a/docs/SYSTEM_DESIGN.md b/docs/SYSTEM_DESIGN.mdindex 3f81b86d..39de32e9 100644--- a/docs/SYSTEM_DESIGN.md+++ b/docs/SYSTEM_DESIGN.md@@ -58,19 +58,27 @@ write a complete safetensors shard to disk.Instead, the repacker:1. reads the source index and tensor metadata;-2. requests bounded remote byte ranges;-3. copies packed values, scales, and biases through tile-sized scratch;-4. writes resident tensors and routed experts directly into their final+2. binds a versioned checkpoint to the pinned source and canonical range plan;+3. requests bounded remote byte ranges;+4. copies packed values, scales, and biases through tile-sized scratch;+5. makes each completed range durable before recording its destination digest;+6. writes resident tensors and routed experts directly into their finallocations;-5. omits the vision tensors; and-6. writes `manifest.json` after every file listed in it is complete and hashed,- then writes `verified-install.json`.+7. omits the vision tensors; and+8. writes and verifies `manifest.json` and `verified-install.json` in the+ partial directory before atomically promoting it.The repacker changes the layout but copies the quantized values unchanged. Itnever dequantizes and requantizes them. In the validated install, the largestpayload and scratch heap were 524,288 bytes each. The full 15 GB-class sourcenever exists in a Swift heap buffer.+Cancellation pauses the transaction instead of deleting it. Resume+revalidates the recorded destination digest for every completed range and+downloads only missing or damaged ranges. An advisory lock serializes+inspection, install, resume, discard, and promotion for the target path.+Discard is explicit.+See the [command-line instructions](../README.md#command-line-interface) forinstallation. The [optimization journey](OPTIMIZATION_JOURNEY.md#explicit-reads-made-expert-streaming-work)records the current instruction-checkpoint validation.diff --git a/docs/experiments/summaries/01-model-install-and-expert-io.md b/docs/experiments/summaries/01-model-install-and-expert-io.mdindex 0c640e86..3bbd57d9 100644--- a/docs/experiments/summaries/01-model-install-and-expert-io.md+++ b/docs/experiments/summaries/01-model-install-and-expert-io.md@@ -174,7 +174,8 @@ runtime artifact appears last.- **Hypothesis:** The installer could convert the source model directly fromremote byte ranges without storing or loading the complete source checkpoint.- **Variants tested:** A pinned remote revision, range planning, bounded payload- copying, interruption guards, and final manifest verification.+ copying, durable per-range checkpoints, interruption and process-death+ recovery, explicit discard, and atomic final promotion.- **Evidence:** Avalidated run downloaded 14,952,958,284 bytes in 229 ranges. Its largesttransfer was 64 MiB; peak payload and scratch heap were each 524,288 bytes.@@ -182,10 +183,13 @@ runtime artifact appears last.for `The capital of France is` generated at 5.015 tok/s; this validated theinstall/load path, not answer quality.- **What changed the conclusion:** Nothing; later installs kept the same- core path.+ core path. A later interruption gate reused every checkpointed range,+ redownloaded only the unfinished work, and produced output identical to an+ uninterrupted install.- **Final disposition:** Production.-- **Lesson:** Model installation- must obey the same bounded-memory architecture as inference.+- **Lesson:** Model installation must obey the same bounded-memory architecture+ as inference, and resumability must trust only durable, digest-verified+ destination bytes.[Experiment inventory](../EXPERIMENT_INVENTORY.md) |[Optimization journey](../../OPTIMIZATION_JOURNEY.md) |