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
9 changes: 9 additions & 0 deletions changelog.d/zdr-prefix-cache-ram-tier.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### A RAM-only prefix cache for zero-data-retention requests

- Requests whose sealed cache metadata asks for `cache_policy: memory_only` (zero data retention) can now reuse a repeated prompt prefix, from memory only, where they were served with their prompt cache off. On the complete-checkpoint models (gpt-oss-20b, Gemma 4, Qwen 3.5, Qwen 3.6 and the other models with complete checkpoints) such a request's checkpoints go into page-locked RAM, instead of being prefilled cold every time. The provider never writes them to a file, they never reach the swap file, and they are released before the Mac sleeps, so no hibernation image holds them.
- Only `memory_only` requests read or write this tier; ordinary requests keep the encrypted SSD cache exactly as before, and neither ever sees the other's entries.
- Entries expire with the SSD tier's 30-minute TTL (sliding on reuse, or fixed with `DARKBLOOM_SSD_KV_TTL_MODE=fixed`). Every entry is wiped on an OS memory-pressure warning or critical, before the Mac sleeps, before a model load that needs the room (before any model is evicted for it), on model unload and at shutdown. A refused memory charge that the tier's entries cover releases the least recently used ones and is retried at once, so ordinary requests are admitted as before.
- The budget is `min(8 GiB, a quarter of the fleet KV headroom)`, off below 1 GiB; it is charged to the provider's memory ledger and takes nothing from the KV pool's grant. `DARKBLOOM_ZDR_PREFIX_CACHE_RAM=off` turns the tier off (default `auto`: it holds nothing until a marked request arrives) and `DARKBLOOM_ZDR_PREFIX_CACHE_RAM_MAX_MB` replaces the cap. Both are forwarded to the LaunchAgent.
- Where there is no tier (Nemotron Super, GLM-5.3-Flash, DiffusionGemma, native MiMo, pairs, media, a budget of 0, or a slot that hosts the operator opt-in resident tiers of `DARKBLOOM_PREFIX_CACHE_MEMORY=1`, which have no TTL), marked requests still run with their prefix cache off.
- **Default change for every request:** the prompt-token piece cache (`DARKBLOOM_TTFT_PROMPT_CACHE`) now drops a piece 30 minutes after its last use, like the prefix caches, instead of keeping it until it is displaced or the model unloads. `DARKBLOOM_TTFT_PROMPT_CACHE_TTL_SECONDS` sets a shorter TTL; `0` restores the earlier behaviour. It is forwarded to the LaunchAgent.
- The local `/metrics` page adds `darkbloom_zdr_prefix_ram_*` counters (lookups, hit tokens, stores, evictions by reason, bytes, entries, budget); they hold counts only.
12 changes: 11 additions & 1 deletion docs/architecture/hardware-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,17 @@ loadIsServeable(measuredLiveKVHeadroomBytes) = measuredLiveKVHeadroomBytes ≥ m
```

`ramPrefix` is always 0 in production — there is no RAM prefix-cache carve
([`prefix-cache.md`](prefix-cache.md)).
([`prefix-cache.md`](prefix-cache.md)). The RAM-only tier of `memory_only`
requests takes nothing from any grant. Each entry is charged to the process
ledger instead (`reserveHostBuffers`), and is admitted only while a whole
budget of headroom remains beside it. When free system memory bounds the
headroom, an entry's wired pages lower it too, so an entry can cost up to twice
its size in admission headroom. A refused charge that the tier covers releases
its least recently used entries and is retried once
(`GlobalKVCacheBudget.yieldMemoryOnlyTier`); the tier is also released on
memory pressure, before the Mac sleeps, and before a model load, which counts
it as reclaimable
([RAM-only tier](prefix-cache.md#ram-only-tier-for-memory_only-requests)).

Fused causal prompt attention changes the prefill transient, not these
constants. An eligible full-attention prompt chunk takes one `.causal` SDPA
Expand Down
27 changes: 19 additions & 8 deletions docs/architecture/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -2602,6 +2602,10 @@ mismatch, or when the served template rejects a prompt the cache rendered. Reuse
never crosses a cache scope; `DARKBLOOM_TTFT_PROMPT_CACHE=0` restores the
unchanged path
([configuration](../reference/configuration.md#prompt-preparation-and-admission)).
A piece unused for `DARKBLOOM_TTFT_PROMPT_CACHE_TTL_SECONDS` (30 minutes by
default) is never returned again, and a sweep at least once a minute removes it,
also on an idle Mac. Reuse restarts its TTL; `0` keeps pieces until they are
displaced (`PromptPieceTokenStore`).

Decoded text keeps the spacing the tokens spell, unless the tokenizer config sets
`clean_up_tokenization_spaces` to true. swift-transformers reads an absent key as
Expand Down Expand Up @@ -2736,14 +2740,21 @@ bridge with the scope (`ProviderLoop.handleInferenceRequest`, the scheduler
engine and the Nemotron Super owner pass it on), and
`PrefixCacheSubmissionPolicy` decides there what it changes
(`provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+CachePolicy.swift`).
A `memory_only` request runs with `prefixCacheEnabled` off, on one Mac and on a
pair alike: the engine then makes no prefix lookup, capture or donation, the
bridge stages nothing and registers no SSD ready receipt or donation demand,
the scheduler skips the prompt-token piece cache, and a pair's ranks get
`ClusterWorkerPrefixCache.disabled`. Its receipt, were its cache on, would be
minted in the memory-only range, which every SSD store refuses
(`MemoryOnlyReceipt`). Its answer and usage are otherwise those of an
uncached request. The local API serves its requests under
A `memory_only` text request on a single-Mac slot with a RAM-only tier keeps
its prefix cache. Its receipt is minted in the memory-only range
(`MemoryOnlyReceipt`), the bridge stages from the slot's
`MemoryOnlyCheckpointTier`, and the SSD store hands the engine's take and
donation for that receipt to the tier
([RAM-only tier](prefix-cache.md#ram-only-tier-for-memory_only-requests)).
Everywhere else (media, a pair, a slot without the tier or with a tier
budget of 0) it runs with `prefixCacheEnabled` off: the engine then makes no
prefix lookup, capture or donation, and a pair's ranks get
`ClusterWorkerPrefixCache.disabled`. In both
cases the bridge stages nothing from the SSD tier and registers no SSD ready
receipt or donation demand, the scheduler skips the prompt-token piece cache,
and no SSD read, write or index path accepts the receipt. Its answer and usage
are otherwise those of an uncached request, or of a cache hit with tier
`memory`. The local API serves its requests under
`DARKBLOOM_LOCAL_CACHE_POLICY` instead ([local
API](../provider/direct-mode.md#cache-policy-of-local-requests)).

Expand Down
126 changes: 126 additions & 0 deletions docs/architecture/prefix-cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,124 @@ hits report the memory tier locally but do not yet publish coordinator holder
anchors. Resident and durable SSD routing evidence remain separate; see
[cache-aware-routing.md](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/docs/architecture/cache-aware-routing.md).

### RAM-only tier for `memory_only` requests

A request whose sealed cache metadata carries `cache_policy: memory_only`
never touches the SSD tier. Its prefix-cache receipt is minted in the reserved
range (`MemoryOnlyReceipt`), so each SSD entry point recognises it from the ID
alone. On a single-Mac complete-checkpoint slot those entry points hand it to
the slot's RAM-only tier instead of refusing it
(`provider-swift/Sources/ProviderCore/KVCacheRAM/MemoryOnlyCheckpointTier.swift`).

```mermaid
flowchart LR
R[request] --> P{memory_only receipt?}
P -- no --> S[SSD store: stage / takeStaged / donate, unchanged]
P -- yes --> T[MemoryOnlyCheckpointTier]
T --> L[stage: same chain tags + manifest checks, engine import from wired RAM]
T --> D[donate: export segments copied into one mlock'ed region]
D --> M[MemoryOnlyCheckpointPool: budget, LRU, TTL, release points]
```

- **Same semantics as the SSD tier, no file.** A donation copies the engine's
export (`readSegment`) and its encoded manifest into one region. A restore
replays those bytes through the engine's own import (`planCompleteCheckpointImport`,
`appendSegment`, `finish`), as a file restore does.
- Lookup uses the same scope-salted chain hash and HMAC tag derivation
(`SSDLookupKeys.checkpointTag`) under a per-process random key, the same
position floor and block rule, and the same identity, salt and exact-prefix
checks before the engine's own.
- The tier keeps full checkpoints (no deltas) for text requests only.
- Its lookups report tier `memory` with no chain anchors, and it sends no
holder evidence.
- **Wired, never swapped, released before sleep.** Each entry is its own `mmap`
region with `MADV_ZERO_WIRED_PAGES`, `minherit(VM_INHERIT_NONE)` and `mlock`
(`LockedHostRegion.swift`). If wiring fails, nothing is stored. Release zeroes,
unlocks and unmaps the region. `mlock` keeps pages out of the swap file but not
out of a hibernation image, so the pool releases every entry when macOS says
the Mac is about to sleep, before it lets it sleep (`SystemSleepRelease.swift`).
Ordinary process memory, as for every request, holds:
- data of a request in flight: its live KV, and each ≤ 4 MiB segment the
engine hands over while it is copied;
- the short-lived JSON encode and decode buffers of an entry's manifest;
- a restored manifest (with the prefix's token IDs) until the engine takes or
drops the staged checkpoint.
- **Budget.** `MemoryOnlyPrefixCachePolicy.budgetBytes` = `min(cap, fleet KV
headroom / 4)`, with the cap `DARKBLOOM_ZDR_PREFIX_CACHE_RAM_MAX_MB` (default
8 GiB), and off below 1 GiB. The fleet KV headroom is `UnifiedMemoryCap.kvBudgetBytes`
for the serving set, recomputed at each load and unload.
- Each entry is charged to the process ledger (`reserveHostBuffers`) and is
admitted only while the ledger keeps a whole budget of headroom beside it.
When free system memory, not the cap, bounds the ledger's headroom, an
entry's wired pages also lower that free memory, so it can cost up to twice
its size in admission headroom until it is released.
- The tier takes nothing from any slot's KV grant.
- With a budget of 0 the tier is not offered: a `memory_only` request runs
with its prefix cache off. An export larger than the budget is refused
before it is copied.
- **Release.** Every entry is released:
- on an OS memory-pressure warning or critical (`ProviderLoop+MemoryProtection.swift`,
`StandaloneServer`);
- before the Mac sleeps (`SystemSleepRelease.swift`);
- when a model load needs room, before any model is evicted for it, also with
both reclaim rollbacks set (`releaseReclaimableMemoryForLoad`,
`evictUntilAvailable`); the load gate counts the tier as reclaimable;
- at shutdown, before the wait for native owners (`ProviderLoop+StartupShutdown.swift`,
`StandaloneServer.finishShutdown`).

A refused memory charge that the tier's entries can cover releases the least
recently used ones until the shortfall is covered, and the charge is retried
once, so the request is admitted on its first call
(`GlobalKVCacheBudget.yieldMemoryOnlyTier`). An engine's own refused charge
releases the shortfall off the engine's admission lock, and the engine retries
at its next step (`directChargeRefusalSignal`). A charge too large to fit even
without the tier leaves it held. While native MiMo work is refused, the
provider has no pressure monitor; the other release points and the TTL still
apply.

A slot's entries are released when its store closes (model unload), and
closing waits for a restore still filling an engine import. Entries expire
with the SSD tier's TTL (`DARKBLOOM_PREFIX_CACHE_SSD_TTL_SECONDS`), sliding on
reuse unless `DARKBLOOM_SSD_KV_TTL_MODE=fixed`. They are refused at lookup once
expired and swept every 60 s, or every TTL when that is shorter. A donation of
a prefix already held copies nothing (`duplicate`), so a fixed TTL counts from
the first store. Least recently used entries make room for new ones.
- **Not attached** to GLM-5.3-Flash, DiffusionGemma, native MiMo, Nemotron Super,
pairs, or a slot built with `DARKBLOOM_PREFIX_CACHE_MEMORY=1`
(`MemoryOnlyPrefixCachePolicy.attachesTier`). That opt-in's
resident tiers have no TTL, so a `memory_only` request runs there with its
prefix cache off. `memory_only` requests also skip the prompt-token piece
cache. Settings:
[configuration reference](../reference/configuration.md#ram-only-prefix-tier-for-memory_only-requests).

### Prompt-derived memory that is not a cache

These keep the bytes of finished requests until they are reused or returned,
but no lookup reaches them, so no request can read them:

- MLX's freed-buffer pool, up to `DARKBLOOM_MLX_CACHE_LIMIT_GB` (default 8 GiB),
is reused by later allocations, which overwrite it, and is returned to the OS on
pressure and idle sweeps (`MLXMemoryGuard.swift`, `KVPoolReclaimer.swift`).
- Paged pools keep freed KV pages and up to `min(2 GiB, slot grant / 8)` of free KV
segments (`DARKBLOOM_TTFT_SEGMENT_RETENTION`). Segments are dropped on a
refused admission, on memory pressure, before a load gate and after 30 s of
engine idleness (`EngineV2Factory+SegmentedBackend.swift`).
- Freed Swift heap buffers (prompt token arrays, JSON buffers, segment copies)
return to the allocator without zeroing, like any freed memory of the process.

These caches, which a later request can read, expire 30 minutes after their
last use:
- the SSD tier;
- the RAM-only tier above;
- the prompt-token piece cache (`DARKBLOOM_TTFT_PROMPT_CACHE_TTL_SECONDS`).

Under `DARKBLOOM_SSD_KV_TTL_MODE=fixed` the first two expire 30 minutes after
they were written instead. The piece cache's TTL is always sliding.

The exception is the engine-resident tiers of the operator opt-in
`DARKBLOOM_PREFIX_CACHE_MEMORY=1`. They have no TTL, and `memory_only` requests
never use them.

### SSD provider gates

Standalone loading retains the pre/post weight-load hash bracket for dense
Expand Down Expand Up @@ -1031,6 +1149,12 @@ rules applied to these signals.
`libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift`
(`mtpTakeHistoryState`); opt-in per head
(`CBv2MTPPrefixCheckpointDrafter.checkpointsNonSpeculatingRows`).
10. A `memory_only` request's checkpoints exist only in wired RAM, never in a
file the provider writes or in the swap file, and are released before the
Mac sleeps. The RAM-only tier refuses every call made with an ordinary receipt
(`darkbloom_zdr_prefix_ram_unmarked_refusals_total` stays 0), and the SSD
store forwards a memory-only receipt to it before any SSD path —
`MemoryOnlyCheckpointTier.swift` (`donate`, `stage`), `LockedHostRegion.swift`.

## Failure modes

Expand All @@ -1044,6 +1168,7 @@ rules applied to these signals.
| Recurrent repeat served cold | No actual checkpoint, incompatible geometry/identity, scope mismatch, SSD stage refusal/eviction, or opt-in memory bank eviction | `HybridPrefixCache.swift`, `EngineLoopV2+HybridPrefix.swift`, `PrefixCachePolicy+Hybrid.swift` |
| A model with a history-keeping MTP head gets no coordinator holders although its slots are cache-ready | Its requests cannot speculate and its head does not record their prompt history: providers 0.10.5 through 0.10.11 on the Qwen 3.5/3.6 builds (whose default request there carried the card's presence penalty), or a head that has not opted in (NemotronH35, GLM5-Next; MiMo V2.6 before its opt-in, where every request that could not speculate published nothing) ([invariant 9](#invariants)) | `EngineLoopV2+MTPPlanning.swift` (`mtpRecordsPromptHistory`), `MTPPrefixCheckpoint.swift` (`checkpointsNonSpeculatingRows`), `CompleteCheckpointCapture.swift` |
| Local memory hit gives no coordinator routing preference | Paged resident publication is not implemented; recurrent slot missing verified identity; or holder evidence expired/invalidated | `ResidentPrefixCacheEvidence.swift`, [coordinator/registry/cache_routing_hints.go](https://github.com/Layr-Labs/darkbloom-platform/blob/48a198c71a2d30feec5597bacf1101120f7f955d/coordinator/registry/cache_routing_hints.go) |
| A `memory_only` repeat served cold | No RAM-only tier on the slot (see its attach rules), budget 0 (headroom below 4 GiB or `DARKBLOOM_ZDR_PREFIX_CACHE_RAM=off`), an entry larger than the budget (the engine still captures and exports it, since capture follows the SSD tier's size limit), too little ledger headroom, a full donation queue (`refused_busy`), wiring refused, or a release (pressure, sleep, load, refused charge, unload, shutdown, TTL) since the donation; see `darkbloom_zdr_prefix_ram_*` on local `/metrics` | `MemoryOnlyCheckpointPool.swift`, `MemoryOnlyPrefixCachePolicy.swift` |
| Load refused with `pagedUnavailable` | Explicit `paged` and preflight/capacity/pool construction failed | `EngineV2Factory+BackendPreparation.swift` |
| Every slot contiguous despite `paged` config | `DARKBLOOM_CBV2_PAGED_KV` set to a negative value, or `supportsPagedKV == false` | `EngineV2KVBackendPolicy.swift`, `EngineV2Factory+BackendPreparation.swift` |

Expand All @@ -1066,6 +1191,7 @@ rules applied to these signals.
| Complete SSD construction and identity | `provider-swift/Sources/ProviderCore/Inference/Engine/Factory/EngineV2SlotFactory+CompletePrefixCache.swift`, `provider-swift/Sources/ProviderCore/Inference/PrefixCache/PrefixCachePolicy+CheckpointIdentity.swift` |
| Complete SSD stream/import/ownership | `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDHybridCheckpointStore+Read.swift`, `provider-swift/Sources/ProviderCore/KVCacheSSD/SSDHybridCheckpointStore+Write.swift`, `libs/mlx-swift-lm/Libraries/MLXLMCommon/ContinuousBatchingV2/Prefix/CompleteCheckpointTransfer.swift` |
| SSD tier | `provider-swift/Sources/ProviderCore/KVCacheSSD/` (`SSDPrefixCache`, `SSDPrefixCacheFactory`, `SSDPrefixCachePolicy`, `SSDBlockStore`) |
| RAM-only tier for `memory_only` requests | `provider-swift/Sources/ProviderCore/KVCacheRAM/` (`MemoryOnlyCheckpointTier`, `MemoryOnlyCheckpointPool`, `LockedHostRegion`, `MemoryOnlyPrefixCachePolicy`) |
| Status and outcome vocabularies | `provider-swift/Sources/ProviderCore/Protocol/Messages.swift` (`PrefixCacheStatusReason`, `PrefixCacheDonationOutcome`) |

## Related
Expand Down
18 changes: 13 additions & 5 deletions docs/provider/direct-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -510,10 +510,13 @@ already sent: `code` `request_exceeds_node_budget` and the busy memory 503's wor
### Cache policy of local requests

`DARKBLOOM_LOCAL_CACHE_POLICY=memory_only` serves every request on this API
with its prefix cache off, as a coordinator request whose sealed
as a coordinator request whose sealed
[`cache_policy`](../reference/protocol-messages.md#sealed-cache-policy) is
`memory_only`: nothing it sends is read from, staged on or written to the SSD
tier (`RequestCachePolicy.localServing`,
`memory_only`. Nothing it sends is read from, staged on or written to the SSD
tier. On a slot with the
[RAM-only tier](../architecture/prefix-cache.md#ram-only-tier-for-memory_only-requests)
its text prefixes are kept in page-locked RAM only; elsewhere its prefix cache
is off (`RequestCachePolicy.localServing`,
`provider-swift/Sources/ProviderCore/Inference/PrefixCache/RequestCachePolicy.swift`).
Unset, empty or `default` keeps the cache; any other value is `memory_only`.
Coordinator requests never read it. `/metrics` counts the coordinator's
Expand All @@ -523,8 +526,13 @@ tier's refusals of a `memory_only` request's engine calls
read, write or index path, each refused there
(`darkbloom_memory_only_ssd_tier_touches_total`, which stays 0)
(`RequestCachePolicyCounters`). Both SSD counts stay 0 while `memory_only`
requests run with their cache off; they would count only for a memory-only
request run with a cache on, as by a RAM-only tier.
requests run with their cache off, and on a slot with a RAM-only tier the SSD
store hands their calls to that tier before any SSD path. The RAM-only tier's
`darkbloom_zdr_prefix_ram_*` lines follow: lookups by outcome, hit tokens,
stores by outcome, evictions by reason, bytes, entries and budget
(`MemoryOnlyCheckpointPool+Metrics.swift`). A standalone server releases that
tier on an OS memory-pressure warning or critical, before a model load and when
it stops.

### A long prompt's progress

Expand Down
Loading
Loading