Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

session files r4: SAVE RAM preflight before any checkpoint copy; progress after every block and bounded SWAIT allowances for blocking steps (review A/B)

Maurizio Verde8b2160888bfd
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 824e8d628..b51f4b0cd 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -781,9 +781,13 @@ tokens in the measurement below). Only the deepest checkpoint is saved, so an ed
Clients still send their messages (and images): the file holds engine state and token/image identity, not a chat
export. Underneath, `strata --serve` takes `SAVE <path>` and `RESTORE <path>` on stdin between requests and answers
`SAVED <tokens> <bytes> <ms>`, `RESTORED <tokens> <bytes> <ms>`, `SERR <kind> <published 0|1> <reason>` (failed,
-the engine and the session as they were) or `FATAL <reason>` (then exits); `SESSION <done> <total>` lines report a large
-file as it moves (at most once a second and at every 256 MiB). The server checks every line: a malformed or unknown
-one, counts that are negative or go back, or a time that is not a finite number end the engine as out of step.
+the engine and the session as they were) or `FATAL <reason>` (then exits). On the way, `SESSION <done> <total>` follows
+every block of the file that moved (at most 16 MiB, the last partial block and a small file included), and
+`SWAIT <phase> <seconds>` comes before a step that blocks in one call (`fingerprint`, `capture`, `flush`, `publish`,
+`validate`, `transfer`): that step is allowed those seconds - 60 plus one per 4 MiB it concerns, at most 3600 - by the
+engine's watchdog and by the server, then it counts as stuck. The next line clears the allowance. The server checks
+every line: a malformed or unknown one, counts that are negative or go back, an allowance outside 1..3600 or a time
+that is not a finite number end the engine as out of step.
One file holds the running state, the deepest checkpoint, every QSA layer's K/V up to the conversation's length and
the draft layer's K/V. Format v1, little-endian, fixed-width integers, IEEE-754 floats (a big-endian build does not
diff --git a/include/strata/core/conversation_file.hpp b/include/strata/core/conversation_file.hpp
index 73aa08dfe..069ca2423 100644
--- a/include/strata/core/conversation_file.hpp
+++ b/include/strata/core/conversation_file.hpp
@@ -126,14 +126,29 @@ struct SessionStatus {
bool dir_flush_unsupported = false;
};
+// Progress of a file transfer: (bytes done, bytes in the file). A write reports once when its temporary file is
+// created (0) and after every block it hands to the OS (16 MiB, or less for the last one: a small file reports too);
+// a read reports after every block it reads (16 MiB, or what is left; the first one, which holds the header, too).
+// Each report follows a completed transfer of at most 16 MiB: no step between two reports moves more.
+using SessionProgress = std::function<void(uint64_t done, uint64_t total)>;
+// A step that does not stream - one call that blocks until it is done, over far more than 16 MiB or on the OS's
+// schedule (flushing the file, the rename and folder flush) - is announced before it starts, with the bytes it
+// concerns. The engine turns this into an explicit, bounded allowance (session_phase_limit_s) for its watchdog and
+// for the server; when the allowance runs out the step is stuck.
+using SessionPhase = std::function<void(const char* phase, uint64_t bytes)>;
+// The longest a non-streaming step over `bytes` may take before both sides call it stuck: 60 s plus one second per
+// 4 MiB (a slow disk or network folder at 4 MiB/s), at most an hour. 1.2 GB: 345 s.
+int64_t session_phase_limit_s(uint64_t bytes);
+
// Optional knobs of a write.
struct SessionWriteOptions {
// the free-space PREFLIGHT: refused when the disk has less than the new file plus this many bytes free before the
// write starts. Not a reservation: other writers can take the space afterwards.
uint64_t min_free_bytes = 0;
bool durable = true; // flush the file before the rename and (POSIX) the folder after it
- // after a 16 MiB block at most once a second, and at least at every 256 MiB boundary
- std::function<void(uint64_t done, uint64_t total)> progress;
+ SessionProgress progress;
+ // "flush" (the file's flush, `bytes` = the file) and "publish" (rename and folder flush), before each starts
+ SessionPhase phase;
// tests: return an errno value to make a step fail ("write", "file_flush", "rename", "dir_flush"), 0 to go on
std::function<int(const char* step)> fault;
};
@@ -167,6 +182,25 @@ bool session_file_write(const std::string& path, const SavedConversation& meta,
// The checkpoints worth a disk write: the deepest one (the next turn's resume point when the live tail was
// rewritten). Earlier checkpoints only serve edits further back and cost ~118 MB each at this geometry.
std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vector<ConversationCheckpoint>& chain);
+// The same choice without a copy (nullptr for an empty chain).
+const ConversationCheckpoint* session_deepest_checkpoint(const std::vector<ConversationCheckpoint>& chain);
+
+// What a SAVE copies into RAM besides what the engine already holds, for its RAM preflight.
+struct SessionSaveLive {
+ uint64_t state_bytes = 0; // the live running state (gdn + ple + every owned QSA layer's tail, dead, block_pos)
+ uint64_t tokens = 0, images = 0;
+ uint64_t kv_layers = 0; // K/V sources (owned QSA layers + the draft)
+};
+// The peak, with saturating arithmetic: two copies of the deepest checkpoint (the list handed to the capture and the
+// one inside the captured image), the copied live state with its token and image lists, the K/V source directory,
+// the 16 MiB write buffer and 1 MiB for the small vectors.
+uint64_t session_save_peak_bytes(const ConversationCheckpoint* deepest, const SessionSaveLive& live);
+// The SAVE's RAM PREFLIGHT, BEFORE anything is copied: `admit` is asked for session_save_peak_bytes; only when it
+// agrees is the deepest checkpoint copied into `out`. On a refusal nothing was allocated, `out` is empty, `chain`
+// and the live state are untouched and no file was opened. Not a reservation.
+bool session_save_checkpoints(const std::vector<ConversationCheckpoint>& chain, const SessionSaveLive& live,
+ const std::function<bool(uint64_t need_bytes, std::string& why)>& admit,
+ std::vector<ConversationCheckpoint>& out, std::string& why);
// What a read checks before it allocates. Every count is checked against the bytes left in the payload and against
// these limits BEFORE its array is allocated; the defaults accept whatever the payload can hold. The engine sets all
@@ -187,8 +221,7 @@ struct SessionReadLimits {
// the RAM PREFLIGHT: asked once the header and identity match and before any payload allocation, with what the
// parse holds at its peak (session_read_peak_bytes); false refuses the file. Not a reservation.
std::function<bool(uint64_t need_bytes, std::string& why)> admit;
- // after a 16 MiB block at most once a second, and at least at every 256 MiB boundary
- std::function<void(uint64_t done, uint64_t total)> progress;
+ SessionProgress progress;
};
// The largest file these limits admit (UINT64_MAX when one of them is open); session_file_read applies it.
uint64_t session_read_max_file_bytes(const SessionReadLimits& limits);
diff --git a/include/strata/core/progress.hpp b/include/strata/core/progress.hpp
index 0d982c1d8..4bc4a901a 100644
--- a/include/strata/core/progress.hpp
+++ b/include/strata/core/progress.hpp
@@ -22,6 +22,9 @@ struct Progress {
std::atomic<int64_t> chunk{-1}; ///< #251: the prompt chunk (its first position) a batched-read stage is in
std::atomic<int64_t> since_ms{0}; ///< when `where` was set (steady clock): how long a stage has lasted
std::atomic<uint64_t> ticks{0}; ///< layers served: a window that still moves, slowly, against one that stopped
+ /// a step that blocks in one call (a file flush, a host->device transfer of a whole session) is given until this
+ /// time (steady ms; 0 = none) instead of the watchdog's limit - an explicit, bounded allowance, not a beat
+ std::atomic<int64_t> allow_until_ms{0};
};
inline int64_t progress_now_ms() {
@@ -57,5 +60,11 @@ inline void progress_at(const char* where, int64_t detail = -1, int64_t chunk =
inline void progress_beat() { progress().beats.fetch_add(1, std::memory_order_relaxed); }
inline void progress_tick() { progress().ticks.fetch_add(1, std::memory_order_relaxed); }
+/// A beat that also sets (seconds > 0) or clears (0) the allowance of a blocking step: the watchdog does not fire
+/// before the allowance ends, and fires at its end if nothing beat since.
+inline void progress_allow(int64_t seconds) {
+ progress().allow_until_ms.store(seconds > 0 ? progress_now_ms() + seconds * 1000 : 0, std::memory_order_relaxed);
+ progress_beat();
+}
} // namespace strata::core
diff --git a/serve/server.py b/serve/server.py
index 84602c0da..a9889bd64 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -202,6 +202,9 @@ RATE_MIN_SPAN_S = 0.25 # younger than this there is no rate yet: the mean s
# server (the engine's main thread waits, untimed, for its next command): the engine is ended and the request fails;
# the next request starts it again. The config's "engine_silence_s" sets it (0: wait forever, as before).
ENGINE_SILENCE_S = 300.0
+# Disk sessions: the longest allowance an engine may announce (`SWAIT <phase> <s>`) for one step that blocks in a
+# single call (a file flush, the host->device transfer); the engine's own bound is the same (session_phase_limit_s).
+SESSION_WAIT_MAX_S = 3600
# ... except while a prompt is read: a PP line comes once per chunk (up to 32768 tokens with --prefill auto, issue
# #282), and the slowest PCs read ~100 tok/s, so a first chunk can take minutes before the first line. Until the first
# PP the wait adds the chunk's tokens at PP_FLOOR_TOK_S; after one, a chunk may take PP_SLACK x the last one's time.
@@ -1405,8 +1408,11 @@ class StrataEngine:
malformed one, a bare ERR, an answer with negative counts or a non-finite time - means the two sides lost
step: the engine is ended (EngineDied) and the next request starts it again. EngineDied also when it ended
by itself (a restore transfer that failed after the device state changed ends it on purpose: FATAL), and
- EngineSilent (#481) when it printed nothing valid - a SESSION progress line counts only when its numbers are
- - for engine_silence_s."""
+ EngineSilent (#481) when it printed nothing valid for engine_silence_s - a SESSION progress line (one per
+ block of the file moved, at most 16 MiB) counts only when its numbers are. `SWAIT <phase> <seconds>` announces
+ a step that blocks in one call (a flush, the device transfer): until the next line the wait is that step's
+ explicit allowance (at most SESSION_WAIT_MAX_S) when it is longer than engine_silence_s - no more, so a step
+ that never ends is still ended."""
if action not in ("save", "restore") or any(c in path for c in "\r\n\0"):
raise ValueError("invalid session command")
try:
@@ -1434,14 +1440,17 @@ class StrataEngine:
return int(s)
last_done = -1
+ allow = 0.0 # the announced blocking step's allowance, seconds
while True:
- left = silence - (time.monotonic() - heard) if silence > 0 else None
+ limit = max(silence, allow)
+ left = limit - (time.monotonic() - heard) if silence > 0 else None
try:
if left is not None and left <= 0:
raise queue.Empty
line = self.lines.get(timeout=left)
except queue.Empty:
- raise self._silent(f"the engine said nothing for {silence:.0f} s during a session {action}") from None
+ raise self._silent(f"the engine said nothing for {limit:.0f} s during a session {action}"
+ + (f" (in a blocking step allowed {allow:.0f} s)" if allow > silence else "")) from None
if line is None:
raise EngineDied(f"the engine stopped unexpectedly (exit code {self.exit_code()})")
f = line.split()
@@ -1456,7 +1465,18 @@ class StrataEngine:
except ValueError:
raise out_of_step(line) from None
last_done = done
- heard = time.monotonic()
+ heard, allow = time.monotonic(), 0.0
+ continue
+ if head == "SWAIT": # a blocking step starts: its bounded allowance
+ try:
+ if len(f) != 3 or not f[1].isalpha() or not f[1].isascii():
+ raise ValueError
+ seconds = count(f[2])
+ if not 0 < seconds <= SESSION_WAIT_MAX_S:
+ raise ValueError
+ except ValueError:
+ raise out_of_step(line) from None
+ heard, allow = time.monotonic(), float(seconds)
continue
if head == "FATAL":
raise EngineDied(line[6:].strip() or "the engine ended during a session restore")
diff --git a/serve/test_slots.py b/serve/test_slots.py
index 24a19c769..f2df6f138 100644
--- a/serve/test_slots.py
+++ b/serve/test_slots.py
@@ -38,11 +38,18 @@ class FakeProc:
cmd, _, path = s.strip().partition(" ")
script = self.engine.script
if script is not None: # a scripted answer: a list of lines, None = the process ends
- for line in script:
- if isinstance(line, float):
- time.sleep(line)
- else:
- self.engine.lines.put(line)
+ # played by its own thread, like the real engine's output: write() returns at once, so the server's
+ # wait (and its deadline) is already running when a delayed line arrives
+ def play():
+ for line in script:
+ if self.killed:
+ return
+ if isinstance(line, float):
+ time.sleep(line)
+ else:
+ self.engine.lines.put(line)
+ self.player = threading.Thread(target=play, daemon=True)
+ self.player.start()
return
if cmd == "SAVE":
if self.engine.fail:
@@ -105,9 +112,18 @@ class Slots(unittest.TestCase):
self.engine.fail = False
self.engine.script = None
self.engine.silence_s = 300.0
+ self.fresh_engine()
+ self.svc.slot_save_path = self.dir.name
+
+ def fresh_engine(self):
self.engine.ended = False
+ old = getattr(self.engine.proc, "player", None)
+ if old is not None: # the previous scripted engine has finished...
+ self.engine.proc.killed = True
+ old.join(timeout=5)
+ while not self.engine.lines.empty(): # ...and left no line for the next exchange
+ self.engine.lines.get_nowait()
self.engine.proc = FakeProc(self.engine)
- self.svc.slot_save_path = self.dir.name
def post(self, path, body, headers=None):
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
@@ -214,11 +230,71 @@ class Slots(unittest.TestCase):
self.engine.silence_s = 0.3
self.engine.script = [0.2, "SESSION 268435456 1198691396\n", 0.2, "SESSION 536870912 1198691396\n", 0.2,
"SAVED 63000 1198691396 2000.0\n"]
+ t0 = time.monotonic()
s, b = self.post("/slots/0?action=save", {"filename": "long.bin"})
self.assertEqual(s, 200, b)
+ self.assertGreater(time.monotonic() - t0, 0.5) # the lines arrived during the wait, past its 0.3 s
self.assertEqual(b["n_written"], 1198691396)
self.assertFalse(self.engine.ended)
+ def test_a_small_save_reports_its_only_partial_block(self):
+ """B: a file below one 16 MiB block still reports (the start, then its last partial block)."""
+ self.engine.silence_s = 0.3
+ self.engine.script = ["SESSION 0 56834\n", 0.2, "SESSION 56834 56834\n", 0.2, "SAVED 120 56834 410.0\n"]
+ s, b = self.post("/slots/0?action=save", {"filename": "small.bin"})
+ self.assertEqual(s, 200, b)
+ self.assertEqual(b["n_written"], 56834)
+ self.assertFalse(self.engine.ended)
+
+ def test_a_blocking_step_gets_its_announced_allowance(self):
+ """B: SWAIT gives one non-streaming step (a flush, the device transfer) its own bounded wait."""
+ self.engine.silence_s = 0.3
+ self.engine.script = ["SESSION 1198691396 1198691396\n", "SWAIT flush 1\n", 0.7, "SWAIT publish 1\n", 0.7,
+ "SAVED 63000 1198691396 2000.0\n"]
+ t0 = time.monotonic()
+ s, b = self.post("/slots/0?action=save", {"filename": "flush.bin"})
+ self.assertEqual(s, 200, b)
+ self.assertGreater(time.monotonic() - t0, 1.3) # longer than the silence limit, twice
+ self.assertFalse(self.engine.ended)
+ Path(self.dir.name, "flush.bin").write_bytes(b"x") # the scripted engine wrote nothing; restore needs a file
+ self.engine.script = ["SESSION 16777216 1198691396\n", 0.2, "SWAIT validate 1\n", 0.7, "SWAIT transfer 1\n", 0.7,
+ "RESTORED 63000 1198691396 900.0\n"]
+ s, b = self.post("/slots/0?action=restore", {"filename": "flush.bin"})
+ self.assertEqual(s, 200, b)
+
+ def test_a_blocking_step_that_never_ends_is_ended(self):
+ """B: the allowance is a bound, not a heartbeat: a step that outlives it ends the engine."""
+ self.engine.silence_s = 0.3
+ self.engine.script = ["SWAIT flush 1\n"] # then nothing
+ t0 = time.monotonic()
+ s, b = self.post("/slots/0?action=save", {"filename": "stuck.bin"})
+ took = time.monotonic() - t0
+ self.assertEqual(s, 500, b)
+ self.assertGreater(took, 0.9)
+ self.assertLess(took, 5)
+ self.assertIn("blocking step allowed 1 s", b["error"]["message"])
+ self.assertTrue(self.engine.ended and self.engine.proc.killed)
+
+ def test_progress_ends_the_allowance(self):
+ """B: after a SESSION line the ordinary silence limit applies again (the allowance was for one step)."""
+ self.engine.silence_s = 0.3
+ self.engine.script = ["SWAIT transfer 2\n", "SESSION 1 2\n", 0.8, "SAVED 1 2 1.0\n"]
+ s, b = self.post("/slots/0?action=save", {"filename": "reset.bin"})
+ self.assertEqual(s, 500, b)
+ self.assertIn("said nothing", b["error"]["message"])
+ self.assertNotIn("blocking step", b["error"]["message"])
+ self.assertTrue(self.engine.ended)
+
+ def test_malformed_allowances_end_the_engine(self):
+ for script in (["SWAIT flush 0\n"], ["SWAIT flush 3601\n"], ["SWAIT 5\n"], ["SWAIT flush x\n"],
+ ["SWAIT flush -1\n"], ["SWAIT fl:sh 5\n"], ["SWAIT flush 5 extra\n"]):
+ with self.subTest(script=script):
+ self.fresh_engine()
+ self.engine.script = script + [0.1, "SAVED 1 2 1.0\n"]
+ s, b = self.post("/slots/0?action=save", {"filename": "bad.bin"})
+ self.assertEqual(s, 500, b)
+ self.assertTrue(self.engine.ended and self.engine.proc.killed)
+
def test_a_silent_engine_is_ended_not_waited_for(self):
self.engine.silence_s = 0.3
self.engine.script = [] # the engine never answers
diff --git a/src/core/conversation_file.cpp b/src/core/conversation_file.cpp
index 92dc73f06..ab1ba2c1a 100644
--- a/src/core/conversation_file.cpp
+++ b/src/core/conversation_file.cpp
@@ -47,24 +47,15 @@ constexpr char kMagic[8] = {'S', 'T', 'R', 'S', 'E', 'S', 'S', '\x01'};
constexpr char kEnd[8] = {'S', 'T', 'R', 'S', 'E', 'N', 'D', '\x01'};
constexpr uint32_t kVersion = 1;
constexpr size_t kHeader = 64, kTrailer = 16;
-constexpr uint64_t kProgressEvery = 256ull << 20;
-// Progress for a large transfer: after a block when a second has passed since the last report, and always at a
-// 256 MiB boundary - so a slow disk still reports (and beats the engine's watchdog) once per 16 MiB block.
+// Progress for a transfer: one report after every block that was handed to (or read from) the OS, whatever its size
+// - the last, partial block included - so a small file reports too, and each report follows real movement.
class Ticker {
public:
- explicit Ticker(const std::function<void(uint64_t, uint64_t)>& fn) : fn_(fn), last_(Clock::now()) {}
- void operator()(uint64_t before, uint64_t done, uint64_t total) {
- if (!fn_) return;
- const auto now = Clock::now();
- if (done / kProgressEvery == before / kProgressEvery && now - last_ < std::chrono::seconds(1)) return;
- last_ = now;
- fn_(done, total);
- }
+ explicit Ticker(const SessionProgress& fn) : fn_(fn) {}
+ void operator()(uint64_t done, uint64_t total) { if (fn_) fn_(done, total); }
private:
- using Clock = std::chrono::steady_clock;
- std::function<void(uint64_t, uint64_t)> fn_;
- Clock::time_point last_;
+ SessionProgress fn_;
};
SessionError errno_kind(int e) {
@@ -565,13 +556,16 @@ public:
const size_t padded = f_.direct() ? (used_ + kAlign - 1) / kAlign * kAlign : used_;
std::memset(buf_.get() + used_, 0, padded - used_);
bool ok = f_.write_all(buf_.get(), padded);
+ if (ok && used_ && progress) (*progress)(total_, expected); // the last, partial block
ok = ok && (padded == used_ || f_.truncate(total_));
+ if (ok && durable && phase) phase("flush", total_);
if (ok && durable && flush_fault) { fail_with(flush_fault); ok = false; }
ok = ok && (!durable || f_.sync());
ok = f_.close() && ok;
return ok;
}
std::optional<Ticker> progress;
+ SessionPhase phase;
uint64_t expected = 0;
int write_fault = 0, flush_fault = 0; // tests: errno values injected at the first block write / the file flush
private:
@@ -580,7 +574,7 @@ private:
if (write_fault) { fail_with(write_fault); return false; }
if (!f_.write_all(buf_.get(), used_)) return false;
used_ = 0;
- if (progress) (*progress)(total_ - kBlock, total_, expected);
+ if (progress) (*progress)(total_, expected);
return true;
}
Aligned buf_;
@@ -622,7 +616,7 @@ private:
}
const uint64_t before = total_;
total_ += have_;
- if (progress) (*progress)(before, total_, expected);
+ if (progress && total_ > before) (*progress)(total_, expected);
return have_ > 0;
}
Aligned buf_;
@@ -1068,7 +1062,9 @@ bool write_impl(const std::string& path, const SavedConversation& image, const s
FileSink f(raw);
if (!f.ok()) { st.error = SessionError::memory; error = "session file: " + f.error(); return false; }
if (opt.progress) f.progress.emplace(opt.progress);
+ f.phase = opt.phase;
f.expected = total;
+ if (f.progress) (*f.progress)(0, total); // the temporary file exists: the transfer starts
const std::function<int(const char*)>* fault = opt.fault ? &opt.fault : nullptr;
f.write_fault = injected(fault, "write");
f.flush_fault = injected(fault, "file_flush");
@@ -1091,10 +1087,13 @@ bool write_impl(const std::string& path, const SavedConversation& image, const s
why = out.read_failed ? "K/V source read" + (out.read_error.empty() ? std::string() : ": " + out.read_error)
: f.error();
st.error = out.read_failed ? SessionError::io : f.kind();
- } else if (pub.publish(why, opt.durable, st, fault)) {
- st.error = SessionError::none;
- bytes = (size_t) total;
- return true;
+ } else {
+ if (opt.phase) opt.phase("publish", total);
+ if (pub.publish(why, opt.durable, st, fault)) {
+ st.error = SessionError::none;
+ bytes = (size_t) total;
+ return true;
+ }
}
error = "session file: writing " + path + " failed" + (why.empty() ? std::string() : ": " + why);
if (st.published) error += " (the new file has already replaced the old one; its folder entry may not survive a power loss)";
@@ -1119,11 +1118,40 @@ bool write_guarded(const std::string& path, const SavedConversation& image, cons
} // namespace
std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vector<ConversationCheckpoint>& chain) {
+ const ConversationCheckpoint* deepest = session_deepest_checkpoint(chain);
+ if (!deepest) return {};
+ return {*deepest};
+}
+
+const ConversationCheckpoint* session_deepest_checkpoint(const std::vector<ConversationCheckpoint>& chain) {
const ConversationCheckpoint* deepest = nullptr;
for (const auto& c : chain)
if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;
- if (!deepest) return {};
- return {*deepest};
+ return deepest;
+}
+
+uint64_t session_save_peak_bytes(const ConversationCheckpoint* deepest, const SessionSaveLive& live) {
+ uint64_t n = sat_add(kBlock, uint64_t(1) << 20); // write buffer, small vectors
+ if (deepest) n = sat_add(n, sat_mul(2, deepest->bytes())); // the list and the image's copy
+ n = sat_add(n, live.state_bytes); // the live running state
+ n = sat_add(n, sat_mul(live.tokens, sizeof(int32_t))); // its token list
+ n = sat_add(n, sat_mul(live.images, sizeof(ConversationImageKey))); // its images
+ n = sat_add(n, sat_mul(live.kv_layers, sizeof(SessionKvSource) + 256)); // the K/V source directory
+ return n;
+}
+
+bool session_save_checkpoints(const std::vector<ConversationCheckpoint>& chain, const SessionSaveLive& live,
+ const std::function<bool(uint64_t need_bytes, std::string& why)>& admit,
+ std::vector<ConversationCheckpoint>& out, std::string& why) {
+ out.clear();
+ const ConversationCheckpoint* deepest = session_deepest_checkpoint(chain);
+ if (admit && !admit(session_save_peak_bytes(deepest, live), why)) return false;
+ if (deepest) out.push_back(*deepest);
+ return true;
+}
+
+int64_t session_phase_limit_s(uint64_t bytes) {
+ return std::min<int64_t>(3600, 60 + (int64_t) std::min<uint64_t>(bytes >> 22, 3600));
}
bool session_file_write(const std::string& path, const SavedConversation& meta, const std::vector<SessionKvSource>& kv,
@@ -1159,6 +1187,9 @@ bool read_impl(const std::string& path, const SessionFileIdentity& id, SavedConv
}
FileSource f(raw);
if (!f.ok()) { st.error = SessionError::memory; error = "session file: " + f.error(); return false; }
+ // installed before the first block (the header's) is read: every block reports, the first one included
+ if (limits.progress) f.progress.emplace(limits.progress);
+ f.expected = size;
uint8_t h[kHeader];
if (!f.read(h, kHeader)) { st.error = f.kind(); error = "session file: header read error: " + f.error(); return false; }
uint32_t version = 0, hsize = 0;
@@ -1185,8 +1216,6 @@ bool read_impl(const std::string& path, const SessionFileIdentity& id, SavedConv
return false;
}
}
- if (limits.progress) f.progress.emplace(limits.progress);
- f.expected = size;
SavedConversation parsed;
In in{&f, SessionHasher(0), payload, error, limits};
if (!get_payload(in, parsed)) { st.error = in.kind; return false; }
diff --git a/src/core/conversation_file_test.cpp b/src/core/conversation_file_test.cpp
index 4503035c9..fa725d757 100644
--- a/src/core/conversation_file_test.cpp
+++ b/src/core/conversation_file_test.cpp
@@ -12,11 +12,14 @@
#include <filesystem>
#include <fstream>
#include <string>
+#include <new>
#include <utility>
#include <vector>
#ifndef _WIN32
+#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/types.h>
+#include <sys/wait.h>
#include <unistd.h>
#endif
@@ -202,6 +205,8 @@ int main() {
}
// buffered I/O (the path taken where direct I/O is refused or unavailable) writes and reads the same bytes
{
+ const char* inherited = std::getenv("STRATA_SESSION_BUFFERED");
+ const std::string kept = inherited ? inherited : "";
set_env("STRATA_SESSION_BUFFERED", "1");
const fs::path p = dir / "buffered.bin";
check(session_file_write(p.string(), original, id, written, error), "buffered write");
@@ -209,7 +214,7 @@ int main() {
SavedConversation back;
size_t read = 0;
check(session_file_read(p.string(), id, back, read, error) && same(original, back), "buffered read");
- set_env("STRATA_SESSION_BUFFERED", nullptr);
+ set_env("STRATA_SESSION_BUFFERED", inherited ? kept.c_str() : nullptr); // the caller's choice again
}
const std::vector<char> image = slurp(good);
@@ -291,19 +296,22 @@ int main() {
uint64_t f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, f6 = 0, f7 = 0, f8 = 0;
const std::vector<SessionModelFile> both = {{"a", m1.string()}, {"b", m2.string()}};
check(session_model_fingerprint(both, f1, error), "fingerprint ok");
- check(session_model_fingerprint({{"a", m1.string()}}, f2, error), "fingerprint subset ok");
- check(session_model_fingerprint({{"b", m1.string()}, {"a", m2.string()}}, f5, error), "fingerprint roles ok");
+ const std::vector<SessionModelFile> subset = {{"a", m1.string()}};
+ const std::vector<SessionModelFile> roles = {{"b", m1.string()}, {"a", m2.string()}};
+ check(session_model_fingerprint(subset, f2, error), "fingerprint subset ok");
+ check(session_model_fingerprint(roles, f5, error), "fingerprint roles ok");
check(f1 != f5, "fingerprint follows the role each file plays");
// a moved folder: same roles, same bytes, other paths
const fs::path moved = dir / "moved";
fs::create_directories(moved);
fs::copy_file(m1, moved / "m1.bin"); fs::copy_file(m2, moved / "m2.bin");
- check(session_model_fingerprint({{"a", (moved / "m1.bin").string()}, {"b", (moved / "m2.bin").string()}}, f6,
- error) && f6 == f1, "fingerprint does not follow the folder");
+ const std::vector<SessionModelFile> moved_list = {{"a", (moved / "m1.bin").string()}, {"b", (moved / "m2.bin").string()}};
+ check(session_model_fingerprint(moved_list, f6, error) && f6 == f1, "fingerprint does not follow the folder");
// an optional input that is absent is recorded, not an error; a present one changes the fingerprint
- check(session_model_fingerprint({{"a", m1.string()}, {"b", m2.string()}, {"c", (dir / "nothere").string(), true}},
- f7, error), "absent optional input ok");
- check(session_model_fingerprint({{"a", m1.string()}, {"b", m2.string()}, {"c", m2.string(), true}}, f8, error) &&
+ const std::vector<SessionModelFile> absent = {{"a", m1.string()}, {"b", m2.string()}, {"c", (dir / "nothere").string(), true}};
+ const std::vector<SessionModelFile> present = {{"a", m1.string()}, {"b", m2.string()}, {"c", m2.string(), true}};
+ check(session_model_fingerprint(absent, f7, error), "absent optional input ok");
+ check(session_model_fingerprint(present, f8, error) &&
f7 != f8 && f7 != f1, "optional input presence enters the fingerprint");
auto d = slurp(m1); d[10] = 'z'; spit(m1, d);
check(session_model_fingerprint(both, f3, error), "fingerprint after edit ok");
@@ -562,6 +570,128 @@ int main() {
std::string(session_error_name(SessionError::invalid)) == "invalid" &&
std::string(session_error_name(SessionError::io)) == "io", "status: protocol names");
}
+ // B: progress after every block, the last partial one included (a file below 16 MiB reports too), and the
+ // blocking steps announced before they start
+ {
+ const fs::path p = dir / "progress.bin";
+ std::vector<std::pair<uint64_t, uint64_t>> seen;
+ std::vector<std::string> phases;
+ SessionWriteOptions opt;
+ opt.progress = [&](uint64_t d, uint64_t t) { seen.push_back({d, t}); };
+ opt.phase = [&](const char* ph, uint64_t b) { phases.push_back(std::string(ph) + ":" + std::to_string(b)); };
+ // a file below one block (the sample without its K/V layers) reports too: at the start and its one block
+ SavedConversation small = original;
+ small.kv.clear();
+ check(session_file_write(p.string(), small, id, written, error, opt), "progress: small write");
+ check(written > 0 && written < (16u << 20), "progress: the small file is below one block");
+ check(seen.size() == 2 && seen[0] == std::make_pair(uint64_t(0), uint64_t(written)) &&
+ seen[1] == std::make_pair(uint64_t(written), uint64_t(written)), "progress: start and the partial block");
+ check(phases.size() == 2 && phases[0] == "flush:" + std::to_string(written) &&
+ phases[1] == "publish:" + std::to_string(written), "progress: flush and publish announced, in order");
+ opt.durable = false;
+ phases.clear();
+ check(session_file_write(p.string(), small, id, written, error, opt) && phases.size() == 1 &&
+ phases[0].rfind("publish:", 0) == 0, "progress: no flush step announced without a flush");
+ // a read reports every block, the first (the header's) included
+ seen.clear();
+ SessionReadLimits l;
+ l.progress = [&](uint64_t d, uint64_t t) { seen.push_back({d, t}); };
+ SavedConversation back;
+ size_t n = 0;
+ check(session_file_read(p.string(), id, back, n, error, l) && seen.size() == 1 &&
+ seen[0] == std::make_pair(uint64_t(n), uint64_t(n)), "progress: a small read reports its one block");
+ // the fixed sample: one full block and a partial one, both reported on write and on read
+ seen.clear();
+ opt.durable = true;
+ check(session_file_write(p.string(), original, id, written, error, opt) && written > (16u << 20) &&
+ written < (32u << 20), "progress: sample write");
+ check(seen.size() == 3 && seen[1].first == (16u << 20) && seen[2].first == written,
+ "progress: the sample's full block and its partial last block");
+ seen.clear();
+ check(session_file_read(p.string(), id, back, n, error, l) && seen.size() == 2 &&
+ seen[0].first == (16u << 20) && seen[1].first == n, "progress: the sample's read reports both blocks");
+ // a multi-block streamed write: 16 MiB blocks then the partial one, never more than a block apart
+ SavedConversation meta = original;
+ meta.kv.clear();
+ std::vector<SessionKvSource> big(1);
+ big[0].sizes = {(40u << 20) + 123, 0, 0, 0, 0};
+ big[0].read = [](size_t, size_t, void* d, size_t c) { std::memset(d, 0x5a, c); return true; };
+ seen.clear();
+ opt.durable = true;
+ check(session_file_write(p.string(), meta, big, id, written, error, opt), "progress: 40 MiB write");
+ bool steps = seen.size() == 4 && seen.front().first == 0 && seen.back().first == written;
+ for (size_t i = 1; i < seen.size(); ++i)
+ steps = steps && seen[i].first > seen[i - 1].first && seen[i].first - seen[i - 1].first <= (16u << 20);
+ check(steps, "progress: every block reported, at most 16 MiB apart, the last one at the end");
+ // the allowance of a blocking step: bounded, growing with its size
+ check(session_phase_limit_s(0) == 60 && session_phase_limit_s(1198691396) == 60 + (1198691396 >> 22) &&
+ session_phase_limit_s(UINT64_MAX) == 3600, "phase limit: 60 s + 1 s per 4 MiB, at most an hour");
+ }
+ // A: the SAVE's RAM preflight comes BEFORE the checkpoint is copied
+ {
+ std::vector<ConversationCheckpoint> chain;
+ chain.push_back(checkpoint(10, 2));
+ chain.push_back(checkpoint(700, 3));
+ chain.back().gdn.assign(8u << 20, 0x11); // the deepest: an 8 MiB running state
+ const auto before = chain;
+ SessionSaveLive live;
+ live.state_bytes = 5000; live.tokens = 1000; live.images = 1; live.kv_layers = 13;
+ check(session_deepest_checkpoint(chain) == &chain[1], "save: deepest chosen by reference");
+ const uint64_t need = session_save_peak_bytes(&chain[1], live);
+ check(need >= 2 * (uint64_t) chain[1].bytes() + 5000 + 4000 + (16u << 20) &&
+ need <= 2 * (uint64_t) chain[1].bytes() + 5000 + 4000 + (18u << 20),
+ "save: the peak counts two checkpoint copies, the live state, tokens and the buffer");
+ SessionSaveLive huge = live;
+ huge.state_bytes = UINT64_MAX;
+ check(session_save_peak_bytes(&chain[1], huge) == UINT64_MAX, "save: the peak saturates");
+ std::vector<ConversationCheckpoint> out(1);
+ std::string why;
+ uint64_t asked = 0;
+ bool empty_when_asked = false;
+ const auto refuse = [&](uint64_t n, std::string& w) { asked = n; empty_when_asked = out.empty(); w = "low RAM"; return false; };
+ check(!session_save_checkpoints(chain, live, refuse, out, why) && why == "low RAM" && asked == need,
+ "save: the preflight is asked for the peak and can refuse");
+ check(empty_when_asked && out.empty(), "save: refused before any copy (nothing copied)");
+ bool same_chain = chain.size() == before.size();
+ for (size_t i = 0; same_chain && i < chain.size(); ++i) same_chain = same_checkpoint(chain[i], before[i]);
+ check(same_chain, "save: a refusal leaves the live checkpoints untouched");
+ const auto agree = [&](uint64_t, std::string&) { return true; };
+ check(session_save_checkpoints(chain, live, agree, out, why) && out.size() == 1 &&
+ same_checkpoint(out[0], chain[1]), "save: admitted, the deepest checkpoint is copied");
+ check(session_save_checkpoints({}, live, agree, out, why) && out.empty(), "save: no checkpoints, none copied");
+#if defined(__linux__) && !defined(__SANITIZE_ADDRESS__) && !defined(STRATA_NO_RLIMIT_TEST)
+ // under a real address-space limit that cannot hold one more copy: the refusal comes first, no bad_alloc;
+ // and the same limit with an admitting preflight does fail at the copy (the test can see the difference)
+ std::vector<ConversationCheckpoint> fat(1);
+ fat[0].ids = {1, 2, 3};
+ fat[0].gdn.assign(256u << 20, 0x22);
+ const fs::path old_file = dir / "old-session.bin";
+ spit(old_file, std::vector<char>(9, 'o'));
+ std::fflush(nullptr);
+ const pid_t pid = ::fork();
+ if (pid == 0) {
+ long pages = 0, rss = 0;
+ if (FILE* f = std::fopen("/proc/self/statm", "r")) { if (std::fscanf(f, "%ld %ld", &pages, &rss) != 2) pages = 0; std::fclose(f); }
+ struct rlimit rl {};
+ rl.rlim_cur = rl.rlim_max = (rlim_t) pages * (rlim_t) ::sysconf(_SC_PAGESIZE) + (64u << 20);
+ if (pages <= 0 || ::setrlimit(RLIMIT_AS, &rl) != 0) ::_exit(10);
+ std::vector<ConversationCheckpoint> o2;
+ std::string w;
+ const auto low = [](uint64_t n, std::string& m) { m = "need " + std::to_string(n); return false; };
+ bool refused = false;
+ try { refused = !session_save_checkpoints(fat, live, low, o2, w) && o2.empty(); } catch (...) { ::_exit(11); }
+ if (!refused) ::_exit(12);
+ try { session_save_checkpoints(fat, live, agree, o2, w); } catch (const std::bad_alloc&) { ::_exit(0); }
+ ::_exit(13); // the copy fitted: the limit did not bite, the test proves nothing
+ }
+ int status = 0;
+ check(pid > 0 && ::waitpid(pid, &status, 0) == pid, "save: low-memory child ran");
+ check(WIFEXITED(status) && WEXITSTATUS(status) == 0,
+ "save: under a low address-space limit the preflight refuses before the copy (an admitted copy fails)");
+ check(fat[0].gdn.size() == (256u << 20) && fat[0].gdn[12345] == 0x22 &&
+ slurp(old_file) == std::vector<char>(9, 'o'), "save: live state and the old file intact");
+#endif
+ }
// R6: the folder the free-space query is asked about
{
check(session_free_space_dir("\\\\server\\share\\sessions\\chat.bin", true) == "\\\\server\\share\\sessions\\",
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index fe92c092e..e86942d44 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -1255,13 +1255,6 @@ private:
std::thread th_; // last: started once the members above exist
};
-int argmax(const std::vector<float>& v) {
- int best = 0;
- for (size_t i = 1; i < v.size(); ++i)
- if (v[i] > v[best]) best = (int) i;
- return best;
-}
-
// ---- --serve's conversation cache. A chat or an agent sends the whole conversation again with every request, and
// reading it again is what made a long session wait minutes for every turn. What a sequence leaves behind splits in
// two, and only one half needs copying:
@@ -6116,7 +6109,8 @@ int main(int argc, char** argv) {
// that change what the saved bytes mean - the rope (K is cached post-RoPE), the loaded control vector, the
// K/V format and the arithmetic switches. Sampling, seeds, draft tuning and the expert tier are not in it.
std::optional<uint64_t> model_fp, config_fp;
- auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e) -> bool {
+ auto session_identity = [&](strata::core::SessionFileIdentity& id, std::string& e,
+ const std::function<void()>& next_file) -> bool {
if (!model_fp) {
// what the loaders actually resolved: the CLI inputs, the pack's files and - from the expert source
// itself - every file its experts were read from (native_experts.txt can name GGUFs per layer/role)
@@ -6142,7 +6136,9 @@ int main(int argc, char** argv) {
files.push_back({"mtp draft_vocab.bin", o.mtp + "/draft_vocab.bin", true});
}
uint64_t fp = 0;
- if (!strata::core::session_model_fingerprint(files, fp, e, [] { strata::core::progress_beat(); }))
+ // each file is one blocking read of at most 2 MiB (head and tail): announced before it starts
+ if (next_file) next_file();
+ if (!strata::core::session_model_fingerprint(files, fp, e, next_file))
return false;
model_fp = fp;
}
@@ -6998,6 +6994,8 @@ int main(int argc, char** argv) {
const uint64_t b = p.beats.load();
if (!p.busy.load() || b != last) { last = b; ticks_at = p.ticks.load(); since = now; continue; }
if (now - since < std::chrono::seconds(limit)) continue;
+ // a blocking step's explicit allowance (session files): still within it, not yet stuck
+ if (strata::core::progress_now_ms() < p.allow_until_ms.load()) continue;
std::fprintf(stderr, "strata serve: no progress for %d s during a request (%s) - stopping "
"the engine so the server starts it again (issue #29)\n",
limit, stage_text().c_str());
@@ -7567,16 +7565,29 @@ int main(int argc, char** argv) {
if (line == "QUIT") break;
// the watchdog watches a request from here until this iteration ends, whichever way it ends
struct BusyScope {
- BusyScope() { strata::core::progress().busy.store(true); strata::core::progress_at("request"); }
- ~BusyScope() { strata::core::progress().busy.store(false); strata::core::progress_at("idle"); }
+ BusyScope() {
+ strata::core::progress().allow_until_ms.store(0);
+ strata::core::progress().busy.store(true);
+ strata::core::progress_at("request");
+ }
+ ~BusyScope() {
+ strata::core::progress().busy.store(false);
+ strata::core::progress().allow_until_ms.store(0);
+ strata::core::progress_at("idle");
+ }
} busy_scope;
stop_req.store(false); // a STOP that arrived between requests is stale
err.clear();
// Disk sessions: SAVE <path> | RESTORE <path>, between requests (the path runs to the end of the line,
// UTF-8). The file holds what a parked conversation holds (conversation_file.hpp). Answers: SAVED /
- // RESTORED <tokens> <bytes> <ms>; ERR <reason> for a refusal that left the session as it was;
- // FATAL <reason> (and the engine exits) for a restore transfer that failed after the device state was
- // touched. While a large file moves, SESSION <done> <total> lines show it is moving (and beat the watchdog).
+ // RESTORED <tokens> <bytes> <ms>; SERR <invalid|storage|memory|io> <published 0|1> <reason> for a refusal
+ // or failure that leaves the engine in step (the live session as it was, unless published=1 says the new
+ // file already replaced the old one); FATAL <reason> (and the engine exits) for a restore transfer that
+ // failed after the device state was touched. On the way: SESSION <done> <total> after every block of
+ // the file moved (at most 16 MiB), and SWAIT <phase> <seconds> before a step that blocks in one call
+ // (fingerprint file, state capture, file flush, rename + folder flush, validation, device transfer):
+ // that step is allowed <seconds> (session_phase_limit_s) by the watchdog and by the server, no more.
+ // (A verifier commit that fails before the command still answers ERR and exits, as for a request.)
if (line.rfind("SAVE ", 0) == 0 || line.rfind("RESTORE ", 0) == 0) {
const bool save = line[0] == 'S';
const std::string path = line.substr(save ? 5 : 8);
@@ -7595,10 +7606,18 @@ int main(int argc, char** argv) {
auto moving = [&](uint64_t done, uint64_t total) {
strata::core::progress_at(save ? "writing a session file, MiB" : "reading a session file, MiB",
(int64_t) (done >> 20));
- strata::core::progress_beat();
+ strata::core::progress_allow(0); // a block moved: the ordinary watchdog limit again, and a beat
std::printf("SESSION %llu %llu\n", (unsigned long long) done, (unsigned long long) total);
std::fflush(stdout);
};
+ // a step that blocks in one call: its explicit allowance, on both sides, announced before it starts
+ auto blocking = [&](const char* phase, uint64_t bytes) {
+ const int64_t s = strata::core::session_phase_limit_s(bytes);
+ strata::core::progress_at(phase);
+ strata::core::progress_allow(s);
+ std::printf("SWAIT %s %lld\n", phase, (long long) s);
+ std::fflush(stdout);
+ };
strata::core::progress_at(save ? "saving a session" : "restoring a session");
if (path.empty()) { refuse("missing path"); continue; }
if (!stages.empty() || multi_gpu) { refuse("session files do not support --layer-split"); continue; }
@@ -7610,7 +7629,10 @@ int main(int argc, char** argv) {
}
strata::core::SessionFileIdentity id;
try {
- if (!session_identity(id, err)) { refuse(err, strata::core::SessionError::io); continue; }
+ if (!session_identity(id, err, [&] { blocking("fingerprint", 2u << 20); })) {
+ refuse(err, strata::core::SessionError::io);
+ continue;
+ }
} catch (const std::bad_alloc&) {
refuse("session identity: out of memory", strata::core::SessionError::memory);
continue;
@@ -7623,34 +7645,50 @@ int main(int argc, char** argv) {
size_t bytes = 0, kept = 0;
double capture_ms = 0;
try {
- // only the deepest checkpoint goes to disk (the next turn's resume point); the K/V is streamed
- // from the authoritative pools straight into the file, without a full host capture
- const auto disk_checks = strata::core::session_checkpoints_to_save(checks);
- kept = disk_checks.size();
- // RAM PREFLIGHT for the save (not a reservation): the copied running state, the checkpoint
- // copies (this list and the one in `meta`) and the 16 MiB write buffer, above the parking floor
+ // RAM PREFLIGHT for the save (not a reservation), BEFORE anything is copied: the deepest
+ // checkpoint is chosen by reference, and the copies it will take (the list below and the one
+ // in `meta`), the copied live running state with its tokens and images, the K/V source
+ // directory and the 16 MiB write buffer are asked for above the parking floor. Only the
+ // deepest checkpoint goes to disk (the next turn's resume point); the K/V is streamed from
+ // the authoritative pools straight into the file, without a full host capture.
+ strata::core::SessionSaveLive sl;
{
- uint64_t need = (uint64_t) (17u << 20) + (uint64_t) live.size() * sizeof(int32_t);
strata::core::ConversationStateSizes z;
std::string why;
- if (strata::core::conversation_session_sizes(g, ss, z, why))
- need += z.gdn + z.ple + (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0) *
- (z.tail + z.dead + z.block_pos);
- for (const auto& c : disk_checks) need += 2 * (uint64_t) c.bytes();
- const uint64_t floor = (uint64_t) o.conversation_cache_min_free_mib << 20;
- const auto avail = strata::core::conversation_available_memory();
- if (!strata::core::conversation_memory_admit(avail, need, floor)) {
- refuse("not enough RAM to save the session (" + 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)"),
- strata::core::SessionError::memory);
- continue;
+ uint64_t state = UINT64_MAX; // unknown sizes: the preflight refuses rather than guesses
+ if (strata::core::conversation_session_sizes(g, ss, z, why)) {
+ const uint64_t q = (uint64_t) std::max<int64_t>(ss.qsa_alloc, 0);
+ const uint64_t per = (uint64_t) z.tail + z.dead + z.block_pos;
+ if (q == 0 || per <= (UINT64_MAX - z.gdn - z.ple) / q) state = z.gdn + z.ple + q * per;
}
+ sl.state_bytes = state;
+ sl.tokens = live.size();
+ sl.images = live_imgs.size();
+ 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;
+ auto admit = [&](uint64_t need, std::string& why) {
+ const auto avail = strata::core::conversation_available_memory();
+ 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)");
+ return false;
+ };
+ std::vector<ConvCheckpoint> disk_checks;
+ std::string why;
+ if (!strata::core::session_save_checkpoints(checks, sl, admit, disk_checks, why)) {
+ refuse(why, strata::core::SessionError::memory);
+ continue;
+ }
+ kept = disk_checks.size();
const strata::core::ConversationView view{live, live_imgs, disk_checks, cvec_cached};
strata::core::SavedConversation meta;
std::vector<strata::core::SessionKvSource> sources;
+ // the live running state comes off the device in one synchronous copy
+ blocking("capture", sl.state_bytes == UINT64_MAX ? 0 : sl.state_bytes);
if (!strata::core::conversation_snapshot_sources(meta, sources, view, ss, g, mtp.kv_state(),
err)) {
refuse(err, strata::core::SessionError::io);
@@ -7660,6 +7698,7 @@ int main(int argc, char** argv) {
strata::core::SessionWriteOptions wo;
wo.min_free_bytes = (uint64_t) o.session_min_free_mib << 20;
wo.progress = moving;
+ wo.phase = blocking;
strata::core::SessionStatus st;
if (!strata::core::session_file_write(path, meta, sources, id, bytes, err, wo, &st)) {
refuse(err, st.error, st.published);
@@ -7711,12 +7750,15 @@ int main(int argc, char** argv) {
}
const double read_ms = ms();
// the whole image against this engine, still without any device write
+ blocking("validate", bytes);
if (!strata::core::conversation_snapshot_validate(image, ss, g, mtp.kv_state(), err)) {
refuse(err);
continue;
}
conversations.take_reuse(); // retained K/V described the outgoing session
live_ok = false;
+ // host -> device in synchronous copies of the whole state: one bounded allowance
+ blocking("transfer", bytes);
if (strata::core::conversation_snapshot_restore(image, ss, g, mtp.kv_state(), err) !=
strata::core::ConversationRestore::restored) {
// validated above: a failure here is a transfer failure, after device writes began - never