Skip to content

refactor(engine): per-turn execution planning (TurnPlan/ExecutionPlan) + fail-closed fixes - #94

Merged
Brooooooklyn merged 4 commits into
mainfrom
refactor/inference-plan-fixes
Jul 10, 2026
Merged

Brooooooklyn merged 4 commits into
mainfrom
refactor/inference-plan-fixes

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

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/lm and a new docs/inference-architecture.md. On top of the refactor baseline, three fixes close every blocker found in review:

  • Model loader fails closed — malformed config.json (non-object root, numeric/object architectures) now throws MalformedModelConfigError instead of silently loading as qwen3; LoadableModel is restored to the native @mlx-node/core class union (registry rows carry nativeModelClass), so downstream native-instance assignments keep compiling.
  • Gemma4 media prepare fails closed — media_session_context/paged_text_turn_context are cleared only after the fallible paged prepare succeeds, and the text-delta guards consult session_media(); a block-exhaustion failure now yields the typed IMAGE_CHANGE_REQUIRES_SESSION_RESTART: rejection in both windows (keys set, and warm-continued sessions where provenance lives only in the context).
  • LFM2 delta turns stay paged — supports_delta: true; continuations ride the single existing run_paged_turn warm 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

  • Per-fix: TDD where applicable, cargo clippy --all-targets -- -D warnings, cargo fmt --check, yarn typecheck, vp lint --type-aware --type-check, full cargo test -p mlx-core green.
  • LFM2 E2E on the real 1.2B checkpoint: parity suite 8/8; 3-turn TS session (paged default) cachedTokens 0→494→683 with correct recall answers matching the forced-flat control.
  • Each fix passed a task-scoped adversarial review; the final whole-branch adversarial review returned PASS with zero findings.

Follow-ups (triaged, not blockers)

  • Gemma4 media cores record first_token_instant after 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).
  • Silent MTP→AR fallback on paged checkpoints (mtpCycles: 0 with enableMtp: true) deserves an explicit signal.
  • Dense/MoE plan-helper duplication (qwen3_5 ↔ qwen3_5_moe), gemma4 paged_text_turn_context side-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.rs so each chat turn is planned once from load-time ExecutionPlan and request facts (TurnPlan: media input vs live context, paged attention, speculative decoder, TurnPath). The session core stops chaining has_paged_adapter / vision_turn / mtp_turn probes and instead calls required run_paged_turn, run_speculative_turn, or run_multimodal_turn handlers with bundled MediaInputs and text_delta_media_guard.

Gemma4 advertises media via gemma4_media_plan (truthful encoders vs backend-validated admission), tracks persistent media_session_context, and only clears media provenance after a successful paged prepare so failed prepares still fail closed through session_media(). LFM2 sets supports_delta: true so 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.json errors, LoadableModel compile-time probes); docs/inference-architecture.md is linked from CLAUDE.md.

Reviewed by Cursor Bugbot for commit 8c0f052. Bugbot is set up for automated code reviews on this repo. Configure here.

Brooooooklyn and others added 4 commits July 10, 2026 16:06
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]>
@cursor

cursor Bot commented Jul 10, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f42e69a4-fbc3-44d1-a754-7653bacb587b

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/inference-plan-fixes

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.

❤️ Share

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

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread packages/lm/src/models/model-loader.ts Resolved
@Brooooooklyn
Brooooooklyn merged commit 5138310 into main Jul 10, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the refactor/inference-plan-fixes branch July 10, 2026 10:18
Brooooooklyn added a commit that referenced this pull request Jul 22, 2026
…/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]>
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.

1 participant