Skip to content

perf(provider): charge the SSD write ledger once per attention donation (~5× faster donations) - #1647

Merged
Gajesh2007 merged 3 commits into
masterfrom
perf/ssd-ledger-charge-per-donation
Oct 28, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
perf/ssd-ledger-charge-per-donation

Conversation

@jonathan308

@jonathan308 jonathan308 commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

GPT-OSS and Gemma donate one SSD cache file per 256-token block, and the write-behind consumer charged the daily write budget once per block. In production that budget is the root-wide .write-budget ledger: every charge rewrites it with pwrite + F_FULLFSYNC under a non-blocking flock. Block data itself is not fsynced (strictFsync is off), so the ledger flush dominated each block's write. Because the ledger is shared and nothing waits on it by design, another model's writer that met the held lock was refused as rate-limited.

A donation of more than one block now first reserves the summed serialized size of all its blocks in one charge, before its first write. If that charge is refused (cap near, ledger busy), each block is charged before its own write exactly as before, so the leading blocks that fit are still written. Single-block donations are unchanged.

Linked issue

No linked issue. Found while measuring the SSD write path.

Test plan

  • Throughput probe (appendix): one SSDWriteBehind with real DBK3 writes, a 64-block donation, a fresh root and ledger per run, M3 Ultra internal SSD, debug test build, 3 runs each.
Block size No ledger Ledger, master Ledger, this PR
1 MiB 69.6-72.8 ms 411.9-445.4 ms 73.4-77.8 ms
4 MiB 108.0-114.9 ms 502.1-518.3 ms 114.3-118.4 ms

The ledger cost falls from about 5.4-6.3 ms per block to one flush per donation.

  • Contention probe: two stores with separate limiters and SSDWriteBudget instances on one ledger root, like two models in a default installation.
Scenario master This PR
Store Y's mightAccept checks while store X writes a 64-block donation 138 of 203 refused 5 of 41 refused (the donation is shorter)
Both stores start a 64-block donation at the same moment, 10 repetitions 633 of 1,280 blocks refused (58-96 per repetition) 123 of 1,280 refused (10-15 per repetition)
  • New SSDWriteBehindLedgerChargeTests (deterministic, no sleeps):

    • a four-block donation touches the shared ledger once, and the ledger then holds exactly the four blocks' serialized size. A second holder takes the ledger lock while the first block is written. On master this test fails: 1 block is written and 3 are refused.
    • a donation charge refused by a busy ledger falls back to block-by-block charges: 3 of 4 written, 1 refused.
    • near the daily cap the leading blocks that fit are still written: 2 of 4 written, 2 refused.
    • when other stores have spent the shared ledger down to 2.5 blocks while this store's own bucket is full, the same 2 of 4 are written. That is the usual production shape near the cap.

    The last three pass on master too; they guard behavior this PR keeps.

  • Every SSD-cache suite (all Tests/ProviderCoreTests/KVCacheSSD/ files plus the write-budget, rate-limiter, cache-volume and cache-storage suites): 403 tests in 73 suites pass, on the build with this change.

  • make docs-impact-check BASE=origin/master, make docs-check, make changelog-check, git diff --check.

Components touched

  • provider-swift (Swift CLI)
  • native runtime / MLX
  • landing (Next.js)
  • enclave (Swift)
  • CI / provider release
  • docs

Protocol / interface changes

  • No protocol/interface changes

The ledger format, its SHA-256 record check, the inode and device checks, the no-follow path walk and the daily cap are unchanged (SSDWriteBudget.swift and SSDWriteRateLimiter.swift are untouched). Cache encryption, file names and the coordinator-facing outcomes are unchanged.

Documentation impact

  • Canonical documentation updated: docs/reference/ssd-kv-cache.md (write-budget paragraph).
  • No documentation needed — reason:

Changelog

  • Added or updated this PR's unique changelog.d/<topic>.md fragment and ran make changelog-check.
  • No user-visible change, or an explicitly authorized release/history change.

Notes for reviewers

  • Accounting. A charge still precedes every write and is never refunded. A block skipped after the donation's charge stays charged, like a failed write. The skip causes are an unsafe file name, a busy per-file lease, cancellation or close, a write error, and ENOSPC. Such skips only ever over-count, which is the conservative direction for the endurance cap.
  • No waiting. A refused donation charge has no side effect and falls through to the old per-block path. Both stores still refuse rather than wait. That is why two donations that start at the same instant still lose some blocks: the one that loses the race for the single charge falls back, and its per-block charges are refused while the other store's flush holds the ledger. A short async retry on a busy ledger would remove that remaining loss. It would change the ledger's documented "deny rather than wait" rule, so it is left to the owner.
  • Scope. Complete checkpoints (SSDHybridCheckpointStore) already write one file per job and charge once, so they are unchanged. So is the donate-side advisory check (mightAcceptWrite, gated on a single block).

