Skip to content

Chat context floors to 4096 (below the agent system prompt) because the memory probe ignores macOS reclaimable pages — every tool-using turn fails #1758

Closed

Description

@malibio

Overview

On macOS, sysinfo::available_memory() counts only genuinely-free pages and excludes the reclaimable inactive pool. After a chat model's weights become resident it can report 0.0 GB available on a machine with several GB of reclaimable cache. compute_effective_n_ctx then computes a KV budget of zero and floors n_ctx to N_CTX_FLOOR (4096) — which is below the agent's own system prompt (~6,600 tokens with 14 tools registered). Every tool-using turn fails before the model runs:

WARN Reducing chat context to fit memory: configured=32768 effective=4096
     available=0.0GB (KV 2 B/elem) — large model on constrained memory
WARN inference turn failed — Context window exceeded:
     Prompt uses 6556 tokens but context window is 4096

This is a hard failure of the whole local-agent surface, not a degradation: the user sees every AI request fail.

The memory is not actually scarce

Measured on a 16 GB M2 Pro while the floor was being hit:

metric value
available_memory() (what the code reads) 0.0–1.1 GB
free pages 1.17 GB
inactive (reclaimable) 6.65 GB
swap used 0

Gemma 4 E4B's KV cache is cheap — 42 layers, GQA 8/2 → 105 KiB/token, so even a full 32K window is ~3.3 GB and 16K is ~1.6 GB. The machine has that. The probe just cannot see it, because macOS holds it as inactive rather than free.

Root cause

packages/nlp-engine/src/chat/mod.rs:

  • compute_effective_n_ctx reads sys.available_memory() and passes it to fit_n_ctx_to_budget.
  • fit_n_ctx_to_budget computes min(available − KV_HEADROOM_BYTES, available × KV_BUDGET_PERCENT%).
  • With KV_HEADROOM_BYTES = 2 GiB, any available at or below 2 GiB makes the first term zero, so the result clamps to N_CTX_FLOOR regardless of the model's real KV cost.

The 2 GiB headroom and 40% cap were tuned against a 12B model OOMing at a 32K window (the adaptive-sizing change that introduced them). E4B pays the same fixed tax despite needing a fraction of the memory, and the pessimistic probe pushes it over the edge.

Impact

  • Reproducible on a 16 GB machine with a warm page cache — i.e. normal desktop conditions, not an artificial low-memory state.
  • Not limited to test rigs: the same code path runs in the shipped app. Any user whose free-page count reads low when a model loads gets a 4096-token context and a 100% agent failure rate.
  • It has already blocked verification work twice: the decomposition PR could not complete a live aichat-matrix run for this exact reason, and reproducing it later required temporarily overriding the probe.

Suggested fixes

  1. Count reclaimable memory. Use free + inactive (+ purgeable) rather than available_memory() alone on macOS, so the budget reflects memory the OS will actually hand over under pressure.
  2. Never floor below what the prompt needs. N_CTX_FLOOR (4096) is smaller than the agent's own system prompt (~6,600 tokens). If the computed window cannot hold the system prompt plus a minimal reply, that is a hard error worth surfacing — not a silent clamp that makes every turn fail with a confusing "context window exceeded."
  3. Scale headroom to the model. A fixed 2 GiB subtraction is right for a 12B model at 32K and wrong for E4B; consider deriving it from the measured per-token KV cost.
  4. KV-cache quantization would independently reduce the pressure (KvCacheQuantType exists in chat/types.rs but is None by default with no override).

Acceptance Criteria

  • On a 16 GB machine with a warm page cache, loading gemma-4-e4b-q4km yields a context window large enough for the agent system prompt plus a working conversation (not the 4096 floor)
  • A computed window that cannot fit the system prompt surfaces a clear, actionable error rather than a generic per-turn "Context window exceeded"
  • scripts/aichat-matrix.ts runs end-to-end against E4B on such a machine without any memory-probe override
  • No regression to the OOM protection the adaptive sizing was introduced for (a large model on a genuinely constrained machine must still be throttled)

Reproduction

cargo build --release -p nodespace-daemon -p nodespace-cli
rm -rf /tmp/nodespaced-test && mkdir -p /tmp/nodespaced-test
NODESPACED_HEADLESS=1 NODESPACED_SOCKET=/tmp/nodespaced-test/daemon.sock \
  NODESPACED_DB_PATH=/tmp/nodespaced-test/nodespace.db RUST_LOG=info \
  target/release/nodespaced > /tmp/nodespaced-test/daemon.log 2>&1 &
target/release/nodespace --socket /tmp/nodespaced-test/daemon.sock model load gemma-4-e4b-q4km
grep -E "Reducing chat context" /tmp/nodespaced-test/daemon.log

Then send any tool-using request (e.g. "Create an invoice tracking database") and observe the per-turn context failure. Compare vm_stat's inactive-page count against the available= figure in the warning.

Activity

  1. added
    bug
    on Jul 28, 2026
  2. malibio commented on Jul 28, 2026

    @malibio
    CollaboratorAuthor

    Baseline (worktree issue-1758-chat-context-memory-probe): Frontend 4091 passed / 166 test files.

  3. self-assigned this
    on Jul 28, 2026
  4. malibio commented on Jul 28, 2026

    @malibio
    CollaboratorAuthor

    Correction to the diagnosis in this issue (fixed in #1762).

    The stated root cause — that sysinfo::available_memory() ignores the reclaimable inactive pool — does not hold. sysinfo 0.33.1 already computes free + inactive + purgeable − compressor (unix/apple/system.rs:200-204), so the proposed host_statistics64 probe (suggested fix 1) would have been a no-op.

    Instrumented probe during an E4B load on the reporting machine:

    free=1.87GB inactive=1.57GB purgeable=0.01GB compressor=3.33GB
    wired=8.09GB || available=0.13GB total=17.18GB
    geometry n_layer=42 n_embd=2560 n_head=8 n_head_kv=2  -> 107,520 B/token
    

    The 105 KiB/token figure in the issue is confirmed exactly. But the weights land in wired, not inactive, and the compressor pool is subtracted — which is what drives available to ~0. Metal reported ~11.9GB free at the same moment.

    Two real causes: (1) n_batch was pinned to the full context window, so a 32K window reserved a 32K-token compute buffer — the actual memory sink, and the only justification for the 40% cap that starved the window; (2) the budget was keyed off available_memory(), which on this machine reports ~0.1-0.4GB whether or not a model is loaded.

    Suggested fix 4 (KV quantization) was also skipped: E4B reaches its full 32K window at F16, and the tiers that need Q8_0 already set it.

    Also filed #1761 for a pre-existing deadlock found while verifying this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

backendbugrust

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions