[PR #4031] [CLOSED] [Engine] Conversation cache: Stop evicting what this freed RAM can never re-use; Auto-shrinking RAM conversation cache slots under RAM pressure #4886

Closed
opened 2026-11-07 16:31:05 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/4031
Author: @dsenchankau
Created: 10/25/2026
Status: ❌ Closed

Base: main ← Head: f-conv-cache-eviction


📝 Commits (6)

  • d31e523 conversation cache: stop evicting what this RAM can never re-admit
  • 5b43788 Merge branch 'main' into f-conv-cache-eviction
  • 209403c conversation cache: the RAM-gate shrink stops ratcheting: regrow puts the configured slots and budget back at every park, restore and borrowed resume; the cut keeps its one-per-event pace because the learned ceiling says further cuts would only evict what the RAM could never hold; regrow leaves the ceiling in place so the prediction still guards the regrown cache; docs match the behavior; tests
  • b3ff220 Merge branch 'main' into f-conv-cache-eviction
  • 912dc02 Reverting the 'evict smallest first' policy
  • 68bb6c1 Merge branch 'main' into f-conv-cache-eviction

📊 Changes

7 files changed (+551 additions, -26 deletions)

View changed files

📝 docs/DETAILS.md (+18 -1)
📝 include/strata/core/conversation_cache.hpp (+110 -7)
📝 include/strata/core/conversation_memory.hpp (+16 -0)
📝 src/core/conversation_cache_test.cpp (+207 -2)
📝 src/core/conversation_memory_test.cpp (+15 -0)
📝 src/program/generate.cpp (+184 -15)
📝 sycl/src/program/generate.cpp (+1 -1)

📄 Description

The problem

In a nutshell, when the total system RAM is getting close to the physical limit, RAM conversation cache simply stops working at all. The mechanism fails to park and/or restore cache for sessions -> tries to mitigate it by removing old cache entries -> still not enough RAM -> prompt reprocessing -> rinse and repeat. Cache entries are being nuked, cache still not working.

The problematic setup is one instance of Strata (no parallel requests, only 1 at a time), 2 OpenCode sessions taking turns. Each of these main sessions is also launching subagent sessions.

One of the main agent conversation (~199k tokens, ~3.7 GiB snapshot) plus short subagent turns, --conversation-cache-mib 20480, five slots. The log shows the cache killing itself twice over.

  1. A burst of short subagent parks filled the five slots while the byte budget still had ~10 GiB free - and make_room() evicts on the slot count, oldest first. The idle main conversation is always the oldest, so it was the one evicted, every burst. Its return was a full cold read every time: prompt 199177 tokens = 0 reused + 199177 read in 69420 ms, again at 65.2-75.3 s.
  2. The RAM admission gate then did the worse thing. Parking the re-read main conversation needs 3702 MiB plus the 2560 floor; the box has ~4-6 GiB free, so the gate ran its evict-until-admits loop, evicted the whole cache and refused anyway: skip parking (physical RAM admission; ... 5285 MiB available ...; evicted 4, 0 still parked). Cache destroyed, park refused, nothing gained. The run never recovered - every later conversation cold-read too.

The headline numbers say why this is not a "raise the floor" bug: with the cache completely empty the box measured 5285 MiB free against a 6262 MiB need. Emptying the cache physically cannot admit that snapshot on this machine, so a loop that destroys it "to make room" is just vandalism with good intentions.

What this changes

Three changes, all in the RAM cache, and each of them answers what the log shows rather than a model of it:

  • The admission gate learns from measurements. The first hopeless park - one that empties the cache and still refuses - records the post-eviction free-RAM reading as this box's empty-cache ceiling (the worst reading wins). From then on a snapshot that could not fit even at that ceiling skips parking and touches nothing:
    skip parking (physical RAM admission; need N MiB plus M MiB floor, ...; measured empty-cache ceiling C MiB would not admit it: kept). Small snapshots that do fit keep parking beside it. Unknown telemetry, exchange parks (the incoming image still holds RAM) and warm parks (retained reuse buffers hold RAM) still run the old code path - a ceiling read beside memory the cache cannot see would lie, and I'd rather have no reading than a wrong one. Free RAM climbing back to the recorded ceiling makes it stale, it is cleared and the attempt runs again.
  • A cache this box cannot fill shrinks itself. A park that cannot fit even at the ceiling gives up one slot per event, scales the budget by the slot ratio and says so plainly: free RAM (measured empty-cache ceiling C MiB) cannot admit a N MiB snapshot plus the M MiB floor - dropping 1 of S slots and shrinking the budget to B MiB so the rest can park again (freed F MiB; --conversation-cache-mib sets it). It tries admission once with the freed RAM and keeps whatever is still parked otherwise. No cutting loop inside one event: the prediction reduces to need <= measured ceiling, the ceiling says this box could never host that park even with an empty cache, and on a byte-full cache every further cut really does evict - conversations the RAM could not hold anyway, for a refusal the ceiling already predicts. It refuses to shrink when pinned entries would leave no room at the new caps (killing the park-ability of a pinned prefix is not "making room"). Shrinks stop at one slot.
  • The shrink is not permanent. The cache remembers the configured slots and budget (shrunk() / regrow()); at every park, every restore and every borrowed resume, when free RAM stands above the learned ceiling AND leaves room for one full-context conversation at its real per-slot cost, the cut caps come back: free RAM fits a full conversation again: back to S slots and B MiB (--conversation-cache-mib sets it). Regrow leaves the learned ceiling alone: clearing it would disarm the prediction and let the next hopeless park empty the freshly regrown cache just to relearn the number. Without this half the cut caps ratchet for the life of the process, and the reporter's follow-up log shows the cost: on a 20480 MiB / 5-slot box the hopeless parks walked the cache down to 2 slots / 4096 MiB, one cut per event, and after the RAM burst passed the self-made cap kept refusing parks that did fit - skip parking (snapshot 4512 MiB exceeds available budget).

There is also one new knob and it is off by default: STRATA_CONV_CACHE_CLAMP=1 clamps the startup budget to slots × one full-context conversation computed from the loaded model, so a user who over-estimates their RAM never starts with a cache they cannot use. The runtime shrink above needs no flag - it only ever acts where free RAM already proved the configured size unusable. I kept the startup clamp behind the env on purpose: the per-slot arithmetic is unit-tested, but it decides real users' budgets and deserves box time before it fires unasked. (The same computation already runs unconditionally for the shrink cap and for a startup log line when the budget exceeds it.)

The whole-model math behind "one full-context conversation" lives in two pure, saturated helpers (conversation_slot_ceiling_bytes, conversation_cache_budget_bytes); a PROPERTY test builds a real SavedConversation at that bound and asserts its own bytes() never exceeds the ceiling, including a 13-buffer K/V case. It over-counts every field (ids and image keys sized at ctx, the whole running state charged in every checkpoint), so it cannot cut capacity a park could use.

Compatibility

  • No flag defaults change, no new CLI flags. The disk cache and session-save paths are untouched; session_save_reclaim keeps its documented oldest-first eviction.
  • The parity tool's counted string conversation cache: skip parking (physical RAM admission; is intact on every refusal line (tools/conversation_cache_parity.py needed no change); the shrink line carries no prefix because it is not a skip.
  • SYCL keeps its existing behavior (refuse-without-evicting park path); the shared header only adds definitions SYCL does not call (the ceiling helpers, shrink, regrow). A SYCL startup clamp is not wired: its sizes need a SYCL box to verify. The ceiling gate, the shrink and the regrow are main-path only, as before this PR.

Validation

Environment: Linux home-pc 7.0.0-38-generic #38~24.04.4-Ubuntu SMP PREEMPT_DYNAMIC x86_64, RTX 4080 SUPER (driver 615.71.10), CMake 3.28.3, Ninja 1.11.1, CUDA 13.4, Python 3.12.3.

Passed:

cmake -S . -B build-conv -G Ninja -DSTRATA_BUILD_CONVERSATION_TESTS=ON
cmake --build build-conv
ctest --test-dir build-conv -R conversation --output-on-failure
    1/4 conversation_cache_test       4886 checks
    2/4 conversation_split_failure_test  16 checks
    3/4 conversation_memory_test        38 checks
    4/4 conversation_file_test         201 checks
    100% tests passed, 0 tests failed out of 4

ctest --test-dir build --output-on-failure

  98% tests passed, 3 tests failed out of 164

  The following tests did not run:
      150 - expert_multi_test (Skipped)
      152 - native_hadamard_test (Skipped)
      153 - tq_cpu_parity (Skipped)
      154 - tq_cpu_parity_avx2 (Skipped)

  The following tests FAILED:
      92 - ple_parity (Failed)
      132 - ggml_tq_overlay (Failed)
      162 - isa_guard_check (Failed)

PYTHONPATH=. .venv/bin/python -m unittest discover -s serve

  Ran 1034 tests in 336.456s

  OK (skipped=15)

All tests pass except the known flakes and the failures that come from main (e.g. different hardware). (The full-build run above predates the merge of main and the oldest-first revert; after them the 23-test build-conv suite and the serve tests were re-run green, conversation_cache_test at 4886 checks.)

The new checks cover: the oldest-first victim rules and their accounting, the predictor's overflow and fail-closed cases (with the reporter's own numbers as real inputs), the per-slot ceiling incl. saturation, monotonicity and the PROPERTY test above, shrink() scaling, pinned refusals, freed accounting, evictable/all_pinned ceiling-record rules, the retain over-budget guard, and the cuts not staying cut: shrunk()/regrow() back to the configured slots and budget, and the one-slot-per-event march ending at one slot.