Freshness receipt

Source Observed tip Consumed Disposition
d-inference master 8effff7f7 branch base 8effff7f7 current
SDK gitlinks master's pins (libs/mlx-swift-lm aee6ebb6, libs/mlx-swift 4926d3d9) unchanged no dependency change

Before And After

sequenceDiagram
  participant W as Write-behind consumer
  participant L as Shared .write-budget ledger
  participant D as Cache files
  Note over W,D: Before: a 64-block donation
  loop each of 64 blocks
    W->>L: flock (non-blocking), pwrite, F_FULLFSYNC (about 6 ms)
    W->>D: encrypt and write block
  end
  Note over W,D: After
  W->>L: one charge for the summed size (about 6 ms)
  loop each of 64 blocks
    W->>D: encrypt and write block
  end
  Note over W,L: If that charge is refused, each block is charged as before
Loading
flowchart TD
  subgraph Before
    a0["consume(job)"] --> a1["for each block"] --> a2{"tryConsume(block size)?"}
    a2 -->|"yes"| a3["write block"]
    a2 -->|"no"| a4["drop, write_rate_limited"]
  end
  subgraph After
    b0["consume(job)"] --> b1{"more than one block and<br/>tryConsume(summed size)?"}
    b1 -->|"yes"| b2["for each block: write"]
    b1 -->|"no"| b3["for each block"] --> b4{"tryConsume(block size)?"}
    b4 -->|"yes"| b5["write block"]
    b4 -->|"no"| b6["drop, write_rate_limited"]
  end
Loading

Refactor Pass

A dedicated refactor reviewer read the diff against the invariants: a charge before every write, no refunds, no waiting, a refused charge with no side effects and the old per-block path behind it, single-block donations unchanged, and SSDWriteBudget.swift/SSDWriteRateLimiter.swift untouched. It found no logic issue and made wording edits only: the comment and doc now say "instead" rather than "as before"; the helper doc covers the overflow exit; and the reference doc's list of refusal causes is marked as examples.

It confirmed two accepted over-charge cases, both in the conservative direction. A paid donation dropped because the writer closed is still charged. A ledger write whose pwrite landed but whose flush failed is reported refused and then charged again per block, as per-block charges already were.

From its other notes, two comments that described charging as always per entry now say it applies when the whole donation does not fit (SSDPrefixCache.swift, SSDPrefixCacheTests.swift). I also added the shared-ledger near-cap test. After the pass: rebuild, 403 tests in 73 suites passing, and docs-impact-check, docs-check, changelog-check and git diff --check clean.

Appendix: measurement probe (temporary test file, not committed)

Run with ZZ_LEDGER_PROBE=1 swift test --skip-build --no-parallel --filter ZZLedgerProbe.

import CryptoKit
import Foundation
import Testing
@testable import ProviderCore

@Suite("ZZ ledger probe", .serialized, .enabled(if: ProcessInfo.processInfo.environment["ZZ_LEDGER_PROBE"] == "1"))
struct ZZLedgerProbe {
    private func dir(_ label: String) throws -> URL {
        let url = try SSDTestDirectory.parent()
            .appendingPathComponent("zz-ledger-\(label)-\(UUID().uuidString)", isDirectory: true)
        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
        return url
    }

    private func blocks(_ count: Int, chunkBytes: Int, seed: UInt8) -> [SSDBlockWrite] {
        let lastDim = chunkBytes / (8 * 256 * 2)
        return (0 ..< count).map { i in
            var tag = Data(repeating: seed, count: 16)
            tag[0] = UInt8(i & 0xff); tag[1] = UInt8(i >> 8)
            let chunks = [Data(repeating: UInt8(i & 0xff), count: chunkBytes),
                          Data(repeating: UInt8((i + 1) & 0xff), count: chunkBytes)]
            let metadata = SSDBlockMetadata(
                lookupTag: String(repeating: "ab", count: 32), weightHash: "w-hash",
                layoutEpoch: "probe", blockSize: 256, layerCount: 1,
                chunks: [0, 1].map {
                    SSDBlockChunkDescriptor(layerIndex: 0, tensor: $0, shape: [1, 8, 256, lastDim], dtype: "float16")
                },
                chunkPlaintextSizes: chunks.map(\.count), createdAt: 10_000)
            return SSDBlockWrite(tag16: tag, tag16Hex: SSDLookupKeys.hex(tag), metadata: metadata,
                                 chunks: chunks, plaintextBytes: chunkBytes * 2)
        }
    }

