Skip to content

Cap the prefill batch and budget chat context against total RAM, not free pages - #1762

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1758-chat-context-memory-probe
Jul 28, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1758-chat-context-memory-probe

Conversation

@malibio

@malibio malibio commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1758.

The issue's diagnosis was wrong

The issue attributes the 4096 floor to sysinfo::available_memory() ignoring macOS's reclaimable inactive pool, and proposes a custom host_statistics64 probe as the primary fix. That fix would be a no-op. sysinfo 0.33.1 (the resolved version) already counts inactive pages — sysinfo-0.33.1/src/unix/apple/system.rs:200-204:

self.mem_available = free_count + inactive_count + purgeable_count
    - compressor_page_count) * page_size

I instrumented the probe and loaded E4B on the reporting machine (16GB M2 Pro, 16KB pages):

free=1.87GB inactive=1.57GB purgeable=0.01GB compressor=3.33GB
speculative=0.18GB active=1.77GB 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 (105 KiB)

The weights land in wired, not inactive, so counting reclaimable pages was never going to help. And the compressor pool (3.33 GB) is subtracted, driving available to 0.13 GB — while the Metal device simultaneously reported ~11.9 GB free. It stays near zero with the daemon stopped, so it isn't measuring anything we can budget against.

Actual causes, both fixed

1. n_batch was pinned to the full context window (mod.rs:132). A 32K window reserved a 32K-token compute buffer — 16× llama.cpp's own default. That allocation, not the KV cache, was the memory sink, and it is the sole stated justification for the KV_BUDGET_PERCENT = 40 cap that starved the window.

n_batch/n_ubatch are now fixed at llama.cpp's 2048/512. Since llama_decode rejects a batch larger than n_batch, the prefill decode is now chunked, with absolute positions preserved across chunk boundaries so RoPE and the KV cache see an unbroken sequence. Measured compute buffer at 32K afterwards: 338 MiB.

2. The budget was keyed off a signal that lies. It now derives from total RAM − weights − fixed reserves. Total RAM is a hardware constant, so the same machine yields the same window on every load. Weights are stat'd from the GGUF, which is also correct for user-supplied non-catalog models.

A window too small for the system prompt is now a load-time ChatError::InsufficientMemory naming total RAM, weight size, and the shortfall — one actionable error instead of an opaque overflow on every turn.

Verification on the reporting machine

Check Before After
E4B window 4096 (floor) 32,768
Tool-using turn fails every time ✅ completes, zero overflows
10,787-token prompt (~6 prefill chunks) rejected ✅ follows instructions exactly
Compute buffer @32k multi-GB 338 MiB
ai_chat_send_to_idle_test 300s timeout, assistant_count=0 ✅ passes in 33s

That last row is independent confirmation: the pre-push gate initially failed because the checked-in sidecar binary was stale pre-fix code. Swapping in the fixed daemon — with no test changes — took it from "never produces a reply" to a complete turn. The gate was reproducing the bug.

