Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/glm-ready-stage-estimate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Realistic GLM restore estimates in cache receipts

- A complete-checkpoint ready receipt now advertises what a restore of the file actually costs on this provider, not only its read time at the 1.5 GB/s planning rate. GLM-5.3-Flash restores take about 0.9 s beyond their bytes on an M5 Ultra, so the old estimate was a third to a half of the measured stage (478 ms for a 716 MB checkpoint that restores in 1.1–1.4 s; 125 ms for a 187 MB one that takes 1.0–1.1 s). The estimate now adds a running average of the store's own measured restores beyond their byte price, starting from the measured GLM value, so the coordinator no longer overstates the saving of short cached GLM prompts.
3 changes: 2 additions & 1 deletion docs/reference/ssd-kv-cache.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# SSD KV cache reference

> Last updated: 2026-10-21
> Last updated: 2026-10-24

Exact on-disk format, paths, identity binding, environment knobs, size and
eviction rules, and per-family reuse capability of the provider's encrypted SSD
Expand Down Expand Up @@ -122,6 +122,7 @@ and MTP codec. No public header field exposes those token boundaries
| Imported lifetime | Single-use staged state retains native owners through aliases. Paged adoption replaces temporary staging with the full request promise and actual backing; recurrent/MTP auxiliary state has its own charge | `CompleteCheckpointTransfer.swift` |
| Host IO lifetime | Read/decrypt aliases retire before the read charge returns; writers claim host buffers before encoding and release them after the complete write stack drains | `SSDHybridCheckpointStore+ReadAttempt.swift` (`readCheckpoint`), `SSDHybridCheckpointStore+Write.swift` (`write`) |
| Durable ready | Only supplied actual input checkpoint after committed write and engine donor/export retirement; requires request mode echo | `SSDHybridCheckpointStore+Write.swift`, `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCacheEvidenceSequencer.swift` |
| Ready stage estimate | `stage_ms` is the largest ready file's bytes at `conservativeStageBytesPerSecond` plus an exponentially weighted average (newest weight 0.25) of how much longer this store's first-attempt restores took than their byte price. The first restore replaces the layout's prior: `glm5NextPriorOverheadMilliseconds = 935` for GLM5-Next (median of nine M5 Ultra restores), 0 otherwise. The coordinator scores a holder with it until a hit's measured lookup `stage_ms` replaces it ([`Holder.StageCostAt`](https://github.com/Layr-Labs/darkbloom-platform/blob/d7be846198448baded8c933cacce63f20541f7ed/coordinator/internal/registry/cachetracker/holder.go)) | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDCheckpointStageCost.swift`, `SSDHybridCheckpointStore+Maintenance.swift` (`publishReady`), `SSDHybridCheckpointStore+Read.swift` (`stage`) |
| Disk compatibility | Verified model/template, binary, loaded metallib, OS and numerical/MTP settings, plus actual native dtype, effective checkpoint profile and storage geometry | `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy+CheckpointIdentity.swift`, `CompleteCheckpointStorageIdentity.swift` |
| Numerical environment identity | Process and slot values whose keys start with `MLX_`, `DARKBLOOM_CBV2_`, `DARKBLOOM_QWEN_`, `DARKBLOOM_MTP_`, `DARKBLOOM_GPTOSS_` or `DARKBLOOM_GEMMA4_`; native `mimo_v2` additionally binds its `DARKBLOOM_MIMO_` controls. Changing an included optimization or rollback setting selects a different disk namespace | `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy+CheckpointIdentity.swift` (`completeCheckpointIdentity`) |

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright © 2026 Eigen Labs.

import Foundation
import MLXLMCommon

/// The restore cost a complete-checkpoint store advertises in its ready
/// receipts (`PrefixCacheReadyResult.stageMs`). The coordinator charges it
/// against a holder's prefill saving until a hit's measured lookup replaces
/// it. Bytes at the planning rate
/// (`SSDPrefixCachePolicy.conservativeStageBytesPerSecond`) price the read
/// and decrypt but miss the part of a restore that does not grow with the
/// file: on GLM it is mostly the device's first work after idling, plus engine
/// turns under load. The estimate adds an exponentially weighted average of
/// what this store's completed stages took beyond the byte price. Until the
/// first one completes, a layout with a measured fixed part starts from it;
/// any other layout starts from zero.
final class SSDCheckpointStageCost: @unchecked Sendable {
/// Weight of the newest stage.
static let smoothing = 0.25

/// GLM-5.3-Flash on an M5 Ultra: the median, over nine restores of the
/// 187, 301 and 716 MB BF16 checkpoints, of the stage beyond the byte price.
static let glm5NextPriorOverheadMilliseconds = 935.0

static func priorOverheadMilliseconds(backendLayout: String) -> Double {
backendLayout == CBv2CompleteCheckpointManifest.glm5NextPagedLayout
? glm5NextPriorOverheadMilliseconds : 0
}

private let lock = NSLock()
private var overheadMilliseconds: Double
private var observed = false

init(priorOverheadMilliseconds: Double) {
overheadMilliseconds = max(0, priorOverheadMilliseconds)
}

/// One completed stage of a `bytes`-byte file. The first measurement
/// replaces the prior; later ones are averaged in.
func record(bytes: Int, milliseconds: Double) {
guard bytes > 0, milliseconds.isFinite, milliseconds >= 0 else { return }
let overhead = max(
0, milliseconds - SSDPrefixCachePolicy.estimatedStageMillisDouble(bytes: bytes))
lock.withLock {
overheadMilliseconds =
observed
? overheadMilliseconds + Self.smoothing * (overhead - overheadMilliseconds)
: overhead
observed = true
}
}

func estimatedMilliseconds(bytes: Int) -> Double {
let priced = SSDPrefixCachePolicy.estimatedStageMillisDouble(bytes: bytes)
guard priced > 0 else { return 0 }
let overhead = lock.withLock { overheadMilliseconds }
return min(PrefixCacheReadyResult.maxStageMs, (priced + overhead).rounded(.up))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ extension SSDHybridCheckpointStore: SSDEvictableStore, DurablePrefixCacheEvidenc
return (proof, PrefixCacheReadyResult(
readyTokens: Int(latest.tokenCount), requiredRecomputeTokens: 0,
expectedPrefillTokensSaved: Int(latest.tokenCount), tier: .ssd,
stageMs: SSDPrefixCachePolicy.estimatedStageMillisDouble(bytes: maximumFileBytes),
stageMs: stageCost.estimatedMilliseconds(bytes: maximumFileBytes),
finalAnchor: latest, readyAnchors: proof.anchors))
}
if let delivery { delivery.0.callback(delivery.1) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ extension SSDHybridCheckpointStore {
budget: budget, makeImportPlan: makeImportPlan)
if case .staged = outcome.disposition {
transferred = true
return result(outcome.disposition, deviceBytes: outcome.deviceBytes)
let staged = result(outcome.disposition, deviceBytes: outcome.deviceBytes)
// A retried stage also paid for the refused first attempt.
if !retried { stageCost.record(bytes: selected.fileBytes, milliseconds: staged.stageMs) }
return staged
}
guard outcome.retryable else {
// The refund runs on its own task; a cold result returns only
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public final class SSDHybridCheckpointStore: CBv2NativeCompletePrefixCache, CBv2
var afterPublishBeforeIndexForTesting: (@Sendable () -> Void)?
#endif
let statsBox = SSDHybridCheckpointStatsBox()
let stageCost: SSDCheckpointStageCost
let activity = SSDCheckpointActivity()
let fileCoordinator = SSDCheckpointFileCoordinator.shared
let namespace = UUID().uuidString
Expand Down Expand Up @@ -103,6 +104,9 @@ public final class SSDHybridCheckpointStore: CBv2NativeCompletePrefixCache, CBv2
repeatReserveFraction: SSDCheckpointDemand.repeatReserveFraction,
writeBudget: writeBudget, nowSeconds: writeNowSeconds)
self.writeDemand = SSDCheckpointDemand(ttlSeconds: config.ttlSeconds)
self.stageCost = SSDCheckpointStageCost(
priorOverheadMilliseconds: SSDCheckpointStageCost.priorOverheadMilliseconds(
backendLayout: config.backendLayout))
self.pipeline = BoundedSingleConsumerPipeline(
capacity: 1,
onDropped: { [weak self] job in self?.settle(job, positions: []) ?? job.finish([]) },
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import Foundation
import MLX
@testable import MLXLMCommon
import Testing
@testable import ProviderCore

@Suite("Complete-checkpoint ready-receipt stage estimate", .serialized)
struct SSDCheckpointStageCostTests {
/// The measured 8,192-token GLM checkpoint; 201 ms at the planning rate.
private let glmCheckpointBytes = 300_547_000

@Test("a GLM store starts from its measured fixed part; other layouts price bytes only")
func priorFollowsLayout() {
#expect(SSDCheckpointStageCost.priorOverheadMilliseconds(
backendLayout: CBv2CompleteCheckpointManifest.glm5NextPagedLayout) == 935)
for layout in [CBv2CompleteCheckpointManifest.layout, CBv2CompleteCheckpointManifest.pagedLayout,
CBv2CompleteCheckpointManifest.historicalAttentionLayout] {
#expect(SSDCheckpointStageCost.priorOverheadMilliseconds(backendLayout: layout) == 0)
}
#expect(SSDPrefixCachePolicy.estimatedStageMillisDouble(bytes: glmCheckpointBytes) == 201)
let glm = SSDCheckpointStageCost(priorOverheadMilliseconds: 935)
#expect(glm.estimatedMilliseconds(bytes: glmCheckpointBytes) == 1_136)
#expect(glm.estimatedMilliseconds(bytes: 0) == 0)
#expect(SSDCheckpointStageCost(priorOverheadMilliseconds: 0)
.estimatedMilliseconds(bytes: glmCheckpointBytes) == 201)
}

@Test("the first measured stage replaces the prior; later ones average in at a quarter")
func measuredStagesMoveTheEstimate() {
let cost = SSDCheckpointStageCost(priorOverheadMilliseconds: 935)
cost.record(bytes: glmCheckpointBytes, milliseconds: 1_001)
#expect(cost.estimatedMilliseconds(bytes: glmCheckpointBytes) == 1_001)
// 187,126,608 bytes price at 125 ms: 400 ms beyond the price.
cost.record(bytes: 187_126_608, milliseconds: 525)
#expect(cost.estimatedMilliseconds(bytes: glmCheckpointBytes) == 901)
// A stage faster than its byte price counts as no fixed part.
cost.record(bytes: glmCheckpointBytes, milliseconds: 50)
#expect(cost.estimatedMilliseconds(bytes: glmCheckpointBytes) == 726)
cost.record(bytes: 0, milliseconds: 5_000)
cost.record(bytes: glmCheckpointBytes, milliseconds: .nan)
cost.record(bytes: glmCheckpointBytes, milliseconds: -1)
#expect(cost.estimatedMilliseconds(bytes: glmCheckpointBytes) == 726)
#expect(cost.estimatedMilliseconds(bytes: .max) == PrefixCacheReadyResult.maxStageMs)
}

@Test("ready receipts price the store's own first-attempt restores, not retried ones",
arguments: [false, true])
func readyReceiptLearnsFromStagedRestores(_ retried: Bool) async throws {
try await SSDShorterRestoreFixture.withStore { fixture, donor in
await donor.closeAndWait()
let clock = SSDCheckpointTestClock()
var config = donor.config
config.stageNow = clock.now
let store = SSDHybridCheckpointStore(config: config, kekKey: fixture.key, kvBudget: fixture.budget,
diskBudget: SSDDiskBudget(), maxWriteBytesPerDay: 1 << 30)
store.scanOnDisk()
let bytes = try #require(try FileManager.default.attributesOfItem(
atPath: fixture.file(store, position: 512).path)[.size] as? Int)
let priced = SSDPrefixCachePolicy.estimatedStageMillisDouble(bytes: bytes)
let receipts = Receipts()
func readyStageMs(_ receipt: UInt64) throws -> Double {
store.registerReadyReceipt(requestID: .init(receipt), promptTokens: fixture.tokens,
cacheScope: "tenant-a", callback: receipts.append)
store.publishReady(requestID: .init(receipt), positions: [512])
return try #require(receipts.last?.stageMs)
}
#expect(try readyStageMs(960) == priced)
let probe = SSDShorterRestoreProbe()
let result = await store.stage(requestID: .init(950), request: fixture.request(),
reserveReadScratch: { try probe.scratch(fixture) }) { manifest in
if retried && manifest.position == 512 {
throw CBv2KVError.capacityExhausted(needed: 2, available: 1)
}
clock.advance(.milliseconds(600))
return try probe.cpuPlan(manifest, fixture: fixture)
}
#expect(result.staged && result.stagedTokens == (retried ? 256 : 512) && result.stageMs == 600)
// A retried stage also paid for its refused first attempt.
#expect(try readyStageMs(961) == (retried ? priced : 600))
await store.closeAndWait()
#expect(await fixture.budget.outstandingReservedBytes() == 0)
#expect(fixture.codec.admission.bytesReserved == 0)
}
}

private final class Receipts: @unchecked Sendable {
private let lock = NSLock()
private var values: [PrefixCacheReadyResult] = []
func append(_ value: PrefixCacheReadyResult) { lock.withLock { values.append(value) } }
var last: PrefixCacheReadyResult? { lock.withLock { values.last } }
}
}
Loading