    private func writer(root: URL, limiter: SSDWriteRateLimiter, stats: SSDPrefixCacheStatsBox) -> SSDWriteBehind {
        SSDWriteBehind(
            config: .init(
                root: root, kekKey: SymmetricKey(size: .bits256), strictFsync: false, ttlSeconds: 0,
                maxJobs: 4, maxQueuedBytes: 4 << 30, diskBudgetBytes: { 64 << 30 },
                volumeSpace: { nil }, nowSeconds: { Int64(Date().timeIntervalSince1970) },
                maintainWholeRoot: nil, writeBlock: nil),
            rateLimiter: limiter, index: SSDBlockIndex(), diskBudget: SSDDiskBudget(),
            stats: stats, onBlockSettled: { _ in }, sweepExpired: {})
    }

    private func runJob(_ writer: SSDWriteBehind, _ blocks: [SSDBlockWrite]) async -> Double {
        let start = ContinuousClock.now
        #expect(writer.submit(.init(blocks: blocks, totalBytes: blocks.reduce(0) { $0 + $1.plaintextBytes })))
        await writer.waitUntilDrained()
        let elapsed = ContinuousClock.now - start
        return Double(elapsed.components.seconds) + Double(elapsed.components.attoseconds) / 1e18
    }

    @Test func throughput() async throws {
        for chunkBytes in [512 << 10, 2 << 20] {
            for ledger in [false, true] {
                var times: [Double] = []
                for run in 0 ..< 3 {
                    let model = try dir("model"), ledgerRoot = try dir("ledger")
                    defer { try? FileManager.default.removeItem(at: model); try? FileManager.default.removeItem(at: ledgerRoot) }
                    let limiter = SSDWriteRateLimiter(
                        capBytesPerDay: 1 << 40, writeBudget: ledger ? try SSDWriteBudget(root: ledgerRoot) : nil)
                    let stats = SSDPrefixCacheStatsBox()
                    let w = writer(root: model, limiter: limiter, stats: stats)
                    times.append(await runJob(w, blocks(64, chunkBytes: chunkBytes, seed: UInt8(run))))
                    #expect(stats.snapshot().blocksWritten == 64)
                    w.close()
                }
                let ms = times.map { String(format: "%.1f", $0 * 1000) }.joined(separator: " / ")
                print("[zz-ledger] blockBytes=\(chunkBytes * 2) blocks=64 ledger=\(ledger) ms=\(ms)")
            }
        }
    }

    @Test func contention() async throws {
        let ledgerRoot = try dir("shared-ledger")
        let modelX = try dir("model-x"), modelY = try dir("model-y")
        defer { for d in [ledgerRoot, modelX, modelY] { try? FileManager.default.removeItem(at: d) } }
        let limiterX = SSDWriteRateLimiter(capBytesPerDay: 1 << 40, writeBudget: try SSDWriteBudget(root: ledgerRoot))
        let limiterY = SSDWriteRateLimiter(capBytesPerDay: 1 << 40, writeBudget: try SSDWriteBudget(root: ledgerRoot))
        let statsX = SSDPrefixCacheStatsBox(), statsY = SSDPrefixCacheStatsBox()
        let x = writer(root: modelX, limiter: limiterX, stats: statsX)
        let y = writer(root: modelY, limiter: limiterY, stats: statsY)
        // Store Y's advisory checks while store X writes a 64-block donation.
        let probe = Task.detached { () -> (Int, Int) in
            var checks = 0, refused = 0
            while !Task.isCancelled {
                checks += 1
                if !limiterY.mightAccept(bytes: 1 << 20) { refused += 1 }
                try? await Task.sleep(for: .milliseconds(1))
            }
            return (checks, refused)
        }
        _ = await runJob(x, blocks(64, chunkBytes: 512 << 10, seed: 1))
        probe.cancel()
        let (checks, refused) = await probe.value
        print("[zz-ledger] advisory checks by store Y during X's 64-block job: \(checks), refused \(refused)")
        // Both stores write 64-block donations at once.
        async let tx = runJob(x, blocks(64, chunkBytes: 512 << 10, seed: 2))
        async let ty = runJob(y, blocks(64, chunkBytes: 512 << 10, seed: 3))
        _ = await (tx, ty)
        print("[zz-ledger] concurrent jobs: X wrote \(statsX.snapshot().blocksWritten - 64)/64, Y wrote \(statsY.snapshot().blocksWritten)/64, Y rate-limited \(statsY.snapshot().writeRateLimited), X rate-limited \(statsX.snapshot().writeRateLimited)")
        x.close(); y.close()
    }

