Skip to content

feat(chat): add high-level chat() API with tool calling support - #3

Merged
Brooooooklyn merged 2 commits into
mainfrom
tool-use
Dec 16, 2025
Merged

Brooooooklyn merged 2 commits into
mainfrom
tool-use

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Add model.chat() API for conversational AI with built-in tool calling:

  • Chat API (model.chat()): High-level interface returning ChatResult with
    parsed tool calls, extracted thinking, and clean response text
  • Tool call parsing: Rust parser for <tool_call> tags (JSON/XML formats)
  • Thinking extraction: Parse tags for chain-of-thought reasoning
  • Jinja2 templates: Full template rendering via minijinja for chat formatting

Rust implementation (crates/mlx-core/src/tools/):

  • ToolCallResult with id, name, arguments (native JS objects), status, error
  • parse_tool_calls(), parse_thinking(), parse_generation_output()
  • 18 comprehensive unit tests

TypeScript utilities (packages/lm/src/tools/):

  • createToolDefinition() helper for OpenAI-compatible tool definitions
  • formatToolResponse() for building tool response messages
  • Full type definitions for ToolDefinition, ChatConfig, ChatResult

Tests:

  • 13 type tests for chat API
  • 12 integration tests for model.chat() with tiny model

Brooooooklyn and others added 2 commits December 16, 2025 18:26
Add model.chat() API for conversational AI with built-in tool calling:

- Chat API (model.chat()): High-level interface returning ChatResult with
  parsed tool calls, extracted thinking, and clean response text
- Tool call parsing: Rust parser for <tool_call> tags (JSON/XML formats)
- Thinking extraction: Parse <think> tags for chain-of-thought reasoning
- Jinja2 templates: Full template rendering via minijinja for chat formatting

Rust implementation (crates/mlx-core/src/tools/):
- ToolCallResult with id, name, arguments (native JS objects), status, error
- parse_tool_calls(), parse_thinking(), parse_generation_output()
- 18 comprehensive unit tests

TypeScript utilities (packages/lm/src/tools/):
- createToolDefinition() helper for OpenAI-compatible tool definitions
- formatToolResponse() for building tool response messages
- Full type definitions for ToolDefinition, ChatConfig, ChatResult

Tests:
- 13 type tests for chat API
- 12 integration tests for model.chat() with tiny model

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Copilot AI review requested due to automatic review settings December 16, 2025 12:33

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 a comprehensive high-level chat API with built-in tool calling support to mlx-node. The implementation includes:

Purpose: Provide a streamlined conversational AI API that handles tool/function calling, thinking extraction, and clean response parsing automatically.

Key Changes:

  • Rust-based tool call parser supporting JSON and XML formats with 18 unit tests
  • Jinja2 template rendering integration via minijinja for chat formatting with tools
  • New model.chat() API returning structured ChatResult with parsed tool calls and thinking
  • TypeScript utilities (createToolDefinition, formatToolResponse) for developer convenience
  • 13 new integration tests and 12 type tests

Reviewed changes

Copilot reviewed 60 out of 65 changed files in this pull request and generated no comments.

Show a summary per file
File Description
crates/mlx-core/src/tools/mod.rs Core Rust tool call parser with JSON/XML support
crates/mlx-core/src/tokenizer.rs Jinja2 template rendering for chat with tools
crates/mlx-core/src/models/qwen3/model.rs High-level chat() API implementation
crates/mlx-core/src/models/qwen3/generation.rs ChatResult and ChatConfig types
packages/lm/src/tools/types.ts TypeScript tool definition helpers
packages/lm/src/tools/index.ts Tool utilities export
examples/tool-use-example.ts Complete working example
__test__/tools/chat.test.ts Type and structure tests
__test__/models/qwen3-chat.test.ts Integration tests with model
Cargo.toml Added minijinja, uuid, regex dependencies
yarn.lock Updated dependencies (@ast-grep, @esbuild, etc.)

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

@Brooooooklyn
Brooooooklyn merged commit fca66a4 into main Dec 16, 2025
@Brooooooklyn
Brooooooklyn deleted the tool-use branch December 16, 2025 13:00
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
Add model.chat() API for conversational AI with built-in tool calling:

- Chat API (model.chat()): High-level interface returning ChatResult
with
  parsed tool calls, extracted thinking, and clean response text
- Tool call parsing: Rust parser for <tool_call> tags (JSON/XML formats)
- Thinking extraction: Parse <think> tags for chain-of-thought reasoning
- Jinja2 templates: Full template rendering via minijinja for chat
formatting

Rust implementation (crates/mlx-core/src/tools/):
- ToolCallResult with id, name, arguments (native JS objects), status,
error
- parse_tool_calls(), parse_thinking(), parse_generation_output()
- 18 comprehensive unit tests

TypeScript utilities (packages/lm/src/tools/):
- createToolDefinition() helper for OpenAI-compatible tool definitions
- formatToolResponse() for building tool response messages
- Full type definitions for ToolDefinition, ChatConfig, ChatResult

Tests:
- 13 type tests for chat API
- 12 integration tests for model.chat() with tiny model

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
Two correctness improvements driven by smoke benchmark (b366bc3).

Fix #2 — MTP K/V cache offset drift vs main offset:
- Per outer cycle, main offset advanced by D+2 (1 Step A + D+1
  verify forwards), MTP draft offset advanced by D. Drift = +2/cycle.
  MTP draft's RoPE positions diverged from the absolute sequence
  positions, poisoning attention and collapsing acceptance to 0.
- Fix: new FFI `mlx_qwen35_mtp_compiled_begin_cycle(main_offset)`
  zeroes MTP K/V caches and re-anchors `g_mtp_offset_int =
  main_offset` at the start of every cycle. MoE twin
  `mlx_qwen35_moe_mtp_compiled_begin_cycle` mirrors. `MtpOps`
  gains a `begin_cycle` closure; macro calls it before
  `run_mtp_cycle_inner`.

Fix #3 — accept_with_residual non-deterministic at T=0:
- W4 spec said T=0 collapses to argmax(p_target) == draft_id, but
  the implementation always took the raw-softmax ratio path and
  sampled from (p_target - p_draft)+ via MLX `categorical()` on
  rejection — stochastic via MLX's global RNG.
- Fix: `accept_with_residual` now takes `sampling_config:
  &SamplingConfig`. When temperature <= 1e-6, returns
  (argmax(p_target) == draft_id, argmax(p_target)) — zero RNG
  consumed. Stochastic path unchanged for T > 0.
- Unit tests: 2 new (`accepts_argmax_at_t_zero`,
  `rejects_non_argmax_at_t_zero_emits_argmax`) + existing 7
  threaded through helper builders.

Smoke result after both fixes:
- Bug #1 fix advanced parity prefix from 0 → 42 chars.
- Bug #2 fix held that and eliminated the offset drift.
- Bug #3 fix made the residual emission deterministic.
- AR  : "...is essential for testing speculative decoding because
        it eliminates stochasticity, ensuring..."
- MTP : "...is useful for testing speculative decoding
        implementations.\n\nThis ensures that every run produces
        identical outputs..."

Both AR and MTP now produce coherent, deterministic output, but
they still diverge at char 43. Remaining gap (Bug #4): the verify
FFI's logits at position 0 disagree with `forward_compiled_with_hidden`'s
logits for the same prefix and same K/V state. Both paths should
end up in `qwen35_decode_fn`, so the divergence implies stateful
interaction between Step A and verify that needs runtime
instrumentation to isolate.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
… prewarm flag

Issue 1 — exception-leak window in batched verify FFI

  `mlx_qwen35_forward_batched_verify` (mlx_qwen35.cpp:839-840) and the
  MoE mirror (mlx_qwen35_moe.cpp:1182-1183) both wrote two heap `array`
  pointers directly to the caller's out-params:

    *out_logits  = new array(outputs[...]);
    *out_hiddens = new array(outputs[...]);

  If the SECOND `new` throws (`std::bad_alloc` under OOM), the catch
  block zeroes the out-pointers but never `delete`s the first heap
  array — silent leak. Fix: stage into local `array*` and only commit
  to out-pointers after BOTH allocations succeed; the catch path now
  deletes the partial allocation before rethrowing.

Issue 2 — reset path drops dispatch table but not the prewarm flag

  `mlx_qwen35_mtp_compiled_reset` (mlx_qwen35_mtp_compiled.cpp:864-872)
  and the MoE mirror clear `g_verify_compiled_by_depth[]` but the
  static `std::once_flag prewarm_once` inside
  `mlx_qwen35_mtp_compiled_prewarm_verify` stayed flipped. After a
  reset+re-init, the prewarm short-circuits via `call_once` and the
  closure table stays null. Verified via inspection of
  `get_or_make_verify_fn` (line 382-388): it IS lazy
  (`if (!slot) slot = make_verify_fn(d);`), so this is a PERF
  regression on reset+re-init (test-isolation) paths rather than a
  correctness bug — but it does defeat the entire purpose of the
  prewarm.

  Picked Option (b): swap `std::once_flag` for `std::atomic<bool>`
  gated by `compare_exchange_strong`. The reset hook now flips it back
  with `store(false)`. 3-line change in each MTP file; namespace-local
  flag stays inside the anonymous namespace next to the other globals.
  Option (a) (placement-new on `once_flag`) is gross UB-adjacent;
  option (c) accepts the regression rather than fixing it.

Files: `crates/mlx-sys/src/mlx_qwen35.cpp`,
       `crates/mlx-sys/src/mlx_qwen35_moe.cpp`,
       `crates/mlx-sys/src/mlx_qwen35_mtp_compiled.cpp`,
       `crates/mlx-sys/src/mlx_qwen35_moe_mtp_compiled.cpp`.

Verification:
  - cargo clippy --all-targets -- -D warnings: clean
  - cargo fmt --check: clean
  - cargo test -p mlx-core --lib: 1466 passed, 0 failed
  - vp lint --type-aware --type-check: 6 pre-existing warnings, 0 errors
  - vp fmt --check: clean
  - oxnode examples/qwen35-mtp-smoke.ts (3 flag combos): all 3 print
    `OK: AR and MTP produced identical output` — byte-exact parity holds.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
MTPLX-style: at T=0 with default penalties, replace the per-position
accept loop's D + 1 full-vocab softmax materializations + D × per-
position .eval() sync points with ONE batched argmax(verify_logits,
axis=-1) op. Accept loop runs entirely on CPU buffers of D+1 int32
values vs materializing D × ~151k-element softmax arrays.

Eligibility (T=0 fast path):
- temperature <= 1e-6 (matches accept_with_residual's argmax shortcut;
  Bug #3 invariant preserved — zero RNG consumed).
- All penalties at defaults (repetition=1.0, presence=0.0,
  frequency=0.0). When penalties are active hist_extended mutates per
  position; legacy per-position path handles that case.

Gated behind MLX_MTP_SPARSE_ACCEPT (default ON, opt-out for
diagnostics). Bonus-token on full-accept folds into the same batched
argmax — no extra ops.

Baseline on qwen3.6-27b-nvfp4-mtp / depth=3 / M3 Max (3-run mean):
  AR:   ~15.7 tok/s
  MTP:  ~8.5 tok/s  (~0.55x; system-noise-dominated)

Perf gate (>= 0.66x) NOT met on this hardware. The accept loop is
not the cycle-wall bottleneck on the 27B-NVFP4 smoke — verify and
Step A dominate (consistent with W6.18 findings on draft fusion).
Parity holds byte-exact across all 5 MTP knob combos × {qwen3.5-4b,
qwen3.6-27b-nvfp4-mtp}.

Co-Authored-By: Claude Opus 4.7 <[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 22, 2026
Round-3 adversarial review of the starterSlug permalink fix surfaced three
real defects (all verified against control flow before fixing):

#1 (HIGH) A crafted `#s=` slug could CRASH /jspace. STARTERS is a plain object,
   so `STARTERS['toString']` / `['__proto__']` / `['constructor']` resolve
   INHERITED Object.prototype members (truthy → the `?? default` fallback never
   fires); the render then read `.logit`/`.cells` off a non-frame and reviveRun
   threw during render. The starterSlug fix opened this by flowing untrusted `s=`
   into the lookup. Fix: `resolveStarterSlug` (own-property-safe via Object.hasOwn)
   clamps untrusted slugs to the default tile, applied at BOTH the restore clamp
   and the render lookup (defense in depth).

#2 (MED) The encoder's cold gate was `.trim() === ''` while the app's authoritative
   `isColdPrompt` is exactly-empty. A whitespace prompt therefore carried a hidden
   `s=<tile>` on the wire while the app rendered it as custom content — a later
   "clear" could expose the sender's stale tile. Fix: the encoder now imports and
   uses the SAME `isColdPrompt`, so codec and app can never diverge.

#3 (MED) Returning to the full default left a dirty hash: cold → type a prompt →
   clear it wrote `#p=&mode=l&s=french-season` because the guard only SKIPPED the
   write when already clean. Fix: when isColdDefault, actively STRIP the hash
   (replaceState to pathname+search) and reset the ref, so the URL truly returns
   to bare.

Tests: +resolveStarterSlug clamp (toString/__proto__/constructor/unknown → default),
flipped the whitespace codec test (whitespace ≠ cold), +2 app regressions
(#s=__proto__ renders default not crash; cold→custom→cold strips the hash).
tsc clean; 50 jspace tests pass; build + SSG prerender green; lint clean.

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
covers_all_shards granted coverage on a basename match, so a marker listing
a shard under a subdir (or an absolute / dot-segment path) falsely covered a
distinct top-level shard of the same size, skipping its bytes on the cheap
path -> two different weights produced the same fingerprint -> cross-model KV
restore. Match only a single Normal path component equal to the shard name;
anything else falls through to the full digest.

Whole-branch review #3, Finding 3.

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
- publish() re-checks downloader ownership adjacent to the swap so an unowned
  checkpoint that races in after the first guard is refused, never deleted (F1)
- resolveRevision() requires an immutable 40-hex commit and fails closed
  instead of pinning the mutable "main" ref into the completion marker (F2)
- staging is job-private (.staging/<slug>@<rev>.<pid>.<uuid>) so a concurrent
  process can never write into another's just-published tree; resume is
  HF-cache-backed (F4)
- sweep orphaned *.backup-* at start: restore if the final dir is missing,
  else reap (F5)
- on verify failure, invalidate the HF cache pointer+blob before retrying so a
  pinned-revision retry actually re-fetches instead of recopying corrupt bytes
  (F13)

Whole-branch review #3, Findings 1, 2, 4, 5, 13.

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
…ence

- migrate parsed session entries (migrateSessionEntries) before topology
  validation and projection so legacy v1 sessions index instead of vanishing (F9)
- isValidSessionTopology is now a memoized single pass (amortized O(n)) and is
  exported (F10)
- session detail route validates topology before projecting, so a file mutated
  into a cycle surfaces a bounded error instead of hanging pi's parent walk (F6)
- db schema check is == SCHEMA_VERSION plus a column-signature probe, so a newer
  or drifted schema quarantines+rebuilds instead of failing at first insert (F8)
- Clear-all sends {all:true} to match the hardened DELETE /api/cache contract (F11)
- paged-config override mirrors native snake-first persist precedence, so a
  config with conflicting aliases no longer silently disables persistence (F12)

Whole-branch review #3, Findings 6, 8, 9, 10, 11, 12.

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
…ounded model walk, no-follow install preflight, genuine-child session metrics

Fix-delta review of the review-#14 fixes surfaced 5 edge-case tails (each a
refinement of an R14 fix, none a reverted/broken fix). All verified via
control-flow analysis before fixing.

Native (crates/mlx-paged-attn/src/cold_cache.rs):
- #5 honest drain durability: the writer discarded persist_block errors and
  acked the barrier unconditionally, so drain() reported success even when a
  covered block failed to persist. Barrier now carries SyncSender<bool>; the
  writer accumulates a per-window failure flag and acks !failed; drain returns
  true only on an Ok(true) ack.
- #4 whole-drain bounded by timeout: drain's blocking send admitted the barrier
  before recv_timeout, so a full queue behind a stuck fsync could exceed the
  timeout or hang exit. Admission is now deadline-aware try_send (recovering the
  barrier job on Full) plus a remaining-time recv_timeout — total wall time is
  bounded by the timeout.

Dashboard:
- #1 (models.ts walkDirStats): readdirSync eagerly materialized the whole
  Dirent[] before the entry budget applied. Switched to incremental
  opendirSync/readSync so the budget bounds memory and time on a pathological
  high-fan-out directory; closeSync in finally.
- #2 (download.ts processJob): existsSync(finalDir) follows symlinks, so a
  dangling finalDir symlink bypassed the ownership preflight and triggered a
  full wasted download. Added a no-follow occupied() (lstatSync) used at the
  preflight and both publish-time ownership checks.
- #3 (api.ts handleSessionMetrics): the session_id = ? OR root_session_id = ?
  union resurrected an abandoned root turn (dropped from turns after a branch)
  as a fake delegated turn, inflating count/token totals. Narrowed to genuine
  children (root_session_id = ? AND session_id != ?); verified the child-trace
  discriminator against the metrics-trace writer.

Also de-flaked download.test.ts's mid-job-error case: staging cleanup runs in
the job finally, after the error event the test unblocks on, so it now waits
for eventual staging reclaim instead of racing that teardown.

Gate: cold_cache 37/0; typecheck 0; dashboard 191/191 (×2, race gone);
lint 0; clippy clean. NAPI signature unchanged — no build:native needed.

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
… iterative FD-bounded model walk

Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced
two Important edge-case defects in the two dashboard #15 fixes. Both verified
via control-flow analysis before fixing.

- A (models.ts isDownloaderOwned): the ownership marker was read with
  readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an
  external directory carrying a valid .mlx-download-complete.json was reported
  downloader-owned — slipping a foreign install past the no-follow occupancy
  preflight (a wasted overwrite, or a false "done" through the link). R15 #2
  hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL
  directory before reading the marker, so ANY symlink/non-directory (dangling OR
  live-into-a-marked-dir) is foreign at all three ownership call sites.

- B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a
  child while the parent Dir handle was still open, holding one fd per level; a
  deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child
  opendirSync, which was swallowed with truncated=false — a silent
  false-complete undercount. Rewrote the walk as an explicit worklist of
  directory paths: each handle is closeSync'd before any child is opened (at
  most one fd ever live), and opendirSync/readSync failures now set
  truncated=true (a lower bound) instead of a silent return. Budget, no-follow
  symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary
  are preserved.

Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native
(#4/#5) and api.ts (#3) unchanged.

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
covers_all_shards granted coverage on a basename match, so a marker listing
a shard under a subdir (or an absolute / dot-segment path) falsely covered a
distinct top-level shard of the same size, skipping its bytes on the cheap
path -> two different weights produced the same fingerprint -> cross-model KV
restore. Match only a single Normal path component equal to the shard name;
anything else falls through to the full digest.

Whole-branch review #3, Finding 3.

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
- publish() re-checks downloader ownership adjacent to the swap so an unowned
  checkpoint that races in after the first guard is refused, never deleted (F1)
- resolveRevision() requires an immutable 40-hex commit and fails closed
  instead of pinning the mutable "main" ref into the completion marker (F2)
- staging is job-private (.staging/<slug>@<rev>.<pid>.<uuid>) so a concurrent
  process can never write into another's just-published tree; resume is
  HF-cache-backed (F4)
- sweep orphaned *.backup-* at start: restore if the final dir is missing,
  else reap (F5)
- on verify failure, invalidate the HF cache pointer+blob before retrying so a
  pinned-revision retry actually re-fetches instead of recopying corrupt bytes
  (F13)

Whole-branch review #3, Findings 1, 2, 4, 5, 13.

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
…ence

- migrate parsed session entries (migrateSessionEntries) before topology
  validation and projection so legacy v1 sessions index instead of vanishing (F9)
- isValidSessionTopology is now a memoized single pass (amortized O(n)) and is
  exported (F10)
- session detail route validates topology before projecting, so a file mutated
  into a cycle surfaces a bounded error instead of hanging pi's parent walk (F6)
- db schema check is == SCHEMA_VERSION plus a column-signature probe, so a newer
  or drifted schema quarantines+rebuilds instead of failing at first insert (F8)
- Clear-all sends {all:true} to match the hardened DELETE /api/cache contract (F11)
- paged-config override mirrors native snake-first persist precedence, so a
  config with conflicting aliases no longer silently disables persistence (F12)

Whole-branch review #3, Findings 6, 8, 9, 10, 11, 12.

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
…ounded model walk, no-follow install preflight, genuine-child session metrics

Fix-delta review of the review-#14 fixes surfaced 5 edge-case tails (each a
refinement of an R14 fix, none a reverted/broken fix). All verified via
control-flow analysis before fixing.

Native (crates/mlx-paged-attn/src/cold_cache.rs):
- #5 honest drain durability: the writer discarded persist_block errors and
  acked the barrier unconditionally, so drain() reported success even when a
  covered block failed to persist. Barrier now carries SyncSender<bool>; the
  writer accumulates a per-window failure flag and acks !failed; drain returns
  true only on an Ok(true) ack.
- #4 whole-drain bounded by timeout: drain's blocking send admitted the barrier
  before recv_timeout, so a full queue behind a stuck fsync could exceed the
  timeout or hang exit. Admission is now deadline-aware try_send (recovering the
  barrier job on Full) plus a remaining-time recv_timeout — total wall time is
  bounded by the timeout.

Dashboard:
- #1 (models.ts walkDirStats): readdirSync eagerly materialized the whole
  Dirent[] before the entry budget applied. Switched to incremental
  opendirSync/readSync so the budget bounds memory and time on a pathological
  high-fan-out directory; closeSync in finally.
- #2 (download.ts processJob): existsSync(finalDir) follows symlinks, so a
  dangling finalDir symlink bypassed the ownership preflight and triggered a
  full wasted download. Added a no-follow occupied() (lstatSync) used at the
  preflight and both publish-time ownership checks.
- #3 (api.ts handleSessionMetrics): the session_id = ? OR root_session_id = ?
  union resurrected an abandoned root turn (dropped from turns after a branch)
  as a fake delegated turn, inflating count/token totals. Narrowed to genuine
  children (root_session_id = ? AND session_id != ?); verified the child-trace
  discriminator against the metrics-trace writer.

Also de-flaked download.test.ts's mid-job-error case: staging cleanup runs in
the job finally, after the error event the test unblocks on, so it now waits
for eventual staging reclaim instead of racing that teardown.

Gate: cold_cache 37/0; typecheck 0; dashboard 191/191 (×2, race gone);
lint 0; clippy clean. NAPI signature unchanged — no build:native needed.

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
… iterative FD-bounded model walk

Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced
two Important edge-case defects in the two dashboard #15 fixes. Both verified
via control-flow analysis before fixing.

- A (models.ts isDownloaderOwned): the ownership marker was read with
  readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an
  external directory carrying a valid .mlx-download-complete.json was reported
  downloader-owned — slipping a foreign install past the no-follow occupancy
  preflight (a wasted overwrite, or a false "done" through the link). R15 #2
  hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL
  directory before reading the marker, so ANY symlink/non-directory (dangling OR
  live-into-a-marked-dir) is foreign at all three ownership call sites.

- B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a
  child while the parent Dir handle was still open, holding one fd per level; a
  deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child
  opendirSync, which was swallowed with truncated=false — a silent
  false-complete undercount. Rewrote the walk as an explicit worklist of
  directory paths: each handle is closeSync'd before any child is opened (at
  most one fd ever live), and opendirSync/readSync failures now set
  truncated=true (a lower bound) instead of a silent return. Budget, no-follow
  symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary
  are preserved.

Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native
(#4/#5) and api.ts (#3) unchanged.

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
covers_all_shards granted coverage on a basename match, so a marker listing
a shard under a subdir (or an absolute / dot-segment path) falsely covered a
distinct top-level shard of the same size, skipping its bytes on the cheap
path -> two different weights produced the same fingerprint -> cross-model KV
restore. Match only a single Normal path component equal to the shard name;
anything else falls through to the full digest.

Whole-branch review #3, Finding 3.

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
- publish() re-checks downloader ownership adjacent to the swap so an unowned
  checkpoint that races in after the first guard is refused, never deleted (F1)
- resolveRevision() requires an immutable 40-hex commit and fails closed
  instead of pinning the mutable "main" ref into the completion marker (F2)
- staging is job-private (.staging/<slug>@<rev>.<pid>.<uuid>) so a concurrent
  process can never write into another's just-published tree; resume is
  HF-cache-backed (F4)
- sweep orphaned *.backup-* at start: restore if the final dir is missing,
  else reap (F5)
- on verify failure, invalidate the HF cache pointer+blob before retrying so a
  pinned-revision retry actually re-fetches instead of recopying corrupt bytes
  (F13)

Whole-branch review #3, Findings 1, 2, 4, 5, 13.

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
…ence

- migrate parsed session entries (migrateSessionEntries) before topology
  validation and projection so legacy v1 sessions index instead of vanishing (F9)
- isValidSessionTopology is now a memoized single pass (amortized O(n)) and is
  exported (F10)
- session detail route validates topology before projecting, so a file mutated
  into a cycle surfaces a bounded error instead of hanging pi's parent walk (F6)
- db schema check is == SCHEMA_VERSION plus a column-signature probe, so a newer
  or drifted schema quarantines+rebuilds instead of failing at first insert (F8)
- Clear-all sends {all:true} to match the hardened DELETE /api/cache contract (F11)
- paged-config override mirrors native snake-first persist precedence, so a
  config with conflicting aliases no longer silently disables persistence (F12)

Whole-branch review #3, Findings 6, 8, 9, 10, 11, 12.

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
…ounded model walk, no-follow install preflight, genuine-child session metrics

Fix-delta review of the review-#14 fixes surfaced 5 edge-case tails (each a
refinement of an R14 fix, none a reverted/broken fix). All verified via
control-flow analysis before fixing.

Native (crates/mlx-paged-attn/src/cold_cache.rs):
- #5 honest drain durability: the writer discarded persist_block errors and
  acked the barrier unconditionally, so drain() reported success even when a
  covered block failed to persist. Barrier now carries SyncSender<bool>; the
  writer accumulates a per-window failure flag and acks !failed; drain returns
  true only on an Ok(true) ack.
- #4 whole-drain bounded by timeout: drain's blocking send admitted the barrier
  before recv_timeout, so a full queue behind a stuck fsync could exceed the
  timeout or hang exit. Admission is now deadline-aware try_send (recovering the
  barrier job on Full) plus a remaining-time recv_timeout — total wall time is
  bounded by the timeout.

Dashboard:
- #1 (models.ts walkDirStats): readdirSync eagerly materialized the whole
  Dirent[] before the entry budget applied. Switched to incremental
  opendirSync/readSync so the budget bounds memory and time on a pathological
  high-fan-out directory; closeSync in finally.
- #2 (download.ts processJob): existsSync(finalDir) follows symlinks, so a
  dangling finalDir symlink bypassed the ownership preflight and triggered a
  full wasted download. Added a no-follow occupied() (lstatSync) used at the
  preflight and both publish-time ownership checks.
- #3 (api.ts handleSessionMetrics): the session_id = ? OR root_session_id = ?
  union resurrected an abandoned root turn (dropped from turns after a branch)
  as a fake delegated turn, inflating count/token totals. Narrowed to genuine
  children (root_session_id = ? AND session_id != ?); verified the child-trace
  discriminator against the metrics-trace writer.

Also de-flaked download.test.ts's mid-job-error case: staging cleanup runs in
the job finally, after the error event the test unblocks on, so it now waits
for eventual staging reclaim instead of racing that teardown.

Gate: cold_cache 37/0; typecheck 0; dashboard 191/191 (×2, race gone);
lint 0; clippy clean. NAPI signature unchanged — no build:native needed.

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
… iterative FD-bounded model walk

Fix-delta review of the review-#15 fixes confirmed #3/#4/#5 sound and surfaced
two Important edge-case defects in the two dashboard #15 fixes. Both verified
via control-flow analysis before fixing.

- A (models.ts isDownloaderOwned): the ownership marker was read with
  readFileSync, which FOLLOWS symlinks, so a live finalDir symlink into an
  external directory carrying a valid .mlx-download-complete.json was reported
  downloader-owned — slipping a foreign install past the no-follow occupancy
  preflight (a wasted overwrite, or a false "done" through the link). R15 #2
  hardened only the occupancy check. Now isDownloaderOwned lstat-gates on a REAL
  directory before reading the marker, so ANY symlink/non-directory (dangling OR
  live-into-a-marked-dir) is foreign at all three ownership call sites.

- B (models.ts walkDirStats): R15 #1's incremental opendirSync recursed into a
  child while the parent Dir handle was still open, holding one fd per level; a
  deep real-directory tree under a low RLIMIT_NOFILE hit EMFILE on a child
  opendirSync, which was swallowed with truncated=false — a silent
  false-complete undercount. Rewrote the walk as an explicit worklist of
  directory paths: each handle is closeSync'd before any child is opened (at
  most one fd ever live), and opendirSync/readSync failures now set
  truncated=true (a lower bound) instead of a silent return. Budget, no-follow
  symlink semantics, dev:ino cycle guard, and the exactly-maxEntries boundary
  are preserved.

Gate: typecheck 0; dashboard 198/198 (×2); lint 0. Dashboard-only — native
(#4/#5) and api.ts (#3) unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
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