Skip to content

provider: release each chunk of a chunked file read - #1836

Merged
davidtai merged 4 commits into
devfrom
fix/chunked-hash-autorelease
Nov 6, 2026
Merged

davidtai merged 4 commits into
devfrom
fix/chunked-hash-autorelease

Conversation

@davidtai

@davidtai davidtai commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Cause

On Darwin, FileHandle.read(upToCount:) and readData(ofLength:) return autoreleased storage. A Swift concurrency thread drains no autorelease pool between jobs, and a Dispatch block drains none before it returns. A loop that reads a file or a pipe in chunks therefore kept every chunk resident until its thread went idle, so memory grew with the bytes read. #1829 found this in the update hashes (one test process reached 14.96 GiB). This PR fixes the same pattern in the other sites. It does not touch #1829's files.

Fix

FileHandle.readDrained(upToCount:) (ProviderCoreFoundation/FileHandle+DrainedRead.swift) is read(upToCount:) inside its own autoreleasepool. It has the same errors, the same end of file (nil or empty) and the same bytes. On Linux (darkbloom-publish) it is a plain read. Each call site keeps its own error mapping and cancellation checks.

The first CI run found a second cause in the two child-output readers. DesktopOutputBuffer kept its tail as data.suffix(32_768), and SandboxOutputTail used removeFirst(_:). Both make a slice of the same storage, and each later append grows that storage, so the "32 KiB" tail held every byte the child wrote: 256 MiB of output left 258 MiB resident. Each tail is now Data(data.suffix(limit)), a copy. The text is unchanged. BoundedProcess's StderrTailBox had the same removeFirst(_:) trimming and now copies the same way; its readabilityHandler read (availableData) also runs in its own pool, because the handler's queue may run many callbacks before it drains.

Sites