    @Test func simultaneousRepeats() async throws {
        var lost: [Int] = []
        for rep in 0 ..< 10 {
            let ledgerRoot = try dir("rep-ledger"), modelX = try dir("rep-x"), modelY = try dir("rep-y")
            defer { for d in [ledgerRoot, modelX, modelY] { try? FileManager.default.removeItem(at: d) } }
            let sx = SSDPrefixCacheStatsBox(), sy = SSDPrefixCacheStatsBox()
            let x = writer(root: modelX, limiter: SSDWriteRateLimiter(capBytesPerDay: 1 << 40, writeBudget: try SSDWriteBudget(root: ledgerRoot)), stats: sx)
            let y = writer(root: modelY, limiter: SSDWriteRateLimiter(capBytesPerDay: 1 << 40, writeBudget: try SSDWriteBudget(root: ledgerRoot)), stats: sy)
            async let tx = runJob(x, blocks(64, chunkBytes: 512 << 10, seed: UInt8(2 * rep)))
            async let ty = runJob(y, blocks(64, chunkBytes: 512 << 10, seed: UInt8(2 * rep + 1)))
            _ = await (tx, ty)
            lost.append(sx.snapshot().writeRateLimited + sy.snapshot().writeRateLimited)
            x.close(); y.close()
        }
        print("[zz-ledger] simultaneous 64+64-block donations, blocks refused per rep: \(lost) total \(lost.reduce(0, +))/1280")
    }
}

Final verification (2026-10-28, head cfea5a690)

Re-run with the same probe at the exact head and on master (8effff7f7), M3 Ultra, debug test build:

64-block donation, ledger attached master (3 runs) This PR (3 runs)
1 MiB blocks 427.3, 456.7, 425.1 ms 90.0, 92.4, 77.4 ms
4 MiB blocks 504.2, 517.6, 522.9 ms 113.2, 113.5, 112.2 ms
Contention, two stores on one ledger master This PR
Store Y's mightAccept during X's donation 139 of 197 refused 3 of 40 refused
Simultaneous 64+64-block donations, 10 repetitions 606 of 1,280 refused 132 of 1,280 refused
  • The 1 MiB range is a little wider than the first measurement (77-92 ms against 73-78 ms). The conclusion, about one ledger flush per donation instead of one per block, is unchanged.
  • 403 tests in 73 SSD suites pass at the head. CI's Provider Unit Tests passes, and the combined build of all eight d-inference PRs passes.

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need.

Freshness (2026-10-28 19:00 UTC)

GPT-OSS and Gemma write one SSD cache file per 256-token block, and the
write-behind consumer charged the daily write budget once per block. In
production that budget is the shared .write-budget ledger: each charge
rewrote it with pwrite and F_FULLFSYNC under a non-blocking flock, and a
writer that met the held lock was refused as rate-limited. Block data
is not fsynced, so the ledger flush dominated each block's write.

A donation of more than one block now first reserves the summed
serialized size of all its blocks in one charge, before any block is
written. When that charge is refused, near the daily cap or while
another writer holds the ledger, each block is charged before its own
write, so the leading blocks that fit are still written. Charges still
precede writes and are never refunded; blocks skipped after the
donation's charge stay charged, like a failed write.

64-block donations on an M3 Ultra, debug build: 412-445 ms -> 73-78 ms
with 1 MiB blocks and 502-518 ms -> 114-118 ms with 4 MiB blocks. Two
stores sharing the ledger and donating 64 blocks each at the same
moment, 10 repetitions: 633/1280 -> 123/1280 blocks refused.

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

