Skip to content

feat(provider): delta complete checkpoints for Qwen's native recurrent layouts - #1591

Merged
Gajesh2007 merged 2 commits into
Layr-Labs:masterfrom
javiech1:feat/delta-checkpoints
Oct 27, 2026
Merged

Gajesh2007 merged 2 commits into
Layr-Labs:masterfrom
javiech1:feat/delta-checkpoints

Conversation

@javiech1

@javiech1 javiech1 commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements #1574 for Qwen's native recurrent checkpoints, paged and contiguous. After a request restores a complete checkpoint and the engine consumes it, its later checkpoints are written as deltas. A delta holds only the K/V and MTP-history rows the restored file lacks, plus the recurrent state. A restore streams the chain of files forward together and rebuilds the same bytes.

On a six-turn 30K–55K conversation, checkpoint writes fall from 20.0 GB to 5.4 GB. Outputs are identical and TTFT changes by at most 2.5%.

Linked issue

Refs #1574

Test plan

  • swift build --build-tests (provider-swift)
  • swift test --skip-build --filter "SSD|Checkpoint|PrefixCache" --skip "NativeDiffusionCheckpointStoreTests|SSDNativeCheckpointOracleTests|MiMoV26DiscoveryLoadFootprintTests|GPTOSS": 565 tests pass.
    • The suites skipped by that filter fail on master too on this Mac.
    • The suite sometimes hangs in the untouched SSDCacheEpochStore tests, also on master (1 run in 6).
  • New SSDCheckpointDeltaTests, run on both the paged and the contiguous fixture:
    • eight-file chains restore every tensor byte-exactly, and a full chain rebases onto its root;
    • a reopened store pairs every delta with its parent, and a durable delta is reused, not rewritten;
    • a stage the engine never took, or the flag off, writes complete files;
    • a corrupt parent fails the restore;
    • another reader holding the shared root does not hold up the chain;
    • layout rows, steps and the commitment are covered directly.
  • Cursor coverage in SSDBlockStreamingTests.
  • Full swift test --skip-build on this branch and on master: the same failures on both, all MiMo artifact fixtures that are unavailable locally.
  • Live ModelCheckpointConversationLiveTests on an M5 Max 128 GB:
    • Setup: EigenLabs/Qwen3.8-27B-4bit-mtp, MTP on, native live and checkpoint KV, exclusive GPU, isolated ephemeral cache.
    • Comparison: DARKBLOOM_PREFIX_CACHE_SSD_INCREMENTAL_CHECKPOINTS=0 against the default.
    • Result: each turn's 64 greedy tokens are identical in both modes.
Turn Prompt Restored TTFT complete → delta (paged) Written complete → delta TTFT complete → delta (contiguous)
0 30,164 0 36.55 → 36.59 s 2.79 → 2.79 GB 35.44 → 35.47 s
1 35,279 28,672 10.26 → 10.24 s 2.64 → 0.46 GB 9.59 → 9.61 s
2 40,394 32,768 12.14 → 12.22 s 2.95 → 0.46 GB 11.37 → 11.45 s
3 45,506 36,864 14.60 → 14.73 s 3.57 → 0.77 GB 13.39 → 13.55 s
4 50,054 45,056 10.03 → 10.20 s 3.88 → 0.46 GB 8.86 → 9.05 s
5 55,166 49,152 11.46 → 11.67 s 4.19 → 0.46 GB 10.38 → 10.64 s
Total 20.01 → 5.42 GB (same bytes)
  • The gap from the last token to the terminal, which waits for checkpoint publication, fell from 0.6–1.0 s to 0.14–0.26 s.
  • Local darkbloom start --local from master and from this branch, with an isolated HOME, cache root and key:
    • One conversation: 5 streaming OpenAI turns, 32K → 54K tokens. Outputs are identical and TTFT is within 0.2 s. The cache wrote 5.45 GB instead of 18.2 GB.
    • Mixed traffic: Qwen 3.8, Gemma 4 26B and Qwen 3.5 9B loaded at once. Four concurrent agents share a 20K-token document and take their turns together, while Gemma and Qwen 3.5 9B serve chat. Two rounds per build: 0 errors, all 36 outputs identical per round, agent latency 565–585 s against 568 s. The cache wrote 8.5–8.7 GB instead of 17.3–20.3 GB.
  • make docs-check, make docs-impact-check BASE=origin/master, make changelog-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
  • Yes — described above and matching side updated

