openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(inference): gate local Ollama models by memory-layer context-window minimum

Open sanil-23 opened this issue 6 months ago • 2 comments

Summary

  • Reject local Ollama models whose native context window is below 8192 — the floor the memory layer requires (bge-m3 embedder is requested at num_ctx=8192; summariser output is capped at 5000 to fit that embed ceiling). Sub-floor models silently truncate chunks/summaries and corrupt recall.
  • The floor is derived from the embedder's own EMBED_NUM_CTX (now pub(crate)), so the acceptance gate can never drift from what the pipeline actually requests.
  • New Ollama /api/show client resolves each model's real context_length (architecture-agnostic).
  • inference.diagnostics now reports per-model context_length + an eligibility verdict, a context_requirement, and rejecting issues for sub-floor active models.
  • Settings → Local AI Model shows a per-model context badge (accepted / rejected+flagged / unknown).

Problem

The memory tree's embedder over-requests num_ctx=8192 and the whole summary-budget logic exists to keep embed input ≤ 8192. Nothing validated that a user-selected local model actually supports that context — a short-context model (e.g. a 2048-ctx embedder) was accepted and then silently truncated input at embed time, corrupting recall with no signal to the user. /api/tags (the only Ollama metadata fetched) does not expose context length, so the gate needs /api/show.

Solution

  • memory::tree::score::embed::ollama::EMBED_NUM_CTX made pub(crate); inference::local::model_requirements::MIN_CONTEXT_TOKENS re-exports it (single source of truth, drift-guarded by a test).
  • evaluate_context(Option<u64>) → Ok / BelowMinimum / Unknown. Unknown (/api/show unreachable or metadata absent) is not a hard rejection — only a conclusive sub-floor report is.
  • OllamaAdmin::fetch_model_context issues one bounded (5s) /api/show per installed model, concurrently, only on the diagnostics path.
  • Frontend types are additive/optional → back-compatible with older cores (no badge rendered when eligibility is absent).
  • No embedding-dimension / re-index work (explicitly out of scope for this PR).

Submission Checklist

