Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

count deleted subagents spend in the title (#3121)

Sebastian Müller47c6b90d8af2
diff --git a/.changes/fix-rust-cost-followups.md b/.changes/fix-rust-cost-followups.md
new file mode 100644
index 0000000000..7591fb3611
--- /dev/null
+++ b/.changes/fix-rust-cost-followups.md
@@ -0,0 +1 @@
+- The chat title and the agents view now include the spend of deleted subagents, and both show the same number.
diff --git a/crates/pa-cli/tests/subagent_panel_nav_e2e.rs b/crates/pa-cli/tests/subagent_panel_nav_e2e.rs
index ac11aae46c..701d1a943c 100644
--- a/crates/pa-cli/tests/subagent_panel_nav_e2e.rs
+++ b/crates/pa-cli/tests/subagent_panel_nav_e2e.rs
@@ -170,6 +170,20 @@ fn write_fixture(
path
}
+/// One billed assistant turn appended to a fixture transcript: the
+/// usage-bearing row the own-usage fold reads.
+fn append_billed_turn(path: &Path, id: &str, input: u64, output: u64, cost: f64) {
+ let mut file = std::fs::OpenOptions::new()
+ .append(true)
+ .open(path)
+ .expect("open the fixture for its billed turn");
+ let _ = writeln!(
+ file,
+ "{{\"type\":\"message\",\"id\":\"{id}\",\"timestamp\":\"2026-09-29T00:00:02.100Z\",\"message\":{{\"role\":\"assistant\",\"provider\":\"prime-inference\",\"model\":\"internal/glm-5.3-fast\",\"content\":[{{\"type\":\"text\",\"text\":\"work complete\"}}],\"stopReason\":\"stop\",\"timestamp\":2100,\"usage\":{{\"input\":{input},\"output\":{output},\"cacheRead\":0,\"cacheWrite\":0,\"totalTokens\":{},\"cost\":{{\"input\":0.0,\"output\":{cost},\"cacheRead\":0.0,\"cacheWrite\":0.0,\"total\":{cost}}}}}}}}}",
+ input + output,
+ );
+}
+
/// The first frame showing `marker` (the state before the later keystrokes
/// mutate it).
fn first_frame_of(frames: &[String], marker: &str) -> String {
@@ -474,15 +488,7 @@ async fn the_title_bills_a_passive_subagents_spend() {
(&parent_path, "pm1a", 100, 10, 1.0),
(&child_path, "cm1a", 50, 5, 0.3),
] {
- let mut file = std::fs::OpenOptions::new()
- .append(true)
- .open(path)
- .expect("open the fixture for its billed turn");
- let _ = writeln!(
- file,
- "{{\"type\":\"message\",\"id\":\"{id}\",\"timestamp\":\"2026-09-29T00:00:02.100Z\",\"message\":{{\"role\":\"assistant\",\"provider\":\"prime-inference\",\"model\":\"internal/glm-5.3-fast\",\"content\":[{{\"type\":\"text\",\"text\":\"work complete\"}}],\"stopReason\":\"stop\",\"timestamp\":2100,\"usage\":{{\"input\":{input},\"output\":{output},\"cacheRead\":0,\"cacheWrite\":0,\"totalTokens\":{},\"cost\":{{\"input\":0.0,\"output\":{cost},\"cacheRead\":0.0,\"cacheWrite\":0.0,\"total\":{cost}}}}}}}}}",
- input + output,
- );
+ append_billed_turn(path, id, input, output, cost);
}
// The durable spawn edge: the roster surfaces the child as the
@@ -533,3 +539,106 @@ async fn the_title_bills_a_passive_subagents_spend() {
"the top bar bills the family rollup beside the chat name:\n{top_bar}"
);
}
+
+/// The attached parent's top bar bills a deleted subagent's spend: the
+/// RLM-deleted child keeps its transcript under session-artifacts (no
+/// catalog row exists for it), so its captured spend rides the parent's
+/// roster row through the deleted-descendant bucket. This test asserts
+/// the top bar; the agents-view row reads the same row through the same
+/// `compute_rollups`, so it bills the same number.
+#[tokio::test]
+async fn the_title_bills_a_deleted_subagents_spend() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let agent_dir = dir.path().join("agent");
+ let session_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&session_dir).expect("session dir");
+ let supervisor = spawn_supervisor(dir.path());
+
+ // The parent ($1.00 own) and its child, whose transcript lives under
+ // the parent's session-artifacts tree (the real RLM child location:
+ // the flat catalog never lists it, so the child has no row anywhere).
+ let parent_path = write_fixture(
+ &session_dir,
+ "title-del-parent",
+ "title del parent",
+ None,
+ 0,
+ &[],
+ );
+ let child_dir = agent_dir
+ .join("session-artifacts")
+ .join("title-del-parent")
+ .join("title-del-child");
+ std::fs::create_dir_all(&child_dir).expect("child artifacts dir");
+ let child_path = write_fixture(
+ &child_dir,
+ "title-del-worker",
+ "title del worker",
+ Some(&parent_path),
+ 1,
+ &[],
+ );
+ // The billed turns: the parent $1.00, the deleted child $0.30.
+ append_billed_turn(&parent_path, "dm1a", 100, 10, 1.0);
+ append_billed_turn(&child_path, "dm1c", 50, 5, 0.3);
+
+ // The durable spawn edge plus the RLM delete's tombstone carrying
+ // the captured usage (the amendment the stop finalize appends after
+ // the flush barrier): the child's spend survives the deletion.
+ let ledger = pa_daemon::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &session_dir, |_m| {});
+ ledger
+ .append_spawn(&pa_daemon::rlm_ledger::RlmSpawnInput {
+ child_id: "title-del-child".to_string(),
+ parent: parent_path.to_string_lossy().to_string(),
+ child: child_path.to_string_lossy().to_string(),
+ depth: 1,
+ name: "title del worker".to_string(),
+ })
+ .expect("append spawn edge");
+ ledger
+ .append_delete_with_usage(
+ "title-del-child",
+ &child_path.to_string_lossy(),
+ pa_daemon::rlm_ledger::RlmLedgerDeleteReason::User,
+ &pa_daemon::session_usage::SessionUsageSummary {
+ input_tokens: 50,
+ output_tokens: 5,
+ cost: 0.3,
+ },
+ )
+ .expect("append delete tombstone");
+
+ let options = session_options(
+ &supervisor.socket,
+ &session_dir,
+ SessionSelection::Resume(parent_path.clone()),
+ None,
+ true,
+ );
+ let plan = pa_tui::interactive::HeadlessPlan {
+ steps: vec![
+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 15_000 },
+ pa_tui::interactive::HeadlessStep::WaitRender {
+ needle: "$1.30".to_string(),
+ timeout_ms: 15_000,
+ },
+ ],
+ width: 120,
+ height: 36,
+ };
+ let run = pa_tui::interactive::run_interactive(options, UiMode::Headless(plan))
+ .await
+ .expect("parent session run");
+ // The top bar row (render_top_bar): the parent's own $1.00 plus the
+ // deleted child's $0.30, the family rollup - the child's spend
+ // bills through the bucket even though no row exists for it.
+ let top_bar = frame_of(&run.frames, "$1.30")
+ .lines()
+ .next()
+ .expect("the top bar row")
+ .to_string();
+ assert!(
+ top_bar.contains("title del parent") && top_bar.contains("$1.30"),
+ "the top bar bills the family rollup beside the chat name:\n{top_bar}"
+ );
+}
diff --git a/crates/pa-daemon/src/agent_roster.rs b/crates/pa-daemon/src/agent_roster.rs
index b47026710b..110eeb7e48 100644
--- a/crates/pa-daemon/src/agent_roster.rs
+++ b/crates/pa-daemon/src/agent_roster.rs
@@ -9,10 +9,11 @@
use std::collections::HashMap;
use std::path::Path;
+use crate::session_usage::SessionUsageSummary;
use pa_types::daemon::agent_roster::{
classify_summary_value, roster_agent_id_for_summary, slim_roster_summary, AgentRosterEntry,
};
-use serde_json::{Map, Value};
+use serde_json::{json, Map, Value};
/// The supervisor-owned roster. `Write()` classifies once and its file index
/// converges seed and worker keys.
@@ -20,6 +21,21 @@ pub(crate) struct AgentRoster {
entries: HashMap<String, AgentRosterEntry>,
agent_id_by_active_session_id: HashMap<String, String>,
agent_id_by_session_file: HashMap<String, String>,
+ /// The deleted-descendant spend bucket keyed by canonical parent
+ /// session path (the spawn ledger's fold): the bucket changes only at
+ /// ledger events and when a root appears, never on a worker delta, so
+ /// the store holds the current map and [`AgentRoster::store`] attaches
+ /// the value on every write - a delta costs one map lookup on the key
+ /// `store` already computes, and no delta path reads the ledger.
+ deleted_descendant_usage: HashMap<String, SessionUsageSummary>,
+ /// The bucket folds' ordering tickets, the delta watermark's rule for
+ /// the ledger fold: a fold takes its ticket before it reads the
+ /// ledger, and an apply with an older ticket than the last applied
+ /// one never overwrites it (the folds run on independent tasks, so
+ /// an older read can otherwise finish after a newer apply and hide a
+ /// deleted child's spend until the next event).
+ bucket_fold_ticket: u64,
+ bucket_applied_ticket: u64,
/// The stale-delta gate of one worker: a single bounded slot naming
/// the worker's CURRENT process generation (`instance`) and the
/// newest sequence applied from it. The Rust supervisor link dials
@@ -49,6 +65,9 @@ impl AgentRoster {
entries: HashMap::new(),
agent_id_by_active_session_id: HashMap::new(),
agent_id_by_session_file: HashMap::new(),
+ deleted_descendant_usage: HashMap::new(),
+ bucket_fold_ticket: 0,
+ bucket_applied_ticket: 0,
delta_watermarks: HashMap::new(),
}
}
@@ -228,11 +247,12 @@ impl AgentRoster {
}
/// The shared write path behind [`AgentRoster::write_summary`] and
- /// [`AgentRoster::write_seeded`]: classify once, converge the indexes,
- /// and evict a previous owner of the same session file.
+ /// [`AgentRoster::write_seeded`]: classify once, attach the
+ /// deleted-descendant bucket, converge the indexes, and evict a
+ /// previous owner of the same session file.
fn store(
&mut self,
- summary: Value,
+ mut summary: Value,
queued_child: Option<bool>,
worker_id: Option<&str>,
status_label: Option<&str>,
@@ -240,6 +260,20 @@ impl AgentRoster {
) -> AgentRosterEntry {
let queued = queued_child.unwrap_or(false);
let agent_id = roster_agent_id_for_summary(&summary);
+ let file = summary
+ .get("sessionFile")
+ .and_then(Value::as_str)
+ .filter(|file| !file.is_empty())
+ .map(canonical_roster_path);
+ // The bucket rides the row under the same canonical session-file
+ // key the index converges on (a summary rewritten for another
+ // worker keeps its family's deleted spend, and a rewrite whose
+ // family no longer has any sheds the stale value).
+ attach_deleted_descendant_usage(
+ &mut summary,
+ file.as_deref()
+ .and_then(|key| self.deleted_descendant_usage.get(key)),
+ );
let stored = AgentRosterEntry {
agent_id: agent_id.clone(),
queued_child,
@@ -258,13 +292,7 @@ impl AgentRoster {
if let Some(previous) = self.entries.get(&agent_id).cloned() {
self.drop_indexes(&previous);
}
- if let Some(file) = stored
- .summary
- .get("sessionFile")
- .and_then(Value::as_str)
- .filter(|file| !file.is_empty())
- {
- let file = canonical_roster_path(file);
+ if let Some(file) = file {
if let Some(existing) = self.agent_id_by_session_file.get(&file) {
if existing != &agent_id {
let existing = existing.clone();
@@ -286,6 +314,50 @@ impl AgentRoster {
stored
}
+ /// Take the next fold ticket: a bucket fold reads it before it
+ /// reads the ledger, so a fold that started earlier can never
+ /// overwrite a bucket applied by a newer one.
+ pub(crate) fn begin_bucket_fold(&mut self) -> u64 {
+ self.bucket_fold_ticket += 1;
+ self.bucket_fold_ticket
+ }
+
+ /// Replace the deleted-descendant bucket (the ledger fold keyed by
+ /// canonical parent session path) and rewrite in place every row
+ /// whose attached value differs, returning those rows for the
+ /// caller's push. Rows are visited by their store-time canonical key
+ /// (the session-file index). The bucket changes only at ledger
+ /// events and when a root appears, so the event's one fold rewrites
+ /// the rows that did not re-store (a passivated parent, a live
+ /// worker's row); a row whose value did not change never ships. An
+ /// older fold's ticket never overwrites a newer applied bucket (the
+ /// delta watermark's rule) - the newer apply already rewrote and
+ /// pushed its rows, so skipping the older one loses nothing.
+ pub(crate) fn set_deleted_descendant_usage(
+ &mut self,
+ ticket: u64,
+ bucket: HashMap<String, SessionUsageSummary>,
+ ) -> Vec<AgentRosterEntry> {
+ if ticket < self.bucket_applied_ticket {
+ return Vec::new();
+ }
+ self.bucket_applied_ticket = ticket;
+ self.deleted_descendant_usage = bucket;
+ let mut changed = Vec::new();
+ for (file, agent_id) in &self.agent_id_by_session_file {
+ let Some(entry) = self.entries.get_mut(agent_id) else {
+ continue;
+ };
+ if attach_deleted_descendant_usage(
+ &mut entry.summary,
+ self.deleted_descendant_usage.get(file),
+ ) {
+ changed.push(entry.clone());
+ }
+ }
+ changed
+ }
+
pub(crate) fn delete(&mut self, agent_id: &str) {
let Some(entry) = self.entries.remove(agent_id) else {
return;
@@ -410,6 +482,32 @@ fn canonical_roster_path(path: &str) -> String {
)
}
+/// Set or clear the row's `deletedDescendantUsage`; `true` when it
+/// changed. One rule for both writers: the store attach and the event
+/// refresh rewrite the same key the same way, so a re-stored row and a
+/// refreshed one can never disagree.
+fn attach_deleted_descendant_usage(
+ summary: &mut Value,
+ usage: Option<&SessionUsageSummary>,
+) -> bool {
+ let Value::Object(object) = summary else {
+ return false;
+ };
+ let next = usage.map(|usage| json!(usage));
+ if object.get("deletedDescendantUsage") == next.as_ref() {
+ return false;
+ }
+ match next {
+ Some(value) => {
+ object.insert("deletedDescendantUsage".to_string(), value);
+ }
+ None => {
+ object.remove("deletedDescendantUsage");
+ }
+ }
+ true
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -649,4 +747,51 @@ mod tests {
roster.forget_worker_sequences("w1");
assert!(roster.delta_watermarks.is_empty());
}
+
+ /// The bucket folds' ordering rule (the delta watermark's twin): a
+ /// fold that started earlier never overwrites a bucket applied by a
+ /// newer one, whatever order the two folds FINISH in.
+ #[test]
+ fn an_older_bucket_fold_never_overwrites_a_newer_one() {
+ let roster = locked();
+ let mut roster = roster.lock().unwrap();
+ let parent = roster.write_summary(
+ summary("s1", Some("a1"), Some("/tmp/s1.jsonl")),
+ Some("w1"),
+ None,
+ );
+ let file = canonical_roster_path("/tmp/s1.jsonl");
+ let older = HashMap::from([(
+ file.clone(),
+ SessionUsageSummary {
+ input_tokens: 1_000,
+ output_tokens: 100,
+ cost: 0.30,
+ },
+ )]);
+ let newer = HashMap::from([(
+ file,
+ SessionUsageSummary {
+ input_tokens: 2_000,
+ output_tokens: 200,
+ cost: 0.55,
+ },
+ )]);
+ // Two folds read the ledger; the newer one applies first (the
+ // older fold's blocking read finished last).
+ let older_ticket = roster.begin_bucket_fold();
+ let newer_ticket = roster.begin_bucket_fold();
+ let applied = roster.set_deleted_descendant_usage(newer_ticket, newer);
+ assert_eq!(applied.len(), 1, "the newer fold rewrites the parent's row");
+ assert_eq!(
+ roster.set_deleted_descendant_usage(older_ticket, older),
+ Vec::<AgentRosterEntry>::new(),
+ "the older fold never overwrites the newer applied bucket"
+ );
+ assert_eq!(
+ roster.get(&parent.agent_id),
+ applied.first(),
+ "the newer bucket stays on the row"
+ );
+ }
}
diff --git a/crates/pa-daemon/src/rlm_ledger.rs b/crates/pa-daemon/src/rlm_ledger.rs
index 8ebeae67e6..97366c2bdf 100644
--- a/crates/pa-daemon/src/rlm_ledger.rs
+++ b/crates/pa-daemon/src/rlm_ledger.rs
@@ -403,13 +403,16 @@ impl RlmSpawnLedger {
/// anywhere, so nothing re-adds its spend once the tombstone drops its
/// row - this folds the captured spend back per family so cost rollups
/// bill it to the parent that spent it. Live paths never contribute
- /// (their own rows carry their spend); the first tombstoned edge claims
- /// a path (a raced ledger must not bill one child to two parents); the
- /// fold is an iterative post-order walk (a pathological chain must not
- /// overflow the stack) that reads each tombstoned child's captured own
- /// usage first and falls back to the whole-file scan for legacy
- /// tombstones that predate the capture - a path with neither a snapshot
- /// nor a readable transcript is the documented historical gap (no
+ /// (their own rows carry their spend); a tombstoned path that still
+ /// has a catalog row bills through that row instead (see the skip
+ /// below); the first tombstoned edge claims a path (a raced ledger
+ /// must not bill one child to two parents); the fold is an iterative
+ /// post-order walk (a pathological chain must not overflow the
+ /// stack) that reads each tombstoned child's captured own usage
+ /// first and falls back to the transcript's own-usage fold (the
+ /// resumable `read_session_info` scan) for legacy tombstones that
+ /// predate the capture - a path with neither a snapshot nor a
+ /// readable transcript is the documented historical gap (no
/// fabricated backfill: zero).
///
/// # Errors
@@ -444,13 +447,19 @@ impl RlmSpawnLedger {
if live_paths.contains(&child) || snapshot_by_path.contains_key(&child) {
continue;
}
- // A tombstoned path whose transcript still exists bills
- // through its own archived row (the RLM delete keeps the
- // file; the rollup sums the child row AND the parent
- // bucket, so reading both would double the spend): the
- // bucket is for files that are gone — the capture rides the
- // tombstone for the day the transcript dies.
- if Path::new(&edge.child).is_file() {
+ // A tombstoned path that still has a catalog row bills
+ // through that row instead (the rollup sums the child row
+ // AND the parent bucket, so billing both would double the
+ // spend): the flat catalog scans this ledger's sessions dir,
+ // so the row exists exactly while the file sits directly in
+ // it. Real RLM children persist under session-artifacts,
+ // where the flat catalog never lists them - the RLM delete
+ // keeps that transcript and no row anywhere bills it, so the
+ // bucket is the only surface that keeps its spend.
+ let child_file = Path::new(&child);
+ if child_file.is_file()
+ && child_file.parent() == Some(self.canonical_sessions_dir.as_path())
+ {
continue;
}
let parent = canonical(&edge.parent);
@@ -474,7 +483,11 @@ impl RlmSpawnLedger {
let tombstone_usage = |path: &str| -> SessionUsageSummary {
match snapshot_by_path.get(path).cloned().flatten() {
Some(snapshot) => snapshot,
- None => crate::session_usage::read_own_usage_summary(Path::new(path))
+ // The legacy fallback is the same own-usage fold, read
+ // through the resumable scan: a repeat bucket fold on a
+ // surviving legacy transcript is one stat per child.
+ None => crate::session_store::read_session_info(Path::new(path))
+ .and_then(|info| info.usage)
.unwrap_or_else(zero),
}
};
diff --git a/crates/pa-daemon/src/rlm_ledger/tests.rs b/crates/pa-daemon/src/rlm_ledger/tests.rs
index da3a7e7e02..880049ca74 100644
--- a/crates/pa-daemon/src/rlm_ledger/tests.rs
+++ b/crates/pa-daemon/src/rlm_ledger/tests.rs
@@ -1,6 +1,7 @@
//! The RLM ledger test battery (moved with its concern): grammar,
//! replay, tombstone, seed, display, and usage-bucket families.
use super::*;
+use crate::session_usage::SessionUsageSummary;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("pa-ledger-{name}-{}", uuid::Uuid::new_v4()));
@@ -704,9 +705,9 @@ fn bucket_folds_own_snapshots_post_order_without_double_counting() {
&usage_summary(0.10),
)
.unwrap();
- // The tombstoned children's transcripts are gone (a delete that
- // leaves the file alive rides the row — the bucket is for files
- // that died).
+ // The tombstoned children's transcripts are gone (a transcript
+ // directly in the sessions dir keeps its catalog row and the bucket
+ // skips it).
fs::remove_file(&child_1).unwrap();
fs::remove_file(&grandchild_1).unwrap();
// The live child subtree never enters the bucket.
@@ -787,10 +788,10 @@ fn bucket_legacy_tombstones_fall_back_then_gap_to_zero() {
let parent_key = crate::lease::canonical_session_path(&parent)
.to_string_lossy()
.to_string();
- // A tombstoned path whose transcript still exists rides its own
- // archived row (the rollup sums the row AND the parent bucket, so
- // billing both would double the spend) — the bucket never claims
- // a live file, legacy tombstone or not.
+ // A tombstoned transcript directly in the sessions dir keeps its
+ // catalog row (the rollup sums the row AND the parent bucket, so
+ // billing both would double the spend): the bucket skips it,
+ // legacy tombstone or not.
let bucket = ledger.deleted_descendant_usage_by_parent().unwrap();
assert!(
!bucket.contains_key(&parent_key),
@@ -806,6 +807,115 @@ fn bucket_legacy_tombstones_fall_back_then_gap_to_zero() {
);
}
+/// A tombstoned child whose transcript lives under session-artifacts
+/// (every real RLM child: the flat catalog scans only the sessions dir,
+/// so no archived row bills it) has no catalog row: the bucket bills its
+/// captured snapshot, and a legacy tombstone that predates the capture
+/// falls back to the transcript's own-usage fold. A transcript directly
+/// in the sessions dir keeps its catalog row and stays skipped (the
+/// flat-dir tests above pin that half).
+#[test]
+fn bucket_bills_tombstoned_children_without_catalog_rows() {
+ let dir = temp_dir("bucket-no-row");
+ let ledger = ledger_for(&dir);
+ let sessions = dir.join("sessions");
+ fs::create_dir_all(&sessions).unwrap();
+ let parent = sessions.join("p.jsonl");
+ fs::write(&parent, "{}").unwrap();
+ // The real RLM child locations: under the agent dir's
+ // session-artifacts tree, one per child id.
+ let snapshot_child = dir
+ .join("session-artifacts")
+ .join("p")
+ .join("sub-1")
+ .join("sub-1.jsonl");
+ let legacy_child = dir
+ .join("session-artifacts")
+ .join("p")
+ .join("sub-2")
+ .join("sub-2.jsonl");
+ for child in [&snapshot_child, &legacy_child] {
+ fs::create_dir_all(child.parent().unwrap()).unwrap();
+ }
+ fs::write(&snapshot_child, assistant_usage_row("m1", 0.30)).unwrap();
+ // The legacy child's transcript predates the capture: its own fold
+ // is the only record of its spend. Its rows carry the persisted
+ // shape - the top-level timestamp every real entry has, which the
+ // resumable scan's fold reads.
+ let mut legacy = String::from(
+ "{\"type\":\"session\",\"version\":3,\"id\":\"sub-2\",\"timestamp\":\"2024-01-01T00:00:00.000Z\",\"cwd\":\"/tmp\"}\n",
+ );
+ legacy.push_str(
+ &serde_json::json!({
+ "type": "message",
+ "id": "m1",
+ "timestamp": "2024-01-01T00:00:01.000Z",
+ "message": {
+ "role": "assistant",
+ "content": [{ "type": "text", "text": "work complete" }],
+ "stopReason": "stop",
+ "timestamp": 1000,
+ "usage": {
+ "input": 1_000,
+ "output": 100,
+ "cacheRead": 0,
+ "cacheWrite": 0,
+ "totalTokens": 1_100,
+ "cost": { "input": 0.0, "output": 0.25, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.25 }
+ }
+ }
+ })
+ .to_string(),
+ );
+ legacy.push('\n');
+ fs::write(&legacy_child, legacy).unwrap();
+ let spawn = |child_id: &str, child: &Path| {
+ ledger
+ .append_spawn(&RlmSpawnInput {
+ child_id: child_id.into(),
+ parent: parent.to_string_lossy().into(),
+ child: child.to_string_lossy().into(),
+ depth: 1,
+ name: "w".into(),
+ })
+ .unwrap();
+ };
+ spawn("sub-1", &snapshot_child);
+ spawn("sub-2", &legacy_child);
+ // The captured delete, and the legacy (snapshot-less) delete.
+ ledger
+ .append_delete_with_usage(
+ "sub-1",
+ &snapshot_child.to_string_lossy(),
+ RlmLedgerDeleteReason::User,
+ &usage_summary(0.30),
+ )
+ .unwrap();
+ ledger
+ .append_delete(
+ "sub-2",
+ &legacy_child.to_string_lossy(),
+ RlmLedgerDeleteReason::User,
+ )
+ .unwrap();
+ let bucket = ledger.deleted_descendant_usage_by_parent().unwrap();
+ let parent_key = crate::lease::canonical_session_path(&parent)
+ .to_string_lossy()
+ .to_string();
+ assert_eq!(
+ bucket,
+ HashMap::from([(
+ parent_key,
+ SessionUsageSummary {
+ input_tokens: 2_000,
+ output_tokens: 200,
+ cost: 0.55,
+ },
+ )]),
+ "the captured snapshot 0.30 + the legacy transcript's own fold 0.25; only the parent bills"
+ );
+}
+
/// A raced ledger claims each tombstoned path once (first writer wins):
/// one child path billed to two parents would double the spend.
#[test]
diff --git a/crates/pa-daemon/src/saved_session_commands.rs b/crates/pa-daemon/src/saved_session_commands.rs
index 1cf4f84cb4..f3a8a73897 100644
--- a/crates/pa-daemon/src/saved_session_commands.rs
+++ b/crates/pa-daemon/src/saved_session_commands.rs
@@ -677,14 +677,25 @@ impl Supervisor {
// the daemon's lifetime. `canonical` was resolved while the
// file still existed - the same key the table stores.
self.session_bindings.forget_file(&canonical);
- if let Some(entry) = roster_entry {
- let agent_id = entry.agent_id;
- self.roster
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .delete(&agent_id);
- self.push_roster_update(Vec::new(), vec![agent_id]);
- }
+ // The tombstone above changed the ledger, whether or not the
+ // deleted session had a roster row (a subagent of a stopped
+ // parent has none - its only row was the saved listing's):
+ // every successful delete refreshes the bucket, and only the
+ // row removal stays conditional. The refreshed rows and the
+ // removal ship in one push.
+ let changed = self.refresh_deleted_descendant_usage().await;
+ let removed_ids = match roster_entry {
+ Some(entry) => {
+ let agent_id = entry.agent_id;
+ self.roster
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .delete(&agent_id);
+ vec![agent_id]
+ }
+ None => Vec::new(),
+ };
+ self.push_roster_update(changed, removed_ids);
}
(
vec![response_line(&response_success(
diff --git a/crates/pa-daemon/src/session_usage.rs b/crates/pa-daemon/src/session_usage.rs
index 9043b72bac..51015cbdbb 100644
--- a/crates/pa-daemon/src/session_usage.rs
+++ b/crates/pa-daemon/src/session_usage.rs
@@ -326,11 +326,11 @@ fn scan_file(path: &Path) -> Option<UsageScan> {
}
/// Whole-file own usage (the saved-row summary) for the one-off readers
-/// outside the resumable scan: the spawn ledger's tombstone fallback
-/// (`rlm_ledger`) and the saved-delete capture
-/// (`saved_session_commands`). The listing surfaces (and the worker's
-/// live row) read the resumable `session_store::read_session_info`
-/// instead.
+/// outside the resumable scan: the saved-delete capture
+/// (`saved_session_commands`), which reads the file once while it is
+/// still alive. The listing surfaces, the worker's live row, and the
+/// spawn ledger's tombstone fallback (`rlm_ledger`) all read the
+/// resumable `session_store::read_session_info` instead.
#[must_use]
pub fn read_own_usage_summary(path: &Path) -> Option<SessionUsageSummary> {
scan_file(path).and_then(|scan| scan.summary())
diff --git a/crates/pa-daemon/src/stop_cleanup.rs b/crates/pa-daemon/src/stop_cleanup.rs
index cff690757d..bcd17d8d6e 100644
--- a/crates/pa-daemon/src/stop_cleanup.rs
+++ b/crates/pa-daemon/src/stop_cleanup.rs
@@ -791,10 +791,9 @@ mod tests {
.clone()
.expect("the snapshot rides the edge");
assert!((snapshot.cost - 0.06).abs() < 1e-9);
- // While the transcript still exists its own archived row carries
- // the spend — the bucket skips live files (the rollup sums the
- // child row AND the parent bucket, so billing both would double
- // the spend).
+ // A transcript directly in the sessions dir keeps its catalog
+ // row, so the bucket skips it (the rollup sums the row AND the
+ // parent bucket; billing both would double the spend).
let live_bucket = ledger.deleted_descendant_usage_by_parent().unwrap();
let parent_key = canonical_session_path(&parent_file)
.to_string_lossy()
diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rs
index 3ebddc7856..41039911f5 100644
--- a/crates/pa-daemon/src/supervisor/routing.rs
+++ b/crates/pa-daemon/src/supervisor/routing.rs
@@ -1235,6 +1235,26 @@ impl Supervisor {
crate::saved_session_commands::remove_session_artifacts(std::path::Path::new(
&session_file,
));
+ // The resident delete's end state, continued: no stop ran for
+ // this child (its worker was already passivated), so the
+ // passivation's row lingers unowned while the bucket bills the
+ // captured spend on the parent - the same settle the resident
+ // delete's pass performs, in one push.
+ let changed = self.refresh_deleted_descendant_usage().await;
+ let canonical = crate::lease::canonical_session_path(std::path::Path::new(&session_file))
+ .to_string_lossy()
+ .to_string();
+ let removed: Vec<String> = {
+ let mut roster = self.roster.lock().unwrap();
+ let agent_id = roster
+ .by_session_file(&canonical)
+ .map(|row| row.agent_id.clone());
+ if let Some(agent_id) = &agent_id {
+ roster.delete(agent_id);
+ }
+ agent_id.into_iter().collect()
+ };
+ self.push_roster_update(changed, removed);
Ok(())
}
}
diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rs
index 8bb771591a..910840d41d 100644
--- a/crates/pa-daemon/src/supervisor/tests.rs
+++ b/crates/pa-daemon/src/supervisor/tests.rs
@@ -1336,6 +1336,187 @@ async fn a_ledger_delete_of_a_stopped_child_tombstones_without_a_worker() {
);
}
+/// The stopped-child delete settles the roster the way the resident
+/// delete does (the D1b composition with the idle passivation): a
+/// `rlmLedgerDelete` aimed at an idle-passivated child finds no stop to
+/// settle the row, so the passivation's unowned row would linger while
+/// the bucket bills the captured spend on the parent - the same child
+/// billed twice until some later stop's unowned sweep catches the row.
+/// The delete's own push carries both halves together: the parent's
+/// refreshed bucket AND the child's row removal, one `roster_update`.
+#[tokio::test]
+async fn the_stopped_childs_delete_removes_its_row_and_bills_the_parent() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let agent_dir = dir.path().join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ std::fs::create_dir_all(&sessions_dir).unwrap();
+ let supervisor = Arc::new(
+ Supervisor::new(SupervisorOptions {
+ socket_path: dir.path().join("daemon.sock"),
+ agent_dir: agent_dir.clone(),
+ })
+ .expect("supervisor"),
+ );
+ // The parent's roster row: the bucket's target.
+ let parent_file = sessions_dir.join("parent.jsonl");
+ std::fs::write(&parent_file, "{\"type\":\"session\",\"id\":\"p\"}\n").unwrap();
+ let parent_row = json!({
+ "sessionId": "p",
+ "activeSessionId": "p-live",
+ "runtimeKind": "top-level",
+ "sessionFile": parent_file.to_string_lossy(),
+ "sessionName": "parent",
+ "status": "idle",
+ });
+ supervisor.write_roster_summary(&parent_row, None);
+ // The idle-passivated child: its transcript lives under
+ // session-artifacts (the real RLM-delete shape - the flat catalog
+ // never lists it, so the bucket is its only billing surface), one
+ // billed assistant turn ($0.30) the delete captures into the
+ // tombstone, and the passivation's lingering unowned roster row.
+ let child_transcript = agent_dir
+ .join("session-artifacts")
+ .join("root-1")
+ .join("sub-gone")
+ .join("sub-gone.jsonl");
+ std::fs::create_dir_all(child_transcript.parent().expect("artifact dir")).unwrap();
+ {
+ use std::io::Write;
+ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&child_transcript)
+ .expect("open the child transcript");
+ writeln!(
+ file,
+ "{}",
+ json!({
+ "type": "session", "version": 3, "id": "sub-gone",
+ "timestamp": "2026-09-29T00:00:00.000Z", "cwd": "/the/stopped/cwd",
+ "parentSession": parent_file.to_string_lossy(), "rlmDepth": 1
+ })
+ )
+ .expect("the child header");
+ writeln!(
+ file,
+ "{}",
+ json!({
+ "type": "message", "id": "dm1a", "parentId": null,
+ "timestamp": "2026-09-29T00:00:02.100Z",
+ "message": {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "parked work"}],
+ "timestamp": 2100,
+ "usage": {
+ "input": 60, "output": 6, "cacheRead": 0, "cacheWrite": 0,
+ "totalTokens": 66,
+ "cost": {"input": 0.0, "output": 0.3, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.3}
+ }
+ }
+ })
+ )
+ .expect("the billed turn");
+ }
+ let child_row = json!({
+ "sessionId": "sub-gone-persisted",
+ "activeSessionId": "sub-gone-live",
+ "runtimeKind": "subagent",
+ "rlmChildId": "sub-gone",
+ "rlmDepth": 1,
+ "sessionFile": child_transcript.to_string_lossy(),
+ "sessionName": "parked-worker",
+ "cwd": "/the/stopped/cwd",
+ "parentSessionPath": parent_file.to_string_lossy(),
+ "status": "done",
+ "usage": { "inputTokens": 60, "outputTokens": 6, "cost": 0.3 },
+ });
+ let child_agent_id = supervisor
+ .write_roster_summary(&child_row, None)
+ .expect("the child row")
+ .agent_id;
+ // A live ledger edge for the stopped child (the whole-worker idle
+ // stop left the edge behind).
+ let ledger = supervisor
+ .rlm_spawn_ledger_for(None)
+ .await
+ .expect("the spawn ledger resolves");
+ ledger
+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {
+ child_id: "sub-gone".to_string(),
+ parent: parent_file.to_string_lossy().into_owned(),
+ child: child_transcript.to_string_lossy().into_owned(),
+ depth: 1,
+ name: "parked-worker".to_string(),
+ })
+ .expect("the spawn edge appends");
+ let mut events = supervisor.events.subscribe();
+ // The parent's delete of its stopped child.
+ supervisor
+ .tombstone_saved_rlm_child(
+ "sub-gone",
+ Some("sub-gone"),
+ crate::rlm_ledger::RlmLedgerDeleteReason::User,
+ )
+ .await
+ .expect("the stopped child's delete tombstones");
+ // ONE push carries both halves of the settle: the parent's
+ // refreshed bucket and the child's row removal.
+ let mut pushes = Vec::new();
+ loop {
+ match events.try_recv() {
+ Ok((ClientRouting::RosterSubscribers, payload)) => pushes.push((*payload).clone()),
+ Ok(_) => {}
+ Err(
+ tokio::sync::broadcast::error::TryRecvError::Empty
+ | tokio::sync::broadcast::error::TryRecvError::Closed,
+ ) => break,
+ Err(tokio::sync::broadcast::error::TryRecvError::Lagged(missed)) => {
+ panic!("roster push subscriber lagged by {missed}");
+ }
+ }
+ }
+ assert_eq!(
+ pushes.len(),
+ 1,
+ "the stopped child's delete settles in one push: {pushes:?}"
+ );
+ let parent_after = supervisor
+ .roster
+ .lock()
+ .unwrap()
+ .entries()
+ .into_iter()
+ .find(|entry| entry.summary.get("sessionId").and_then(Value::as_str) == Some("p"))
+ .expect("the parent row");
+ assert_eq!(
+ pushes[0]["changed"],
+ serde_json::to_value(vec![parent_after]).expect("serialized parent"),
+ "the push carries the parent's refreshed row: {pushes:?}"
+ );
+ assert_eq!(
+ pushes[0]["changed"][0]["summary"]["deletedDescendantUsage"],
+ json!({ "inputTokens": 60, "outputTokens": 6, "cost": 0.3 }),
+ "the deleted child's captured spend bills through the parent"
+ );
+ assert_eq!(
+ pushes[0]["removed"],
+ json!([child_agent_id]),
+ "the lingering row is removed in the same push: {pushes:?}"
+ );
+ assert!(
+ supervisor
+ .roster
+ .lock()
+ .unwrap()
+ .entries()
+ .into_iter()
+ .all(|entry| {
+ entry.summary.get("rlmChildId").and_then(Value::as_str) != Some("sub-gone")
+ }),
+ "the deleted child's row is gone from the roster"
+ );
+}
+
/// The delete's edge resolution must match BOTH the selector's stem and
/// the explicit child id on the SAME edge (Macroscope's shared-id
/// finding): two live edges sharing a child id never let a delete
diff --git a/crates/pa-daemon/src/supervisor_roster.rs b/crates/pa-daemon/src/supervisor_roster.rs
index a586fe8c9a..4b3d804ecb 100644
--- a/crates/pa-daemon/src/supervisor_roster.rs
+++ b/crates/pa-daemon/src/supervisor_roster.rs
@@ -373,6 +373,12 @@ impl Supervisor {
) = (Vec::new(), HashMap::new());
let (_, parent_by_child) = ledger_view.as_ref().unwrap_or(&empty_view);
let roots = self.roster_seed_roots().await;
+ // The stop's own ledger event: an RLM delete tombstoned its child
+ // before the stop began, and the shutdown route was the
+ // transcript's flush barrier, so the fold beside the ledger view
+ // reads the final bucket - the later capture amendment yields the
+ // same value, so no second push follows it.
+ let bucket_fold = self.deleted_descendant_usage_bucket().await;
// The ledger/roots awaits opened a late-write window. Only
// rows that carry the STOPPED generation settle here: the
// stopped worker's own in-flight delta can have written a row
@@ -397,6 +403,14 @@ impl Supervisor {
let mut removed = Vec::new();
{
let mut roster = self.roster.lock().unwrap();
+ // The refreshed bucket applies FIRST: the settle loop's
+ // passivated rewrites then attach the new value at store
+ // time, and the rewritten rows ship in this same push - the
+ // child's removal and its parent's new bucket together, with
+ // no frame in between where the spend dips.
+ if let Some((ticket, bucket)) = bucket_fold {
+ changed.extend(roster.set_deleted_descendant_usage(ticket, bucket));
+ }
let mut settle: Vec<AgentRosterEntry> = owned;
for late in roster.entries_for_worker(worker_id).into_iter().cloned() {
if !settle
@@ -900,6 +914,262 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
+ /// The RLM delete's stop: the passivation's single push carries both
+ /// the tombstoned child's removal and its parent's refreshed
+ /// deleted-descendant bucket. The child's transcript survives under
+ /// session-artifacts (the real RLM-delete shape: no catalog row
+ /// exists for it), so its captured spend bills through the bucket
+ /// on the parent's row - not through a row anywhere.
+ #[tokio::test]
+ async fn stop_carries_the_deleted_childs_spend_to_its_parent() {
+ let (dir, supervisor, root_file, child_file) = roster_fixture().await;
+ let agent_dir = dir.join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ register_root_worker(&supervisor, "w-root", &root_file).await;
+ // The parent's top-level row: the bucket's target.
+ let mut parent_summary = live_child_summary(&root_file, &child_file);
+ parent_summary["runtimeKind"] = json!("top-level");
+ parent_summary["sessionId"] = json!("root-persisted");
+ parent_summary["id"] = json!("root-persisted");
+ parent_summary["sessionFile"] = json!(root_file.to_string_lossy());
+ parent_summary.as_object_mut().unwrap().remove("rlmChildId");
+ parent_summary
+ .as_object_mut()
+ .unwrap()
+ .remove("parentSessionPath");
+ supervisor.write_roster_summary(&parent_summary, Some("w-root"));
+ // The deleted child's real transcript location: under the agent
+ // dir's session-artifacts tree (the file exists - the shape the
+ // RLM delete leaves behind).
+ let child_artifact = agent_dir
+ .join("session-artifacts")
+ .join("root-1")
+ .join("sub-9")
+ .join("sub-9.jsonl");
+ std::fs::create_dir_all(child_artifact.parent().expect("artifact dir")).unwrap();
+ write_display_file(&child_artifact, "/the/deleted/cwd");
+ // The flushed transcript carries the child's final own spend
+ // ($0.30): the kill route was the flush barrier, so the
+ // passivation fold reads this row.
+ {
+ use std::io::Write;
+ let mut file = std::fs::OpenOptions::new()
+ .append(true)
+ .open(&child_artifact)
+ .expect("open the child transcript for its billed turn");
+ writeln!(
+ file,
+ "{}",
+ json!({
+ "type": "message",
+ "id": "dm1a",
+ "parentId": null,
+ "timestamp": "2026-09-29T00:00:02.100Z",
+ "message": {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "work complete"}],
+ "timestamp": 2100,
+ "usage": {
+ "input": 60,
+ "output": 6,
+ "cacheRead": 0,
+ "cacheWrite": 0,
+ "totalTokens": 66,
+ "cost": {"input": 0.0, "output": 0.3, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.3}
+ }
+ }
+ })
+ )
+ .expect("append the billed turn");
+ }
+ append_family_edge(
+ &agent_dir,
+ &sessions_dir,
+ "sub-9",
+ &root_file,
+ &child_artifact,
+ );
+ // The RLM delete's tombstone carries no usage yet (the capture
+ // amendment lands after the stop); the passivation fold bills
+ // the flushed transcript.
+ let ledger = crate::rlm_ledger::RlmSpawnLedger::new(&agent_dir, &sessions_dir, |_| {});
+ ledger
+ .append_delete(
+ "sub-9",
+ &child_artifact.to_string_lossy(),
+ crate::rlm_ledger::RlmLedgerDeleteReason::User,
+ )
+ .expect("append delete");
+ // The child's live roster row, owned by the stopping worker.
+ let mut events = supervisor.events.subscribe();
+ supervisor.write_roster_summary(
+ &live_child_summary(&root_file, &child_artifact),
+ Some("w-child"),
+ );
+ let child_agent_id = drain_roster_pushes(&mut events)[0]["changed"][0]["agentId"]
+ .as_str()
+ .expect("the child agent id")
+ .to_string();
+
+ supervisor.passivate_roster_worker("w-child", false).await;
+ let pushes = drain_roster_pushes(&mut events);
+ assert_eq!(pushes.len(), 1, "one settle push: {pushes:?}");
+ // The parent's refreshed row is the push's whole `changed`.
+ let parent_after = supervisor
+ .roster
+ .lock()
+ .unwrap()
+ .entries()
+ .into_iter()
+ .find(|entry| {
+ entry.summary.get("sessionId").and_then(Value::as_str) == Some("root-persisted")
+ })
+ .expect("the parent row");
+ assert_eq!(
+ pushes[0]["changed"],
+ serde_json::to_value(vec![parent_after]).expect("serialized parent"),
+ "the push carries the parent's refreshed row: {pushes:?}"
+ );
+ assert_eq!(
+ pushes[0]["changed"][0]["summary"]["deletedDescendantUsage"],
+ json!({ "inputTokens": 60, "outputTokens": 6, "cost": 0.3 }),
+ "the deleted child's captured spend bills through the parent"
+ );
+ assert_eq!(
+ pushes[0]["removed"],
+ json!([child_agent_id]),
+ "the tombstoned child's row dies in the same push: {pushes:?}"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// A saved delete of a subagent whose only row was the saved listing
+ /// (no roster row - its parent is stopped, so no seed ever wrote
+ /// one) still refreshes the bucket: the ledger tombstone is the
+ /// event, and the parent's roster row bills the deleted child's
+ /// captured spend in the delete's own push.
+ #[tokio::test]
+ async fn a_saved_delete_without_a_roster_row_bills_the_parent() {
+ let (dir, supervisor, root_file, child_file) = roster_fixture().await;
+ let agent_dir = dir.join("agent");
+ let sessions_dir = agent_dir.join("sessions");
+ register_root_worker(&supervisor, "w-root", &root_file).await;
+ // The parent's top-level row: the ONLY roster row (the child has
+ // none).
+ let mut parent_summary = live_child_summary(&root_file, &child_file);
+ parent_summary["runtimeKind"] = json!("top-level");
+ parent_summary["sessionId"] = json!("root-persisted");
+ parent_summary["id"] = json!("root-persisted");
+ parent_summary["sessionFile"] = json!(root_file.to_string_lossy());
+ parent_summary.as_object_mut().unwrap().remove("rlmChildId");
+ parent_summary
+ .as_object_mut()
+ .unwrap()
+ .remove("parentSessionPath");
+ supervisor.write_roster_summary(&parent_summary, Some("w-root"));
+ // The child: a transcript under the session-artifacts tree whose
+ // header links it to the parent (the capture's child shape), with
+ // one billed assistant row ($0.30), plus its spawn edge.
+ let child_artifact = agent_dir
+ .join("session-artifacts")
+ .join("root-1")
+ .join("sub-9")
+ .join("sub-9.jsonl");
+ std::fs::create_dir_all(child_artifact.parent().expect("artifact dir")).unwrap();
+ std::fs::write(
+ &child_artifact,
+ format!(
+ "{{\"type\":\"session\",\"version\":3,\"id\":\"sub-9\",\"timestamp\":\"2024-01-01T00:00:00.000Z\",\"cwd\":\"/the/deleted/cwd\",\"parentSession\":\"{}\",\"rlmDepth\":1}}\n",
+ root_file.to_string_lossy()
+ ),
+ )
+ .unwrap();
+ {
+ use std::io::Write;
+ let mut file = std::fs::OpenOptions::new()
+ .append(true)
+ .open(&child_artifact)
+ .expect("open the child transcript for its billed turn");
+ writeln!(
+ file,
+ "{}",
+ json!({
+ "type": "message",
+ "id": "dm1a",
+ "parentId": null,
+ "timestamp": "2026-09-29T00:00:02.100Z",
+ "message": {
+ "role": "assistant",
+ "content": [{"type": "text", "text": "work complete"}],
+ "timestamp": 2100,
+ "usage": {
+ "input": 60,
+ "output": 6,
+ "cacheRead": 0,
+ "cacheWrite": 0,
+ "totalTokens": 66,
+ "cost": {"input": 0.0, "output": 0.3, "cacheRead": 0.0, "cacheWrite": 0.0, "total": 0.3}
+ }
+ }
+ })
+ )
+ .expect("append the billed turn");
+ }
+ append_family_edge(
+ &agent_dir,
+ &sessions_dir,
+ "sub-9",
+ &root_file,
+ &child_artifact,
+ );
+ // The selector-less saved delete of the child: the supervisor arm.
+ let mut events = supervisor.events.subscribe();
+ let command = pa_types::daemon::DaemonCommand::DeleteSavedSession {
+ id: None,
+ active_session_id: None,
+ session_path: child_artifact.to_string_lossy().to_string(),
+ rest: Map::default(),
+ };
+ let (responses, _) = supervisor
+ .handle_delete_saved_session(&command, "client-1", "c1", "delete_saved_session")
+ .await;
+ assert_eq!(
+ responses[0]["success"],
+ json!(true),
+ "the delete succeeded: {responses:?}"
+ );
+ assert!(!child_artifact.is_file(), "the child transcript is gone");
+ // The delete's own push carries the parent's refreshed row - the
+ // whole `changed`, with no removal (the child had no row).
+ let pushes = drain_roster_pushes(&mut events);
+ assert_eq!(pushes.len(), 1, "one refresh push: {pushes:?}");
+ let parent_after = supervisor
+ .roster
+ .lock()
+ .unwrap()
+ .entries()
+ .into_iter()
+ .find(|entry| {
+ entry.summary.get("sessionId").and_then(Value::as_str) == Some("root-persisted")
+ })
+ .expect("the parent row");
+ assert_eq!(
+ pushes[0]["changed"],
+ serde_json::to_value(vec![parent_after]).expect("serialized parent"),
+ "the push carries the parent's refreshed row: {pushes:?}"
+ );
+ assert_eq!(
+ pushes[0]["changed"][0]["summary"]["deletedDescendantUsage"],
+ json!({ "inputTokens": 60, "outputTokens": 6, "cost": 0.3 }),
+ "the deleted child's captured spend bills through the parent"
+ );
+ assert!(
+ pushes[0].get("removed").is_none() || pushes[0]["removed"].is_null(),
+ "no removal rides the push: {pushes:?}"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// Unanchored subagent rows are removed, never passivated (a
/// tombstoned ledger edge - the user deleted the subagent - or a live
/// edge with no resident root), a queued child and an ephemeral
diff --git a/crates/pa-daemon/src/supervisor_roster_seed.rs b/crates/pa-daemon/src/supervisor_roster_seed.rs
index 5cfe184e1e..4155cde3bd 100644
--- a/crates/pa-daemon/src/supervisor_roster_seed.rs
+++ b/crates/pa-daemon/src/supervisor_roster_seed.rs
@@ -15,6 +15,7 @@ use serde_json::{json, Value};
use crate::lease::canonical_session_path;
use crate::rlm_ledger::RlmLedgerEdge;
use crate::session_store::read_session_info;
+use crate::session_usage::SessionUsageSummary;
use crate::supervisor::Supervisor;
impl Supervisor {
@@ -155,10 +156,11 @@ impl Supervisor {
// takes (and is awaited before its snapshot) or it spawns after
// the take (and its pushes land after the response - either way
// the push cannot overtake the snapshot answer). The hydration
- // stays DETACHED inside the task: the tracked work is the
- // lightweight seed (the ledger walk and the edge-only row
- // writes), never the serial transcript reads - a subscribe must
- // not block on hydration (that would reintroduce the
+ // and the deleted-descendant fold stay DETACHED inside the
+ // task: the tracked work is the lightweight seed (the ledger
+ // walk and the edge-only row writes), never the serial
+ // transcript reads or the ledger-wide bucket fold - a subscribe
+ // must not block on either (that would reintroduce the
// large-session open latency this PR removes).
if let Ok(mut pending) = self.pending_registration_seeds.lock() {
// Self-pruning: a daemon without subscribers must not
@@ -179,6 +181,16 @@ impl Supervisor {
// themselves.
drop(supervisor.spawn_seeded_hydration(seeded));
}
+ // The newly resident root's family bills its deleted
+ // descendants, detached like the hydration: the fold
+ // reads the whole ledger and may cold-scan legacy
+ // transcripts, so it never rides the subscribe
+ // barrier. Its push applies on top of the snapshot, and
+ // the fold ticket orders it against concurrent folds.
+ drop(tokio::spawn(async move {
+ let refreshed = supervisor.refresh_deleted_descendant_usage().await;
+ supervisor.push_roster_update(refreshed, Vec::new());
+ }));
});
pending.push(handle);
}
@@ -203,6 +215,63 @@ impl Supervisor {
Ok((edges, parent_by_child))
}
+ /// The deleted-descendant bucket (the spawn ledger's fold keyed by
+ /// canonical parent session path) with the fold's ticket, computed
+ /// off the async runtime: the fold reads the ledger, stats
+ /// tombstoned paths, and may cold-scan a legacy child's transcript
+ /// once. The ticket is taken under the roster lock BEFORE the ledger
+ /// is read (the folds run on independent tasks, so an older read can
+ /// otherwise finish after a newer apply). `None` is the degrade (a
+ /// failed fold is logged) - the roster keeps its last bucket instead
+ /// of billing a broken read as zero.
+ pub(crate) async fn deleted_descendant_usage_bucket(
+ self: &Arc<Self>,
+ ) -> Option<(u64, HashMap<String, SessionUsageSummary>)> {
+ let ticket = self.roster.lock().unwrap().begin_bucket_fold();
+ let bucket = match self.rlm_spawn_ledger_for(None).await {
+ Ok(ledger) => {
+ tokio::task::spawn_blocking(move || ledger.deleted_descendant_usage_by_parent())
+ .await
+ .unwrap_or_else(|error| Err(anyhow::anyhow!(error)))
+ }
+ Err(error) => Err(error),
+ };
+ match bucket {
+ Ok(bucket) => Some((ticket, bucket)),
+ Err(error) => {
+ self.log_line(&format!(
+ "Could not refresh deleted-descendant usage: {error:#}"
+ ));
+ None
+ }
+ }
+ }
+
+ /// Recompute the deleted-descendant bucket and rewrite the roster
+ /// rows whose attached value changed, returning them for the
+ /// caller's push. The bucket changes only at ledger events and when
+ /// a root appears, so this runs at exactly those: a registration
+ /// seed (create, resume, and supervisor-restart re-registration),
+ /// a stop passivation (the RLM delete's tombstone landed before the
+ /// stop, and the later capture amendment yields the same value),
+ /// a stopped-child delete (the idle-passivated child's tombstone -
+ /// no stop runs for it, so the delete settles the row itself), and
+ /// a saved-session delete. The worker-process delete arm and
+ /// the forwarded-owner arm stay uncovered by design: the TUI never
+ /// sends those forms, and their tombstones are picked up at the
+ /// next registration or stop.
+ pub(crate) async fn refresh_deleted_descendant_usage(
+ self: &Arc<Self>,
+ ) -> Vec<AgentRosterEntry> {
+ let Some((ticket, bucket)) = self.deleted_descendant_usage_bucket().await else {
+ return Vec::new();
+ };
+ self.roster
+ .lock()
+ .unwrap()
+ .set_deleted_descendant_usage(ticket, bucket)
+ }
+
/// The seeded candidate's roster row when already present (TS
/// `roster().has` + `hasSessionFile`): by agent id or session file.
fn roster_row_for_candidate(&self, candidate: &SeededRosterEntry) -> Option<AgentRosterEntry> {
diff --git a/crates/pa-tui/src/agents_view_forest/lineage.rs b/crates/pa-tui/src/agents_view_forest/lineage.rs
index 19b9dadbdf..62197e80c7 100644
--- a/crates/pa-tui/src/agents_view_forest/lineage.rs
+++ b/crates/pa-tui/src/agents_view_forest/lineage.rs
@@ -186,13 +186,24 @@ pub fn compute_rollups(records: &[UnifiedRecord]) -> HashMap<String, Rollup> {
// cost: an orchestrator parent with no own billable work (the
// own-zero gate omits `usage` entirely) still bills its deleted
// descendants' spend — the bucket carried inside the own-cost
- // Option would drop with it.
+ // Option would drop with it. The roster row (daemon) is the
+ // fresher writer between the two — the same `daemon ?? saved`
+ // precedence as the own cost below — so the title (roster rows
+ // only) and the agents view bill the same bucket.
let deleted_descendants = records[*position]
- .saved
+ .daemon
.as_ref()
- .and_then(|saved| saved.get("deletedDescendantUsage"))
+ .and_then(|daemon| daemon.get("deletedDescendantUsage"))
.and_then(|deleted| deleted.get("cost"))
.and_then(Value::as_f64)
+ .or_else(|| {
+ records[*position]
+ .saved
+ .as_ref()
+ .and_then(|saved| saved.get("deletedDescendantUsage"))
+ .and_then(|deleted| deleted.get("cost"))
+ .and_then(Value::as_f64)
+ })
.unwrap_or(0.0);
// Deleted subagents keep no row, and their spend is already
// subtracted from the parent's own usage by the attribution