The DBK3 public metadata gains an optional parentCommitment. It is omitted when nil, so complete files encode byte-identically. The new env flag DARKBLOOM_PREFIX_CACHE_SSD_INCREMENTAL_CHECKPOINTS is provider-local and is not forwarded to LaunchAgents.

Documentation impact

  • Canonical documentation updated:
    • reference/ssd-kv-cache.md: new "Delta complete checkpoints" section, cursor row, env row and observer note.
    • reference/configuration.md
    • architecture/prefix-cache.md
    • architecture/security/encryption.md
    • developer/test.md
  • 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

  • Exactness. The delta is armed only after takeStage hands the restored state to the engine. Only then do the request's rows extend the restored rows byte for byte. A refused, abandoned or never-taken stage leaves the request cold, so its checkpoints are written complete and rows from two executions are never combined. Only the native recurrent layouts are eligible, because their restored rows are exported again unchanged. Lossy (balanced), historical-window, GLM and native-block layouts keep complete files.
  • Chains. The parent is the restored file. Once the chain holds eight files, the parent is the chain's root instead, which is still exact because the root's rows are restored unchanged. A chain must also fit maxReadBytes, otherwise the checkpoint is written complete. Each additional file adds one maximumSegmentBytes of read scratch.
  • Binding. parentCommitment = HMAC(K_lookup, domain ‖ parent full tag ‖ parent file IV) is authenticated as AAD. The scan pairs it with each file's own tag and IV, and an observer without K_lookup cannot link the files.
  • Locking. Only the leaf, which is the request's registration, is locked and identity-checked. Ancestors are read unlocked: each chunk is authenticated and the commitment pins the exact file. An open handle survives removal or replacement. Ancestor mtimes are touched only when free. Readers whose chains share a root therefore never wait for each other.
  • Failure and eviction. A failure retires the file in use, through the existing removeCorrupt/forgetMissing. A file built on a missing link is never a candidate and ages out by TTL and LRU. A hit or a new child refreshes the whole chain.
  • Read path. A complete file is a chain of one and restores with the same appendSegment sequence as before. readStreaming keeps its order of checks, now through SSDBlockChunkCursor.
  • Follow-ups, if useful.
    • Gemma and GPT-OSS checkpoints are balanced encoded streams with an exact recent band, so a delta there needs codec-aware stored rows. I am happy to do it next.
    • An engine-side checkpoint at each turn's end would let agents restore almost the whole previous turn, for both TTFT and bytes.

Before And After

flowchart LR
  classDef old fill:#fbe9e7,stroke:#c62828,color:#3b0d0d
  classDef new fill:#e3f4e8,stroke:#2e7d32,color:#0d2b14
  subgraph Before
    B0["Turn n restores file F(P)"]:::old --> B1["Capture at D writes a complete file:<br/>rows 0..D + recurrent state"]:::old
    B1 --> B2["Turn n+1 restores F(D)"]:::old
  end
  subgraph After
    A0["Turn n restores chain … → F(P);<br/>engine takes the stage"]:::new --> A1["Capture at D writes a delta:<br/>rows P..D + recurrent state<br/>+ parentCommitment(F(P))"]:::new
    A1 --> A2["Turn n+1 reads root … F(P) → Δ(D) forward together,<br/>skipping replaced tensors unread"]:::new
  end
Loading
flowchart TD
  classDef new fill:#e3f4e8,stroke:#2e7d32,color:#0d2b14
  W["donate (Write)"] --> E{"deltaEnvelope:<br/>consumed restore, chain under 8 files<br/>and within maxReadBytes?"}
  E -- yes --> D["SSDCheckpointDeltaLayout segments<br/>→ delta file + index parent link"]:::new
  E -- no --> C["complete file (unchanged)"]
  R["stage (ReadAttempt)"] --> K["index.chain: root first, all fresh"]:::new --> O["openChain ×2: cursor per file,<br/>commitments + manifests"]:::new --> S["streamChain → appendSegment"]:::new
Loading

Refactor Pass