Regression guard (AC #4): Gemma 4 12B computes 26,624, below the 27,136 window that OOM'd. Gemma 4 31B on 16GB yields 0 → clean load error.

Frontend 4091 passed / 166 files, unchanged from baseline. nodespace-nlp-engine: 103 lib + 11 integration, all passing.

Deliberately not implemented

  • The issue's fix 1 (macOS mach probe) — proven a no-op above; would add unsafe FFI against a #[repr(packed)] struct for zero benefit.
  • The issue's fix 4 (KV quantization) — E4B reaches its full window at F16, so Q8_0 would cost Metal throughput (~10-25%) and quality for headroom it doesn't need. The tiers that need it (12B/31B) already set it.

Follow-ups filed

🤖 Generated with Claude Code

https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr

…pages (closes #1758)

The agent's context window collapsed to the 4096 N_CTX_FLOOR — below its own
~6,600-token system prompt — so every tool-using turn failed with "Prompt uses
6556 tokens but context window is 4096".

The issue attributed this to `sysinfo::available_memory()` ignoring macOS's
reclaimable inactive pool. Measurement disproved that: sysinfo 0.33.1 already
computes free + inactive + purgeable − compressor. Instrumenting the probe on
the reporting machine (16GB M2 Pro) during an E4B load showed why it still
reads near zero:

    free=1.87GB inactive=1.57GB purgeable=0.01GB compressor=3.33GB
    wired=8.09GB || available=0.13GB total=17.18GB

The weights land in `wired`, not `inactive`, and the compressor pool is
subtracted — so "available" reports 0.13GB on a machine whose Metal device
simultaneously reports ~11.9GB free. It stays near zero with the daemon
stopped, so it is not measuring anything we can budget against.

Two real causes, both fixed here:

1. `n_batch` was pinned to the full context window, so a 32K window reserved a
   32K-token compute buffer. That allocation — not the KV cache — was the
   memory sink, and it is what the fixed 2GiB headroom and 40% fraction cap
   were empirically tuned to compensate for. `n_batch`/`n_ubatch` are now fixed
   at llama.cpp's own 2048/512 defaults, which required chunking the prefill
   decode since llama_decode rejects a batch larger than n_batch. Measured
   compute buffer at 32K: 338 MiB.

2. The budget now derives from total RAM minus the weights (stat'd from the
   GGUF, so it is also correct for non-catalog models) minus fixed OS and
   compute reserves. Total RAM is a hardware constant, so the same machine
   yields the same window on every load regardless of page-cache state.

A window too small to hold the system prompt is now a load-time
ChatError::InsufficientMemory naming total RAM, weight size, and the shortfall,
rather than a silent clamp that fails on every subsequent turn.

Verified on the reporting machine: E4B loads at the full 32768 (was 4096); a
tool-using turn completes with no context overflow; a 10,787-token prompt
prefills across ~6 chunks and still follows instructions exactly, confirming
absolute positions survive chunk boundaries. Gemma 4 12B computes 26,624 —
below the 27,136 window that OOM'd — preserving the throttling the adaptive
sizing was introduced for.

Not implemented, deliberately: the issue's suggested macOS host_statistics64
probe (a no-op — sysinfo already does this) and its KV-quantization change
(E4B reaches its full window at F16; the tiers that need Q8_0 already set it).

Frontend 4091 passed / 166 files, unchanged from baseline.

Co-Authored-By: Claude <[email protected]>
@malibio malibio changed the title Chat context floors to 4096 (below the agent system prompt) because the memory probe ignores macOS reclaimable pages — every tool-using turn fails Cap the prefill batch and budget chat context against total RAM, not free pages Jul 28, 2026
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1762

Review Type: Initial Review (0 prior reviews, 0 comments)
Scope: d748425 — 2 files, +433/−147


Verdict up front

The diff is a net improvement and the diagnosis is right. I independently re-derived the central claims rather than taking them on trust, and the two deliberate deviations from the issue are correctly justified. The chunked prefill — the highest-risk part — is provably correct, including the subtlety the author didn't call out. One finding is worth resolving before merge; it is a constant, not a design flaw.

Verification I performed independently

Claim Result
sysinfo 0.33.1 already does free+inactive+purgeable−compressor ✅ Confirmed at sysinfo-0.33.1/src/unix/apple/system.rs:200-204; Cargo.lock resolves 0.33.1. The issue's fix 1 is genuinely a no-op.
Chunk position math ✅ Confirmed by exhaustive simulation (below)
cargo test -p nodespace-nlp-engine --release --lib ✅ 103 passed, 0 failed
N_CTX_FLOOR/KV_HEADROOM_BYTES/KV_BUDGET_PERCENT fully deleted ✅ Zero residue repo-wide — no commented-out corpses
No lint suppression / #[deprecated] / #[allow(dead_code)] / issue numbers in code comments / new .md files ✅ All clean
tools: None sites are per-request ✅ Confirmed — all 4 sites construct InferenceRequest, not a load path. Your reasoning holds.

Requirements Check (issue #1758)

  • ✅ AC 1 — E4B on 16 GB yields a usable window. I recomputed the budget from the constants: 17.18 GB − 5.34 GB weights − 4.5 GiB reserves ÷ 105 KiB/token → caps at the configured 32,768. No longer page-cache dependent.
  • ✅ AC 2 — ChatError::InsufficientMemory at load time, naming total RAM, weight size, shortfall, and a concrete next step ("Choose a smaller model"). This is a genuine improvement over an opaque per-turn overflow.
  • ⚠️ AC 3 — Partially met. aichat.ts single turns (incl. a 10,787-token/~6-chunk prompt) were run, but not the full aichat-matrix.ts suite. See Finding 3 — I consider this immaterial to merge, and here's why.
  • ✅ AC 4 — OOM protection preserved. 12B computes 26,624, below the 27,136 that OOM'd, and the test asserts weights + KV + reserves ≤ total RAM.

On the deviations: both are correctly argued. Skipping the mach probe avoids unsafe FFI against a #[repr(packed)] struct for provably zero benefit — that is YAGNI applied correctly, and rejecting a spec whose premise measurement disproved is the right call. Skipping KV quantization is right because E4B reaches its full window at F16; forcing Q8_0 would cost Metal throughput and quality to buy headroom that isn't needed.


Findings

🟡 Important 1 — N_CTX_MINIMUM makes every model unloadable on an 8 GB machine

📁 packages/nlp-engine/src/chat/mod.rs:1289 (N_CTX_MINIMUM), 1275-1283 (reserves)

This is the one finding I'd want addressed. The fixed reserves total 4.5 GiB, and the error is a hard failure. I computed the resulting matrix:

RAM E4B (5.3 GB) 12B (7.4 GB) 31B (18.7 GB)
8 GB ❌ 0 ❌ 0 ❌ 0
16 GB ✅ 32,768 ✅ 26,624 ❌ 0
24 GB ✅ 32,768 ✅ 32,768 ✅ 17,408
32 GB+ ✅ 32,768 ✅ 32,768 ✅ 32,768

Reaching N_CTX_MINIMUM with E4B requires 11.11 GiB of total RAM (4.97 weights + 1.64 KV + 4.50 reserves). On 8 GB the budget is negative before the KV cache is even considered, so an 8 GB Mac gets a hard load error for the smallest catalog model — where the old code, however wrongly sized, at least produced something. The reserves consume 56% of an 8 GB machine but only 14% of a 32 GB one; a fixed subtraction is regressive at the low end.

This is a behavioral regression on a machine class that was never tested (n=1, 16 GB M2 Pro). It may well be the honest answer — E4B at 16K F16 genuinely may not fit in 8 GB — but that conclusion is currently an accident of three constants, not a decision anyone made.

Recommendation (pick one; I'd take the second):

  1. Confirm 8 GB is formally unsupported and say so in the error text, or
  2. Make the reserves proportional at the low end, e.g. OS_RESERVE = min(3 GiB, total_ram / 4), preserving current behavior at ≥16 GB while degrading gracefully below it, or
  3. Fall back to Q8_0 KV before erroring — it drops the E4B requirement from 11.11 → 10.29 GiB, and this is precisely the situation the issue's fix 4 was aimed at.

Principle: fail-fast must be calibrated to the supported hardware envelope. A hard error is only better than a degraded window if the machine genuinely cannot work; asserting that from a single machine's measurements over-generalizes.

🟡 Important 2 — Budgeting against total RAM is macOS-shaped but ungated

📁 packages/nlp-engine/src/chat/mod.rs:1275-1283, 1296-1301

The doc for OS_RESERVE_BYTES explicitly reasons from macOS behavior ("macOS pages other processes out under pressure"), and the whole total-RAM approach is justified by macOS's compressor accounting. But the code is unconditional across all platforms.

On Linux, available_memory() (via MemAvailable) is a genuinely good signal and does not have the compressor pathology — the premise for discarding it doesn't hold there. On a Linux box where another process holds 20 GB of a 32 GB machine, this budgets as if all 32 GB were free and can over-commit into the OOM killer. Unified memory also makes total RAM a better proxy on Apple Silicon than on a discrete-GPU Linux box, where VRAM is the real constraint.

I am not asking for #[cfg] branches in this PR — that's scope creep, and macOS is the shipping target. But the constants' rationale should state the platform assumption so the next person doesn't port it blindly. A one-line note that non-macOS sizing is unvalidated would do it.

Principle: encode the validity domain of an empirical constant next to the constant.

🟢 Suggestion 3 — aichat-matrix.ts gap (AC 3) is immaterial

📁 verification scope

You flagged this yourself. My assessment: not a blocker. The 10,787-token/~6-chunk prompt exercises the actual risk this PR introduces (multi-chunk position continuity) more directly than the matrix would, and ai_chat_send_to_idle_test going 300s-timeout/assistant_count=0 → passing in 33s is strong independent evidence. The matrix adds scenario breadth, not coverage of the risky code path. Worth running before relying on it for future decomposition work, but it shouldn't gate this.

🟢 Suggestion 4 — Stale comment now contradicts the code

📁 packages/nlp-engine/src/chat/mod.rs:121-122

/// Unlike the embedding context, the chat context does NOT use embeddings mode and has a fixed batch size matching the context window.

The batch size no longer matches the context window — decoupling them is the point of this PR. This sits four lines above with_n_batch(PREFILL_BATCH_TOKENS). Given CLAUDE.md's warning not to infer architecture from stale comments, this is worth the one-line fix.

🟢 Suggestion 5 — fs::metadata failing open is defensible, but note the asymmetry

📁 packages/nlp-engine/src/chat/mod.rs:1330-1343

On stat failure the code returns Ok(configured) — skipping sizing entirely. I think failing open is correct here: the file was just loaded successfully by llama.cpp, so a stat failure is near-impossible, and llama.cpp still enforces real limits at allocation time. The comment explains this well.

Worth noting the asymmetry though: a stat failure yields the most aggressive window (full 32K), i.e. the failure mode skips the very protection AC 4 demands. Since the model loaded, metadata failing implies something pathological. Fine as-is — flagging so the trade-off is a recorded decision.

🟢 Nit 6 — KvGeometry is lint-driven but lands on the right abstraction

📁 packages/nlp-engine/src/chat/mod.rs:1224-1252

You asked me to judge whether this is real design or clippy appeasement. It was prompted by too_many_arguments, but it's the right call regardless: the five fields are genuinely one cohesive concept (model shape + element width), it has real behavior (bytes_per_token()), and moving the degenerate-geometry guard inside it removed duplicated validation. Passing n_head/n_head_kv as separate u32s was also an easy transposition bug. Keep it.

One inconsistency: bytes_per_elem is per-element width, not geometry, so the struct is slightly two things. Immaterial.


Highest-risk area: chunked prefill — verified correct

📁 packages/nlp-engine/src/chat/mod.rs:461-490

I simulated the position arithmetic exhaustively rather than eyeballing it, since an off-by-chunk error corrupts RoPE silently:

tokens decode_from contiguous logits count chunks
10,787 0 ✅ 1 6
10,787 4,096 ✅ 1 4
2,048 / 2,049 0 ✅ 1 1 / 2
4,097 2,048 ✅ 1 2
32,768 0 ✅ 1 16
6,000 5,999 ✅ 1 1

All four of your specific questions check out:

  • pos is absolute — chunk_start = decode_from + chunk_idx * PREFILL_BATCH_TOKENS. Since chunks() partitions tokens[decode_from..] into exact PREFILL_BATCH_TOKENS strides, decode_from + chunk_idx * stride is exactly the absolute index of each chunk's head. Emitted positions are exactly decode_from..tokens.len(), contiguous, at every boundary including exact multiples.
  • logits on exactly one token — pos == last_idx is evaluated against the absolute position, so it fires once globally, never per-chunk.
  • Prefix reuse composes — decode_from shifts both the slice and chunk_start identically, so KV trim at prefix_len and the chunk walk stay in lockstep.
  • batch.clear() placement is sound — cleared at the top of each iteration; clear() resets initialized_logits, so no stale logit flags leak between chunks. Reusing one allocation across chunks is a genuine improvement over the old per-call LlamaBatch::new(effective_n_ctx) — that allocation shrank from 32K to 2048 slots.

The subtlety worth stating explicitly (correct, but load-bearing and undocumented): sampler.sample(ctx, batch.n_tokens() - 1) at line 547 indexes into the final chunk's batch, not the full prompt. This is right only because the global-last token always lands in the last chunk's final slot — which the simulation confirms holds in every case, including exact multiples of 2048. It's correct, but it's an invariant a future edit could break without any test failing. Worth a one-line comment at the sampling site noting it depends on the last chunk ending at last_idx.

The debug_assert! on pending non-empty is good defensive practice; note it compiles out in release, but the prompt_tokens >= effective_n_ctx guard upstream plus prefix_len < tokens.len() in has_reusable_prefix already make the empty case unreachable.


Test quality — genuinely guards behavior

Above average. These are not restatements of the implementation:

  • fit_is_monotonic_in_total_memory — sweeps 1–64 GiB asserting more RAM never shrinks the window. Catches sign/saturation errors a point test would miss. This is the strongest test in the file.
  • fit_never_exceeds_configured_and_stays_aligned — property-style invariant sweep.
  • fit_throttles_12b_below_known_oom_window — anchored to the real 27,136 OOM datum, and independently asserts weights + KV + reserves ≤ total RAM rather than hardcoding an expected number.
  • fit_gives_e4b_full_window_on_16gb — asserts the 105 KiB/token figure derived from the actual GGUF.

On the const-block assertion in n_ctx_minimum_exceeds_agent_system_prompt: using const { assert!(...) } makes it a compile-time check, so the invariant can't be broken even transiently. That's stronger than a runtime test. Minor caveat: the 6_600 literal duplicates a number that really lives in agent_loop.rs, so it won't notice if the system prompt grows — which is exactly the drift your PR description flags re: SYSTEM_PROMPT_BUDGET = 4_000.

Gap: no test covers the chunking itself. The position math is the riskiest code here and is verified only by manual end-to-end runs. It's hard to unit-test (needs a live LlamaContext), but extracting the position calculation into a free function — fn chunk_positions(decode_from, len, stride) -> impl Iterator — would make it testable and lock in the invariant that the last chunk ends at last_idx. Worth doing given silent corruption is the failure mode.


Standards compliance

✅ No lint suppression · ✅ no #[deprecated]/#[allow(dead_code)] · ✅ deleted code actually deleted · ✅ tracing:: not println! · ✅ no .md files added · ✅ no issue numbers in code comments (the #1758/#1761 references are confined to the commit message and PR body, which is correct) · ✅ no backward-compat shims.


Recommendation: APPROVE

This fixes a total-failure bug in the local-agent surface, replaces an empirically-tuned budget that measurement showed was keyed off a signal that lies, and does it with better tests than it found. The root-cause analysis is the strongest part: the author disproved the issue's stated cause with instrumentation and correctly declined two specified fixes rather than implementing them for compliance.

Approving because the one substantive finding is a constant tuning question on an untested machine class, not a defect in the merged path — the 16 GB behavior is verified end-to-end, and the risky chunking logic is provably correct.

Before or shortly after merge:

  1. 🟡 Decide the 8 GB story explicitly (Finding 1) — currently every model hard-fails there
  2. 🟡 Note the macOS assumption beside the reserve constants (Finding 2)
  3. 🟢 Fix the stale n_batch comment at mod.rs:121-122 (Finding 4)
  4. 🟢 Comment the sampling-index invariant at mod.rs:547

Items 3 and 4 are one-liners I'd fold into this PR. Item 1 is worth its own issue if 8 GB is a supported configuration.

@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.

Review verdict: APPROVE (posted as a comment — GitHub blocks self-approval on your own PR).

Full report: #1762 (comment)

Independently verified: sysinfo 0.33.1 does compute free+inactive+purgeable−compressor (system.rs:200-204), so the issue's fix 1 is genuinely a no-op; chunk position math is correct at every boundary (exhaustive simulation, incl. exact multiples of 2048 and the prefix-reuse offset); 103 lib tests pass; deleted constants left zero residue; no issue numbers in code comments.

Non-blocking follow-ups: (1) 🟡 N_CTX_MINIMUM + 4.5 GiB fixed reserves make every catalog model — including E4B — hard-unloadable on an 8 GB machine (needs 11.11 GiB to reach the minimum); worth an explicit decision. (2) 🟡 total-RAM budgeting is macOS-shaped but ungated. (3) 🟢 stale "batch size matching the context window" comment at mod.rs:121-122. (4) 🟢 sampling at mod.rs:547 depends on the last chunk ending at last_idx — correct, but worth a comment.

…nking invariant

Review findings on PR #1762.

**Important — 8GB machines could not load a model the catalog says fits.**
The flat 3 GiB OS reserve is a modest slice of 32GB but nearly half of 8GB.
Ministral 3B (catalogued min_memory_gb: 8, ~2.1GB weights) computed a
12,288-token window on an 8GB machine — a perfectly usable size, but just under
N_CTX_MINIMUM, so it was refused outright. The reserve is now capped at
total_ram / 4, which leaves 16GB and above untouched (the flat value is already
the smaller of the two there) and degrades proportionally below it. Ministral 3B
on 8GB now gets 20,480. E4B and 12B on 8GB still compute 0 and are still
refused, correctly — their weights genuinely do not fit, and both are
catalogued at min_memory_gb: 16.

**Important — the platform assumption was undocumented.** The total-RAM budget
is calibrated on Apple Silicon, where unified memory makes total RAM a good
proxy for what a GPU allocation can obtain. The reserve now records that
validity domain so the next person does not port it blindly to a discrete-GPU
platform, where VRAM is the real ceiling, or to a memory manager whose
"available" figure is trustworthy.

**Suggestion — the chunking position math had no unit test.** It was verified
only by manual runs, and an off-by-chunk error corrupts RoPE silently rather
than failing. Extracted `prefill_chunk_start` and added
`prefill_chunk_positions` (test-only) mirroring the emission loop, with tests
asserting contiguous absolute positions and exactly one logits request across
nine boundary cases — exact stride multiples, one either side, and prefix reuse
landing on a stride boundary. Also documented the load-bearing invariant at the
sampling site: it indexes the final chunk's batch, which is only correct because
the prompt's last token lands in that chunk's final slot.

**Suggestion — stale comments.** `get_or_create_context` still claimed a "fixed
batch size matching the context window" (decoupling them is the point of this
change) and "sized to available memory" (no longer the signal used).

Not addressed, deliberately:
- aichat-matrix.ts scenario suite — the reviewer judged this immaterial and I
  agree: the 10,787-token multi-chunk run exercises the risky path introduced
  here more directly than the matrix would.
- fs::metadata failing open — reviewer concluded it is correct; the asymmetry is
  already recorded in the comment at that site.
- KvGeometry — reviewer confirmed it is the right abstraction; keeping it.

Verified after the change: E4B still loads at n_ctx=32768; a 10,787-token
multi-chunk prompt still returns a coherent single-word answer; the Tauri-seam
ai-chat test passes in 33s; 94 chat tests pass.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed — 5aeb2706

✅ 🟡 Finding 1 — 8 GB machines couldn't load a model the catalog says fits

Confirmed the reviewer's arithmetic (E4B needs 11.11 GiB to clear the minimum), and found a sharper case while checking it: Ministral 3B is catalogued min_memory_gb: 8 with ~2.1 GB weights, and computed a 12,288-token window on an 8 GB machine — usable, but just under N_CTX_MINIMUM, so it was refused outright. A model the catalog advertises as fitting became unloadable.

Took option 2 (proportional reserve), now capped at total_ram / 4:

model 8 GB 16 GB 24 GB 32 GB
Ministral 3B 20,480 (was refused) 32,768 32,768 32,768
E4B 0 → refused ✓ 32,768 32,768 32,768
Gemma 12B 0 → refused ✓ 26,624 32,768 32,768

16 GB and above is bit-for-bit unchanged — the flat 3 GiB is already the smaller value there, so the measured machine class is untouched (guarded by a new test). E4B/12B on 8 GB still refuse, correctly: their weights genuinely don't fit and both are catalogued at min_memory_gb: 16.

I did not take option 3 (Q8_0 fallback) — silently changing inference precision to squeeze under a memory bound trades a visible failure for an invisible quality change, and it would re-introduce the KV-quant coupling this PR deliberately avoided.

✅ 🟡 Finding 2 — platform assumption undocumented

OS_RESERVE_BYTES now records its validity domain: calibrated on Apple Silicon where unified memory makes total RAM a good proxy; unvalidated on discrete-GPU platforms (VRAM is the real ceiling) or where the OS "available" figure is trustworthy. No #[cfg] branching, per your scope call.

✅ 🟢 Chunking position math had no unit test

This was the most valuable catch — verified only by manual runs, and the failure mode is silent corruption. Extracted prefill_chunk_start, added a test-only prefill_chunk_positions mirroring the emission loop, and asserted contiguous absolute positions + exactly one logits request across nine boundary cases (exact stride multiples, one either side, prefix reuse landing on a stride boundary).

Also documented the invariant you flagged at the sampling site: it indexes the final chunk's batch, correct only because the prompt's last token lands in that chunk's final slot.

✅ 🟢 Finding 4 — stale comments

get_or_create_context claimed a "fixed batch size matching the context window" (decoupling them is the point of this PR) and "sized to available memory" (no longer the signal used). Both corrected.

⏭️ Skipped, with reasoning

  • 🟢 3 aichat-matrix.ts — you judged it immaterial and I agree: the 10,787-token multi-chunk run exercises the code path this PR actually introduces more directly than scenario breadth would.
  • 🟢 5 fs::metadata fail-open — you concluded it's correct; the asymmetry is already recorded in the comment at that site. Flagging it as a recorded decision was the ask, and it is.
  • 🟢 6 KvGeometry — you confirmed it's the right abstraction. Keeping it.

Verification after the change

E4B still loads at n_ctx=32768; the 10,787-token multi-chunk prompt still returns a coherent single-word answer; ai_chat_send_to_idle_test passes in 33s; 94 chat tests pass; full pre-push gate green.

Incidentally confirmed the system-prompt figure: a bare turn logged 6,551 prompt tokens, which is why the old 4096 floor failed 100% of tool-using turns.


Note on review status: the review above was produced by an AI reviewer on my own changes, and GitHub correctly blocked it from self-approving. It should be read as advisory input, not as an approval — this PR still has zero human approvals, and the merge decision is the maintainer's.

@malibio
malibio merged commit 1d43c23 into main Jul 28, 2026
2 checks passed
@malibio
malibio deleted the worktree-issue-1758-chat-context-memory-probe branch July 28, 2026 08:24
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.

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

1 participant