vercel Bot commented Oct 28, 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 Oct 28, 2026 10:05pm UTC
d-inference-console-ui-dev Error Error Oct 28, 2026 10:05pm UTC
d-inference-landing Ready Ready Preview Oct 28, 2026 10:05pm UTC
darkbloom-status Ready Ready Preview Oct 28, 2026 10:05pm UTC
eigen-homepages-darkbloom Ready Ready Preview Oct 28, 2026 10:05pm UTC

Request Review

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

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head 02485ea9aa86 against base 228d4b761f7b.

Reviewers: anthropic/claude-sonnet-5.5: first pass completed; anthropic/claude-opus-5.5: selected depth completed (1 batches); openai/gpt-6.1-sol: not needed by escalation policy

No actionable findings in the reviewed text. This is not a security approval.

Models: budgeted Sonnet / selective Opus / selective Sol 6.1. Findings require human validation; this review never requests changes or blocks merging.

Scan completed.

Coverage: 46/46 source units; cross-file integration complete. 0 selected depth batch(es) pending. All threat definitions indexed; relevant full definitions selected. Unchanged callers are not scanned.

Cost this run: $0.0000 reported, $0.0000 reserved with unknown cost; 0 paid request(s), 0 reused batch(es), 0 provider cache-hit tokens.

Saved findings and earlier report · Historical findings are not confirmed resolved.

Bedrock: 17 request(s), 825781 uncached + 0 cache-read + 0 cache-write input / 10518 output tokens; 0 request(s) with unknown usage. OpenRouter backup used 0 time(s). Dollar amounts above cover OpenRouter only; AWS billing is reconciled separately.
Workload allowance: 18 native request(s), including one shared response repair; 500 emergency ceiling. Selected depth and integration rounds are admitted as their scope becomes known.

Freshness refresh: master gained #1637, #1639, #1640, #1646 and #1655. The merge has no conflicts and leaves the SDK pin unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 merged commit 4949268 into master Oct 28, 2026
29 of 33 checks passed
jonathan308 added a commit that referenced this pull request Oct 28, 2026
Brings in #1651 (retire SSD sweeps in short slices), #1642 (reread only
new or changed headers in root maintenance), #1647 (charge the write
ledger once per attention donation), #1649 (single-copy SSD reads) and
#1648 (startup expiry is not counted as corruption).

The only textual conflict was docs/reference/ssd-kv-cache.md. Master's
maintenance-sweep, header-reuse and retirement-slicing text is kept, and
this branch's TTL row and its exclusive-lease wording for owned
retirement (a file a stage is reading is skipped) are applied on top.
Sources and tests merged cleanly: master does not touch the coordinator
or the read path, and the attention write-behind keeps exclusive leases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 28, 2026
Freshness refresh: master gained #1651, #1642, #1647, #1649 and #1648. The merge has no conflicts; the SDK repin follows in its own commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 29, 2026
Brings in the SSD cache changes merged since this branch's base (#1642,
#1647, #1648, #1649, #1651) plus #1639, #1640 and #1646. The only conflict
was the docs/reference/ssd-kv-cache.md table: keep this PR's victim
selection row and master's updated maintenance sweep row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CertifiedCryp pushed a commit to CertifiedCryp/d-inference that referenced this pull request Oct 31, 2026
Brings the 13 changes that landed on master only into dev, so the next dev release and the move to master contain them: SSD cache work (Layr-Labs#1641, Layr-Labs#1642, Layr-Labs#1643, Layr-Labs#1647, Layr-Labs#1648, Layr-Labs#1649, Layr-Labs#1651, Layr-Labs#1657 and the test fixture fix 093aaf3), overlapped weight hashing (Layr-Labs#1638), GPT-OSS stop sequences in the Harmony final message (Layr-Labs#1645), faster reconnects (Layr-Labs#1613) and the provider 0.10.5 preparation (Layr-Labs#1678). Layr-Labs#1659 is master's copy of dev's Layr-Labs#1658.

Conflicts: the reconnect loop keeps dev's cluster-member handling and takes master's reconnect policy (the member-aware delay now starts from the policy's range, and the session is marked open after registration for both roles). The bridge passes both dev's default max-token context limit and master's stop-string scope. WeightHasher takes master's overlapped reads with dev's reason for reading uncached. Four case lists were the same set in a different order, a test-budget line differed only in wrapping, and two docs needed both sides. libs/mlx-swift-lm moves to mlx-swift-lm main 2beb401f, which contains dev's d5bd32b8 and master's Layr-Labs#368 and Layr-Labs#369.

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

This branch had an error being deployed

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

2 participants