Repository navigation
refactor(engine): per-turn execution planning (TurnPlan/ExecutionPlan) + fail-closed fixes - #94
Conversation
Baseline snapshot of the uncommitted planner refactor so blocker fixes land as reviewable commits on top. Co-Authored-By: Claude Fable 5 <[email protected]>
…LoadableModel contract
Fix A: normalizeConfig rejects a config.json whose root is not a plain
JSON object or whose architectures field is neither an array nor a
string (MalformedModelConfigError, rethrown intact past detectModelType's
broad catch) instead of coercing to {}/[] and silently resolving to the
qwen3 nullish-model_type default. Blessed lenient shapes are unchanged:
{} root, missing/null architectures, bare-string architectures, and
non-string array entries.
Fix B: every registry row carries its native @mlx-node/core class
(nativeModelClass, generalizing nativeTrainerModelClass), and the public
LoadableModel union derives from those native classes again — restoring
the pre-refactor contract where native model instances are assignable to
LoadableModel/TrainableModel and flow directly into the Rust trainer
engine factories. Compile-time assignability probes added to
model-loader-types.test.ts.
Co-Authored-By: Claude Fable 5 <[email protected]>
Both vision cores cleared media_session_context and paged_text_turn_context BEFORE the fallible paged prepare, so a block-exhaustion failure left the session with media-expanded history but no provenance; after a warm text continuation (raw media keys already dropped by save_paged_history) the next text delta was silently admitted and re-prefilled image/audio placeholder positions from raw token embeddings. - Move both context clears into the success-only clear block in vision_paged_turn_sync_core and vision_paged_turn_stream_core; the media_session_continuable disarm stays ahead of the prepare (a stale armed marker could wrongly warm-continue against a partially prepared request). - Read session_media() (raw keys ∪ persistent context) instead of the raw keys in text_delta_media_guard's non-continuable branches and in verify_cache_prefix's media gate, so the surviving context alone rejects the delta with the typed IMAGE_CHANGE_REQUIRES_SESSION_RESTART error and forces a prefix miss. Without this the preserved context was dead state: the marker=false + keys=None + context-set combination admitted the delta. - Unit test drives the warm-continued state through the real transitions and pins both gates plus the fail-open counterfactual. Co-Authored-By: Claude Fable 5 <[email protected]>
…orruption With the paged adapter live, a fresh LFM2 turn writes attention K/V only into the paged pool (flat attention caches stay empty) while conv state lands in flat slots and save_paged_history persists only the token history. Declaring supports_delta:false then routed chat_session_continue deltas to the generic flat tail, which tail-prefilled just the delta onto empty attention KV at offset 0 with conv state warm at position ~N — degenerating into input-independent garbage. Declare supports_delta:true instead and drop the fresh-only debug_assert: the session core already rebuilds the full token stream (history ++ delta) before plan resolution, so a delta reaches the ONE existing run_paged_turn path as the exact strict extension a resent growing conversation produces — the adapter warm-continues the live request (ContinuedLivePrefix) and conv Pass-1 (run_conv_only_prefill) rebuilds short-conv state over the cached prefix. No new loop, no signature change. Oracle strengthening: new lfm2_paged_delta_memory_probe_parity plants amber=7/cobalt=11, asks the sum on a delta (18), extends with jade=13 and re-derives (31) — content assertions on both the paged session and the forced-flat control, plus strictly-growing cached_tokens proving the deltas took the paged warm-continue. Byte-parity is deliberately not asserted at these answer-capable lengths (the accepted ~1-ULP paged-vs-flat near-tie class flips greedy argmax mid-think there); it stays pinned by the short-length tests (a)/(a2)/(b2)/(c) — (c)'s delta turn now runs paged and still matches flat byte-for-byte. Gates: clippy -D warnings + fmt clean; yarn build:native; parity suite 8/8 with the real 1.2b checkpoint; TS 3-turn E2E paged (cachedTokens 0→494→683, answers 18/31) == forced-flat control answers; planner lib tests 20/20; lfm2_session gated suite 12/12. Co-Authored-By: Claude Fable 5 <[email protected]>
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_974ef0a9-e133-46ab-82ab-71669380667a) |
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8c0f05214a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…/main
The 396-commit rebase onto origin/main replayed cleanly (our-owned model/
engine files taken as our whole file to converge), but git AUTO-MERGED the
shared wasm-compiled files with main's native-oriented changes without
conflict — and those auto-merges broke the wasm build by referencing symbols
the wasm target does not have:
- crate::quant (gated out of wasm) from quant_dispatch.rs
- sys fns mlx_to_fp8 / mlx_eval_with_error / mlx_array_deep_copy (native-only)
from array/creation.rs, array/data.rs
- main's new convert fns reject_awq_for_prequantized_body /
has_qwen35_hybrid_weight_shape from a main-kept gguf.rs, while convert.rs
is our version (seam)
- main's mlx_paged_stubs_linux.cpp variant (20 C++ errors on wasm)
Fix: reset every wasm-COMPILED file that diverged back to the branch's proven
versions, so the wasm surface == the branch's known-green surface. The
native-only-gated modules (engine #94 TurnPlan refactor, grpo, calibration,
gemma4 dspark/assistant, qianfan_ocr — all #[cfg(not(target_family="wasm"))])
keep main's versions; they are not in the wasm build. Also aligned
.yarnrc.yml to yarn 4.17.1 (the release binary main ships).
Verified: `build:wasm` green — Finished wasi profile, Copied WASM, 0 errors.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Summary
vLLM-aligned per-turn execution planning: a new
engine/plan.rs(TurnPlan/ExecutionPlan) replaces scattered per-family probes so paged/flat/speculative routing and delta-turn admission are decided in one typed place, plus a model-loader registry rework in@mlx-node/lmand a newdocs/inference-architecture.md. On top of the refactor baseline, three fixes close every blocker found in review:config.json(non-object root, numeric/objectarchitectures) now throwsMalformedModelConfigErrorinstead of silently loading as qwen3;LoadableModelis restored to the native@mlx-node/coreclass union (registry rows carrynativeModelClass), so downstream native-instance assignments keep compiling.media_session_context/paged_text_turn_contextare cleared only after the fallible paged prepare succeeds, and the text-delta guards consultsession_media(); a block-exhaustion failure now yields the typedIMAGE_CHANGE_REQUIRES_SESSION_RESTART:rejection in both windows (keys set, and warm-continued sessions where provenance lives only in the context).supports_delta: true; continuations ride the single existingrun_paged_turnwarm strict-extension path (adapter block reuse + conv Pass-1 reconstruction). This ends the reproduced corruption where a paged fresh turn + flat delta tail-prefilled onto never-populated flat attention KV and emitted input-independent repeated<think>tokens. The parity suite gains a content-sensitive memory-probe oracle (the old one passed on a 48-token context-insensitive prompt).Verification
cargo clippy --all-targets -- -D warnings,cargo fmt --check,yarn typecheck,vp lint --type-aware --type-check, fullcargo test -p mlx-coregreen.Follow-ups (triaged, not blockers)
first_token_instantafter the decode loop (invalid media TTFT/decode telemetry; pre-existing from Chat-engine refactor: model-neutral engine (P1–P8) + honor generation_config.json (#38) #70).mtpCycles: 0withenableMtp: true) deserves an explicit signal.paged_text_turn_contextside-channel → explicit save-context parameter, registry-derived draft-model error message.🤖 Generated with Claude Code
Note
High Risk
Changes core chat routing, speculative/media session semantics, and model detection fail-closed behavior across many families; incorrect planning or Gemma4 media state would corrupt KV reuse or mis-load checkpoints.
Overview
Introduces
engine/plan.rsso each chat turn is planned once from load-timeExecutionPlanand request facts (TurnPlan: media input vs live context, paged attention, speculative decoder,TurnPath). The session core stops chaininghas_paged_adapter/vision_turn/mtp_turnprobes and instead calls requiredrun_paged_turn,run_speculative_turn, orrun_multimodal_turnhandlers with bundledMediaInputsandtext_delta_media_guard.Gemma4 advertises media via
gemma4_media_plan(truthful encoders vs backend-validated admission), tracks persistentmedia_session_context, and only clears media provenance after a successful paged prepare so failed prepares still fail closed throughsession_media(). LFM2 setssupports_delta: trueso session continuations stay on the generic paged path instead of flat tail-prefill on empty attention KV.The @mlx-node/lm loader gains broad registry/detection tests (architecture precedence, malformed
config.jsonerrors,LoadableModelcompile-time probes);docs/inference-architecture.mdis linked fromCLAUDE.md.Reviewed by Cursor Bugbot for commit 8c0f052. Bugbot is set up for automated code reviews on this repo. Configure here.