If a section does not apply to this change, mark the item as N/A with a one-line reason. Do not delete items.

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] Diff coverage ≥ 80% — every new/changed line is exercised: 10 Rust tests (eligibility classification incl. below/unknown, /api/show parse incl. missing/float, axum-mock diagnostics gate) + 4 Vitest cases (accept / reject+flag / unknown / older-core). Full pnpm test:coverage/pnpm test:rust merge deferred to CI (see Validation Run).
  • [x] Coverage matrix updated — added row 3.1.5 in docs/TEST-COVERAGE-MATRIX.md
  • [x] All affected feature IDs from the matrix are listed in the PR description under ## Related
  • [x] No new external network dependencies introduced — uses the existing local Ollama /api/show; no new crates/deps; tests use an in-process axum mock
  • [x] N/A: manual smoke checklist — diagnostics-panel badge + advisory issues; not a release-cut smoke surface
  • [x] N/A: no tracking issue — issue-less feature per maintainer request (no Closes #NNN)

Impact

  • Desktop only (Settings → Local AI Model diagnostics). No migration, no schema change, no new deps.
  • Performance: adds one /api/show round-trip per installed model, only when diagnostics runs, fetched concurrently with a 5s per-call timeout. No effect on hot paths.
  • Behavior change: a sub-8192-context active model now produces a diagnostics issue (ok:false) and a red badge instead of being silently used.

Related

  • Closes: N/A (issue-less)
  • Affected matrix feature IDs: 3.1.5 Model Context-Window Requirement Gate
  • Capability: local_ai.model_context_check
  • Follow-up PR(s)/TODOs: embedding-dimension / re-index handling (deferred; out of scope here)

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: feat/ollama-context-gate (off upstream/main)
  • Commit SHA: b8af174cd18620e5881a2d29a4e4cafcee1bfb37

Validation Run

  • [x] pnpm --filter openhuman-app format:check — Prettier run scoped to the 3 changed app files (clean); repo-wide skipped (Windows CRLF churn rewrites ~600 unrelated files — established --no-verify pattern)
  • [x] pnpm typecheck — passed
  • [x] Focused tests: cargo test --lib -- model_requirements:: context_length_ diagnostics_gates_models_by_context_window (10 passed); Vitest ModelStatusSection.test.tsx (18 passed)
  • [x] Rust fmt/check (if changed): cargo fmt + cargo check --manifest-path Cargo.toml — clean, no new warnings on changed files
  • [x] N/A: Tauri fmt/check — app/src-tauri not touched (changes are core Rust + app TS); pre-push pnpm rust:check skipped via --no-verify per established Windows pattern

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: reject (don't silently use) local models whose native context window is below the memory-layer minimum of 8192
  • User-visible effect: per-model context badge in Local AI Model settings; diagnostics flags a sub-floor active model as an issue

Parity Contract

  • Legacy behavior preserved: /api/tags listing unchanged; older cores (no eligibility) render exactly as before (no badge); Unknown does not block
  • Guard/fallback/dispatch parity checks: /api/show failure → Unknown (soft), never a hard reject; LM Studio diagnostics path untouched

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this
  • Resolution: N/A

Summary by CodeRabbit

  • New Features

    • Per-model context-window eligibility badges and visual highlighting for models rejected for insufficient context; diagnostics now reports each model’s resolved context length and the minimum-context requirement.
  • Tests

    • Added unit and integration tests for eligibility evaluation, metadata parsing, and diagnostics gating by context-window.
  • Documentation

    • Updated test-coverage matrix and diagnostics schema descriptions for the context-window requirement gate.
  • Chores

    • Exposed the memory-layer minimum context constant for cross-module use.

Review Change Stack

sanil-23 avatar May 18 '26 14:05 sanil-23

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: aa9dd1d4-8c7c-4845-b2e8-403ef4b4ca36

📥 Commits

Reviewing files that changed from the base of the PR and between d05999077dc79b10165505e3f5fb228a357ad28e and 8f03c3b1d5001018886eab2c43b407e18a4bc897.

📒 Files selected for processing (2)
  • src/openhuman/inference/local/mod.rs
  • src/openhuman/inference/local/ollama.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/openhuman/inference/local/ollama.rs

📝 Walkthrough

Walkthrough

Defines a memory-layer minimum (8192), extracts native context windows from Ollama /api/show, evaluates per-model eligibility, includes eligibility and min_context_tokens in diagnostics, and renders eligibility badges and rejection styling in the frontend.

Changes

Local Model Context-Window Eligibility Gating

Layer / File(s) Summary
Model requirements foundation and constants
src/openhuman/memory/tree/score/embed/ollama.rs, src/openhuman/inference/local/mod.rs, src/openhuman/inference/local/model_requirements.rs
Expose EMBED_NUM_CTX (8192) as crate-visible, add ContextEligibility enum (Ok, BelowMinimum, Unknown), evaluate_context(), helpers, and unit tests.
Ollama model metadata extraction
src/openhuman/inference/local/ollama.rs
Add /api/show request/response types and context_length() extraction that prefers architecture-scoped keys with fallback scanning and flexible numeric parsing; include extraction tests.
Diagnostics service integration
src/openhuman/inference/local/service/ollama_admin.rs
Concurrently fetch per-model context, evaluate eligibility, build installed_models[] with context_length and eligibility, add context_requirement.min_context_tokens, and emit issues for below-minimum expected models.
Diagnostics integration test
src/openhuman/inference/local/service/ollama_admin_tests.rs
Tokio integration test mocking Ollama endpoints asserting min_context_tokens, per-model context_length, and eligibility statuses in diagnostics.
Frontend types and UI components
app/src/utils/tauriCommands/localAi.ts, app/src/components/settings/panels/local-model/ModelStatusSection.tsx
Add ModelContextEligibility and InstalledModelInfo types, implement ContextEligibilityBadge, and update diagnostics rows to render badges and conditional rejected styling.
Frontend component tests
app/src/components/settings/panels/local-model/ModelStatusSection.test.tsx
Tests for accepted models (success badge), below-minimum models (below-min badge and red name styling), unknown eligibility, and legacy models without eligibility metadata.
Documentation and capability catalog
src/openhuman/inference/schemas.rs, src/openhuman/about_app/catalog.rs, docs/TEST-COVERAGE-MATRIX.md
Document diagnostics payload fields, add local_ai.model_context_check capability entry, and add test-coverage matrix row for the model context-window gate.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • tinyhumansai/openhuman#1975: Touches the same local-Ollama diagnostics/UI surface and earlier diagnostics refactor relevant to per-model metadata handling.

Suggested labels

working

Suggested reviewers

  • graycyrus
  • senamakel

Poem

🐰 I hop through models, tallying each span,

Counting tokens with a careful plan.
Eight-thousand-one-hundred-something is the floor,
Badges bloom green or red at the door.
A rabbit's nod: only fit models go on.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main feature: gating Ollama models by a memory-layer context-window minimum, which is the primary objective across the entire changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

coderabbitai[bot] avatar May 18 '26 14:05 coderabbitai[bot]

@graycyrus ready for re-review 🙏

Both your review comments are addressed and resolved (commit 8f03c3b1):

  • inference/local/mod.rs: pub mod → pub(crate) mod model_requirements (matches sibling module convention)
  • inference/local/ollama.rs: added a comment on the capabilities field documenting it exists to mirror the Ollama API wire shape (not yet consumed)

Status: all CI green (22/22, only the always-skipped macOS/Windows e2e remaining), 0 unresolved threads, MERGEABLE, no conflicts. Blocked only on an approving review. Thanks!

sanil-23 avatar May 19 '26 13:05 sanil-23