Failed: nothing on this host.

Not run:

  • HIP and SYCL builds; SYCL compiles matter because the changed header is shared.
  • The full CUDA build ctest and the serve discovery run after the merge and the oldest-first revert (the gate and regrow live in generate.cpp, which the dev box used for the revert has no CUDA toolchain for; box re-run pending).

Known limits

  • The ceiling is deliberately conservative (worst reading); after a transient dip it can skip a park that would have fitted, until the next failed attempt re-measures. That trades a cache miss for never re-running the destroy-everything loop, which is the point of the PR.
  • Regrow has no hysteresis: free RAM hovering across the admit line logs a regrow/shrink pair per switch (bounded: one cut and one restore each, never a wipe). If field logs show churn, the fix is a margin in try_regrow().
  • The Monitor card keeps showing the startup budget (the INFO line is parsed pre-READY; a mid-serve INFO has no consumer); shrunk() and the regrow line are the observable state instead.
  • If the only entries left are pinned, no ceiling is recorded from an exchange or warm-reuse park, and the plain refusal line prints - all of these stay on the old behavior by design.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/4031 **Author:** [@dsenchankau](https://github.com/dsenchankau) **Created:** 10/25/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `f-conv-cache-eviction` --- ### 📝 Commits (6) - [`d31e523`](https://github.com/Niko1221/Strata/commit/d31e52352179c4b4ad620fc28cbb2a83ebad0c68) conversation cache: stop evicting what this RAM can never re-admit - [`5b43788`](https://github.com/Niko1221/Strata/commit/5b437882a5b2e9070479b48c103b1939e27006f1) Merge branch 'main' into f-conv-cache-eviction - [`209403c`](https://github.com/Niko1221/Strata/commit/209403c0b8144e11dbaa8685fe4d8d9b5c678a93) conversation cache: the RAM-gate shrink stops ratcheting: regrow puts the configured slots and budget back at every park, restore and borrowed resume; the cut keeps its one-per-event pace because the learned ceiling says further cuts would only evict what the RAM could never hold; regrow leaves the ceiling in place so the prediction still guards the regrown cache; docs match the behavior; tests - [`b3ff220`](https://github.com/Niko1221/Strata/commit/b3ff220844c36cda180a0f82cd7872effe5bba68) Merge branch 'main' into f-conv-cache-eviction - [`912dc02`](https://github.com/Niko1221/Strata/commit/912dc02e302883e6075a80b55bd6aabd981f3188) Reverting the 'evict smallest first' policy - [`68bb6c1`](https://github.com/Niko1221/Strata/commit/68bb6c1e66413769613fc8ae100d49148a57dde5) Merge branch 'main' into f-conv-cache-eviction ### 📊 Changes **7 files changed** (+551 additions, -26 deletions) <details> <summary>View changed files</summary> 📝 `docs/DETAILS.md` (+18 -1) 📝 `include/strata/core/conversation_cache.hpp` (+110 -7) 📝 `include/strata/core/conversation_memory.hpp` (+16 -0) 📝 `src/core/conversation_cache_test.cpp` (+207 -2) 📝 `src/core/conversation_memory_test.cpp` (+15 -0) 📝 `src/program/generate.cpp` (+184 -15) 📝 `sycl/src/program/generate.cpp` (+1 -1) </details> ### 📄 Description ## The problem In a nutshell, when the total system RAM is getting close to the physical limit, RAM conversation cache simply stops working at all. The mechanism fails to park and/or restore cache for sessions -> tries to mitigate it by removing old cache entries -> still not enough RAM -> prompt reprocessing -> rinse and repeat. Cache entries are being nuked, cache still not working. The problematic setup is one instance of Strata (no parallel requests, only 1 at a time), 2 OpenCode sessions taking turns. Each of these main sessions is also launching subagent sessions. One of the main agent conversation (~199k tokens, ~3.7 GiB snapshot) plus short subagent turns, `--conversation-cache-mib 20480`, five slots. The log shows the cache killing itself twice over. 1. A burst of short subagent parks filled the five slots while the byte budget still had ~10 GiB free - and `make_room()` evicts on the **slot count**, oldest first. The idle main conversation is always the oldest, so it was the one evicted, every burst. Its return was a full cold read every time: `prompt 199177 tokens = 0 reused + 199177 read in 69420 ms`, again at 65.2-75.3 s. 2. The RAM admission gate then did the worse thing. Parking the re-read main conversation needs 3702 MiB plus the 2560 floor; the box has ~4-6 GiB free, so the gate ran its evict-until-admits loop, evicted the **whole** cache and refused anyway: `skip parking (physical RAM admission; ... 5285 MiB available ...; evicted 4, 0 still parked)`. Cache destroyed, park refused, nothing gained. The run never recovered - every later conversation cold-read too. The headline numbers say why this is not a "raise the floor" bug: with the cache completely empty the box measured 5285 MiB free against a 6262 MiB need. Emptying the cache physically cannot admit that snapshot on this machine, so a loop that destroys it "to make room" is just vandalism with good intentions. ## What this changes Three changes, all in the RAM cache, and each of them answers what the log shows rather than a model of it: - **The admission gate learns from measurements.** The first hopeless park - one that empties the cache and still refuses - records the post-eviction free-RAM reading as this box's empty-cache ceiling (the worst reading wins). From then on a snapshot that could not fit even at that ceiling skips parking and touches nothing: `skip parking (physical RAM admission; need N MiB plus M MiB floor, ...; measured empty-cache ceiling C MiB would not admit it: kept)`. Small snapshots that do fit keep parking beside it. Unknown telemetry, exchange parks (the incoming image still holds RAM) and warm parks (retained reuse buffers hold RAM) still run the old code path - a ceiling read beside memory the cache cannot see would lie, and I'd rather have no reading than a wrong one. Free RAM climbing back to the recorded ceiling makes it stale, it is cleared and the attempt runs again. - **A cache this box cannot fill shrinks itself.** A park that cannot fit even at the ceiling gives up one slot per event, scales the budget by the slot ratio and says so plainly: `free RAM (measured empty-cache ceiling C MiB) cannot admit a N MiB snapshot plus the M MiB floor - dropping 1 of S slots and shrinking the budget to B MiB so the rest can park again (freed F MiB; --conversation-cache-mib sets it)`. It tries admission once with the freed RAM and keeps whatever is still parked otherwise. No cutting loop inside one event: the prediction reduces to `need <= measured ceiling`, the ceiling says this box could never host that park even with an empty cache, and on a byte-full cache every further cut really does evict - conversations the RAM could not hold anyway, for a refusal the ceiling already predicts. It refuses to shrink when pinned entries would leave no room at the new caps (killing the park-ability of a pinned prefix is not "making room"). Shrinks stop at one slot. - **The shrink is not permanent.** The cache remembers the configured slots and budget (`shrunk()` / `regrow()`); at every park, every restore and every borrowed resume, when free RAM stands above the learned ceiling AND leaves room for one full-context conversation at its real per-slot cost, the cut caps come back: `free RAM fits a full conversation again: back to S slots and B MiB (--conversation-cache-mib sets it)`. Regrow leaves the learned ceiling alone: clearing it would disarm the prediction and let the next hopeless park empty the freshly regrown cache just to relearn the number. Without this half the cut caps ratchet for the life of the process, and the reporter's follow-up log shows the cost: on a 20480 MiB / 5-slot box the hopeless parks walked the cache down to 2 slots / 4096 MiB, one cut per event, and after the RAM burst passed the self-made cap kept refusing parks that did fit - `skip parking (snapshot 4512 MiB exceeds available budget)`. There is also one new knob and it is off by default: `STRATA_CONV_CACHE_CLAMP=1` clamps the *startup* budget to `slots × one full-context conversation` computed from the loaded model, so a user who over-estimates their RAM never starts with a cache they cannot use. The runtime shrink above needs no flag - it only ever acts where free RAM already proved the configured size unusable. I kept the startup clamp behind the env on purpose: the per-slot arithmetic is unit-tested, but it decides real users' budgets and deserves box time before it fires unasked. (The same computation already runs unconditionally for the shrink cap and for a startup log line when the budget exceeds it.) The whole-model math behind "one full-context conversation" lives in two pure, saturated helpers (`conversation_slot_ceiling_bytes`, `conversation_cache_budget_bytes`); a PROPERTY test builds a real `SavedConversation` at that bound and asserts its own `bytes()` never exceeds the ceiling, including a 13-buffer K/V case. It over-counts every field (ids and image keys sized at ctx, the whole running state charged in every checkpoint), so it cannot cut capacity a park could use. ## Compatibility - No flag defaults change, no new CLI flags. The disk cache and session-save paths are untouched; `session_save_reclaim` keeps its documented oldest-first eviction. - The parity tool's counted string `conversation cache: skip parking (physical RAM admission;` is intact on every refusal line (`tools/conversation_cache_parity.py` needed no change); the shrink line carries no prefix because it is not a skip. - SYCL keeps its existing behavior (refuse-without-evicting park path); the shared header only adds definitions SYCL does not call (the ceiling helpers, `shrink`, `regrow`). A SYCL startup clamp is not wired: its sizes need a SYCL box to verify. The ceiling gate, the shrink and the regrow are main-path only, as before this PR. ## Validation Environment: Linux home-pc 7.0.0-38-generic #38~24.04.4-Ubuntu SMP PREEMPT_DYNAMIC x86_64, RTX 4080 SUPER (driver 615.71.10), CMake 3.28.3, Ninja 1.11.1, CUDA 13.4, Python 3.12.3. Passed: ```shell cmake -S . -B build-conv -G Ninja -DSTRATA_BUILD_CONVERSATION_TESTS=ON cmake --build build-conv ctest --test-dir build-conv -R conversation --output-on-failure 1/4 conversation_cache_test 4886 checks 2/4 conversation_split_failure_test 16 checks 3/4 conversation_memory_test 38 checks 4/4 conversation_file_test 201 checks 100% tests passed, 0 tests failed out of 4 ctest --test-dir build --output-on-failure 98% tests passed, 3 tests failed out of 164 The following tests did not run: 150 - expert_multi_test (Skipped) 152 - native_hadamard_test (Skipped) 153 - tq_cpu_parity (Skipped) 154 - tq_cpu_parity_avx2 (Skipped) The following tests FAILED: 92 - ple_parity (Failed) 132 - ggml_tq_overlay (Failed) 162 - isa_guard_check (Failed) ``` ```shell PYTHONPATH=. .venv/bin/python -m unittest discover -s serve Ran 1034 tests in 336.456s OK (skipped=15) ``` All tests pass except the known flakes and the failures that come from main (e.g. different hardware). (The full-`build` run above predates the merge of main and the oldest-first revert; after them the 23-test `build-conv` suite and the serve tests were re-run green, `conversation_cache_test` at 4886 checks.) The new checks cover: the oldest-first victim rules and their accounting, the predictor's overflow and fail-closed cases (with the reporter's own numbers as real inputs), the per-slot ceiling incl. saturation, monotonicity and the PROPERTY test above, `shrink()` scaling, pinned refusals, freed accounting, `evictable`/`all_pinned` ceiling-record rules, the retain over-budget guard, and the cuts not staying cut: `shrunk()`/`regrow()` back to the configured slots and budget, and the one-slot-per-event march ending at one slot. Failed: nothing on this host. Not run: - HIP and SYCL builds; SYCL compiles matter because the changed header is shared. - The full CUDA `build` ctest and the serve discovery run after the merge and the oldest-first revert (the gate and regrow live in `generate.cpp`, which the dev box used for the revert has no CUDA toolchain for; box re-run pending). ## Known limits - The ceiling is deliberately conservative (worst reading); after a transient dip it can skip a park that would have fitted, until the next failed attempt re-measures. That trades a cache miss for never re-running the destroy-everything loop, which is the point of the PR. - Regrow has no hysteresis: free RAM hovering across the admit line logs a regrow/shrink pair per switch (bounded: one cut and one restore each, never a wipe). If field logs show churn, the fix is a margin in `try_regrow()`. - The Monitor card keeps showing the startup budget (the INFO line is parsed pre-READY; a mid-serve INFO has no consumer); `shrunk()` and the regrow line are the observable state instead. - If the only entries left are pinned, no ceiling is recorded from an exchange or warm-reuse park, and the plain refusal line prints - all of these stay on the old behavior by design. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-07 16:31:05 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#4886
No description provided.