Site Verdict
ManifestBuilder.hashOne (publish, 64 KiB reads) Fixed: readDrained
SpecDecStore.digestRegularFile (1 MiB) Fixed: readDrained; the cancellation check before each read is unchanged
BinaryHasher.sha256Digest(of:) (64 KiB readData(ofLength:); hashFile(atPath:), SecurityFoundation) Fixed: readData(ofLength:) inside autoreleasepool (it keeps its non-throwing API)
makeRuntimeMetallibSnapshot, the metallib copy loop (1 MiB) Fixed: readDrained, and the write in its own pool
SSDBlockStore.readExactly, called once per chunk by the streamed KV restore (SSDBlockChunkCursor, readStreaming) Fixed: readDrained. A restore reads every chunk of a checkpoint file in one call, and the uncopied chunk it returns stayed resident after the caller dropped it
LiveContext.workerSHA256 (4 MiB reads, worker of tens of MB) Fixed: readDrained
MTPBenchmarkDigest.sha256(file:) (weight files) Fixed: readDrained
WorkerCodeIdentity.inspect, the executable hash (1 MiB) Fixed: moved to WorkerCodeIdentity.sha256Hex(of:) with an inline autoreleasepool (ProviderAppAttest does not depend on ProviderCoreFoundation)
DesktopWorker.run pipe reader (4 KiB, one Dispatch block for the child's life; keeps a 32 KiB tail) Fixed: readDrained
SandboxChildProcess.read pipe reader (16 KiB, same shape; tail or lines) Fixed: readDrained
UpdateAtomicFilesystem.sha256(file:) / treeHash(root:) #1829
WeightHasher.hashSingleFileViaHandle Not needed: already drains each read (withAutoreleasePool)
WeightHasher InputStream path, OverlappedFileDigest Not needed: they read into buffers they own (InputStream.read, pread); no Foundation object per chunk
WorkerTransport.readExactly Not needed: Darwin.read into one Data
ClusterLogScan.lastLine Not needed: one scan reads at most limitBytes (8 MiB), whatever the log size
TeacherForcedBenchmarkInput.readBounded, SSDCacheEpochStore.readRecord Not needed: loops bounded by a 1 MiB / maxRecordBytes total
BoundedProcess stderr (availableData in a readabilityHandler, StderrTailBox) Fixed: compact tail copy, and the read in its own pool
FanProcessRunner (availableData) Not needed: FanProcessOutputBox stops appending at 64 KiB, so it holds at most that; short helper output with a 15 s limit
Single bounded reads (ModelScanner, ClusterRuntimeApprovalFacts, Qwen4ExpMmapFootprint, SpecDecStore header, DistributedEngineFactory, KVEstimation, DeviceAuth, OwnerOnlyFile, LifecycleMailbox, AddonHoldStore, FanDurableFile, DeviceCheckEvidence, BenchmarkCommand, DeadlinePowerPolicyReader, ClusterSetupWizardCommand stdin, SSDBlockChunkCursor.finish) and readDataToEndOfFile calls Not needed: one read per call, no chunk loop

Tests

  • ProviderCoreTests/ChunkedReadMemoryTests (serial shard): each case reads a 256 MiB sparse file through one site on the test's concurrency thread. It checks the known digest (a6d72ac7…06484, SHA-256 of 256 MiB of zeros), and the size where it applies. It also checks that the process footprint grows by less than 64 MiB, like UpdateFileHashMemoryTests. Cases: readDrained, ManifestBuilder.hashOne, SpecDecStore.digestRegularFile, hashFile(atPath:), makeRuntimeMetallibSnapshot (copied size and digest), SSDBlockStore.readExactly × 256, LiveContext.workerSHA256, MTPBenchmarkDigest.sha256(file:), WorkerCodeIdentity.sha256Hex(of:).
  • DarkbloomCLITests/ChildOutputReadMemoryTests: a real child writes 256 MiB of zeros, marks a file and waits for a release file. The test measures the footprint while the reader's Dispatch block is still running, then checks the exit and the 32 KiB tail. In the first run both cases failed (270 MB and 268 MB held), which found the tail retention. Cases: DesktopWorker, SandboxChildProcess.
  • ProviderCoreTests/Process/BoundedProcessStderrMemoryTests: a real child writes 256 MiB of zeros to stderr, marks a file and waits for a release file. The test measures the footprint while the child still runs, then checks exit 3 and its 4096-byte stderr tail.
  • To make the sites testable, ManifestBuilder.hashOne/Hashed and SpecDecStore.digestRegularFile go from private to internal.

Diagrams

Before:

flowchart LR
  L[chunk loop on a task or Dispatch thread] --> R["read(upToCount:)"]
  R --> P[(thread autorelease pool)]
  R --> H[hash / copy / tail]
  H --> L
  P -. drains only when the thread idles .-> F[every chunk freed]
Loading

After:

flowchart LR
  L[chunk loop on a task or Dispatch thread] --> D["readDrained(upToCount:)"]
  D --> AP[(own pool per read)]
  AP -->|drained on return| D
  D --> H[hash / copy / tail]
  H -->|chunk freed when dropped| L
Loading

Validation

No local build or test (laptop rule). CI runs the provider build and tests. Docs: one sentence each in ssd-kv-cache.md, model-registry-format.md, configuration.md (metallib snapshot), identity-binding.md and inference.md (worker digest), with stamps refreshed. Changelog: changelog.d/chunked-read-memory.md.

Refactor pass: run separately by the coordinator; not done in this PR yet.

🤖 Generated with Claude Code

On Darwin, FileHandle.read(upToCount:) and readData(ofLength:) return
autoreleased storage. A Swift concurrency thread drains no autorelease
pool between jobs, and a Dispatch block drains none before it returns,
so a loop that reads a file or a pipe in chunks kept every chunk
resident until its thread went idle: memory grew with the bytes read.

FileHandle.readDrained(upToCount:) (ProviderCoreFoundation) runs each
read in its own pool and is otherwise read(upToCount:). The chunked
loops now use it: ManifestBuilder.hashOne, SpecDecStore
.digestRegularFile, the metallib snapshot copy, SSDBlockStore
.readExactly (the streamed KV restore), LiveContext.workerSHA256,
MTPBenchmarkDigest.sha256(file:), DesktopWorker and
SandboxChildProcess. sha256Digest(of:) keeps readData(ofLength:) inside
a pool, and WorkerCodeIdentity, which cannot depend on
ProviderCoreFoundation, pools its reads inline. Digests, copied bytes,
errors and cancellation are unchanged.

Tests read 256 MiB sparse files (or child output) through each site and
check the known digest and less than 64 MiB of footprint growth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated
d-inference Error Error Nov 6, 2026 1:06am UTC
d-inference-console-ui-dev Error Error Nov 6, 2026 1:06am UTC
d-inference-landing Ready Ready Preview Nov 6, 2026 1:06am UTC
darkbloom-status Ready Ready Preview Nov 6, 2026 1:06am UTC
eigen-homepages-darkbloom Ready Ready Preview Nov 6, 2026 1:06am UTC

Request Review

DesktopOutputBuffer kept its last 32 KiB as `data.suffix(_:)` and
SandboxOutputTail as `removeFirst(_:)`. Both make a slice of the same
storage, and each later append grows that storage, so the tail held
every byte the child wrote. ChildOutputReadMemoryTests found it: 256 MiB
of output left 258 MiB resident with drained reads. Each tail is now a
copy of its last bytes; the text it gives is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
StderrTailBox trimmed with removeFirst(_:), which slices: each later
append grew the shared storage, so the tail kept all of a child's
stderr. It now keeps a copy of its last bytes; the reported text is
unchanged. The readabilityHandler's availableData read runs in its own
autorelease pool, as the other chunked reads do.

BoundedProcessStderrMemoryTests runs a real child that writes 256 MiB to
stderr and checks the footprint while it runs, then its exit status and
tail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DesktopOutputBuffer, SandboxOutputTail and StderrTailBox each trimmed
their tail with the same copy-not-slice step and the same comment. One
ProviderCoreFoundation helper, Data.keepLast(_:), now holds that step and
its reason; the bytes kept and the truncation flag do not change.

Also: the inference doc names the worker digest key's modification time
(st_mtimespec), not change time, and WorkerCodeIdentity says why its
read pool is inline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davidtai
davidtai merged commit 06eefcb into dev Nov 6, 2026
20 of 22 checks passed
@davidtai
davidtai deleted the fix/chunked-hash-autorelease branch November 6, 2026 01:28
davidtai added a commit that referenced this pull request Nov 6, 2026
Brings #1838 (measured job sizes), #1839 (stream failure frame before
the pair retires), #1836 (drained chunked reads) and #1848 (GLM video
readiness test disabled). Clean merge; Package.swift and
BuildEnvironmentTests.swift stay equal to master, MLX pins unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

2 failed and 3 active deployments
Preview – eigen-homepages-darkbloom — a63d4b6e Deployed Nov 6, 2026 by vercel[bot]
Preview – d-inference-landing — a63d4b6e Deployed Nov 6, 2026 by vercel[bot]
Preview – d-inference — a63d4b6e Deployed Nov 6, 2026 by vercel[bot]
Preview – darkbloom-status — a63d4b6e Deployed Nov 6, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — a63d4b6e Deployed Nov 6, 2026 by vercel[bot]
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.

1 participant