leviath_runtime/pipeline/persist.rs
1//! Per-agent snapshot writing and interaction-status reflection.
2
3use super::*;
4
5// ─── Persistence (per-agent snapshot writing) ────────────────────────────────
6
7/// How long an agent may go without a snapshot before one is written purely to
8/// refresh `updated_at`.
9///
10/// The watermark below debounces on *progress*, which means a run that is busy
11/// but not progressing (one long inference, or a genuinely wedged one) writes
12/// nothing at all. Observers then cannot tell "working" from "dead", because
13/// `updated_at` looks equally old in both cases. A periodic beat makes a stale
14/// timestamp mean something.
15pub(crate) const PERSIST_HEARTBEAT_SECS: i64 = 30;
16
17/// Longest log line the event broadcast carries; the on-disk stage logs keep
18/// the full line. 8 KB shows any tool banner or error whole while keeping the
19/// (never-shrinking) broadcast ring's worst-case floor at ring-size x this.
20pub(crate) const BROADCAST_LOG_LINE_MAX_BYTES: usize = 8 * 1024;
21
22/// Clone `line` for the event broadcast, truncated to
23/// [`BROADCAST_LOG_LINE_MAX_BYTES`] on a char boundary with a marker so a
24/// reader knows to fetch the stage log for the rest.
25fn truncate_log_line(line: &str) -> String {
26 if line.len() <= BROADCAST_LOG_LINE_MAX_BYTES {
27 return line.to_string();
28 }
29 let cut = leviath_core::text::floor_char_boundary(line, BROADCAST_LOG_LINE_MAX_BYTES);
30 format!(
31 "{} [truncated {} bytes]",
32 line.split_at(cut).0,
33 line.len() - cut
34 )
35}
36
37/// Debounce watermark: the (iteration, stage index, status) last persisted for an
38/// agent. A snapshot is written only when one of these changes, so the world
39/// writes on meaningful progress rather than every tick. `None` until the first
40/// snapshot, so a freshly-spawned agent is always written once.
41#[derive(Component, Default)]
42pub struct PersistWatermark {
43 last: Option<(usize, usize, leviath_core::run_meta::RunStatus)>,
44 /// When the last snapshot was written, for the heartbeat above.
45 last_written_at: Option<i64>,
46 /// When the watermark itself last changed - that is, when the agent last
47 /// actually moved.
48 ///
49 /// `last_written_at` cannot answer that: the heartbeat advances it whether
50 /// or not anything happened, which is the whole point of the heartbeat and
51 /// exactly why `meta.json`'s `updated_at` is not evidence of progress. Issue
52 /// #184 was reported on the strength of a fresh `updated_at`, so this is the
53 /// timestamp `lev ps` ages its rows against.
54 last_progress_at: Option<i64>,
55 /// The taint audit already on disk, as `(stage index, event count)`.
56 ///
57 /// The audit file is only rewritten when the gate recorded a new event.
58 /// Without it every snapshot re-serialized the whole (append-only) log,
59 /// an O(events) allocation per tick that grew with the run.
60 last_taint: Option<(usize, usize)>,
61}
62
63impl PersistWatermark {
64 /// Unix seconds when this agent last made progress (iteration, stage, or
65 /// status changed). `None` before the first snapshot.
66 pub fn last_progress_at(&self) -> Option<i64> {
67 self.last_progress_at
68 }
69
70 /// The run status the last dispatched snapshot carried, if any - the proof
71 /// that a given status has reached the persistence lane. Unloading
72 /// decisions key on this: an entity may only be slimmed or paged out once
73 /// the state being dropped is known to be on its way to disk.
74 pub(crate) fn persisted_status(&self) -> Option<leviath_core::run_meta::RunStatus> {
75 self.last.as_ref().map(|(_, _, status)| status.clone())
76 }
77
78 /// Move both stamps back to `at`, so a test can reach the heartbeat window
79 /// without sleeping through it.
80 #[cfg(test)]
81 pub(crate) fn backdate(&mut self, at: i64) {
82 self.last_written_at = Some(at);
83 self.last_progress_at = Some(at);
84 }
85
86 /// Stamp the watermark as though a snapshot with `status` was dispatched,
87 /// so unload tests can drive [`Self::persisted_status`] without running the
88 /// full persistence schedule.
89 #[cfg(test)]
90 pub(crate) fn stamp_status(&mut self, status: leviath_core::run_meta::RunStatus) {
91 self.last = Some((0, 0, status));
92 }
93}
94
95/// The sending end of the persistence I/O lane (the receiving end is drained by
96/// `persistence_bridge::persistence_worker`).
97#[derive(Resource)]
98pub struct PersistenceStage(pub UnboundedSender<PersistMsg>);
99
100/// What `reflect_interaction_status` selects.
101///
102/// `&'static` is bevy's `WorldQuery` convention, not a claim about
103/// lifetimes: the borrow is bound when the query is fetched.
104type ReflectInteractionStatusQuery = (
105 Entity,
106 &'static mut AgentState,
107 Option<&'static AwaitingInteraction>,
108);
109
110/// Persistence-dispatch system: for each agent carrying run metadata whose
111/// (iteration, stage, status) has changed since its last snapshot, build the
112/// `meta.json` + `context.json` value snapshot and hand it to the persistence
113/// lane. Fire-and-forget - no result to collect; the single-worker lane keeps a
114/// given agent's writes ordered. Agents without [`RunMetadata`] aren't persisted.
115/// Interaction-status reflection system: mirror the shared [`InteractionHub`]'s
116/// open requests into agent status so a blocked agent shows as `Waiting` (and
117/// the dashboard / `lev ps` surface its prompt) instead of a silent `Active`.
118///
119/// An agent's `ask_user_*` / tool-approval / plan-approval call blocks deep in
120/// the async tool lane, invisible to the ECS - which otherwise leaves the agent
121/// `Active` with meta.json written `running`, so the dashboard (gated on
122/// `WaitingInput`) never shows the prompt and the run looks frozen. This system
123/// closes that gap: an agent whose id has an open hub request flips
124/// `Active → Waiting` (tagged [`AwaitingInteraction`]); when the request clears
125/// it flips back `Waiting → Active`. No-op when the world has no hub resource
126/// (test worlds).
127///
128/// Agents parked by the engine rather than by a prompt - fan-out parents
129/// ([`FanOutWaiting`]) and stages holding for sub-agents
130/// ([`WaitingForChildren`]) - are excluded. Their `Waiting` belongs to whoever
131/// set it, and the clearing arm below would otherwise walk them back to `Active`
132/// the moment an unrelated prompt of theirs resolved, un-parking a run whose
133/// children are still going.
134pub fn reflect_interaction_status(
135 hub: Option<Res<InteractionHub>>,
136 mut agents: Query<
137 ReflectInteractionStatusQuery,
138 (Without<FanOutWaiting>, Without<WaitingForChildren>),
139 >,
140 mut commands: Commands,
141) {
142 crate::tick_scope::clear();
143 let Some(hub) = hub else { return };
144 let pending: std::collections::HashSet<String> =
145 hub.pending().into_iter().map(|(id, _)| id).collect();
146 for (entity, mut state, marked) in agents.iter_mut() {
147 crate::tick_scope::enter(entity);
148 match (pending.contains(&state.agent_id), marked.is_some()) {
149 // Newly blocked on a prompt: surface it as Waiting.
150 (true, false) => {
151 if state.status == AgentStatus::Active {
152 state.status = AgentStatus::Waiting;
153 commands.entity(entity).insert(AwaitingInteraction);
154 }
155 }
156 // Request cleared (answered / cancelled): return to Active, unless
157 // the agent has since reached a terminal status.
158 (false, true) => {
159 commands.entity(entity).remove::<AwaitingInteraction>();
160 if state.status == AgentStatus::Waiting {
161 state.status = AgentStatus::Active;
162 }
163 }
164 _ => {}
165 }
166 }
167}
168
169/// Reconcile a [`StageLedger`]'s per-stage `status` + timestamps against the
170/// agent's current stage index and status.
171///
172/// The cursor stage takes the mapped agent status and is marked entered. Every
173/// other stage is judged on whether it has *ever* been entered, not on where it
174/// sits relative to the cursor: one the run has been in and left is `Complete`,
175/// one it has not is `Pending` while the run is live and
176/// [`Skipped`](leviath_core::run_meta::StageRunStatus::Skipped) once the run is
177/// over.
178///
179/// Position used to stand in for "has run", which is only true of a linear
180/// blueprint. A graph reaches its stages in whatever order its edges describe,
181/// so every branch the run went past without taking was filed as `Complete`
182/// with an empty `region_tokens` - and since that map is a snapshot, an empty
183/// one in the middle of the sequence made the next real stage appear to have
184/// written every region from nothing (#372).
185///
186/// `started_at`/`ended_at` are stamped once and never overwritten, so repeated
187/// calls are idempotent.
188pub(crate) fn reconcile_stage_ledger(
189 ledger: &mut StageLedger,
190 cursor_index: usize,
191 status: &AgentStatus,
192 now: i64,
193) {
194 use leviath_core::run_meta::StageRunStatus;
195 let active = crate::persistence::stage_status_from(status);
196 let run_is_over = matches!(
197 status,
198 AgentStatus::Complete | AgentStatus::Error { .. } | AgentStatus::Cancelled
199 );
200 for rec in ledger.0.iter_mut() {
201 if rec.index == cursor_index {
202 rec.entered = true;
203 if rec.started_at.is_none() {
204 rec.started_at = Some(now);
205 }
206 if active == StageRunStatus::Complete && rec.ended_at.is_none() {
207 rec.ended_at = Some(now);
208 }
209 rec.status = active.clone();
210 continue;
211 }
212 // Billed tokens count as evidence as well as the flag. Reconcile runs
213 // on the persist tick rather than on stage entry, so resting "did this
214 // run" entirely on having been observed as the cursor would report a
215 // stage that somehow slipped between two ticks as never entered - and
216 // calling a stage that did work `Skipped` is a worse error than the one
217 // being fixed. A stage with tokens against its name ran.
218 rec.entered |= rec.prompt_tokens > 0 || rec.completion_tokens > 0;
219 if !rec.entered {
220 rec.status = match run_is_over {
221 true => StageRunStatus::Skipped,
222 false => StageRunStatus::Pending,
223 };
224 continue;
225 }
226 // Entered earlier and not the current stage, so it has been left. A
227 // stage that loops back becomes the cursor again and is re-marked.
228 rec.status = StageRunStatus::Complete;
229 if rec.ended_at.is_none() {
230 rec.ended_at = Some(now);
231 }
232 }
233}
234
235/// What `dispatch_persistence` selects.
236///
237/// `&'static` is bevy's `WorldQuery` convention, not a claim about
238/// lifetimes: the borrow is bound when the query is fetched.
239type PersistenceQuery = (
240 Entity,
241 &'static RunMetadata,
242 &'static AgentState,
243 &'static ContextWindow,
244 &'static StageCursor,
245 &'static TokenTotals,
246 &'static mut PersistWatermark,
247 Option<&'static mut StageLedger>,
248 Option<&'static mut StageIoBuffer>,
249 Option<&'static crate::taint::TaintGate>,
250 Option<&'static crate::components::ParentRef>,
251 Option<&'static crate::components::SubAgentChildren>,
252 Option<&'static crate::fanout::FanOutWaiting>,
253 (
254 Option<&'static crate::interaction_points::AwaitingInteractionPoint>,
255 Option<&'static crate::interaction_points::InteractionPointCursor>,
256 Option<&'static crate::interaction_points::InteractionPointRounds>,
257 Option<&'static crate::persistence::RunOutcomeFlags>,
258 Option<&'static crate::persistence::FinalOutput>,
259 ),
260);
261
262/// Hand each agent's current state to the persistence lane, which writes it to
263/// disk off the schedule thread.
264///
265/// Coalescing lives here rather than in the lane: an agent whose digest has not
266/// changed since its last send is skipped, so a world full of idle runs costs
267/// nothing per tick.
268pub fn dispatch_persistence(
269 mut agents: Query<PersistenceQuery>,
270 stage: Res<PersistenceStage>,
271 hub: Option<Res<InteractionHub>>,
272 sink: Option<Res<crate::host::WorldEventSink>>,
273) {
274 crate::tick_scope::clear();
275 for (
276 entity,
277 md,
278 state,
279 window,
280 cursor,
281 totals,
282 mut watermark,
283 mut ledger,
284 buffer,
285 taint_gate,
286 parent_ref,
287 children,
288 fan_out_waiting,
289 (awaiting_point, ip_cursor, ip_rounds, outcome_flags, final_output),
290 ) in agents.iter_mut()
291 {
292 crate::tick_scope::enter(entity);
293 let now = chrono::Utc::now().timestamp();
294
295 // Reconcile the stage ledger every persist tick so status/timestamps track
296 // the agent regardless of whether the run-level watermark changed.
297 if let Some(ledger) = ledger.as_deref_mut() {
298 reconcile_stage_ledger(ledger, cursor.index, &state.status, now);
299 }
300
301 // Always flush any buffered per-stage output/log lines.
302 let (output_appends, log_appends) = match buffer {
303 Some(mut buf) => (
304 std::mem::take(&mut buf.output),
305 std::mem::take(&mut buf.logs),
306 ),
307 None => (Vec::new(), Vec::new()),
308 };
309 let has_appends = !output_appends.is_empty() || !log_appends.is_empty();
310
311 let status = crate::persistence::run_status_from(&state.status);
312 let current = (state.iteration, cursor.index, status);
313 let watermark_changed = watermark.last.as_ref() != Some(¤t);
314 // Beat even when nothing changed, so `updated_at` distinguishes a run
315 // that is slow from one that nothing is driving.
316 let due_for_heartbeat = watermark
317 .last_written_at
318 .is_none_or(|at| now.saturating_sub(at) >= PERSIST_HEARTBEAT_SECS);
319 if !watermark_changed && !has_appends && !due_for_heartbeat {
320 continue; // nothing meaningful changed, nothing buffered, beat not due
321 }
322
323 // Stream each buffered line to WS subscribers as a `Log` event (in
324 // addition to the disk append below). No-op in worlds without the sink
325 // (test / `lev run`); a zero-subscriber `send` error is ignored.
326 //
327 // Truncated for the broadcast only - the full line still reaches the
328 // stage log on disk. The ring retains every slot's strings until the
329 // slot is overwritten, so an assistant's whole multi-KB turn broadcast
330 // per line made the ring a multi-MB permanent floor after any busy run.
331 if let Some(sink) = &sink {
332 for (_idx, line) in output_appends.iter().chain(log_appends.iter()) {
333 // `Res<T>` derefs to `T` in bevy_ecs 0.19; it is not a tuple struct.
334 let _ = sink.0.send(crate::host::WorldEvent::Log {
335 run_id: md.run_id.clone(),
336 agent_id: state.agent_id.clone(),
337 line: truncate_log_line(line),
338 });
339 }
340 }
341
342 // Buffered lines with no real progress and no heartbeat due: journal
343 // just the lines. The full path below deep-clones the whole context
344 // window per snapshot, and tool activity buffers lines several times
345 // per iteration - snapshotting on each batch multiplied the lane's
346 // biggest allocation by the run's tool traffic for no new state.
347 if !watermark_changed && !due_for_heartbeat {
348 let _ = stage.0.send(PersistMsg::StageLines {
349 run_id: md.run_id.clone(),
350 output_appends,
351 log_appends,
352 });
353 continue;
354 }
355
356 if watermark_changed {
357 watermark.last = Some(current);
358 watermark.last_progress_at = Some(now);
359 }
360 watermark.last_written_at = Some(now);
361
362 // Tree links, for a deterministic restart-time rebuild of the graph.
363 let depth = parent_ref.map(|p| p.depth).unwrap_or(0);
364 let max_child_depth = children.map(|c| c.max_child_depth).unwrap_or(0);
365 let flags = outcome_flags.cloned().unwrap_or_default();
366 // Read the progress stamp *after* the update above, so a write that
367 // carried progress reports `now` and a heartbeat-only write reports
368 // whenever the run last moved. That difference is the whole signal: it is
369 // what lets an observer reading `meta.json` tell a slow run from a wedged
370 // one, which `updated_at` (which is `now` either way) cannot.
371 let meta = build_run_meta(
372 crate::persistence::RunMetaSources {
373 md,
374 state,
375 totals,
376 flags: &flags,
377 final_output,
378 },
379 crate::persistence::RunPosition {
380 stage_index: cursor.index,
381 now_secs: now,
382 last_progress_at: watermark.last_progress_at(),
383 depth,
384 max_child_depth,
385 },
386 );
387 let context = build_context_snapshot(window, &state.current_stage);
388 let stages = ledger.as_deref().map(|l| l.0.clone()).unwrap_or_default();
389 // Persist the taint gate's audit log (per-stage) when it gained events
390 // since the last write, so security decisions are inspectable after
391 // the fact. The log is append-only, so an unchanged (stage, count)
392 // means the file on disk is already current - re-serializing the whole
393 // log every heartbeat was an O(events) allocation that grew with the
394 // run.
395 let taint_audit = taint_gate
396 .filter(|g| !g.audit_log().is_empty())
397 .and_then(|g| {
398 let key = (cursor.index, g.audit_log().len());
399 if watermark.last_taint == Some(key) {
400 return None;
401 }
402 watermark.last_taint = Some(key);
403 Some((
404 cursor.index,
405 serde_json::to_string(g.audit_log())
406 .expect("GateEvent slice always serializes"),
407 ))
408 });
409 // A parent parked mid fan-out: persist its waiting state so the
410 // split/merge resumes after a restart (removed once it's no longer
411 // waiting - see the writer).
412 let fanout = fan_out_waiting
413 .map(|w| serde_json::to_string(&w.to_state()).expect("FanOutState always serializes"));
414 // An agent parked at a stage-boundary interaction point: persist the open
415 // point (cursor/round + the reviewed document) so a restart re-presents the
416 // same prompt rather than dropping it and re-inferring (issue #38). The
417 // document comes from the open request in the hub - which is present by the
418 // time `reflect_interaction_status` (running just before this system) has
419 // flipped the agent to `Waiting`. If the request isn't registered yet, skip
420 // this tick; the next persist captures it (removing any stale sidecar).
421 let interactions = awaiting_point.and_then(|_| {
422 let request = hub
423 .as_ref()?
424 .pending()
425 .into_iter()
426 .find(|(aid, req)| aid == &state.agent_id && req.id.contains("-point-"))?;
427 let ip_state = crate::interaction_points::InteractionPointState {
428 cursor: ip_cursor.map_or(0, |c| c.0),
429 round: ip_rounds.map_or(0, |r| r.0),
430 body: request.1.body.unwrap_or_default(),
431 };
432 Some(serde_json::to_string(&ip_state).expect("InteractionPointState always serializes"))
433 });
434 // Always carry the answer's bytes when the agent holds them; the
435 // persistence lane decides whether they still need writing.
436 //
437 // This used to be skipped here, keyed on a watermark advanced when the
438 // job was *built*. That assumed every job it built would be written,
439 // and the lane explicitly does not promise that: it coalesces queued
440 // snapshots per run and keeps only the newest. A run that finished
441 // inside one persistence window therefore had the job carrying the body
442 // dropped as superseded, while every later job carried `None` and still
443 // rewrote `meta.json` with the descriptor - leaving the descriptor and
444 // the sidecar permanently disagreeing, which `read_final_output` reads
445 // as "no answer" (issue #276).
446 //
447 // The skip itself was worth keeping - it stops a heartbeat rewriting a
448 // quarter-megabyte file every thirty seconds - so it moved to the lane,
449 // past the coalescing, where "did this get written" is a fact rather
450 // than an assumption. The cost here is one clone of the answer per
451 // snapshot, on a path that already deep-clones the whole context window.
452 let final_output_body = final_output.map(|o| o.0.content.clone());
453 let _ = stage.0.send(PersistMsg::Snapshot(Box::new(PersistJob {
454 run_id: md.run_id.clone(),
455 meta,
456 context,
457 stages,
458 output_appends,
459 log_appends,
460 taint_audit,
461 final_output: final_output_body,
462 fanout,
463 interactions,
464 })));
465 }
466}