A dedicated refactor subagent reviewed the diff with the invariants above. It simplified the envelope's delta construction, the stats line and the duplicate-validation guard, kept master's explicit header close, and changed no behavior (−18 source lines). After its pass and the unlocked-ancestor change, the build, the SSD/checkpoint suites, make docs-check and the paged and contiguous live runs were all rerun.

🤖 Generated with Claude Code

https://claude.ai/code/session_01CDrGQJwa1LC3j4TE6Dvgmo


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

…t layouts

Once the engine has consumed a restored native recurrent checkpoint
(paged or contiguous), the request holds that file's rows byte for
byte. Its later checkpoints are therefore written as deltas: only the
K/V and MTP-history rows the restored file lacks, plus the recurrent
state. A delta extends the restored file, or the chain's root once the
chain holds eight files. If the chain would no longer fit the stage
cap, the checkpoint is written complete.

A delta names its parent through a public parentCommitment,
HMAC(K_lookup) over the parent's full tag and random file IV. It pins
one exact file without letting a disk observer link the two, and the
startup scan pairs commitments with files.

A restore candidate is the whole chain: every link fresh and the total
bytes within the stage caps. SSDBlockChunkCursor, a pull-style DBK3
reader that readStreaming now drives, streams the leaf's tensors from
every file at once. Each file is read forward, and replaced tensors are
skipped unread. Only the leaf is locked and identity-checked. Ancestors
are authenticated per chunk and pinned by the commitment, so readers
that share a root never wait for each other. A failure retires the
file in use; files built on a missing link never stage again and age
out. A complete file is a chain of one and restores exactly as before.

DARKBLOOM_PREFIX_CACHE_SSD_INCREMENTAL_CHECKPOINTS=0 writes complete
files again. ModelCheckpointConversationLiveTests now records delta
files and output tokens, so the two modes can be compared.

Measured on an M5 Max with Qwen 3.8 27B:
- A six-turn 30K-55K conversation wrote 5.4 GB instead of 20.0 GB, on
  both paged and contiguous KV. Outputs were identical and TTFT stayed
  within 2.5%.
- In local multi-model traffic (four concurrent agents sharing a
  20K-token document, plus Gemma 4 and Qwen 3.5 9B chats), the cache
  wrote 8.5-8.7 GB instead of 17.3-20.3 GB. Latency was unchanged and
  outputs were identical.

Refs Layr-Labs#1574

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CDrGQJwa1LC3j4TE6Dvgmo
@vercel

vercel Bot commented Oct 24, 2026

Copy link
Copy Markdown

@javiech1 is attempting to deploy a commit to the EigenLabs Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Threat model review — advisory

Reviewed head 9b518b878b3e against base f9d1af3d0d3e.

Review not completed for this head. Previous findings are superseded, not confirmed resolved.
normal spending limit reached; remaining coverage deferred

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

Human review required: CI did not complete the security review. A maintainer must review the saved findings and remaining scope. A green advisory job is not security clearance; do not manually rerun the paid scan.

Failure diagnostics: REVIEW_BUDGET_STOPPED

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

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

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

@javiech1

Copy link
Copy Markdown
Contributor Author

Field data point: since v0.10.0, providers in #providers have reported much higher SSD writes (23 Oct and again today). That matches what I measure on an M5 Max: each long Qwen 3.8 turn writes a new 3–4 GB complete checkpoint, because #1520 raised the large-memory cap to 7 GiB and that cap also bounds capture. This PR brings the six-turn conversation from 20.0 GB to 5.4 GB with identical outputs, so it should take most of that load off Qwen MTP hosts. Gemma/GPT-OSS balanced checkpoints would need the follow-up mentioned in #1574.

@Gajesh2007
Gajesh2007 merged commit 1cfbcb4 into Layr-Labs:master Oct 27, 2026
7 of 13 checks passed
jonathan308 added a commit that referenced this pull request Oct 27, 2026
Brings in #1605 and #1606 (merged), #1566, #1591, #1602 and #1625.

Conflict resolved:
- docs/provider/troubleshooting.md: only the "Last updated" stamp
  conflicted; kept one stamp (2026-10-27). Both sides' text is kept.
