Skip to content

feat(sft): add SFT trainer infrastructure - #5

Merged
Brooooooklyn merged 1 commit into
mainfrom
sft
Dec 22, 2025
Merged

Brooooooklyn merged 1 commit into
mainfrom
sft

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Dec 22, 2025 •

Copy link
Copy Markdown
Contributor
  • Add SFTConfig for training configuration
  • Add SFTDataset for chat-format dataset handling
  • Add SFTTrainer with training loop, checkpointing, logging
  • Extend cross-entropy loss with label smoothing and ignore_index
  • Add Qwen3 model sft_forward for training forward pass
  • Export SFT components from @mlx-node/trl
  • Add comprehensive tests for config and dataset

🤖 Generated with Claude Code


Note

Introduce end-to-end SFT training stack (Rust engine + TS trainer/dataset/config), fix cross-entropy ignore_index normalization and dtype-safe updates, adjust Qwen3 params export behavior, and add tests/examples.

  • Core (Rust):
    • SFT Module: Add sft/{loss,autograd,engine}.rs implementing cross-entropy SFT training with autograd, gradient accumulation/clipping, metrics, resume logic, and emergency checkpoint signaling.
    • Losses: Update Losses::cross_entropy to mask ignored labels and normalize by valid-token count; guard divide-by-zero (all-ignored => 0); keep label smoothing; resource cleanup.
    • Qwen3 Model: apply_gradients now preserves param dtype by casting LR; only expose lm_head.weight when tie_word_embeddings is false.
  • JS/TS Packages:
    • TRL: Add SFTTrainer (Rust-native loop wrapper), SFTDataset (prompt-completion & conversation formats with masking/truncation/shuffle), and SFT config utilities (defaults, TOML loader, CLI overrides). Export new SFT APIs from @mlx-node/trl.
    • Core bindings/typings: Export SftTrainingEngine and related types (SftEngineConfig, step/epoch metrics, ResumePosition).
    • Tests: New tests for extended losses, SFT config, and SFT dataset; update Qwen3 parameter access expectations.
  • Examples:
    • Improve language detection and completion wiring in GRPO examples; point tool-use training to SFT output model path.

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

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

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 infrastructure for Supervised Fine-Tuning (SFT), enabling training on fixed prompt-completion pairs using cross-entropy loss. The implementation includes both TypeScript and Rust components with a focus on performance and memory efficiency.

Key Changes

  • Rust-native SFT training engine with gradient accumulation, clipping, and NaN protection
  • TypeScript trainer with checkpoint management, TUI support, and training state resumption
  • Dataset handling supporting both prompt-completion and conversation formats with proper masking
  • Enhanced cross-entropy loss with correct normalization by valid token count only (fixes gradient scaling)

Reviewed changes

Copilot reviewed 19 out of 19 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
packages/trl/src/trainers/sft-trainer.ts Main SFT trainer with training loop, checkpointing, and TUI controls
packages/trl/src/trainers/sft-config.ts Configuration management with validation and TOML support
packages/trl/src/data/sft-dataset.ts Dataset handling for prompt-completion and conversation formats with tokenization
packages/trl/src/index.ts Export new SFT components for public API
crates/mlx-core/src/sft/mod.rs Rust module organization for SFT components
crates/mlx-core/src/sft/loss.rs SFT loss configuration
crates/mlx-core/src/sft/engine.rs Complete Rust training engine with gradient accumulation and NaN handling
crates/mlx-core/src/sft/autograd.rs Autograd-based loss and gradient computation
crates/mlx-core/src/nn/losses.rs Fixed cross-entropy normalization by valid token count (critical fix)
crates/mlx-core/src/models/qwen3/model.rs Added dtype preservation in gradient application and tie_word_embeddings support
crates/mlx-core/src/lib.rs Added SFT module to exports
packages/core/index.d.cts TypeScript definitions for SFT engine
packages/core/index.cjs Export SftTrainingEngine
test/trainers/sft-dataset.test.ts Comprehensive dataset tests
test/trainers/sft-config.test.ts Configuration validation tests
test/core/losses-extended.test.ts Updated cross-entropy tests for new normalization behavior
examples/test-converted-model.ts Updated model path reference
examples/grpo/train-tool-use.ts Enhanced language detection and updated default model path
examples/grpo/compare-models.ts Updated model path and language detection

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

