Skip to content

fix(provider): resumable 4-bit model download + restart-safe detection - #372

Merged
Gajesh2007 merged 6 commits into
masterfrom
fix/resumable-4bit-model-download
Jun 16, 2026
Merged

Gajesh2007 merged 6 commits into
masterfrom
fix/resumable-4bit-model-download

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

Problem

Providers on flaky Wi-Fi can never complete the ~15.6 GB 3-shard gemma-4-26b-qat-4bit download, and after it "completes" it isn't detected so it re-downloads. Targets the 0.6.12 release.

Root causes (verified against master)

  1. The foreground/CLI manifest download path was not resumable. ModelCatalog.swift had two downloaders: the resumable byte-stream streamDownload (HTTP Range, flush to a stable .part, Content-Range validation — 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 used URLSession.downloadTask with no Range and no resume data (ModelCatalog.swift:1098). Every interruption restarted the shard from byte 0 (throwaway CFNetworkDownload_*.tmp). Callers: StartCommand.swift:737/:810, ModelsCommand.swift:206.
  2. Interrupted downloads were invisible. Completed shards land in a hidden .local-staging-… dir; snapshots/local is only created at final publish, and ModelScanner.findLatestSnapshot uses .skipsHiddenFiles (ModelScanner.swift:101), so a download killed before publish looked "not downloaded" and re-downloaded from scratch.
  3. On-disk models hidden by the RAM filter. The picker's "downloaded" flag came from the memory-filtered scan (ModelScanner+Discovery.swift:46-56 via Darkbloom.swift:136, flagged at StartCommand.swift:677/:687; same bug in ModelsCommand.swift:127), so a fully-downloaded model that exceeds available RAM read "not downloaded" forever on marginal-RAM boxes.

Related field report: darkbloom models download got jetsam-killed (SIGKILL/OOM) on 36 GB Macs — the old downloadTask path could buffer whole shards; the streaming path flushes every 64 KB.

Fix (scoped to provider-swift)

  1. Resumable + restart-safe foreground download. downloadManifestModel now downloads each shard through the resume-capable downloadManifestFileWithResume → downloadFile → streamDownload (Range + Content-Range validation + 64 KB streaming flush to a stable per-shard .part). An interrupted shard resumes via Range: bytes=N- and never restarts from zero. Preserved: the stable .local-staging-{prefix} dir, the size+SHA alreadyValid skip, 4-way concurrency (each shard owns its .part), the aggregate-hash gate, and publishStagedSnapshot. Live per-shard progress is threaded through streamDownload via a byte-progress callback into a new callback-based tracker (the old URLSessionDownloadDelegate tracker is gone). The streaming path never holds a full shard in RAM.
  2. Finish-on-restart. When the stable staging dir already holds every shard size+SHA-valid, downloadManifestModel verifies the aggregate and publishes without re-downloading (shared finalizeStagedManifest helper). The picker surfaces "resuming" (via ModelDownloader.hasResumableStaging) instead of "not downloaded".
  3. Unfiltered downloaded detection. The picker (Start.buildPickerEntries) and models listing 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 unused downloadManifestFile. Progress UI extracted into ModelDownloadProgress.swift so ModelCatalog.swift stays focused (net −517 lines there).

Tests (mock URLProtocol)

  • foregroundDownloadByteResumesAcrossRestart — a mid-stream-dropped foreground shard leaves a .part, and the next download() resumes with Range: bytes=<prefix>- (never bytes=0-) and completes.
  • foregroundDownloadFinishesCompleteStagingWithoutRefetch — a pre-populated complete staging dir publishes with zero shard re-downloads (only manifest.json is fetched).
  • ModelScannerMemoryFilterTests — scanAllModels sees a too-big model the memory-filtered scan drops.
  • PickerEntryTests — Start.buildPickerEntries classifies an on-disk-but-too-big model as downloaded, hides only not-downloaded unrunnable models, flags staged builds resumable, and sorts downloaded-first.

Verification

cd provider-swift && swift build        # clean
swift test --filter ModelPrefetchDownloaderTests   # 16 passed
swift test --filter ModelCatalogTests --filter ModelScannerMemoryFilterTests   # passed
swift test --filter PickerEntryTests --filter ModelScanner --filter CLIDispatchTests   # passed

No coordinator / submodule / unrelated files touched.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

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.
@vercel

vercel Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 16, 2026 10:15pm
d-inference-console-ui-dev Ready Ready Preview Jun 16, 2026 10:15pm
d-inference-landing Ready Ready Preview Jun 16, 2026 10:15pm

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
  • 🔵 [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
  • 🟡 [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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 1097 to 1124
@@ -1471,7 +1124,10 @@ public struct ModelDownloader: Sendable {
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 493 to 500
/// 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 659 to +678
)
}

// 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +680 to +690
// 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%.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +1 to +263
/// 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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 724 to +750
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
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@github-actions

github-actions Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

No files in this PR match any affected_files pattern in the threat model; the changes are limited to model catalog metadata, download/progress helpers, and their tests.


Trust boundaries touched

None of the formally defined TB-xxx boundaries are directly exercised by this diff.


Threat coverage

No T-xxx threats are affected. No existing mitigations are strengthened, weakened, or removed.


New attack surface not covered by the threat model

Two areas are worth a brief look before closing:

  1. Remote model download URLs (ModelCatalog.swift, StreamingFileDownloadDelegate.swift).
    If ModelCatalog stores or constructs HTTPS URLs that are later used to fetch weight files, and those URLs are (a) read from a coordinator-supplied payload or (b) otherwise attacker-influenced, this becomes a new sub-surface of TB-002 / T-007 (provider fetches weights from an untrusted origin) and potentially T-012 (operator-or-coordinator-supplied URL points to adversarially crafted weights). The threat model currently assumes weights arrive at ~/.cache/huggingface by out-of-band means; if this code is the download mechanism, T-007 and T-012's affected_files lists should include ModelCatalog.swift, StreamingFileDownloadDelegate.swift, and WeightHasher.swift together, and the download URL source should be pinned to the coordinator's signed release manifest.

  2. StartCommand.swift / ModelsCommand.swift CLI entry points.
    These are new or modified user-facing CLI surfaces. If they accept a --model flag or similar argument that bypasses the catalog filter applied at registration time, a local operator could load a model not present in the coordinator's catalog (relevant to T-007 / T-012 / T-027). Worth confirming that model selection here is validated against the same catalog list that gets advertised to the coordinator at registration.


Recommendation

No immediate security action is required. If StreamingFileDownloadDelegate performs live model downloads from coordinator- or internet-supplied URLs, add these three files to the affected_files lists of T-007 and T-012 in the threat model so future PRs touching the download path receive the weight-hash-enforcement review hint automatically.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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")) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@blacksmith-sh

blacksmith-sh Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestIntegration_ConcurrentRequests View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

…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.
@Gajesh2007

Copy link
Copy Markdown
Member Author

Pushed three review-feedback fixes (all with tests):

1. 84d8ef20 — promote a complete .part on HTTP 416 instead of re-downloading. If a prior run received every byte but died before verify+promote, the next run sent Range: bytes=<full>-; the object store answered 416 and the generic non-2xx guard deleted the complete .part and re-fetched the whole file. Now 416 (when we sent a Range) returns success so downloadFile's SHA/size check promotes the complete prefix (or deletes+restarts a corrupt one). Test stub updated to answer real 416 past EOF.

2. bc0a084d — stream shards in OS-sized chunks via a data delegate (perf). streamDownload iterated URLSession.AsyncBytes one UInt8 per async step — pathologically slow for multi-GB shards. New StreamingFileDownloadDelegate receives Data chunks and writes each synchronously to .part. This preserves AsyncBytes' backpressure for free: URLSession won't deliver the next chunk until didReceive(data:) returns, throttling the socket to disk speed with nothing queued in memory. Resume/404/416/cancellation semantics unchanged. Existing resume + prefetch resume/verify tests now run through the delegate; added many-chunk-assembly and optional-404 tests.

3. f5a1510e — guard the non-TTY fallback picker against won't-fit selections. The TUI refuses to toggle a model that can't fit in RAM, but the non-TTY fallbackPicker let a scripted/piped darkbloom start pick (by number or 'all') a downloaded-but-too-big model that then OOMs on load. Extracted the shared budget rule and a pure, testable resolveFallbackSelection that rejects won't-fit picks and filters 'all' to fitting models.

Tests: 14 ModelCatalog + 36 prefetch + 24 CLI all green locally.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines 493 to 503
/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 659 to 727
@@ -1026,28 +727,26 @@ public struct ModelDownloader: Sendable {
let job = pending[next]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +155 to +167
}

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))")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +58 to +104
/// 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] }
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 813 to +840
.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(".") }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 578 to +606
// 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".

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +32 to +71
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()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +14 to +40
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
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1043 to +1047
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines 493 to 503
/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 659 to 727
@@ -1026,28 +727,26 @@ public struct ModelDownloader: Sendable {
let job = pending[next]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +180 to +190
}
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [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

Comment on lines +58 to +103
/// 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] }
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +1 to +263
/// 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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines +1 to +246
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)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 578 to +628
// 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +1 to +157
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)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@Gajesh2007

