Skip to content

Add Gemma 4 E4B and 31B as downloadable model options (#1094) - #1134

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1094-gemma-4-models
May 17, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1094-gemma-4-models

Conversation

@malibio

@malibio malibio commented May 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds Gemma 4 E4B (~5.0 GB, 16GB+ Apple Silicon) and 31B (~18.7 GB, 24GB+) to the model registry alongside Ministral 3B/8B, downloadable from ggml-org/gemma-4-*-it-GGUF. No HuggingFace login required (public, official llama.cpp-team repos using Xet storage).
  • Switches apply_chat_template to apply_chat_template_oaicompat (use_jinja: true) — handles Mistral + Gemma 4 on a single code path via llama.cpp's common_chat_* machinery. Fixes the ffi error -1 Gemma 4 hit on the old C API.
  • Extends the tool-call parser with a "Format C" path that accepts both Mistral ({name, arguments}) and Gemma 4 ({tool_name, tool_args}) schemas via dual-deserialization.
  • First-launch recommendation now picks Gemma 4 by RAM tier (E4B for <32 GB, 31B for ≥32 GB). recommended_model_id_for(family) lets callers ask for the right size within a user-chosen family.

Deviations from the issue body

  1. No manual build_gemma4_prompt formatter. The nodespace-nlp-experiment repo (see its README, Experiments 1-5) validated that switching everyone to apply_chat_template_oaicompat + use_jinja: true on llama-cpp-2 v0.1.146 handles Gemma 4 natively — cleaner than a manual formatter and no per-family prompt dispatch. The Jinja upper-on-Array bug is fixed in ggml-org's April 12+ GGUFs.
  2. 31B, not "27B". Gemma 4's dense large variant is 31B; "27B" was a Gemma 2 size. The intent (larger quality tier for 24GB+ Apple Silicon) is preserved.
  3. Phase 1 validation cited, not re-run. ../nodespace-nlp-experiment/README.md documents PASS for Experiments 2-5 with Gemma 4 E4B Q4_K_M on llama-cpp-2 v0.1.146. Tool calling, dual-model loading, context stress, and download behavior all validated.

What changed

File Change
packages/agent/src/agent_types.rs Add Gemma4 variant to ModelFamily; add family field to ChatModelSpec.
packages/agent/src/local_agent/model_manager.rs Add GEMMA_4_E4B and GEMMA_4_31B catalog entries; add family_for(model_id) and recommended_model_id_for(family) helpers; centralize empty-sha256 policy doc.
packages/agent/src/local_agent/inference.rs LlamaChatInferenceEngine::load takes family: ModelFamily; model_info() returns it.
packages/agent/src/local_agent/ollama_inference.rs ModelFamily::Ollama in spec.
packages/desktop-app/src-tauri/src/commands/local_agent.rs Look up family from registry when loading the engine.
packages/desktop-app/src/lib/types/agent-types.ts Widen ModelFamily to 'ministral' | 'gemma4' | 'ollama'.
packages/nlp-engine/Cargo.toml Bump llama-cpp-2 floor to >=0.1.146.
packages/nlp-engine/src/chat/mod.rs Rewrite apply_chat_template to use apply_chat_template_oaicompat; tools passed via tools_json; AddBos::Never to avoid double-BOS. detect_tool_calls_token hoisted out of the inference hot path and cached per-model.
packages/nlp-engine/src/chat/parser.rs Format C dual-deserialization (MistralCallObject / GemmaCallObject); shared find_balanced(open, close) helper; 8 new tests.

Test plan

  • cargo test -p nodespace-nlp-engine --lib chat::parser — 45 pass (37 existing + 8 new Gemma 4 cases).
  • cargo test -p nodespace-agent --lib local_agent::model_manager — 22 pass (incl. new list_includes_gemma4_entries_with_correct_metadata and recommended_model_id_for_family_returns_family_match).
  • cargo test -p nodespace-agent --lib — 235 unit tests pass.
  • cargo test -p nodespace-nlp-engine --lib — 60 unit tests pass.
  • bun run test — 3918 frontend tests pass (matches baseline).
  • bun run quality:fix — 0 ESLint errors/warnings, 0 svelte-check issues, cargo fmt, cargo clippy --all-targets -- -D warnings clean.
  • cargo clippy -p nodespace-agent --features testing --tests -- -D warnings clean (PR Gate AgentSession.system_prompt_override behind testing feature (closes #1093) #1132 testing feature gate preserved through rebase).

Required before merge

🟡 Ministral tool-call smoke test — the agreed mitigation for the captured-prompt regression test the reviewer flagged but we skipped (the test would have required loading a real GGUF in CI, which is currently unstable under parallel Metal contention). One round of Ministral 3B or 8B with a real tool, asserting the parser still extracts a tool call from the OAI-compat-formatted output. Result must be noted on this PR before merge.

🟡 Manual E2E (M2 Pro 16 GB) — download Gemma 4 E4B → load → chat streams → tool-call detected. The chat-template path change makes this the highest-value end-to-end signal.

Known pre-existing test infrastructure failures (unrelated)

nodespace-agent's ollama_integration suite has 8 failures that require a configured Ollama daemon and downloaded models; nodespace-nlp-engine's embedding integration_tests hang under parallel Metal contention when run alongside other suites. Neither touches code modified here.

Deferred to follow-up

Closes #1094.

🤖 Generated with Claude Code

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic Code Review — PR #1134

Review Type: Initial Review
Branch: worktree-issue-1094-gemma-4-models
Commits since base: 1 (abfe5672)
Issue: #1094


Summary

A focused, well-architected change that delivers Gemma 4 E4B/31B support by leveraging llama.cpp's OAI-compat Jinja machinery instead of inventing per-family prompt formatters. The parser additions are surgical and well-tested (8 new tests covering object form, array form, OpenAI-style fallback, mixed schemas, and error cases). The chat-template rewrite is the boldest change but is plausibly correct based on the PR description's reference to validated experiment results.

However, there is one blocker that has nothing to do with Gemma 4: this branch was cut before PR #1132 landed on main, and merging as-is will silently revert that PR's gating of system_prompt_override behind the testing feature. This needs to be resolved before merge.


Requirements Check (Issue #1094)

Criterion Status Notes
Gemma 4 E4B experiments 2-5 completed and documented partial PR description cites validation in ../nodespace-nlp-experiment (Phase 1) but does not re-run in this repo. Reasonable given experiment-repo separation; acceptable.
ModelFamily enum defined; all registry entries carry family yes agent_types.rs:294-301 + model_manager.rs:42,54,68,83,99
All per-family dispatch branches on ModelFamily — no string sniffing yes family_for() (model_manager.rs:222) looks up by id; LlamaChatInferenceEngine::load (inference.rs:34) receives family directly. No filename heuristics.
build_gemma4_prompt implemented intentionally deviated Replaced by apply_chat_template_oaicompat (chat/mod.rs:507). Documented in PR body. Net simpler — preferable.
apply_chat_template works for Gemma 4 — no ffi errors yes Rewritten path uses the OAI-compat function which routes through llama.cpp's common_chat_* layer.
Streaming parser handles both schemas yes Format C added in parser.rs:120-199; dual-deserialization in parse_tool_call_object (parser.rs:51-65).
Gemma 4 E4B and 31B registered with download URL, SHA256, and size partial URLs and sizes present; SHA256 fields are intentionally empty for all four catalog entries (skip-verification policy). Issue body asked for SHA256 explicitly. See finding 7.
Both models appear in UI with hardware requirements not in this PR UI surface unchanged — model-store.svelte.ts mock still only has Ministral entries; no rendering changes in the desktop-app's chat panel for Gemma. Real-app path goes through Tauri command chat_model_list which returns the new entries, so they will appear, but no hardware-requirement metadata or labels exist in the schema. See finding 8.
Download / load / chat work end-to-end on M2 Pro 16GB acceptance not demonstrated in PR Cited as validated in experiment repo.
Tests pass yes Per PR description: 305 + 60 Rust + 3918 frontend, quality:fix clean.
quality:fix clean yes Per PR description.

Findings

CRITICAL — Branch is behind main; merging reverts PR #1132

Files affected: packages/agent/src/agent_types.rs:550-552, packages/agent/src/local_agent/agent_loop.rs:44-58, 236-244, 851-855, 880-895

This PR's diff against origin/main shows wholesale removal of the #[cfg(any(test, feature = "testing"))] gating around AgentSession.system_prompt_override, the session_prompt_override accessor function, and LocalAgentService::set_system_prompt. That gating did not exist when this branch was cut, but it was added on main by PR #1132 (a992b3de, merged 2026-05-17) which explicitly closed issue #1093.

The PR #1132 commit message is unambiguous about intent:

system_prompt_override and the set_system_prompt method were test infrastructure embedded in a production, Tauri-serialized struct. They are now gated by a testing Cargo feature on nodespace-agent, so production builds compile without the field, the method, or the override branch in run_turn.

Concrete evidence the gating is now absent in this branch:

  • agent_types.rs:551 — pub system_prompt_override: Option<String>, has no #[cfg] attribute.
  • agent_loop.rs:887 — pub async fn set_system_prompt(...) has no #[cfg] attribute.
  • packages/agent/Cargo.toml — has no [features] table, so the testing feature is undeclared. PR #1132 was supposed to add it; this branch lacks it.

Net effect if merged: a test-only API hook becomes part of the production Tauri/serde surface again, undoing #1132 silently because there are no conflict markers — the lines simply re-appear without their guards.

Recommendation:

  1. Rebase this branch onto current origin/main (which is 3 commits ahead: 82f14bfb, 8a9e0cd1, 5e7ef289). The #1132 gating will then be present and the Gemma 4 changes can be replayed cleanly on top.
  2. After rebase, re-verify both cargo clippy --all-targets -- -D warnings (no features) and cargo clippy -p nodespace-agent --features testing --tests -- -D warnings (matching PR #1132's verification).
  3. Re-confirm the [[test]] required-features = ["testing"] declaration on the ollama integration target.

Engineering principle: Branch hygiene — never ship a diff that silently reverts a sibling change to the same module. A clean rebase makes the reviewer's diff reflect only the intended functional change.


IMPORTANT — Doc comment on ModelFamily::Gemma4 still says "27B"

File: packages/agent/src/agent_types.rs:297

/// Gemma 4 -- Google's multimodal model series (E4B, 27B).
Gemma4,

The catalog and PR description correctly use 31B (Gemma 4's actual dense large variant; 27B was a Gemma 2 size). This doc comment is the last stale "27B" reference. Trivial to fix and avoids reader confusion when grepping for "27B" later.

Recommendation: Change to (E4B, 31B).

Engineering principle: Documentation drift causes future bugs — a future contributor seeing "27B" in the public-facing doc may hunt for a 27B variant that doesn't exist.


IMPORTANT — Mistral tool-call format change is a real behaviour change, not just a refactor

File: packages/nlp-engine/src/chat/mod.rs:499-598

The PR description notes this risk; flagging that it does materially alter what reaches the model for Mistral too. Previously, the codebase hand-injected [AVAILABLE_TOOLS]...[/AVAILABLE_TOOLS] text into the system prompt before calling the C-level apply_chat_template. Now, tools are passed via tools_json and the Jinja template inside the Mistral GGUF formats them. These two paths should produce equivalent strings only if Mistral's embedded Jinja template implements the same [AVAILABLE_TOOLS] wrapper. The Mistral 3B/8B 2512 GGUFs (the ones registered in the catalog) ship with such a Jinja template, but I have no independent verification of byte-for-byte equivalence to the prior hand-injected form.

Observed coverage: Format B ([TOOL_CALLS]name{json}) parsing tests still pass, but those operate on parser input, not on prompt content produced by the new template path. The PR cites validation in ../nodespace-nlp-experiment but I cannot inspect that repo from this review.

Recommendation:

  1. Before merge, run one live Ministral 3B/8B tool-calling smoke test (e.g., re-run the ollama_integration test against a local GGUF) and confirm parse rate is unchanged.
  2. If feasible, add a Rust integration test that captures the prompt string produced by apply_chat_template for a Ministral model + a known tool list, and asserts the string contains the expected [AVAILABLE_TOOLS] block. This pins behaviour against future llama.cpp template churn.

Engineering principle: Refactors that touch shared code paths (Mistral was working; this PR's primary goal is Gemma 4) deserve regression evidence for the previously-working path, not just for the new one.


IMPROVEMENT — parse_format_b returns a Result but stores the error variant in the Ok arm

File: packages/nlp-engine/src/chat/parser.rs:280-308

fn parse_format_b(after_sentinel: &str) -> std::result::Result<(String, &str, &str), ParseResult> {

Using ParseResult (which is an enum that includes a non-error PlainText variant) as the Err type of an internal Result is unusual. It compiles and works because callers only construct ParseResult::Error(...) in the Err arm, but it inverts the conventional semantics of Result. A reader who sees Err(ParseResult::PlainText(...)) later would be confused.

Recommendation: Either return a Result<(String, &str, &str), String> and let the caller wrap into ParseResult::Error, or define a small private FormatBError(String) type. Pure ergonomics — non-blocking.

Engineering principle: Idiomatic types — Result<T, E> where E is itself a sum type containing non-error variants is a code smell that costs reviewer cognition.


IMPROVEMENT — tool_calls_token_id detection scans IDs 0..20 linearly per inference run

File: packages/nlp-engine/src/chat/mod.rs:336-354

This detection loop runs every call to generate_blocking and decodes up to 20 token pieces just to find the [TOOL_CALLS] control token. The cost is tiny per-call but the lookup is pure-model metadata — it can be computed once at load time and cached in ChatLlamaState. Doing so also makes it easy to extend later for Gemma 4 if Gemma 4 ever ships a similar control token (this PR's parser handles Gemma 4's tool calls via stream text, but a future model might need a different control token).

Recommendation: Compute tool_calls_token_id in ChatLlamaState::new or in get_or_create_context, store as Option<LlamaToken>, and read it in generate_blocking. Non-blocking.

Engineering principle: Hoist invariant computation out of hot paths; especially when the cost is unbounded by a magic number (0..20) that itself encodes an assumption ("control tokens are always low IDs") that could quietly break.


IMPROVEMENT — Mock test sites use ModelFamily::Ministral as placeholder

Files: packages/agent/src/local_agent/agent_loop.rs:1091, packages/desktop-app/src-tauri/tests/agent_e2e.rs:139, 1559

The PR description flags this. The mocks are not asserting anything about family, so the placeholder is technically harmless. But: as ModelFamily grows, having tests blanketly default to one family hides any code paths that branch on family. The cheapest mitigation is to use different families for different mock engines — e.g., the CapturingMockEngine (which tests prompt assembly) could declare family: ModelFamily::Gemma4, letting it exercise the Gemma-4-specific message-list handling path the moment any such branching is added.

Recommendation: Optional. Switch one of the mocks (e.g., CapturingMockEngine since it's already prompt-focused) to ModelFamily::Gemma4. Non-blocking.

Engineering principle: Mocks should diversify on dimensions the production code branches on; uniform mocks hide future bugs.


IMPROVEMENT — Empty sha256 for Gemma 4 entries is policy-inherited from Ministral but worth a brief comment

File: packages/agent/src/local_agent/model_manager.rs:89, 105

Both new catalog entries set sha256: "" with the comment "Skip verification — official ggml-org repo (llama.cpp team), Xet storage". The existing Ministral entries set sha256: "" with a similar justification ("official Mistral repo, Xet storage"). The download code (perform_download, line 697) correctly checks for empty string and logs the skip.

This is consistent with existing policy. However, the issue body explicitly says "SHA256, and size" for both Gemma 4 entries. If Xet storage's tamper-evidence is the rationale for accepting empty hashes, that rationale belongs in a central comment (e.g., on the CatalogEntry::sha256 field at line 47) rather than repeated four times. Future contributors might think "I should compute the hash" without realizing it's a deliberate policy.

Recommendation: Add a paragraph to the sha256 field doc explaining the Xet-backed-repos policy. Non-blocking; pre-existing.

Engineering principle: Centralize justifications for deviations from documented requirements; per-instance comments are how policy decisions go undocumented.


IMPROVEMENT — UI hardware-requirement labels not surfaced

File: packages/desktop-app/src/lib/types/agent-types.ts:282-300, packages/desktop-app/src/lib/stores/model-store.svelte.ts

Issue #1094 acceptance criterion: "Both models appear in model selection UI with hardware requirements visible." The Rust ModelInfo struct carries no min_memory_gb field, and the TS type's ModelInfo doesn't either. The catalog entries in the issue's spec sketch had min_memory_gb: u8 but the actual CatalogEntry struct in model_manager.rs:36-49 omits it. So the UI has nothing to display.

This may be intentionally deferred (e.g., a follow-up UI issue), but the PR closes #1094 — which lists this as an unchecked acceptance criterion. Two reasonable resolutions:

  1. Add a small min_memory_gb (or min_ram_gb) field to CatalogEntry + ModelInfo + the TS type, with E4B=16, 31B=24, Ministral 3B=8, Ministral 8B=16. Surface it in the model selection list.
  2. Don't claim "closes #1094" in the commit message; reference it as "Phase 4 of #1094" and open a follow-up UI issue.

Recommendation: Either land the hardware-requirement metadata in this PR or update the closes/references wording. Non-blocking for the Rust changes, but the acceptance-criteria record should match reality.

Engineering principle: "closes #X" should mean every checkbox in X is done; otherwise the issue closure misrepresents project state.


NIT — [TOOL_CALLS][ (lone bracket, no [ARGS]) returns "Unbalanced brackets in tool call array"

File: packages/nlp-engine/src/chat/parser.rs:160-167

When a malformed input has [TOOL_CALLS] followed by a [ that does not begin [ARGS] and does not close, the error message says "tool call array". For a debugging engineer this might be misleading — they may go hunt the JSON array branch when really the input is incomplete. Tiny issue; only matters for malformed model outputs (essentially never happens in production).

Recommendation: Optional message tweak: "Unbalanced brackets after [TOOL_CALLS]". Non-blocking.


NIT — find_balanced_bracket and find_balanced_brace are near-duplicates

File: packages/nlp-engine/src/chat/parser.rs:314-345, 351-382

The two functions differ only in the '['/']' vs '{'/'}' chars. A small generic fn find_balanced(s: &str, open: char, close: char) -> Option<usize> would dedupe. Non-blocking.

Engineering principle: DRY — but only when the abstraction cost is lower than the duplication cost. Two tiny near-identical helpers is borderline; flagging for awareness.


Specific Review-Focus Answers (per request)

  1. Mistral tool format equivalence after the rewrite: See finding 3. Plausible but worth one live smoke test before merge.
  2. AddBos::Always → Never: I verified grep shows all str_to_token calls in chat/mod.rs use Never (lines 289, 609). The embedding path (embedding.rs:541) still uses Always, which is correct — it's a different model and code path. The change is contained and consistent.
  3. [ARGS] corner case with leading whitespace: I traced [TOOL_CALLS] [ARGS]name{...}: leading_ws=3, arr_region = "[ARGS]name{...}", starts_with(ARGS_SENTINEL) = true, falls through to Format A which correctly returns "Empty function name" because after_sentinel[..3].trim() = "". The guard is correct for this case.
  4. Catalog naming: gemma-4-e4b-q4km / gemma-4-31b-q4km matches the ministral-3b-q4km / ministral-8b-q4km pattern (lowercase, hyphen-separated, quant suffix). Consistent.
  5. Test mock Ministral placeholders: See finding 6.
  6. Frontend type widening: TS union is consistent with Rust enum (lowercase serde). The mock data in model-store.svelte.ts is dead-code for any path that lands in Tauri; updating it is purely cosmetic. Non-blocking.

Recommendation

REQUEST CHANGES — primarily on finding 1 (branch behind main, will silently revert PR #1132). Once rebased, finding 2 (stale "27B" doc comment) is the only other must-fix; everything else is non-blocking improvement or nit. Findings 3 and 8 (Mistral regression evidence; UI hardware-requirement labels) are worth a quick judgment call.

Michael Libio and others added 3 commits May 17, 2026 21:27
Adds Google's Gemma 4 family alongside Ministral 3B/8B in the model
registry. Gemma 4 E4B brings substantially stronger reasoning (GPQA
Diamond 58.6% vs 33.8%/39.9% for Ministral 3B/8B) at competitive speed;
31B is the larger quality-tier option for 24GB+ Apple Silicon.

Implementation notes that differ from issue body:

1. Replaces the proposed manual build_gemma4_prompt formatter with a
   switch to apply_chat_template_oaicompat (use_jinja: true), which
   handles Mistral and Gemma 4 natively via llama.cpp's common_chat_*
   layer. Validated end-to-end in nodespace-nlp-experiment on
   llama-cpp-2 v0.1.146. The simple apply_chat_template C API used to
   return ffi error -1 for Gemma 4; the OAI-compat path fixes that
   without any per-family prompt-format dispatch.

2. Tool-call parser gains a "Format C" path: when a JSON object/array
   appears directly after [TOOL_CALLS] (no function-name prefix), parse
   with dual deserialization — Mistral's {name, arguments} or Gemma 4's
   {tool_name, tool_args}. Handles both single-object and array forms.

3. Catalog uses 31B (not "27B" as the issue body said). Gemma 4's dense
   large variant is 31B; 27B was Gemma 2. Source: ggml-org/gemma-4-31B-it-GGUF.

Other changes:
- Bumped llama-cpp-2 floor from >=0.1.141 to >=0.1.146 for the
  apply_chat_template_oaicompat API.
- Switched tokenization from AddBos::Always to AddBos::Never to avoid
  double-BOS (the Jinja template injects BOS itself).
- Added Gemma4 variant to ModelFamily enum.
- Plumbed family through ChatModelSpec and LlamaChatInferenceEngine so
  the spec returned by model_info() carries the family.
- Widened the TypeScript ModelFamily type to match backend ('ministral'
  | 'gemma4' | 'ollama').
- Tools are now passed via tools_json field instead of hand-injected
  [AVAILABLE_TOOLS] tags — the Jinja template formats tools per-family.

Test coverage:
- 8 new parser tests covering Gemma 4 object form, array form, OpenAI-
  style {name, arguments} object form, mixed-schema arrays, whitespace,
  nested args, chained calls, and unknown-schema errors.
- list_includes_gemma4_entries_with_correct_metadata in model_manager.
- Updated existing e2e catalog test to expect 4 entries.

References:
- Validation: ../nodespace-nlp-experiment README (Experiments 1-5
  documented as PASS for Gemma 4 E4B Q4_K_M on llama-cpp-2 v0.1.146).
- GGUF source: ggml-org repos (maintained by llama.cpp team; April 12+
  builds include Google's fixed chat template).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Threshold raised from 16 GB to 32 GB.
- <32 GB systems get Gemma 4 E4B; >=32 GB get Gemma 4 31B.
- Adds recommended_model_id_for(family) so callers that already know
  the user's family preference can ask for the right size within it:
  Ministral 3B/8B or Gemma 4 E4B/31B, RAM-gated by the same threshold.
- Family choice (Gemma vs Ministral) remains a user decision; size
  within a family is RAM-based.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Fix stale "27B" doc on ModelFamily::Gemma4 (review finding 2).
- Replace parse_format_b's Result<_, ParseResult> error type with
  Result<_, String>; callers wrap into ParseResult::Error. Removes the
  confusing "Err(ParseResult::PlainText(...))" type smell (finding 4).
- Cache [TOOL_CALLS] control-token id once per model load in
  ChatLlamaState; extract the scan into detect_tool_calls_token() and
  cover the full vocab instead of the magic 0..20 range (finding 5).
- Centralize the "skip SHA-256 for Xet-backed official repos" policy as
  a single doc comment on CatalogEntry::sha256 (finding 7).
- Improve the malformed-input error message from "Unbalanced brackets
  in tool call array" to "Unbalanced brackets after [TOOL_CALLS]" — the
  old wording misled debuggers into looking at the array branch when
  the input was simply incomplete (finding 9).
- Dedupe find_balanced_brace and find_balanced_bracket through a shared
  find_balanced(open, close) helper. Named wrappers preserved for
  call-site clarity (finding 10).

Skipped (with rationale):
- Finding 3 (live captured-prompt regression test for Mistral): would
  require loading a real GGUF in tests, which already destabilizes the
  suite under parallel Metal contention. Risk acknowledged; manual
  smoke test left to merge-time verification.
- Finding 6 (diversify ModelFamily in test mocks): no production code
  currently branches on ChatModelSpec.family, so diversifying mocks
  would test nothing today. Defer until the first family-branching
  consumer lands.
- Finding 8 (min_memory_gb field + UI surfacing): the recommendation
  side of this was handled in the previous commit via
  recommended_model_id_for(family). Adding a display field is a UI
  scope expansion the user has not requested for this PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@malibio
malibio force-pushed the worktree-issue-1094-gemma-4-models branch from 718a31f to 49f814a Compare May 17, 2026 19:35
@malibio

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Review Recommendations Addressed

Rebased onto current origin/main (commits efe0b06a, ad43e5aa, 49f814ab now sit on top of 5e7ef289) and addressed 7 of the 10 findings. Force-pushed with --force-with-lease.

✅ Addressed

  • 🔴 Finding 1 — Branch behind main, would have reverted PR Gate AgentSession.system_prompt_override behind testing feature (closes #1093) #1132. Clean rebase, no conflicts. Verified post-rebase:
  • 🟡 Finding 2 — 27B → 31B doc comment on ModelFamily::Gemma4 in agent_types.rs.
  • 🟡 Finding 4 — parse_format_b error type. Changed Result<_, ParseResult> to Result<_, String>; the caller wraps into ParseResult::Error. Removes the "Err(ParseResult::PlainText(...))" type smell.
  • 🟡 Finding 5 — tool_calls_token_id detection. Extracted to detect_tool_calls_token(&model), called once at load from ChatLlamaState::new, cached in the struct. Also widened the scan from the magic 0..20 range to 0..model.n_vocab() so the assumption "control tokens are always low IDs" no longer hides in the code.
  • 🟢 Finding 7 — Centralize sha256: "" policy. Single doc paragraph on CatalogEntry::sha256 explains the Xet-backed-official-repos skip policy.
  • 🟢 Finding 9 — Error message. "Unbalanced brackets in tool call array" → "Unbalanced brackets after [TOOL_CALLS]" for accuracy.
  • 🟢 Finding 10 — Dedupe find_balanced_*. Single find_balanced(open, close) helper; the two named wrappers stay for call-site clarity.

⏭️ Skipped (with rationale)

  • 🟡 Finding 3 — Captured-prompt regression test for Mistral. A test that asserts on the prompt string produced by apply_chat_template for a real Ministral GGUF would require loading the model in the test runner — the same path that already destabilizes our suite under parallel Metal contention. The runtime regression risk is real, but the suggested mechanism doesn't fit our infrastructure. Manual smoke test left to merge-time verification; flagging here so a reviewer can confirm Ministral tool calls still parse after switching to the OAI-compat Jinja path.
  • 🟡 Finding 6 — Diversify ModelFamily in mocks. No production code branches on ChatModelSpec.family today, so diversified mocks would test no real behavior. Will revisit when the first family-branching consumer lands.
  • 🟡 Finding 8 — min_memory_gb + UI hardware-requirement labels. The recommendation-side concern was already addressed in commit ad43e5aa via recommended_model_id_for(family) (RAM-tiered choice within a user-selected family). Adding a display field on CatalogEntry plus rendering it in the model selection UI is a UX scope expansion the user hasn't requested for this PR; better to defer to a focused follow-up issue. I will not claim "all UI acceptance criteria complete" on closing Add Gemma 4 E4B and 27B as downloadable model options #1094.

Verification

  • cargo test -p nodespace-nlp-engine --lib → 60 passed
  • cargo test -p nodespace-agent --lib → 235 passed (includes 22 model_manager + parser tests)
  • cargo clippy --all-targets -- -D warnings (no feature) → clean
  • cargo clippy -p nodespace-agent --features testing --tests -- -D warnings → clean
  • bun run quality:fix → 0 ESLint, 0 svelte-check, cargo fmt, cargo clippy strict-warnings all clean.

🤖 Generated with Claude Code

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic Code Review — PR #1134 (Re-Review)

Review Type: Re-Review
Branch: worktree-issue-1094-gemma-4-models
Commits since base: 3 (efe0b06a, ad43e5aa, 49f814ab); rebased onto origin/main (5e7ef289)
New commit under review: 49f814ab "Address pragmatic-code-review on PR #1134"
Issue: #1094


Previous Review Summary

The initial review (abfe5672) raised 10 findings:

  • 1 Critical (branch behind main, would revert #1132)
  • 2 Important (stale "27B" doc; Mistral prompt regression test)
  • 4 Improvements (parse_format_b error type; tool_calls_token_id hoist; diversify mock ModelFamily; centralize empty-sha256 policy; UI hardware-requirement labels)
  • 2 Nits (error message wording; dedupe find_balanced_*)

The author posted a follow-up summary listing 7 addressed and 3 skipped with rationale.


Per-Finding Verdict

1. CRITICAL — Branch behind main, would revert PR #1132 — Addressed cleanly

Rebase is clean. git diff origin/main..HEAD -- packages/agent/src/agent_types.rs packages/agent/src/local_agent/agent_loop.rs packages/agent/Cargo.toml shows only the intended Gemma 4 additions (ModelFamily::Gemma4 variant, family field on ChatModelSpec, mock update in agent_loop.rs:1112). PR #1132's gating is intact:

  • packages/agent/Cargo.toml:34-41 — [features] table with testing = [] present, with the originating-PR comment preserved.
  • packages/agent/Cargo.toml:51-54 — [[test]] name = "ollama_integration" ... required-features = ["testing"] preserved.
  • packages/agent/src/agent_types.rs:447-449 — #[cfg(any(test, feature = "testing"))] gate on system_prompt_override retained.
  • packages/agent/src/local_agent/agent_loop.rs:52-59 — both cfg arms of session_prompt_override present.
  • packages/agent/src/local_agent/agent_loop.rs:871, 907-913 — #[cfg(any(test, feature = "testing"))] retained on construction default and on set_system_prompt.

cargo clippy -p nodespace-agent --all-targets --features testing -- -D warnings is clean.

2. IMPORTANT — Stale "27B" doc comment — Addressed cleanly

agent_types.rs:248 now reads (E4B, 31B). One-line fix, exactly as recommended.

3. IMPORTANT — Mistral captured-prompt regression test — Skipped with valid reason

Author's rationale is sound: capturing the prompt string output by apply_chat_template_oaicompat requires loading a real GGUF, and the current test runner already has known instability with parallel Metal contention. Adding a single fragile test for one chat-template invocation is a poor trade. The author preserves the underlying risk by flagging Ministral as the smoke-test target for merge-time verification, which is the right escalation path. I would have made the same call. Recommend explicit Ministral tool-call validation be noted in the merge commit body or PR description before merging.

4. IMPROVEMENT — parse_format_b returns Result<_, ParseResult> — Addressed cleanly

parser.rs:280 now reads Result<(String, &str, &str), String>; the two call sites at parser.rs:220 and parser.rs:228 wrap into ParseResult::Error(msg). The Err(ParseResult::PlainText(...)) type smell is gone. Idiomatic Rust.

5. IMPROVEMENT — Hoist tool_calls_token_id detection out of hot path — Addressed cleanly, with a bonus fix

Extracted to free function detect_tool_calls_token at chat/mod.rs:148-162. Called once from ChatLlamaState::new (line 89), cached on the struct (line 79), read into a local at the top of generate_blocking (line 365). Construction happens exactly once per model load (single call site at chat/mod.rs:210).

Bonus: the magic 0..20i32 range from the original review's flagged code is gone — the scan is now 0..model.n_vocab(), removing the implicit "control tokens are always low IDs" assumption. For Ministral this is the same answer; for any future model whose [TOOL_CALLS] token sits at a higher id, detection no longer silently fails. Cost is a one-time decode of up to ~256k tokens at load, which is acceptable for a one-shot operation.

The doc comment correctly flags Gemma 4's behavior (None return, plain text emission) for future readers.

6. IMPROVEMENT — Diversify mock ModelFamily — Skipped with valid reason

Author argues that no production code currently branches on ChatModelSpec.family, so diversified mocks would exercise no behavior. Confirmed via inspection: family is plumbed through model_manager.rs:222 (family_for()) and consumed by inference.rs:34 (LlamaChatInferenceEngine::load), but no inference path forks on it today (the OAI-compat Jinja path handles family-specific prompting inside llama.cpp). The recommendation in the original review was speculative ("the moment any such branching is added"). I agree this is a reasonable defer — flag it again the first time a match family lands in production code so the test mocks get diversified in the same PR.

7. IMPROVEMENT — Centralize empty-sha256 policy — Addressed cleanly

model_manager.rs:45-55 now carries the policy paragraph on CatalogEntry::sha256, naming both mistralai/... and ggml-org/... repos and the Xet content-addressing rationale, plus the escalation path ("for any unofficial source, populate this and perform_download will enforce it"). The per-entry inline comments are kept, which is fine — they serve as call-site reminders, not as the policy of record.

8. IMPROVEMENT — min_memory_gb field + UI hardware labels — Skipped with partial valid reason

The author argues this is UX scope expansion and that the recommendation-side concern was addressed in ad43e5aa via recommended_model_id_for(family).

I accept this with a caveat. The PR no longer claims to close all acceptance criteria of #1094 (the author explicitly states they "will not claim 'all UI acceptance criteria complete' on closing #1094"), which is the correct response to my original finding. The decision is reasonable — adding a min_memory_gb field plus a Svelte rendering pass for a single UX label genuinely is a separate concern.

However: the commit message on efe0b06a still reads "Add Gemma 4 E4B and 31B as downloadable model options (closes #1094)". If the UI acceptance criterion truly is being deferred, the closing keyword should be removed or downgraded to (refs #1094) and a follow-up issue opened for the UI label. Otherwise GitHub will auto-close #1094 with unchecked criteria. Recommend either: (a) edit the commit message before merge to use (refs #1094), or (b) keep closes #1094 and open a follow-up issue immediately on merge for the hardware-requirement labels, linking back to this PR's review thread.

9. NIT — Error message wording — Addressed cleanly

parser.rs:164 now reads "Unbalanced brackets after [TOOL_CALLS]". Precise and debugger-friendly.

10. NIT — Dedupe find_balanced_brace/find_balanced_bracket — Addressed cleanly

Shared find_balanced(s, open, close) helper at parser.rs:319 with a clear doc comment about string-handling semantics and call-site invariants. The two named wrappers (find_balanced_bracket, find_balanced_brace) are preserved as one-liners for call-site clarity — a nice middle ground between DRY and readability. The original implementations are fully replaced; no dead code remains.


New Issues Introduced by 49f814ab

None. The refactor is mechanical and conservative:

  • The parse_format_b return-type change is a no-op behavior change (same error messages, same paths, just rewrapped at the call sites). Verified by reading the two match parse_format_b(...) call sites — both now return ParseResult::Error(msg), which is exactly what the old return e would have evaluated to.
  • The detect_tool_calls_token hoist moves logic without changing it. The vocab-scan widening (0..20 → 0..n_vocab) is a one-way correctness improvement.
  • The find_balanced consolidation is a pure refactor; same algorithm, same edge cases (string escaping, depth tracking).

cargo clippy -p nodespace-agent --all-targets --features testing -- -D warnings clean; cargo test -p nodespace-nlp-engine --lib → 60 passed; cargo test -p nodespace-agent --lib → 235 passed.


Skipped Findings — Engineering Call Evaluation

Finding Skip Reason Verdict
3 (Mistral regression test) Loading real GGUF in test runner destabilizes suite Valid. Merge-time smoke test must happen — flag in merge commit.
6 (Diversify mock ModelFamily) No production code currently branches on family Valid. Re-flag when first family branch lands.
8 (min_memory_gb + UI labels) UX scope expansion; recommendation side already handled Mostly valid, but: commit message (closes #1094) is inconsistent with the deferred UI work. Either adjust the closing keyword to refs #1094 or open the follow-up issue at merge time.

Final Recommendation

APPROVE — with one small process item to resolve before merge:

  1. Commit-message / issue-closure alignment for finding 8: either edit efe0b06a's message to (refs #1094) and open a follow-up issue for the UI hardware-requirement labels, or accept that closes #1094 will auto-close the issue and add a follow-up issue link in the closing comment. Both routes are fine; just don't leave #1094 in a state where it auto-closes with unchecked UI acceptance criteria and no successor issue.
  2. Reminder for merge-time: run a Ministral tool-calling smoke test (Ministral 3B or 8B, single round, real tool) and note the result on the PR before merging, per the author's own commitment for the skipped finding 3. This is the agreed mitigation for the chat-template path change.

Everything technical is in order. The refactor commit is exemplary: small, focused, accompanied by a precise commit body that enumerates which findings were addressed vs skipped and why. No new issues introduced, all previous critical/important findings either addressed or skipped with rationale I'd sign off on.

🤖 Generated with Claude Code

@malibio

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Process Items from Re-Review Addressed

Both items the reviewer flagged before merge are now resolved:

1. UI hardware-requirement labels — follow-up issue opened

Created #1140 to track the deferred UI work (min_memory_gb field on CatalogEntry, propagation to TS types, rendering in model-manager.svelte, with suggested values per model). PR description's "Deferred to follow-up" section now links it explicitly, so closing #1094 from this PR will leave a visible successor.

2. Ministral tool-call smoke test — flagged as required before merge

PR description now has a "Required before merge" section calling out the Ministral 3B/8B smoke test as the agreed mitigation for skipped review finding #3 (captured-prompt regression test). The check is explicit, not buried in a test-plan checkbox.

No code changes in this commit. The re-review approved the technical implementation; both items were process/documentation.

🤖 Generated with Claude Code

@malibio
malibio merged commit 19629de into main May 17, 2026
@malibio
malibio deleted the worktree-issue-1094-gemma-4-models branch May 17, 2026 20:08
malibio added a commit that referenced this pull request Jun 22, 2026
* Add Gemma 4 E4B and 31B as downloadable model options (closes #1094)

Adds Google's Gemma 4 family alongside Ministral 3B/8B in the model
registry. Gemma 4 E4B brings substantially stronger reasoning (GPQA
Diamond 58.6% vs 33.8%/39.9% for Ministral 3B/8B) at competitive speed;
31B is the larger quality-tier option for 24GB+ Apple Silicon.

Implementation notes that differ from issue body:

1. Replaces the proposed manual build_gemma4_prompt formatter with a
   switch to apply_chat_template_oaicompat (use_jinja: true), which
   handles Mistral and Gemma 4 natively via llama.cpp's common_chat_*
   layer. Validated end-to-end in nodespace-nlp-experiment on
   llama-cpp-2 v0.1.146. The simple apply_chat_template C API used to
   return ffi error -1 for Gemma 4; the OAI-compat path fixes that
   without any per-family prompt-format dispatch.

2. Tool-call parser gains a "Format C" path: when a JSON object/array
   appears directly after [TOOL_CALLS] (no function-name prefix), parse
   with dual deserialization — Mistral's {name, arguments} or Gemma 4's
   {tool_name, tool_args}. Handles both single-object and array forms.

3. Catalog uses 31B (not "27B" as the issue body said). Gemma 4's dense
   large variant is 31B; 27B was Gemma 2. Source: ggml-org/gemma-4-31B-it-GGUF.

Other changes:
- Bumped llama-cpp-2 floor from >=0.1.141 to >=0.1.146 for the
  apply_chat_template_oaicompat API.
- Switched tokenization from AddBos::Always to AddBos::Never to avoid
  double-BOS (the Jinja template injects BOS itself).
- Added Gemma4 variant to ModelFamily enum.
- Plumbed family through ChatModelSpec and LlamaChatInferenceEngine so
  the spec returned by model_info() carries the family.
- Widened the TypeScript ModelFamily type to match backend ('ministral'
  | 'gemma4' | 'ollama').
- Tools are now passed via tools_json field instead of hand-injected
  [AVAILABLE_TOOLS] tags — the Jinja template formats tools per-family.

Test coverage:
- 8 new parser tests covering Gemma 4 object form, array form, OpenAI-
  style {name, arguments} object form, mixed-schema arrays, whitespace,
  nested args, chained calls, and unknown-schema errors.
- list_includes_gemma4_entries_with_correct_metadata in model_manager.
- Updated existing e2e catalog test to expect 4 entries.

References:
- Validation: ../nodespace-nlp-experiment README (Experiments 1-5
  documented as PASS for Gemma 4 E4B Q4_K_M on llama-cpp-2 v0.1.146).
- GGUF source: ggml-org repos (maintained by llama.cpp team; April 12+
  builds include Google's fixed chat template).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Default first-launch recommendation to Gemma 4 by RAM tier

- Threshold raised from 16 GB to 32 GB.
- <32 GB systems get Gemma 4 E4B; >=32 GB get Gemma 4 31B.
- Adds recommended_model_id_for(family) so callers that already know
  the user's family preference can ask for the right size within it:
  Ministral 3B/8B or Gemma 4 E4B/31B, RAM-gated by the same threshold.
- Family choice (Gemma vs Ministral) remains a user decision; size
  within a family is RAM-based.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* Address pragmatic-code-review on PR #1134

- Fix stale "27B" doc on ModelFamily::Gemma4 (review finding 2).
- Replace parse_format_b's Result<_, ParseResult> error type with
  Result<_, String>; callers wrap into ParseResult::Error. Removes the
  confusing "Err(ParseResult::PlainText(...))" type smell (finding 4).
- Cache [TOOL_CALLS] control-token id once per model load in
  ChatLlamaState; extract the scan into detect_tool_calls_token() and
  cover the full vocab instead of the magic 0..20 range (finding 5).
- Centralize the "skip SHA-256 for Xet-backed official repos" policy as
  a single doc comment on CatalogEntry::sha256 (finding 7).
- Improve the malformed-input error message from "Unbalanced brackets
  in tool call array" to "Unbalanced brackets after [TOOL_CALLS]" — the
  old wording misled debuggers into looking at the array branch when
  the input was simply incomplete (finding 9).
- Dedupe find_balanced_brace and find_balanced_bracket through a shared
  find_balanced(open, close) helper. Named wrappers preserved for
  call-site clarity (finding 10).

Skipped (with rationale):
- Finding 3 (live captured-prompt regression test for Mistral): would
  require loading a real GGUF in tests, which already destabilizes the
  suite under parallel Metal contention. Risk acknowledged; manual
  smoke test left to merge-time verification.
- Finding 6 (diversify ModelFamily in test mocks): no production code
  currently branches on ChatModelSpec.family, so diversifying mocks
  would test nothing today. Defer until the first family-branching
  consumer lands.
- Finding 8 (min_memory_gb field + UI surfacing): the recommendation
  side of this was handled in the previous commit via
  recommended_model_id_for(family). Adding a display field is a UI
  scope expansion the user has not requested for this PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[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.

Add Gemma 4 E4B and 27B as downloadable model options

1 participant