Merge branch 'f-142-engine2' into f-142

# Conflicts:
#	src/core/conversation_memory.cpp
This commit is contained in:
Niko1221 committed 2026-10-09 14:46:54 +02:00
commit e85f56209c
17 files changed
+1642 -35

No files matched your search

+12
View File
@@ -114,6 +114,9 @@ if(STRATA_BUILD_CONVERSATION_TESTS)
add_executable(conversation_file_test src/core/conversation_file_test.cpp src/core/conversation_file.cpp)
target_include_directories(conversation_file_test PRIVATE include)
add_test(NAME conversation_file_test COMMAND conversation_file_test)
add_executable(session_save_reclaim_test src/core/session_save_reclaim_test.cpp src/core/conversation_file.cpp)
target_include_directories(session_save_reclaim_test PRIVATE include)
add_test(NAME session_save_reclaim_test COMMAND session_save_reclaim_test)
endif()
if(STRATA_HIP_GFX906)
@@ -477,6 +480,15 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60)
endif()
# available_host_bytes(): MemAvailable, cgroup limits and the operator's --memory-limit-mib cap on fixture directories
# - no GPU, no CUDA
if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/memory_guard_test.cpp")
add_executable(memory_guard_test tests/core/memory_guard_test.cpp src/core/conversation_memory.cpp)
target_include_directories(memory_guard_test PRIVATE include)
add_test(NAME memory_guard_test COMMAND memory_guard_test)
set_tests_properties(memory_guard_test PROPERTIES TIMEOUT 60)
endif()
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")
enable_testing()
add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp)
+102 -4
View File
@@ -941,12 +941,90 @@ nothing and stores nothing; the log line is `conversation cache: skip parking (N
parked=P)`. 0 is the pre-flag behaviour and the flag leaves the answers untouched - it only decides which
conversations keep a slot.
`--conversation-cache-min-free-mib N` (default 2560) additionally requires that
physical-RAM headroom remain available: the engine checks before allocation and
again after capture. Unknown telemetry or insufficient RAM skips parking. Windows
uses `GlobalMemoryStatusEx`, Linux uses `MemAvailable`; these are host-level samples,
not a reservation or enforcement of container/job memory limits. An 8 GiB budget
RAM headroom remain available: the engine checks before allocation (against the
snapshot's estimated size, less the K/V it already retains) and again after capture.
Unknown telemetry or insufficient RAM skips parking, and the same figure and floor
decide whether a session file may be saved or restored (below). An 8 GiB budget
is a cap, not a recommendation for every machine.
**The RAM figure (`available_host_bytes()`).** The headroom is the smallest of three
numbers, sampled each time it is asked and not a reservation (other writers can take the
room afterwards):
1. `MemAvailable` (Windows: `GlobalMemoryStatusEx`'s available physical memory).
2. The room under each memory limit of the engine's own cgroup and of every ancestor
visible under `/sys/fs/cgroup` (the group named in `/proc/self/cgroup`, or the deepest
part of that path this mount shows): cgroup v2 `memory.max` and `memory.high`, each
minus `memory.current`; cgroup v1 `memory.limit_in_bytes` minus
`memory.usage_in_bytes` (both less the clean inactive file cache, below). `max` and v1's "unlimited" count as no limit; a file that is
absent (no memory controller at that level) is skipped; a file that is there but
cannot be read or parsed makes the cgroup terms unusable: without `--memory-limit-mib` the guard then uses
`MemAvailable` alone, as 0.1.41 did, and prints one warning per process; with the flag the sample is unknown, and unknown skips parking.
3. `--memory-limit-mib N` (or `STRATA_MEMORY_LIMIT_MIB=N`; the flag wins, `0` = none):
N MiB is the total this engine's container or cgroup may use, minus what that
container uses now. Use it when the container cannot see its own limit. The usage
is `memory.current` of the top cgroup this mount shows (the container's own, in a
container with its own cgroup namespace); if that file cannot be read it is
`MemTotal - MemAvailable`, which is a weaker figure (it is only as true as the
container's `/proc/meminfo`), and if `MemTotal` is missing too the sample is
unknown. The cap is taken in addition to 1 and 2, never instead of them: whichever
number is smallest decides. It is an engine argument, so the server config carries it in
`args` (`"--memory-limit-mib", "102400"`); the variable also works from the config's
`"env"`.
Usage is `memory.current` as the kernel reports it, **less one reclaimable kind: clean
inactive file cache**. That is the group's own `memory.stat` `inactive_file` (cgroup v1:
`total_inactive_file`), less its dirty and writeback pages when `memory.stat` lists them
(`file_dirty`, `file_writeback`; v1 `total_dirty`, `total_writeback`), and never more than
`memory.current`. The kernel gives such pages back at `memory.high` or the limit before
it kills anything, and a loaded model's file reads leave a lot of them behind. Nothing
else is credited: `active_file` (it holds the mlocked pages), `shmem` (pinned expert
complements, the KV pool) and anonymous memory stay charged in full, since a kill at a
hard limit is worse than a skipped park. For each limit the room is
`limit - (memory.current - credit)`, so it never exceeds the limit. A `memory.stat` that is missing or cannot be
parsed gives no credit; it does not make the sample unknown. The operator's cap uses the
`memory.stat` of the same top group whose `memory.current` it reads. A parked
conversation is part of the engine's own usage once captured; the check before
capture is what stops it from growing past the cap.
The startup log has one line for it, `strata generate: memory guard: limit X GiB
(source: flag|cgroup|meminfo), current Y GiB, reclaimable cache credited Z GiB;
available ...`, where `source` names the
number that was smallest at that moment (`meminfo`: MemTotal and `MemTotal -
MemAvailable`), and a skipped park or a refused save/restore says how much it had and
from which source. The line is printed before the model is loaded, so its credit is the
cache at that moment, not at the time of a park. Without a cgroup limit and without `--memory-limit-mib` the figure is
plain `MemAvailable`, as before.
What it does not touch: the startup sizing of the expert arena, the file tier's resident budget, the Windows commit
check and `STRATA_PIN_GUARD` (#1250: whether to page-lock the expert copy in steps follows `MemFree`, and each step
is checked against the cgroup-aware `host_available_memory`) keep their own probes (`--resident-budget-gib`, #633,
#1250), and `--memory-limit-mib` does not reach them. This figure is for what runs after the start: parking a
conversation and saving or restoring a session file, which read `MemAvailable` alone. `host_available_memory`
(expert_source.cpp) and this figure both read the cgroup limits; this one also reads `memory.high` and the operator's
cap; an unreadable cgroup file makes it fall back to `MemAvailable` (one warning), or unknown when a cap is set.
Earlier measurement on a Proxmox LXC where the engine's container cannot see its limit (a 100 GiB cap on the parent
cgroup, outside the container's namespace; the container's own `memory.max` and `memory.high` read `max`):
`/proc/meminfo` showed about 25 GiB `MemAvailable` while about 1 GiB was really left, and right after the engine had
loaded the container's `memory.current` was 98.29 GiB with `anon` 1.29 GiB, `shmem` 65.51 GiB, `inactive_file`
3.81 GiB (clean page cache left from reading the model files) and `active_file` 0.01 GiB, of which the 3.8 GiB of
clean cache is what the credit gives back. There `--memory-limit-mib 102400` is the cap, and the floor
(`--conversation-cache-min-free-mib`) is measured against what is left under it: with the engine already near the cap,
a floor of several GiB refuses every park; a few hundred MiB keeps a margin for the allocator and the kernel while
letting a snapshot that really fits go through.
Measured on the test machine (2x RTX 3080 20 GB, UD-Q4_K_XL, a 90 GiB container, resident RAM mode, 2 slots), one restart
per arm, `--conversation-cache-min-free-mib 2048`. With `--memory-limit-mib 101376` (the cap our deployment runs with)
the engine parked on every attempt: 135 parks and 0 skips over one run of 308 requests. With `--memory-limit-mib 78000`
the start line read `limit 76.2 GiB (source: flag) ... available 73.0 GiB (MemAvailable 88.6 GiB)`, and 8 of 8 parking
attempts were skipped (`skip parking (physical RAM admission; need 226 MiB plus 2048 MiB floor, 0 MiB available, source
flag)`), none parked. The container's `memory.current` sat at 89.7-89.9 GiB, above the 76.2 GiB cap, so the headroom
under the cap is 0, while `MemAvailable` read 15.7-15.9 GiB in the same samples; a check on `MemAvailable` alone would
have let those parks through (the old check was not run). The requests were served normally (median of 6 decodes
79.6 tok/s); only parking is refused, and the log says so. The unit test `memory_guard_test` (CPU only, no model) passes
130 checks. Not measured: a cap between 78000 and 101376, a run without the flag, any effect on throughput.
The shared snapshot core validates all layers and checkpoints before applying any
state. Invalid entries are discarded; transfer/synchronization failure is fatal
rather than permission to continue with partial state. Indexer spare keys and the
@@ -980,6 +1058,26 @@ NAME may
not contain a path, a drive, a stream (`:`), a Windows device name (`NUL`, `CON.bin`, `COM1`...), a control character,
a leading dot or a trailing dot or space.
`--session-save-reclaim` (an engine argument in the config's `args`, off by default) lets a SAVE that fails its
RAM preflight first release reconstructible host caches: retained K/V buffers, oldest unpinned parked
conversations, then unpinned checkpoints other than the one selected for the file. It stops as soon as measured
available RAM meets the original allocation estimate plus `--conversation-cache-min-free-mib`; it does not lower
that floor or assume that freed allocations have reached the OS. Pinned prefixes and the selected checkpoint
stay intact, including their order and tie preference. Unknown RAM telemetry or an unknown allocation estimate
does not evict anything. The usual admission check still runs before copying state.
With this option the HTTP server also allows up to 30 seconds for physical RAM accounting to catch up after
cache reclamation. Only an unpublished `memory` refusal from the SAVE RAM preflight is retried, at most three
times, when measured available RAM reaches the reported estimate plus the original floor and 2 MiB for rounding.
The same live engine process and service FIFO are held throughout; a process change, death, unknown telemetry
or missing estimate ends the wait. This does not unload a model or trim another process's working set. Persistent
pressure still returns the last refusal. The wait is outside the engine's reported `save_ms`.
This can trade later prefix-cache hits for room to save. Released caches stay released even if admission or file
I/O later fails; the current tokens, images, steering and live device state are unchanged. It cannot guarantee a
SAVE under arbitrary memory pressure. With the option off, or enough RAM at the first probe, cache retention and
the session file format are unchanged. RESTORE is unchanged.
The request must be `Content-Type: application/json` (else `415`) and come from no browser page, Strata's own or a
trusted origin (another site's `Origin` gets `403`, also with an API key); the Host and API-key checks apply as
everywhere. Errors: `501` without `--slot-save-path` or with parallel requests; `400` for a slot other than 0, an unknown action, a refused
+58 -3
View File
@@ -3,12 +3,67 @@
#include <cstdint>
#include <istream>
#include <optional>
#include <string>
namespace strata::core {
// Host physical memory, not swap/commit or a container/job memory reservation.
// Unknown telemetry is deliberately distinct from a measured zero.
std::optional<uint64_t> conversation_available_memory();
// The RAM a runtime allocation (parking a conversation, saving or restoring a session file) may still take.
//
// available_host_bytes() is the smallest of
// * MemAvailable (Windows: the available physical memory);
// * the room under every memory limit of this process's cgroup and of each ancestor visible under
// /sys/fs/cgroup (cgroup v2: memory.max and memory.high, each minus usage; cgroup v1:
// memory.limit_in_bytes minus memory.usage_in_bytes);
// * the operator's own cap, when one is set (--memory-limit-mib / STRATA_MEMORY_LIMIT_MIB): that many MiB minus
// what the container uses now - the top visible cgroup's memory.current, or MemTotal - MemAvailable when the
// cgroup files cannot be read. For a container whose real limit sits on a parent cgroup it cannot see.
//
// Usage is memory.current as the kernel reports it, less one reclaimable kind: the clean inactive file cache of the
// same group (memory.stat inactive_file, v1 total_inactive_file, less dirty and writeback pages, never more than
// memory.current), which the kernel gives back at memory.high or the limit before it kills anything. Nothing else is
// credited: active_file holds mlocked pages, and shmem is the pinned complements and the KV pool. A memory.stat that
// is missing or unparsable gives no credit (it does not make the sample unknown).
// Pinned, locked and shared memory stays charged in full: a hard-limit kill is worse than a skipped park.
//
// Unknown telemetry is deliberately distinct from a measured zero. A limit file that exists but cannot be parsed
// makes the sample unknown (fail closed); a file that is absent (no such controller, not mounted) is ignored.
// Not a reservation: other writers can take the room after the sample.
enum class MemorySource { meminfo, cgroup, flag };
const char* memory_source_name(MemorySource source);
/// One sample. `available` is the smallest term; `source`, `limit` and `current` describe the term that was the
/// smallest (meminfo: MemTotal and MemTotal - MemAvailable; cgroup: that group's limit and memory.current; flag: the
/// operator's cap and the usage it was measured against). `mem_available` is MemAvailable by itself (0 if unknown).
struct HostMemoryReading {
uint64_t available = 0;
MemorySource source = MemorySource::meminfo;
uint64_t limit = 0;
uint64_t current = 0; ///< memory.current (meminfo: MemTotal - MemAvailable), before the credit
uint64_t credit = 0; ///< the clean inactive file cache counted as reclaimable (0 for meminfo)
uint64_t mem_available = 0;
};
/// The files the sampler reads; the defaults are the real ones (tests point them at a fixture directory).
struct MemoryProbePaths {
std::string meminfo = "/proc/meminfo";
std::string self_cgroup = "/proc/self/cgroup";
std::string cgroup_root = "/sys/fs/cgroup";
};
/// The operator's cap in bytes for the container/cgroup this engine runs in (0 = none). Set once at start.
void set_memory_limit_bytes(uint64_t bytes);
uint64_t memory_limit_bytes();
/// Linux: reads `paths`. `explicit_limit` 0 = no operator cap. nullopt when the RAM cannot be determined.
std::optional<HostMemoryReading> sample_host_memory(const MemoryProbePaths& paths, uint64_t explicit_limit);
/// The real files (Windows: GlobalMemoryStatusEx) and the cap set by set_memory_limit_bytes().
std::optional<HostMemoryReading> sample_host_memory();
std::optional<uint64_t> available_host_bytes();
std::optional<uint64_t> conversation_mem_available(std::istream& meminfo);
inline bool conversation_memory_admit(std::optional<uint64_t> available,
@@ -0,0 +1,55 @@
// Optional SAVE admission: free reconstructible host caches, never the live device state.
#pragma once
#include "strata/core/conversation_file.hpp"
#include "strata/core/conversation_memory.hpp"
namespace strata::core {
struct SessionSaveReclaimed {
size_t checkpoints = 0, parked = 0, bytes = 0;
};
// Called BEFORE session_save_checkpoints selects a pointer into chain. Probe after each
// eviction: freed capacity is not necessarily physical RAM returned by the allocator.
// No allocation is needed here. Unknown telemetry / sizes cannot justify cache eviction.
// Preserve every explicit pin and exactly the checkpoint the file would have selected.
template<class Probe>
SessionSaveReclaimed session_save_reclaim(std::vector<ConversationCheckpoint>& chain,
ConversationCache& cache, const SessionSaveLive& live,
uint64_t floor, Probe available) {
SessionSaveReclaimed out;
const auto* selected = session_deepest_checkpoint(chain);
const uint64_t need = session_save_peak_bytes(selected, live);
auto room = available();
auto done = [&] { return !room || need == UINT64_MAX || conversation_memory_admit(room, need, floor); };
if (done()) return out;
if (cache.retained_bytes()) {
out.bytes += cache.retained_bytes();
{ auto unused = cache.take_reuse(); }
room = available();
if (done()) return out;
}
while (true) {
const size_t before = cache.bytes();
if (!cache.evict_oldest()) break; // pinned conversations stay parked
++out.parked;
out.bytes += before - cache.bytes();
room = available();
if (done()) return out;
}
size_t keep = selected ? size_t(selected - chain.data()) : chain.size();
// Erase from the back to preserve order, ties and the selected checkpoint's storage.
for (size_t i = chain.size(); i-- > 0;) {
if (i == keep || chain[i].pinned) continue;
out.bytes += chain[i].bytes();
chain.erase(chain.begin() + static_cast<std::ptrdiff_t>(i));
if (i < keep) --keep;
++out.checkpoints;
room = available();
if (done()) break;
}
return out;
}
} // namespace strata::core
+6 -1
View File
@@ -604,6 +604,7 @@ class StrataEngine:
def __init__(self, exe: str, args: list[str], cwd: str | None = None, log: str | None = None,
env: dict | None = None, lazy: bool = False):
self.spawn = (exe, list(args), cwd, log, env) # to start it again after it died (issue #27)
self.session_save_reclaim = '--session-save-reclaim' in args
paths = {k: v for k, v in zip(args, args[1:]) if k in ("--native", "--pack")}
self.model_path = paths.get("--native") or paths.get("--pack", "pack/full")
self.log_path = log
@@ -2796,7 +2797,11 @@ class Service:
else "restoring a session", started=time.time(), first_token=None,
prompt_tokens=None, generated=None, max_tokens=None)
try:
r = self.engine.session_file(action, path)
if action == 'save' and getattr(self.engine, 'session_save_reclaim', False):
from serve.session_save_retry import session_file
r = session_file(self, action, path, SessionRefused)
else:
r = self.engine.session_file(action, path)
except SessionRefused as e:
body = error(e.status, str(e))
body[1]["error"]["kind"] = e.kind
+84
View File
@@ -0,0 +1,84 @@
"""Bounded SAVE admission retries after opt-in engine cache reclamation.
The caller holds the service FIFO. Only an unpublished, typed RAM preflight
refusal is retried, on the same live engine process and with its floor intact.
No model unload, working-set trim or unrelated process is involved.
"""
from __future__ import annotations
import re
import time
SETTLE_SECONDS = 30.0
MAX_RETRIES = 3
POLL_SECONDS = 0.5
def required_mib(error) -> int | None:
match = re.search(r'^not enough RAM to save the session '
r'\((\d+) MiB plus a floor of (\d+) MiB needed,', str(error))
# Each diagnostic term rounds bytes down; two MiB preserve admission headroom.
return sum(map(int, match.groups())) + 2 if match else None
def available_mib() -> int | None:
try:
import psutil
available = psutil.virtual_memory().available
if isinstance(available, bool) or not isinstance(available, int) or available < 0:
return None
return available // 2**20
except (ImportError, OSError, AttributeError, ValueError):
return None
def retryable(action, error) -> bool:
return (action == 'save' and error.kind == 'memory' and not error.published
and required_mib(error) is not None)
def session_file(service, action, path, refused_type):
"""Called only when --session-save-reclaim is enabled; never changes RESTORE."""
engine = service.engine
process = getattr(engine, 'proc', None)
try:
return engine.session_file(action, path)
except refused_type as error:
if not retryable(action, error) or process is None:
raise
deadline = time.monotonic() + SETTLE_SECONDS
last_error = error
def same_process():
try:
return (service.engine is engine and engine.proc is process
and not getattr(engine, 'ended', False) and process.poll() is None)
except OSError:
return False
print('[strata] SAVE waiting for RAM after cache reclaim: '
f'need={required_mib(error)} MiB, limit={SETTLE_SECONDS:g}s; floor unchanged', flush=True)
for attempt in range(MAX_RETRIES):
while True:
if not same_process() or time.monotonic() >= deadline:
raise last_error
available = available_mib()
needed = required_mib(last_error)
if available is None or needed is None:
raise last_error
if available >= needed:
break
time.sleep(max(0.0, min(POLL_SECONDS, deadline - time.monotonic())))
# No replacement, restart, or blind retry when telemetry is unknown.
if not same_process():
raise last_error
try:
return engine.session_file(action, path)
except refused_type as failure:
if not retryable(action, failure):
raise
last_error = failure
if attempt + 1 == MAX_RETRIES or time.monotonic() >= deadline:
raise
time.sleep(max(0.0, min(POLL_SECONDS, deadline - time.monotonic())))
raise last_error
+192
View File
@@ -0,0 +1,192 @@
"""SAVE memory settling on a fake clock and real HTTP/FIFO; no GPU or model."""
from __future__ import annotations
import io
from pathlib import Path
import tempfile
import threading
import time
from types import SimpleNamespace
import unittest
from unittest import mock
from serve import session_save_retry as retry
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, EngineDied, Service, SessionRefused, serve
from serve import test_slots as slot_tests
from serve.test_slots import FakeEngine, FakeProc
RESULT = {'tokens': 62993, 'bytes': 1234, 'ms': 401.5}
def refused(need=355, floor=768):
return SessionRefused('memory', f'not enough RAM to save the session ({need} MiB plus a floor of {floor} MiB needed, 503 MiB available)')
class Clock:
def __init__(self): self.now=0.0; self.on_sleep=lambda:None
def monotonic(self): return self.now
def sleep(self, seconds):
assert 0 <= seconds <= .5
self.now += seconds
self.on_sleep()
class Retry(unittest.TestCase):
def setUp(self):
self.clock=Clock()
self.proc=SimpleNamespace(poll=lambda:None)
self.engine=SimpleNamespace(proc=self.proc,ended=False,session_file=mock.Mock())
self.service=SimpleNamespace(engine=self.engine)
self.clock_patch=mock.patch.object(retry,'time',self.clock)
self.clock_patch.start()
self.addCleanup(self.clock_patch.stop)
self.stdout=mock.patch('sys.stdout',new_callable=io.StringIO)
self.stdout.start(); self.addCleanup(self.stdout.stop)
def call(self, available=5000, action='save'):
with mock.patch.object(retry,'available_mib',side_effect=available if isinstance(available,list) else None,
return_value=None if isinstance(available,list) else available):
return retry.session_file(self.service,action,'same.bin',SessionRefused)
def test_success_does_not_poll_or_wait(self):
self.engine.session_file.return_value=RESULT
with mock.patch.object(retry,'available_mib',side_effect=AssertionError('unexpected memory probe')):
self.assertEqual(retry.session_file(self.service,'save','same.bin',SessionRefused),RESULT)
self.assertEqual(self.clock.now,0)
self.engine.session_file.assert_called_once_with('save','same.bin')
def test_delayed_ram_reuses_same_process_path_and_floor(self):
self.engine.session_file.side_effect=[refused(),RESULT]
self.assertEqual(self.call([534,541,800,1400]),RESULT)
self.assertEqual(self.clock.now,1.5)
self.assertIs(self.engine.proc,self.proc)
self.assertEqual(self.engine.session_file.call_args_list,[mock.call('save','same.bin')]*2)
self.assertEqual(retry.required_mib(refused()),1125)
def test_persistent_pressure_expires_without_another_save(self):
error=refused(); self.engine.session_file.side_effect=error
with self.assertRaises(SessionRefused) as got: self.call(541)
self.assertIs(got.exception,error)
self.assertEqual(self.clock.now,30)
self.assertEqual(self.engine.session_file.call_count,1)
def test_admission_races_are_bounded_and_keep_latest_error(self):
errors=[refused(355+n) for n in range(4)]
self.engine.session_file.side_effect=errors
with self.assertRaises(SessionRefused) as got: self.call()
self.assertIs(got.exception,errors[-1])
self.assertEqual(self.engine.session_file.call_count,4) # first SAVE plus three retries
self.assertEqual(self.clock.now,1)
def test_new_refusal_rechecks_its_larger_estimate(self):
self.engine.session_file.side_effect=[refused(),refused(2048),RESULT]
self.assertEqual(self.call([1400,1400,2900]),RESULT)
self.assertEqual(self.clock.now,1)
def test_unknown_telemetry_or_estimate_never_retries(self):
for error,available in [(refused(),None),
(SessionRefused('memory','not enough RAM to save the session'),5000),
(SessionRefused('memory','not enough RAM to save the session (unknown MiB plus a floor of 768 MiB needed,'),5000)]:
with self.subTest(error=error):
self.engine.session_file=mock.Mock(side_effect=error)
with self.assertRaises(SessionRefused) as got: self.call(available)
self.assertIs(got.exception,error)
self.assertEqual(self.engine.session_file.call_count,1)
def test_restore_other_categories_and_published_files_never_retry(self):
for action,error in [('restore',refused()),('save',SessionRefused('io',str(refused()))),
('save',SessionRefused('storage',str(refused()))),('save',SessionRefused('invalid',str(refused()))),
('save',SessionRefused('memory',str(refused()),published=True))]:
with self.subTest(action=action,error=error):
self.engine.session_file=mock.Mock(side_effect=error)
with self.assertRaises(SessionRefused) as got: self.call(action=action)
self.assertIs(got.exception,error)
self.assertEqual(self.engine.session_file.call_count,1)
def test_process_death_or_replacement_ends_wait(self):
for change in [lambda:setattr(self.proc,'poll',lambda:1),
lambda:setattr(self.engine,'proc',SimpleNamespace(poll=lambda:None)),
lambda:setattr(self.service,'engine',SimpleNamespace(proc=self.proc)),
lambda:setattr(self.engine,'ended',True)]:
with self.subTest(change=change):
self.proc=SimpleNamespace(poll=lambda:None)
self.engine=SimpleNamespace(proc=self.proc,ended=False,session_file=mock.Mock(side_effect=refused()))
self.service.engine=self.engine
self.clock.now=0; self.clock.on_sleep=change
with self.assertRaises(SessionRefused): self.call(541)
self.assertEqual(self.engine.session_file.call_count,1)
self.assertEqual(self.clock.now,.5)
def test_non_admission_error_during_retry_is_returned(self):
for error in [EngineDied('gone'), SessionRefused('io','flushing directory',published=True)]:
self.engine.session_file=mock.Mock(side_effect=[refused(),error])
with self.assertRaises(type(error)) as got: self.call()
self.assertIs(got.exception,error)
self.assertEqual(self.engine.session_file.call_count,2)
def test_memory_probe_is_portable_and_unknown_fails_closed(self):
for value,expected in [(1400*2**20,1400),(0,0),(-1,None),(True,None),(None,None),(float('nan'),None)]:
with mock.patch.dict('sys.modules',{'psutil':SimpleNamespace(virtual_memory=lambda:SimpleNamespace(available=value))}):
self.assertEqual(retry.available_mib(),expected)
class AdmissionProc(FakeProc):
def write(self,text):
if not self.sent and text.startswith('SAVE '):
self.sent.append(text)
self.engine.lines.put('SERR memory 0 '+str(refused())+'\n')
return
super().write(text)
class HTTP(unittest.TestCase):
post=slot_tests.Slots.post
def setUp(self):
self.directory=tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
tok=ByteTokenizer(); self.engine=FakeEngine(); self.engine.session_save_reclaim=True
self.engine.proc=AdmissionProc(self.engine)
self.svc=Service(self.engine,tok,ChatTemplate(Path(__file__).parent/'chat_template.jinja'))
self.svc.slot_save_path=self.directory.name
self.httpd=serve(self.svc,port=0)
self.base=f'http://127.0.0.1:{self.httpd.server_address[1]}'
self.addCleanup(self.httpd.server_close); self.addCleanup(self.httpd.shutdown)
def test_opt_in_recovers_native_refusal_and_keeps_response_and_process(self):
proc=self.engine.proc
with mock.patch.object(retry,'available_mib',return_value=1400):
status,body=self.post('/slots/0?action=save',{'filename':'a.bin'})
self.assertEqual(status,200,body)
self.assertEqual(body,{'id_slot':0,'filename':'a.bin','n_saved':62993,'n_written':1234,'timings':{'save_ms':401.5}})
self.assertEqual(proc.sent,[f'SAVE {Path(self.directory.name,"a.bin")}\n']*2)
self.assertIs(self.engine.proc,proc); self.assertFalse(self.engine.ended)
self.assertEqual(Path(self.directory.name,'a.bin').read_bytes(),b'x'*1234)
def test_default_refusal_is_immediate_and_byte_identical(self):
self.engine.session_save_reclaim=False
with mock.patch.object(retry,'available_mib',side_effect=AssertionError('default must not probe')):
status,body=self.post('/slots/0?action=save',{'filename':'off.bin'})
self.assertEqual(status,503)
self.assertEqual(body,{'error':{'code':503,'message':str(refused()),'type':'server_error','kind':'memory'}})
self.assertEqual(len(self.engine.proc.sent),1)
self.assertFalse(Path(self.directory.name,'off.bin').exists())
def test_fifo_blocks_restore_while_save_waits_and_releases_afterwards(self):
waiting=threading.Event(); enough=threading.Event()
def available(): waiting.set(); return 1400 if enough.is_set() else 541
result={}
path=Path(self.directory.name,'fifo.bin'); path.write_bytes(b'old file')
a=threading.Thread(target=lambda:result.update(save=self.post('/slots/0?action=save',{'filename':'fifo.bin'})))
b=threading.Thread(target=lambda:result.update(restore=self.post('/slots/0?action=restore',{'filename':'fifo.bin'})))
with mock.patch.object(retry,'available_mib',side_effect=available), mock.patch.object(retry,'POLL_SECONDS',.01):
try:
a.start(); self.assertTrue(waiting.wait(2)); b.start()
deadline=time.monotonic()+2
while self.svc.status['queued'] != 1 and time.monotonic()<deadline: time.sleep(.01)
self.assertTrue(self.svc.status['busy']); self.assertEqual(self.svc.status['queued'],1)
self.assertEqual(len(self.engine.proc.sent),1)
finally:
enough.set(); a.join(5)
if b.ident is not None: b.join(5)
self.assertFalse(a.is_alive() or b.is_alive())
self.assertEqual(result['save'][0],200); self.assertEqual(result['restore'][0],200)
self.assertEqual(self.engine.proc.sent,[f'SAVE {path}\n',f'SAVE {path}\n',f'RESTORE {path}\n'])
self.assertFalse(self.svc.status['busy']); self.assertEqual(self.svc.status['queued'],0)
self.assertTrue(self.svc.fifo.acquire(blocking=False)); self.svc.fifo.release()
if __name__=='__main__': unittest.main()
+27
View File
@@ -1,6 +1,7 @@
// CPU-only tests for the on-disk session format (include/strata/core/conversation_file.hpp).
// Built with -DSTRATA_BUILD_CONVERSATION_TESTS=ON; no CUDA, no model.
#include "strata/core/conversation_file.hpp"
#include "strata/core/session_save_reclaim.hpp"
#include <array>
#include <cerrno>
@@ -698,6 +699,32 @@ int main() {
slurp(old_file) == std::vector<char>(9, 'o'), "save: live state and the old file intact");
#endif
}
// Opt-in pressure reclamation does not change the selected file bytes, even with pin=N.
for (bool pin : {false, true}) {
auto source = sample();
source.checkpoints[0].pinned = pin;
const auto live_before = source.live;
auto expected = sample();
expected.checkpoints = session_checkpoints_to_save(source.checkpoints);
const fs::path before_path = dir / "reclaim-before.bin", after_path = dir / "reclaim-after.bin";
check(session_file_write(before_path.string(), expected, id, written, error), "reclaim: baseline file written");
ConversationCache parked(1u << 20, 4);
SessionSaveLive sl; sl.state_bytes = source.live.bytes(); sl.tokens = source.live.ids.size();
const auto freed = session_save_reclaim(source.checkpoints, parked, sl, 0,
[] { return std::optional<uint64_t>(0); });
check(freed.checkpoints == 1, "reclaim: a non-selected checkpoint released");
check(same_checkpoint(source.live, live_before), "reclaim: live state remains intact");
check(session_file_write(after_path.string(), source, id, written, error), "reclaim: file written after pressure");
check(slurp(before_path) == slurp(after_path), "reclaim: file byte-identical to original selection");
const auto old = slurp(after_path);
SessionWriteOptions opt;
opt.fault = [](const char* step) { return std::strcmp(step, "write") == 0 ? ENOSPC : 0; };
SessionStatus status;
check(!session_file_write(after_path.string(), source, id, written, error, opt, &status) &&
status.error == SessionError::storage && !status.published, "reclaim: later write failure reported");
check(slurp(after_path) == old && same_checkpoint(source.live, live_before) && no_temp(dir),
"reclaim: later failure preserves old file and live state, no temporary left");
}
// R6: the folder the free-space query is asked about
{
check(session_free_space_dir("\\\\server\\share\\sessions\\chat.bin", true) == "\\\\server\\share\\sessions\\",
+255 -8
View File
@@ -1,11 +1,16 @@
#include "strata/core/conversation_memory.hpp"
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <charconv>
#include <filesystem>
#include <fstream>
#include <limits>
#include <sstream>
#include <string>
#include <system_error>
#include <vector>
#if defined(_WIN32)
#ifndef NOMINMAX
@@ -16,13 +21,20 @@
namespace strata::core {
std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {
namespace fs = std::filesystem;
namespace {
std::atomic<uint64_t> g_memory_limit_bytes{0};
// "<key> <n> kB", exactly once, nothing else on the line; the value in bytes. Anything else is unknown.
std::optional<uint64_t> meminfo_kb_bytes(std::istream& meminfo, const char* wanted) {
std::optional<uint64_t> result;
std::string line;
while (std::getline(meminfo, line)) {
std::istringstream fields(line);
std::string key, value, unit, extra;
if (!(fields >> key) || key != "MemAvailable:") continue;
if (!(fields >> key) || key != wanted) continue;
if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {};
uint64_t kb = 0;
const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb);
@@ -34,20 +46,255 @@ std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {
return result;
}
std::optional<uint64_t> conversation_available_memory() {
// One cgroup control file: absent (no such file), a number, "max", or unusable (unreadable, empty, not a number).
struct Value {
enum Kind { absent, bad, max, number } kind = absent;
uint64_t n = 0;
};
Value read_value(const fs::path& path) {
std::error_code ec;
const bool there = fs::exists(path, ec);
if (ec) return {Value::bad, 0};
if (!there) return {};
std::ifstream file(path);
if (!file) return {Value::bad, 0};
char buf[64];
file.read(buf, sizeof buf);
if (file.bad()) return {Value::bad, 0};
size_t len = (size_t) file.gcount();
if (len == sizeof buf) return {Value::bad, 0};
while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' ' || buf[len - 1] == '\t')) --len;
if (len == 0) return {Value::bad, 0};
if (len == 3 && std::string(buf, 3) == "max") return {Value::max, 0};
Value v{Value::number, 0};
const auto parsed = std::from_chars(buf, buf + len, v.n);
if (parsed.ec != std::errc{} || parsed.ptr != buf + len) return {Value::bad, 0};
return v;
}
// The one reclaimable kind that is credited: clean inactive file cache, from the same group's memory.stat
// (v2 inactive_file, v1 total_inactive_file), less its dirty and writeback pages when those are listed, and never
// more than the group's charged usage. active_file (it holds mlocked pages) and shmem (pinned complements, the KV
// pool) are not credited. A memory.stat that is missing or unparsable gives no credit - not an unknown sample.
uint64_t reclaimable_cache(const fs::path& dir, uint64_t current, bool v1) {
std::ifstream stat(dir / "memory.stat");
if (!stat) return 0;
const char* inactive_key = v1 ? "total_inactive_file" : "inactive_file";
const char* dirty_key = v1 ? "total_dirty" : "file_dirty";
const char* writeback_key = v1 ? "total_writeback" : "file_writeback";
std::optional<uint64_t> inactive;
uint64_t dirty = 0, writeback = 0;
std::string line;
while (std::getline(stat, line)) {
std::istringstream fields(line);
std::string key, value, extra;
if (!(fields >> key >> value) || (fields >> extra)) continue;
uint64_t* target = key == dirty_key ? &dirty : key == writeback_key ? &writeback : nullptr;
uint64_t n = 0;
const auto parsed = std::from_chars(value.data(), value.data() + value.size(), n);
const bool ok = parsed.ec == std::errc{} && parsed.ptr == value.data() + value.size();
if (key == inactive_key) { if (!ok || inactive) return 0; inactive = n; }
else if (target != nullptr) { if (!ok) return 0; *target = n; }
}
if (!inactive) return 0;
uint64_t credit = std::min(*inactive, current);
credit = dirty >= credit ? 0 : credit - dirty;
credit = writeback >= credit ? 0 : credit - writeback;
return credit;
}
// What the cgroup files say: every finite limit with the usage charged against it (and the cache credit of that
// group), and the usage and credit of the topmost visible group (the root of this namespace - what a container's own
// limit is measured over).
struct CgroupScan {
struct Limit { uint64_t limit, current, credit; };
std::vector<Limit> limits;
std::optional<uint64_t> root_current;
uint64_t root_credit = 0;
bool any_files = false;
};
// `dirs` runs from the top visible group down to the process's own. False when a file that is there cannot be used.
bool scan_levels(const std::vector<fs::path>& dirs, const char* const* limit_names, size_t n_limits,
const char* current_name, bool v1, CgroupScan& out) {
for (size_t i = 0; i < dirs.size(); ++i) {
const Value current = read_value(dirs[i] / current_name);
std::vector<Value> limits;
for (size_t k = 0; k < n_limits; ++k) limits.push_back(read_value(dirs[i] / limit_names[k]));
bool unusable = current.kind == Value::bad || current.kind == Value::max;
bool finite_limit = false;
for (const Value& v : limits) {
unusable = unusable || v.kind == Value::bad;
finite_limit = finite_limit || v.kind == Value::number;
}
if (unusable) return false;
if (current.kind == Value::absent) {
if (finite_limit) return false; // a limit with no usage beside it: the room cannot be told
continue; // no memory controller at this level (e.g. the host's root group)
}
out.any_files = true;
const uint64_t credit = reclaimable_cache(dirs[i], current.n, v1);
if (i == 0) { out.root_current = current.n; out.root_credit = credit; }
for (const Value& v : limits) {
if (v.kind != Value::number) continue;
if (v1 && v.n >= (1ull << 62)) continue; // v1's "unlimited" is a number near 2^63
out.limits.push_back({v.n, current.n, credit});
}
}
return true;
}
// "/a/b/c" -> root, root/a, root/a/b, root/a/b/c, cut at the first one that is not a directory here: a container
// without its own cgroup namespace sees its group's host path in /proc/self/cgroup, but only its own subtree under
// the mount, so the deepest one that exists (at worst the mount itself) is the nearest group we can read.
bool group_dirs(const fs::path& root, const std::string& group, std::vector<fs::path>& dirs) {
dirs.clear();
std::vector<std::string> names;
std::istringstream parts(group);
for (std::string part; std::getline(parts, part, '/');) {
if (part.empty()) continue;
if (part == "." || part == "..") return false; // never walk out of the mount, nor trust a path that tries
names.push_back(part);
}
std::error_code ec;
if (!fs::is_directory(root, ec)) return true; // nothing mounted: no cgroup terms
dirs.push_back(root);
fs::path at = root;
for (const std::string& part : names) {
at /= part;
if (!fs::is_directory(at, ec)) break;
dirs.push_back(at);
}
return true;
}
bool scan_cgroups(const MemoryProbePaths& paths, CgroupScan& out) {
std::optional<std::string> v2_group, v1_group;
std::ifstream groups(paths.self_cgroup);
if (!groups) {
v2_group = "/"; // no /proc/self/cgroup: the mount's own top group is still readable
} else {
std::string line;
while (std::getline(groups, line)) {
const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
if (c2 == std::string::npos) continue;
const std::string controllers = line.substr(c1 + 1, c2 - c1 - 1), group = line.substr(c2 + 1);
if (line.compare(0, c1, "0") == 0 && controllers.empty()) { v2_group = group; continue; }
std::istringstream names(controllers);
for (std::string name; std::getline(names, name, ',');)
if (name == "memory") v1_group = group;
}
}
std::vector<fs::path> dirs;
if (v2_group) {
if (!group_dirs(paths.cgroup_root, *v2_group, dirs)) return false;
static const char* const names[] = {"memory.max", "memory.high"};
if (!scan_levels(dirs, names, 2, "memory.current", false, out)) return false;
}
if (!out.any_files && v1_group) { // cgroup v1: the memory controller's own tree
if (!group_dirs(fs::path(paths.cgroup_root) / "memory", *v1_group, dirs)) return false;
static const char* const names[] = {"memory.limit_in_bytes"};
if (!scan_levels(dirs, names, 1, "memory.usage_in_bytes", true, out)) return false;
}
return true;
}
std::optional<HostMemoryReading> combine(std::optional<uint64_t> available, std::optional<uint64_t> total,
const CgroupScan& cg, uint64_t explicit_limit) {
if (!available) return {};
HostMemoryReading r;
r.mem_available = *available;
r.available = *available;
r.source = MemorySource::meminfo;
r.limit = total.value_or(0);
r.current = total && *total >= *available ? *total - *available : 0;
for (const CgroupScan::Limit& l : cg.limits) {
const uint64_t used = l.current - l.credit; // credit <= current
const uint64_t room = l.limit > used ? l.limit - used : 0;
if (room < r.available) {
r.available = room;
r.source = MemorySource::cgroup;
r.limit = l.limit;
r.current = l.current;
r.credit = l.credit;
}
}
if (explicit_limit != 0) {
uint64_t used = 0, credit = 0;
if (cg.root_current) { used = *cg.root_current; credit = cg.root_credit; }
else if (total && *total >= *available) used = *total - *available;
else return {};
const uint64_t net = used - credit;
const uint64_t room = explicit_limit > net ? explicit_limit - net : 0;
if (room <= r.available) { // a tie goes to the operator's number: it is the one that names the real cap
r.available = room;
r.source = MemorySource::flag;
r.limit = explicit_limit;
r.current = used;
r.credit = credit;
}
}
return r;
}
} // namespace
const char* memory_source_name(MemorySource source) {
switch (source) {
case MemorySource::flag: return "flag";
case MemorySource::cgroup: return "cgroup";
default: return "meminfo";
}
}
std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {
return meminfo_kb_bytes(meminfo, "MemAvailable:");
}
void set_memory_limit_bytes(uint64_t bytes) { g_memory_limit_bytes.store(bytes, std::memory_order_relaxed); }
uint64_t memory_limit_bytes() { return g_memory_limit_bytes.load(std::memory_order_relaxed); }
std::optional<HostMemoryReading> sample_host_memory(const MemoryProbePaths& paths, uint64_t explicit_limit) {
std::ifstream avail_file(paths.meminfo);
if (!avail_file) return {};
const std::optional<uint64_t> available = conversation_mem_available(avail_file);
if (!available) return {};
std::ifstream total_file(paths.meminfo);
std::optional<uint64_t> total;
if (total_file) total = meminfo_kb_bytes(total_file, "MemTotal:");
CgroupScan cg;
if (!scan_cgroups(paths, cg)) {
// Without an operator cap the cgroup files are only an extra: the guard falls back to MemAvailable alone (what
// 0.1.41 used), once-warned. With a cap the usage cannot be told, so the sample stays unknown.
if (explicit_limit != 0) return {};
static std::atomic<bool> warned{false};
if (!warned.exchange(true))
std::fprintf(stderr, "[strata] memory guard: the cgroup memory files could not be read or parsed, using "
"MemAvailable; set --memory-limit-mib to the container's limit\n");
cg = CgroupScan{};
}
return combine(available, total, cg, explicit_limit);
}
std::optional<HostMemoryReading> sample_host_memory() {
#if defined(_WIN32)
MEMORYSTATUSEX status{};
status.dwLength = sizeof status;
// #1607: the commit limit (RAM + page file) refuses an allocation while physical RAM is still free
if (GlobalMemoryStatusEx(&status)) return std::min<uint64_t>(status.ullAvailPhys, status.ullAvailPageFile);
return {};
if (!GlobalMemoryStatusEx(&status)) return {};
return combine(std::min<uint64_t>(status.ullAvailPhys, status.ullAvailPageFile), status.ullTotalPhys, CgroupScan{}, memory_limit_bytes());
#elif defined(__linux__)
std::ifstream meminfo("/proc/meminfo");
if (!meminfo) return {};
return conversation_mem_available(meminfo);
return sample_host_memory(MemoryProbePaths{}, memory_limit_bytes());
#else
return {};
#endif
}
std::optional<uint64_t> available_host_bytes() {
const auto reading = sample_host_memory();
if (!reading) return {};
return reading->available;
}
} // namespace strata::core
+1 -1
View File
@@ -50,7 +50,7 @@ int main() {
check(!conversation_memory_admit(std::numeric_limits<uint64_t>::max(),
std::numeric_limits<uint64_t>::max(), 1), "maximal sum overflow rejected");
// Test the real provider without assuming any particular amount of free RAM.
const auto available = conversation_available_memory();
const auto available = available_host_bytes();
check(!available || conversation_memory_admit(available, 0, 0), "provider returns bytes or unknown");
#if defined(_WIN32)
// Unknown must fail closed in production, but must not let a broken Windows provider pass this test.
+115
View File
@@ -0,0 +1,115 @@
// CPU only: pressure is injected through telemetry, not by exhausting the host.
#include "strata/core/session_save_reclaim.hpp"
#include <cstdio>
#include <cstdlib>
#include <new>
static bool deny_alloc = false;
void* operator new(std::size_t n) {
if (deny_alloc) throw std::bad_alloc();
if (void* p = std::malloc(n ? n : 1)) return p;
throw std::bad_alloc();
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }
using namespace strata::core;
static int checks_run = 0;
static void check(bool ok, const char* label) {
++checks_run;
if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
}
static ConversationCheckpoint checkpoint(size_t n, bool pinned = false) {
ConversationCheckpoint c;
c.ids.assign(n, 42); c.imgs = {{1, 99}};
c.gdn.assign(4096, 1); c.ple = {2}; c.tails = {3}; c.dead = {4}; c.block_pos = {5};
c.used = n; c.pinned = pinned;
return c;
}
static bool same(const ConversationCheckpoint& a, const ConversationCheckpoint& b) {
return a.ids == b.ids && a.imgs == b.imgs && a.gdn == b.gdn && a.ple == b.ple &&
a.tails == b.tails && a.dead == b.dead && a.block_pos == b.block_pos &&
a.used == b.used && a.pinned == b.pinned && a.stage_parts.size() == b.stage_parts.size();
}
static void park(ConversationCache& cache, int tokens, bool pin = false) {
SavedConversation c; c.live = checkpoint(tokens);
c.checkpoints.push_back(checkpoint(tokens - 1, pin));
// Distinct histories, so put() does not remove superseded entries.
c.live.ids[0] = tokens; c.checkpoints[0].ids[0] = tokens;
check(cache.put(std::move(c)), "fixture parked");
}
int main() {
SessionSaveLive live; live.state_bytes = 1000; live.tokens = 100; live.images = 1; live.kv_layers = 2;
const uint64_t floor = 1u << 20;
// Every selected position, first-tie preference, and explicit pins (a pin can be shallower).
for (size_t selected = 0; selected < 4; ++selected) for (bool pin : {false, true}) {
std::vector<ConversationCheckpoint> chain;
for (size_t i = 0; i < 4; ++i) chain.push_back(checkpoint(i == selected ? 300 : 100, pin && i == selected));
if (pin) chain[(selected + 1) % 4].ids.resize(500); // deeper, unpinned
auto before = *session_deepest_checkpoint(chain);
const auto* storage = session_deepest_checkpoint(chain)->gdn.data();
ConversationCache cache(1u << 20, 10);
park(cache, 10); park(cache, 20, true); park(cache, 30);
std::vector<ConversationKv> kv(1); kv[0].k.resize(16384); cache.retain(std::move(kv), 100);
const size_t bytes_before = cache.bytes();
size_t chain_bytes = 0; for (const auto& c : chain) chain_bytes += c.bytes();
deny_alloc = true;
auto freed = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });
deny_alloc = false;
check(chain.size() == 1 && same(chain[0], before), "selected checkpoint unchanged under pressure");
check(chain[0].gdn.data() == storage, "checkpoint moved without copying storage");
check(freed.checkpoints == 3 && freed.parked == 2 && cache.size() == 1, "pins survive, other entries reclaimed");
check(cache.evictions() == 2 && cache.retained_bytes() == 0, "cache accounting and retained buffers");
check(freed.bytes == bytes_before - cache.bytes() + chain_bytes - chain[0].bytes(), "released byte accounting");
check(session_deepest_checkpoint(chain)->ids == before.ids, "same file selection after reclaim");
auto again = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });
check(again.bytes == 0 && again.checkpoints == 0 && again.parked == 0, "exhausted reclaim is idempotent");
}
// No-pressure path, unknown telemetry, overflowed estimate: no cache mutation.
for (int mode = 0; mode < 4; ++mode) {
std::vector<ConversationCheckpoint> chain{checkpoint(100), checkpoint(300)};
ConversationCache cache(1u << 20, 10); park(cache, 10);
const auto before = chain;
const auto bytes = cache.bytes(); auto sl = live;
if (mode == 2) sl.state_bytes = UINT64_MAX;
const uint64_t need = session_save_peak_bytes(session_deepest_checkpoint(chain), sl);
auto r = session_save_reclaim(chain, cache, sl, floor, [&]() -> std::optional<uint64_t> {
if (mode == 1) return std::nullopt;
return mode == 2 ? 0 : need + floor + (mode == 3 ? 1 : 0);
});
check(!r.bytes && !r.parked && !r.checkpoints && cache.bytes() == bytes, "no eviction without known pressure");
check(chain.size() == 2 && same(chain[0], before[0]) && same(chain[1], before[1]), "unchanged order/content");
}
// Admit after any individual step; never clear the whole cache when one release suffices.
for (int sufficient_after = 1; sufficient_after <= 4; ++sufficient_after) {
std::vector<ConversationCheckpoint> chain{checkpoint(100), checkpoint(300), checkpoint(300)};
auto* selected_storage = chain[1].gdn.data();
ConversationCache cache(1u << 20, 10); park(cache, 10); park(cache, 20);
std::vector<ConversationKv> kv(1); kv[0].v.resize(100); cache.retain(std::move(kv), 100);
const auto need = session_save_peak_bytes(session_deepest_checkpoint(chain), live);
int probes = 0;
auto r = session_save_reclaim(chain, cache, live, floor, [&]() -> std::optional<uint64_t> {
return probes++ >= sufficient_after ? need + floor : 0;
});
check(probes == sufficient_after + 1, "stop immediately once RAM meets unchanged floor");
check(r.parked == size_t(std::min(sufficient_after - 1, 2)), "one-at-a-time parked eviction");
check(r.checkpoints == size_t(sufficient_after == 4), "checkpoint eviction only after parked cache");
check(session_deepest_checkpoint(chain)->gdn.data() == selected_storage, "first deepest tie retained");
}
{
std::vector<ConversationCheckpoint> chain{checkpoint(100, true), checkpoint(300, true), checkpoint(500)};
ConversationCache cache(0, 0);
auto r = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });
check(r.checkpoints == 1 && chain.size() == 2 && chain[0].pinned && chain[1].pinned, "all pins survive in original order");
std::vector<ConversationCheckpoint> out; std::string why;
check(!session_save_checkpoints(chain, live, [](uint64_t, std::string& w) { w = "low RAM"; return false; }, out, why)
&& out.empty() && why == "low RAM", "still refused before copying when reclamation is insufficient");
}
{
std::vector<ConversationCheckpoint> chain;
ConversationCache cache(0, 0);
auto r = session_save_reclaim(chain, cache, live, floor, [] { return std::optional<uint64_t>(0); });
check(!r.bytes && !r.checkpoints && !r.parked, "empty chain and disabled cache");
}
std::printf("session_save_reclaim: %d checks passed\n", checks_run);
}
+102 -14
View File
@@ -22,6 +22,7 @@
#include "strata/core/expert_cache.hpp"
#include "strata/core/conversation_snapshot.hpp"
#include "strata/core/conversation_file.hpp"
#include "strata/core/session_save_reclaim.hpp"
#include "strata/core/conversation_memory.hpp"
#include "strata/core/coupled_draft.hpp"
#include "strata/core/expert_source.hpp"
@@ -601,8 +602,12 @@ struct Options {
/// conversation_cache_slots whatever its length, so without it a client that interleaves short side requests
/// with one long conversation evicts the long one (oldest first). 0 = park every conversation.
int64_t conversation_cache_min_tokens = 0;
/// --memory-limit-mib N / STRATA_MEMORY_LIMIT_MIB: the total RAM this engine's container or cgroup may use, for a
/// container that cannot see its real limit (0 or unset = none; the flag wins over the variable)
int64_t memory_limit_mib = -1;
/// --serve SAVE: disk space a session file must leave free where it is written (MiB; 0 = no check)
int64_t session_min_free_mib = 4096;
bool session_save_reclaim = false;
/// --serve: also keep a checkpoint every N freshly read prompt tokens (0 = only at the last turn boundary)
int64_t prompt_cache_every = 16384;
bool prompt_cache_tail = false; // optional extra checkpoint at an existing near-tail chunk boundary
@@ -743,11 +748,15 @@ void usage() {
" of RAM each; 0 = read every prompt from the start)\n"
" --conversation-cache-mib N --serve: RAM budget for parked conversations (default 0 = off)\n"
" --conversation-cache-slots N --serve: at most N parked conversations (default 4)\n"
" --conversation-cache-min-free-mib N --serve: physical RAM floor when parking or restoring a\n"
" session file (default 2560)\n"
" --conversation-cache-min-free-mib N --serve: RAM floor (under MemAvailable, the cgroup limits and\n"
" --memory-limit-mib) when parking, saving or restoring a session (default 2560)\n"
" --memory-limit-mib N --serve: the total RAM (MiB) this engine's container or cgroup may use, when\n"
" the container cannot see its real limit (also STRATA_MEMORY_LIMIT_MIB; the flag\n"
" wins; 0 = none). Parking and session save/restore keep their floor under it\n"
" --conversation-cache-min-tokens N --serve: park only conversations of at least N tokens, so\n"
" short side requests do not take the slots a long one needs (default 0 = park any)\n"
" --session-min-free-mib N --serve: disk space a SAVE must leave free (default 4096; 0 = no check)\n"
" --session-save-reclaim --serve: reclaim unpinned host caches if SAVE needs RAM (opt-in)\n"
" --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n"
" default 512), so the command `VRAM <reserve_mib>` (the server's POST /v1/vram) can\n"
" give VRAM back to other programs between requests and take it back later\n"
@@ -1036,6 +1045,13 @@ struct GpuStage {
int32_t* mrope = nullptr; ///< --vision: the image-position table on its device
};
// what a refusal on the RAM guard says it had: "900 MiB available, source cgroup" (the smallest of MemAvailable, the
// cgroup limits above the engine and --memory-limit-mib; see strata/core/conversation_memory.hpp)
static std::string ram_note(const std::optional<strata::core::HostMemoryReading>& mem) {
if (!mem) return "RAM telemetry unavailable";
return std::to_string(mem->available >> 20) + " MiB available, source " + strata::core::memory_source_name(mem->source);
}
// ---- issue #31: what the watchdog prints before it stops a stalled engine
struct MemSample {
unsigned long long faults = 0, rss_mib = 0, avail_mib = 0, commit_mib = 0; // faults: hard (Linux) / all (Windows)
@@ -1840,10 +1856,11 @@ int main(int argc, char** argv) {
else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode");
else if (a == "--serve") o.serve = true;
else if (a == "--vision") o.vision = true;
else if (a == "--session-save-reclaim") o.session_save_reclaim = true;
else if (a == "--prompt-cache") o.prompt_cache = std::max(0, std::atoi(next("--prompt-cache")));
else if (a == "--conversation-cache-mib" || a == "--conversation-cache-slots" ||
a == "--conversation-cache-min-free-mib" || a == "--conversation-cache-min-tokens" ||
a == "--session-min-free-mib") {
a == "--session-min-free-mib" || a == "--memory-limit-mib") {
const std::string value = next(a.c_str());
int64_t number = 0;
const auto result = std::from_chars(value.data(), value.data() + value.size(), number);
@@ -1857,6 +1874,7 @@ int main(int argc, char** argv) {
else if (a == "--conversation-cache-min-free-mib") o.conversation_cache_min_free_mib = number;
else if (a == "--conversation-cache-min-tokens") o.conversation_cache_min_tokens = number;
else if (a == "--session-min-free-mib") o.session_min_free_mib = number;
else if (a == "--memory-limit-mib") o.memory_limit_mib = number;
else o.conversation_cache_slots = (int) number;
}
else if (a == "--prompt-cache-tail") o.prompt_cache_tail = true;
@@ -1996,6 +2014,38 @@ int main(int argc, char** argv) {
if (hc == "last") strata::kernels::cpu::set_host_core(strata::kernels::cpu::HostCore::Last);
}
strata::core::set_peer_portable(o.peer_device >= 1); // multi-GPU: the Portable flag on mapped host buffers only with a peer device (before any allocation)
{ // the RAM guard (parking, session save/restore): --memory-limit-mib, else STRATA_MEMORY_LIMIT_MIB, else none
int64_t mib = o.memory_limit_mib;
if (mib < 0) {
const char* env = std::getenv("STRATA_MEMORY_LIMIT_MIB");
if (env != nullptr && env[0] != '\0') {
const size_t len = std::strlen(env);
const auto parsed = std::from_chars(env, env + len, mib);
if (parsed.ec != std::errc{} || parsed.ptr != env + len || mib < 0 || mib > INT64_MAX / (1024 * 1024)) {
std::fprintf(stderr, "STRATA_MEMORY_LIMIT_MIB needs a nonnegative integer within range (got \"%s\")\n", env);
return 2;
}
} else mib = 0;
}
strata::core::set_memory_limit_bytes((uint64_t) mib << 20);
if (o.serve || mib > 0) {
constexpr double GiB = 1073741824.0;
const auto mem = strata::core::sample_host_memory();
if (!mem) {
std::fprintf(stderr, "strata generate: memory guard: the available RAM cannot be read; parking and session "
"save/restore are refused\n");
} else {
std::fprintf(stderr, "strata generate: memory guard: limit %.1f GiB (source: %s), current %.1f GiB, "
"reclaimable cache credited %.1f GiB; available %.1f GiB (MemAvailable %.1f GiB%s), "
"floor %lld MiB\n",
(double) mem->limit / GiB, strata::core::memory_source_name(mem->source),
(double) mem->current / GiB, (double) mem->credit / GiB, (double) mem->available / GiB,
(double) mem->mem_available / GiB,
mib > 0 ? (", --memory-limit-mib " + std::to_string((long long) mib)).c_str() : "",
(long long) o.conversation_cache_min_free_mib);
}
}
}
if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0))
std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n",
o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0");
@@ -7288,18 +7338,21 @@ int main(int argc, char** argv) {
// left. Each ConversationBuffer is a list of 16 MiB segments, each segment its own
// allocation, so an evicted entry is back with the kernel before the next check reads
// /proc/meminfo; no waiting is needed. slots() bounds the loop, and the two lines
// below say what it did either way.
// below say what it did either way. The reading is the guard's (MemAvailable, the cgroup
// limits above the engine, --memory-limit-mib); `mem` keeps the last one for the refusal line.
size_t evicted = 0;
std::optional<strata::core::HostMemoryReading> mem;
auto admit = [&] {
mem = strata::core::sample_host_memory();
return strata::core::conversation_memory_admit(
strata::core::conversation_available_memory(), additional, floor);
mem ? std::optional<uint64_t>(mem->available) : std::nullopt, additional, floor);
};
while (!admit() && conversations.size() > 0 && evicted < conversations.slots() &&
conversations.evict_oldest())
++evicted;
if (!admit()) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor; evicted %zu, %zu still parked, or telemetry unavailable)\n",
additional >> 20, (long long) o.conversation_cache_min_free_mib,
std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, %s; evicted %zu, %zu still parked)\n",
additional >> 20, (long long) o.conversation_cache_min_free_mib, ram_note(mem).c_str(),
evicted, conversations.size());
return true;
}
@@ -7322,8 +7375,11 @@ int main(int argc, char** argv) {
return false;
image.stage_images.push_back(std::move(part));
}
if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");
const auto mem_after = strata::core::sample_host_memory();
if (!strata::core::conversation_memory_admit(
mem_after ? std::optional<uint64_t>(mem_after->available) : std::nullopt, 0, floor)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (RAM floor after capture: %lld MiB needed, %s)\n",
(long long) o.conversation_cache_min_free_mib, ram_note(mem_after).c_str());
return true;
}
const size_t snapshot_bytes = image.bytes();
@@ -7353,6 +7409,9 @@ int main(int argc, char** argv) {
// #471: the position the prompt pass has read up to (a chunk's or a window's end): what a request cancelled
// mid-read reports as read, instead of the whole prompt
int64_t pp_reached = 0;
// #1620: the session holds exactly the tokens [0, pp_reached) of the prompt (no chunk or window is in flight, none
// failed): a request cancelled here keeps them as the live conversation instead of dropping what it restored
bool pp_exact = false;
Clock::time_point pp_t0 = Clock::now();
auto imgs_below = [&](const std::vector<ImgKey>& all, int64_t L) {
std::vector<ImgKey> v;
@@ -8943,14 +9002,27 @@ int main(int argc, char** argv) {
sl.kv_layers = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0) + 1;
}
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
if (o.session_save_reclaim) {
const auto freed = strata::core::session_save_reclaim(
checks, conversations, sl, floor, strata::core::available_host_bytes);
if (freed.bytes || freed.checkpoints || freed.parked) {
// A removed tail must not mark a later checkpoint at this length as a tail.
if (tail_ckpt_len >= 0 && std::none_of(checks.begin(), checks.end(), [&](const auto& c) {
return int64_t(c.ids.size()) == tail_ckpt_len;
})) tail_ckpt_len = -1;
std::fprintf(stderr, "strata serve: save reclaimed %zu checkpoints, %zu parked, "
"%zu host bytes; checking RAM again\n",
freed.checkpoints, freed.parked, freed.bytes);
}
}
auto admit = [&](uint64_t need, std::string& why) {
const auto avail = strata::core::conversation_available_memory();
const auto mem = strata::core::sample_host_memory();
const std::optional<uint64_t> avail = mem ? std::optional<uint64_t>(mem->available) : std::nullopt;
if (strata::core::conversation_memory_admit(avail, need, floor)) return true;
why = "not enough RAM to save the session (" +
(need == UINT64_MAX ? std::string("unknown") : std::to_string(need >> 20)) +
" MiB plus a floor of " + std::to_string((long long) o.conversation_cache_min_free_mib) +
" MiB needed, " + (avail ? std::to_string(*avail >> 20) + " MiB available)"
: "RAM telemetry unavailable)");
" MiB needed, " + ram_note(mem) + ")";
return false;
};
std::vector<ConvCheckpoint> disk_checks;
@@ -9002,11 +9074,12 @@ int main(int argc, char** argv) {
limits.progress = moving;
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
limits.admit = [floor, &o](uint64_t need, std::string& why) {
const auto avail = strata::core::conversation_available_memory();
const auto mem = strata::core::sample_host_memory();
const std::optional<uint64_t> avail = mem ? std::optional<uint64_t>(mem->available) : std::nullopt;
if (strata::core::conversation_memory_admit(avail, need, floor)) return true;
why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " +
std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " +
(avail ? std::to_string(*avail >> 20) + " MiB available)" : "RAM telemetry unavailable)");
ram_note(mem) + ")";
return false;
};
if (!strata::core::conversation_session_read_limits(
@@ -9531,6 +9604,7 @@ int main(int argc, char** argv) {
pp_total = n;
pp_from = read_from;
pp_reached = read_from;
pp_exact = true; // a restore, a checkpoint mount or a zeroed session: the state is exactly at read_from
pp_t0 = r0;
pp_next_check = reread_to > 0 || !req_ckpt ? INT64_MAX : resume + o.prompt_cache_every; // ckpt=0: none
pp_tail_saved = reread_to > 0 || !req_ckpt; // ckpt=0 (#861): no tail checkpoint either
@@ -9684,8 +9758,10 @@ int main(int argc, char** argv) {
~NoHeadSampling() { v.set_head_sampling(true); }
} no_head_sampling(ver);
std::vector<int32_t> win((size_t) S), outw((size_t) S), nxt((size_t) S);
pp_exact = true; // between windows the session is exactly at `a`
for (int64_t q = a; q < b;) {
if (stop_req.load()) { e = "cancelled"; return false; }
pp_exact = false; // until this window and the drafter's rows are in
const int T = (int) std::min<int64_t>(S, b - q);
for (int t = 0; t < T; ++t) {
win[(size_t) t] = (int32_t) cur[(size_t) (q + t)];
@@ -9715,6 +9791,7 @@ int main(int argc, char** argv) {
if (!ver.commit(T, e) || (use_mtp && !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e))) return false;
q += T;
pp_reached = q; // #471
pp_exact = true;
}
// the batched prompt path (other streams), checkpoints and snapshots may follow: the last commit first
if (!ver.wait_commit(e)) return false;
@@ -10054,7 +10131,9 @@ int main(int argc, char** argv) {
return 1;
}
const auto tsp = Clock::now();
pp_exact = false; // a batched or pipelined part is in flight: a cancel may leave the state past pp_reached
const bool sp_ok = win ? read_windows(at, to, err) : read_part(at, to, err);
if (sp_ok) pp_exact = true;
if (trace) {
std::fprintf(stderr, "strata trace: read %lld tokens (%s) in %.1f ms\n", (long long) (to - at),
win ? "windows" : "batched",
@@ -10967,6 +11046,15 @@ int main(int argc, char** argv) {
live.swap(consumed);
live_imgs = imgs_below(req_imgs, (int64_t) live.size());
live_ok = o.prompt_cache > 0 && req_ckpt; // ckpt=0: nothing to continue or park (#830)
} else if (pp_exact && pp_reached > 0 && o.prompt_cache > 0 && req_ckpt && pp_reached <= (int64_t) cur.size()) {
// #1620: stopped between two windows (or before the first token was read): the session is exactly at
// pp_reached, so it stays the live conversation - the next request continues from it or parks it.
// Without this a cancelled request that had restored a parked conversation dropped it.
live.assign(cur.begin(), cur.begin() + pp_reached);
live_imgs = imgs_below(req_imgs, pp_reached);
live_ok = true;
std::fprintf(stderr, "strata serve: cancelled request keeps its conversation: %lld tokens live\n",
(long long) pp_reached);
}
static const bool state_hash = std::getenv("STRATA_STATE_HASH") != nullptr;
if (state_hash && !cancelled && o.prompt_cache > 0) { // every finished request, ckpt=0 too (parity gates)
+4 -4
View File
@@ -7400,7 +7400,7 @@ int main(int argc, char **argv) try {
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib * 1024 * 1024;
const size_t retained = reuse.bytes() + stage_retained;
const size_t additional = estimate > retained ? estimate - retained : 0;
if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(),
if (!strata::core::conversation_memory_admit(strata::core::available_host_bytes(),
additional, floor)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM admission; need %zu MiB plus %lld MiB floor, or telemetry unavailable)\n",
additional >> 20, (long long) o.conversation_cache_min_free_mib);
@@ -7424,7 +7424,7 @@ int main(int argc, char **argv) try {
return false;
image.stage_images.push_back(std::move(part));
}
if (!strata::core::conversation_memory_admit(strata::core::conversation_available_memory(), 0, floor)) {
if (!strata::core::conversation_memory_admit(strata::core::available_host_bytes(), 0, floor)) {
std::fprintf(stderr, "strata serve: conversation cache: skip parking (physical RAM floor after capture, or telemetry unavailable)\n");
return true;
}
@@ -9100,7 +9100,7 @@ int main(int argc, char **argv) try {
}
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
auto admit = [&](uint64_t need, std::string& why) {
const auto avail = strata::core::conversation_available_memory();
const auto avail = strata::core::available_host_bytes();
if (strata::core::conversation_memory_admit(avail, need, floor)) return true;
why = "not enough RAM to save the session (" +
(need == UINT64_MAX ? std::string("unknown") : std::to_string(need >> 20)) +
@@ -9158,7 +9158,7 @@ int main(int argc, char **argv) try {
limits.progress = moving;
const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
limits.admit = [floor, &o](uint64_t need, std::string& why) {
const auto avail = strata::core::conversation_available_memory();
const auto avail = strata::core::available_host_bytes();
if (strata::core::conversation_memory_admit(avail, need, floor)) return true;
why = "not enough RAM to read it (" + std::to_string(need >> 20) + " MiB plus a floor of " +
std::to_string((long long) o.conversation_cache_min_free_mib) + " MiB needed, " +
+349
View File
@@ -0,0 +1,349 @@
// available_host_bytes(): MemAvailable, the cgroup limits above this process, and the operator's cap, on fixture
// directories standing in for /proc/meminfo, /proc/self/cgroup and /sys/fs/cgroup. CPU only, no GPU.
#include "strata/core/conversation_memory.hpp"
#include <unistd.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
#include <fstream>
#include <string>
using namespace strata::core;
namespace fs = std::filesystem;
namespace {
int checks = 0;
void check(bool ok, const char* label) {
++checks;
if (!ok) { std::fprintf(stderr, "FAIL: %s\n", label); std::exit(1); }
}
constexpr uint64_t MiB = 1ull << 20;
constexpr uint64_t GiB = 1ull << 30;
struct Fixture {
fs::path dir;
Fixture() {
static int n = 0;
dir = fs::temp_directory_path() / ("strata_memory_guard_" + std::to_string((long) ::getpid()) + "_" + std::to_string(n++));
fs::remove_all(dir);
fs::create_directories(dir / "cgroup");
}
~Fixture() { std::error_code ec; fs::remove_all(dir, ec); }
void put(const std::string& rel, const std::string& text) {
const fs::path p = dir / rel;
fs::create_directories(p.parent_path());
std::ofstream(p, std::ios::binary) << text;
}
void put(const std::string& rel, uint64_t n) { put(rel, std::to_string(n) + "\n"); }
void meminfo(uint64_t total, uint64_t available) {
put("meminfo", "MemTotal: " + std::to_string(total / 1024) + " kB\nMemFree: 1 kB\nMemAvailable: " +
std::to_string(available / 1024) + " kB\n");
}
void self(const std::string& text) { put("self_cgroup", text + "\n"); }
MemoryProbePaths paths() const { return {(dir / "meminfo").string(), (dir / "self_cgroup").string(), (dir / "cgroup").string()}; }
std::optional<HostMemoryReading> sample(uint64_t explicit_limit = 0) const { return sample_host_memory(paths(), explicit_limit); }
};
} // namespace
int main() {
// no cgroup limit anywhere ("max" at every level, and the root without memory files): plain MemAvailable
{
Fixture f;
f.meminfo(120 * GiB, 25 * GiB);
f.self("0::/a/b");
f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.current", 90 * GiB);
f.put("cgroup/a/memory.max", "max\n"); f.put("cgroup/a/memory.current", 60 * GiB);
f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 50 * GiB);
const auto r = f.sample();
check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "max everywhere is plain MemAvailable");
check(r->limit == 120 * GiB && r->current == 95 * GiB && r->mem_available == 25 * GiB, "meminfo reading: MemTotal and used");
}
// nested v2 limits: the tightest room of the group and its ancestors wins, "max" levels are skipped
{
Fixture f;
f.meminfo(120 * GiB, 80 * GiB);
f.self("0::/a/b");
f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 90 * GiB); // 10 GiB of room
f.put("cgroup/a/memory.max", 60 * GiB); f.put("cgroup/a/memory.current", 58 * GiB); // 2 GiB of room
f.put("cgroup/a/b/memory.max", "max\n"); f.put("cgroup/a/b/memory.current", 50 * GiB);
auto r = f.sample();
check(r && r->available == 2 * GiB && r->source == MemorySource::cgroup, "tightest ancestor wins");
check(r->limit == 60 * GiB && r->current == 58 * GiB, "reading names that group's limit and usage");
f.put("cgroup/a/memory.current", 59 * GiB + 512 * MiB);
r = f.sample();
check(r && r->available == 512 * MiB, "the room follows memory.current");
f.put("cgroup/a/memory.current", 61 * GiB);
r = f.sample();
check(r && r->available == 0 && r->source == MemorySource::cgroup, "usage over the limit is a known zero");
f.put("cgroup/a/memory.current", 10 * GiB);
r = f.sample();
check(r && r->available == 10 * GiB && r->limit == 100 * GiB, "the root's room wins once the group has more");
check(r->source == MemorySource::cgroup, "source cgroup");
// the room under a limit larger than MemAvailable is bounded by MemAvailable
f.meminfo(120 * GiB, 4 * GiB);
r = f.sample();
check(r && r->available == 4 * GiB && r->source == MemorySource::meminfo, "MemAvailable bounds a roomy cgroup");
}
// memory.high below memory.max counts, and a high of "max" does not
{
Fixture f;
f.meminfo(120 * GiB, 80 * GiB);
f.self("0::/g");
f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.high", 99 * GiB + 900 * MiB);
f.put("cgroup/g/memory.current", 99 * GiB);
auto r = f.sample();
check(r && r->available == 900 * MiB && r->limit == 99 * GiB + 900 * MiB, "memory.high lower than memory.max");
f.put("cgroup/g/memory.high", "max\n");
r = f.sample();
check(r && r->available == 1 * GiB && r->limit == 100 * GiB, "memory.high max leaves memory.max");
f.put("cgroup/g/memory.max", "max\n"); f.put("cgroup/g/memory.high", 90 * GiB);
r = f.sample();
check(r && r->available == 0, "memory.high alone, already exceeded");
}
// the operator's cap: the container cannot see its real limit (memory.max is "max" at the namespace root)
{
Fixture f;
f.meminfo(120 * GiB, 25 * GiB); // the stale view: MemAvailable says 25 GiB
f.self("0::/system.slice/strata.service");
f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.high", "max\n");
f.put("cgroup/memory.current", 99 * GiB + 724 * MiB);
f.put("cgroup/system.slice/strata.service/memory.max", "max\n");
f.put("cgroup/system.slice/strata.service/memory.current", 97 * GiB);
check(f.sample() && f.sample()->available == 25 * GiB && f.sample()->source == MemorySource::meminfo,
"without the cap the stale MemAvailable is believed");
auto r = f.sample(100 * GiB);
check(r && r->available == 300 * MiB && r->source == MemorySource::flag, "the cap minus the root's memory.current");
check(r->limit == 100 * GiB && r->current == 99 * GiB + 724 * MiB, "reading names the cap and the usage");
r = f.sample(99 * GiB);
check(r && r->available == 0 && r->source == MemorySource::flag, "usage over the cap is a known zero");
r = f.sample(200 * GiB);
check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "a cap above everything else changes nothing");
// a real limit visible and tighter than the cap: the tighter one
f.put("cgroup/system.slice/memory.max", 98 * GiB); f.put("cgroup/system.slice/memory.current", 97 * GiB + 512 * MiB);
r = f.sample(100 * GiB);
check(r && r->available == 300 * MiB && r->source == MemorySource::flag, "cap tighter than the visible cgroup limit");
r = f.sample(150 * GiB);
check(r && r->available == 512 * MiB && r->source == MemorySource::cgroup, "visible cgroup limit tighter than the cap");
// equal rooms: the operator's number is the one reported
r = f.sample(99 * GiB + 724 * MiB + 512 * MiB);
check(r && r->available == 512 * MiB && r->source == MemorySource::flag, "a tie goes to the operator's cap");
// no memory.current at the root: used = MemTotal - MemAvailable
fs::remove(f.dir / "cgroup/system.slice/memory.max");
fs::remove(f.dir / "cgroup/memory.current");
r = f.sample(100 * GiB);
check(r && r->available == 5 * GiB && r->source == MemorySource::flag && r->current == 95 * GiB,
"without the root's memory.current the meminfo-derived usage is used");
// ... and with no MemTotal either, the usage is unknown: unknown, not a guess
f.put("meminfo", "MemAvailable: 1024 kB\n");
check(!f.sample(100 * GiB), "cap with unknown usage is unknown");
check(f.sample().has_value(), "no cap, no usage needed");
}
// malformed or unusable files: without a cap the guard falls back to MemAvailable alone (meminfo source, once-warned);
// with a cap the sample is unknown (admission refuses), never a guess
{
const char* bad_values[] = {"garbage\n", "", "\n", "-5\n", "+5\n", "12x\n", "1 2\n", "18446744073709551616\n",
"0x10\n", "MAX\n"};
for (const char* file : {"memory.max", "memory.high", "memory.current"}) {
for (const char* text : bad_values) {
Fixture f;
f.meminfo(120 * GiB, 25 * GiB);
f.self("0::/g");
f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.high", "max\n");
f.put("cgroup/g/memory.current", 50 * GiB);
f.put(std::string("cgroup/g/") + file, text);
{
const auto r = f.sample();
check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo,
"malformed cgroup file without a cap: MemAvailable alone");
}
check(!f.sample(100 * GiB), "malformed cgroup file is unknown with the cap too");
}
}
Fixture f;
f.self("0::/g");
f.put("cgroup/g/memory.max", 100 * GiB); f.put("cgroup/g/memory.current", 50 * GiB);
f.meminfo(120 * GiB, 25 * GiB);
check(f.sample() && f.sample()->available == 25 * GiB, "the fixture itself is sound");
fs::remove(f.dir / "cgroup/g/memory.current");
check(f.sample() && f.sample()->available == 25 * GiB && f.sample()->source == MemorySource::meminfo,
"a finite limit with no usage beside it, no cap: MemAvailable alone");
check(!f.sample(100 * GiB), "... and with the cap it is unknown");
f.put("cgroup/g/memory.max", "max\n");
check(f.sample() && f.sample()->available == 25 * GiB, "no finite limit and no usage: the level is skipped");
f.put("cgroup/g/memory.current", "max\n");
check(f.sample() && f.sample()->source == MemorySource::meminfo, "memory.current is never \"max\": MemAvailable alone");
check(!f.sample(100 * GiB), "... unknown with the cap");
f.put("cgroup/g/memory.current", 1ull);
for (const char* text : {"", "MemAvailable: 12 MB\n", "MemAvailable: 1x kB\n", "MemTotal: 5 kB\n",
"MemAvailable: 5 kB\nMemAvailable: 6 kB\n"}) {
f.put("meminfo", text);
check(!f.sample(), "malformed MemAvailable is unknown");
}
fs::remove(f.dir / "meminfo");
check(!f.sample(), "no meminfo is unknown");
f.meminfo(120 * GiB, 25 * GiB);
f.self("0::/a/../g");
check(f.sample() && f.sample()->source == MemorySource::meminfo, "a .. component in the cgroup path: MemAvailable alone");
check(!f.sample(100 * GiB), "a .. component with the cap is refused");
f.self("garbage without colons");
check(f.sample() && f.sample()->available == 25 * GiB, "unparsable /proc/self/cgroup lines are ignored");
}
// a path from /proc/self/cgroup that this mount does not show: the deepest group that is there (at worst the root)
{
Fixture f;
f.meminfo(120 * GiB, 25 * GiB);
f.self("0::/lxc/105/ns/deep");
f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 99 * GiB);
auto r = f.sample();
check(r && r->available == 1 * GiB && r->source == MemorySource::cgroup, "an invisible group falls back to the mount's root");
f.put("cgroup/lxc/memory.max", 100 * GiB); f.put("cgroup/lxc/memory.current", 99 * GiB + 256 * MiB);
r = f.sample();
check(r && r->available == 1 * GiB - 256 * MiB, "the deepest visible prefix is read too");
}
// no /proc/self/cgroup file: the mount's root group; no mount: MemAvailable alone
{
Fixture f;
f.meminfo(120 * GiB, 25 * GiB);
f.put("cgroup/memory.max", 100 * GiB); f.put("cgroup/memory.current", 98 * GiB);
auto r = f.sample();
check(r && r->available == 2 * GiB, "no cgroup file: the root group");
fs::remove_all(f.dir / "cgroup");
r = f.sample();
check(r && r->available == 25 * GiB && r->source == MemorySource::meminfo, "no cgroup mount: MemAvailable");
check(f.sample(100 * GiB) && f.sample(100 * GiB)->source == MemorySource::flag &&
f.sample(100 * GiB)->available == 5 * GiB, "no cgroup mount, a cap: meminfo-derived usage");
}
// cgroup v1
{
Fixture f;
f.meminfo(120 * GiB, 80 * GiB);
f.self("12:cpu,cpuacct:/x\n4:memory:/m/n\n1:name=systemd:/x");
f.put("cgroup/memory/memory.limit_in_bytes", 9223372036854771712ull);
f.put("cgroup/memory/memory.usage_in_bytes", 90 * GiB);
f.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); f.put("cgroup/memory/m/memory.usage_in_bytes", 60 * GiB);
f.put("cgroup/memory/m/n/memory.limit_in_bytes", 9223372036854771712ull);
f.put("cgroup/memory/m/n/memory.usage_in_bytes", 1 * GiB);
auto r = f.sample();
check(r && r->available == 4 * GiB && r->source == MemorySource::cgroup && r->limit == 64 * GiB, "v1: the tightest limit, unlimited skipped");
r = f.sample(100 * GiB);
check(r && r->available == 4 * GiB && r->source == MemorySource::cgroup, "v1 with a looser cap");
r = f.sample(92 * GiB);
check(r && r->available == 2 * GiB && r->source == MemorySource::flag && r->current == 90 * GiB, "v1 with a tighter cap: the v1 root's usage");
f.put("cgroup/memory/m/memory.limit_in_bytes", "junk\n");
check(f.sample() && f.sample()->source == MemorySource::meminfo, "v1 malformed limit, no cap: MemAvailable alone");
check(!f.sample(100 * GiB), "v1 malformed limit with the cap is unknown");
}
// hybrid: a v2 line, but the memory controller lives in the v1 tree
{
Fixture f;
f.meminfo(120 * GiB, 80 * GiB);
f.self("5:memory:/g\n0::/g");
f.put("cgroup/cgroup.controllers", "cpu\n");
f.put("cgroup/g/cpu.max", "max 100000\n");
f.put("cgroup/memory/g/memory.limit_in_bytes", 10 * GiB); f.put("cgroup/memory/g/memory.usage_in_bytes", 9 * GiB);
auto r = f.sample();
check(r && r->available == 1 * GiB && r->source == MemorySource::cgroup, "hybrid falls through to v1");
f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.current", 1 * GiB);
r = f.sample();
check(r && r->available == 80 * GiB, "v2 memory files win over v1 when both exist");
}
// the one credited kind of reclaimable memory: clean inactive file cache from the same group's memory.stat
{
const auto stat = [](uint64_t inactive, uint64_t active, uint64_t shmem, uint64_t dirty = 0, uint64_t wb = 0) {
return "anon 1\nfile 2\nshmem " + std::to_string(shmem) + "\ninactive_file " + std::to_string(inactive) +
"\nactive_file " + std::to_string(active) + "\nfile_dirty " + std::to_string(dirty) +
"\nfile_writeback " + std::to_string(wb) + "\nunevictable 5\n";
};
Fixture f;
f.meminfo(120 * GiB, 25 * GiB);
f.self("0::/system.slice/strata.service");
f.put("cgroup/memory.max", "max\n"); f.put("cgroup/memory.high", "max\n");
f.put("cgroup/memory.current", 98 * GiB + 324 * MiB);
f.put("cgroup/memory.stat", stat(3 * GiB + 800 * MiB, 27 * GiB, 65 * GiB));
f.put("cgroup/system.slice/strata.service/memory.max", "max\n");
f.put("cgroup/system.slice/strata.service/memory.current", 90 * GiB);
// the operator's cap: the root's memory.current less the root's inactive_file; active_file and shmem are not credited
auto r = f.sample(99 * GiB);
check(r && r->source == MemorySource::flag && r->available == 99 * GiB - (98 * GiB + 324 * MiB - 3 * GiB - 800 * MiB),
"the cap path credits the root's inactive_file");
check(r->credit == 3 * GiB + 800 * MiB && r->current == 98 * GiB + 324 * MiB, "reading shows the credit and the raw usage");
f.put("cgroup/memory.stat", stat(0, 27 * GiB, 65 * GiB));
r = f.sample(99 * GiB);
check(r && r->available == 700 * MiB && r->credit == 0, "only inactive_file counts: active_file and shmem give nothing");
// dirty and writeback pages are not clean: taken off the credit
f.put("cgroup/memory.stat", stat(3 * GiB, 0, 0, 1 * GiB, 512 * MiB));
r = f.sample(99 * GiB);
check(r && r->credit == 1 * GiB + 512 * MiB && r->available == 700 * MiB + 1 * GiB + 512 * MiB, "dirty and writeback come off");
f.put("cgroup/memory.stat", stat(3 * GiB, 0, 0, 2 * GiB, 2 * GiB));
r = f.sample(99 * GiB);
check(r && r->credit == 0 && r->available == 700 * MiB, "dirty plus writeback over inactive_file leaves no credit");
// inactive_file larger than the usage: the credit stops at the usage, headroom never exceeds the cap
f.put("cgroup/memory.stat", stat(500 * GiB, 0, 0));
f.meminfo(300 * GiB, 200 * GiB); // so the cap's room (not MemAvailable) is the smallest term
r = f.sample(99 * GiB);
check(r && r->credit == 98 * GiB + 324 * MiB && r->available == 99 * GiB && r->source == MemorySource::flag,
"inactive_file above the usage cannot lift headroom over the cap");
// no memory.stat, or one that cannot be read: no credit, still a sample
fs::remove(f.dir / "cgroup/memory.stat");
r = f.sample(99 * GiB);
check(r && r->available == 700 * MiB && r->credit == 0, "no memory.stat: no credit");
for (const char* text : {"", "garbage\n", "inactive_file\n", "inactive_file -1\n", "inactive_file 12x\n",
"inactive_file 1\ninactive_file 2\n", "inactive_file 99999999999999999999\n",
"inactive_file 4096\nfile_dirty zz\n"}) {
f.put("cgroup/memory.stat", text);
r = f.sample(99 * GiB);
check(r && r->available == 700 * MiB && r->credit == 0, "unparsable memory.stat: no credit, not unknown");
}
// a cgroup limit's own group is credited from its own memory.stat
f.put("cgroup/memory.stat", stat(0, 0, 0));
f.put("cgroup/system.slice/strata.service/memory.max", 92 * GiB);
f.put("cgroup/system.slice/strata.service/memory.stat", stat(1 * GiB, 0, 0));
r = f.sample();
check(r && r->source == MemorySource::cgroup && r->available == 3 * GiB && r->credit == 1 * GiB &&
r->limit == 92 * GiB && r->current == 90 * GiB, "a cgroup limit credits its own group's inactive_file");
f.put("cgroup/system.slice/strata.service/memory.stat", stat(500 * GiB, 0, 0));
f.meminfo(300 * GiB, 200 * GiB);
r = f.sample();
check(r && r->available == 92 * GiB && r->credit == 90 * GiB, "cgroup term: the credit stops at the usage too");
// cgroup v1: total_inactive_file (and total_dirty / total_writeback)
Fixture g;
g.meminfo(120 * GiB, 80 * GiB);
g.self("4:memory:/m");
g.put("cgroup/memory/m/memory.limit_in_bytes", 64 * GiB); g.put("cgroup/memory/m/memory.usage_in_bytes", 62 * GiB);
g.put("cgroup/memory/memory.limit_in_bytes", 9223372036854771712ull); g.put("cgroup/memory/memory.usage_in_bytes", 62 * GiB);
g.put("cgroup/memory/m/memory.stat", "cache 1\ninactive_file 7\ntotal_inactive_file " + std::to_string(3 * GiB) +
"\ntotal_dirty " + std::to_string(1 * GiB) + "\ntotal_writeback 0\n");
r = g.sample();
check(r && r->available == 2 * GiB + 2 * GiB && r->credit == 2 * GiB && r->source == MemorySource::cgroup,
"v1 credits total_inactive_file less total_dirty");
g.put("cgroup/memory/m/memory.stat", "inactive_file " + std::to_string(3 * GiB) + "\n");
r = g.sample();
check(r && r->available == 2 * GiB && r->credit == 0, "v1 ignores the non-total inactive_file");
}
// the process-wide setting and the real files
{
check(memory_limit_bytes() == 0, "no cap by default");
set_memory_limit_bytes(123 * MiB);
check(memory_limit_bytes() == 123 * MiB, "cap round trip");
#if defined(__linux__)
set_memory_limit_bytes(1); // one byte: whatever this machine uses, nothing is left
const auto r = sample_host_memory();
check(!r || (r->available == 0 && r->source == MemorySource::flag && available_host_bytes() == 0u),
"the real files honour the process-wide cap");
#endif
set_memory_limit_bytes(0);
const auto none = available_host_bytes();
check(!none || conversation_memory_admit(none, 0, 0), "the real files without a cap: bytes or unknown");
check(std::string(memory_source_name(MemorySource::flag)) == "flag" &&
std::string(memory_source_name(MemorySource::cgroup)) == "cgroup" &&
std::string(memory_source_name(MemorySource::meminfo)) == "meminfo", "source names");
}
std::printf("memory_guard_test: %d checks passed\n", checks);
return 0;
}
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""#1604: with --batch N --batch-groups N on a layer split, two long conversations that alternate must reuse their slot
(or the conversation cache) on every later turn instead of reading their prompt from token 0.
python3 tools/batch_groups_cache_test.py CFG OUT.json
STRATA_EXTRA_ARGS="--batch 2 --batch-groups 2 --prompt-cache 4 --conversation-cache-mib 4096 --conversation-cache-slots 3"
Three rounds; each round runs conversation A and conversation B at the same time (so both go through the batch slots),
the next round continues each one (prompt + its answer + a new user turn). The engine log says per request how many
prompt tokens were reused. PASS when every request of rounds 2 and 3 reused at least 90 % of the previous round's
prompt. The answers (token ids) are written to OUT.json to compare two runs.
"""
import json, os, re, sys, threading
from pathlib import Path
REPO = Path(os.environ.get("STRATA_REPO", Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(REPO / "tools")); sys.path.insert(0, str(REPO))
import strata_tokenizer as ST
from serve.server import StrataEngine, child_env, engine_args
cfg = json.load(open(sys.argv[1]))
tp = Path(cfg["tokenizer"])
vocab = json.loads((tp / "vocab.json").read_text())
toks = [None] * len(vocab)
for t, i in vocab.items():
toks[i] = t
tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text().split("\n"), json.loads((tp / "token_type.json").read_text()))
if os.environ.get("GPUS"): # e.g. GPUS=0,1: a layer split over those cards (SPLIT=auto)
cfg["gpu"] = [int(x) for x in os.environ["GPUS"].split(",")]
cfg["layer_split"] = os.environ.get("SPLIT", "auto")
args = engine_args(cfg) + os.environ.get("STRATA_EXTRA_ARGS", "").split()
log = os.environ.get("SMOKE_LOG", cfg["log"])
eng = StrataEngine(os.environ.get("STRATA_EXE", cfg["exe"]), args, cwd=cfg.get("cwd"), log=log, env=child_env(cfg))
GEN = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
def enc(text):
return tok.encode(text, parse_special=True)
def first(tag, n):
return enc(f"<|im_start|>user\n[{tag}] " + " ".join(f"Entry {i} of {tag}: value {i * 13 % 97}." for i in range(n))
+ "\nCount from 1 to 80 separated by commas." + GEN)
conv = {"A": first("alpha", 250), "B": first("bravo", 250)}
answers = {"A": [], "B": []}
prev_len = {}
rounds = []
def one(name, ids, out):
res = [t for t in eng.generate(ids, 80, {"temperature": 0}, threading.Event()) if t is not None]
out[name] = res
for rnd in range(3):
lens = {k: len(v) for k, v in conv.items()}
out = {}
ts = [threading.Thread(target=one, args=(k, conv[k], out)) for k in ("A", "B")]
for t in ts:
t.start()
for t in ts:
t.join()
rounds.append({"prompt_lens": lens, "answers": out})
print(f"round {rnd + 1}: prompts {lens}, answers {[len(v) for v in out.values()]}", flush=True)
for k in conv:
answers[k].append(out[k])
conv[k] = conv[k] + out[k] + enc(f"<|im_end|>\n<|im_start|>user\nNow count from {rnd + 2} to {rnd + 60}." + GEN)
eng.proc.stdin.close()
try:
eng.proc.wait(60)
except Exception:
eng.proc.kill()
json.dump(rounds, open(sys.argv[2], "w"))
text = open(log, errors="replace").read()
reqs = [(int(a), int(b)) for a, b in re.findall(r"strata serve: prompt (\d+) tokens = (\d+) reused", text)]
print("requests (prompt tokens, reused):", reqs)
print("slot gave back lines:", len(re.findall(r"gave back", text)), " conversation cache restores:",
len(re.findall(r"conversation cache: restored", text)))
# rounds 2 and 3 are the last 4 requests of the log
ok = len(reqs) >= 6
for p, r in reqs[2:]:
if r < 0.9 * (p - 140): # the previous prompt + answer is ~all of it but the new turn
ok = False
print("PASS" if ok else "FAIL")
sys.exit(0 if ok else 1)
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""#1620: a request cancelled right after it restored a parked conversation must not lose that conversation.
A (long answer) -> B (an unrelated chat parks A) -> A2 = A + a short next turn, STOPped as soon as the engine
says RESUME (the parked A is restored, nothing or a few windows read) -> A3 = A + another next turn.
A3 must reuse the whole of A and its answer from the live session; without the fix the cancelled A2 had taken
the parked entry and A3 fell back to the turn checkpoint (the prompt, not the answer).
python3 tools/cancel_park_test.py CFG # CFG: a run config json (as tools used by smoke); needs a conversation cache:
STRATA_EXTRA_ARGS="--prompt-cache 4 --conversation-cache-mib 2048 --conversation-cache-slots 3"
Prints PASS / FAIL and the reused token counts. Exit status 0 on PASS.
"""
import json, os, queue, sys, threading, time
from pathlib import Path
REPO = Path(os.environ.get("STRATA_REPO", Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(REPO / "tools")); sys.path.insert(0, str(REPO))
import strata_tokenizer as ST
from serve.server import StrataEngine, child_env
cfg = json.load(open(sys.argv[1]))
tp = Path(cfg["tokenizer"])
vocab = json.loads((tp / "vocab.json").read_text())
toks = [None] * len(vocab)
for t, i in vocab.items():
toks[i] = t
tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text().split("\n"), json.loads((tp / "token_type.json").read_text()))
args = cfg["args"] + os.environ.get("STRATA_EXTRA_ARGS", "").split()
eng = StrataEngine(os.environ.get("STRATA_EXE", cfg["exe"]), args, cwd=cfg.get("cwd"),
log=os.environ.get("SMOKE_LOG", cfg["log"]), env=child_env(cfg))
HEAD = "<|im_start|>user\n"
GEN = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
def enc(text):
return tok.encode(text, parse_special=True)
def run(ids, max_new=200):
out = [t for t in eng.generate(ids, max_new, {"temperature": 0}, threading.Event()) if t is not None]
return out, int(eng.last.get("reused") or 0)
def run_cancelled(ids):
"""GEN, then STOP once the engine has said RESUME (the restore is done, the prompt is not read yet)."""
eng.proc.stdin.write("GEN 200 " + ",".join(str(int(t)) for t in ids) + "\n")
eng.proc.stdin.flush()
stopped, reused, fin = False, None, None
deadline = time.time() + 600
while time.time() < deadline:
try:
line = eng.lines.get(timeout=1)
except queue.Empty:
continue
if line is None:
raise SystemExit("FAIL: the engine died")
if line.startswith("RESUME "):
reused = int(line.split()[1])
eng.proc.stdin.write("STOP\n"); eng.proc.stdin.flush(); stopped = True
elif line.startswith("DONE "):
fin = line.split()[5] if len(line.split()) > 5 else "?"
break
return reused, fin, stopped
story = " ".join(f"Item {i}: the quick brown fox number {i} jumps over lazy dog {i * 7}." for i in range(70))
A1 = enc(HEAD + story + "\nNow count from 1 to 120 separated by commas." + GEN)
outA, r0 = run(A1, 300)
print(f"A: prompt {len(A1)} tokens, {len(outA)} generated, reused {r0}", flush=True)
B1 = enc(HEAD + "Say hello in one short sentence." + GEN)
outB, rb = run(B1, 20)
print(f"B: prompt {len(B1)} tokens, reused {rb} (A is parked now)", flush=True)
cont = enc("<|im_end|>\n<|im_start|>user\nNow say only the word done." + GEN)
A2 = A1 + outA + cont
reused2, fin2, stopped = run_cancelled(A2)
print(f"A2 (cancelled): restored/reused at RESUME {reused2}, finish {fin2}, STOP sent {stopped}", flush=True)
cont3 = enc("<|im_end|>\n<|im_start|>user\nNow say only the word finished." + GEN)
A3 = A1 + outA + cont3
outA3, reused3 = run(A3, 20)
want = len(A1) + len(outA) - 3
print(f"A3: prompt {len(A3)} tokens, reused {reused3} (A + its answer = {len(A1) + len(outA)}; need >= {want})", flush=True)
eng.proc.stdin.close()
try:
eng.proc.wait(60)
except Exception:
eng.proc.kill()
ok = fin2 == "cancel" and reused3 >= want
print("PASS" if ok else "FAIL")
sys.exit(0 if ok else 1)
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""SAVE / RESTORE round trip with parked conversations holding the host RAM (#1572 / #1573).
python3 tools/session_pressure_test.py CFG OUTFILE
STRATA_EXTRA_ARGS="--prompt-cache 4 --conversation-cache-mib 3072 --conversation-cache-slots 4
--conversation-cache-min-free-mib <floor> [--session-save-reclaim]"
Parks three conversations, runs a fourth (D), SAVEs it, runs an unrelated one, RESTOREs, and checks that D's next turn
gives the same token ids after the restore as it does when continued live. Prints SAVE: ok|refused (...) and PASS/FAIL.
"""
import json, os, sys, threading, time
from pathlib import Path
REPO = Path(os.environ.get("STRATA_REPO", Path(__file__).resolve().parent.parent))
sys.path.insert(0, str(REPO / "tools")); sys.path.insert(0, str(REPO))
import strata_tokenizer as ST
from serve import server as S
from serve.server import StrataEngine, child_env
cfg = json.load(open(sys.argv[1]))
out_file = sys.argv[2]
tp = Path(cfg["tokenizer"])
vocab = json.loads((tp / "vocab.json").read_text())
toks = [None] * len(vocab)
for t, i in vocab.items():
toks[i] = t
tok = ST.Tokenizer(toks, (tp / "merges.txt").read_text().split("\n"), json.loads((tp / "token_type.json").read_text()))
args = cfg["args"] + os.environ.get("STRATA_EXTRA_ARGS", "").split()
eng = StrataEngine(os.environ.get("STRATA_EXE", cfg["exe"]), args, cwd=cfg.get("cwd"),
log=os.environ.get("SMOKE_LOG", cfg["log"]), env=child_env(cfg))
GEN = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
def enc(text):
return tok.encode(text, parse_special=True)
def run(ids, max_new=60):
out = [t for t in eng.generate(ids, max_new, {"temperature": 0}, threading.Event()) if t is not None]
return out, int(eng.last.get("reused") or 0)
def chat(tag, n):
return enc(f"<|im_start|>user\n[{tag}] " + " ".join(f"Entry {i} of {tag}: value {i * 13 % 97}." for i in range(n))
+ "\nSummarize in one line." + GEN)
for tag in ("alpha", "bravo", "charlie"):
p = chat(tag, 70)
run(p, 20)
D = chat("delta", 80)
outD, _ = run(D, 60)
print(f"D: prompt {len(D)} tokens, {len(outD)} generated", flush=True)
nxt = enc("<|im_end|>\n<|im_start|>user\nNow say only the word done." + GEN)
saved = False
hog = None
if os.environ.get("HOG_TARGET_MIB"): # take the RAM so that only HOG_TARGET_MIB stay available: a SAVE needs more
import psutil
extra = psutil.virtual_memory().available - int(os.environ["HOG_TARGET_MIB"]) * 2**20
if extra > 0:
hog = bytearray(extra)
for i in range(0, len(hog), 4096):
hog[i] = 1
print("available now: %d MiB" % (psutil.virtual_memory().available >> 20), flush=True)
try:
r = eng.session_file("save", out_file)
saved = True
print("SAVE: ok", r, flush=True)
except S.SessionRefused as e:
print("SAVE: refused", e.kind, str(e)[:300], flush=True)
if not saved and "--session-save-reclaim" in args:
# the server's bounded retry on the same engine
class Svc:
engine = eng
from serve.session_save_retry import session_file as retry
try:
r = retry(Svc, "save", out_file, S.SessionRefused)
saved = True
print("SAVE after the bounded wait: ok", r, flush=True)
except S.SessionRefused as e:
print("SAVE after the bounded wait: refused", e.kind, str(e)[:300], flush=True)
hog = None # the RAM goes back
if not saved:
print("NOSAVE")
eng.proc.stdin.close()
sys.exit(2)
live_next, reused_live = run(D + outD + nxt, 20)
print(f"D live next turn: reused {reused_live}", flush=True)
run(chat("echo", 70), 20) # something else takes the session
r = eng.session_file("restore", out_file)
print("RESTORE:", r, flush=True)
again, reused_r = run(D + outD + nxt, 20)
print(f"D after RESTORE: reused {reused_r}", flush=True)
eng.proc.stdin.close()
try:
eng.proc.wait(60)
except Exception:
eng.proc.kill()
ok = again == live_next and reused_r > 0
print("PASS" if ok else "FAIL (ids %s)" % ("equal" if again == live_next else "differ"))
sys.exit(0 if ok else 1)