Repository navigation
fix(provider): resumable 4-bit model download + restart-safe detection - #372
Conversation
Providers on flaky Wi-Fi could never complete the ~15.6 GB 3-shard `gemma-4-26b-qat-4bit` download, and after it "completed" it wasn't detected so it re-downloaded. Three root causes, all in provider-swift: 1. The foreground/CLI manifest download path was NOT resumable. `downloadManifestModel` -> `downloadManifestFileWithProgress` used `URLSession.downloadTask` with no Range and no resume data, so every interruption restarted the shard from byte 0 (writing throwaway `CFNetworkDownload_*.tmp`). Only the background prefetch used the resumable `streamDownload`/`downloadFile` (HTTP Range, 64 KB flush to a stable `.part`). 2. Interrupted downloads were invisible. Completed shards land in a hidden `.local-staging-…` dir; `snapshots/local` is only created at final publish, and the scanner uses `.skipsHiddenFiles`, so a killed-before- publish download looked "not downloaded" and re-downloaded. 3. On-disk models were hidden by the RAM filter. The picker / `models` listing computed "downloaded" from the memory-filtered scan, so a fully-downloaded model that exceeds available RAM read "not downloaded" forever on marginal-RAM boxes. Fixes: - Route the foreground per-shard download through the resume-capable `downloadManifestFileWithResume` -> `downloadFile` -> `streamDownload` (Range + Content-Range validation + 64 KB streaming flush to disk), so an interrupted shard resumes via `Range: bytes=N-` and never restarts from zero. Keeps the stable staging dir, the size+SHA skip, 4-way concurrency (each shard owns its `.part`), the aggregate-hash gate, and `publishStagedSnapshot`. Byte progress is threaded through `streamDownload` into a new callback-based tracker so the live per-shard bar survives. The streaming path never buffers a whole shard in RAM (flushes every 64 KB), avoiding the jetsam/OOM kill seen on 36 GB Macs. - Finish-on-restart: when staging already holds every shard size+SHA-valid, verify the aggregate and publish without re-downloading; the picker shows "resuming" for a partially-staged build. - Compute the picker / `models` "downloaded" flag from an UNFILTERED on-disk scan (`scanAllModels`); the memory filter only drives the "won't fit" warning. A present-but-too-big model now reads "downloaded (won't fit)". - Removed the now-dead `downloadManifestFileWithProgress`, `DownloadProgressTracker`, and unused `downloadManifestFile`; extracted the progress UI into `ModelDownloadProgress.swift` to keep `ModelCatalog.swift` focused. Tests (mock `URLProtocol`): a mid-stream-dropped foreground shard resumes with a `Range` header and never re-fetches from 0; a pre-populated complete staging dir publishes with zero shard re-downloads; an on-disk-but-too-big model is seen by the unfiltered scan and classified "downloaded" by the picker.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 4 finding(s) (2 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:672— remainingBytesToFetch calculation may allocate large arrays without pre-sizing- Suggestion: Pre-allocate arrays with known capacity:
partBytes.reserveCapacity(jobs.count)before the map operation
- Suggestion: Pre-allocate arrays with known capacity:
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:1084— Data buffer allocation without capacity reservation in streaming download- Suggestion: Use
buffer.reserveCapacity(Self.streamFlushThreshold)before the loop to avoid repeated reallocations during streaming
- Suggestion: Use
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:1097-1124— Redundant buffer operations and onChunk calls in streaming loop- Suggestion: Batch onChunk calls and optimize buffer management by avoiding removeAll(keepingCapacity: true) after every flush
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelDownloadProgress.swift:59— O(n) lookup in progress dictionary for every update- Suggestion: Consider using a more efficient data structure or caching frequently accessed entries if update frequency is high
Type_diligence — ✅ No issues found
Additive_complexity — 6 finding(s) (3 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493-500— onChunk callback parameter adds complexity without clear necessity- Suggestion: Consider if this callback is truly needed or if progress could be tracked differently. The callback adds coupling between download logic and progress reporting.
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:659-678— Complex capacity calculation logic duplicated across methods- Suggestion: Extract the capacity calculation with partBytes into a shared helper method to avoid duplication and improve maintainability.
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:680-690— Finish-on-restart logic adds significant complexity to download flow- Suggestion: Consider if this edge case handling could be simplified or moved to a separate method to reduce cognitive load in the main download path.
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelDownloadProgress.swift:1-263— Entire progress tracking system extracted but still tightly coupled- Suggestion: While extraction helps, the progress system is still deeply coupled to the download implementation. Consider a more generic progress interface.
- 🟡 [MEDIUM]
provider-swift/Sources/darkbloom/StartCommand.swift:578-625— Complex picker entry building with many parameters- Suggestion: The buildPickerEntries method takes 5 parameters and has complex logic. Consider breaking this into smaller, more focused methods or using a configuration object.
- 🔵 [INFO]
provider-swift/Sources/darkbloom/StartCommand.swift:724-750— Multiple scans and ID set building could be consolidated- Suggestion: The logic for building downloadedIDs, localMemoryByID, and resumableIDs could be consolidated into a single scan operation to reduce redundant work.
10 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| let partBytes = jobs.map { fileSize($0.destination.appendingPathExtension("part")) } | ||
| try Self.ensureAvailableCapacity( | ||
| at: snapshotsDir, | ||
| requiredBytes: Self.remainingBytesToFetch( |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ remainingBytesToFetch calculation may allocate large arrays without pre-sizing
💡 Suggestion: Pre-allocate arrays with known capacity: partBytes.reserveCapacity(jobs.count) before the map operation
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| @@ -1441,6 +1084,10 @@ public struct ModelDownloader: Sendable { | |||
| // errors mid-transfer (connection drop), flush whatever was buffered | |||
There was a problem hiding this comment.
🔵 [INFO] ⚡ Data buffer allocation without capacity reservation in streaming download
💡 Suggestion: Use buffer.reserveCapacity(Self.streamFlushThreshold) before the loop to avoid repeated reallocations during streaming
📊 Score: 2×3 = 6 · Category: unbounded_allocations
| @@ -1471,7 +1124,10 @@ public struct ModelDownloader: Sendable { | |||
| } | |||
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Redundant buffer operations and onChunk calls in streaming loop
💡 Suggestion: Batch onChunk calls and optimize buffer management by avoiding removeAll(keepingCapacity: true) after every flush
📊 Score: 2×4 = 8 · Category: repeated_work
| /// Fed by byte-progress callbacks from the streaming downloader and read on a | ||
| /// timer by `ProgressRenderer`. Registration order is preserved so the rendered | ||
| /// rows stay stable across frames. | ||
| final class ManifestDownloadProgress: @unchecked Sendable { |
There was a problem hiding this comment.
🔵 [INFO] ⚡ O(n) lookup in progress dictionary for every update
💡 Suggestion: Consider using a more efficient data structure or caching frequently accessed entries if update frequency is high
📊 Score: 2×3 = 6 · Category: inefficient_data_structures
| /// from a `.part` file when present, verifying size + SHA-256 before | ||
| /// promoting to the final staged path. Reuses the resume-capable | ||
| /// `downloadFile` helper (Range requests, Content-Range validation, retries). | ||
| /// | ||
| /// `onChunk(bytesOnDisk)` reports cumulative bytes-on-disk for this file as | ||
| /// it streams, so the foreground path can render a live per-shard bar; the | ||
| /// background prefetch passes nil and accounts progress per whole file. | ||
| private func downloadManifestFileWithResume( |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 onChunk callback parameter adds complexity without clear necessity
💡 Suggestion: Consider if this callback is truly needed or if progress could be tracked differently. The callback adds coupling between download logic and progress reporting.
📊 Score: 3×4 = 12 · Category: over-abstraction
| ) | ||
| } | ||
|
|
||
| // Resume: skip files already staged + valid, and size the capacity | ||
| // pre-check to only the bytes that remain (less anything already saved in a | ||
| // `.part`) so a near-complete resume isn't rejected for lacking room equal | ||
| // to the whole model. Only the not-yet-valid files are enqueued below. | ||
| // Resume: skip files already staged + valid; only the not-yet-valid files | ||
| // are enqueued below. | ||
| let alreadyValid = jobs.map { Self.fileMatches($0.destination, size: $0.file.sizeBytes, sha256: $0.file.sha256) } | ||
| // The foreground per-file downloader does a full GET (it does NOT byte- | ||
| // resume — it deletes any stale `.part`), so only fully-valid files are | ||
| // creditable here; every not-yet-valid file needs its full size. (Only the | ||
| // background `prefetch` path byte-resumes and may credit `.part` bytes.) | ||
| // The foreground per-file downloader now byte-resumes (streams to a stable | ||
| // `.part` and appends via HTTP `Range`), so credit any bytes already saved | ||
| // in each `.part`: a near-complete resume of a big shard must not be charged | ||
| // disk room equal to the whole shard. | ||
| let partBytes = jobs.map { fileSize($0.destination.appendingPathExtension("part")) } | ||
| try Self.ensureAvailableCapacity( | ||
| at: snapshotsDir, | ||
| requiredBytes: Self.remainingBytesToFetch( | ||
| sizes: jobs.map(\.file.sizeBytes), alreadyValid: alreadyValid | ||
| sizes: jobs.map(\.file.sizeBytes), alreadyValid: alreadyValid, partBytes: partBytes | ||
| ) | ||
| ) | ||
| let pending = zip(jobs, alreadyValid).filter { !$0.1 }.map(\.0) | ||
|
|
||
| // Set up delegate-based session for progress tracking. | ||
| let tracker = DownloadProgressTracker() | ||
| let delegateSession = URLSession( | ||
| configuration: urlSession.configuration, | ||
| delegate: tracker, | ||
| delegateQueue: nil | ||
| ) | ||
| defer { delegateSession.finishTasksAndInvalidate() } | ||
| // FINISH-ON-RESTART: a prior run already staged every shard size+SHA-valid |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Complex capacity calculation logic duplicated across methods
💡 Suggestion: Extract the capacity calculation with partBytes into a shared helper method to avoid duplication and improve maintainability.
📊 Score: 2×3 = 6 · Category: duplicate logic
| // the scanner, so the picker showed "not downloaded"). Don't re-download — | ||
| // verify the aggregate and publish. | ||
| if pending.isEmpty { | ||
| try finalizeStagedManifest(model: model, manifest: manifest, jobs: jobs, stagingDir: stagingDir, cacheDir: cacheDir) | ||
| onProgress?(ProgressEvent(file: model.id, bytesDownloaded: manifest.totalSizeBytes, bytesTotal: manifest.totalSizeBytes)) | ||
| return | ||
| } | ||
|
|
||
| let renderer = ProgressRenderer() | ||
| // Live per-shard progress. Seed each pending file's bar with any bytes | ||
| // already saved in its `.part` (a resumed prefix) so the display reflects | ||
| // real on-disk progress instead of restarting the bar at 0%. |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Finish-on-restart logic adds significant complexity to download flow
💡 Suggestion: Consider if this edge case handling could be simplified or moved to a separate method to reduce cognitive load in the main download path.
📊 Score: 3×4 = 12 · Category: over-configuration
| /// Download progress tracking + terminal rendering for the foreground model | ||
| /// download path (`darkbloom models download` / the interactive picker). | ||
| /// | ||
| /// Split out of `ModelCatalog.swift` so that file stays focused on catalog + | ||
| /// download orchestration. The tracker here is callback-driven (fed by the | ||
| /// streaming, byte-resumable downloader in `ModelCatalog.swift`) rather than a | ||
| /// `URLSessionDownloadDelegate`: downloads now stream straight to a `.part` | ||
| /// file for true byte-level resume, so there is no `URLSessionDownloadTask` to | ||
| /// observe — progress arrives as cumulative-bytes-on-disk callbacks instead. | ||
|
|
||
| import Foundation | ||
| #if canImport(Darwin) | ||
| import Darwin | ||
| #endif | ||
|
|
||
| // MARK: - Per-file progress | ||
|
|
||
| /// Per-file progress state rendered by `ProgressRenderer`. | ||
| struct FileProgress: Sendable { | ||
| let label: String | ||
| let expectedBytes: Int64 | ||
| var downloadedBytes: Int64 = 0 | ||
| /// Bytes already on disk when tracking started (a resumed `.part` prefix). | ||
| /// Excluded from the speed/ETA math so a resume doesn't report an inflated | ||
| /// instantaneous rate for bytes it never actually transferred this run. | ||
| var baselineBytes: Int64 = 0 | ||
| var startTime: Date = Date() | ||
| var completed: Bool = false | ||
| var completionTime: Date? | ||
|
|
||
| /// Bytes/second over this run's transfer (excludes the resumed prefix). | ||
| var speed: Double { | ||
| let elapsed = (completionTime ?? Date()).timeIntervalSince(startTime) | ||
| guard elapsed > 0.1 else { return 0 } | ||
| return Double(max(0, downloadedBytes - baselineBytes)) / elapsed | ||
| } | ||
|
|
||
| /// Estimated seconds remaining. | ||
| var eta: Double? { | ||
| guard speed > 0, expectedBytes > 0 else { return nil } | ||
| let remaining = Double(expectedBytes - downloadedBytes) | ||
| guard remaining > 0 else { return nil } | ||
| return remaining / speed | ||
| } | ||
|
|
||
| var fraction: Double { | ||
| guard expectedBytes > 0 else { return 0 } | ||
| return min(1.0, Double(downloadedBytes) / Double(expectedBytes)) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Tracker | ||
|
|
||
| /// Thread-safe per-file download progress keyed by file label (manifest path). | ||
| /// | ||
| /// Fed by byte-progress callbacks from the streaming downloader and read on a | ||
| /// timer by `ProgressRenderer`. Registration order is preserved so the rendered | ||
| /// rows stay stable across frames. | ||
| final class ManifestDownloadProgress: @unchecked Sendable { | ||
|
|
||
| private let lock = NSLock() | ||
| private var progress: [String: FileProgress] = [:] | ||
| private var order: [String] = [] | ||
|
|
||
| /// Register a file to track. `initialBytes` seeds a resumed `.part` prefix | ||
| /// so the bar starts where the previous run left off (and is excluded from | ||
| /// the speed math via `baselineBytes`). | ||
| func register(label: String, expectedBytes: Int64, initialBytes: Int64 = 0) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| if progress[label] == nil { order.append(label) } | ||
| var p = FileProgress(label: label, expectedBytes: expectedBytes) | ||
| p.downloadedBytes = max(0, initialBytes) | ||
| p.baselineBytes = max(0, initialBytes) | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Update cumulative bytes-on-disk for a file. | ||
| func update(label: String, downloadedBytes: Int64) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = downloadedBytes | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Mark a file complete (full size, stop the clock). | ||
| func complete(label: String) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = p.expectedBytes > 0 ? p.expectedBytes : p.downloadedBytes | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Thread-safe snapshot of all tracked file progress, in registration order. | ||
| var allProgress: [FileProgress] { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return order.compactMap { progress[$0] } | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Renderer | ||
|
|
||
| /// Renders a multi-line progress display to the terminal using ANSI escape | ||
| /// codes. Falls back to simple per-file messages when stdout is not a TTY. | ||
| final class ProgressRenderer: @unchecked Sendable { | ||
|
|
||
| private let isTTY: Bool | ||
| private var linesPrinted: Int = 0 | ||
| private let lock = NSLock() | ||
| /// Set of labels already printed in non-TTY mode. | ||
| private var printedLabels: Set<String> = [] | ||
|
|
||
| init() { | ||
| self.isTTY = isatty(STDOUT_FILENO) != 0 | ||
| } | ||
|
|
||
| /// Render a frame given the current file progress snapshot. | ||
| func render(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if !isTTY { | ||
| renderPlain(files) | ||
| return | ||
| } | ||
| renderANSI(files) | ||
| } | ||
|
|
||
| /// Final render: clear the progress area and print completion summary. | ||
| func finish(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if isTTY { | ||
| // Move up and clear all lines. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| for _ in 0..<linesPrinted { | ||
| print("\u{1B}[2K") | ||
| } | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| linesPrinted = 0 | ||
| } | ||
| } | ||
|
|
||
| // Print final summary lines. | ||
| for f in files { | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(max(0, f.downloadedBytes - f.baselineBytes)) / elapsed : 0 | ||
| let speedStr = Self.formatSpeed(avgSpeed) | ||
| let timeStr = Self.formatDuration(elapsed) | ||
| print(" \u{2713} \(f.label) \(totalStr) \(speedStr) \(timeStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - ANSI rendering | ||
|
|
||
| private func renderANSI(_ files: [FileProgress]) { | ||
| // Move cursor up to overwrite previous render. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| } | ||
|
|
||
| let termWidth = Self.terminalWidth() | ||
| var lines = 0 | ||
| for f in files { | ||
| print("\u{1B}[2K", terminator: "") // Clear the line | ||
| let line = Self.formatLine(f, termWidth: termWidth) | ||
| print(line) | ||
| lines += 1 | ||
| } | ||
| linesPrinted = lines | ||
| fflush(stdout) | ||
| } | ||
|
|
||
| private func renderPlain(_ files: [FileProgress]) { | ||
| for f in files where f.completed && !printedLabels.contains(f.label) { | ||
| printedLabels.insert(f.label) | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| print(" \u{2713} \(f.label) \(totalStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Line formatting | ||
|
|
||
| private static func formatLine(_ f: FileProgress, termWidth: Int) -> String { | ||
| if f.completed { | ||
| let totalStr = formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(max(0, f.downloadedBytes - f.baselineBytes)) / elapsed : 0 | ||
| return " \u{2713} \(f.label) \(totalStr) \(formatSpeed(avgSpeed)) done" | ||
| } | ||
|
|
||
| let pct = Int(f.fraction * 100) | ||
| let dlStr = formatBytes(f.downloadedBytes) | ||
| let totStr = formatBytes(f.expectedBytes) | ||
| let speedStr = formatSpeed(f.speed) | ||
| let etaStr: String | ||
| if let eta = f.eta { | ||
| etaStr = "ETA \(formatDuration(eta))" | ||
| } else { | ||
| etaStr = "---" | ||
| } | ||
|
|
||
| // Assemble the suffix: " 62% 2.1/4.8 GB 113 MB/s ETA 24s" | ||
| let suffix = " \(String(format: "%3d", pct))% \(dlStr)/\(totStr) \(speedStr) \(etaStr)" | ||
|
|
||
| // Calculate bar width: total - label - prefix - suffix - brackets - spaces | ||
| let labelMaxWidth = min(f.label.count, 45) | ||
| let label = f.label.count > labelMaxWidth | ||
| ? String(f.label.suffix(labelMaxWidth - 1)).padding(toLength: labelMaxWidth, withPad: " ", startingAt: 0) | ||
| : f.label | ||
| let prefix = " \(label) [" | ||
| let postfix = "]\(suffix)" | ||
| let barWidth = max(10, termWidth - prefix.count - postfix.count) | ||
|
|
||
| let filled = Int(f.fraction * Double(barWidth)) | ||
| let empty = barWidth - filled | ||
| let bar = String(repeating: "\u{2588}", count: filled) + String(repeating: "\u{2591}", count: empty) | ||
|
|
||
| return "\(prefix)\(bar)\(postfix)" | ||
| } | ||
|
|
||
| // MARK: - Formatting helpers | ||
|
|
||
| static func formatBytes(_ bytes: Int64) -> String { | ||
| let b = Double(bytes) | ||
| if b < 1024 { return "\(bytes) B" } | ||
| if b < 1_048_576 { return String(format: "%.1f KB", b / 1024) } | ||
| if b < 1_073_741_824 { return String(format: "%.1f MB", b / 1_048_576) } | ||
| return String(format: "%.1f GB", b / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatSpeed(_ bytesPerSec: Double) -> String { | ||
| if bytesPerSec < 1024 { return String(format: "%.0f B/s", bytesPerSec) } | ||
| if bytesPerSec < 1_048_576 { return String(format: "%.0f KB/s", bytesPerSec / 1024) } | ||
| if bytesPerSec < 1_073_741_824 { return String(format: "%.0f MB/s", bytesPerSec / 1_048_576) } | ||
| return String(format: "%.1f GB/s", bytesPerSec / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatDuration(_ seconds: Double) -> String { | ||
| let s = Int(seconds) | ||
| if s < 60 { return "\(s)s" } | ||
| if s < 3600 { return "\(s / 60)m \(s % 60)s" } | ||
| return "\(s / 3600)h \(s / 60 % 60)m" | ||
| } | ||
|
|
||
| static func terminalWidth() -> Int { | ||
| #if canImport(Darwin) | ||
| var w = winsize() | ||
| if ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0, w.ws_col > 0 { | ||
| return Int(w.ws_col) | ||
| } | ||
| #endif | ||
| return 80 | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Entire progress tracking system extracted but still tightly coupled
💡 Suggestion: While extraction helps, the progress system is still deeply coupled to the download implementation. Consider a more generic progress interface.
📊 Score: 2×2 = 4 · Category: misplaced responsibility
| throw ExitCode.failure | ||
| } | ||
|
|
||
| let localByID = Dictionary(uniqueKeysWithValues: snapshot.models.map { ($0.id, $0) }) | ||
| let memoryGb: Double = Double(snapshot.hardware?.memoryGb ?? 16) | ||
|
|
||
| // Build picker entries: filter to models that fit, sort downloaded-first | ||
| // then by size descending. | ||
| var entries: [PickerEntry] = catalog.compactMap { row -> PickerEntry? in | ||
| let entry = row.model | ||
| if let minRam = entry.minRamGb, Double(minRam) > memoryGb { | ||
| return nil | ||
| } | ||
| let isDownloaded = localByID[entry.id] != nil | ||
| let size: Double | ||
| if isDownloaded, let local = localByID[entry.id] { | ||
| size = local.estimatedMemoryGb | ||
| } else { | ||
| size = entry.sizeGb | ||
| } | ||
| return PickerEntry( | ||
| id: entry.id, | ||
| catalogModel: entry, | ||
| displayName: row.displayName, | ||
| sizeGb: size, | ||
| minRamGb: entry.minRamGb, | ||
| downloaded: isDownloaded | ||
| ) | ||
| } | ||
|
|
||
| entries.sort { a, b in | ||
| if a.downloaded != b.downloaded { return a.downloaded } | ||
| return a.sizeGb > b.sizeGb | ||
| } | ||
| // "Downloaded" must be computed from an UNFILTERED on-disk scan: the | ||
| // memory-filtered `snapshot.models` drops models too large for available | ||
| // RAM, which would make a fully-downloaded-but-too-big model read "not | ||
| // downloaded" forever on a marginal-RAM box. The filtered scan is only | ||
| // used (via the renderer's budget check) to flag "won't fit". | ||
| let allLocal = snapshot.hardware.map { ModelScanner.scanAllModels(hardwareInfo: $0) } ?? [] | ||
| let downloadedIDs = Set(allLocal.map(\.id)) | ||
| let localMemoryByID = Dictionary(allLocal.map { ($0.id, $0.estimatedMemoryGb) }, uniquingKeysWith: { first, _ in first }) | ||
| // Builds with an interrupted foreground download staged on disk: show | ||
| // "resuming" so re-selecting finishes rather than restarts. | ||
| let resumableIDs = Set(catalog.compactMap { row -> String? in | ||
| guard !downloadedIDs.contains(row.model.id), let prefix = row.model.r2Prefix else { return nil } | ||
| return ModelDownloader.hasResumableStaging(modelID: row.model.id, r2Prefix: prefix) ? row.model.id : nil | ||
| }) | ||
|
|
||
| let entries = Start.buildPickerEntries( | ||
| rows: catalog, | ||
| downloadedIDs: downloadedIDs, | ||
| localMemoryByID: localMemoryByID, | ||
| resumableIDs: resumableIDs, | ||
| memoryGb: memoryGb | ||
| ) |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Multiple scans and ID set building could be consolidated
💡 Suggestion: The logic for building downloadedIDs, localMemoryByID, and resumableIDs could be consolidated into a single scan operation to reduce redundant work.
📊 Score: 2×3 = 6 · Category: duplicate logic
|
No files in this PR match any Trust boundaries touchedNone of the formally defined TB-xxx boundaries are directly exercised by this diff. Threat coverageNo T-xxx threats are affected. No existing mitigations are strengthened, weakened, or removed. New attack surface not covered by the threat modelTwo areas are worth a brief look before closing:
RecommendationNo immediate security action is required. If 🔐 Threat model: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a16e0f304a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| var entries: [PickerEntry] = rows.compactMap { row in | ||
| let model = row.model | ||
| let isDownloaded = downloadedIDs.contains(model.id) | ||
| if !isDownloaded, let minRam = model.minRamGb, Double(minRam) > memoryGb { |
There was a problem hiding this comment.
Reject non-fitting downloaded picks in fallback picker
In the non-TTY picker path, a downloaded model that is present on disk but filtered out of snapshot.models for available memory now passes this filter because !isDownloaded is false. fallbackPicker accepts all or explicit numbers without the TUI's canFitIndividually guard, and the launchd child later resolves overrides from the memory-filtered snapshot.models, so selecting such a row can install a service that immediately starts with no advertised model. Please either make these rows unselectable in fallback or reject them before returning IDs.
Useful? React with 👍 / 👎.
| try await self.downloadManifestFileWithProgress( | ||
| job, tracker: tracker, session: delegateSession | ||
| ) | ||
| try await self.downloadManifestFileWithResume(job, onChunk: { bytes in |
There was a problem hiding this comment.
Avoid byte-at-a-time foreground downloads
This switches the foreground manifest path from the previous URLSessionDownloadTask implementation to downloadManifestFileWithResume, which ultimately drains URLSession.AsyncBytes one UInt8 at a time in streamDownload. For multi-GB shards with four concurrent downloads, that means billions of async iterator steps in the interactive download path, making normal model installs CPU-bound and much slower than the old delegate download. Please keep byte resume, but use a chunked streaming/delegate path for foreground shards instead of per-byte iteration.
Useful? React with 👍 / 👎.
| // `.part` and appends via HTTP `Range`), so credit any bytes already saved | ||
| // in each `.part`: a near-complete resume of a big shard must not be charged | ||
| // disk room equal to the whole shard. | ||
| let partBytes = jobs.map { fileSize($0.destination.appendingPathExtension("part")) } |
There was a problem hiding this comment.
Preserve complete .part shards on restart
Crediting .part bytes here treats a full-size partial as having nothing left to fetch, but the foreground resume path still enqueues it because the final staged destination is missing. If the process is killed after streaming a multi-GB shard to <dest>.part but before the hash/promote step, the next run sends Range: bytes=<size>-; a normal server returns 416, streamDownload deletes the complete partial, and the entire shard is downloaded again. Please detect full-size .part files and verify/promote them before issuing a range request.
Useful? React with 👍 / 👎.
|
Found 1 test failure on Blacksmith runners: Failure
|
…nloading When a prior run received every byte of a shard into its resumable .part but the process died before the file was verified + promoted, the next run sends Range: bytes=<full>- and the object store answers 416 Range Not Satisfiable. The generic non-2xx guard treated that as an error, deleted the complete .part, and re-downloaded the entire file from byte 0. Handle 416 explicitly (only when we actually sent a Range): drain the empty body and return success so downloadFile's existing SHA/size check promotes the complete prefix, or deletes + restarts a genuinely corrupt/oversized one. Update the URLProtocol test stub to answer 416 past EOF (real R2/S3 behavior) and add a regression test proving the complete .part is promoted, not re-fetched.
…tions The interactive TUI refuses to toggle a model that can't fit in RAM (Space only selects when canFitIndividually), but the non-TTY fallbackPicker had no such guard: a scripted/piped `darkbloom start` could pick (by number or 'all') a downloaded-but-too-big model, which is then served and OOMs on load. Extract the shared budget rule (Start.modelFitsBudget / pickerOSReserveGb) used by both the TUI and the fallback, and add a pure, testable resolveFallbackSelection that rejects won't-fit explicit picks and filters 'all' down to models that fit (erroring if none do). The fallback list now also shows a [won't fit] flag for parity with the TUI. Adds unit tests for the resolver.
…egate streamDownload iterated URLSession.AsyncBytes one UInt8 per async step, which is pathologically slow for multi-GB model shards (one async resumption per byte). Replace it with StreamingFileDownloadDelegate, which receives OS-sized Data chunks via the URLSession data-delegate callbacks and writes each straight to the .part file. Crucially this preserves the backpressure that AsyncBytes gave for free: the chunk is written synchronously inside didReceive(data:), and URLSession does not deliver the next chunk until that returns, so the socket is throttled to disk speed with nothing queued in memory (no drops, no unbounded growth on a slow disk / fast network). Resume/restart/404/416 semantics are unchanged; cancellation flows through withTaskCancellationHandler -> task.cancel() and still leaves a resumable .part. Existing resume + 416 + prefetch resume/verify tests now run through the delegate path; adds tests for many-chunk assembly and the optional-404 .part cleanup.
|
Pushed three review-feedback fixes (all with tests): 1. 2. 3. Tests: 14 ModelCatalog + 36 prefetch + 24 CLI all green locally. |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 4 finding(s) (3 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493-503— downloadManifestFileWithResume creates unbounded onChunk closures in concurrent downloads- Suggestion: Consider using weak references or limiting the number of concurrent downloads to prevent potential memory growth from retained closures
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:659-727— withThrowingTaskGroup creates up to 4 concurrent downloads without proper resource limits- Suggestion: Add explicit resource limits and consider using a semaphore or bounded channel to control concurrent downloads, especially for large model files
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift:155-167— Synchronous file writes in URLSession delegate callback can block network processing- Suggestion: Consider using async file I/O or a background queue for disk writes to avoid blocking the URLSession delegate queue
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelDownloadProgress.swift:58-104— ManifestDownloadProgress uses linear search through order array for progress lookups- Suggestion: Consider using a more efficient data structure or caching mechanism if the number of concurrent downloads grows large
Type_diligence — ✅ No issues found
Additive_complexity — 7 finding(s) (4 blocking)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:12-20— Comment-only reference to extracted code creates maintenance burden- Suggestion: Remove the comment block and let the import speak for itself - the extracted files are self-documenting
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493-503— Optional callback parameter with complex signature adds cognitive load- Suggestion: Consider making onChunk required or use a simpler progress reporting mechanism
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:813-840— File existence and staging detection logic duplicated across methods- Suggestion: Extract shared staging validation logic into a private helper method
- 🟡 [MEDIUM]
provider-swift/Sources/darkbloom/StartCommand.swift:578-606— Complex nested struct hierarchy for picker entries- Suggestion: Flatten the picker data structures or use simpler value types
- 🔴 [CRITICAL]
provider-swift/Sources/darkbloom/StartCommand.swift:608-695— Pure business logic mixed with UI concerns in buildPickerEntries- Suggestion: Split picker entry building from UI-specific filtering and sorting logic
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift:32-71— Complex delegate with multiple responsibilities and state management- Suggestion: Consider splitting into separate download handler and progress tracker classes
- 🔵 [INFO]
provider-swift/Tests/DarkbloomCLITests/PickerEntryTests.swift:14-40— Repetitive test helper methods with similar patterns- Suggestion: Create a shared test fixture builder to reduce duplication
11 finding(s) total, 7 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| /// from a `.part` file when present, verifying size + SHA-256 before | ||
| /// promoting to the final staged path. Reuses the resume-capable | ||
| /// `downloadFile` helper (Range requests, Content-Range validation, retries). | ||
| /// | ||
| /// `onChunk(bytesOnDisk)` reports cumulative bytes-on-disk for this file as | ||
| /// it streams, so the foreground path can render a live per-shard bar; the | ||
| /// background prefetch passes nil and accounts progress per whole file. | ||
| private func downloadManifestFileWithResume( | ||
| _ job: (file: ManifestFile, destination: URL, url: String) | ||
| _ job: (file: ManifestFile, destination: URL, url: String), | ||
| onChunk: (@Sendable (Int64) -> Void)? = nil | ||
| ) async throws { |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ downloadManifestFileWithResume creates unbounded onChunk closures in concurrent downloads
💡 Suggestion: Consider using weak references or limiting the number of concurrent downloads to prevent potential memory growth from retained closures
📊 Score: 3×4 = 12 · Category: unbounded allocations
| @@ -1026,28 +727,26 @@ public struct ModelDownloader: Sendable { | |||
| let job = pending[next] | |||
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ withThrowingTaskGroup creates up to 4 concurrent downloads without proper resource limits
💡 Suggestion: Add explicit resource limits and consider using a semaphore or bounded channel to control concurrent downloads, especially for large model files
📊 Score: 4×3 = 12 · Category: unbounded goroutines
| } | ||
|
|
||
| func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { | ||
| guard setupError == nil, let writer else { return } | ||
| do { | ||
| // Synchronous write == backpressure: the next didReceive(data:) is | ||
| // not delivered until this returns, throttling the socket to disk. | ||
| try writer.write(contentsOf: data) | ||
| written += Int64(data.count) | ||
| onChunk?(baseline + written) | ||
| } catch { | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): write failed (\(error.localizedDescription))") |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ Synchronous file writes in URLSession delegate callback can block network processing
💡 Suggestion: Consider using async file I/O or a background queue for disk writes to avoid blocking the URLSession delegate queue
📊 Score: 2×4 = 8 · Category: blocking I/O
| /// rows stay stable across frames. | ||
| final class ManifestDownloadProgress: @unchecked Sendable { | ||
|
|
||
| private let lock = NSLock() | ||
| private var progress: [String: FileProgress] = [:] | ||
| private var order: [String] = [] | ||
|
|
||
| /// Register a file to track. `initialBytes` seeds a resumed `.part` prefix | ||
| /// so the bar starts where the previous run left off (and is excluded from | ||
| /// the speed math via `baselineBytes`). | ||
| func register(label: String, expectedBytes: Int64, initialBytes: Int64 = 0) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| if progress[label] == nil { order.append(label) } | ||
| var p = FileProgress(label: label, expectedBytes: expectedBytes) | ||
| p.downloadedBytes = max(0, initialBytes) | ||
| p.baselineBytes = max(0, initialBytes) | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Update cumulative bytes-on-disk for a file. | ||
| func update(label: String, downloadedBytes: Int64) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = downloadedBytes | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Mark a file complete (full size, stop the clock). | ||
| func complete(label: String) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = p.expectedBytes > 0 ? p.expectedBytes : p.downloadedBytes | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Thread-safe snapshot of all tracked file progress, in registration order. | ||
| var allProgress: [FileProgress] { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return order.compactMap { progress[$0] } | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] ⚡ ManifestDownloadProgress uses linear search through order array for progress lookups
💡 Suggestion: Consider using a more efficient data structure or caching mechanism if the number of concurrent downloads grows large
📊 Score: 2×3 = 6 · Category: inefficient data structures
| .appendingPathComponent("local", isDirectory: true) | ||
| } | ||
|
|
||
| /// Stable foreground-download staging dir name, keyed by the manifest's | ||
| /// `r2Prefix` so an interrupted download resumes into the SAME dir instead of | ||
| /// a throwaway UUID. `r2Prefix` is path-like (e.g. "v2/org__name/version"); | ||
| /// flatten it to a single safe component. | ||
| static func localStagingDirName(r2Prefix: String) -> String { | ||
| ".local-staging-" + r2Prefix | ||
| .replacingOccurrences(of: "/", with: "__") | ||
| .replacingOccurrences(of: "\\", with: "__") | ||
| } | ||
|
|
||
| /// Whether an interrupted foreground download left resumable content staged on | ||
| /// disk for this model build (keyed by `r2Prefix`): a completed shard or a | ||
| /// `.part` prefix in the stable `.local-staging-…` dir. Lets the picker show | ||
| /// "resuming" instead of "not downloaded" for a partially-downloaded model so | ||
| /// re-selecting it FINISHES the download rather than appearing to start over. | ||
| public static func hasResumableStaging(modelID: String, r2Prefix: String) -> Bool { | ||
| let stagingDir = cacheModelDirectory(for: modelID) | ||
| .appendingPathComponent("snapshots", isDirectory: true) | ||
| .appendingPathComponent(localStagingDirName(r2Prefix: r2Prefix), isDirectory: true) | ||
| guard let entries = try? FileManager.default.contentsOfDirectory(atPath: stagingDir.path) else { | ||
| return false | ||
| } | ||
| // Any non-hidden staged entry (a finished file, a `.part`, or a nested | ||
| // subdir like `adapters/`) is resumable content worth finishing. | ||
| return entries.contains { !$0.hasPrefix(".") } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 File existence and staging detection logic duplicated across methods
💡 Suggestion: Extract shared staging validation logic into a private helper method
📊 Score: 2×3 = 6 · Category: duplicate logic
| // MARK: - Interactive Catalog Picker | ||
|
|
||
| /// Entry shown in the interactive TUI model picker. | ||
| private struct PickerEntry { | ||
| /// | ||
| /// `downloaded` is computed from an UNFILTERED on-disk check (not the | ||
| /// available-memory-filtered scan) so a fully-downloaded model that exceeds | ||
| /// available RAM still reads "downloaded (won't fit)" rather than "not | ||
| /// downloaded". `resumable` flags a build whose foreground download was | ||
| /// interrupted (staging on disk) so the picker can show "resuming". | ||
| struct PickerEntry: Equatable { | ||
| let id: String | ||
| let catalogModel: CatalogModel | ||
| let displayName: String | ||
| let sizeGb: Double | ||
| let minRamGb: Int? | ||
| let downloaded: Bool | ||
| var resumable: Bool = false | ||
| } | ||
|
|
||
| private struct PickerCatalogRow { | ||
| struct PickerCatalogRow { | ||
| let model: CatalogModel | ||
| let displayName: String | ||
| } | ||
|
|
||
| /// Build picker entries from catalog rows and on-disk state. Pure (no IO) so | ||
| /// the downloaded / won't-fit / resuming classification is unit-testable. | ||
| /// | ||
| /// - `downloadedIDs` MUST come from an UNFILTERED on-disk scan so a | ||
| /// present-but-too-big model still reads "downloaded". |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Complex nested struct hierarchy for picker entries
💡 Suggestion: Flatten the picker data structures or use simpler value types
📊 Score: 3×4 = 12 · Category: over-abstraction
| final class StreamingFileDownloadDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable { | ||
| enum Outcome { | ||
| /// Body streamed to `.part` successfully (appended or rewritten). | ||
| case success | ||
| /// 416: the `.part` is already at/beyond the object length. | ||
| case completeBeyondRange | ||
| /// 404/403 for an optional file. | ||
| case notFound(Int) | ||
| } | ||
|
|
||
| private let partial: URL | ||
| private let existingBytes: Int64 | ||
| private let label: String | ||
| private let onChunk: (@Sendable (Int64) -> Void)? | ||
| private let fm = FileManager.default | ||
|
|
||
| // Mutated only from the URLSession delegate queue (callbacks are serialized). | ||
| private var writer: FileHandle? | ||
| private var baseline: Int64 = 0 | ||
| private var written: Int64 = 0 | ||
| private var decided: Outcome? | ||
| private var setupError: Error? | ||
|
|
||
| // The continuation may be resumed from any delegate callback; guard it. | ||
| private let lock = NSLock() | ||
| private var continuation: CheckedContinuation<Outcome, Error>? | ||
| private var resumed = false | ||
|
|
||
| init( | ||
| partial: URL, | ||
| existingBytes: Int64, | ||
| label: String, | ||
| onChunk: (@Sendable (Int64) -> Void)? | ||
| ) { | ||
| self.partial = partial | ||
| self.existingBytes = existingBytes | ||
| self.label = label | ||
| self.onChunk = onChunk | ||
| super.init() | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Complex delegate with multiple responsibilities and state management
💡 Suggestion: Consider splitting into separate download handler and progress tracker classes
📊 Score: 3×3 = 9 · Category: over-abstraction
| struct PickerEntryTests { | ||
|
|
||
| private func model(_ id: String, sizeGb: Double = 10, minRamGb: Int? = nil) -> CatalogModel { | ||
| CatalogModel( | ||
| id: id, | ||
| s3Name: id, | ||
| displayName: id, | ||
| sizeGb: sizeGb, | ||
| minRamGb: minRamGb, | ||
| r2Prefix: "v2/\(id)/v1" | ||
| ) | ||
| } | ||
|
|
||
| private func row(_ m: CatalogModel) -> Start.PickerCatalogRow { | ||
| Start.PickerCatalogRow(model: m, displayName: m.displayName) | ||
| } | ||
|
|
||
| private func entry(_ id: String, sizeGb: Double, downloaded: Bool = true) -> Start.PickerEntry { | ||
| Start.PickerEntry( | ||
| id: id, | ||
| catalogModel: model(id, sizeGb: sizeGb), | ||
| displayName: id, | ||
| sizeGb: sizeGb, | ||
| minRamGb: nil, | ||
| downloaded: downloaded | ||
| ) | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Repetitive test helper methods with similar patterns
💡 Suggestion: Create a shared test fixture builder to reduce duplication
📊 Score: 2×2 = 4 · Category: duplicate logic
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bc0a084d3a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| case .completeBeyondRange: | ||
| // The `.part` already holds the whole object; the caller's SHA/size | ||
| // check promotes it (or deletes + restarts a corrupt/oversized one). | ||
| onChunk?(existingBytes) | ||
| return true |
There was a problem hiding this comment.
Gate 416 promotion on verified downloads
In the legacy CDN path (downloadLegacyModelFromCDN) all calls to downloadFile leave expectedSHA256 nil, but this 416 branch now returns success for any existing .part and downloadFile immediately moves it to the final snapshot. If a stale or oversized partial is left for a legacy model and R2/S3 answers the resume request with 416, we publish that partial without any size or hash check, corrupting the local model; the caller-side SHA/size check only exists for manifest jobs. Please only use this fast path when a verifier is present, or parse the 416 length and restart otherwise.
Useful? React with 👍 / 👎.
On a 416 (Range Not Satisfiable) during a resumed download the delegate unconditionally returned `.completeBeyondRange`, so `downloadFile` moved the existing `.part` to the final destination. On the manifest path a SHA check gates that move, but the legacy path (`downloadLegacyModelFromCDN`) always calls `downloadFile` with `expectedSHA256 == nil`, so a stale, oversized, or undersized `.part` was promoted and served with NO verification at all. Fix: a 416 carries `Content-Range: bytes */<total>` (RFC 7233; R2/S3 send it). Use it to size-verify the `.part` regardless of whether a SHA is available: - Add `StreamingFileDownloadDelegate.parseContentRangeTotal(_:)` parsing the total from both `bytes */123` and `bytes 0-9/123` forms. - In the 416 branch, only keep `.completeBeyondRange` when the total is present AND `existingBytes == total` (the `.part` is exactly the full object). Otherwise delete the `.part` and set a RETRYABLE `downloadFailed` error (not CancellationError, which is never retried) so `downloadFile`'s loop re-runs `streamDownload` from byte 0 (existingBytes == 0 → no Range → full GET). This closes the legacy-path unverified-promote gap: a size-mismatched `.part` on 416 is now discarded and re-fetched rather than published. Tests: existing `downloadFilePromotesCompletePartOn416` still passes (a `.part` whose size == full size is promoted). New `downloadFileDiscardsOversizedPartOn416` writes an oversized `.part` and asserts the final file is the correct re-downloaded payload and the `.part` is gone.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 4 finding(s) (2 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493-503— downloadManifestFileWithResume creates unbounded onChunk closures in concurrent downloads- Suggestion: Consider using weak references or limiting the number of concurrent downloads to prevent potential memory growth from retained closures
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:659-727— fileSize() called multiple times on same paths during resume calculation- Suggestion: Cache fileSize() results in local variables since file sizes don't change during this operation
- 🔴 [CRITICAL]
provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift:180-190— Synchronous file writes in URLSession delegate callback block network processing- Suggestion: Consider using async file I/O or a background queue for writes to avoid blocking the URLSession delegate queue, though this may require careful coordination to maintain backpressure
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelDownloadProgress.swift:58-103— ManifestDownloadProgress uses linear search through order array for progress updates- Suggestion: Use a more efficient data structure or maintain reverse lookup map from label to index to avoid O(n) lookups on progress updates
Type_diligence — ✅ No issues found
Additive_complexity — 8 finding(s) (4 blocking)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493— onChunk callback parameter with default nil adds complexity without clear necessity- Suggestion: Consider making onChunk required or removing the default parameter to clarify the interface
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:641-757— Complex downloadManifestModel method mixes multiple responsibilities- Suggestion: Extract the finish-on-restart logic and progress tracking setup into separate methods to reduce cognitive load
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:813-841— hasResumableStaging method duplicates file existence checking logic- Suggestion: Consider reusing existing file utility methods or consolidating with similar directory scanning logic
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelDownloadProgress.swift:1-263— Entire progress tracking system extracted but creates tight coupling- Suggestion: Consider keeping simpler progress tracking inline or using a more decoupled event-based approach
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift:1-246— Complex delegate class reimplements URLSession functionality- Suggestion: Evaluate if URLSession.downloadTask with resume data could achieve the same result with less code
- 🔵 [INFO]
provider-swift/Sources/darkbloom/StartCommand.swift:578-628— Multiple nested structs and static methods for picker logic- Suggestion: Consider consolidating picker-related types into a single cohesive module
- 🟡 [MEDIUM]
provider-swift/Sources/darkbloom/StartCommand.swift:787-825— Complex picker entry building logic duplicates model filtering- Suggestion: Extract common model filtering/classification logic into a shared utility
- 🔵 [INFO]
provider-swift/Tests/DarkbloomCLITests/PickerEntryTests.swift:1-157— Extensive test setup with many helper methods for simple classification logic- Suggestion: Simplify test helpers or consider if the classification logic itself is too complex
12 finding(s) total, 6 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| /// from a `.part` file when present, verifying size + SHA-256 before | ||
| /// promoting to the final staged path. Reuses the resume-capable | ||
| /// `downloadFile` helper (Range requests, Content-Range validation, retries). | ||
| /// | ||
| /// `onChunk(bytesOnDisk)` reports cumulative bytes-on-disk for this file as | ||
| /// it streams, so the foreground path can render a live per-shard bar; the | ||
| /// background prefetch passes nil and accounts progress per whole file. | ||
| private func downloadManifestFileWithResume( | ||
| _ job: (file: ManifestFile, destination: URL, url: String) | ||
| _ job: (file: ManifestFile, destination: URL, url: String), | ||
| onChunk: (@Sendable (Int64) -> Void)? = nil | ||
| ) async throws { |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ downloadManifestFileWithResume creates unbounded onChunk closures in concurrent downloads
💡 Suggestion: Consider using weak references or limiting the number of concurrent downloads to prevent potential memory growth from retained closures
📊 Score: 3×4 = 12 · Category: unbounded allocations
| @@ -1026,28 +727,26 @@ public struct ModelDownloader: Sendable { | |||
| let job = pending[next] | |||
There was a problem hiding this comment.
🔵 [INFO] ⚡ fileSize() called multiple times on same paths during resume calculation
💡 Suggestion: Cache fileSize() results in local variables since file sizes don't change during this operation
📊 Score: 2×3 = 6 · Category: repeated work
| } | ||
| completionHandler(.allow) | ||
| } | ||
|
|
||
| func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { | ||
| guard setupError == nil, let writer else { return } | ||
| do { | ||
| // Synchronous write == backpressure: the next didReceive(data:) is | ||
| // not delivered until this returns, throttling the socket to disk. | ||
| try writer.write(contentsOf: data) | ||
| written += Int64(data.count) |
There was a problem hiding this comment.
🔴 [CRITICAL] ⚡ Synchronous file writes in URLSession delegate callback block network processing
💡 Suggestion: Consider using async file I/O or a background queue for writes to avoid blocking the URLSession delegate queue, though this may require careful coordination to maintain backpressure
📊 Score: 4×4 = 16 · Category: blocking I/O
| /// rows stay stable across frames. | ||
| final class ManifestDownloadProgress: @unchecked Sendable { | ||
|
|
||
| private let lock = NSLock() | ||
| private var progress: [String: FileProgress] = [:] | ||
| private var order: [String] = [] | ||
|
|
||
| /// Register a file to track. `initialBytes` seeds a resumed `.part` prefix | ||
| /// so the bar starts where the previous run left off (and is excluded from | ||
| /// the speed math via `baselineBytes`). | ||
| func register(label: String, expectedBytes: Int64, initialBytes: Int64 = 0) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| if progress[label] == nil { order.append(label) } | ||
| var p = FileProgress(label: label, expectedBytes: expectedBytes) | ||
| p.downloadedBytes = max(0, initialBytes) | ||
| p.baselineBytes = max(0, initialBytes) | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Update cumulative bytes-on-disk for a file. | ||
| func update(label: String, downloadedBytes: Int64) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = downloadedBytes | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Mark a file complete (full size, stop the clock). | ||
| func complete(label: String) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = p.expectedBytes > 0 ? p.expectedBytes : p.downloadedBytes | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Thread-safe snapshot of all tracked file progress, in registration order. | ||
| var allProgress: [FileProgress] { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return order.compactMap { progress[$0] } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] ⚡ ManifestDownloadProgress uses linear search through order array for progress updates
💡 Suggestion: Use a more efficient data structure or maintain reverse lookup map from label to index to avoid O(n) lookups on progress updates
📊 Score: 2×3 = 6 · Category: inefficient data structures
| @@ -811,16 +493,22 @@ public struct ModelDownloader: Sendable { | |||
| /// from a `.part` file when present, verifying size + SHA-256 before | |||
There was a problem hiding this comment.
🔵 [INFO] 🧩 onChunk callback parameter with default nil adds complexity without clear necessity
💡 Suggestion: Consider making onChunk required or removing the default parameter to clarify the interface
📊 Score: 2×3 = 6 · Category: over-abstraction
| /// Download progress tracking + terminal rendering for the foreground model | ||
| /// download path (`darkbloom models download` / the interactive picker). | ||
| /// | ||
| /// Split out of `ModelCatalog.swift` so that file stays focused on catalog + | ||
| /// download orchestration. The tracker here is callback-driven (fed by the | ||
| /// streaming, byte-resumable downloader in `ModelCatalog.swift`) rather than a | ||
| /// `URLSessionDownloadDelegate`: downloads now stream straight to a `.part` | ||
| /// file for true byte-level resume, so there is no `URLSessionDownloadTask` to | ||
| /// observe — progress arrives as cumulative-bytes-on-disk callbacks instead. | ||
|
|
||
| import Foundation | ||
| #if canImport(Darwin) | ||
| import Darwin | ||
| #endif | ||
|
|
||
| // MARK: - Per-file progress | ||
|
|
||
| /// Per-file progress state rendered by `ProgressRenderer`. | ||
| struct FileProgress: Sendable { | ||
| let label: String | ||
| let expectedBytes: Int64 | ||
| var downloadedBytes: Int64 = 0 | ||
| /// Bytes already on disk when tracking started (a resumed `.part` prefix). | ||
| /// Excluded from the speed/ETA math so a resume doesn't report an inflated | ||
| /// instantaneous rate for bytes it never actually transferred this run. | ||
| var baselineBytes: Int64 = 0 | ||
| var startTime: Date = Date() | ||
| var completed: Bool = false | ||
| var completionTime: Date? | ||
|
|
||
| /// Bytes/second over this run's transfer (excludes the resumed prefix). | ||
| var speed: Double { | ||
| let elapsed = (completionTime ?? Date()).timeIntervalSince(startTime) | ||
| guard elapsed > 0.1 else { return 0 } | ||
| return Double(max(0, downloadedBytes - baselineBytes)) / elapsed | ||
| } | ||
|
|
||
| /// Estimated seconds remaining. | ||
| var eta: Double? { | ||
| guard speed > 0, expectedBytes > 0 else { return nil } | ||
| let remaining = Double(expectedBytes - downloadedBytes) | ||
| guard remaining > 0 else { return nil } | ||
| return remaining / speed | ||
| } | ||
|
|
||
| var fraction: Double { | ||
| guard expectedBytes > 0 else { return 0 } | ||
| return min(1.0, Double(downloadedBytes) / Double(expectedBytes)) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Tracker | ||
|
|
||
| /// Thread-safe per-file download progress keyed by file label (manifest path). | ||
| /// | ||
| /// Fed by byte-progress callbacks from the streaming downloader and read on a | ||
| /// timer by `ProgressRenderer`. Registration order is preserved so the rendered | ||
| /// rows stay stable across frames. | ||
| final class ManifestDownloadProgress: @unchecked Sendable { | ||
|
|
||
| private let lock = NSLock() | ||
| private var progress: [String: FileProgress] = [:] | ||
| private var order: [String] = [] | ||
|
|
||
| /// Register a file to track. `initialBytes` seeds a resumed `.part` prefix | ||
| /// so the bar starts where the previous run left off (and is excluded from | ||
| /// the speed math via `baselineBytes`). | ||
| func register(label: String, expectedBytes: Int64, initialBytes: Int64 = 0) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| if progress[label] == nil { order.append(label) } | ||
| var p = FileProgress(label: label, expectedBytes: expectedBytes) | ||
| p.downloadedBytes = max(0, initialBytes) | ||
| p.baselineBytes = max(0, initialBytes) | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Update cumulative bytes-on-disk for a file. | ||
| func update(label: String, downloadedBytes: Int64) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = downloadedBytes | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Mark a file complete (full size, stop the clock). | ||
| func complete(label: String) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = p.expectedBytes > 0 ? p.expectedBytes : p.downloadedBytes | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Thread-safe snapshot of all tracked file progress, in registration order. | ||
| var allProgress: [FileProgress] { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return order.compactMap { progress[$0] } | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Renderer | ||
|
|
||
| /// Renders a multi-line progress display to the terminal using ANSI escape | ||
| /// codes. Falls back to simple per-file messages when stdout is not a TTY. | ||
| final class ProgressRenderer: @unchecked Sendable { | ||
|
|
||
| private let isTTY: Bool | ||
| private var linesPrinted: Int = 0 | ||
| private let lock = NSLock() | ||
| /// Set of labels already printed in non-TTY mode. | ||
| private var printedLabels: Set<String> = [] | ||
|
|
||
| init() { | ||
| self.isTTY = isatty(STDOUT_FILENO) != 0 | ||
| } | ||
|
|
||
| /// Render a frame given the current file progress snapshot. | ||
| func render(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if !isTTY { | ||
| renderPlain(files) | ||
| return | ||
| } | ||
| renderANSI(files) | ||
| } | ||
|
|
||
| /// Final render: clear the progress area and print completion summary. | ||
| func finish(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if isTTY { | ||
| // Move up and clear all lines. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| for _ in 0..<linesPrinted { | ||
| print("\u{1B}[2K") | ||
| } | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| linesPrinted = 0 | ||
| } | ||
| } | ||
|
|
||
| // Print final summary lines. | ||
| for f in files { | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(max(0, f.downloadedBytes - f.baselineBytes)) / elapsed : 0 | ||
| let speedStr = Self.formatSpeed(avgSpeed) | ||
| let timeStr = Self.formatDuration(elapsed) | ||
| print(" \u{2713} \(f.label) \(totalStr) \(speedStr) \(timeStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - ANSI rendering | ||
|
|
||
| private func renderANSI(_ files: [FileProgress]) { | ||
| // Move cursor up to overwrite previous render. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| } | ||
|
|
||
| let termWidth = Self.terminalWidth() | ||
| var lines = 0 | ||
| for f in files { | ||
| print("\u{1B}[2K", terminator: "") // Clear the line | ||
| let line = Self.formatLine(f, termWidth: termWidth) | ||
| print(line) | ||
| lines += 1 | ||
| } | ||
| linesPrinted = lines | ||
| fflush(stdout) | ||
| } | ||
|
|
||
| private func renderPlain(_ files: [FileProgress]) { | ||
| for f in files where f.completed && !printedLabels.contains(f.label) { | ||
| printedLabels.insert(f.label) | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| print(" \u{2713} \(f.label) \(totalStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Line formatting | ||
|
|
||
| private static func formatLine(_ f: FileProgress, termWidth: Int) -> String { | ||
| if f.completed { | ||
| let totalStr = formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(max(0, f.downloadedBytes - f.baselineBytes)) / elapsed : 0 | ||
| return " \u{2713} \(f.label) \(totalStr) \(formatSpeed(avgSpeed)) done" | ||
| } | ||
|
|
||
| let pct = Int(f.fraction * 100) | ||
| let dlStr = formatBytes(f.downloadedBytes) | ||
| let totStr = formatBytes(f.expectedBytes) | ||
| let speedStr = formatSpeed(f.speed) | ||
| let etaStr: String | ||
| if let eta = f.eta { | ||
| etaStr = "ETA \(formatDuration(eta))" | ||
| } else { | ||
| etaStr = "---" | ||
| } | ||
|
|
||
| // Assemble the suffix: " 62% 2.1/4.8 GB 113 MB/s ETA 24s" | ||
| let suffix = " \(String(format: "%3d", pct))% \(dlStr)/\(totStr) \(speedStr) \(etaStr)" | ||
|
|
||
| // Calculate bar width: total - label - prefix - suffix - brackets - spaces | ||
| let labelMaxWidth = min(f.label.count, 45) | ||
| let label = f.label.count > labelMaxWidth | ||
| ? String(f.label.suffix(labelMaxWidth - 1)).padding(toLength: labelMaxWidth, withPad: " ", startingAt: 0) | ||
| : f.label | ||
| let prefix = " \(label) [" | ||
| let postfix = "]\(suffix)" | ||
| let barWidth = max(10, termWidth - prefix.count - postfix.count) | ||
|
|
||
| let filled = Int(f.fraction * Double(barWidth)) | ||
| let empty = barWidth - filled | ||
| let bar = String(repeating: "\u{2588}", count: filled) + String(repeating: "\u{2591}", count: empty) | ||
|
|
||
| return "\(prefix)\(bar)\(postfix)" | ||
| } | ||
|
|
||
| // MARK: - Formatting helpers | ||
|
|
||
| static func formatBytes(_ bytes: Int64) -> String { | ||
| let b = Double(bytes) | ||
| if b < 1024 { return "\(bytes) B" } | ||
| if b < 1_048_576 { return String(format: "%.1f KB", b / 1024) } | ||
| if b < 1_073_741_824 { return String(format: "%.1f MB", b / 1_048_576) } | ||
| return String(format: "%.1f GB", b / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatSpeed(_ bytesPerSec: Double) -> String { | ||
| if bytesPerSec < 1024 { return String(format: "%.0f B/s", bytesPerSec) } | ||
| if bytesPerSec < 1_048_576 { return String(format: "%.0f KB/s", bytesPerSec / 1024) } | ||
| if bytesPerSec < 1_073_741_824 { return String(format: "%.0f MB/s", bytesPerSec / 1_048_576) } | ||
| return String(format: "%.1f GB/s", bytesPerSec / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatDuration(_ seconds: Double) -> String { | ||
| let s = Int(seconds) | ||
| if s < 60 { return "\(s)s" } | ||
| if s < 3600 { return "\(s / 60)m \(s % 60)s" } | ||
| return "\(s / 3600)h \(s / 60 % 60)m" | ||
| } | ||
|
|
||
| static func terminalWidth() -> Int { | ||
| #if canImport(Darwin) | ||
| var w = winsize() | ||
| if ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0, w.ws_col > 0 { | ||
| return Int(w.ws_col) | ||
| } | ||
| #endif | ||
| return 80 | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Entire progress tracking system extracted but creates tight coupling
💡 Suggestion: Consider keeping simpler progress tracking inline or using a more decoupled event-based approach
📊 Score: 4×3 = 12 · Category: misplaced responsibility
| import Foundation | ||
|
|
||
| /// Streams an HTTP GET body straight to a `.part` file in OS-sized chunks using | ||
| /// the `URLSession` data-delegate callbacks. | ||
| /// | ||
| /// This replaces `URLSession.AsyncBytes`, whose `for await byte in …` yields a | ||
| /// single `UInt8` per async-iterator step. That is pathologically slow for the | ||
| /// multi-GB model shards we download (one async resumption per byte → billions | ||
| /// of them per file). `URLSession.bytes` only exposes a per-byte sequence, so to | ||
| /// get OS-sized `Data` chunks we drop to the delegate API. | ||
| /// | ||
| /// Backpressure — the one virtue of `AsyncBytes` we must NOT lose — is preserved | ||
| /// without any in-memory queue: `URLSession` serializes delegate callbacks and | ||
| /// does not invoke `urlSession(_:dataTask:didReceive:)` again until the previous | ||
| /// call returns. Writing each chunk synchronously to disk here therefore | ||
| /// throttles the socket to disk speed; nothing is buffered beyond the single | ||
| /// chunk the system hands us (so no drops and no unbounded growth on a slow | ||
| /// disk / fast network). | ||
| /// | ||
| /// The resume contract matches the previous `streamDownload` implementation: | ||
| /// - If `existingBytes > 0` the caller sent `Range: bytes=N-`. | ||
| /// - 206 whose `Content-Range` start == N → append to the existing prefix. | ||
| /// - 200 (range ignored) or a mismatched/unverifiable 206 → truncate and rewrite | ||
| /// THIS file from byte 0. | ||
| /// - 404/403 → `.notFound` (caller removes the `.part`; throws iff required). | ||
| /// - 416 with a prefix → size-verify against the 416's `Content-Range: bytes | ||
| /// */<total>`. If the `.part` size equals `<total>` it is the whole object → | ||
| /// `.completeBeyondRange` (caller verifies + promotes it). Otherwise the | ||
| /// `.part` is stale/oversized/undersized → delete it and surface a retryable | ||
| /// error so the caller re-downloads it cleanly from byte 0. | ||
| /// - A mid-stream transport drop leaves every received byte durably in `.part` | ||
| /// and surfaces as a thrown error so the caller retries with a fresh `Range`. | ||
| /// - Cooperative cancellation (`task.cancel()`) surfaces as `CancellationError` | ||
| /// and likewise leaves a resumable `.part`. | ||
| final class StreamingFileDownloadDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable { | ||
| enum Outcome { | ||
| /// Body streamed to `.part` successfully (appended or rewritten). | ||
| case success | ||
| /// 416: the `.part` is already at/beyond the object length. | ||
| case completeBeyondRange | ||
| /// 404/403 for an optional file. | ||
| case notFound(Int) | ||
| } | ||
|
|
||
| private let partial: URL | ||
| private let existingBytes: Int64 | ||
| private let label: String | ||
| private let onChunk: (@Sendable (Int64) -> Void)? | ||
| private let fm = FileManager.default | ||
|
|
||
| // Mutated only from the URLSession delegate queue (callbacks are serialized). | ||
| private var writer: FileHandle? | ||
| private var baseline: Int64 = 0 | ||
| private var written: Int64 = 0 | ||
| private var decided: Outcome? | ||
| private var setupError: Error? | ||
|
|
||
| // The continuation may be resumed from any delegate callback; guard it. | ||
| private let lock = NSLock() | ||
| private var continuation: CheckedContinuation<Outcome, Error>? | ||
| private var resumed = false | ||
|
|
||
| init( | ||
| partial: URL, | ||
| existingBytes: Int64, | ||
| label: String, | ||
| onChunk: (@Sendable (Int64) -> Void)? | ||
| ) { | ||
| self.partial = partial | ||
| self.existingBytes = existingBytes | ||
| self.label = label | ||
| self.onChunk = onChunk | ||
| super.init() | ||
| } | ||
|
|
||
| /// Attach the awaiting continuation. Call exactly once, immediately before | ||
| /// `task.resume()`. | ||
| func attach(_ continuation: CheckedContinuation<Outcome, Error>) { | ||
| lock.lock() | ||
| self.continuation = continuation | ||
| lock.unlock() | ||
| } | ||
|
|
||
| private func finish(_ result: Result<Outcome, Error>) { | ||
| lock.lock() | ||
| guard !resumed, let cont = continuation else { lock.unlock(); return } | ||
| resumed = true | ||
| continuation = nil | ||
| lock.unlock() | ||
| switch result { | ||
| case .success(let outcome): cont.resume(returning: outcome) | ||
| case .failure(let error): cont.resume(throwing: error) | ||
| } | ||
| } | ||
|
|
||
| // MARK: URLSessionDataDelegate | ||
|
|
||
| func urlSession( | ||
| _ session: URLSession, | ||
| dataTask: URLSessionDataTask, | ||
| didReceive response: URLResponse, | ||
| completionHandler: @escaping (URLSession.ResponseDisposition) -> Void | ||
| ) { | ||
| guard let http = response as? HTTPURLResponse else { | ||
| setupError = ModelCatalogError.downloadFailed("\(label): unexpected response type") | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| let status = http.statusCode | ||
|
|
||
| if status == 404 || status == 403 { | ||
| decided = .notFound(status) | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| // 416 Range Not Satisfiable: we asked for bytes past EOF. A 416 carries | ||
| // `Content-Range: bytes */<total>` (RFC 7233; R2/S3 send it), so use the | ||
| // total to verify the `.part` is EXACTLY the full object before promoting | ||
| // it — regardless of whether a SHA is available. This closes the legacy | ||
| // path gap: `downloadLegacyModelFromCDN` calls `downloadFile` with | ||
| // `expectedSHA256 == nil`, so without this check a stale/oversized/ | ||
| // undersized `.part` would be promoted and served with NO verification. | ||
| if status == 416, existingBytes > 0 { | ||
| let total = http.value(forHTTPHeaderField: "Content-Range") | ||
| .flatMap(Self.parseContentRangeTotal) | ||
| if let total, UInt64(existingBytes) == total { | ||
| // The `.part` is precisely the whole object — promote it (the | ||
| // manifest path additionally SHA-checks before publishing). | ||
| decided = .completeBeyondRange | ||
| } else { | ||
| // Total missing/unknown, or the `.part` size disagrees with the | ||
| // object size: the `.part` is untrustworthy (stale/oversized/ | ||
| // undersized). Discard it and surface a RETRYABLE error so | ||
| // `downloadFile`'s loop re-runs `streamDownload` from byte 0 | ||
| // (existingBytes == 0 → no Range → full GET). This must NOT be a | ||
| // CancellationError, which `downloadFile` special-cases to never | ||
| // retry. | ||
| try? fm.removeItem(at: partial) | ||
| let totalDesc = total.map { "\($0)" } ?? "unknown" | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): 416 with untrustworthy .part (size \(existingBytes) != object total " | ||
| + "\(totalDesc)); discarded for clean re-download") | ||
| } | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| guard (200..<300).contains(status) else { | ||
| setupError = ModelCatalogError.downloadFailed("\(label): HTTP \(status)") | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
|
|
||
| // Append only when the server confirms it resumed at our exact offset. | ||
| var append = false | ||
| if existingBytes > 0, status == 206, | ||
| let contentRange = http.value(forHTTPHeaderField: "Content-Range"), | ||
| let start = Self.parseContentRangeStart(contentRange), | ||
| start == UInt64(existingBytes) { | ||
| append = true | ||
| } | ||
|
|
||
| do { | ||
| if !append { try? fm.removeItem(at: partial) } | ||
| if !fm.fileExists(atPath: partial.path) { | ||
| fm.createFile(atPath: partial.path, contents: nil) | ||
| } | ||
| let handle = try FileHandle(forWritingTo: partial) | ||
| if append { | ||
| try handle.seekToEnd() | ||
| } else { | ||
| try handle.truncate(atOffset: 0) | ||
| } | ||
| writer = handle | ||
| baseline = append ? existingBytes : 0 | ||
| } catch { | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): could not open .part for writing (\(error.localizedDescription))") | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| completionHandler(.allow) | ||
| } | ||
|
|
||
| func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { | ||
| guard setupError == nil, let writer else { return } | ||
| do { | ||
| // Synchronous write == backpressure: the next didReceive(data:) is | ||
| // not delivered until this returns, throttling the socket to disk. | ||
| try writer.write(contentsOf: data) | ||
| written += Int64(data.count) | ||
| onChunk?(baseline + written) | ||
| } catch { | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): write failed (\(error.localizedDescription))") | ||
| dataTask.cancel() | ||
| } | ||
| } | ||
|
|
||
| func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { | ||
| try? writer?.close() | ||
| writer = nil | ||
|
|
||
| // Decisions taken during response handling win over the cancellation | ||
| // error that our own `completionHandler(.cancel)` produces. | ||
| if let setupError { | ||
| finish(.failure(setupError)) | ||
| return | ||
| } | ||
| if let decided { | ||
| finish(.success(decided)) | ||
| return | ||
| } | ||
| if let error { | ||
| if (error as? URLError)?.code == .cancelled { | ||
| finish(.failure(CancellationError())) | ||
| } else { | ||
| // Transport drop mid-stream: the prefix stays in `.part`. | ||
| finish(.failure(error)) | ||
| } | ||
| return | ||
| } | ||
| onChunk?(baseline + written) | ||
| finish(.success(.success)) | ||
| } | ||
|
|
||
| /// Parse the start offset from a `Content-Range` value, e.g. | ||
| /// "bytes 12345-67890/123456". | ||
| static func parseContentRangeStart(_ value: String) -> UInt64? { | ||
| guard value.hasPrefix("bytes ") else { return nil } | ||
| let afterBytes = value.dropFirst("bytes ".count) | ||
| guard let dashIndex = afterBytes.firstIndex(of: "-") else { return nil } | ||
| return UInt64(afterBytes[afterBytes.startIndex..<dashIndex]) | ||
| } | ||
|
|
||
| /// Parse the total object length (the value after the "/") from a | ||
| /// `Content-Range` value, supporting BOTH the unsatisfied-range form a 416 | ||
| /// uses, "bytes */123", and the satisfied form "bytes 0-9/123". Returns nil | ||
| /// when the total is absent or unknown ("bytes */*"). | ||
| static func parseContentRangeTotal(_ value: String) -> UInt64? { | ||
| guard value.hasPrefix("bytes ") else { return nil } | ||
| guard let slashIndex = value.lastIndex(of: "/") else { return nil } | ||
| let total = value[value.index(after: slashIndex)...] | ||
| .trimmingCharacters(in: .whitespaces) | ||
| return UInt64(total) | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Complex delegate class reimplements URLSession functionality
💡 Suggestion: Evaluate if URLSession.downloadTask with resume data could achieve the same result with less code
📊 Score: 3×4 = 12 · Category: over-abstraction
| // MARK: - Interactive Catalog Picker | ||
|
|
||
| /// Entry shown in the interactive TUI model picker. | ||
| private struct PickerEntry { | ||
| /// | ||
| /// `downloaded` is computed from an UNFILTERED on-disk check (not the | ||
| /// available-memory-filtered scan) so a fully-downloaded model that exceeds | ||
| /// available RAM still reads "downloaded (won't fit)" rather than "not | ||
| /// downloaded". `resumable` flags a build whose foreground download was | ||
| /// interrupted (staging on disk) so the picker can show "resuming". | ||
| struct PickerEntry: Equatable { | ||
| let id: String | ||
| let catalogModel: CatalogModel | ||
| let displayName: String | ||
| let sizeGb: Double | ||
| let minRamGb: Int? | ||
| let downloaded: Bool | ||
| var resumable: Bool = false | ||
| } | ||
|
|
||
| private struct PickerCatalogRow { | ||
| struct PickerCatalogRow { | ||
| let model: CatalogModel | ||
| let displayName: String | ||
| } | ||
|
|
||
| /// Build picker entries from catalog rows and on-disk state. Pure (no IO) so | ||
| /// the downloaded / won't-fit / resuming classification is unit-testable. | ||
| /// | ||
| /// - `downloadedIDs` MUST come from an UNFILTERED on-disk scan so a | ||
| /// present-but-too-big model still reads "downloaded". | ||
| /// - `localMemoryByID` carries the on-disk estimated memory for sizing | ||
| /// downloaded rows (falls back to the catalog `size_gb` when absent). | ||
| /// - `resumableIDs` are builds with interrupted-download staging on disk. | ||
| /// - A not-yet-downloaded model whose declared `min_ram_gb` exceeds this box | ||
| /// is hidden; a downloaded one is always shown (with a won't-fit note in | ||
| /// the renderer). | ||
| static func buildPickerEntries( | ||
| rows: [PickerCatalogRow], | ||
| downloadedIDs: Set<String>, | ||
| localMemoryByID: [String: Double], | ||
| resumableIDs: Set<String>, | ||
| memoryGb: Double | ||
| ) -> [PickerEntry] { | ||
| var entries: [PickerEntry] = rows.compactMap { row in | ||
| let model = row.model | ||
| let isDownloaded = downloadedIDs.contains(model.id) | ||
| if !isDownloaded, let minRam = model.minRamGb, Double(minRam) > memoryGb { | ||
| return nil | ||
| } | ||
| let size = isDownloaded ? (localMemoryByID[model.id] ?? model.sizeGb) : model.sizeGb | ||
| return PickerEntry( | ||
| id: model.id, |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Multiple nested structs and static methods for picker logic
💡 Suggestion: Consider consolidating picker-related types into a single cohesive module
📊 Score: 2×3 = 6 · Category: over-abstraction
| import Testing | ||
| import ProviderCore | ||
|
|
||
| @testable import darkbloom | ||
|
|
||
| /// Unit tests for the pure picker-entry classifier `Start.buildPickerEntries`. | ||
| /// | ||
| /// The key invariant (the "invisible after interruption" fix): a model that is | ||
| /// physically on disk reads "downloaded" even when it exceeds available RAM — | ||
| /// `downloaded` is computed from an UNFILTERED on-disk check, never the | ||
| /// memory-filtered scan. Resumable (interrupted-download) builds are flagged so | ||
| /// the picker can show "resuming" rather than "not downloaded". | ||
| @Suite("Start.buildPickerEntries classification") | ||
| struct PickerEntryTests { | ||
|
|
||
| private func model(_ id: String, sizeGb: Double = 10, minRamGb: Int? = nil) -> CatalogModel { | ||
| CatalogModel( | ||
| id: id, | ||
| s3Name: id, | ||
| displayName: id, | ||
| sizeGb: sizeGb, | ||
| minRamGb: minRamGb, | ||
| r2Prefix: "v2/\(id)/v1" | ||
| ) | ||
| } | ||
|
|
||
| private func row(_ m: CatalogModel) -> Start.PickerCatalogRow { | ||
| Start.PickerCatalogRow(model: m, displayName: m.displayName) | ||
| } | ||
|
|
||
| private func entry(_ id: String, sizeGb: Double, downloaded: Bool = true) -> Start.PickerEntry { | ||
| Start.PickerEntry( | ||
| id: id, | ||
| catalogModel: model(id, sizeGb: sizeGb), | ||
| displayName: id, | ||
| sizeGb: sizeGb, | ||
| minRamGb: nil, | ||
| downloaded: downloaded | ||
| ) | ||
| } | ||
|
|
||
| // MARK: - resolveFallbackSelection (non-TTY picker won't-fit guard) | ||
|
|
||
| @Test("fallback 'all' selects only models that fit in RAM") | ||
| func fallbackAllExcludesWontFit() { | ||
| let small = entry("org/small", sizeGb: 8) | ||
| let huge = entry("org/huge", sizeGb: 200) | ||
| // 18 GB box → 14 GB budget: small fits, huge does not. | ||
| let r = Start.resolveFallbackSelection(input: "all", entries: [small, huge], memoryGb: 18) | ||
| #expect(r == .selected(["org/small"])) | ||
| } | ||
|
|
||
| @Test("fallback rejects an explicit won't-fit pick instead of serving it") | ||
| func fallbackRejectsWontFitIndex() { | ||
| let small = entry("org/small", sizeGb: 8) | ||
| let huge = entry("org/huge", sizeGb: 200) | ||
| guard case .rejected = Start.resolveFallbackSelection(input: "2", entries: [small, huge], memoryGb: 18) else { | ||
| Issue.record("expected a won't-fit explicit selection to be rejected") | ||
| return | ||
| } | ||
| } | ||
|
|
||
| @Test("fallback selects explicit fitting models in order") | ||
| func fallbackSelectsFitting() { | ||
| let small = entry("org/small", sizeGb: 8) | ||
| let mid = entry("org/mid", sizeGb: 12) | ||
| #expect( | ||
| Start.resolveFallbackSelection(input: "1,2", entries: [small, mid], memoryGb: 18) | ||
| == .selected(["org/small", "org/mid"])) | ||
| } | ||
|
|
||
| @Test("fallback rejects 'all' when nothing fits") | ||
| func fallbackRejectsAllTooBig() { | ||
| let huge = entry("org/huge", sizeGb: 200) | ||
| guard case .rejected = Start.resolveFallbackSelection(input: "all", entries: [huge], memoryGb: 18) else { | ||
| Issue.record("expected rejection when no model fits") | ||
| return | ||
| } | ||
| } | ||
|
|
||
| @Test("fallback empty input cancels, out-of-range and non-numeric are rejected") | ||
| func fallbackEmptyAndRange() { | ||
| let small = entry("org/small", sizeGb: 8) | ||
| #expect(Start.resolveFallbackSelection(input: "", entries: [small], memoryGb: 18) == .cancelled) | ||
| #expect(Start.resolveFallbackSelection(input: " ", entries: [small], memoryGb: 18) == .cancelled) | ||
| guard case .rejected = Start.resolveFallbackSelection(input: "5", entries: [small], memoryGb: 18) else { | ||
| Issue.record("expected out-of-range rejection") | ||
| return | ||
| } | ||
| guard case .rejected = Start.resolveFallbackSelection(input: "x", entries: [small], memoryGb: 18) else { | ||
| Issue.record("expected non-numeric rejection") | ||
| return | ||
| } | ||
| } | ||
|
|
||
| @Test("a downloaded-but-too-big model still shows downloaded (never hidden by RAM)") | ||
| func tooBigDownloadedShowsDownloaded() { | ||
| let big = model("org/too-big", sizeGb: 200, minRamGb: 256) // far over an 18 GB box | ||
| let entries = Start.buildPickerEntries( | ||
| rows: [row(big)], | ||
| downloadedIDs: ["org/too-big"], // present on disk (UNFILTERED) | ||
| localMemoryByID: ["org/too-big": 240.0], // way over budget | ||
| resumableIDs: [], | ||
| memoryGb: 18 | ||
| ) | ||
| #expect(entries.count == 1) | ||
| #expect(entries[0].id == "org/too-big") | ||
| #expect(entries[0].downloaded == true, "a model on disk must read downloaded even when it won't fit") | ||
| // Sized from the on-disk estimate, not the catalog size. | ||
| #expect(entries[0].sizeGb == 240.0) | ||
| } | ||
|
|
||
| @Test("a NOT-downloaded model whose min RAM exceeds the box is hidden") | ||
| func tooBigNotDownloadedHidden() { | ||
| let big = model("org/too-big", sizeGb: 200, minRamGb: 256) | ||
| let entries = Start.buildPickerEntries( | ||
| rows: [row(big)], | ||
| downloadedIDs: [], | ||
| localMemoryByID: [:], | ||
| resumableIDs: [], | ||
| memoryGb: 18 | ||
| ) | ||
| #expect(entries.isEmpty, "an unrunnable model that isn't on disk should not clutter the picker") | ||
| } | ||
|
|
||
| @Test("an interrupted (staged) not-downloaded model is flagged resumable") | ||
| func stagedModelIsResumable() { | ||
| let m = model("org/partial", sizeGb: 12, minRamGb: 16) | ||
| let entries = Start.buildPickerEntries( | ||
| rows: [row(m)], | ||
| downloadedIDs: [], | ||
| localMemoryByID: [:], | ||
| resumableIDs: ["org/partial"], | ||
| memoryGb: 32 | ||
| ) | ||
| #expect(entries.count == 1) | ||
| #expect(entries[0].downloaded == false) | ||
| #expect(entries[0].resumable == true) | ||
| } | ||
|
|
||
| @Test("downloaded entries sort before not-downloaded, larger first") | ||
| func sortingDownloadedFirst() { | ||
| let a = model("org/a-small-dl", sizeGb: 4, minRamGb: 8) | ||
| let b = model("org/b-big-dl", sizeGb: 40, minRamGb: 8) | ||
| let c = model("org/c-avail", sizeGb: 20, minRamGb: 8) | ||
| let entries = Start.buildPickerEntries( | ||
| rows: [row(a), row(b), row(c)], | ||
| downloadedIDs: ["org/a-small-dl", "org/b-big-dl"], | ||
| localMemoryByID: ["org/a-small-dl": 4, "org/b-big-dl": 40], | ||
| resumableIDs: [], | ||
| memoryGb: 64 | ||
| ) | ||
| #expect(entries.map(\.id) == ["org/b-big-dl", "org/a-small-dl", "org/c-avail"]) | ||
| #expect(entries.prefix(2).allSatisfy { $0.downloaded }) | ||
| #expect(entries.last?.downloaded == false) | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Extensive test setup with many helper methods for simple classification logic
💡 Suggestion: Simplify test helpers or consider if the classification logic itself is too complex
📊 Score: 2×2 = 4 · Category: over-configuration
|
Addressed the Codex P2 "Gate 416 promotion on verified downloads" ( |
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 3 finding(s) (3 blocking)
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493-503— downloadManifestFileWithResume creates unbounded onChunk closures in concurrent downloads- Suggestion: Pre-allocate progress tracking structures or use weak references to avoid potential memory growth during concurrent multi-GB downloads
- 🔴 [CRITICAL]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:659-727— Synchronous file I/O operations in hot download path- Suggestion: Use async file operations for createDirectory, fileExists checks, and Data.write operations to avoid blocking the download task group
- 🔴 [CRITICAL]
provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift:180-192— Synchronous file writes in URLSession delegate callback block network I/O- Suggestion: Buffer writes and flush asynchronously, or use a dedicated I/O queue to prevent blocking the URLSession delegate queue and throttling network throughput
Type_diligence — ✅ No issues found
Additive_complexity — 9 finding(s) (3 blocking)
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:12-20— Removed 330+ lines of progress tracking code replaced by new file- Suggestion: Verify all removed classes (DownloadProgressTracker, ProgressRenderer, FileProgress) are fully replaced by ModelDownloadProgress.swift and no callers remain
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:493-503— Added onChunk callback parameter that's optional and only used in one path- Suggestion: Consider if this callback could be handled through the existing progress system rather than adding another parameter
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:641-670— Staging directory name generation duplicated in multiple methods- Suggestion: Extract staging directory logic into a shared helper method to avoid duplication
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelCatalog.swift:813-841— Static utility methods for staging and resumable detection mixed with instance methods- Suggestion: Consider moving static utility methods to a separate utility class or namespace
- 🔵 [INFO]
provider-swift/Sources/ProviderCore/Models/ModelDownloadProgress.swift:1-263— New file duplicates progress tracking logic that was removed from ModelCatalog- Suggestion: Verify this split provides clear separation of concerns and isn't just moving code around
- 🟡 [MEDIUM]
provider-swift/Sources/ProviderCore/Models/StreamingFileDownloadDelegate.swift:1-246— Complex delegate class with multiple responsibilities (HTTP handling, file I/O, progress tracking)- Suggestion: Consider breaking this into smaller, focused classes - one for HTTP protocol handling, one for file operations
- 🔵 [INFO]
provider-swift/Sources/darkbloom/StartCommand.swift:578-628— PickerEntry and related structs could be simplified or consolidated- Suggestion: Consider if PickerEntry, PickerCatalogRow, and related logic could be simplified or use existing model types
- 🟡 [MEDIUM]
provider-swift/Sources/darkbloom/StartCommand.swift:630-720— Complex pure function buildPickerEntries with many parameters- Suggestion: Consider breaking this into smaller functions or using a configuration object to reduce parameter count
- 🔵 [INFO]
provider-swift/Sources/darkbloom/StartCommand.swift:722-815— Fallback selection logic could be simplified- Suggestion: The resolveFallbackSelection function has complex branching that could be simplified with helper methods
12 finding(s) total, 6 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
| /// from a `.part` file when present, verifying size + SHA-256 before | ||
| /// promoting to the final staged path. Reuses the resume-capable | ||
| /// `downloadFile` helper (Range requests, Content-Range validation, retries). | ||
| /// | ||
| /// `onChunk(bytesOnDisk)` reports cumulative bytes-on-disk for this file as | ||
| /// it streams, so the foreground path can render a live per-shard bar; the | ||
| /// background prefetch passes nil and accounts progress per whole file. | ||
| private func downloadManifestFileWithResume( | ||
| _ job: (file: ManifestFile, destination: URL, url: String) | ||
| _ job: (file: ManifestFile, destination: URL, url: String), | ||
| onChunk: (@Sendable (Int64) -> Void)? = nil | ||
| ) async throws { |
There was a problem hiding this comment.
🟡 [MEDIUM] ⚡ downloadManifestFileWithResume creates unbounded onChunk closures in concurrent downloads
💡 Suggestion: Pre-allocate progress tracking structures or use weak references to avoid potential memory growth during concurrent multi-GB downloads
📊 Score: 3×4 = 12 · Category: unbounded_allocations
| @@ -1026,28 +727,26 @@ public struct ModelDownloader: Sendable { | |||
| let job = pending[next] | |||
There was a problem hiding this comment.
🔴 [CRITICAL] ⚡ Synchronous file I/O operations in hot download path
💡 Suggestion: Use async file operations for createDirectory, fileExists checks, and Data.write operations to avoid blocking the download task group
📊 Score: 4×4 = 16 · Category: blocking_io
| } | ||
| completionHandler(.allow) | ||
| } | ||
|
|
||
| func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { | ||
| guard setupError == nil, let writer else { return } | ||
| do { | ||
| // Synchronous write == backpressure: the next didReceive(data:) is | ||
| // not delivered until this returns, throttling the socket to disk. | ||
| try writer.write(contentsOf: data) | ||
| written += Int64(data.count) | ||
| onChunk?(baseline + written) | ||
| } catch { |
There was a problem hiding this comment.
🔴 [CRITICAL] ⚡ Synchronous file writes in URLSession delegate callback block network I/O
💡 Suggestion: Buffer writes and flush asynchronously, or use a dedicated I/O queue to prevent blocking the URLSession delegate queue and throttling network throughput
📊 Score: 4×5 = 20 · Category: blocking_io
| /// matching what `ModelScanner` already discovers. | ||
|
|
||
| import Foundation | ||
| #if canImport(Darwin) | ||
| import Darwin | ||
| #endif | ||
|
|
||
| // MARK: - Download progress tracking & rendering | ||
|
|
||
| /// Per-file progress state used by `DownloadProgressTracker`. | ||
| private struct FileProgress: Sendable { | ||
| let label: String | ||
| let expectedBytes: Int64 | ||
| var downloadedBytes: Int64 = 0 | ||
| var startTime: Date = Date() | ||
| var completed: Bool = false | ||
| var completionTime: Date? | ||
| var destinationURL: URL? | ||
|
|
||
| /// Bytes/second using elapsed wall time. | ||
| var speed: Double { | ||
| let elapsed = (completionTime ?? Date()).timeIntervalSince(startTime) | ||
| guard elapsed > 0.1 else { return 0 } | ||
| return Double(downloadedBytes) / elapsed | ||
| } | ||
|
|
||
| /// Estimated seconds remaining. | ||
| var eta: Double? { | ||
| guard speed > 0, expectedBytes > 0 else { return nil } | ||
| let remaining = Double(expectedBytes - downloadedBytes) | ||
| guard remaining > 0 else { return nil } | ||
| return remaining / speed | ||
| } | ||
|
|
||
| var fraction: Double { | ||
| guard expectedBytes > 0 else { return 0 } | ||
| return min(1.0, Double(downloadedBytes) / Double(expectedBytes)) | ||
| } | ||
| } | ||
|
|
||
| /// Delegate-based download tracker that provides incremental progress. | ||
| /// | ||
| /// Each download task is registered with `register(taskID:label:expectedBytes:)`. | ||
| /// The delegate callbacks update shared state that `ProgressRenderer` reads. | ||
| /// Completed downloads are signalled via per-task continuations. | ||
| private final class DownloadProgressTracker: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { | ||
|
|
||
| /// Result of a single file download: the temporary location where | ||
| /// URLSession wrote the file (must be moved before the delegate returns). | ||
| struct DownloadResult { | ||
| let location: URL | ||
| let response: URLResponse | ||
| } | ||
|
|
||
| private let lock = NSLock() | ||
| private var progressMap: [Int: FileProgress] = [:] // taskIdentifier -> progress | ||
| private var continuations: [Int: CheckedContinuation<DownloadResult, Error>] = [:] | ||
| private var _allProgress: [FileProgress] = [] | ||
|
|
||
| /// Register a task so we can track its progress. | ||
| func register(taskID: Int, label: String, expectedBytes: Int64) { | ||
| lock.lock() | ||
| progressMap[taskID] = FileProgress(label: label, expectedBytes: expectedBytes) | ||
| rebuildSnapshot() | ||
| lock.unlock() | ||
| } | ||
|
|
||
| /// Store the continuation that will be resumed when the download finishes. | ||
| func setContinuation(_ cont: CheckedContinuation<DownloadResult, Error>, forTaskID taskID: Int) { | ||
| lock.lock() | ||
| continuations[taskID] = cont | ||
| lock.unlock() | ||
| } | ||
|
|
||
| /// Thread-safe snapshot of all tracked file progress, ordered by | ||
| /// registration time. | ||
| var allProgress: [FileProgress] { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return _allProgress | ||
| } | ||
|
|
||
| /// Whether all registered downloads have completed (or errored). | ||
| var isComplete: Bool { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return !progressMap.isEmpty && progressMap.values.allSatisfy(\.completed) | ||
| } | ||
|
|
||
| private func rebuildSnapshot() { | ||
| _allProgress = progressMap.keys.sorted().map { progressMap[$0]! } | ||
| } | ||
|
|
||
| // MARK: URLSessionDownloadDelegate | ||
|
|
||
| func urlSession( | ||
| _ session: URLSession, | ||
| downloadTask: URLSessionDownloadTask, | ||
| didWriteData bytesWritten: Int64, | ||
| totalBytesWritten: Int64, | ||
| totalBytesExpectedToWrite: Int64 | ||
| ) { | ||
| lock.lock() | ||
| let id = downloadTask.taskIdentifier | ||
| if var p = progressMap[id] { | ||
| p.downloadedBytes = totalBytesWritten | ||
| if totalBytesExpectedToWrite > 0 { | ||
| // Update expected if the server tells us (e.g. after resume | ||
| // partial content). Keep original manifest value if server | ||
| // returns -1. | ||
| } | ||
| progressMap[id] = p | ||
| rebuildSnapshot() | ||
| } | ||
| lock.unlock() | ||
| } | ||
|
|
||
| func urlSession( | ||
| _ session: URLSession, | ||
| downloadTask: URLSessionDownloadTask, | ||
| didFinishDownloadingTo location: URL | ||
| ) { | ||
| // URLSession deletes the temp file when this callback returns. | ||
| // Move it to a stable location so the continuation consumer can | ||
| // process it. | ||
| let stableLocation = FileManager.default.temporaryDirectory | ||
| .appendingPathComponent("darkbloom-dl-\(downloadTask.taskIdentifier)-\(UUID().uuidString)") | ||
| try? FileManager.default.moveItem(at: location, to: stableLocation) | ||
|
|
||
| lock.lock() | ||
| let id = downloadTask.taskIdentifier | ||
| if var p = progressMap[id] { | ||
| p.downloadedBytes = p.expectedBytes > 0 ? p.expectedBytes : p.downloadedBytes | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| p.destinationURL = stableLocation | ||
| progressMap[id] = p | ||
| rebuildSnapshot() | ||
| } | ||
| let cont = continuations.removeValue(forKey: id) | ||
| lock.unlock() | ||
|
|
||
| let response = downloadTask.response ?? HTTPURLResponse( | ||
| url: downloadTask.originalRequest?.url ?? URL(string: "about:blank")!, | ||
| statusCode: 200, | ||
| httpVersion: nil, | ||
| headerFields: nil | ||
| )! | ||
| cont?.resume(returning: DownloadResult(location: stableLocation, response: response)) | ||
| } | ||
|
|
||
| func urlSession( | ||
| _ session: URLSession, | ||
| task: URLSessionTask, | ||
| didCompleteWithError error: (any Error)? | ||
| ) { | ||
| guard let error else { return } | ||
| lock.lock() | ||
| let id = task.taskIdentifier | ||
| if var p = progressMap[id] { | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| progressMap[id] = p | ||
| rebuildSnapshot() | ||
| } | ||
| let cont = continuations.removeValue(forKey: id) | ||
| lock.unlock() | ||
| cont?.resume(throwing: error) | ||
| } | ||
| } | ||
|
|
||
| /// Renders a multi-line progress display to the terminal using ANSI escape | ||
| /// codes. Falls back to simple per-file messages when stdout is not a TTY. | ||
| private final class ProgressRenderer: @unchecked Sendable { | ||
|
|
||
| private let isTTY: Bool | ||
| private var linesPrinted: Int = 0 | ||
| private let lock = NSLock() | ||
| /// Set of labels already printed in non-TTY mode. | ||
| private var printedLabels: Set<String> = [] | ||
|
|
||
| init() { | ||
| self.isTTY = isatty(STDOUT_FILENO) != 0 | ||
| } | ||
|
|
||
| /// Render a frame given the current file progress snapshot. | ||
| func render(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if !isTTY { | ||
| renderPlain(files) | ||
| return | ||
| } | ||
| renderANSI(files) | ||
| } | ||
|
|
||
| /// Final render: clear the progress area and print completion summary. | ||
| func finish(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if isTTY { | ||
| // Move up and clear all lines. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| for _ in 0..<linesPrinted { | ||
| print("\u{1B}[2K") | ||
| } | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| linesPrinted = 0 | ||
| } | ||
| } | ||
|
|
||
| // Print final summary lines. | ||
| for f in files { | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(f.downloadedBytes) / elapsed : 0 | ||
| let speedStr = Self.formatSpeed(avgSpeed) | ||
| let timeStr = Self.formatDuration(elapsed) | ||
| print(" \u{2713} \(f.label) \(totalStr) \(speedStr) \(timeStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - ANSI rendering | ||
|
|
||
| private func renderANSI(_ files: [FileProgress]) { | ||
| // Move cursor up to overwrite previous render. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| } | ||
|
|
||
| let termWidth = Self.terminalWidth() | ||
| var lines = 0 | ||
| for f in files { | ||
| print("\u{1B}[2K", terminator: "") // Clear the line | ||
| let line = Self.formatLine(f, termWidth: termWidth) | ||
| print(line) | ||
| lines += 1 | ||
| } | ||
| linesPrinted = lines | ||
| fflush(stdout) | ||
| } | ||
|
|
||
| private func renderPlain(_ files: [FileProgress]) { | ||
| for f in files where f.completed && !printedLabels.contains(f.label) { | ||
| printedLabels.insert(f.label) | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| print(" \u{2713} \(f.label) \(totalStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Line formatting | ||
|
|
||
| private static func formatLine(_ f: FileProgress, termWidth: Int) -> String { | ||
| if f.completed { | ||
| let totalStr = formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(f.downloadedBytes) / elapsed : 0 | ||
| return " \u{2713} \(f.label) \(totalStr) \(formatSpeed(avgSpeed)) done" | ||
| } | ||
|
|
||
| let pct = Int(f.fraction * 100) | ||
| let dlStr = formatBytes(f.downloadedBytes) | ||
| let totStr = formatBytes(f.expectedBytes) | ||
| let speedStr = formatSpeed(f.speed) | ||
| let etaStr: String | ||
| if let eta = f.eta { | ||
| etaStr = "ETA \(formatDuration(eta))" | ||
| } else { | ||
| etaStr = "---" | ||
| } | ||
|
|
||
| // Assemble the suffix: " 62% 2.1/4.8 GB 113 MB/s ETA 24s" | ||
| let suffix = " \(String(format: "%3d", pct))% \(dlStr)/\(totStr) \(speedStr) \(etaStr)" | ||
|
|
||
| // Calculate bar width: total - label - prefix - suffix - brackets - spaces | ||
| let labelMaxWidth = min(f.label.count, 45) | ||
| let label = f.label.count > labelMaxWidth | ||
| ? String(f.label.suffix(labelMaxWidth - 1)).padding(toLength: labelMaxWidth, withPad: " ", startingAt: 0) | ||
| : f.label | ||
| let prefix = " \(label) [" | ||
| let postfix = "]\(suffix)" | ||
| let barWidth = max(10, termWidth - prefix.count - postfix.count) | ||
|
|
||
| let filled = Int(f.fraction * Double(barWidth)) | ||
| let empty = barWidth - filled | ||
| let bar = String(repeating: "\u{2588}", count: filled) + String(repeating: "\u{2591}", count: empty) | ||
|
|
||
| return "\(prefix)\(bar)\(postfix)" | ||
| } | ||
|
|
||
| // MARK: - Formatting helpers | ||
|
|
||
| static func formatBytes(_ bytes: Int64) -> String { | ||
| let b = Double(bytes) | ||
| if b < 1024 { return "\(bytes) B" } | ||
| if b < 1_048_576 { return String(format: "%.1f KB", b / 1024) } | ||
| if b < 1_073_741_824 { return String(format: "%.1f MB", b / 1_048_576) } | ||
| return String(format: "%.1f GB", b / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatSpeed(_ bytesPerSec: Double) -> String { | ||
| if bytesPerSec < 1024 { return String(format: "%.0f B/s", bytesPerSec) } | ||
| if bytesPerSec < 1_048_576 { return String(format: "%.0f KB/s", bytesPerSec / 1024) } | ||
| if bytesPerSec < 1_073_741_824 { return String(format: "%.0f MB/s", bytesPerSec / 1_048_576) } | ||
| return String(format: "%.1f GB/s", bytesPerSec / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatDuration(_ seconds: Double) -> String { | ||
| let s = Int(seconds) | ||
| if s < 60 { return "\(s)s" } | ||
| if s < 3600 { return "\(s / 60)m \(s % 60)s" } | ||
| return "\(s / 3600)h \(s / 60 % 60)m" | ||
| } | ||
|
|
||
| static func terminalWidth() -> Int { | ||
| #if canImport(Darwin) | ||
| var w = winsize() | ||
| if ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0, w.ws_col > 0 { | ||
| return Int(w.ws_col) | ||
| } | ||
| #endif | ||
| return 80 | ||
| } | ||
| } | ||
| // | ||
| // Progress state (`FileProgress`, `ManifestDownloadProgress`) and terminal | ||
| // rendering (`ProgressRenderer`) live in `ModelDownloadProgress.swift` so this | ||
| // file stays focused on catalog + download orchestration. |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Removed 330+ lines of progress tracking code replaced by new file
💡 Suggestion: Verify all removed classes (DownloadProgressTracker, ProgressRenderer, FileProgress) are fully replaced by ModelDownloadProgress.swift and no callers remain
📊 Score: 2×3 = 6 · Category: dead code
| /// from a `.part` file when present, verifying size + SHA-256 before | ||
| /// promoting to the final staged path. Reuses the resume-capable | ||
| /// `downloadFile` helper (Range requests, Content-Range validation, retries). | ||
| /// | ||
| /// `onChunk(bytesOnDisk)` reports cumulative bytes-on-disk for this file as | ||
| /// it streams, so the foreground path can render a live per-shard bar; the | ||
| /// background prefetch passes nil and accounts progress per whole file. | ||
| private func downloadManifestFileWithResume( | ||
| _ job: (file: ManifestFile, destination: URL, url: String) | ||
| _ job: (file: ManifestFile, destination: URL, url: String), | ||
| onChunk: (@Sendable (Int64) -> Void)? = nil | ||
| ) async throws { |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Added onChunk callback parameter that's optional and only used in one path
💡 Suggestion: Consider if this callback could be handled through the existing progress system rather than adding another parameter
📊 Score: 3×4 = 12 · Category: over-abstraction
| @@ -972,52 +659,66 @@ public struct ModelDownloader: Sendable { | |||
| ) | |||
| } | |||
|
|
|||
| // Resume: skip files already staged + valid, and size the capacity | |||
| // pre-check to only the bytes that remain (less anything already saved in a | |||
| // `.part`) so a near-complete resume isn't rejected for lacking room equal | |||
| // to the whole model. Only the not-yet-valid files are enqueued below. | |||
| // Resume: skip files already staged + valid; only the not-yet-valid files | |||
| // are enqueued below. | |||
| let alreadyValid = jobs.map { Self.fileMatches($0.destination, size: $0.file.sizeBytes, sha256: $0.file.sha256) } | |||
| // The foreground per-file downloader does a full GET (it does NOT byte- | |||
| // resume — it deletes any stale `.part`), so only fully-valid files are | |||
| // creditable here; every not-yet-valid file needs its full size. (Only the | |||
| // background `prefetch` path byte-resumes and may credit `.part` bytes.) | |||
| // The foreground per-file downloader now byte-resumes (streams to a stable | |||
| // `.part` and appends via HTTP `Range`), so credit any bytes already saved | |||
| // in each `.part`: a near-complete resume of a big shard must not be charged | |||
| // disk room equal to the whole shard. | |||
| let partBytes = jobs.map { fileSize($0.destination.appendingPathExtension("part")) } | |||
| try Self.ensureAvailableCapacity( | |||
There was a problem hiding this comment.
🔵 [INFO] 🧩 Staging directory name generation duplicated in multiple methods
💡 Suggestion: Extract staging directory logic into a shared helper method to avoid duplication
📊 Score: 2×3 = 6 · Category: duplicate logic
| .appendingPathComponent("local", isDirectory: true) | ||
| } | ||
|
|
||
| /// Stable foreground-download staging dir name, keyed by the manifest's | ||
| /// `r2Prefix` so an interrupted download resumes into the SAME dir instead of | ||
| /// a throwaway UUID. `r2Prefix` is path-like (e.g. "v2/org__name/version"); | ||
| /// flatten it to a single safe component. | ||
| static func localStagingDirName(r2Prefix: String) -> String { | ||
| ".local-staging-" + r2Prefix | ||
| .replacingOccurrences(of: "/", with: "__") | ||
| .replacingOccurrences(of: "\\", with: "__") | ||
| } | ||
|
|
||
| /// Whether an interrupted foreground download left resumable content staged on | ||
| /// disk for this model build (keyed by `r2Prefix`): a completed shard or a | ||
| /// `.part` prefix in the stable `.local-staging-…` dir. Lets the picker show | ||
| /// "resuming" instead of "not downloaded" for a partially-downloaded model so | ||
| /// re-selecting it FINISHES the download rather than appearing to start over. | ||
| public static func hasResumableStaging(modelID: String, r2Prefix: String) -> Bool { | ||
| let stagingDir = cacheModelDirectory(for: modelID) | ||
| .appendingPathComponent("snapshots", isDirectory: true) | ||
| .appendingPathComponent(localStagingDirName(r2Prefix: r2Prefix), isDirectory: true) | ||
| guard let entries = try? FileManager.default.contentsOfDirectory(atPath: stagingDir.path) else { | ||
| return false | ||
| } | ||
| // Any non-hidden staged entry (a finished file, a `.part`, or a nested | ||
| // subdir like `adapters/`) is resumable content worth finishing. | ||
| return entries.contains { !$0.hasPrefix(".") } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 Static utility methods for staging and resumable detection mixed with instance methods
💡 Suggestion: Consider moving static utility methods to a separate utility class or namespace
📊 Score: 2×2 = 4 · Category: misplaced responsibility
| /// Download progress tracking + terminal rendering for the foreground model | ||
| /// download path (`darkbloom models download` / the interactive picker). | ||
| /// | ||
| /// Split out of `ModelCatalog.swift` so that file stays focused on catalog + | ||
| /// download orchestration. The tracker here is callback-driven (fed by the | ||
| /// streaming, byte-resumable downloader in `ModelCatalog.swift`) rather than a | ||
| /// `URLSessionDownloadDelegate`: downloads now stream straight to a `.part` | ||
| /// file for true byte-level resume, so there is no `URLSessionDownloadTask` to | ||
| /// observe — progress arrives as cumulative-bytes-on-disk callbacks instead. | ||
|
|
||
| import Foundation | ||
| #if canImport(Darwin) | ||
| import Darwin | ||
| #endif | ||
|
|
||
| // MARK: - Per-file progress | ||
|
|
||
| /// Per-file progress state rendered by `ProgressRenderer`. | ||
| struct FileProgress: Sendable { | ||
| let label: String | ||
| let expectedBytes: Int64 | ||
| var downloadedBytes: Int64 = 0 | ||
| /// Bytes already on disk when tracking started (a resumed `.part` prefix). | ||
| /// Excluded from the speed/ETA math so a resume doesn't report an inflated | ||
| /// instantaneous rate for bytes it never actually transferred this run. | ||
| var baselineBytes: Int64 = 0 | ||
| var startTime: Date = Date() | ||
| var completed: Bool = false | ||
| var completionTime: Date? | ||
|
|
||
| /// Bytes/second over this run's transfer (excludes the resumed prefix). | ||
| var speed: Double { | ||
| let elapsed = (completionTime ?? Date()).timeIntervalSince(startTime) | ||
| guard elapsed > 0.1 else { return 0 } | ||
| return Double(max(0, downloadedBytes - baselineBytes)) / elapsed | ||
| } | ||
|
|
||
| /// Estimated seconds remaining. | ||
| var eta: Double? { | ||
| guard speed > 0, expectedBytes > 0 else { return nil } | ||
| let remaining = Double(expectedBytes - downloadedBytes) | ||
| guard remaining > 0 else { return nil } | ||
| return remaining / speed | ||
| } | ||
|
|
||
| var fraction: Double { | ||
| guard expectedBytes > 0 else { return 0 } | ||
| return min(1.0, Double(downloadedBytes) / Double(expectedBytes)) | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Tracker | ||
|
|
||
| /// Thread-safe per-file download progress keyed by file label (manifest path). | ||
| /// | ||
| /// Fed by byte-progress callbacks from the streaming downloader and read on a | ||
| /// timer by `ProgressRenderer`. Registration order is preserved so the rendered | ||
| /// rows stay stable across frames. | ||
| final class ManifestDownloadProgress: @unchecked Sendable { | ||
|
|
||
| private let lock = NSLock() | ||
| private var progress: [String: FileProgress] = [:] | ||
| private var order: [String] = [] | ||
|
|
||
| /// Register a file to track. `initialBytes` seeds a resumed `.part` prefix | ||
| /// so the bar starts where the previous run left off (and is excluded from | ||
| /// the speed math via `baselineBytes`). | ||
| func register(label: String, expectedBytes: Int64, initialBytes: Int64 = 0) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| if progress[label] == nil { order.append(label) } | ||
| var p = FileProgress(label: label, expectedBytes: expectedBytes) | ||
| p.downloadedBytes = max(0, initialBytes) | ||
| p.baselineBytes = max(0, initialBytes) | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Update cumulative bytes-on-disk for a file. | ||
| func update(label: String, downloadedBytes: Int64) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = downloadedBytes | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Mark a file complete (full size, stop the clock). | ||
| func complete(label: String) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| guard var p = progress[label] else { return } | ||
| p.downloadedBytes = p.expectedBytes > 0 ? p.expectedBytes : p.downloadedBytes | ||
| p.completed = true | ||
| p.completionTime = Date() | ||
| progress[label] = p | ||
| } | ||
|
|
||
| /// Thread-safe snapshot of all tracked file progress, in registration order. | ||
| var allProgress: [FileProgress] { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return order.compactMap { progress[$0] } | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Renderer | ||
|
|
||
| /// Renders a multi-line progress display to the terminal using ANSI escape | ||
| /// codes. Falls back to simple per-file messages when stdout is not a TTY. | ||
| final class ProgressRenderer: @unchecked Sendable { | ||
|
|
||
| private let isTTY: Bool | ||
| private var linesPrinted: Int = 0 | ||
| private let lock = NSLock() | ||
| /// Set of labels already printed in non-TTY mode. | ||
| private var printedLabels: Set<String> = [] | ||
|
|
||
| init() { | ||
| self.isTTY = isatty(STDOUT_FILENO) != 0 | ||
| } | ||
|
|
||
| /// Render a frame given the current file progress snapshot. | ||
| func render(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if !isTTY { | ||
| renderPlain(files) | ||
| return | ||
| } | ||
| renderANSI(files) | ||
| } | ||
|
|
||
| /// Final render: clear the progress area and print completion summary. | ||
| func finish(_ files: [FileProgress]) { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
|
|
||
| if isTTY { | ||
| // Move up and clear all lines. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| for _ in 0..<linesPrinted { | ||
| print("\u{1B}[2K") | ||
| } | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| linesPrinted = 0 | ||
| } | ||
| } | ||
|
|
||
| // Print final summary lines. | ||
| for f in files { | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(max(0, f.downloadedBytes - f.baselineBytes)) / elapsed : 0 | ||
| let speedStr = Self.formatSpeed(avgSpeed) | ||
| let timeStr = Self.formatDuration(elapsed) | ||
| print(" \u{2713} \(f.label) \(totalStr) \(speedStr) \(timeStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - ANSI rendering | ||
|
|
||
| private func renderANSI(_ files: [FileProgress]) { | ||
| // Move cursor up to overwrite previous render. | ||
| if linesPrinted > 0 { | ||
| print("\u{1B}[\(linesPrinted)A", terminator: "") | ||
| } | ||
|
|
||
| let termWidth = Self.terminalWidth() | ||
| var lines = 0 | ||
| for f in files { | ||
| print("\u{1B}[2K", terminator: "") // Clear the line | ||
| let line = Self.formatLine(f, termWidth: termWidth) | ||
| print(line) | ||
| lines += 1 | ||
| } | ||
| linesPrinted = lines | ||
| fflush(stdout) | ||
| } | ||
|
|
||
| private func renderPlain(_ files: [FileProgress]) { | ||
| for f in files where f.completed && !printedLabels.contains(f.label) { | ||
| printedLabels.insert(f.label) | ||
| let totalStr = Self.formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| print(" \u{2713} \(f.label) \(totalStr)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Line formatting | ||
|
|
||
| private static func formatLine(_ f: FileProgress, termWidth: Int) -> String { | ||
| if f.completed { | ||
| let totalStr = formatBytes(f.expectedBytes > 0 ? f.expectedBytes : f.downloadedBytes) | ||
| let elapsed = (f.completionTime ?? Date()).timeIntervalSince(f.startTime) | ||
| let avgSpeed = elapsed > 0.1 ? Double(max(0, f.downloadedBytes - f.baselineBytes)) / elapsed : 0 | ||
| return " \u{2713} \(f.label) \(totalStr) \(formatSpeed(avgSpeed)) done" | ||
| } | ||
|
|
||
| let pct = Int(f.fraction * 100) | ||
| let dlStr = formatBytes(f.downloadedBytes) | ||
| let totStr = formatBytes(f.expectedBytes) | ||
| let speedStr = formatSpeed(f.speed) | ||
| let etaStr: String | ||
| if let eta = f.eta { | ||
| etaStr = "ETA \(formatDuration(eta))" | ||
| } else { | ||
| etaStr = "---" | ||
| } | ||
|
|
||
| // Assemble the suffix: " 62% 2.1/4.8 GB 113 MB/s ETA 24s" | ||
| let suffix = " \(String(format: "%3d", pct))% \(dlStr)/\(totStr) \(speedStr) \(etaStr)" | ||
|
|
||
| // Calculate bar width: total - label - prefix - suffix - brackets - spaces | ||
| let labelMaxWidth = min(f.label.count, 45) | ||
| let label = f.label.count > labelMaxWidth | ||
| ? String(f.label.suffix(labelMaxWidth - 1)).padding(toLength: labelMaxWidth, withPad: " ", startingAt: 0) | ||
| : f.label | ||
| let prefix = " \(label) [" | ||
| let postfix = "]\(suffix)" | ||
| let barWidth = max(10, termWidth - prefix.count - postfix.count) | ||
|
|
||
| let filled = Int(f.fraction * Double(barWidth)) | ||
| let empty = barWidth - filled | ||
| let bar = String(repeating: "\u{2588}", count: filled) + String(repeating: "\u{2591}", count: empty) | ||
|
|
||
| return "\(prefix)\(bar)\(postfix)" | ||
| } | ||
|
|
||
| // MARK: - Formatting helpers | ||
|
|
||
| static func formatBytes(_ bytes: Int64) -> String { | ||
| let b = Double(bytes) | ||
| if b < 1024 { return "\(bytes) B" } | ||
| if b < 1_048_576 { return String(format: "%.1f KB", b / 1024) } | ||
| if b < 1_073_741_824 { return String(format: "%.1f MB", b / 1_048_576) } | ||
| return String(format: "%.1f GB", b / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatSpeed(_ bytesPerSec: Double) -> String { | ||
| if bytesPerSec < 1024 { return String(format: "%.0f B/s", bytesPerSec) } | ||
| if bytesPerSec < 1_048_576 { return String(format: "%.0f KB/s", bytesPerSec / 1024) } | ||
| if bytesPerSec < 1_073_741_824 { return String(format: "%.0f MB/s", bytesPerSec / 1_048_576) } | ||
| return String(format: "%.1f GB/s", bytesPerSec / 1_073_741_824) | ||
| } | ||
|
|
||
| static func formatDuration(_ seconds: Double) -> String { | ||
| let s = Int(seconds) | ||
| if s < 60 { return "\(s)s" } | ||
| if s < 3600 { return "\(s / 60)m \(s % 60)s" } | ||
| return "\(s / 3600)h \(s / 60 % 60)m" | ||
| } | ||
|
|
||
| static func terminalWidth() -> Int { | ||
| #if canImport(Darwin) | ||
| var w = winsize() | ||
| if ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0, w.ws_col > 0 { | ||
| return Int(w.ws_col) | ||
| } | ||
| #endif | ||
| return 80 | ||
| } | ||
| } |
There was a problem hiding this comment.
🔵 [INFO] 🧩 New file duplicates progress tracking logic that was removed from ModelCatalog
💡 Suggestion: Verify this split provides clear separation of concerns and isn't just moving code around
📊 Score: 1×2 = 2 · Category: over-abstraction
| import Foundation | ||
|
|
||
| /// Streams an HTTP GET body straight to a `.part` file in OS-sized chunks using | ||
| /// the `URLSession` data-delegate callbacks. | ||
| /// | ||
| /// This replaces `URLSession.AsyncBytes`, whose `for await byte in …` yields a | ||
| /// single `UInt8` per async-iterator step. That is pathologically slow for the | ||
| /// multi-GB model shards we download (one async resumption per byte → billions | ||
| /// of them per file). `URLSession.bytes` only exposes a per-byte sequence, so to | ||
| /// get OS-sized `Data` chunks we drop to the delegate API. | ||
| /// | ||
| /// Backpressure — the one virtue of `AsyncBytes` we must NOT lose — is preserved | ||
| /// without any in-memory queue: `URLSession` serializes delegate callbacks and | ||
| /// does not invoke `urlSession(_:dataTask:didReceive:)` again until the previous | ||
| /// call returns. Writing each chunk synchronously to disk here therefore | ||
| /// throttles the socket to disk speed; nothing is buffered beyond the single | ||
| /// chunk the system hands us (so no drops and no unbounded growth on a slow | ||
| /// disk / fast network). | ||
| /// | ||
| /// The resume contract matches the previous `streamDownload` implementation: | ||
| /// - If `existingBytes > 0` the caller sent `Range: bytes=N-`. | ||
| /// - 206 whose `Content-Range` start == N → append to the existing prefix. | ||
| /// - 200 (range ignored) or a mismatched/unverifiable 206 → truncate and rewrite | ||
| /// THIS file from byte 0. | ||
| /// - 404/403 → `.notFound` (caller removes the `.part`; throws iff required). | ||
| /// - 416 with a prefix → size-verify against the 416's `Content-Range: bytes | ||
| /// */<total>`. If the `.part` size equals `<total>` it is the whole object → | ||
| /// `.completeBeyondRange` (caller verifies + promotes it). Otherwise the | ||
| /// `.part` is stale/oversized/undersized → delete it and surface a retryable | ||
| /// error so the caller re-downloads it cleanly from byte 0. | ||
| /// - A mid-stream transport drop leaves every received byte durably in `.part` | ||
| /// and surfaces as a thrown error so the caller retries with a fresh `Range`. | ||
| /// - Cooperative cancellation (`task.cancel()`) surfaces as `CancellationError` | ||
| /// and likewise leaves a resumable `.part`. | ||
| final class StreamingFileDownloadDelegate: NSObject, URLSessionDataDelegate, @unchecked Sendable { | ||
| enum Outcome { | ||
| /// Body streamed to `.part` successfully (appended or rewritten). | ||
| case success | ||
| /// 416: the `.part` is already at/beyond the object length. | ||
| case completeBeyondRange | ||
| /// 404/403 for an optional file. | ||
| case notFound(Int) | ||
| } | ||
|
|
||
| private let partial: URL | ||
| private let existingBytes: Int64 | ||
| private let label: String | ||
| private let onChunk: (@Sendable (Int64) -> Void)? | ||
| private let fm = FileManager.default | ||
|
|
||
| // Mutated only from the URLSession delegate queue (callbacks are serialized). | ||
| private var writer: FileHandle? | ||
| private var baseline: Int64 = 0 | ||
| private var written: Int64 = 0 | ||
| private var decided: Outcome? | ||
| private var setupError: Error? | ||
|
|
||
| // The continuation may be resumed from any delegate callback; guard it. | ||
| private let lock = NSLock() | ||
| private var continuation: CheckedContinuation<Outcome, Error>? | ||
| private var resumed = false | ||
|
|
||
| init( | ||
| partial: URL, | ||
| existingBytes: Int64, | ||
| label: String, | ||
| onChunk: (@Sendable (Int64) -> Void)? | ||
| ) { | ||
| self.partial = partial | ||
| self.existingBytes = existingBytes | ||
| self.label = label | ||
| self.onChunk = onChunk | ||
| super.init() | ||
| } | ||
|
|
||
| /// Attach the awaiting continuation. Call exactly once, immediately before | ||
| /// `task.resume()`. | ||
| func attach(_ continuation: CheckedContinuation<Outcome, Error>) { | ||
| lock.lock() | ||
| self.continuation = continuation | ||
| lock.unlock() | ||
| } | ||
|
|
||
| private func finish(_ result: Result<Outcome, Error>) { | ||
| lock.lock() | ||
| guard !resumed, let cont = continuation else { lock.unlock(); return } | ||
| resumed = true | ||
| continuation = nil | ||
| lock.unlock() | ||
| switch result { | ||
| case .success(let outcome): cont.resume(returning: outcome) | ||
| case .failure(let error): cont.resume(throwing: error) | ||
| } | ||
| } | ||
|
|
||
| // MARK: URLSessionDataDelegate | ||
|
|
||
| func urlSession( | ||
| _ session: URLSession, | ||
| dataTask: URLSessionDataTask, | ||
| didReceive response: URLResponse, | ||
| completionHandler: @escaping (URLSession.ResponseDisposition) -> Void | ||
| ) { | ||
| guard let http = response as? HTTPURLResponse else { | ||
| setupError = ModelCatalogError.downloadFailed("\(label): unexpected response type") | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| let status = http.statusCode | ||
|
|
||
| if status == 404 || status == 403 { | ||
| decided = .notFound(status) | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| // 416 Range Not Satisfiable: we asked for bytes past EOF. A 416 carries | ||
| // `Content-Range: bytes */<total>` (RFC 7233; R2/S3 send it), so use the | ||
| // total to verify the `.part` is EXACTLY the full object before promoting | ||
| // it — regardless of whether a SHA is available. This closes the legacy | ||
| // path gap: `downloadLegacyModelFromCDN` calls `downloadFile` with | ||
| // `expectedSHA256 == nil`, so without this check a stale/oversized/ | ||
| // undersized `.part` would be promoted and served with NO verification. | ||
| if status == 416, existingBytes > 0 { | ||
| let total = http.value(forHTTPHeaderField: "Content-Range") | ||
| .flatMap(Self.parseContentRangeTotal) | ||
| if let total, UInt64(existingBytes) == total { | ||
| // The `.part` is precisely the whole object — promote it (the | ||
| // manifest path additionally SHA-checks before publishing). | ||
| decided = .completeBeyondRange | ||
| } else { | ||
| // Total missing/unknown, or the `.part` size disagrees with the | ||
| // object size: the `.part` is untrustworthy (stale/oversized/ | ||
| // undersized). Discard it and surface a RETRYABLE error so | ||
| // `downloadFile`'s loop re-runs `streamDownload` from byte 0 | ||
| // (existingBytes == 0 → no Range → full GET). This must NOT be a | ||
| // CancellationError, which `downloadFile` special-cases to never | ||
| // retry. | ||
| try? fm.removeItem(at: partial) | ||
| let totalDesc = total.map { "\($0)" } ?? "unknown" | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): 416 with untrustworthy .part (size \(existingBytes) != object total " | ||
| + "\(totalDesc)); discarded for clean re-download") | ||
| } | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| guard (200..<300).contains(status) else { | ||
| setupError = ModelCatalogError.downloadFailed("\(label): HTTP \(status)") | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
|
|
||
| // Append only when the server confirms it resumed at our exact offset. | ||
| var append = false | ||
| if existingBytes > 0, status == 206, | ||
| let contentRange = http.value(forHTTPHeaderField: "Content-Range"), | ||
| let start = Self.parseContentRangeStart(contentRange), | ||
| start == UInt64(existingBytes) { | ||
| append = true | ||
| } | ||
|
|
||
| do { | ||
| if !append { try? fm.removeItem(at: partial) } | ||
| if !fm.fileExists(atPath: partial.path) { | ||
| fm.createFile(atPath: partial.path, contents: nil) | ||
| } | ||
| let handle = try FileHandle(forWritingTo: partial) | ||
| if append { | ||
| try handle.seekToEnd() | ||
| } else { | ||
| try handle.truncate(atOffset: 0) | ||
| } | ||
| writer = handle | ||
| baseline = append ? existingBytes : 0 | ||
| } catch { | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): could not open .part for writing (\(error.localizedDescription))") | ||
| completionHandler(.cancel) | ||
| return | ||
| } | ||
| completionHandler(.allow) | ||
| } | ||
|
|
||
| func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { | ||
| guard setupError == nil, let writer else { return } | ||
| do { | ||
| // Synchronous write == backpressure: the next didReceive(data:) is | ||
| // not delivered until this returns, throttling the socket to disk. | ||
| try writer.write(contentsOf: data) | ||
| written += Int64(data.count) | ||
| onChunk?(baseline + written) | ||
| } catch { | ||
| setupError = ModelCatalogError.downloadFailed( | ||
| "\(label): write failed (\(error.localizedDescription))") | ||
| dataTask.cancel() | ||
| } | ||
| } | ||
|
|
||
| func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { | ||
| try? writer?.close() | ||
| writer = nil | ||
|
|
||
| // Decisions taken during response handling win over the cancellation | ||
| // error that our own `completionHandler(.cancel)` produces. | ||
| if let setupError { | ||
| finish(.failure(setupError)) | ||
| return | ||
| } | ||
| if let decided { | ||
| finish(.success(decided)) | ||
| return | ||
| } | ||
| if let error { | ||
| if (error as? URLError)?.code == .cancelled { | ||
| finish(.failure(CancellationError())) | ||
| } else { | ||
| // Transport drop mid-stream: the prefix stays in `.part`. | ||
| finish(.failure(error)) | ||
| } | ||
| return | ||
| } | ||
| onChunk?(baseline + written) | ||
| finish(.success(.success)) | ||
| } | ||
|
|
||
| /// Parse the start offset from a `Content-Range` value, e.g. | ||
| /// "bytes 12345-67890/123456". | ||
| static func parseContentRangeStart(_ value: String) -> UInt64? { | ||
| guard value.hasPrefix("bytes ") else { return nil } | ||
| let afterBytes = value.dropFirst("bytes ".count) | ||
| guard let dashIndex = afterBytes.firstIndex(of: "-") else { return nil } | ||
| return UInt64(afterBytes[afterBytes.startIndex..<dashIndex]) | ||
| } | ||
|
|
||
| /// Parse the total object length (the value after the "/") from a | ||
| /// `Content-Range` value, supporting BOTH the unsatisfied-range form a 416 | ||
| /// uses, "bytes */123", and the satisfied form "bytes 0-9/123". Returns nil | ||
| /// when the total is absent or unknown ("bytes */*"). | ||
| static func parseContentRangeTotal(_ value: String) -> UInt64? { | ||
| guard value.hasPrefix("bytes ") else { return nil } | ||
| guard let slashIndex = value.lastIndex(of: "/") else { return nil } | ||
| let total = value[value.index(after: slashIndex)...] | ||
| .trimmingCharacters(in: .whitespaces) | ||
| return UInt64(total) | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 [MEDIUM] 🧩 Complex delegate class with multiple responsibilities (HTTP handling, file I/O, progress tracking)
💡 Suggestion: Consider breaking this into smaller, focused classes - one for HTTP protocol handling, one for file operations
📊 Score: 3×3 = 9 · Category: over-abstraction
| // MARK: - Interactive Catalog Picker | ||
|
|
||
| /// Entry shown in the interactive TUI model picker. | ||
| private struct PickerEntry { | ||
| /// | ||
| /// `downloaded` is computed from an UNFILTERED on-disk check (not the | ||
| /// available-memory-filtered scan) so a fully-downloaded model that exceeds | ||
| /// available RAM still reads "downloaded (won't fit)" rather than "not | ||
| /// downloaded". `resumable` flags a build whose foreground download was | ||
| /// interrupted (staging on disk) so the picker can show "resuming". | ||
| struct PickerEntry: Equatable { | ||
| let id: String | ||
| let catalogModel: CatalogModel | ||
| let displayName: String | ||
| let sizeGb: Double | ||
| let minRamGb: Int? | ||
| let downloaded: Bool | ||
| var resumable: Bool = false | ||
| } | ||
|
|
||
| private struct PickerCatalogRow { | ||
| struct PickerCatalogRow { | ||
| let model: CatalogModel | ||
| let displayName: String | ||
| } | ||
|
|
||
| /// Build picker entries from catalog rows and on-disk state. Pure (no IO) so | ||
| /// the downloaded / won't-fit / resuming classification is unit-testable. | ||
| /// | ||
| /// - `downloadedIDs` MUST come from an UNFILTERED on-disk scan so a | ||
| /// present-but-too-big model still reads "downloaded". | ||
| /// - `localMemoryByID` carries the on-disk estimated memory for sizing | ||
| /// downloaded rows (falls back to the catalog `size_gb` when absent). | ||
| /// - `resumableIDs` are builds with interrupted-download staging on disk. | ||
| /// - A not-yet-downloaded model whose declared `min_ram_gb` exceeds this box | ||
| /// is hidden; a downloaded one is always shown (with a won't-fit note in | ||
| /// the renderer). | ||
| static func buildPickerEntries( | ||
| rows: [PickerCatalogRow], | ||
| downloadedIDs: Set<String>, | ||
| localMemoryByID: [String: Double], | ||
| resumableIDs: Set<String>, | ||
| memoryGb: Double | ||
| ) -> [PickerEntry] { | ||
| var entries: [PickerEntry] = rows.compactMap { row in | ||
| let model = row.model | ||
| let isDownloaded = downloadedIDs.contains(model.id) | ||
| if !isDownloaded, let minRam = model.minRamGb, Double(minRam) > memoryGb { | ||
| return nil | ||
| } | ||
| let size = isDownloaded ? (localMemoryByID[model.id] ?? model.sizeGb) : model.sizeGb | ||
| return PickerEntry( | ||
| id: model.id, |
There was a problem hiding this comment.
🔵 [INFO] 🧩 PickerEntry and related structs could be simplified or consolidated
💡 Suggestion: Consider if PickerEntry, PickerCatalogRow, and related logic could be simplified or use existing model types
📊 Score: 2×3 = 6 · Category: duplicate logic
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 47170aaf9d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| case .completeBeyondRange: | ||
| // The `.part` already holds the whole object; the caller's SHA/size | ||
| // check promotes it (or deletes + restarts a corrupt/oversized one). | ||
| onChunk?(existingBytes) | ||
| return true |
There was a problem hiding this comment.
Require verification before accepting 416 resumes
Fresh evidence beyond the previous 416 thread is that this version added only an object-length check in the delegate; when downloadLegacyModelFromCDN calls downloadFile with expectedSHA256 == nil, this .completeBeyondRange success path still moves any exact-length stale or corrupt .part to the final model after Range: bytes=<size>- gets a 416. In that legacy-CDN scenario, please fall back to a full GET unless a hash verifier is present, otherwise a previous failed download of a different same-size object can be served as the model.
Useful? React with 👍 / 👎.
Memory & reliability hardening: - 90% unified-memory cap + KV purge on unload + serve-while-load reservation (#363) - bounded checkpoint-capture pipeline, stops the Metal 499000 resource leak (#374) - resumable 4-bit model downloads + restart-safe detection (#372) - default-on [rsrc] resource telemetry in reports (#373 / mlx-swift-lm#42) - don't log raw request-parse errors — prompt-fragment privacy (#376) Coordinator LatestProviderVersion bump is intentionally deferred until the signed 0.6.12 bundle is published (prod uses the in-memory store, so the hardcoded fallback is authoritative after a redeploy).
libs/mlx-swift-lm moves from fd48d47f to 093563be, the merge commit of mlx-swift-lm #367 on main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libs/mlx-swift-lm moves from 04940f55 to 093563be, the merge commit of mlx-swift-lm #367 on main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libs/mlx-swift-lm moves from 1aace467 to 093563be, the merge commit of mlx-swift-lm #367 on main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libs/mlx-swift-lm moves from f6b9ac22 to 093563be, the merge commit of mlx-swift-lm #367 on main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
libs/mlx-swift-lm moves from 51da1368 to 093563be, the merge commit of mlx-swift-lm #367 on main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged. changelog.d/qwen35-mtp-prefill-last-row.md: mlx-swift-lm #302 (Qwen 3.5 MTP prompts project only their last position) rides this pin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Problem
Providers on flaky Wi-Fi can never complete the ~15.6 GB 3-shard
gemma-4-26b-qat-4bitdownload, and after it "completes" it isn't detected so it re-downloads. Targets the 0.6.12 release.Root causes (verified against
master)ModelCatalog.swifthad two downloaders: the resumable byte-streamstreamDownload(HTTPRange, flush to a stable.part,Content-Rangevalidation —ModelCatalog.swift:1365) wired only to the background prefetch (prefetch→downloadManifestFileWithResume→downloadFile); and the path the CLI actually runs,downloadManifestModel→downloadManifestFileWithProgress(ModelCatalog.swift:930/:1080), which usedURLSession.downloadTaskwith no Range and no resume data (ModelCatalog.swift:1098). Every interruption restarted the shard from byte 0 (throwawayCFNetworkDownload_*.tmp). Callers:StartCommand.swift:737/:810,ModelsCommand.swift:206..local-staging-…dir;snapshots/localis only created at final publish, andModelScanner.findLatestSnapshotuses.skipsHiddenFiles(ModelScanner.swift:101), so a download killed before publish looked "not downloaded" and re-downloaded from scratch.ModelScanner+Discovery.swift:46-56viaDarkbloom.swift:136, flagged atStartCommand.swift:677/:687; same bug inModelsCommand.swift:127), so a fully-downloaded model that exceeds available RAM read "not downloaded" forever on marginal-RAM boxes.Related field report:
darkbloom models downloadgot jetsam-killed (SIGKILL/OOM) on 36 GB Macs — the olddownloadTaskpath could buffer whole shards; the streaming path flushes every 64 KB.Fix (scoped to
provider-swift)downloadManifestModelnow downloads each shard through the resume-capabledownloadManifestFileWithResume→downloadFile→streamDownload(Range +Content-Rangevalidation + 64 KB streaming flush to a stable per-shard.part). An interrupted shard resumes viaRange: bytes=N-and never restarts from zero. Preserved: the stable.local-staging-{prefix}dir, the size+SHAalreadyValidskip, 4-way concurrency (each shard owns its.part), the aggregate-hash gate, andpublishStagedSnapshot. Live per-shard progress is threaded throughstreamDownloadvia a byte-progress callback into a new callback-based tracker (the oldURLSessionDownloadDelegatetracker is gone). The streaming path never holds a full shard in RAM.downloadManifestModelverifies the aggregate and publishes without re-downloading (sharedfinalizeStagedManifesthelper). The picker surfaces "resuming" (viaModelDownloader.hasResumableStaging) instead of "not downloaded".Start.buildPickerEntries) andmodelslisting compute "downloaded" from an UNFILTERED on-disk scan (scanAllModels); the memory filter only drives a "won't fit" warning. A present-but-too-big model now reads "downloaded (won't fit)", never "not downloaded".Dead code removed:
downloadManifestFileWithProgress,DownloadProgressTracker, and the unuseddownloadManifestFile. Progress UI extracted intoModelDownloadProgress.swiftsoModelCatalog.swiftstays focused (net −517 lines there).Tests (mock
URLProtocol)foregroundDownloadByteResumesAcrossRestart— a mid-stream-dropped foreground shard leaves a.part, and the nextdownload()resumes withRange: bytes=<prefix>-(neverbytes=0-) and completes.foregroundDownloadFinishesCompleteStagingWithoutRefetch— a pre-populated complete staging dir publishes with zero shard re-downloads (onlymanifest.jsonis fetched).ModelScannerMemoryFilterTests—scanAllModelssees a too-big model the memory-filtered scan drops.PickerEntryTests—Start.buildPickerEntriesclassifies an on-disk-but-too-big model asdownloaded, hides only not-downloaded unrunnable models, flags staged buildsresumable, and sorts downloaded-first.Verification
No coordinator / submodule / unrelated files touched.
Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.