Copy link
Copy Markdown
Member Author

Addressed the Codex P2 "Gate 416 promotion on verified downloads" (3f12a13b). The 416 "complete" branch now size-verifies the .part against the Content-Range total (bytes */<total>): only an exact-size .part is promoted; a stale/oversized/undersized .part is discarded and re-downloaded from byte 0. This closes the legacy-CDN gap where expectedSHA256 is nil and the .part was promoted with no verification. Added a regression test (oversized .part on 416 → re-downloaded, not published); existing exact-size-promote test still passes (15/15 ModelCatalog).

@Gajesh2007
Gajesh2007 merged commit c75f58e into master Jun 16, 2026
9 of 11 checks passed

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment on lines 493 to 503
/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 659 to 727
@@ -1026,28 +727,26 @@ public struct ModelDownloader: Sendable {
let job = pending[next]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [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

Comment on lines +180 to +192
}
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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 [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

Comment on lines 12 to +20
/// 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 493 to 503
/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 641 to 670
@@ -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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines 813 to +841
.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(".") }
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +1 to +263
/// 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
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

Comment on lines +1 to +246
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)
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [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

Comment on lines 578 to +628
// 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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 [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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +1043 to +1047
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Gajesh2007 added a commit that referenced this pull request Jun 16, 2026
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).
jonathan308 added a commit that referenced this pull request Nov 10, 2026
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>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
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>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
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>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
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>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
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>

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 47170aaf Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 47170aaf Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-landing — 47170aaf Deployed Jun 16, 2026 by vercel[bot]
benchmarks — 47170aaf Deployed Jun 16, 2026 by Gajesh2007 via E2E Benchmarks #1057
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants