Skip to content

feat(paged-attn): add Metal kernel dispatch infrastructure for paged attention - #6

Merged
Brooooooklyn merged 1 commit into
mainfrom
paged-attn
Dec 23, 2025
Merged

Brooooooklyn merged 1 commit into
mainfrom
paged-attn

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Dec 22, 2025 •

Copy link
Copy Markdown
Contributor

Add complete Metal kernel dispatch infrastructure for GPU-accelerated paged
attention, including:

New crate: mlx-paged-attn

  • Block-based KV cache allocation (reduces memory waste from 60-80% to <4%)
  • Metal kernel dispatch for reshape_and_cache and paged_attention kernels
  • Template-parameterized kernels (forked from HuggingFace kernels-community)
  • Pipeline caching with RwLock for thread-safe access
  • MLX array to Metal buffer extraction via FFI

Metal Buffer Extraction FFI (mlx-sys)

  • mlx_array_get_metal_buffer() - extract MTLBuffer* from MLX arrays
  • mlx_array_get_buffer_offset() - get byte offset for sliced arrays
  • mlx_array_get_data_size() - get element count
  • mlx_array_get_itemsize() - get dtype size in bytes
  • Uses Metal-specific availability check (mlx::core::metal::is_available)

Integration Tests

  • 33 tests in mlx-paged-attn (Metal state, kernels, scheduler)
  • 10 Metal buffer extraction tests in mlx-core
  • Platform-gated tests for non-macOS compatibility

Key Design Decisions

  • Template parameters instead of Metal function constants (MLX compatibility)
  • RwLock-based pipeline caching for thread safety
  • Separate mlx_metal_is_available() check vs generic GPU availability
  • Robust CI/headless environment handling in tests

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.5 [email protected]


Note

Introduces GPU-accelerated paged attention and integrates it end-to-end.

  • New mlx-paged-attn crate: block allocator, block tables, cache engine, scheduler, MLX↔Metal buffer bridge, and compiled Metal kernels (reshape_and_cache, paged_attention) with build-time metallib
  • mlx-core integration: Qwen3 gains paged KV cache, paged attention forward/prefill, continuous batching scheduler APIs (add/remove requests, step, completion), and stats accessors
  • Transformer updates: expose forward_with_qkv, QKV computation helpers, paged block forward path, and export paged_attention module
  • Array updates: add MxArray::as_raw_ptr() and from_int64() for FFI; extensive Metal buffer extraction tests (macOS-gated)
  • Qwen3 config extended with paged attention options (memory, block size, FP8 flag)
  • CI: matrix runs yarn test and cargo test; add Renovate config and minor .gitignore tweak

Written by Cursor Bugbot for commit 41583b1. This will update automatically on new commits. Configure here.

Copilot AI review requested due to automatic review settings December 22, 2025 15:35

Copy link
Copy Markdown
Contributor Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds comprehensive Metal kernel dispatch infrastructure for GPU-accelerated paged attention on macOS. It introduces a new mlx-paged-attn crate implementing block-based KV cache allocation that reduces memory waste from 60-80% to <4%. The implementation includes forked Metal kernels (adapted from HuggingFace), FFI for Metal buffer extraction, Rust scheduler/cache management, and complete TypeScript bindings.

Key changes:

  • New mlx-paged-attn crate with block allocator, scheduler, and Metal kernel dispatch
  • Metal buffer extraction FFI in mlx-sys for external kernel dispatch
  • Qwen3 model integration with paged attention support
  • 43 new tests across Metal state, kernels, scheduler, and buffer extraction

Reviewed changes

Copilot reviewed 36 out of 38 changed files in this pull request and generated no comments.

Show a summary per file
File Description
packages/core/index.d.cts TypeScript definitions for PagedKVCache, scheduler, and paged attention APIs
packages/core/index.cjs NAPI exports for ContinuousBatchingScheduler and PagedKVCache
crates/mlx-sys/src/paged_attn_kernels.h Inline Metal kernel source (1344 lines) with bfloat16, FP8, and attention kernels
crates/mlx-sys/src/mlx.cpp C++ FFI implementation for paged attention and Metal buffer extraction
crates/mlx-sys/src/lib.rs Rust FFI declarations for paged attention and buffer extraction
crates/mlx-paged-attn/src/scheduler.rs Continuous batching scheduler (765 lines) with request queuing and lifecycle management
crates/mlx-paged-attn/src/paged_kv_cache.rs Main PagedKVCache API (509 lines) with block allocation and slot mapping
crates/mlx-paged-attn/src/metal/state.rs Metal device/library/pipeline management with RwLock-based caching
crates/mlx-paged-attn/src/metal/reshape_and_cache.rs Metal kernel dispatch for reshape_and_cache (142 lines)
crates/mlx-paged-attn/src/metal/paged_attention.rs Metal kernel dispatch for paged_attention V1/V2 (377 lines)
crates/mlx-paged-attn/src/metal/mlx_integration.rs MLX array to Metal buffer extraction bridge (146 lines)
crates/mlx-paged-attn/src/config.rs PagedAttentionConfig with validation (224 lines)
crates/mlx-paged-attn/src/cache_engine.rs Per-layer cache engine management (129 lines)
crates/mlx-paged-attn/src/block_table.rs Block table mapping logical to physical blocks (303 lines)
crates/mlx-paged-attn/src/block_allocator.rs Block allocator with copy-on-write and prefix caching (316 lines)
crates/mlx-paged-attn/metal/*.metal Metal shader source files (utils, float8, reshape_and_cache, copy_blocks)
crates/mlx-paged-attn/build.rs Build script for Metal shader compilation on macOS
crates/mlx-core/src/transformer/paged_attention.rs PagedAttentionLayer integration with MLX tensors (243 lines)
crates/mlx-core/src/transformer/attention.rs Q/K/V computation methods for paged attention
crates/mlx-core/src/transformer/block.rs TransformerBlock paged attention forward methods
crates/mlx-core/src/models/qwen3/config.rs Qwen3Config paged attention options

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Brooooooklyn
Brooooooklyn force-pushed the paged-attn branch 3 times, most recently from d26e70a to e670d77 Compare December 23, 2025 03:40
…attention

Add complete Metal kernel dispatch infrastructure for GPU-accelerated paged
attention, including:

**New crate: mlx-paged-attn**
- Block-based KV cache allocation (reduces memory waste from 60-80% to <4%)
- Metal kernel dispatch for reshape_and_cache and paged_attention kernels
- Template-parameterized kernels (forked from HuggingFace kernels-community)
- Pipeline caching with RwLock for thread-safe access
- MLX array to Metal buffer extraction via FFI

**Metal Buffer Extraction FFI (mlx-sys)**
- mlx_array_get_metal_buffer() - extract MTLBuffer* from MLX arrays
- mlx_array_get_buffer_offset() - get byte offset for sliced arrays
- mlx_array_get_data_size() - get element count
- mlx_array_get_itemsize() - get dtype size in bytes
- Uses Metal-specific availability check (mlx::core::metal::is_available)

**Integration Tests**
- 33 tests in mlx-paged-attn (Metal state, kernels, scheduler)
- 10 Metal buffer extraction tests in mlx-core
- Platform-gated tests for non-macOS compatibility

**Key Design Decisions**
- Template parameters instead of Metal function constants (MLX compatibility)
- RwLock-based pipeline caching for thread safety
- Separate mlx_metal_is_available() check vs generic GPU availability
- Robust CI/headless environment handling in tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 871e4f7 into main Dec 23, 2025
@Brooooooklyn
Brooooooklyn deleted the paged-attn branch December 23, 2025 06:41
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
…attention (#6)

Add complete Metal kernel dispatch infrastructure for GPU-accelerated
paged
attention, including:

**New crate: mlx-paged-attn**
- Block-based KV cache allocation (reduces memory waste from 60-80% to
<4%)
- Metal kernel dispatch for reshape_and_cache and paged_attention
kernels
- Template-parameterized kernels (forked from HuggingFace
kernels-community)
- Pipeline caching with RwLock for thread-safe access
- MLX array to Metal buffer extraction via FFI

**Metal Buffer Extraction FFI (mlx-sys)**
- mlx_array_get_metal_buffer() - extract MTLBuffer* from MLX arrays
- mlx_array_get_buffer_offset() - get byte offset for sliced arrays
- mlx_array_get_data_size() - get element count
- mlx_array_get_itemsize() - get dtype size in bytes
- Uses Metal-specific availability check
(mlx::core::metal::is_available)

**Integration Tests**
- 33 tests in mlx-paged-attn (Metal state, kernels, scheduler)
- 10 Metal buffer extraction tests in mlx-core
- Platform-gated tests for non-macOS compatibility

**Key Design Decisions**
- Template parameters instead of Metal function constants (MLX
compatibility)
- RwLock-based pipeline caching for thread safety
- Separate mlx_metal_is_available() check vs generic GPU availability
- Robust CI/headless environment handling in tests

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Introduces GPU-accelerated paged attention and integrates it
end-to-end.
> 
> - New `mlx-paged-attn` crate: block allocator, block tables, cache
engine, scheduler, MLX↔Metal buffer bridge, and compiled Metal kernels
(`reshape_and_cache`, `paged_attention`) with build-time metallib
> - `mlx-core` integration: Qwen3 gains paged KV cache, paged attention
forward/prefill, continuous batching scheduler APIs (add/remove
requests, step, completion), and stats accessors
> - Transformer updates: expose `forward_with_qkv`, QKV computation
helpers, paged block forward path, and export `paged_attention` module
> - Array updates: add `MxArray::as_raw_ptr()` and `from_int64()` for
FFI; extensive Metal buffer extraction tests (macOS-gated)
> - Qwen3 config extended with paged attention options (memory, block
size, FP8 flag)
> - CI: matrix runs `yarn test` and `cargo test`; add Renovate config
and minor .gitignore tweak
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
41583b1. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 18, 2026
…n-defaults, lfm2 leak)

Adversarially verified all 11 inline review comments (control-flow traced;
the P1 #5 was a false alarm — qwen3_5 flat uses the decode_loop! macro that
forwards EOS before the stop check). Five were real; this fixes them.

Multi-turn flat KV/history alignment (#8 qwen3, #9 lfm2, + gemma4 sibling):
the shared `run_decode_loop` forward gate (`step+1 < max && !is_terminal`)
skips the final committed token's forward on EVERY exit, so the physical
flat cache holds P+N-1 tokens — but the per-family save persisted P+N,
leaving cached_token_history one token ahead of the cache. The next
chatSessionContinue prefills only the delta onto a cache one short →
multi-turn corruption. The two families violated on OPPOSITE axes (qwen3/
gemma4 keep-all-on-length; lfm2 keep-all-on-EOS) and need OPPOSITE fixes:
- qwen3/gemma4 are pure-KV → add a flat `materialize_final` override + an
  engine call on LENGTH exits that records the final token's K/V (mirrors
  each family's existing paged sibling; keep-all-on-length preserves the
  content token, NOT the bot-suggested drop which re-introduces a prior
  Codex-HIGH content truncation).
- lfm2 is conv-state (cannot re-run a forward) → drop-last ALWAYS, mirroring
  its own paged `save_paged_history`.
Removed the now-dead `SaveStateArgs.last_token_in_cache` field (lfm2 was its
only consumer; the shared loop makes it always-false). Added 2 negative-
controlled regression tests asserting cached_token_history.len() ==
physical_cache_len after both a LENGTH exit and an EOS early-stop.

generation_config.json defaults on VLM/MTP routes (#6 dense, #7 moe): the
qwen3_5 dense_whole_turn / paged-MTP and moe_whole_turn legacy cores
re-ran extract_chat_params on the RAW config, bypassing the engine-resolved
args.params, so omitted sampling fields fell back to builtins instead of the
checkpoint's generation_config.json. Fold apply_generation_defaults into the
config before the cores re-extract (no-op when the checkpoint ships none).

lfm2 compiled-weight leak on drop (#3): Lfm2Inner::drop erased only the
compiled-graph slot, never `mlx_clear_weights(model_id)` — so each dropped
compiled-capable lfm2 leaked its full C++ weight copy (+ 2-D transposes +
quant_info) until process exit, OOMing servers that reload models. Free it
under the write lock already held.

Gates (M5 Max): build + clippy -D warnings + fmt --check clean; engine::cmd
20/20 incl 2 new regression tests; full lib 1776 pass / 3 pre-existing flaky
Metal-f32 (banded_attention / attention_vjp, untouched files).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 22, 2026
…e findings

DESIGN (from a 4-philosophy design workshop → synthesized editorial + tooltip-dock
spec): give /jspace real identity and craft on par with the course.
- Instrument-Serif "J-Space" wordmark over a mono eyebrow with the course's glowing
  pink dot; warm subtitle; header divider. Two earned CSS primitives — .jspace-panel
  (soft translucent surface over the fixed page gradient) and .jspace-eyebrow.
- Every region becomes a panel or a recessed well; controls read as a crafted bar;
  consent + skeleton get serif heads; strict one-accent-per-job (pink = you/action/
  selection, qwen indigo = Jacobian telemetry only, book-* = pin data).
- The one spatial move: dock the per-cell readout in a sticky column beside the argmax
  grid on lg, turning the former dead right-half into an instrument+readout pair
  (source order stays grid-then-detail, so F2/F3 selection wiring is unaffected).
- Warm canvas inks (canvas-theme.ts → --text/--text-dim family) + the matching
  RankChart gridline; editorial column max-w-[82rem].

FIXES (all 6 re-gate findings, each independently verified against real control flow):
- #2 layersFor returns 1..24 for BOTH modes (spec §6 comparability); the old comment
  claiming the pack only fits 11 layers was factually false — it carries all 23 J's.
  runSelfTest keeps JACOBIAN_LAYERS (its baked reference is 11-layer).
- #6 heatmap flex item gets min-w-0 flex-1 so the 128-token 8750px canvas scrolls
  inside its bounded scroller instead of overflowing the page (verified live).
- #5 wire the spec's second RankChart: rank-vs-position at the selected layer.
- #3 cancel the pending permalink selection on any explicit divergence (select /
  prompt edit / mode change), so a stale restore never resurfaces after Run.
- #4 reset ArgmaxGridCanvas lastHoverKey on selection change, so keyboard nav then an
  intra-cell pointer move re-syncs hover with the tooltip/charts/Pin target.
- #1 self-test structural gate also asserts per-cell (layer,position) identity.

Verified: tsc 0 · lint clean on touched files · 54/54 jspace tests (10 files) ·
vp run build green · Chrome live-verified across cold/selected/skeleton states, the
128-token no-overflow case, and zero app console errors.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 22, 2026
…t ranks/bands, guards

Adversarial-review reconciliation for the Tier-1 gallery (all 8 verified against
the committed frames + control flow before fixing):

P1 #1  DROP eiffel-capital: 'Paris' IS the ℓ24 greedy output, a SPOKEN answer —
       violates the 'unspoken word' invariant. Gallery now 7 tiles (5 STRONG+2 WEAK).
       New bake assertion: no pinned concept may equal the ℓ24 argmax.
P1 #2  self-test: reject invalid live rank <=0 so a collapsed rank path can't pass
       the fuzzy low-rank delta on the french-season oracle.
P2 #3  grammar caption 'both lenses raise incorrect to rank 1-2' was false for logit
       (pinned 79034 is rank ~20 there) → rewrite to the honest J-vs-logit framing.
P2 #4  openStarter race: monotonic runIntent token; run/mode-change continuations
       bail after their awaits instead of painting a live frame over the tile.
P2 #5  rank captions were 0-based vs the 1-based API — fix inner-sum 2->3 (logit 6->7),
       precedence 0->1, few-shot 2->3, int-cast 1->2 (en+zh).
P2 #6  band drift: grammar peak ℓ18(rank4)->ℓ17(rank2), giza {16,17}->{17,18} to match
       the rank-2 plateau; tighten the bake to require band.peak on a min-rank layer.
P2 #7  cold-URL guard drops the mode check so opening a tile keeps the URL clean.
P2 #8  LandingPage persists storeLocale(useLocale()) so a direct /zh visitor's
       'Open J-Space' inherits zh (the standalone /jspace reads only localStorage).

Frames re-baked (7 byte-identical, eiffel-capital.json removed); +2 committed-data
regression tests encode the unspoken-word and band-peak invariants.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 25, 2026
…udit

Audit found via 7-surface workflow, each finding independently re-verified
(source + live-measured) before fixing.

Contrast (root causes, hit every page):
- #1 --text-muted #6a6168 (~2.9–3.2:1, failed WCAG AA) → #9a908a; now
  5.6–6.2:1 on breadcrumbs, chapter numbers, problem statements, placeholders
  (1260 text-muted-foreground uses + a few raw color: uses).
- #2 `@custom-variant dark` gated every `dark:` utility on a `.dark` ancestor
  that nothing added → intended dark callout/button colors were inert (light
  base rendered: amber/violet chips 2.3–3.6:1). Add `.dark` at boot
  (index.html shell + seo-head, captured by the prerender serialization).
  Callouts now render amber-300/violet-300/emerald-400 at 8.9–12:1.

Responsive:
- #3 no cross-chapter nav below 1024px (sidebar is `hidden lg:block`, no
  drawer/pager) → ChapterPager prev/next at every chapter foot, order from the
  `localizedChapters` registry, locale-prefixed `<a href>` + SPA-intercept,
  first/last handled, sub-chapters threaded (en+zh strings added).
- #4 /chapters hub header collided at 375px (Back over free-chat 8px, 中文
  wrapped) → labels collapse to icon+sr-only below sm (mirrors LessonLayout),
  groups shrink-0, switcher whitespace-nowrap.
- #8 landing locale toggle overlapped the hero badge at 375px (68×23px) →
  corner toggle hidden below sm; mobile in-flow toggle rides above the badge;
  hero top-anchored so the non-scrolling overlay never clips it.

Controls / a11y:
- #5 four widgets (TeacherForcingAnimation/GenerationLoop/LmHeadWalkthrough/
  WeightTyingVisual) auto-animated ignoring prefers-reduced-motion, unlike 48
  siblings → seed `playing` from matchMedia (verbatim sibling idiom) + gated
  aria-live on the step caption.
- #6 dead enabled "Voice input" mic button (no handler) → removed + dropped
  the unused Mic import.
- #7 shared <Button> stayed 32–40px on touch (the coarse-pointer 44px rule
  only matched chat classes) → min-height:44px for [data-slot=button] (+ icon
  min-width) under pointer:coarse.

Verified: build green (vite+prerender), `.dark` in all prerendered pages,
desktop unchanged, mobile pager/headers/landing confirmed live at 375px.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
DELETE /api/models/.staging reached deleteLocalModel, whose guards rejected
only empty/./..'/separators/NUL -- not dot-prefixed reserved names. During a
publish backup window that recursively removed the transaction dir, destroying
both the old model's only copy and the new staging tree. Reject any dot-prefixed
name (legitimate model dirs never start with '.'). Also gate the sweep's backup
reap on isModelInstalled(finalDir) rather than bare existsSync, so a redundant
backup is reaped only when finalDir is a proven-complete install (defensive; a
backup is always a former complete finalDir, so no live data-loss existed).

Whole-branch review #6, Findings 1, 2.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
Two paths followed symlinks the native cold-tier tier refuses, so the dashboard
disagreed with the native side and the advertised "managed root" containment was
not real:
- cache.ts listed the cache root with readdirSync (follows a symlinked root);
  the per-file lstat only guarded the leaf, so clear/evict could unlink through
  a symlinked root into foreign 64-hex .safetensors files. Reject a symlinked or
  non-directory root, mirroring the native opener (F3)
- session ingestion pushed any .jsonl via readdirSync (follows symlinks) and
  insideSessionsRoot was purely lexical, so a symlink to an external Pi session
  was indexed under the target's id -> GET disclosed it and PATCH appended to
  the external file. Skip symlinked/non-regular .jsonl at ingestion, and make
  insideSessionsRoot canonical (realpath both sides) so GET/PATCH/DELETE enforce
  real containment; a missing target falls back to canonicalizing the parent so
  DELETE of a vanished file still reconciles stale rows (F4)

Whole-branch review #6, Findings 3, 4.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…ldcard URL

- the round-5 schema guard used sqlite_schema, which reports an FTS5 virtual
  table as type='table', so a virtual `turns` with the expected columns passed
  and then wedged startup on CREATE INDEX ("virtual tables may not be indexed",
  not classified rebuildable). Use PRAGMA table_list and require type='table',
  rejecting virtual/shadow/view in one check -> quarantine+rebuild (F5)
- the round-5 wildcard-bind allowlist fix left the advertised URL as the literal
  bind host, so --host 0.0.0.0 opened http://0.0.0.0:port (Host 403'd even
  locally) and ::/empty produced malformed URLs. Advertise a connectable
  loopback display host (127.0.0.1 / [::1]) for wildcard binds and bracket
  IPv6; concrete-host binds unchanged (F6)

server.test.ts here also carries the Finding-4 session-symlink route tests.

Whole-branch review #6, Findings 5, 6.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…s; add throughput trend query

#3: session rename called the write-destructive SessionManager.open (migrates v1
and rewrites, dropping unparsed lines) after only a header-id check, so renaming
a session with an incomplete trailing turn permanently truncated it — the GET
handler already avoids this exact call. Reject partial/malformed files with 409
before opening for write (countJsonlLines != parsed length, or a non-parsing
trailing line), leaving the file byte-identical.

#6: ingest skipped a definitively-invalid but still-regular source file (cyclic
topology, missing header) without removing its previously-indexed rows, and
reconciliation only drops rows whose path is no longer a regular file — so a
swapped-to-invalid transcript stayed in the index and metrics forever.
Transactionally quarantine the stale session+turn rows in exactly those two
content-invalid branches; transient read/parse failures and valid-incomplete
prefixes are untouched.

#9 (query): the overview computed one range-wide average per model, not the
spec-promised (spec:138/159) time-bucketed trend. Add a throughputTrend query
grouped by model + day (same bucketing as tokensByDay), keeping the per-model
averages.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
DELETE /api/models/.staging reached deleteLocalModel, whose guards rejected
only empty/./..'/separators/NUL -- not dot-prefixed reserved names. During a
publish backup window that recursively removed the transaction dir, destroying
both the old model's only copy and the new staging tree. Reject any dot-prefixed
name (legitimate model dirs never start with '.'). Also gate the sweep's backup
reap on isModelInstalled(finalDir) rather than bare existsSync, so a redundant
backup is reaped only when finalDir is a proven-complete install (defensive; a
backup is always a former complete finalDir, so no live data-loss existed).

Whole-branch review #6, Findings 1, 2.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
Two paths followed symlinks the native cold-tier tier refuses, so the dashboard
disagreed with the native side and the advertised "managed root" containment was
not real:
- cache.ts listed the cache root with readdirSync (follows a symlinked root);
  the per-file lstat only guarded the leaf, so clear/evict could unlink through
  a symlinked root into foreign 64-hex .safetensors files. Reject a symlinked or
  non-directory root, mirroring the native opener (F3)
- session ingestion pushed any .jsonl via readdirSync (follows symlinks) and
  insideSessionsRoot was purely lexical, so a symlink to an external Pi session
  was indexed under the target's id -> GET disclosed it and PATCH appended to
  the external file. Skip symlinked/non-regular .jsonl at ingestion, and make
  insideSessionsRoot canonical (realpath both sides) so GET/PATCH/DELETE enforce
  real containment; a missing target falls back to canonicalizing the parent so
  DELETE of a vanished file still reconciles stale rows (F4)

Whole-branch review #6, Findings 3, 4.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…ldcard URL

- the round-5 schema guard used sqlite_schema, which reports an FTS5 virtual
  table as type='table', so a virtual `turns` with the expected columns passed
  and then wedged startup on CREATE INDEX ("virtual tables may not be indexed",
  not classified rebuildable). Use PRAGMA table_list and require type='table',
  rejecting virtual/shadow/view in one check -> quarantine+rebuild (F5)
- the round-5 wildcard-bind allowlist fix left the advertised URL as the literal
  bind host, so --host 0.0.0.0 opened http://0.0.0.0:port (Host 403'd even
  locally) and ::/empty produced malformed URLs. Advertise a connectable
  loopback display host (127.0.0.1 / [::1]) for wildcard binds and bracket
  IPv6; concrete-host binds unchanged (F6)

server.test.ts here also carries the Finding-4 session-symlink route tests.

Whole-branch review #6, Findings 5, 6.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…s; add throughput trend query

#3: session rename called the write-destructive SessionManager.open (migrates v1
and rewrites, dropping unparsed lines) after only a header-id check, so renaming
a session with an incomplete trailing turn permanently truncated it — the GET
handler already avoids this exact call. Reject partial/malformed files with 409
before opening for write (countJsonlLines != parsed length, or a non-parsing
trailing line), leaving the file byte-identical.

#6: ingest skipped a definitively-invalid but still-regular source file (cyclic
topology, missing header) without removing its previously-indexed rows, and
reconciliation only drops rows whose path is no longer a regular file — so a
swapped-to-invalid transcript stayed in the index and metrics forever.
Transactionally quarantine the stale session+turn rows in exactly those two
content-invalid branches; transient read/parse failures and valid-incomplete
prefixes are untouched.

#9 (query): the overview computed one range-wide average per model, not the
spec-promised (spec:138/159) time-bucketed trend. Add a throughputTrend query
grouped by model + day (same bucketing as tokensByDay), keeping the per-model
averages.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
DELETE /api/models/.staging reached deleteLocalModel, whose guards rejected
only empty/./..'/separators/NUL -- not dot-prefixed reserved names. During a
publish backup window that recursively removed the transaction dir, destroying
both the old model's only copy and the new staging tree. Reject any dot-prefixed
name (legitimate model dirs never start with '.'). Also gate the sweep's backup
reap on isModelInstalled(finalDir) rather than bare existsSync, so a redundant
backup is reaped only when finalDir is a proven-complete install (defensive; a
backup is always a former complete finalDir, so no live data-loss existed).

Whole-branch review #6, Findings 1, 2.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
Two paths followed symlinks the native cold-tier tier refuses, so the dashboard
disagreed with the native side and the advertised "managed root" containment was
not real:
- cache.ts listed the cache root with readdirSync (follows a symlinked root);
  the per-file lstat only guarded the leaf, so clear/evict could unlink through
  a symlinked root into foreign 64-hex .safetensors files. Reject a symlinked or
  non-directory root, mirroring the native opener (F3)
- session ingestion pushed any .jsonl via readdirSync (follows symlinks) and
  insideSessionsRoot was purely lexical, so a symlink to an external Pi session
  was indexed under the target's id -> GET disclosed it and PATCH appended to
  the external file. Skip symlinked/non-regular .jsonl at ingestion, and make
  insideSessionsRoot canonical (realpath both sides) so GET/PATCH/DELETE enforce
  real containment; a missing target falls back to canonicalizing the parent so
  DELETE of a vanished file still reconciles stale rows (F4)

Whole-branch review #6, Findings 3, 4.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…ldcard URL

- the round-5 schema guard used sqlite_schema, which reports an FTS5 virtual
  table as type='table', so a virtual `turns` with the expected columns passed
  and then wedged startup on CREATE INDEX ("virtual tables may not be indexed",
  not classified rebuildable). Use PRAGMA table_list and require type='table',
  rejecting virtual/shadow/view in one check -> quarantine+rebuild (F5)
- the round-5 wildcard-bind allowlist fix left the advertised URL as the literal
  bind host, so --host 0.0.0.0 opened http://0.0.0.0:port (Host 403'd even
  locally) and ::/empty produced malformed URLs. Advertise a connectable
  loopback display host (127.0.0.1 / [::1]) for wildcard binds and bracket
  IPv6; concrete-host binds unchanged (F6)

server.test.ts here also carries the Finding-4 session-symlink route tests.

Whole-branch review #6, Findings 5, 6.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…s; add throughput trend query

#3: session rename called the write-destructive SessionManager.open (migrates v1
and rewrites, dropping unparsed lines) after only a header-id check, so renaming
a session with an incomplete trailing turn permanently truncated it — the GET
handler already avoids this exact call. Reject partial/malformed files with 409
before opening for write (countJsonlLines != parsed length, or a non-parsing
trailing line), leaving the file byte-identical.

#6: ingest skipped a definitively-invalid but still-regular source file (cyclic
topology, missing header) without removing its previously-indexed rows, and
reconciliation only drops rows whose path is no longer a regular file — so a
swapped-to-invalid transcript stayed in the index and metrics forever.
Transactionally quarantine the stale session+turn rows in exactly those two
content-invalid branches; transient read/parse failures and valid-incomplete
prefixes are untouched.

#9 (query): the overview computed one range-wide average per model, not the
spec-promised (spec:138/159) time-bucketed trend. Add a throughputTrend query
grouped by model + day (same bucketing as tokensByDay), keeping the per-model
averages.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…nload identity, session safety

Six confirmed defects from the final whole-branch review (each control-flow
verified + probed before fixing); one finding refuted, one documented residual.

- #6 metrics (regression from R11): the trace-only token UNION projected GROSS
  traces.prompt_tokens into the `input` column while turns store NET
  (prompt-cacheRead), double-counting cached tokens. Clamp the trace side to
  MAX(prompt-cached,0) in tokensByDay + turnTotals; fixture totals corrected.
- #4 downloads: gate the install-skip on the completion marker's repo+revision
  (new readCompletion helper), not mere presence — a different revision of the
  same slug no longer reports a false `done`; mismatch falls through to the
  owned-swap.
- #7 trace ingest: move the vanished-file row reconciliation BEFORE the ingest
  loop so a renamed trace file's globally-unique rows are freed before the new
  name is ingested (were permanently dropped); watermark reconcile stays after.
- #8 session ingest: reject a non-object top-level entry (a `header\nnull\n`
  file) in isValidSessionTopology before dereferencing .type, routing it to the
  existing quarantine path instead of a warn-only catch that retained stale rows.
- #3 session rename: refuse (409) renaming a session whose file was modified
  within a liveness window — pi has no cross-process lock, so appending to a
  file a live agent is extending would race that turn. Documented best-effort.
- #5 cold cache: publish the index entry before the directory fsync so a
  post-rename dir-fsync failure keeps in-process accounting consistent with the
  on-disk file (rebuild_index already self-heals on restart).
- #2 cold-tier fingerprint→materialize window: documented as an accepted v1
  residual (off-by-default, adversary-owns-files; fd-coupled hashing out of scope).
- #1 (train KV poisoning): refuted — training never uses the paged/cold path.

Gate: typecheck exit0 · cold_cache 33/0 · dashboard 8 suites/175 · lint 0-err.
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…sion discovery, cold-cache durability

Seven confirmed defects from the final whole-branch review (each control-flow
verified + probed); one documented as an accepted fail-open residual.

- #8 (ui): resume commands interpolated the session path into a shell string
  raw — a real injection ($()/backticks/&& fired in a probe) and a break on any
  path with a space. Added a shared POSIX shQuote used at both resume sites.
- #5 (models): walkDirStats followed symlinks with statSync and recursed into
  symlinked directory targets unbounded — two links to '.' hit ~2^31 stats and
  froze the synchronous /api/models. Now recurses only real dirs (Dirent lstat
  semantics), with a dev:ino visited-set and an entry budget.
- #4 (ingest): pi with an explicit --session-dir writes sessions flat as
  <dir>/*.jsonl, but the scanner only accepted <root>/--cwd--/*.jsonl, so the
  documented shared --session-dir flow produced an empty dashboard. Now scans
  both layouts (cwd read from each file's header).
- #6 (download): an unowned (marker-less) install was refused only inside
  publish, after a full multi-GB download+hash. Preflight ownership up front
  (after staging recovery, before any hub work) so a doomed job moves no bytes;
  reworded errors to drop the unexposed overwrite advice.
- #7 (metrics): per-session metrics omitted delegated (subagent) turns —
  session-scoped trace-only union with MAX(prompt-cached,0) net clamp + trace_id
  dedup, mirroring the global overview fix, so counts/tokens match the shown
  child badge + throughput.
- #2 (cold cache): the capture loop kept blitting Metal + persisting descendants
  after a queue-drop; now stops on the first non-Ok(true), keeping the enqueued
  set a contiguous restorable prefix.
- #3 (cold cache): mlx agent -p exited with accepted blocks still queued (no
  drain). Added a bounded native drain barrier (WriteJob::Barrier +
  ColdCacheManager::drain -> #[napi] cold_cache_drain) invoked on clean shutdown.
- #1 (docs): documented that LRU eviction is chain-unaware and can strand prefix
  chains under quota pressure (fail-open; common case unaffected) — chain-aware
  eviction is a follow-up.

Gate: cold_cache 35/0 · typecheck exit0 · dashboard 187 tests/9 files · lint
0-err · UI build 0. (build:native's metallib floor gate fails on a known
toolchain/env hazard, independent of this branch — no shader/build files touched.)
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