Gajesh2007 added a commit that referenced this pull request Oct 27, 2026
…rovider job (#1630)

* fix(provider): forward the delta-checkpoint rollback to the launchd provider job

Delta complete checkpoints (#1591) are on by default and
DARKBLOOM_PREFIX_CACHE_SSD_INCREMENTAL_CHECKPOINTS=0 is their rollback, but
the key was not in LaunchAgent's environment allowlist. launchd does not
inherit the installing shell, so the export reached only a foreground
provider; the background provider job kept writing deltas, and restarts
and watchdog recovery reuse its saved plist.

Add SSDPrefixCachePolicy.incrementalCheckpointsFlag to
LaunchAgent.inferencePassthroughEnvKeys, next to the MiMo complete-prefix
rollback, so `darkbloom start` persists it into the provider plist. The
watchdog plist stays without it: the watchdog never writes the cache.

LaunchAgentEnvironmentTests.forwardsDeltaCheckpointRollbackToProviderJob
checks list membership, the watchdog exclusion, and that the provider plist
resolves the same setting as the shell through the production reader for
unset, empty, 0, " OFF ", false, no, 1 and an unknown value. It fails with
7 issues when the allowlist entry is removed.

Docs: the configuration row says the key is forwarded; the CLI reference
lists it among the forwarded variables; the SSD cache reference names it
with the forwarded cache switches. The unreleased delta-complete-checkpoints
fragment now says the rollback reaches the background provider.

* docs(provider): tighten the delta-checkpoint forwarding notes

The fragment said the rollback reaches the background provider "like the
other rollback switches", but not every default-on rollback is forwarded:
configuration.md says the Bonsai performance controls are not in the
LaunchAgent passthrough, and cli-reference.md says the same of the Qwen4
profile rollbacks. State only what this switch does.

The cli-reference forwarded-variables row restated the negative values
0/false/no/off, which configuration.md defines once as its parsing
convention; the section itself says effects and defaults are specified once
there. Say "a negative value", as the ssd-kv-cache.md row for the same
variable already does.

Docs only; no code or test change.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
davidtai added a commit that referenced this pull request Oct 28, 2026
The merge adds #1566, #1591, #1602, #1605, #1606, #1607, #1612, #1621,
#1622, #1623, #1625, #1629, #1630, #1631, #1632 (provider 0.10.4),
#1633, #1644, #1652 and #1653 to this branch.

Conflicts and resolutions:
- CoordinatorClient+Connection.swift: #1606 moves the transport setup
  out of connectAndRun into the static function connectionParameters(for:),
  and puts the connectAndRun header below it. This branch adds the
  session parameter to the same header. The merge keeps the layout of
  master. The moved header has the signature of this branch:
  connectAndRun(_ session: CoordinatorSessionRecorder). Git merged the
  other changes without a conflict: the bounded handshake of master
  (CoordinatorConnectionHandshake.start) and the session recorder of
  this branch (markOpened after register, the session parameter of
  sessionLoop and receiveLoop, and the close-code read).
- docs/provider/cli-reference.md: the runtime constants table. The merge
  keeps the three reconnect rows and the ping/pong row of this branch.
  It adds the handshake deadline row of master after the ping/pong row,
  where master has it.
- docs/provider/troubleshooting.md: only the "Last updated" stamp had a
  conflict (2026-10-26 on this branch, 2026-10-27 on master). The merge
  keeps one stamp, 2026-10-27. Git merged the rows: the backoff citation
  of this branch and the new rows of master.

Each decision has one owner after the merge:
- CoordinatorReconnectPolicy chooses the wait before the next connection
  attempt, after each end of a session or of an attempt.
- CoordinatorConnectionHandshake (#1606) cancels a handshake that does
  not complete in 30 s. runLoop catches the timeout error. That attempt
  did not send register, so the policy gives the next backoff range, as
  on master.
- UnauthorizedConnectionRecovery (#1607, #1633) decides when to start a
  re-registration of a connection that the coordinator refuses. Its
  retry backoff counts re-registrations, not connection attempts, and an
  authorized verdict sets that count to zero. The re-registration closes
  the session. Then the policy chooses the wait, as for each other end.

Checks: against master, the merge has only the changes of this branch,
in its 15 files. The troubleshooting stamp is the one exception: it has
the date of master. Against this branch, the merge has only the changes
of master, in 651 files. The one exception is the connectAndRun header,
which has the session parameter. The gitlinks do not change: libs/mlx
31f550af, libs/mlx-swift 4926d3d9, libs/mlx-swift-lm aee6ebb6.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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