Comment thread packages/trl/src/data/sft-dataset.ts Resolved
Comment thread __test__/trainers/sft-dataset.test.ts Resolved
Comment thread examples/grpo/compare-models.ts Resolved
Comment thread examples/grpo/compare-models.ts Resolved
Comment thread crates/mlx-core/src/sft/engine.rs Resolved
- Add SFTConfig for training configuration
- Add SFTDataset for chat-format dataset handling
- Add SFTTrainer with training loop, checkpointing, logging
- Extend cross-entropy loss with label smoothing and ignore_index
- Add Qwen3 model sft_forward for training forward pass
- Export SFT components from @mlx-node/trl
- Add comprehensive tests for config and dataset

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 05ee389 into main Dec 22, 2025
@Brooooooklyn
Brooooooklyn deleted the sft branch December 22, 2025 02:45
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
- Add SFTConfig for training configuration
- Add SFTDataset for chat-format dataset handling
- Add SFTTrainer with training loop, checkpointing, logging
- Extend cross-entropy loss with label smoothing and ignore_index
- Add Qwen3 model sft_forward for training forward pass
- Export SFT components from @mlx-node/trl
- Add comprehensive tests for config and dataset

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Introduce end-to-end SFT training stack (Rust engine + TS
trainer/dataset/config), fix cross-entropy ignore_index normalization
and dtype-safe updates, adjust Qwen3 params export behavior, and add
tests/examples.
> 
> - **Core (Rust)**:
> - **SFT Module**: Add `sft/{loss,autograd,engine}.rs` implementing
cross-entropy SFT training with autograd, gradient
accumulation/clipping, metrics, resume logic, and emergency checkpoint
signaling.
> - **Losses**: Update `Losses::cross_entropy` to mask ignored labels
and normalize by valid-token count; guard divide-by-zero (all-ignored =>
0); keep label smoothing; resource cleanup.
> - **Qwen3 Model**: `apply_gradients` now preserves param dtype by
casting LR; only expose `lm_head.weight` when `tie_word_embeddings` is
false.
> - **JS/TS Packages**:
> - **TRL**: Add `SFTTrainer` (Rust-native loop wrapper), `SFTDataset`
(prompt-completion & conversation formats with
masking/truncation/shuffle), and `SFT` config utilities (defaults, TOML
loader, CLI overrides). Export new SFT APIs from `@mlx-node/trl`.
> - **Core bindings/typings**: Export `SftTrainingEngine` and related
types (`SftEngineConfig`, step/epoch metrics, `ResumePosition`).
> - **Tests**: New tests for extended losses, SFT config, and SFT
dataset; update Qwen3 parameter access expectations.
> - **Examples**:
> - Improve language detection and completion wiring in GRPO examples;
point tool-use training to SFT output model path.
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
ce3dd3a. 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
The per-model lock added last round had two real protocol defects: a crash
between O_EXCL create and the pid write left an empty lock that wedged every
later download for up to the 24h stale threshold, and its read/check/unlink
steal was ABA-racy (two stealers could both enter the critical section). A
hand-rolled interprocess lock is error-prone and it guarded only the sweep's
backup restore/reap racing a concurrent same-model publisher. Delete lock.ts
and reuse the proven pid-liveness mechanism: the backup dir is now pid-tagged
(<final>.backup-<pid>.<uuid>) and the sweep skips a live owner's backup and
only restores/reaps a dead owner's. Concurrent same-model publish now resolves
to one atomic-rename winner with the loser erroring cleanly and self-healing on
retry (install = ensure-present) -- no data loss, at most a redundant download.

Also contain the verify-retry pointer unlink: canonicalize the pointer's parent
and skip invalidation if it escapes the cache root (defense-in-depth; the hub
always returns an in-cache pointer).

