Repository navigation
feat(output-store): add training output persistence with libsql - #9
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit 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. 📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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. Usingunwrap_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_stringfails for tool call arguments, an empty string is stored. Consider logging or propagating this error, or at minimum usingunwrap_or_elseto 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 = 0gives 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 resultsAlso 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 & testsThe DDL and
init_schemaloop look correct for the current static SQL, and comment-stripping plustrim().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 orexecute_batch-style helper) instead of a rawsplit(';').- The unit test only asserts that key
CREATE TABLE/CREATE INDEXsubstrings exist. A lightweight in-memory test that actually callsinit_schemaon 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-exportsThe module-level docs, internal submodules, and
pub useofOutputStoreplustypes::*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 namingThe 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) tooutput-store-test-${Date.now()}.dbto 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_recordinglogic mirrorstrain_step_auto; consider deduplicationThe new method correctly:
- Reuses the same generation path and
IntermediateGenerationResultstruct astrain_step_auto.- Builds
RewardOutput[]viabuild_reward_outputs, serializes to JSON once, and conditionally retains a copy whenrecord_outputsis true.- Applies the same degenerate-output filtering (length-based, per-completion) with consistent handling of
valid_indices,effective_group_size, andusable_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_autoandtrain_step_auto_with_recording, which will be easy to get out of sync over time. When convenient, consider extracting shared helpers for:
- The generation +
IntermediateGenerationResultconstruction.- 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 intotrainStepAutoandtrain()looks correct; consider stronger run-finalization guaranteesThe training integration changes are coherent:
trainStepAutonow:
- Lazily initializes the output store via
ensureOutputStoreInitialized()for low-level users.- Chooses
trainStepAutoWithRecordingand passesrecordOutputs = !!this.outputStore, so recording only happens when an store exists.- On success, conditionally calls
recordStepFromOutputswithcurrentStep, metrics, full outputs JSON, rewards, and configuredgroupSize, 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 callsflush().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 attemptendRun('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:
- Adding a comment warning about SQL injection risks if user input is passed
- 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
UPDATEstatements execute separately on the same run record. If the second update fails, the run would haveended_atandstatusset but an incorrecttotal_stepsvalue. Wrap both operations in a transaction, following the pattern already established inrecord_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
⛔ Files ignored due to path filters (1)
yarn.lockis 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.tscrates/mlx-core/Cargo.tomlcrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/lib.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/output_store/reader.rscrates/mlx-core/src/output_store/schema.rscrates/mlx-core/src/output_store/store.rscrates/mlx-core/src/output_store/types.rscrates/mlx-core/src/output_store/writer.rscrates/mlx-core/src/tools/mod.rspackage.jsonpackages/core/index.cjspackages/core/index.d.ctspackages/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.rscrates/mlx-core/src/output_store/writer.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/tools/mod.rscrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/output_store/schema.rscrates/mlx-core/src/output_store/reader.rscrates/mlx-core/src/output_store/types.rscrates/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.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/tools/mod.rscrates/mlx-core/src/output_store/schema.rscrates/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.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/tools/mod.rscrates/mlx-core/src/grpo/engine.rscrates/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.rscrates/mlx-core/src/output_store/mod.rscrates/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.cjspackages/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.rscrates/mlx-core/src/grpo/engine.rscrates/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.rscrates/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.rspackages/core/index.d.ctspackages/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.rspackages/core/index.d.ctspackages/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-parserappears 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
rawContentfield 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
RETURNINGclauses 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:queryRawallows 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
queryRawvalidate or sanitize SQL if the query string could come from external/user input.
2998-3002: LGTM onrawContentfield 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
Deserializederive with#[serde(default)]onraw_contentensures 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
rawContentfield 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: ExposeOutputStorefrom CJS bindingThe new export is consistent with the existing native binding re-export pattern and correctly surfaces
OutputStoreto consumers.crates/mlx-core/src/lib.rs (1)
7-26: Wireoutput_storemodule into crate rootAdding
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:TrainStepResultWithOutputsmatches intended TS-facing APIThe new NAPI object cleanly extends
TrainStepResultwith an optionaloutputs_jsonfield for serializedRewardOutputdata 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 conversionThe updated
rewardCallbackcorrectly:
- Parses the JSON
Vec<RewardOutput>from Rust.- Converts
completion.tool_callsfrom snake_case to camelCase, includingraw_content→rawContent.- Preserves
statusanderrorfields while keepingargumentstyped as aRecord<string, unknown>.This matches the unified
RewardOutputAPI expectation (pre-parsedtoolCalls, extractedthinking, 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 interfacesThe 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 andi64/f64for counts and metrics is appropriate for the underlying SQLite schema.RewardStats: Defaultreturning 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. TheRwLockallows 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_configrouting logic correctly prioritizes embedded replica mode when all three config options are present.
176-199: LGTM!The
start_runmethod 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
flushmethod 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.
There was a problem hiding this comment.
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
OutputStoremodule 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
GRPOTrainervia optional configuration with lazy initialization - Added
raw_contentfield toToolCallResultfor 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.
591b8bc to
f780281
Compare
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]>
f780281 to
db3196a
Compare
There was a problem hiding this comment.
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 logicThe recording variant faithfully reproduces generation, reward building, degenerate filtering, and training/NaN-handling paths from
train_step_auto, and only adds the optionaloutputs_jsonplumbing. 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: boolflag and returns(TrainStepResult, Option<String>), withtrain_step_autodelegating to it and discarding the JSON, whiletrain_step_auto_with_recordingforwards 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 correctThe addition of
raw_contentwith#[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, andCompletionInfo/RewardOutputgainingDeserializeis aligned with OutputStore needs.Only minor nit to keep in mind:
ToolCallResult::missing_namenow embeds the entire raw snippet intoerror, 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 fullraw_contentfield.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 newTrainStepResultWithOutputsshape.- The
OutputStoreclass plusOutputStoreConfig,GenerationRecord,ToolCallRecord,StepRecord,StepSummary,GenerationWithToolCalls,RewardStats, andTrainingRunRecordprovide a coherent, well-documented TS API for both recording and querying training runs.ToolCallResult.rawContent: stringmatches the Rustraw_contentfield and the tests’ expectations, giving a clear path from parser → RewardOutput → OutputStore (viaToolCallRecord.rawContent).Two small optional suggestions:
- In
OutputStore.queryRaw(sql: string), consider explicitly documenting that callers should not pass untrusted input directly intosql, 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 thatoutputsJsonmust be the serializedRewardOutput[]for exactlygroupSize * numPromptscompletions, 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 rawContentIncluding realistic
rawContentstrings on the ToolCallResult mocks keeps these tests aligned with the updated interface (requiredrawContent: string) and with what the Rust parser now emits. You’re already validating the important semantic fields; adding an assertion onrawContentwould 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 rawContentThe additional
rawContentfields 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 onrawContentwould 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, andtool_callsline 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 simplesplit(';')+ 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 to0.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 thattc.argumentsis already a deserialized type, this is unlikely to fail, but consider usingunwrap_or_elsewith 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
⛔ Files ignored due to path filters (1)
yarn.lockis 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.tscrates/mlx-core/Cargo.tomlcrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/lib.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/output_store/reader.rscrates/mlx-core/src/output_store/schema.rscrates/mlx-core/src/output_store/store.rscrates/mlx-core/src/output_store/types.rscrates/mlx-core/src/output_store/writer.rscrates/mlx-core/src/tools/mod.rspackage.jsonpackages/core/index.cjspackages/core/index.d.ctspackages/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.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/output_store/writer.rscrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/lib.rscrates/mlx-core/src/tools/mod.rscrates/mlx-core/src/output_store/reader.rscrates/mlx-core/src/output_store/store.rscrates/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.cjspackages/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.cjscrates/mlx-core/src/grpo/engine.rspackages/trl/src/trainers/grpo-trainer.tspackages/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.rscrates/mlx-core/src/output_store/mod.rscrates/mlx-core/src/lib.rscrates/mlx-core/src/tools/mod.rscrates/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.rscrates/mlx-core/src/lib.rscrates/mlx-core/src/output_store/store.rscrates/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.rscrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/output_store/reader.rscrates/mlx-core/src/output_store/store.rscrates/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.rscrates/mlx-core/src/grpo/engine.rscrates/mlx-core/src/lib.rscrates/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.tscrates/mlx-core/src/tools/mod.rspackages/trl/src/trainers/grpo-trainer.tspackages/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 theauthTokenis explicitly removed from the config before being persisted viaOutputStore.startRun. The export is safe.crates/mlx-core/src/grpo/engine.rs (1)
212-225: TrainStepResultWithOutputs struct matches existing metrics shape and NAPI usageThe new NAPI object cleanly extends
TrainStepResultwith an optionaloutputs_jsonfield, matching the TS-sideTrainStepResultWithOutputs.outputsJson?: stringand preserving the existing metrics/completions/rewards contract.crates/mlx-core/src/lib.rs (1)
16-16: Exporting output_store module from crate root is correctThe 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 usageAdding
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
OutputStoreand 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
afterEachare 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 (
endSteponly,statusonly). 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
recordStepFromOutputsrejectsgroup_size=0with 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_stepfunction correctly uses a transaction to ensure all inserts (step, generations, tool_calls) succeed or fail together. The use ofRETURNINGclauses 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 inpackages/core/index.d.cts. TheDefaultimplementation forRewardStatsprovides 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
enabledflag 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
authTokenbefore persistence- Fallback to
this.config.modelPathat 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
endRunandflushare called with appropriate status on training completion. ThestopRequestedflag 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 == 0is in place.
556-642: JSONL export with buffered writing.The export uses
BufWriterfor 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
OutputStoreusesArc<RwLock<Connection>>for concurrent access, with read locks for queries and write locks for mutations. Thecurrent_run_idis also protected byRwLockfor safe concurrent access.
95-143: Embedded replica mode with initial sync.The
embedded_replicafactory 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_configfactory 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_msnow uses.expect("system clock is set before UNIX_EPOCH")instead of.unwrap(), providing clear context if this edge case ever occurs.
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]>
…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]>
…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
…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
…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
…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
…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
…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
…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.
…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.
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]>

Add OutputStore for recording training outputs to SQLite (local) or Turso (remote).
Features:
Fixes from review:
🤖 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.
mlx-core/output_storemodule (schema, reader, writer, NAPIOutputStore) with local/remote/embedded-replica support vialibsql; queries for runs/steps/generations/tool-calls/reward stats; JSONL exporttrain_step_auto_with_recordingreturning optionaloutputs_jsonfor zero-copy persistence;ToolCallResult/CompletionInfo/RewardOutputnow deserializable and includeraw_content(with#[serde(default)]); parser preserves raw tool-call contentOutputStore(lazy init with promise mutex, start/end run,recordStepFromOutputs, optional cloud sync); newoutputStoreconfig blockOutputStorelifecycle/query/edge-case tests; chat/tool tests updated forrawContentOutputStoreand types inpackages/core, add workspacelibsqldep and devoxc-parserWritten by Cursor Bugbot for commit db3196a. This will update automatically on new commits. Configure here.
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.