Skip to content

feat(output-store): add training output persistence with libsql - #9

Merged
Brooooooklyn merged 1 commit into
mainfrom
fix/output-store-polish
Dec 29, 2025
Merged

Brooooooklyn merged 1 commit into
mainfrom
fix/output-store-polish

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor

Add OutputStore for recording training outputs to SQLite (local) or Turso (remote).

Features:

  • Record training steps with generations, tool calls, and metrics
  • Query by step range, reward thresholds, tool usage patterns
  • Embedded replica mode for local cache + remote sync
  • Automatic run tracking with model/config metadata

Fixes from review:

  • Add transaction wrapper in record_step for atomicity
  • Add #[serde(default)] for raw_content backward compatibility
  • Fix lazy init race with promise mutex pattern
  • Fix toolCalls snake_case → camelCase conversion
  • Fix status type narrowing (ok|invalid_json|missing_name)
  • Ensure outputDir exists before DB open in lazy init

🤖 Generated with Claude Code

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


Note

Adds a persistent output store and wires it into training for recording and analysis.

  • New mlx-core/output_store module (schema, reader, writer, NAPI OutputStore) with local/remote/embedded-replica support via libsql; queries for runs/steps/generations/tool-calls/reward stats; JSONL export
  • Engine: new train_step_auto_with_recording returning optional outputs_json for zero-copy persistence; ToolCallResult/CompletionInfo/RewardOutput now deserializable and include raw_content (with #[serde(default)]); parser preserves raw tool-call content
  • Trainer: integrates OutputStore (lazy init with promise mutex, start/end run, recordStepFromOutputs, optional cloud sync); new outputStore config block
  • Tests: extensive OutputStore lifecycle/query/edge-case tests; chat/tool tests updated for rawContent
  • Packaging: export OutputStore and types in packages/core, add workspace libsql dep and dev oxc-parser

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

Summary by CodeRabbit

  • New Features
    • Output Store: persistent storage for training runs (local, remote, embedded replica) with start/end/run lifecycle, recording, search, filtering, export, and reward stats.
    • Optional training-step recording that can capture full reward outputs alongside extended training results.
    • Tool-call tracking now preserves raw tool-call content for improved debugging and analysis.
  • Tests
    • Added end-to-end tests covering Output Store lifecycle, recording, querying, search, and edge cases.
  • Chores
    • Dependency and public export updates to enable the new persistence surface.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings December 29, 2025 12:55
@coderabbitai

coderabbitai Bot commented Dec 29, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Adds a persistent OutputStore backed by libsql, a recording-aware training step API (train_step_auto_with_recording / trainStepAutoWithRecording) that can serialize RewardOutput, extends tool-call types with raw_content, and integrates OutputStore lifecycle into the GRPO trainer.

Changes

Cohort / File(s) Summary
Dependency Management
Cargo.toml, crates/mlx-core/Cargo.toml, package.json
Added workspace dependency libsql = { version = "0.9", features = ["replication"] }; added oxc-parser@^0.105.0 to package.json.
Output Store Core
crates/mlx-core/src/output_store/mod.rs, .../schema.rs, .../types.rs, .../store.rs
New output_store module: schema constant and initializer, NAPI-exported types (OutputStoreConfig, TrainingRunRecord, StepRecord, GenerationRecord, ToolCallRecord, RewardStats, StepSummary, etc.), and public OutputStore struct with factory constructors (local, remote, embedded_replica, from_config) and lifecycle/query methods.
Reader / Query Surface
crates/mlx-core/src/output_store/reader.rs
New async reader APIs for listing runs, retrieving runs/step summaries/generations, searching, reward statistics, JSONL export, and raw SQL querying; assembles GenerationWithToolCalls and reward stats.
Writer / Persistence
crates/mlx-core/src/output_store/writer.rs
Transactional write APIs: record_step and record_step_from_outputs, parse RewardOutput JSON, insert training_steps, generations, and tool_calls atomically.
GRPO Engine (recording path)
crates/mlx-core/src/grpo/engine.rs
Added TrainStepResultWithOutputs and train_step_auto_with_recording to optionally serialize RewardOutput to JSON and return outputs_json alongside metrics/completions/rewards.
Tools / Parsing
crates/mlx-core/src/tools/mod.rs
ToolCallResult now includes raw_content: String; parsers updated to capture and propagate raw_content; CompletionInfo and RewardOutput derive Deserialize.
Crate Exports
crates/mlx-core/src/lib.rs
Added pub mod output_store and re-exports from the new module.
TypeScript API Surface & Exports
packages/core/index.cjs, packages/core/index.d.cts
Exported OutputStore from native binding; added TypeScript declarations for OutputStore, OutputStoreConfig, GenerationRecord, GenerationWithToolCalls, StepRecord, StepSummary, TrainingRunRecord, ToolCallRecord, TrainStepResultWithOutputs, RewardStats, and trainStepAutoWithRecording.
GRPO Trainer Integration
packages/trl/src/trainers/grpo-trainer.ts
Added optional outputStore config to GRPOTrainerConfig; lazy-initialized OutputStore, getOutputStore() accessor; switched to trainStepAutoWithRecording when enabled and persist step outputs via recordStepFromOutputs; end-run/flush lifecycle handling.
Tests
__test__/models/qwen3-chat.test.ts, __test__/tools/chat.test.ts, __test__/trainers/output-store.test.ts
Tests updated to include rawContent in ToolCallResult mocks; comprehensive output-store.test.ts suite added validating local SQLite flows, recording, querying, searches, tool-calls, and edge cases.

Sequence Diagram(s)

sequenceDiagram
    participant App as Trainer (JS/TS)
    participant Engine as GRPO Engine (native)
    participant Store as OutputStore (native)
    participant DB as libsql Database
    participant Reader as Reader Module

    App->>Store: embedded_replica(...) / local(...)
    Store->>DB: open connection
    Store->>DB: init_schema (CREATE_TABLES_SQL)
    DB-->>Store: OK

    App->>Store: start_run(modelName,...)
    Store->>DB: INSERT training_runs
    DB-->>Store: run_id
    Store-->>App: run_id

    loop per training step
        App->>Engine: train_step_auto_with_recording(prompts, answers, rewardFn, record_outputs=true)
        Engine->>Engine: generate completions & build RewardOutput
        Engine->>Engine: call reward_fn -> rewards
        Engine->>Engine: serialize outputs_json (if record_outputs)
        Engine-->>App: TrainStepResultWithOutputs(metrics, completions, rewards, outputs_json)

        alt OutputStore enabled
            App->>Store: record_step_from_outputs(run_id, step, metrics, outputs_json, rewards, group_size)
            Store->>DB: BEGIN TRANSACTION
            Store->>DB: INSERT training_steps -> step_id
            Store->>DB: INSERT generations -> gen_ids
            Store->>DB: INSERT tool_calls
            Store->>DB: COMMIT
            DB-->>Store: OK
            Store-->>App: step_id
        end
    end

    App->>Store: get_generations / get_reward_stats / search_generations
    Store->>Reader: query helpers
    Reader->>DB: SELECT ... JOIN tool_calls ...
    DB-->>Reader: rows
    Reader-->>Store: parsed GenerationWithToolCalls
    Store-->>App: results

    App->>Store: end_run(status) / flush()
    Store->>DB: UPDATE training_runs / sync
    DB-->>Store: OK
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hopped through code and found the key,

libsql stores each victory,
raw content saved from every call,
rewards and runs preserved for all.
A little hop — persistence, done — hooray!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the main change: adding a training output persistence layer using libsql, which is the central feature of this comprehensive changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/output-store-polish

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor Author

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

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (11)
crates/mlx-core/src/output_store/writer.rs (2)

236-241: Consider handling potential panic in timestamp generation.

While extremely rare, duration_since(UNIX_EPOCH) can fail if the system clock is set before 1970. Using unwrap_or_default() or returning a fallback would make this more robust.

🔎 Defensive alternative
 fn chrono_now_ms() -> i64 {
     std::time::SystemTime::now()
         .duration_since(std::time::UNIX_EPOCH)
-        .unwrap()
+        .unwrap_or_default()
         .as_millis() as i64
 }

224-224: unwrap_or_default() silently discards serialization errors.

If serde_json::to_string fails for tool call arguments, an empty string is stored. Consider logging or propagating this error, or at minimum using unwrap_or_else to include an error indicator.

🔎 Alternative with error visibility
-                arguments: Some(serde_json::to_string(&tc.arguments).unwrap_or_default()),
+                arguments: Some(
+                    serde_json::to_string(&tc.arguments)
+                        .unwrap_or_else(|e| format!("{{\"_serialization_error\": \"{}\"}}", e))
+                ),
crates/mlx-core/src/output_store/reader.rs (2)

540-542: Percentile calculation uses integer division.

For small datasets, rewards[n / 4] may not give accurate quartiles. For example, with 3 elements, n/4 = 0 gives p25=rewards[0]. This is a reasonable approximation but may differ from statistical definitions.

For more accurate percentiles, consider linear interpolation:

let idx_25 = (n - 1) as f64 * 0.25;
let p25 = if n > 0 {
    let low = idx_25.floor() as usize;
    let high = idx_25.ceil() as usize;
    if low == high { rewards[low] }
    else { rewards[low] * (1.0 - idx_25.fract()) + rewards[high] * idx_25.fract() }
} else { 0.0 };

198-202: N+1 query pattern when fetching tool calls.

Each generation triggers a separate query via get_tool_calls_for_generation. For large result sets, this creates many database round-trips.

Consider batch-fetching tool calls for all generation IDs in a single query:

// After collecting all gen_ids
let tool_calls_map = get_tool_calls_for_generations(conn, &gen_ids).await?;
// Then map results

Also applies to: 252-257, 285-290, 332-336, 398-402, 452-456, 609-609

crates/mlx-core/src/output_store/schema.rs (1)

8-100: Schema initialization is sound; consider slightly more robust execution & tests

The DDL and init_schema loop look correct for the current static SQL, and comment-stripping plus trim().is_empty() guards avoid executing blank fragments. Two minor, non-blocking suggestions:

  • To reduce future brittleness if statements ever contain ; inside string literals, consider switching to a more structured splitter (e.g., a small parser or execute_batch-style helper) instead of a raw split(';').
  • The unit test only asserts that key CREATE TABLE / CREATE INDEX substrings exist. A lightweight in-memory test that actually calls init_schema on a temporary connection would give earlier feedback if the SQL becomes syntactically invalid.
crates/mlx-core/src/output_store/mod.rs (1)

1-47: Well-structured OutputStore module and re-exports

The module-level docs, internal submodules, and pub use of OutputStore plus types::* form a clear public surface; this is a good central entry point. Just ensure the TypeScript example stays updated if method signatures change in the future.

__test__/trainers/output-store.test.ts (1)

7-513: Comprehensive OutputStore tests; minor optional improvement for temp DB naming

The suite does a good job exercising lifecycle, recording, query, edge-case binding, and validation paths for OutputStore.local, which should catch most regressions.

If you expect highly parallel test runs across processes, you might consider adding a small random suffix (e.g., crypto.randomUUID() or a counter) to output-store-test-${Date.now()}.db to eliminate the tiny chance of name collisions, but this is optional given current usage.

crates/mlx-core/src/grpo/engine.rs (1)

1882-2443: train_step_auto_with_recording logic mirrors train_step_auto; consider deduplication

The new method correctly:

  • Reuses the same generation path and IntermediateGenerationResult struct as train_step_auto.
  • Builds RewardOutput[] via build_reward_outputs, serializes to JSON once, and conditionally retains a copy when record_outputs is true.
  • Applies the same degenerate-output filtering (length-based, per-completion) with consistent handling of valid_indices, effective_group_size, and usable_count.
  • Reuses the existing autograd training pipeline, NaN/Inf gradient checks, accumulation, cleanup, and state updates, just wrapping the result in TrainStepResultWithOutputs.

Functionally this looks solid; the main concern is the amount of duplicated logic between train_step_auto and train_step_auto_with_recording, which will be easy to get out of sync over time. When convenient, consider extracting shared helpers for:

  • The generation + IntermediateGenerationResult construction.
  • The degenerate filtering / index-selection logic.
  • The core autograd training step.

This would keep both paths aligned and simplify future fixes.

packages/trl/src/trainers/grpo-trainer.ts (1)

807-949: OutputStore integration into trainStepAuto and train() looks correct; consider stronger run-finalization guarantees

The training integration changes are coherent:

  • trainStepAuto now:

    • Lazily initializes the output store via ensureOutputStoreInitialized() for low-level users.
    • Chooses trainStepAutoWithRecording and passes recordOutputs = !!this.outputStore, so recording only happens when an store exists.
    • On success, conditionally calls recordStepFromOutputs with currentStep, metrics, full outputs JSON, rewards, and configured groupSize, while swallowing recording failures so training is not impacted.
  • train():

    • Eagerly initializes the store at the start of a run.
    • After the training loop and checkpointing, ends the run with status 'completed' or 'stopped' and calls flush().

The only potential improvement (optional) would be to wrap the main body of train() in a try/finally so that, if an exception is thrown mid-run, you still attempt endRun('failed')/flush() when an output store is active. That would make run metadata and on-disk state more robust in the face of unexpected errors.

Also applies to: 978-1114

crates/mlx-core/src/output_store/store.rs (2)

439-444: Document security implications of raw SQL execution.

This method accepts arbitrary SQL and could be used for writes or destructive operations. While documented as "for advanced users," consider:

  1. Adding a comment warning about SQL injection risks if user input is passed
  2. Optionally restricting to read-only queries (e.g., prefix check for SELECT)

Is this API intended only for trusted internal use, or could it receive user-provided SQL strings?


213-232: Consider wrapping both updates in a transaction for atomicity.

The two UPDATE statements execute separately on the same run record. If the second update fails, the run would have ended_at and status set but an incorrect total_steps value. Wrap both operations in a transaction, following the pattern already established in record_step:

let tx = conn.transaction().await.map_err(|e| {
    Error::new(Status::GenericFailure, format!("Failed to begin transaction: {}", e))
})?;

tx.execute(
    "UPDATE training_runs SET ended_at = ?1, status = ?2 WHERE id = ?3",
    libsql::params![ended_at, status, run_id.clone()],
)
.await
.map_err(|e| {
    Error::new(
        Status::GenericFailure,
        format!("Failed to update run: {}", e),
    )
})?;

tx.execute(
    "UPDATE training_runs SET total_steps = (SELECT COUNT(*) FROM training_steps WHERE run_id = ?1) WHERE id = ?1",
    libsql::params![run_id],
)
.await
.map_err(|e| Error::new(Status::GenericFailure, format!("Failed to update step count: {}", e)))?;

tx.commit().await.map_err(|e| {
    Error::new(Status::GenericFailure, format!("Failed to commit transaction: {}", e))
})?;
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a6b8db and d0fe9e8.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (18)
  • Cargo.toml
  • __test__/models/qwen3-chat.test.ts
  • __test__/tools/chat.test.ts
  • __test__/trainers/output-store.test.ts
  • crates/mlx-core/Cargo.toml
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/output_store/reader.rs
  • crates/mlx-core/src/output_store/schema.rs
  • crates/mlx-core/src/output_store/store.rs
  • crates/mlx-core/src/output_store/types.rs
  • crates/mlx-core/src/output_store/writer.rs
  • crates/mlx-core/src/tools/mod.rs
  • package.json
  • packages/core/index.cjs
  • packages/core/index.d.cts
  • packages/trl/src/trainers/grpo-trainer.ts
🧰 Additional context used
📓 Path-based instructions (6)
crates/mlx-core/src/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Files:

  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/writer.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/tools/mod.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/output_store/schema.rs
  • crates/mlx-core/src/output_store/reader.rs
  • crates/mlx-core/src/output_store/types.rs
  • crates/mlx-core/src/output_store/store.rs
**/__test__/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

In TypeScript test files, use Vitest framework with TypedArray creation helpers and appropriate tolerance values for floating-point comparisons

Files:

  • __test__/tools/chat.test.ts
  • __test__/models/qwen3-chat.test.ts
  • __test__/trainers/output-store.test.ts
crates/mlx-core/src/grpo/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

GRPO training components (loss, advantages, entropy filtering) must include comprehensive Rust test suites (minimum 10+ tests per component)

Files:

  • crates/mlx-core/src/grpo/engine.rs
packages/{core,lm,trl}/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Use TypedArrays (Float32Array, Int32Array, BigInt64Array) for all data and shape handling in APIs

Files:

  • packages/trl/src/trainers/grpo-trainer.ts
packages/trl/src/trainers/grpo-trainer.ts

📄 CodeRabbit inference engine (CLAUDE.md)

In GRPOTrainer TypeScript implementation, use unified RewardOutput API with pre-parsed toolCalls, extracted thinking, and token counts

Files:

  • packages/trl/src/trainers/grpo-trainer.ts
packages/trl/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Reward functions should accept RewardOutput[] array with pre-parsed tool calls instead of raw completions

Files:

  • packages/trl/src/trainers/grpo-trainer.ts
🧠 Learnings (9)
📓 Common learnings
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/trl/src/trainers/grpo-trainer.ts : In GRPOTrainer TypeScript implementation, use unified RewardOutput API with pre-parsed toolCalls, extracted thinking, and token counts
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/**/*.rs : Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Applied to files:

  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/tools/mod.rs
  • crates/mlx-core/src/output_store/schema.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Maintain functional forward pass architecture in transformer components to enable automatic differentiation through MLX computation graphs

Applied to files:

  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/tools/mod.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/models/qwen3/*.rs : In Qwen3 model files, maintain separation between model architecture (model.rs), configuration (config.rs), generation (generation.rs), and persistence (persistence.rs)

Applied to files:

  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/{core,lm,trl}/src/index.ts : Use the established re-export pattern for clean public APIs in TypeScript packages

Applied to files:

  • packages/core/index.cjs
  • packages/trl/src/trainers/grpo-trainer.ts
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/grpo/**/*.rs : GRPO training components (loss, advantages, entropy filtering) must include comprehensive Rust test suites (minimum 10+ tests per component)

Applied to files:

  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/models/qwen3/generation.rs : For Qwen3 generation, support chat API with tool calling (JSON/XML formats), thinking extraction (<think> tags), and Jinja2 template formatting

Applied to files:

  • crates/mlx-core/src/tools/mod.rs
  • crates/mlx-core/src/output_store/reader.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/trl/src/**/*.ts : Reward functions should accept RewardOutput[] array with pre-parsed tool calls instead of raw completions

Applied to files:

  • crates/mlx-core/src/tools/mod.rs
  • packages/core/index.d.cts
  • packages/trl/src/trainers/grpo-trainer.ts
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/trl/src/trainers/grpo-trainer.ts : In GRPOTrainer TypeScript implementation, use unified RewardOutput API with pre-parsed toolCalls, extracted thinking, and token counts

Applied to files:

  • crates/mlx-core/src/grpo/engine.rs
  • packages/core/index.d.cts
  • packages/trl/src/trainers/grpo-trainer.ts
🧬 Code graph analysis (6)
crates/mlx-core/src/output_store/writer.rs (1)
packages/core/index.d.cts (5)
  • EngineStepMetrics (2329-2348)
  • RewardOutput (2745-2752)
  • StepRecord (2917-2940)
  • GenerationRecord (2425-2446)
  • ToolCallRecord (2971-2984)
crates/mlx-core/src/output_store/mod.rs (1)
packages/trl/src/trainers/grpo-trainer.ts (1)
  • OutputStore (77-77)
crates/mlx-core/src/tools/mod.rs (1)
packages/core/index.d.cts (1)
  • ToolCallResult (2987-3003)
crates/mlx-core/src/grpo/engine.rs (1)
packages/core/index.d.cts (4)
  • TrainStepResultWithOutputs (3044-3056)
  • EngineStepMetrics (2329-2348)
  • ChatMessage (2107-2118)
  • GenerationConfig (2385-2422)
crates/mlx-core/src/output_store/reader.rs (3)
crates/mlx-core/src/output_store/store.rs (7)
  • list_runs (320-327)
  • get_run (331-334)
  • get_generations (350-357)
  • get_generations_with_tool_calls (386-395)
  • search_generations (399-408)
  • get_reward_stats (412-419)
  • export_jsonl (423-437)
packages/core/index.d.cts (5)
  • TrainingRunRecord (3014-3031)
  • GenerationWithToolCalls (2449-2454)
  • GenerationRecord (2425-2446)
  • RewardStats (2755-2772)
  • ToolCallRecord (2971-2984)
crates/mlx-core/src/output_store/types.rs (1)
  • default (171-182)
crates/mlx-core/src/output_store/types.rs (2)
packages/core/index.d.cts (8)
  • OutputStoreConfig (2571-2582)
  • TrainingRunRecord (3014-3031)
  • StepRecord (2917-2940)
  • GenerationRecord (2425-2446)
  • ToolCallRecord (2971-2984)
  • GenerationWithToolCalls (2449-2454)
  • StepSummary (2943-2958)
  • RewardStats (2755-2772)
packages/trl/src/trainers/grpo-trainer.ts (1)
  • OutputStoreConfig (86-86)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Agent
  • GitHub Check: Cursor Bugbot
  • GitHub Check: Build & cargo test
  • GitHub Check: Rust Lint
🔇 Additional comments (23)
package.json (1)

32-32: Remove unused oxc-parser dependency or explain its purpose.

oxc-parser appears in devDependencies but has no usage anywhere in the codebase. Either remove the unused dependency or clarify why it's needed for the database persistence feature described in the PR.

crates/mlx-core/Cargo.toml (1)

27-27: LGTM!

The libsql workspace dependency is correctly added, consistent with other dependency declarations in this file.

__test__/tools/chat.test.ts (1)

28-30: LGTM!

Test mocks correctly include the new rawContent field with appropriate values matching the expected tool call tag content. The test structure follows Vitest conventions as per coding guidelines.

Also applies to: 46-46, 60-60, 125-127, 153-155

crates/mlx-core/src/output_store/writer.rs (1)

15-145: LGTM on transactional record_step implementation.

The transaction-based approach ensures atomicity. Using RETURNING clauses for ID retrieval is efficient. Error handling is consistent throughout.

packages/core/index.d.cts (3)

1028-1081: LGTM on OutputStore API surface.

The class exposes a well-structured API with factory methods for different storage modes (local, remote, embedded replica). The separation between run lifecycle, step recording, and querying is clean.


1079-1080: Note: queryRaw allows arbitrary SQL execution.

This is useful for advanced users but should be documented with security considerations if the store is ever exposed to untrusted input.

Ensure callers of queryRaw validate or sanitize SQL if the query string could come from external/user input.


2998-3002: LGTM on rawContent field addition.

The field is required (non-optional) with serde(default) on the Rust side for backward compatibility with existing serialized data.

crates/mlx-core/src/tools/mod.rs (2)

14-31: LGTM on ToolCallResult updates.

Adding Deserialize derive with #[serde(default)] on raw_content ensures backward compatibility when deserializing older JSON that lacks this field.


188-210: LGTM on parse_tool_calls raw_content capture.

Using cap.get(0) to capture the full match including <tool_call> tags correctly provides the raw content for debugging and persistence purposes.

__test__/models/qwen3-chat.test.ts (1)

120-121: LGTM!

Test mocks correctly updated with rawContent field values that match the expected tool call tag format. Tests verify the ToolCallResult structure including the new field.

Also applies to: 136-136

crates/mlx-core/src/output_store/reader.rs (2)

660-670: Column type inference has limitations.

The loop tries String → i64 → f64 but doesn't handle NULL values or other types (blobs, booleans). Columns that don't match these types will be silently omitted.

Consider documenting this limitation or adding NULL handling:

// Before type checks
if row.get::<libsql::Value>(i).ok().map(|v| v.is_null()).unwrap_or(true) {
    row_data.insert(format!("col{}", i), json!(null));
    continue;
}

15-58: LGTM on list_runs implementation.

Parameterized queries prevent SQL injection. Dynamic SQL construction for optional filters is handled correctly.

Cargo.toml (1)

28-28: libsql 0.9 with replication feature is valid and appropriate.

The libsql dependency is available (latest 0.9.29) with the replication feature properly supported in all 0.9.x releases. This is suitable for the embedded replica mode use case.

packages/core/index.cjs (1)

574-599: Expose OutputStore from CJS binding

The new export is consistent with the existing native binding re-export pattern and correctly surfaces OutputStore to consumers.

crates/mlx-core/src/lib.rs (1)

7-26: Wire output_store module into crate root

Adding pub mod output_store; cleanly exposes the new subsystem alongside existing modules; no issues spotted.

crates/mlx-core/src/grpo/engine.rs (1)

200-225: TrainStepResultWithOutputs matches intended TS-facing API

The new NAPI object cleanly extends TrainStepResult with an optional outputs_json field for serialized RewardOutput data and aligns with the corresponding TypeScript interface (outputsJson?: string). This should interoperate correctly with the JS bindings.

packages/trl/src/trainers/grpo-trainer.ts (1)

823-879: Correct RewardOutput tool call mapping and camelCase conversion

The updated rewardCallback correctly:

  • Parses the JSON Vec<RewardOutput> from Rust.
  • Converts completion.tool_calls from snake_case to camelCase, including raw_content → rawContent.
  • Preserves status and error fields while keeping arguments typed as a Record<string, unknown>.

This matches the unified RewardOutput API expectation (pre-parsed toolCalls, extracted thinking, and token counts) and should keep downstream reward functions type-safe.

crates/mlx-core/src/output_store/types.rs (1)

8-183: NAPI OutputStore types align with TS interfaces

The new #[napi(object)] structs cleanly model the store configuration and records:

  • Field sets and semantics match the corresponding TypeScript interfaces (OutputStoreConfig, TrainingRunRecord, StepRecord, GenerationRecord, ToolCallRecord, GenerationWithToolCalls, StepSummary, RewardStats).
  • Using Option<> for nullable fields and i64/f64 for counts and metrics is appropriate for the underlying SQLite schema.
  • RewardStats: Default returning all zeros is a reasonable sentinel for “no data yet”.

This should provide a stable, type-safe bridge between Rust and the JS bindings.

crates/mlx-core/src/output_store/store.rs (5)

25-31: LGTM!

The struct design correctly uses Arc<RwLock<...>> for thread-safe access patterns. The RwLock allows concurrent reads while serializing writes, which is appropriate for a database connection wrapper exposed via NAPI.


34-171: LGTM!

Factory methods are well-structured with consistent error handling. The from_config routing logic correctly prioritizes embedded replica mode when all three config options are present.


176-199: LGTM!

The start_run method correctly generates a UUID, inserts the run record, and updates the current run state atomically within the write lock scope.


254-314: LGTM!

Recording and sync methods properly delegate to the writer module. The flush method is appropriately stubbed with a clear TODO for future batched writes implementation.


316-437: LGTM!

Query methods consistently use read locks for database access and cleanly delegate to the reader module. The API surface provides good flexibility for filtering and searching training data.

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 pull request adds comprehensive training output persistence using libsql/SQLite, enabling users to record all model outputs during GRPO training for debugging and research purposes. The implementation supports local SQLite files, remote Turso databases, and embedded replica mode with automatic syncing.

Key Changes

  • New OutputStore module with full CRUD operations for training runs, steps, generations, and tool calls
  • Transaction-based atomic writes with automatic schema initialization
  • Query API for filtering by reward, tool usage, finish reason, and text search
  • Integration with GRPOTrainer via optional configuration with lazy initialization
  • Added raw_content field to ToolCallResult for debugging/persistence with backward compatibility

Reviewed changes

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

Show a summary per file
File Description
yarn.lock, package.json, Cargo.toml Added oxc-parser and libsql dependencies
packages/core/index.d.cts Type definitions for OutputStore API and related types
packages/core/index.cjs Export OutputStore class binding
crates/mlx-core/src/lib.rs Added output_store module
crates/mlx-core/src/output_store/*.rs Core implementation: schema, store, reader, writer, types
crates/mlx-core/src/tools/mod.rs Added raw_content field with serde(default) for backward compatibility
crates/mlx-core/src/grpo/engine.rs New trainStepAutoWithRecording method (565 lines)
packages/trl/src/trainers/grpo-trainer.ts OutputStore integration with lazy init and promise mutex
test/trainers/output-store.test.ts Comprehensive test suite (513 lines)
test/tools/chat.test.ts, test/models/qwen3-chat.test.ts Updated tests for raw_content field

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

Comment thread __test__/trainers/output-store.test.ts Resolved
Comment thread __test__/trainers/output-store.test.ts Resolved
Comment thread packages/core/index.cjs Resolved
@Brooooooklyn
Brooooooklyn force-pushed the fix/output-store-polish branch 2 times, most recently from 591b8bc to f780281 Compare December 29, 2025 13:36
Add OutputStore for recording training outputs to SQLite (local) or Turso (remote).

Features:
- Record training steps with generations, tool calls, and metrics
- Query by step range, reward thresholds, tool usage patterns
- Embedded replica mode for local cache + remote sync
- Automatic run tracking with model/config metadata

Fixes from review:
- Add transaction wrapper in record_step for atomicity
- Add #[serde(default)] for raw_content backward compatibility
- Fix lazy init race with promise mutex pattern
- Fix toolCalls snake_case → camelCase conversion
- Fix status type narrowing (ok|invalid_json|missing_name)
- Ensure outputDir exists before DB open in lazy init

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the fix/output-store-polish branch from f780281 to db3196a Compare December 29, 2025 13:39

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

🧹 Nitpick comments (10)
package.json (1)

32-32: Consider updating to [email protected], the latest available version.

The version 0.105.0 exists and was released Dec 22, 2025, with no known security vulnerabilities. However, oxc-parser 0.106.0 is now available as the latest version. Since the caret range (^0.105.0) already allows minor version updates, you may want to update the dependency to 0.106.0 to stay current.

crates/mlx-core/src/grpo/engine.rs (1)

1882-2443: train_step_auto_with_recording correctly mirrors train_step_auto but duplicates complex logic

The recording variant faithfully reproduces generation, reward building, degenerate filtering, and training/NaN-handling paths from train_step_auto, and only adds the optional outputs_json plumbing. Behavior for metrics, filtering, and emergency-save looks consistent.

However, the two methods now share a large amount of nearly-identical code. Any future fix in one (e.g., to filtering, loss config, or NaN handling) will need to be manually replicated in the other.

Consider extracting an internal helper that takes a record_outputs: bool flag and returns (TrainStepResult, Option<String>), with train_step_auto delegating to it and discarding the JSON, while train_step_auto_with_recording forwards the Option. This would reduce surface for subtle divergence without changing runtime behavior.

crates/mlx-core/src/tools/mod.rs (1)

14-31: ToolCallResult raw_content propagation and serde support look correct

The addition of raw_content with #[serde(default)] plus the updated constructors and parsers keeps backwards compatibility while giving you full <tool_call>…</tool_call> context for debugging/persistence. JSON/XML parsers now consistently pass the full tag content through, and CompletionInfo/RewardOutput gaining Deserialize is aligned with OutputStore needs.

Only minor nit to keep in mind: ToolCallResult::missing_name now embeds the entire raw snippet into error, which is great for debugging but could be verbose for very long generations. If this ever becomes noisy in logs/DB, consider truncating the raw text in the error message while still storing the full raw_content field.

Also applies to: 35-69, 101-135, 140-173, 187-207, 274-294

packages/core/index.d.cts (1)

599-615: Type surface for recording-aware GRPO engine and OutputStore is consistent and usable

  • trainStepAutoWithRecording’s signature and return type line up with the Rust NAPI binding and the new TrainStepResultWithOutputs shape.
  • The OutputStore class plus OutputStoreConfig, GenerationRecord, ToolCallRecord, StepRecord, StepSummary, GenerationWithToolCalls, RewardStats, and TrainingRunRecord provide a coherent, well-documented TS API for both recording and querying training runs.
  • ToolCallResult.rawContent: string matches the Rust raw_content field and the tests’ expectations, giving a clear path from parser → RewardOutput → OutputStore (via ToolCallRecord.rawContent).

Two small optional suggestions:

  • In OutputStore.queryRaw(sql: string), consider explicitly documenting that callers should not pass untrusted input directly into sql, since this is intentionally bypassing parameter binding and opens you up to SQL injection if misused.
  • For recordStepFromOutputs, it may help to note in the doc block that outputsJson must be the serialized RewardOutput[] for exactly groupSize * numPrompts completions, matching the step’s rewards vector, to avoid subtle mismatches.

Also applies to: 1028-1081, 2424-2454, 2570-2582, 2754-2772, 2916-2958, 2970-2984, 3013-3031, 3043-3055, 2986-3003

__test__/models/qwen3-chat.test.ts (1)

114-137: ToolCallResult mocks correctly updated for rawContent

Including realistic rawContent strings on the ToolCallResult mocks keeps these tests aligned with the updated interface (required rawContent: string) and with what the Rust parser now emits. You’re already validating the important semantic fields; adding an assertion on rawContent would be purely optional if you ever want to catch formatting regressions.

__test__/tools/chat.test.ts (1)

22-61: chat() API type tests are correctly extended for rawContent

The additional rawContent fields on your ToolCallResult mocks match the new interface and the expected <tool_call>…</tool_call> format from the Rust side. The tests still focus on id/name/arguments/status, which is appropriate for type-level coverage; asserting on rawContent would be a nice-to-have if you ever want stronger end-to-end checks on parser formatting.

Also applies to: 120-155

crates/mlx-core/src/output_store/schema.rs (1)

1-115: OutputStore schema and init_schema implementation are sound for the current use

  • Table layouts for training_runs, training_steps, generations, and tool_calls line up with the TS data models (run/step IDs, rewards, finish reasons, raw tool-call content, created_at).
  • Indexes cover the obvious query patterns (by run/step, reward, finish_reason, generation_id).
  • init_schema’s simple split(';') + comment stripping works fine for this static DDL and correctly skips empty fragments.

If you later extend the schema with more complex SQL (e.g., triggers or statements containing semicolons in strings), consider switching to libsql’s batch execution (if available) or keeping DDL one-statement-per-line to avoid the need for manual splitting.

crates/mlx-core/src/output_store/writer.rs (2)

206-211: Silent reward fallback may mask data inconsistencies.

When idx >= rewards.len(), the reward silently defaults to 0.0. This could mask bugs where the rewards array doesn't match the outputs array length. Consider logging a warning or returning an error if there's a mismatch.

🔎 Proposed enhancement
-            reward: if idx < rewards.len() {
-                rewards[idx]
-            } else {
-                0.0
-            },
+            reward: if idx < rewards.len() {
+                rewards[idx]
+            } else {
+                tracing::warn!(
+                    "Reward index {} out of bounds (len={}), defaulting to 0.0",
+                    idx, rewards.len()
+                );
+                0.0
+            },

220-228: Arguments serialization uses unwrap_or_default().

If serde_json::to_string(&tc.arguments) fails, it silently returns an empty string, potentially losing tool call argument data. Given that tc.arguments is already a deserialized type, this is unlikely to fail, but consider using unwrap_or_else with logging for observability.

crates/mlx-core/src/output_store/reader.rs (1)

159-206: N+1 query pattern in get_generations.

Each generation triggers a separate query for tool calls via get_tool_calls_for_generation. For steps with many generations, this could become a performance concern. Consider batching tool call fetches or using a JOIN with post-processing.

For diagnostic purposes this is acceptable, but if performance becomes an issue:

// Alternative: fetch all tool calls for the step in one query, then distribute
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d0fe9e8 and db3196a.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (18)
  • Cargo.toml
  • __test__/models/qwen3-chat.test.ts
  • __test__/tools/chat.test.ts
  • __test__/trainers/output-store.test.ts
  • crates/mlx-core/Cargo.toml
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/output_store/reader.rs
  • crates/mlx-core/src/output_store/schema.rs
  • crates/mlx-core/src/output_store/store.rs
  • crates/mlx-core/src/output_store/types.rs
  • crates/mlx-core/src/output_store/writer.rs
  • crates/mlx-core/src/tools/mod.rs
  • package.json
  • packages/core/index.cjs
  • packages/core/index.d.cts
  • packages/trl/src/trainers/grpo-trainer.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml
🧰 Additional context used
📓 Path-based instructions (6)
crates/mlx-core/src/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Files:

  • crates/mlx-core/src/output_store/schema.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/output_store/writer.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/tools/mod.rs
  • crates/mlx-core/src/output_store/reader.rs
  • crates/mlx-core/src/output_store/store.rs
  • crates/mlx-core/src/output_store/types.rs
**/__test__/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

In TypeScript test files, use Vitest framework with TypedArray creation helpers and appropriate tolerance values for floating-point comparisons

Files:

  • __test__/models/qwen3-chat.test.ts
  • __test__/tools/chat.test.ts
  • __test__/trainers/output-store.test.ts
crates/mlx-core/src/grpo/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

GRPO training components (loss, advantages, entropy filtering) must include comprehensive Rust test suites (minimum 10+ tests per component)

Files:

  • crates/mlx-core/src/grpo/engine.rs
packages/{core,lm,trl}/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Use TypedArrays (Float32Array, Int32Array, BigInt64Array) for all data and shape handling in APIs

Files:

  • packages/trl/src/trainers/grpo-trainer.ts
packages/trl/src/trainers/grpo-trainer.ts

📄 CodeRabbit inference engine (CLAUDE.md)

In GRPOTrainer TypeScript implementation, use unified RewardOutput API with pre-parsed toolCalls, extracted thinking, and token counts

Files:

  • packages/trl/src/trainers/grpo-trainer.ts
packages/trl/src/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Reward functions should accept RewardOutput[] array with pre-parsed tool calls instead of raw completions

Files:

  • packages/trl/src/trainers/grpo-trainer.ts
🧠 Learnings (8)
📓 Common learnings
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/trl/src/trainers/grpo-trainer.ts : In GRPOTrainer TypeScript implementation, use unified RewardOutput API with pre-parsed toolCalls, extracted thinking, and token counts
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/{core,lm,trl}/src/index.ts : Use the established re-export pattern for clean public APIs in TypeScript packages

Applied to files:

  • packages/core/index.cjs
  • packages/trl/src/trainers/grpo-trainer.ts
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/trl/src/trainers/grpo-trainer.ts : In GRPOTrainer TypeScript implementation, use unified RewardOutput API with pre-parsed toolCalls, extracted thinking, and token counts

Applied to files:

  • packages/core/index.cjs
  • crates/mlx-core/src/grpo/engine.rs
  • packages/trl/src/trainers/grpo-trainer.ts
  • packages/core/index.d.cts
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/**/*.rs : Wrap NAPI exports with #[napi] macros and provide corresponding TypeScript type definitions

Applied to files:

  • crates/mlx-core/src/output_store/schema.rs
  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/tools/mod.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/models/qwen3/*.rs : In Qwen3 model files, maintain separation between model architecture (model.rs), configuration (config.rs), generation (generation.rs), and persistence (persistence.rs)

Applied to files:

  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/store.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/grpo/**/*.rs : GRPO training components (loss, advantages, entropy filtering) must include comprehensive Rust test suites (minimum 10+ tests per component)

Applied to files:

  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/output_store/reader.rs
  • crates/mlx-core/src/output_store/store.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to crates/mlx-core/src/transformer/*.rs : Maintain functional forward pass architecture in transformer components to enable automatic differentiation through MLX computation graphs

Applied to files:

  • crates/mlx-core/src/output_store/mod.rs
  • crates/mlx-core/src/grpo/engine.rs
  • crates/mlx-core/src/lib.rs
  • crates/mlx-core/src/output_store/types.rs
📚 Learning: 2025-12-23T06:42:10.489Z
Learnt from: CR
Repo: mlx-node/mlx-node PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-23T06:42:10.489Z
Learning: Applies to packages/trl/src/**/*.ts : Reward functions should accept RewardOutput[] array with pre-parsed tool calls instead of raw completions

Applied to files:

  • __test__/tools/chat.test.ts
  • crates/mlx-core/src/tools/mod.rs
  • packages/trl/src/trainers/grpo-trainer.ts
  • packages/core/index.d.cts
🧬 Code graph analysis (6)
crates/mlx-core/src/output_store/mod.rs (1)
packages/trl/src/trainers/grpo-trainer.ts (1)
  • OutputStore (77-77)
__test__/trainers/output-store.test.ts (1)
packages/trl/src/trainers/grpo-trainer.ts (1)
  • OutputStore (77-77)
crates/mlx-core/src/tools/mod.rs (1)
packages/core/index.d.cts (1)
  • ToolCallResult (2987-3003)
packages/trl/src/trainers/grpo-trainer.ts (2)
packages/core/index.d.cts (1)
  • TrainStepResultWithOutputs (3044-3056)
packages/trl/src/trainers/training-logger.ts (1)
  • status (260-266)
crates/mlx-core/src/output_store/reader.rs (3)
crates/mlx-core/src/output_store/store.rs (11)
  • list_runs (320-327)
  • get_run (331-334)
  • get_step_summaries (338-346)
  • get_generations (350-357)
  • get_generations_by_reward (361-370)
  • get_generations_by_finish_reason (374-382)
  • get_generations_with_tool_calls (386-395)
  • search_generations (399-408)
  • get_reward_stats (412-419)
  • export_jsonl (423-437)
  • query_raw (441-444)
packages/core/index.d.cts (6)
  • TrainingRunRecord (3014-3031)
  • StepSummary (2943-2958)
  • GenerationWithToolCalls (2449-2454)
  • GenerationRecord (2425-2446)
  • RewardStats (2755-2772)
  • ToolCallRecord (2971-2984)
crates/mlx-core/src/output_store/types.rs (1)
  • default (171-182)
crates/mlx-core/src/output_store/types.rs (1)
packages/core/index.d.cts (8)
  • OutputStoreConfig (2571-2582)
  • TrainingRunRecord (3014-3031)
  • StepRecord (2917-2940)
  • GenerationRecord (2425-2446)
  • ToolCallRecord (2971-2984)
  • GenerationWithToolCalls (2449-2454)
  • StepSummary (2943-2958)
  • RewardStats (2755-2772)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cursor Bugbot
🔇 Additional comments (24)
packages/core/index.cjs (1)

597-597: No action needed. The security concern from the past review has been properly addressed: sanitization is implemented in the TypeScript layer (GRPOTrainer), where the authToken is explicitly removed from the config before being persisted via OutputStore.startRun. The export is safe.

crates/mlx-core/src/grpo/engine.rs (1)

212-225: TrainStepResultWithOutputs struct matches existing metrics shape and NAPI usage

The new NAPI object cleanly extends TrainStepResult with an optional outputs_json field, matching the TS-side TrainStepResultWithOutputs.outputsJson?: string and preserving the existing metrics/completions/rewards contract.

crates/mlx-core/src/lib.rs (1)

16-16: Exporting output_store module from crate root is correct

The new pub mod output_store; neatly wires the OutputStore subsystem into the public crate surface with no side effects elsewhere.

crates/mlx-core/Cargo.toml (1)

27-27: libsql workspace dependency aligns with new OutputStore usage

Adding libsql = { workspace = true } here is consistent with the new output-store module that initializes schemas and runs queries via libsql. The root workspace dependency correctly pins libsql version 0.9 with the replication feature.

crates/mlx-core/src/output_store/mod.rs (1)

1-47: Well-structured module with clear documentation.

The module provides a clean public API surface by re-exporting OutputStore and types. The documentation includes practical TypeScript usage examples covering all key operations (local/remote stores, run lifecycle, recording, querying). The separation into reader, schema, store, types, and writer submodules follows good architectural practices.

__test__/trainers/output-store.test.ts (4)

1-47: Comprehensive test setup with proper resource cleanup.

The test suite properly creates unique temp databases per test and handles cleanup of SQLite auxiliary files (WAL, SHM). The silent catch blocks in afterEach are appropriate for test teardown where failures shouldn't cascade.


49-90: Good lifecycle coverage.

Tests validate the complete training run lifecycle: starting runs, tracking current run ID, ending runs, listing runs, and retrieving specific runs with correct metadata.


307-409: Valuable SQL parameter binding edge case tests.

These tests validate the dynamic placeholder numbering fix by testing scenarios where only some optional parameters are provided (endStep only, status only). This is important for preventing regression on the SQL binding fixes mentioned in the PR.


411-449: Input validation test correctly verifies group_size guard.

The test properly validates that recordStepFromOutputs rejects group_size=0 with a descriptive error, preventing division-by-zero issues in batch/group index calculations.

crates/mlx-core/src/output_store/writer.rs (1)

15-145: Transaction-wrapped writes ensure atomicity.

The record_step function correctly uses a transaction to ensure all inserts (step, generations, tool_calls) succeed or fail together. The use of RETURNING clauses to capture IDs atomically is a good pattern. Error handling at each stage provides clear context.

crates/mlx-core/src/output_store/types.rs (1)

1-183: Well-defined NAPI types with proper documentation.

All types are correctly annotated with #[napi(object)] per coding guidelines and include thorough documentation. The types align with the TypeScript definitions in packages/core/index.d.cts. The Default implementation for RewardStats provides sensible zero-value defaults.

packages/trl/src/trainers/grpo-trainer.ts (5)

162-176: Well-designed output recording configuration.

The config structure provides sensible defaults and clear options for local, remote, or embedded replica modes. The enabled flag makes the feature opt-in.


364-429: Robust lazy initialization with retry support.

The OutputStore initialization addresses all previously raised concerns:

  • Guard at line 369 prevents duplicate initialization
  • Config sanitization at lines 398-403 removes authToken before persistence
  • Fallback to this.config.modelPath at line 397 ensures consistent metadata
  • Promise mutex at lines 416-428 prevents race conditions
  • Clearing promise on failure (line 426) enables retry on transient errors

873-889: Correct camelCase conversion for tool calls.

The mapping from snake_case (raw_content) to camelCase (rawContent) aligns with the unified RewardOutput API pattern. Based on learnings, the GRPOTrainer should use pre-parsed toolCalls with extracted thinking and token counts, which this implementation follows.


944-958: Resilient output recording with error isolation.

Recording errors are logged but don't fail training, which is the correct behavior for a diagnostic/research feature. The error message includes the [OutputStore] prefix for easy filtering in logs.


1124-1129: Proper lifecycle management for OutputStore.

The store's endRun and flush are called with appropriate status on training completion. The stopRequested flag correctly maps to 'stopped' status.

crates/mlx-core/src/output_store/reader.rs (3)

408-460: Search uses parameterized LIKE pattern.

The search implementation correctly uses parameterized queries (?2) for the search pattern, preventing SQL injection from user-provided search terms. The pattern construction at line 416 is safe.


538-543: Approximate percentile calculation is documented as intentional.

Per past review, the simple array indexing for p25/median/p75 is intentional for diagnostic purposes. The edge case handling for n == 0 is in place.


556-642: JSONL export with buffered writing.

The export uses BufWriter for efficient I/O and properly flushes at the end. Error handling is comprehensive for file creation, writes, and JSON serialization.

crates/mlx-core/src/output_store/store.rs (5)

21-31: Thread-safe store design with appropriate locking.

The OutputStore uses Arc<RwLock<Connection>> for concurrent access, with read locks for queries and write locks for mutations. The current_run_id is also protected by RwLock for safe concurrent access.


95-143: Embedded replica mode with initial sync.

The embedded_replica factory correctly configures sync interval and performs an initial sync after schema initialization. This ensures the local replica is consistent before use.


145-171: Config-based factory provides flexible initialization.

The from_config factory correctly prioritizes embedded replica mode when all three parameters are present, falling back to remote-only or local-only as appropriate. The error message for invalid config is clear.


298-304: Flush is a placeholder for future batched writes.

The flush() method is documented as a no-op with a comment indicating future batched write support. This is acceptable as long as current writes are immediate (which they are).


447-453: Timestamp helper uses expect with descriptive message.

Per past review, chrono_now_ms now uses .expect("system clock is set before UNIX_EPOCH") instead of .unwrap(), providing clear context if this edge case ever occurs.

@Brooooooklyn
Brooooooklyn merged commit 553bc14 into main Dec 29, 2025
@Brooooooklyn
Brooooooklyn deleted the fix/output-store-polish branch December 29, 2025 14:02
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
Add OutputStore for recording training outputs to SQLite (local) or
Turso (remote).

Features:
- Record training steps with generations, tool calls, and metrics
- Query by step range, reward thresholds, tool usage patterns
- Embedded replica mode for local cache + remote sync
- Automatic run tracking with model/config metadata

Fixes from review:
- Add transaction wrapper in record_step for atomicity
- Add #[serde(default)] for raw_content backward compatibility
- Fix lazy init race with promise mutex pattern
- Fix toolCalls snake_case → camelCase conversion
- Fix status type narrowing (ok|invalid_json|missing_name)
- Ensure outputDir exists before DB open in lazy init

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

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds a persistent output store and wires it into training for
recording and analysis.
> 
> - New `mlx-core/output_store` module (schema, reader, writer, NAPI
`OutputStore`) with local/remote/embedded-replica support via `libsql`;
queries for runs/steps/generations/tool-calls/reward stats; JSONL export
> - Engine: new `train_step_auto_with_recording` returning optional
`outputs_json` for zero-copy persistence;
`ToolCallResult`/`CompletionInfo`/`RewardOutput` now deserializable and
include `raw_content` (with `#[serde(default)]`); parser preserves raw
tool-call content
> - Trainer: integrates `OutputStore` (lazy init with promise mutex,
start/end run, `recordStepFromOutputs`, optional cloud sync); new
`outputStore` config block
> - Tests: extensive `OutputStore` lifecycle/query/edge-case tests;
chat/tool tests updated for `rawContent`
> - Packaging: export `OutputStore` and types in `packages/core`, add
workspace `libsql` dep and dev `oxc-parser`
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
db3196a. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Output Store: persistent storage for training runs (local, remote,
embedded replica) with start/end/run lifecycle, recording, search,
filtering, export, and reward stats.
* Optional training-step recording that can capture full reward outputs
alongside extended training results.
* Tool-call tracking now preserves raw tool-call content for improved
debugging and analysis.
* **Tests**
* Added end-to-end tests covering Output Store lifecycle, recording,
querying, search, and edge cases.
* **Chores**
* Dependency and public export updates to enable the new persistence
surface.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

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 28, 2026
…s; add throughput trend query

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

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

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

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

#7: the binding trace schema (spec:147) requires queue_ms and resident, but
neither existed, and durationMs folded queue wait + model load into execution
because the turn was timestamped before the serialized/resident host await.
Capture queueMs at callback entry (after the queue+load await) and thread a
resident (was-warm) flag out of model-host.runWithResident, carry both through
the record and JSONL sink, and store them in the traces table (schema + DDL +
EXPECTED_COLUMNS auto-derived from the drizzle schema, so an old DB rebuilds
rather than wedging) and the ingester.

#9 (UI): consume the new throughputTrend overview field and render a temporal
multi-series chart (x = day, one series per model) for decode tok/s and TTFT,
keeping the per-model average bars.

Also widen the runWithResident fakes in stream-adapter.test.ts to the new
(session, resident) callback signature (tsc allowed the 1-arg fakes under
bivariant method checking; the type-aware lint requires the exact shape).

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

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

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

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

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

#7: the binding trace schema (spec:147) requires queue_ms and resident, but
neither existed, and durationMs folded queue wait + model load into execution
because the turn was timestamped before the serialized/resident host await.
Capture queueMs at callback entry (after the queue+load await) and thread a
resident (was-warm) flag out of model-host.runWithResident, carry both through
the record and JSONL sink, and store them in the traces table (schema + DDL +
EXPECTED_COLUMNS auto-derived from the drizzle schema, so an old DB rebuilds
rather than wedging) and the ingester.

#9 (UI): consume the new throughputTrend overview field and render a temporal
multi-series chart (x = day, one series per model) for decode tok/s and TTFT,
keeping the per-model average bars.

Also widen the runWithResident fakes in stream-adapter.test.ts to the new
(session, resident) callback signature (tsc allowed the 1-arg fakes under
bivariant method checking; the type-aware lint requires the exact shape).

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

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

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

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

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

#7: the binding trace schema (spec:147) requires queue_ms and resident, but
neither existed, and durationMs folded queue wait + model load into execution
because the turn was timestamped before the serialized/resident host await.
Capture queueMs at callback entry (after the queue+load await) and thread a
resident (was-warm) flag out of model-host.runWithResident, carry both through
the record and JSONL sink, and store them in the traces table (schema + DDL +
EXPECTED_COLUMNS auto-derived from the drizzle schema, so an old DB rebuilds
rather than wedging) and the ingester.

#9 (UI): consume the new throughputTrend overview field and render a temporal
multi-series chart (x = day, one series per model) for decode tok/s and TTFT,
keeping the per-model average bars.

Also widen the runWithResident fakes in stream-adapter.test.ts to the new
(session, resident) callback signature (tsc allowed the 1-arg fakes under
bivariant method checking; the type-aware lint requires the exact shape).

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
…EOS union

Reviewer findings #8 and #9, verified before applying:

- convert.rs (#8, P1): when the caller omitted -m and the config declared
  the family, is_nemotron_h_ingest was true but the recipe dispatch matched
  the unchanged None model_type and skipped NemotronHRecipe::sanitize —
  saving un-repacked U8/F8 tensors and modelopt sidecars. Resolve an
  effective recipe_model_type from the config detection and use it in the
  dispatch, so a config-detected Nemotron always runs the ingest sanitizer.
- model.rs (#9, P2): extra_eos_ids() returned only config.eos_token_ids,
  but the released checkpoint declares eos 2 in config.json and {2, 11} in
  generation_config.json — EOS 11 was missed by every chat path. Now a
  UNION of both (engine contract: union, never override).
- mtp.rs test hardening: mtp_turn_runs_draft_verify_cycles panicked on the
  zero-cycle expect before its own retry check (random-weights EOS exits
  are valid); the retry is now reachable.

Verified: cargo fmt --check, cargo clippy --all-targets -D warnings,
nemotron 37/37, convert 212 clean.
Brooooooklyn added a commit that referenced this pull request Aug 19, 2026
…EOS union

Reviewer findings #8 and #9, verified before applying:

- convert.rs (#8, P1): when the caller omitted -m and the config declared
  the family, is_nemotron_h_ingest was true but the recipe dispatch matched
  the unchanged None model_type and skipped NemotronHRecipe::sanitize —
  saving un-repacked U8/F8 tensors and modelopt sidecars. Resolve an
  effective recipe_model_type from the config detection and use it in the
  dispatch, so a config-detected Nemotron always runs the ingest sanitizer.
- model.rs (#9, P2): extra_eos_ids() returned only config.eos_token_ids,
  but the released checkpoint declares eos 2 in config.json and {2, 11} in
  generation_config.json — EOS 11 was missed by every chat path. Now a
  UNION of both (engine contract: union, never override).
- mtp.rs test hardening: mtp_turn_runs_draft_verify_cycles panicked on the
  zero-cycle expect before its own retry check (random-weights EOS exits
  are valid); the retry is now reachable.

Verified: cargo fmt --check, cargo clippy --all-targets -D warnings,
nemotron 37/37, convert 212 clean.
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
Stage S8 of the Splash int8 KV alignment (stack #344). Base: FN2 (#363).

DFlash2 on qwen3_5 and qwen3_5_moe verifies on the paged pool (int8 by
default), as Splash does. The flat DFlash2 lane is deleted, and every
turn kind shares one pool window.

```
before:  DFlash2 turn ──► flat K/V + flat compiled verify ──► own window (32,761)
after:   DFlash2 turn ──► paged pool (int8) ──► anchor + 7 rows, one 8-row verify ──► the one pool window (94,201)
```

## Changes
- **Turn on the pool:** dense and MoE DFlash2 plans publish
`supports_paged_attention: true`. `run_paged_turn` sends DFlash2 to
`run_paged_dspark_turn`. The shared driver uses `args.params` (so the
window clamp holds) and gets two hooks whose defaults keep gemma4
unchanged.
- **Verify** (Splash `QwenTarget` verify, `PagedAttention::addVerify`):
the draft always proposes the full block (7). Every cycle verifies
anchor + 7 = 8 rows. `run_paged_dflash2_verify_step` refuses a chunk
that is not 8 rows, or a page table shorter than committed + 8, with the
Splash error text.
- **Booking:** each cycle books committed + 8 and commits through
`open_core_write_cycle` / `commit_cycle`. The cursor moves back 8 −
keep, and no page is freed. The DFlash2 prefill books each chunk end
(Splash `Engine::workEndOf`; `exactTokens` leaves out the pending
anchor). GDN blob adopt/commit stays, with `replay_mtp_snapshot_to(paged
= true)` as the fallback. Each DFlash2 prefill chunk books through
`reclaiming` (Splash `Engine::growLane` → `Engine::allocate` frees, then
retries). A cold DFlash2 prime keeps no prefix chain, so marked
checkpoint pages can be reclaimed.
- **MoE:** the row budget reaches the paged verify as `row_budget`,
clamped to min(budget, 1 + L).
- **One window:** with a draft, the pool lane also charges the DFlash2
state (a second GDN cell + the draft ring, 201,273,344 B). The transient
is the larger of the tapped prefill chunk and the 8-row verify cycle
with its free pool.
- **Load:** a DFlash2 companion with no pool fails the load (CUDA, dense
sym8, paged cache off). Splash has no flat path.
- **Deleted:** the flat DFlash2 turn, its KV booking and growth,
parking, the flat compiled verify (`forward_dflash2_compiled`,
`COMPILED_VERIFY_*`) and its Rust helpers, MoE deferred GDN, the
`MLX_MOE_DFLASH2_*` env switches, the separate speculative window, the
runway hold, and the speculative fields of the published limits (napi +
TS).

## Window (27B + DFlash2, M3 Pro inputs)
| turn | before | after |
|---|---|---|
| DFlash2 | 32,761 | 94,201 |
| AR / MTP / image, on a load with a draft | 102,393 | 94,201 |

6,391 blocks (3,245 MiB). The S4 live capacity gate (LIVE L4) checks
this number on the real load.

## Gaps
- **Speed is not measured.** The flat compiled verify took the flat K/V
as graph inputs, so it could not stay as an A/B arm. The eager paged
verify reads the device ids back to the host and never adopts the GDN
blobs. If LIVE L3 is below 0.90× of the FN2 build, RULES #9 says: build
the compiled paged verify (one fixed 8-row tape) before this merges. The
plan is in LIVE.md.
- **S8 and S9 must merge together.** Until S9, parked DFlash2 states
have no store on the pool. An AR, image or MTP turn drops the live draft
window, and a prefix hit without it prefills the draft from 0. The store
code stays, unused, for S9. The 13 scheduler tests over parked states
and `dflash2_state/tests.rs` are deleted (each one drove a flat DFlash2
turn); S9 brings them back.
- A turn that ends on the length budget runs one extra 1-row forward, so
the last token has a KV row. Splash emits that token without a KV row.
- A refused verify or prefill booking after reclaim fails the turn.
Splash waits or suspends (S11).
- The AR prefill still books the whole prompt (S11).
- The MoE bitwise row-budget test needs a quantized grouped MoE fixture.
The clamp is tested.
- `mlx_segmented_sdpa_forward` (bf16 segmented verify, C++/Metal) has no
library caller now. Its deletion needs a metallib rebuild (follow-up).

## Tests
- 21 named mutations, each red when on and green when off (M1 M2 A1 R1
K1 P1 T0 L1 MM1 B2 W1 W2 T1 C1 LB1 NP1 O3 C11 W0 R0, and R1 of the
reclaim fix: `cold_dflash2_prefill_reclaims_a_marked_live_chain`, dense
and MoE).
- New tests include `paged_dflash2_matches_paged_ar_for_every_keep`
(dense and MoE), `dflash2_cycle_runs_eight_rows_and_commits_keep`,
`paged_dflash2_verify_refuses_a_chunk_that_is_not_eight_rows`,
`dflash2_prefill_books_each_chunk_end`,
`dflash2_takes_the_one_pool_window`, `draft_without_a_pool_is_refused`
and `second_dflash2_turn_resumes_the_live_window`.
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`, `yarn
build:native`, `yarn typecheck`: clean.
- mlx-paged-attn: 16 binaries, 324 passed. mlx-core `--lib`
(`RUST_TEST_THREADS=1`): 4,753 passed, 0 failed. `vp test` on the 7
touched TS test files: 605 passed.
- Reclaim fix (ef025f7): qwen3_5, qwen3_5_moe, engine,
transformer::paged: 1,321 passed, 0 failed.
- After the rebase onto FN2 56a979f: fmt, clippy, `yarn build:native`,
`yarn typecheck` clean; qwen4_exp 238, qwen3_5 445, qwen3_5_moe 139,
engine 543, transformer::paged 192 passed

## Not in this PR (live, not run)
- L0 sanity, L1 lossless DFlash2 vs AR on the pool, L2 teacher-forced
acceptance against the FN2 build, L3 speed at 8K and 64K (RULES #9
gate), L4 S4 capacity at the M3 Pro budget.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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