Whole-branch review #5, Findings A, B.

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
- schema validation ran PRAGMA table_info, which also returns columns for a
  view, so a DB whose `turns` object is a view with the expected columns passed
  validation and then wedged startup on CREATE INDEX ("views may not be
  indexed", not classified rebuildable). Assert type='table' via sqlite_schema
  before the column check -> quarantine+rebuild (F C)
- the paged-config override memo was keyed only by sourcePath, so resolving the
  same model with persistPagedCache true then false returned the first override;
  fold the persist tri-state + modelType into the key (latent today, every
  consumer uses an invariant directive, but a real correctness gap) (F D)
- --host 0.0.0.0 is documented, but the Host allowlist held the literal
  wildcard, which no browser sends, so every LAN request got 403. For a
  wildcard bind, build the allowlist from os.networkInterfaces() addresses,
  keeping DNS-rebinding protection (only real local IPs pass) (F E)

Whole-branch review #5, Findings C, D, E.

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
…se symlinked staging root

E (REGRESSION): cancellation was only checked inside the per-file fetch loop.
After it, prune + whole-set hashing (minutes on a 20+GB tree) + publish ran with
no cancellation check, so DELETE /api/downloads/:id returned 200 {cancelled}
(aborting a fetch that was no longer in flight) while the model still verified,
published, and marked done. Add a non-cancellable 'committing' job state (which
the existing cancel gate already 404s), cancellation checkpoints before prune,
at the top of the verify loop, and immediately before publish (atomic no-await
transition), plus a guard before the shared-HF-cache invalidation so a cancelled
job never mutates the shared cache. The existing catch/finally already reclassify
a pre-commit throw as a clean cancelled terminal and remove private staging.

#5: the .staging root was mkdir'd with no symlink rejection and the containment
check was purely lexical (resolve, not realpath), so a pre-existing .staging
symlink redirected writes and recursive cleanups to an external dir. Refuse a
symlinked/non-directory staging root (no-follow lstat) before mkdir, and validate
each write against the realpath-canonicalized staging dir.

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
The per-model lock added last round had two real protocol defects: a crash
between O_EXCL create and the pid write left an empty lock that wedged every
later download for up to the 24h stale threshold, and its read/check/unlink
steal was ABA-racy (two stealers could both enter the critical section). A
hand-rolled interprocess lock is error-prone and it guarded only the sweep's
backup restore/reap racing a concurrent same-model publisher. Delete lock.ts
and reuse the proven pid-liveness mechanism: the backup dir is now pid-tagged
(<final>.backup-<pid>.<uuid>) and the sweep skips a live owner's backup and
only restores/reaps a dead owner's. Concurrent same-model publish now resolves
to one atomic-rename winner with the loser erroring cleanly and self-healing on
retry (install = ensure-present) -- no data loss, at most a redundant download.

Also contain the verify-retry pointer unlink: canonicalize the pointer's parent
and skip invalidation if it escapes the cache root (defense-in-depth; the hub
always returns an in-cache pointer).

Whole-branch review #5, Findings A, B.

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
- schema validation ran PRAGMA table_info, which also returns columns for a
  view, so a DB whose `turns` object is a view with the expected columns passed
  validation and then wedged startup on CREATE INDEX ("views may not be
  indexed", not classified rebuildable). Assert type='table' via sqlite_schema
  before the column check -> quarantine+rebuild (F C)
- the paged-config override memo was keyed only by sourcePath, so resolving the
  same model with persistPagedCache true then false returned the first override;
  fold the persist tri-state + modelType into the key (latent today, every
  consumer uses an invariant directive, but a real correctness gap) (F D)
- --host 0.0.0.0 is documented, but the Host allowlist held the literal
  wildcard, which no browser sends, so every LAN request got 403. For a
  wildcard bind, build the allowlist from os.networkInterfaces() addresses,
  keeping DNS-rebinding protection (only real local IPs pass) (F E)

Whole-branch review #5, Findings C, D, E.

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
…se symlinked staging root

E (REGRESSION): cancellation was only checked inside the per-file fetch loop.
After it, prune + whole-set hashing (minutes on a 20+GB tree) + publish ran with
no cancellation check, so DELETE /api/downloads/:id returned 200 {cancelled}
(aborting a fetch that was no longer in flight) while the model still verified,
published, and marked done. Add a non-cancellable 'committing' job state (which
the existing cancel gate already 404s), cancellation checkpoints before prune,
at the top of the verify loop, and immediately before publish (atomic no-await
transition), plus a guard before the shared-HF-cache invalidation so a cancelled
job never mutates the shared cache. The existing catch/finally already reclassify
a pre-commit throw as a clean cancelled terminal and remove private staging.

#5: the .staging root was mkdir'd with no symlink rejection and the containment
check was purely lexical (resolve, not realpath), so a pre-existing .staging
symlink redirected writes and recursive cleanups to an external dir. Refuse a
symlinked/non-directory staging root (no-follow lstat) before mkdir, and validate
each write against the realpath-canonicalized staging dir.

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
The per-model lock added last round had two real protocol defects: a crash
between O_EXCL create and the pid write left an empty lock that wedged every
later download for up to the 24h stale threshold, and its read/check/unlink
steal was ABA-racy (two stealers could both enter the critical section). A
hand-rolled interprocess lock is error-prone and it guarded only the sweep's
backup restore/reap racing a concurrent same-model publisher. Delete lock.ts
and reuse the proven pid-liveness mechanism: the backup dir is now pid-tagged
(<final>.backup-<pid>.<uuid>) and the sweep skips a live owner's backup and
only restores/reaps a dead owner's. Concurrent same-model publish now resolves
to one atomic-rename winner with the loser erroring cleanly and self-healing on
retry (install = ensure-present) -- no data loss, at most a redundant download.

Also contain the verify-retry pointer unlink: canonicalize the pointer's parent
and skip invalidation if it escapes the cache root (defense-in-depth; the hub
always returns an in-cache pointer).

Whole-branch review #5, Findings A, B.

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
- schema validation ran PRAGMA table_info, which also returns columns for a
  view, so a DB whose `turns` object is a view with the expected columns passed
  validation and then wedged startup on CREATE INDEX ("views may not be
  indexed", not classified rebuildable). Assert type='table' via sqlite_schema
  before the column check -> quarantine+rebuild (F C)
- the paged-config override memo was keyed only by sourcePath, so resolving the
  same model with persistPagedCache true then false returned the first override;
  fold the persist tri-state + modelType into the key (latent today, every
  consumer uses an invariant directive, but a real correctness gap) (F D)
- --host 0.0.0.0 is documented, but the Host allowlist held the literal
  wildcard, which no browser sends, so every LAN request got 403. For a
  wildcard bind, build the allowlist from os.networkInterfaces() addresses,
  keeping DNS-rebinding protection (only real local IPs pass) (F E)

Whole-branch review #5, Findings C, D, E.

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
…se symlinked staging root

E (REGRESSION): cancellation was only checked inside the per-file fetch loop.
After it, prune + whole-set hashing (minutes on a 20+GB tree) + publish ran with
no cancellation check, so DELETE /api/downloads/:id returned 200 {cancelled}
(aborting a fetch that was no longer in flight) while the model still verified,
published, and marked done. Add a non-cancellable 'committing' job state (which
the existing cancel gate already 404s), cancellation checkpoints before prune,
at the top of the verify loop, and immediately before publish (atomic no-await
transition), plus a guard before the shared-HF-cache invalidation so a cancelled
job never mutates the shared cache. The existing catch/finally already reclassify
a pre-commit throw as a clean cancelled terminal and remove private staging.

#5: the .staging root was mkdir'd with no symlink rejection and the containment
check was purely lexical (resolve, not realpath), so a pre-existing .staging
symlink redirected writes and recursive cleanups to an external dir. Refuse a
symlinked/non-directory staging root (no-follow lstat) before mkdir, and validate
each write against the realpath-canonicalized staging dir.

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