Repository navigation
feat(grpo): refactor reward API, add Rust tests, improve tool-use training - #4
Merged
Merged
Conversation
Contributor
Author
|
cursor review |
Contributor
Author
|
cursor review |
There was a problem hiding this comment.
Pull request overview
This PR refactors the GRPO reward API to use a unified RewardOutput interface with pre-parsed tool calls and thinking content, adds 62 Rust tests for GRPO components, and improves tool-use training with an expanded curriculum dataset.
Key changes:
- Unified reward function signature from 3 parameters to a single
RewardOutput[]type - Pre-parsing of tool calls and thinking content in Rust for improved performance
- Comprehensive Rust test coverage (62 tests) for advantages, entropy, and loss computations
Reviewed changes
Copilot reviewed 31 out of 31 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/trl/src/types.ts | Exports new RewardOutput type and updates RewardFunction signature |
| packages/trl/src/trainers/grpo-trainer.ts | Refactored to use buildRewardOutputs and new unified API |
| packages/trl/src/rewards.ts | Updated all reward functions to use RewardOutput[] |
| packages/core/index.d.cts | Added type definitions for CompletionInfo, RewardOutput, TrainStepResult |
| crates/mlx-core/src/tools/mod.rs | Enhanced tool call parsing with new buildRewardOutputs function |
| crates/mlx-core/src/grpo/loss.rs | Added 25 comprehensive tests for GRPO loss variants |
| crates/mlx-core/src/grpo/entropy.rs | Added 21 tests for entropy filtering |
| crates/mlx-core/src/grpo/advantages.rs | Added 16 tests for advantage computation |
| examples/grpo/train-tool-use.ts | Improved with stronger system prompt and simplified reward function |
| examples/grpo/ast-grep-dataset.ts | New curriculum learning dataset with 50+ patterns |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Brooooooklyn
force-pushed
the
refactor-grpo
branch
2 times, most recently
from
December 20, 2025 04:09
2bff173 to
12a61e6
Compare
Contributor
Author
|
cursor review |
Brooooooklyn
force-pushed
the
refactor-grpo
branch
from
December 20, 2025 04:27
12a61e6 to
db62bb6
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 47 out of 47 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…ining - Unified reward API with RewardOutput containing pre-parsed tool calls - Added 62 Rust tests for GRPO components (advantages, entropy, loss) - Enhanced GRPO engine with batch processing and autograd support - Added compare-models script for A/B model evaluation - Improved TUI with better message handling and help display - Updated Qwen3 model with additional generation utilities 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <[email protected]>
Brooooooklyn
force-pushed
the
refactor-grpo
branch
from
December 20, 2025 04:53
db62bb6 to
d5f3ad3
Compare
Brooooooklyn
added a commit
that referenced
this pull request
Apr 11, 2026
…ining (#4) Reward API Refactoring: - Unified RewardOutput interface with pre-parsed toolCalls and thinking - Moved reward function types to centralized types.ts - Updated all reward functions to use new RewardOutput[] signature Rust Tests Added (62 total): - advantages.rs: 16 tests for advantage computation - entropy.rs: 21 tests for entropy filtering - loss.rs: 25 tests for GRPO loss variants TypeScript Tests: - Deleted grpo-entropy-filtering.test.ts (now covered by Rust) - Updated remaining tests to use new reward API Tool-Use Training Improvements: - Added ast-grep-dataset.ts with curriculum learning - Stronger system prompt requiring tool calls - Added concrete JSON format examples - Fixed floating point precision display in rewards Engine & Tools: - Enhanced tool call parsing in tools/mod.rs - Updated grpo-trainer.ts with improved reward handling - Added new type definitions 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Refactors GRPO to a structured RewardOutput-based API, adds a unified train_step_auto pipeline with tool-call parsing, expands Rust test coverage, and improves generation, engine, and TUI behavior. > > - **GRPO/Engine**: > - **Unified Reward API**: Switch reward functions to `RewardOutput[]` (pre-parsed `toolCalls`, `thinking`, token counts). > - **Unified Training**: Add `train_step_auto` (Rust) and `trainStepAuto` (TS) combining generation → reward → training; introduce `buildRewardOutputs` and `parseToolCallsFromText`. > - **Config**: Add `maxCompletionLengthForTraining`, `memoryCleanupThreshold`. > - **Tool-Use Training**: > - Add `examples/grpo/ast-grep-dataset.ts` (curriculum) and updated system prompt; simplify rewards using pre-parsed tool calls. > - **Core (mlx-core)**: > - **Numerics/Ops**: GPU-native `isnan/isinf/isfinite`; optimizer clipping now GPU-based; entropy mask computation moved to GPU. > - **Autograd/Loss**: Keep native bf16 params; truncate long completions; add extensive GRPO loss/advantage/entropy logic. > - **Generation**: Add repetition loop detection (`maxConsecutiveTokens`, n-gram) and new finish reason `"repetition"`. > - **TUI**: > - Auto-restart with countdown, status indicators, and controls. > - **Tests**: > - Add 62 Rust tests (`advantages`, `entropy`, `loss`); update TS tests to new API; remove redundant entropy TS test. > - **Packages/Types**: > - Update `@mlx-node/trl` types/exports to new API; expose new core helpers; adjust example trainers and config loader. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit d5f3ad3. 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]>
10 tasks done
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
Final correctness fix — parity gate now PASSES at T=0 on real
Qwen3.5 weights (qwen3.5-4b, byte-exact 640 chars).
## Root cause (validated by runtime instrumentation)
Qwen3.5 is hybrid-attention: most layers are gated-delta-net (GDN)
linear-attention with `conv_state` + `recurrent_state` that mutate
sequentially per `mlx_qwen35_forward_compiled` call. The W6 verify
FFI runs D+1 sequential forwards through `[last_committed, d_0,
.., d_{D-1}]`, advancing every linear layer's recurrent state by
D+1 token steps.
On rejection, `mlx_qwen35_compiled_adjust_offset(delta)` only
rewound `g_offset_int` — the GDN linear caches stayed in their
polluted state. Step A's next forward then read a stale recurrent
state and produced wrong logits even though the input token and
offset were correct.
W3 already added snapshot/restore for the eager Rust path
(`Qwen3_5LayerCache`); this fix extends the same design to the
compiled C++ path that production decode actually uses.
## Fix shape
4 new FFI exports (2 per model):
mlx_qwen35_compiled_snapshot_linear_caches()
mlx_qwen35_compiled_restore_linear_caches()
mlx_qwen35_moe_compiled_snapshot_linear_caches()
mlx_qwen35_moe_compiled_restore_linear_caches()
Snapshot captures only linear (GDN) layer K/V from
`g_compiled_caches` plus the offset; full-attention layers are
intentionally NOT snapshotted (slot-based K/V is overwritten on
next write, masked by the rolled-back offset).
`MtpOps` gains `snapshot_main_linear` and `restore_and_replay_main`
closures. The cycle now:
- snapshots before verify;
- on full-accept (K == D): discards snapshot (verify left
linear state correctly advanced through all D+1 emitted tokens);
- on non-full-accept (K < D or all-reject): restores snapshot,
then replays K+1 forwards through [last_committed, d_0..d_{K-1}]
to bring linear state to the AR-equivalent post-emission state.
The residual sample's K/V is laid down by the NEXT cycle's
Step A.
K+1 replay forwards on non-full-accept are a perf hit but the
correctness bar is met. Perf optimization is W6.5 (chained
cycles via verify-hidden export).
## Smoke result (qwen3.5-4b, depth=3, max-tokens=100, T=0)
AR | tokens=100 | TTFT=234ms | decode=7.92 tok/s
MTP | tokens=100 | TTFT=63ms | decode=2.37 tok/s
Parity: OK — AR and MTP produced identical 640-char output.
Speedup: 0.30x (perf is W6.5 territory; correctness is the bar).
## Tests
- 121 dense qwen3_5 unit tests pass.
- 22 MoE qwen3_5_moe unit tests pass.
- 4 mtp_cycle_tests updated for the new MtpOps closure shape.
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Brooooooklyn
added a commit
that referenced
this pull request
Jun 2, 2026
Replaces the W6 Bug #4 K+1 main-model forward replay path on every partial-accept verify cycle with a fused Metal kernel that records GDN innovations during verify and replays only the accepted prefix into the pre-verify snapshot state. Ported from DFlash's `_gated_delta_tape_kernel` + `_tape_replay_kernel` + `RecurrentRollbackCache.rollback()` orchestration. Dense path only this commit. MoE remains on the K+1 path (its compiled graph would need extra outputs to surface the per-step tapes — deferred). Qwen3.5-4b parity gate target is dense, so MoE doesn't block W6.6. Algorithm: 1. `mlx_qwen35_compiled_snapshot_linear_caches()` snapshots GDN conv_state + recurrent_state + main offset BEFORE verify (already existed from Bug #4 fix). 2. `mlx_qwen35_compiled_tape_arm()` (NEW) flips `g_tape_recording_armed` so `qwen35_decode_fn` routes GDN layers through `gdn_pure_fn_with_tape` and appends per-step `(tape, k, g, qkv)` into per-layer accumulators. 3. Verify runs D+1 sequential forwards; each accumulates one step. 4. On partial accept (K < D), `mlx_qwen35_compiled_tape_replay(K+1)` (NEW) slices the first K+1 entries from each accumulator and feeds them to the `tape_replay` Metal kernel, which applies the recorded innovations to the snapshot recurrent_state. Conv state is rebuilt by sliding window over `concat(snapshot_conv_state, qkv_recorded)` (mirrors DFlash `_rebuild_conv_state`). Offset is advanced to `snapshot_offset + (K+1)`. 5. On full accept, `mlx_qwen35_compiled_tape_disarm()` (NEW) drops accumulators without replay — verify already left the state correct. Files: NEW kernels (verbatim DFlash port, scalar-g non-masked variant): - crates/mlx-sys/src/metal/gated_delta_step_tape.metal.inc - crates/mlx-sys/src/metal/tape_replay.metal.inc NEW C++ helpers in mlx_qwen35_common.h: - gated_delta_kernel_with_tape_call (3-output kernel wrapper) - tape_replay_kernel_call - GDNPureResultWithTape struct + gdn_pure_fn_with_tape (forward that emits per-step k_tape, g_tape, qkv_tape alongside the standard output / conv_state / recurrent_state) NEW FFIs in mlx_qwen35.cpp: - mlx_qwen35_compiled_tape_arm / _tape_disarm / _tape_replay Modified: - qwen35_decode_fn routes GDN layers through the tape-emitting helper when armed and appends each step's per-layer tensors into globals - all 3 dense MTP cycle sites in qwen3_5/model.rs (B=1/standard, streaming, chained) wire arm-on-snapshot + replay-or-K+1 dispatch based on the env var Env var: MLX_MTP_USE_TAPE_REPLAY=1 (default ON) MLX_MTP_USE_TAPE_REPLAY=0 / "false" / "off" → falls back to the K+1 replay path for parity validation. Read once per process, cached. Strategy / stash: Prior partial attempt (stash@{0}) had the dense plumbing + both Metal kernel files already authored. Audited and applied as-is; the kernel ports match DFlash byte-for-byte (scalar-g, no-mask variant — the only variant our decode path uses). Build was unverified in the stash; this commit verifies build + clippy + fmt + cargo test + vp lint + vp test + parity gate. MoE work + env-var-removal cleanup deferred to a follow-up. Smoke results (qwen3.5-4b, depth=3, max-tokens=200, M3 Max bf16): Parity gate (BOTH modes pass byte-exact at T=0): - MLX_MTP_USE_TAPE_REPLAY=1 (default): OK, 1256 chars identical - MLX_MTP_USE_TAPE_REPLAY=0 (K+1): OK, 1256 chars identical Perf gate (3-run mean): - tape-replay ON: MTP=2.43 tok/s, ratio=~0.36x (AR avg 6.77 tok/s) - K+1 fallback: MTP=1.88 tok/s, ratio=~0.30x (AR avg 6.27 tok/s) +29% MTP improvement / +20% ratio improvement vs K+1 baseline. Below W6.6 1.8x plan gate. The 0.29→0.36x lift is consistent with the plan's ~30% rollback-budget estimate; the remaining gap to 1.8x is presumably from non-rollback bottlenecks (W6.7+ workstreams not in scope here). Reporting DONE_WITH_CONCERNS on perf. Bench environment: backupd was in FindingChanges during measurement (193k changed items pending) and /Volumes/PM9A1 spotlight indexing was still enabled. Multi-run variance is ±4% on AR baseline; relative ordering (tape ON > K+1) is consistent across all 3 runs per mode. Bug invariants preserved: - Bug #2 (mid-stream divergence): begin_cycle still re-anchors MTP offset every cycle, untouched. - Bug #4 (linear cache pollution): snapshot/restore primitives still work — tape-replay is an alternative consumer of the snapshot, not a replacement for it. Restore is preserved as the fallback path. Co-Authored-By: Claude Opus 4.7 <[email protected]>
5 tasks done
Brooooooklyn
added a commit
that referenced
this pull request
Jun 4, 2026
… fix paged prefill-tps telemetry Quantized lfm2_moe checkpoints carry `.scales` tensors, so they can never register with the compiled-PAGED C++ path; with `use_block_paged_cache` defaulting ON they fell onto the eager-PAGED loop (~12 `synchronize_mlx()`/token, blocking `y.eval()`, no async double-buffering) — ~1.84× slower than the eager-FLAT path (in-graph KVCache + `async_eval_arrays`) on the measured mxfp8 LFM2.5-8B-A1B (74 → 131 tok/s on M5 Max, closing most of the gap vs oMLX's 187). Fix #1: resolve the `use_block_paged_cache` default in `Lfm2Inner::load_from_dir`, keyed on the authoritative `.scales` tensor signal (the SAME signal that gates compiled registration, so the two can't diverge for a checkpoint whose quantization block lacks top-level bits/mode) — quantized + unset → flat; bf16 → paged (PR #66 compiled-PAGED unaffected); an explicit config.json value always wins. The server auto-routes via `has_block_paged_cache()`, so batched / cross-request reuse is unaffected (bf16 stays paged; quantized moves to the warm-slot path the server already supports). Single-stream only. Fix #4: the paged prefill-throughput telemetry divided ttft by the attention SUFFIX (`tokens.len() - cached_prefix_len`), but paged prefill reprocesses the FULL prompt through the conv layers, so ttft is full-prompt scale — this under-reported prefill tok/s by the cache-hit ratio (~37 vs thousands on warm content-addressed prefix reuse). Use the full prompt count at both paged call sites. Qwen3.5's identical expression is correct (no conv reprocessing) and is left untouched. Deferred (plan only): quantized compiled-PAGED decode (#2, for batched serving) and a cross-family paged-loop wired_limit (#3a, no-op for the flat default on a 128GB host). Tests: pure-helper policy unit test; a parse_config-does-not-resolve contract test; a compute_performance_metrics divider test; and two #[ignore] real-weights regressions (quantized default load → flat via has_block_paged_cache(); paged warm-reuse prefill-tps is full-prompt scale). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Brooooooklyn
added a commit
that referenced
this pull request
Jun 4, 2026
…ode (~2.34×) + prefill-tps telemetry fix (#67) ## Summary Closes most of the LFM2.5-8B-A1B quantized single-stream decode gap to oMLX by fixing the default decode path and extending the compiled C++ path to quantized weights. Two commits: - **`fb234575` — quantized → flat default (~1.84×) + paged prefill-tps telemetry fix** - **`46760077` — quantized compiled flat+paged decode (~2.34× paged over eager-paged)** ### #1 — quantized single-stream defaults to FLAT decode (~1.84×) Quantized `lfm2`/`lfm2_moe` was silently defaulting to the **eager-PAGED** loop (~12 `synchronize_mlx()`/token + blocking `y.eval()` + no async double-buffering), ~1.84× slower than FLAT on the measured mxfp8 8B-A1B (74 → 131 tok/s, M5 Max). The default is now keyed on the authoritative `.scales` tensor signal: quantized → FLAT, bf16 → PAGED (unchanged). Explicit `use_block_paged_cache` in `config.json` always wins. ### #4 — paged prefill-tps telemetry fix The paged path reported a bogus ~37 `prefillTokensPerSecond` (it divided full-prompt ttft by the attention *suffix* count on warm prefix-cache hits). Now uses the full-prompt count as the numerator; guarded by `lfm2_paged_prefill_tps_is_full_prompt_scale_on_warm_reuse`. ### #2 — quantized compiled flat+paged decode (~2.34× over eager-paged) Extends the compiled C++ decode path (previously bf16-only) to quantized `lfm2`/`lfm2_moe`. A per-projection quant-info registry (`mlx_store_quant_info`, keyed on each `.scales` prefix) makes the C++ `(mode, bits, group_size)` dispatch **authoritative** instead of the companion-tensor heuristic (which mislabels mxfp4/nvfp4 as mxfp8); the heuristic is retained only as a fallback. Compiled-PAGED is ~2.34× over eager-PAGED, rescuing the pinned-paged quant path (e.g. server/batched). A packed embedding (`embed_tokens.scales`) bars the compiled path (C++ does a dense `take`). Env escape hatch: `MLX_LFM2_DISABLE_QUANT_COMPILED`. ## Correctness Byte-identical to the pure-Rust eager path across **{mxfp8, 4-bit affine} × {flat, paged}**, proven via the model-id **eviction oracle** in `lfm2_compiled_e2e.rs` (`quant_compiled_vs_eager_parity`): loading the compiled model evicts the eager-ref's process-global weights, so the eager-ref runs the *independent* `QuantizedLinear`/`QuantizedSwitchLinear` modules — a C++ dispatch mislabel would diverge early. This is stronger than a same-graph `MLX_NO_COMPILE` reference. ## Perf context This is the **quantized** path — the relevant one for oMLX's 8-bit headline. Separately verified this session: for **bf16**, our decode (~110 tok/s) is at **exact op-for-op parity with mlx-lm** and is **memory-bandwidth-bound** (MoE gather already saturates ~404 GB/s at the k=4 decode shape, ~80% of the M5 Max ceiling); the residual bf16 gap to oMLX is host/measurement, not software. The real lever for absolute decode speed is reducing bytes-per-token (quantization) — which is exactly what these changes make fast. ## Test plan - [x] `cargo clippy --all-targets -- -D warnings` — clean - [x] `cargo fmt --check` — clean - [x] 30 unit tests pass (`cargo test -p mlx-core`, incl. the compiled-registration gate tests) - [x] Byte-identical parity matrix (mxfp8/4-bit × flat/paged) via the eviction oracle (opt-in: `LFM2_COMPILED_E2E=1` + `LFM2_QUANT_MODEL_PATH`) - [x] `yarn build:native` clean; no `index.d.cts` drift ## Review status The mandated `codex:adversarial-review` runtime **hung twice** mid quant-dispatch cross-reference (a codex-runtime issue, not a code signal). A thorough Claude-subagent adversarial review cleared it **SHIP / no blocking bug** — verifying dispatch parity for every projection class (MoE experts, router gate, dense-MLP, attention q/k/v/out, conv, untied lm_head) and ruling out the truncated codex concern on all three plausible completions (packed-embedding guard, registry-authoritative quant modes, pre-existing flat bf16 invariant). **Deferred follow-ups (non-blocking):** - [Medium] Synthetic non-gated quantized parity test (parity is currently operator-verified via `LFM2_COMPILED_E2E=1`; the synthetic harness only generates bf16 weights, and the completeness `debug_assert_eq!` is compiled out in release). - [Low] `mlx_store_weight` transposes packed 2D quant `.weight` into `g_weight_transposes` that's never read (pre-existing waste, surfaced not introduced). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes default decode routing and global compiled weight registration for quantized LFM2, where incorrect quant dispatch or gating would affect correctness and performance; mitigated by expanded unit tests and documented escape hatches. > > **Overview** > **LFM2 load and decode routing** now treat quantized checkpoints differently: when `use_block_paged_cache` is unset, presence of `.scales` tensors defaults to **flat** decode (instead of paged), with resolution moved from `parse_config` to `load_from_dir` so it matches the registration gate. Explicit `config.json` values still win. > > **Quantized models can use the compiled C++ path** (flat and paged): registration publishes per-projection quant info via `mlx_store_quant_info`, `should_register_compiled` and `paged_compiled_decode_setup` use `non_quant_floats_bf16` plus `MLX_LFM2_DISABLE_QUANT_COMPILED`, and packed `embed_tokens` blocks compiled registration because the C++ path does a dense embedding lookup. > > **Paged chat performance metrics** use the full prompt token count for prefill throughput (conv layers re-run the full prompt), fixing inflated TTFT/prefill-tps on warm prefix-cache hits. > > Most other diff hunks are **comment and docstring cleanup** (phase/W6/PR ticket references removed); behavior in convert, MTP, Qwen3, and banded-attention modules is unchanged aside from wording. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a4a760d. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[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 round-3 fixes guarded only the TS writer and used Path::components for
shard coverage. Two reader-side gaps remained: a legacy on-disk marker pinning
a mutable ref ("main") was still trusted on the cheap path (mutable identity ->
same-name/size different-weight collision), and Path::components normalizes
"model.safetensors/", "/.", "//" to one Normal component so crafted marker
entries still forged coverage. read_download_manifest now requires a 40-hex
revision (else None -> full digest), and covers_all_shards compares raw strings.
Whole-branch review #4, Findings 7a, 7b.
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
… lock - verify-failure retry realpaths the pointer before unlinking it and deletes the resolved blob only when contained under realpath(cacheDir); a server-controlled etag with ".." can no longer make the retry delete an unrelated same-user file (F4) - the startup sweep now reaps stale job-private staging trees by their embedded pid + liveness (process.kill(pid,0)); a SIGKILLed download no longer leaks a multi-GB tree forever (F3) - new lock.ts: advisory per-model O_EXCL interprocess lock (pid+mtime staleness, dead-holder steal, own-pid-only release) held across sweep->stage->verify-> publish; the backup restore/reap is slug-scoped so it can never reclaim a concurrent publisher's active backup (F1) - same-model dashboard downloads now serialize under the lock; the shared HF cache .incomplete race stays covered by the existing verify/retry backstop (F2) Whole-branch review #4, Findings 1, 2, 3, 4. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn
added a commit
that referenced
this pull request
Jul 28, 2026
- GET /api/sessions/:id used SessionManager.open, which (persist=true) rewrites the file with "w" on v1/v2 migration and drops malformed lines -- viewing a session could truncate its JSONL. The detail route now parses read-only via a shared readSessionEntries helper (readFileSync + in-memory migrate), identical to ingest, with no disk write (F5) - the schema signature probe ran AFTER CREATE TABLE IF NOT EXISTS, so a missing table was recreated empty and passed validation while watermark-gated re-ingest skipped it (silent metrics loss). Validation now runs on the untouched pre-existing DB BEFORE any DDL, checks every table's full column set (derived from schema.ts), and quarantines+rebuilds on any drift (F6) Whole-branch review #4, Findings 5, 6. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn
added a commit
that referenced
this pull request
Jul 28, 2026
MetricsTrace stamped the mutable current root when a turn finished. A subagent turn that survives a /new or /resume completes on the same stream after the root changed, so its record was attributed to the new session -- and since subagent traces have no session JSONL, root_session_id is their only join key, so the turn vanished from the original session. The root id+file are now snapshotted at request submit (mirroring the existing rootCacheOwnerId snapshot) and threaded through TurnRecorder -> onTurnRecord -> record(). Whole-branch review #4, Finding 8. 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 round-3 fixes guarded only the TS writer and used Path::components for
shard coverage. Two reader-side gaps remained: a legacy on-disk marker pinning
a mutable ref ("main") was still trusted on the cheap path (mutable identity ->
same-name/size different-weight collision), and Path::components normalizes
"model.safetensors/", "/.", "//" to one Normal component so crafted marker
entries still forged coverage. read_download_manifest now requires a 40-hex
revision (else None -> full digest), and covers_all_shards compares raw strings.
Whole-branch review #4, Findings 7a, 7b.
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
… lock - verify-failure retry realpaths the pointer before unlinking it and deletes the resolved blob only when contained under realpath(cacheDir); a server-controlled etag with ".." can no longer make the retry delete an unrelated same-user file (F4) - the startup sweep now reaps stale job-private staging trees by their embedded pid + liveness (process.kill(pid,0)); a SIGKILLed download no longer leaks a multi-GB tree forever (F3) - new lock.ts: advisory per-model O_EXCL interprocess lock (pid+mtime staleness, dead-holder steal, own-pid-only release) held across sweep->stage->verify-> publish; the backup restore/reap is slug-scoped so it can never reclaim a concurrent publisher's active backup (F1) - same-model dashboard downloads now serialize under the lock; the shared HF cache .incomplete race stays covered by the existing verify/retry backstop (F2) Whole-branch review #4, Findings 1, 2, 3, 4. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn
added a commit
that referenced
this pull request
Jul 28, 2026
- GET /api/sessions/:id used SessionManager.open, which (persist=true) rewrites the file with "w" on v1/v2 migration and drops malformed lines -- viewing a session could truncate its JSONL. The detail route now parses read-only via a shared readSessionEntries helper (readFileSync + in-memory migrate), identical to ingest, with no disk write (F5) - the schema signature probe ran AFTER CREATE TABLE IF NOT EXISTS, so a missing table was recreated empty and passed validation while watermark-gated re-ingest skipped it (silent metrics loss). Validation now runs on the untouched pre-existing DB BEFORE any DDL, checks every table's full column set (derived from schema.ts), and quarantines+rebuilds on any drift (F6) Whole-branch review #4, Findings 5, 6. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn
added a commit
that referenced
this pull request
Jul 28, 2026
MetricsTrace stamped the mutable current root when a turn finished. A subagent turn that survives a /new or /resume completes on the same stream after the root changed, so its record was attributed to the new session -- and since subagent traces have no session JSONL, root_session_id is their only join key, so the turn vanished from the original session. The root id+file are now snapshotted at request submit (mirroring the existing rootCacheOwnerId snapshot) and threaded through TurnRecorder -> onTurnRecord -> record(). Whole-branch review #4, Finding 8. 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 round-3 fixes guarded only the TS writer and used Path::components for
shard coverage. Two reader-side gaps remained: a legacy on-disk marker pinning
a mutable ref ("main") was still trusted on the cheap path (mutable identity ->
same-name/size different-weight collision), and Path::components normalizes
"model.safetensors/", "/.", "//" to one Normal component so crafted marker
entries still forged coverage. read_download_manifest now requires a 40-hex
revision (else None -> full digest), and covers_all_shards compares raw strings.
Whole-branch review #4, Findings 7a, 7b.
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
… lock - verify-failure retry realpaths the pointer before unlinking it and deletes the resolved blob only when contained under realpath(cacheDir); a server-controlled etag with ".." can no longer make the retry delete an unrelated same-user file (F4) - the startup sweep now reaps stale job-private staging trees by their embedded pid + liveness (process.kill(pid,0)); a SIGKILLed download no longer leaks a multi-GB tree forever (F3) - new lock.ts: advisory per-model O_EXCL interprocess lock (pid+mtime staleness, dead-holder steal, own-pid-only release) held across sweep->stage->verify-> publish; the backup restore/reap is slug-scoped so it can never reclaim a concurrent publisher's active backup (F1) - same-model dashboard downloads now serialize under the lock; the shared HF cache .incomplete race stays covered by the existing verify/retry backstop (F2) Whole-branch review #4, Findings 1, 2, 3, 4. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn
added a commit
that referenced
this pull request
Jul 28, 2026
- GET /api/sessions/:id used SessionManager.open, which (persist=true) rewrites the file with "w" on v1/v2 migration and drops malformed lines -- viewing a session could truncate its JSONL. The detail route now parses read-only via a shared readSessionEntries helper (readFileSync + in-memory migrate), identical to ingest, with no disk write (F5) - the schema signature probe ran AFTER CREATE TABLE IF NOT EXISTS, so a missing table was recreated empty and passed validation while watermark-gated re-ingest skipped it (silent metrics loss). Validation now runs on the untouched pre-existing DB BEFORE any DDL, checks every table's full column set (derived from schema.ts), and quarantines+rebuilds on any drift (F6) Whole-branch review #4, Findings 5, 6. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn
added a commit
that referenced
this pull request
Jul 28, 2026
MetricsTrace stamped the mutable current root when a turn finished. A subagent turn that survives a /new or /resume completes on the same stream after the root changed, so its record was attributed to the new session -- and since subagent traces have no session JSONL, root_session_id is their only join key, so the turn vanished from the original session. The root id+file are now snapshotted at request submit (mirroring the existing rootCacheOwnerId snapshot) and threaded through TurnRecorder -> onTurnRecord -> record(). Whole-branch review #4, Finding 8. 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
Aug 17, 2026
…ction + TS mock Reviewer findings #4-#7 and the 'yarn test' CI failure, each verified against the engine conventions before applying: - model.rs run_mtp_whole_turn: union the checkpoint's extra_eos_ids (2, 11) into the MTP turn params (engine contract: the executor populates ChatParams::extra_eos_ids — engine/params.rs:115), so MTP turns stop on the alternate terminators like the paged executor. - model.rs: seed the MTP penalty history with the FULL rendered prompt (tokens.clone()) instead of cached_token_history (empty on fresh turns), matching the flat/paged executors and the decode.rs penalty contract. - model.rs: initialize the MTP finish_reason to "length" (matches paged_turn.rs:233); run_mtp_turn overrides it on a real EOS stop. Runtime-verified: a budget-exhausted MTP run reports finish="length". - convert.ts: auto-detect architecture-only Nemotron checkpoints (architectures: ['NemotronHForCausalLM']) and canonicalize to the nemotron_h ingest recipe, mirroring model-loader.ts and the native parser's authoritative-architecture policy. - packages/lm/__test__/stream-template-policy.test.ts: add NemotronHModel to the @mlx-node/core vi.mock (the new wrapper export) — fixes the CI 'yarn build:ts && yarn test' failure. Verified: cargo clippy --all-targets -D warnings clean; nemotron suite 37/37 (incl. real_mtp_t0_lossless_gate); yarn test 177 files passed / 2 environment-dependent failures (gemma4 audio continuation + agent provider-live — reproduced on base by reverting the shared tokenizer change; pass on main's CI; no PR code touches either path).
Brooooooklyn
added a commit
that referenced
this pull request
Aug 19, 2026
…ction + TS mock Reviewer findings #4-#7 and the 'yarn test' CI failure, each verified against the engine conventions before applying: - model.rs run_mtp_whole_turn: union the checkpoint's extra_eos_ids (2, 11) into the MTP turn params (engine contract: the executor populates ChatParams::extra_eos_ids — engine/params.rs:115), so MTP turns stop on the alternate terminators like the paged executor. - model.rs: seed the MTP penalty history with the FULL rendered prompt (tokens.clone()) instead of cached_token_history (empty on fresh turns), matching the flat/paged executors and the decode.rs penalty contract. - model.rs: initialize the MTP finish_reason to "length" (matches paged_turn.rs:233); run_mtp_turn overrides it on a real EOS stop. Runtime-verified: a budget-exhausted MTP run reports finish="length". - convert.ts: auto-detect architecture-only Nemotron checkpoints (architectures: ['NemotronHForCausalLM']) and canonicalize to the nemotron_h ingest recipe, mirroring model-loader.ts and the native parser's authoritative-architecture policy. - packages/lm/__test__/stream-template-policy.test.ts: add NemotronHModel to the @mlx-node/core vi.mock (the new wrapper export) — fixes the CI 'yarn build:ts && yarn test' failure. Verified: cargo clippy --all-targets -D warnings clean; nemotron suite 37/37 (incl. real_mtp_t0_lossless_gate); yarn test 177 files passed / 2 environment-dependent failures (gemma4 audio continuation + agent provider-live — reproduced on base by reverting the shared tokenizer change; pass on main's CI; no PR code touches either path).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reward API Refactoring:
Rust Tests Added (62 total):
TypeScript Tests:
Tool-Use Training Improvements:
Engine & Tools:
🤖 Generated with Claude Code
Note
Refactors GRPO to a structured RewardOutput-based API, adds a unified train_step_auto pipeline with tool-call parsing, expands Rust test coverage, and improves generation, engine, and TUI behavior.
RewardOutput[](pre-parsedtoolCalls,thinking, token counts).train_step_auto(Rust) andtrainStepAuto(TS) combining generation → reward → training; introducebuildRewardOutputsandparseToolCallsFromText.maxCompletionLengthForTraining,memoryCleanupThreshold.examples/grpo/ast-grep-dataset.ts(curriculum) and updated system prompt; simplify rewards using pre-parsed tool calls.isnan/isinf/isfinite; optimizer clipping now GPU-based; entropy mask computation moved to GPU.maxConsecutiveTokens, n-gram) and new finish reason"repetition".advantages,entropy,loss); update TS tests to new API; remove redundant entropy TS test.@mlx-node/trltypes/exports to new API; expose new core helpers; adjust example trainers and config loader.Written by Cursor Bugbot for commit d5f3ad3. This will update automatically on new commits. Configure here.