Skip to content

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

Rust

save the usage scan so big sessions resume faster (#3123)

Sebastian Müllere4f2e586b63d
diff --git a/.changes/fix-rust-cost-sidecar.md b/.changes/fix-rust-cost-sidecar.md
new file mode 100644
index 0000000000..bf21f0bac6
--- /dev/null
+++ b/.changes/fix-rust-cost-sidecar.md
@@ -0,0 +1 @@
+- Large sessions reopen faster: the usage scan is saved when a session closes and reused on the next open.
diff --git a/crates/pa-daemon/src/branch_navigation.rs b/crates/pa-daemon/src/branch_navigation.rs
index 0d2280d6e2..5a98a0dcf9 100644
--- a/crates/pa-daemon/src/branch_navigation.rs
+++ b/crates/pa-daemon/src/branch_navigation.rs
@@ -471,10 +471,14 @@ impl TreeNavigation {
let _ =
tokio::task::spawn_blocking(move || crate::session_store::read_session_info(&primed))
.await;
- {
+ let previous = {
let mut core = self.core.lock().unwrap();
- core.store = Some(forked);
- }
+ core.store.replace(forked)
+ };
+ // The old store's lease release flushes the window and info
+ // sidecars (megabytes for a large session): off the core lock
+ // and the runtime.
+ let _ = tokio::task::spawn_blocking(move || drop(previous)).await;
self.engine.set_session_file(new_path.clone());
// TS re-restores the forked session's saved model at its runtime
// recreation (`createRuntime` -> `createAgentSession`): the fork
diff --git a/crates/pa-daemon/src/lease.rs b/crates/pa-daemon/src/lease.rs
index 326a15d572..dded085509 100644
--- a/crates/pa-daemon/src/lease.rs
+++ b/crates/pa-daemon/src/lease.rs
@@ -338,6 +338,11 @@ fn with_lease_guard<T>(
#[derive(Debug)]
pub struct SessionLease {
pub session_path: PathBuf,
+ /// The path form the holder opened the file by: the process's window
+ /// and scan caches key the file by it, so the release flushes both
+ /// under it (`session_path` is the canonical identity; a symlinked
+ /// sessions dir or macOS `/var` makes the two differ).
+ opened_path: PathBuf,
directory: PathBuf,
token: String,
released: std::sync::atomic::AtomicBool,
@@ -351,7 +356,12 @@ impl SessionLease {
{
return;
}
- let _ = pa_core::session::window::flush_cache(&self.session_path);
+ let _ = pa_core::session::window::flush_cache(&self.opened_path);
+ // The usage-scan sidecar persists beside the window snapshot, in
+ // the same lease-keyed, best-effort shape: only the lease holder
+ // writes, and a failed write costs the next open its warm resume,
+ // nothing more.
+ crate::session_store::persist_info_sidecar(&self.opened_path);
let _ = with_lease_guard(&self.directory, GuardWait::Fast, || {
if let Ok(Some(owner)) = read_owner(&self.directory) {
if owner.token == self.token {
@@ -509,6 +519,7 @@ pub fn acquire_runtime_session_lease(
Ok(()) => {
return Ok(SessionLease {
session_path: canonical.clone(),
+ opened_path: session_path.to_path_buf(),
directory: directory.clone(),
token,
released: std::sync::atomic::AtomicBool::new(false),
@@ -605,6 +616,7 @@ mod tests {
.unwrap();
let winner = SessionLease {
session_path: canonical_session_path(&path),
+ opened_path: path.clone(),
directory,
token: replacement.token,
released: std::sync::atomic::AtomicBool::new(false),
diff --git a/crates/pa-daemon/src/session_navigation.rs b/crates/pa-daemon/src/session_navigation.rs
index d5fcbfaed3..efba8b16fc 100644
--- a/crates/pa-daemon/src/session_navigation.rs
+++ b/crates/pa-daemon/src/session_navigation.rs
@@ -91,10 +91,14 @@ impl SessionNavigation {
let _ =
tokio::task::spawn_blocking(move || crate::session_store::read_session_info(&primed))
.await;
- {
+ let previous = {
let mut core = self.core.lock().unwrap();
- core.store = Some(file);
- }
+ core.store.replace(file)
+ };
+ // The old store's lease release flushes the window and info
+ // sidecars (megabytes for a large session): off the core lock
+ // and the runtime.
+ let _ = tokio::task::spawn_blocking(move || drop(previous)).await;
self.engine.set_session_file(new_path.clone());
// TS re-restores the moved-to session's saved model at its runtime
// recreation (`createRuntime` -> `createAgentSession`): the
diff --git a/crates/pa-daemon/src/session_store.rs b/crates/pa-daemon/src/session_store.rs
index 2744e7d48f..c4058c7a64 100644
--- a/crates/pa-daemon/src/session_store.rs
+++ b/crates/pa-daemon/src/session_store.rs
@@ -90,6 +90,9 @@ use view::message_role;
// test-scoped binding keeps the scan internals' test callers in scope.
mod info;
+// The persisted scan-state sidecar.
+mod info_sidecar;
+
pub(crate) use info::read_session_info_from;
#[cfg(test)]
use info::{
@@ -102,6 +105,7 @@ pub use info::{
find_most_recent_session_for_cwd, read_session_info, SessionInfo,
SESSION_LIST_SEARCH_TEXT_MAX_CHARS,
};
+pub(crate) use info_sidecar::persist_info_sidecar;
// The inline unit battery moved to the child module at the same tree
// position (session_store::tests); its use-super glob keeps resolving
diff --git a/crates/pa-daemon/src/session_store/info.rs b/crates/pa-daemon/src/session_store/info.rs
index acc64915d3..01a9d4469c 100644
--- a/crates/pa-daemon/src/session_store/info.rs
+++ b/crates/pa-daemon/src/session_store/info.rs
@@ -4,8 +4,8 @@
//! most-recent-session lookup.
use super::{
- fs, list_sessions, normalize_state_status, Cow, Deserialize, HashMap, Path, PathBuf,
- SessionHeader, Usage, Value,
+ fs, info_sidecar, list_sessions, normalize_state_status, Cow, Deserialize, HashMap, Path,
+ PathBuf, Serialize, SessionHeader, Usage, Value,
};
/// Port of `readSessionInfo`'s fold (single pass, no resume cache): the durable
@@ -81,7 +81,7 @@ pub(super) fn append_capped_search_text(current: &mut String, text: &str, used:
count + taken
}
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(super) struct SessionInfoGeneration {
pub(super) len: u64,
pub(super) dev: u64,
@@ -230,8 +230,13 @@ pub(super) const SESSION_SCAN_RESUME_TAIL_BYTES: usize = 16;
/// TS `SessionScanAccumulator`: the per-file fold state a resume continues
/// from. The finished [`SessionInfo`] is derived from this; the cached state
/// carries the accumulator so a grown file folds ONLY its appended entries.
-/// Clone is the snapshot fold's copy (TS `snapshotSessionInfo`).
-#[derive(Clone, Default)]
+/// Clone is the snapshot fold's copy (TS `snapshotSessionInfo`). Serialize is
+/// the persisted sidecar's form ([`super::info_sidecar`]): a released lease
+/// holder writes it, a cold process loads it and folds only the tail.
+/// Persisted in `<stem>.info-cache.json`: any change to this fold's semantics
+/// or fields must bump `info_sidecar::INFO_SIDECAR_VERSION`, or old sessions
+/// keep the old build's prefix fold.
+#[derive(Clone, Default, Serialize, Deserialize)]
pub(super) struct SessionScanAccumulator {
header: Option<SessionHeader>,
name: Option<String>,
@@ -252,7 +257,10 @@ pub(super) struct SessionScanAccumulator {
/// One cached scan state (TS `SessionScanState`): the generation the state
/// was certified at, the fold accumulator, the consumed-prefix cursor, the
-/// resume tail, and the derived info.
+/// resume tail, and the derived info. Serialize is the persisted sidecar's
+/// form: `info` and the retained-usage accounting are skipped (the load
+/// rebuilds the row through the fold and `store_state` recounts).
+#[derive(Serialize, Deserialize)]
pub(super) struct SessionScanState {
generation: SessionInfoGeneration,
pub(super) acc: SessionScanAccumulator,
@@ -260,9 +268,11 @@ pub(super) struct SessionScanState {
offset: u64,
/// The trailing window of the consumed prefix (TS `advanceScanTail`).
pub(super) tail: [u8; SESSION_SCAN_RESUME_TAIL_BYTES],
+ #[serde(skip)]
info: Option<SessionInfo>,
/// Usage entries counted against the retained bound at the last store
/// (TS `accountedUsageEntries`).
+ #[serde(skip)]
accounted_usage_entries: usize,
}
@@ -452,7 +462,7 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
let generation = SessionInfoGeneration::from_metadata(&file.metadata().ok()?);
// The unchanged case answers from the cache; the grown case resumes.
- let mut state = {
+ let state = {
let mut cache = session_info_cache().lock().ok()?;
match cache.states.get(path) {
Some(cached) if cached.generation == generation => {
@@ -465,12 +475,38 @@ pub(crate) fn read_session_info_from(file: &mut fs::File, path: &Path) -> Option
&& generation.len > cached.generation.len =>
{
if cached.prefix_intact(file) {
- cached.clone_for_resume()
+ Some(cached.clone_for_resume())
} else {
- SessionScanState::fresh(generation)
+ Some(SessionScanState::fresh(generation))
}
}
- _ => SessionScanState::fresh(generation),
+ // No in-process state serves (absent or invalidated): the
+ // persisted sidecar below decides, outside the lock (its
+ // load is file IO).
+ _ => None,
+ }
+ };
+ let mut state = match state {
+ Some(state) => state,
+ None => {
+ // A previous lease holder's certified fold state, loaded from
+ // the sidecar. It passes the same validation ladder a cached
+ // state passes, minus the derived-info shortcut (a loaded
+ // state carries none): an equal generation folds zero bytes
+ // and rebuilds the row, a grown same-inode file with an
+ // intact prefix folds its appended entries, and anything
+ // else is the cold scan the sidecar-less path always ran.
+ match info_sidecar::load(path) {
+ Some(cached) if cached.generation == generation => cached,
+ Some(cached)
+ if cached.same_file_identity(&generation)
+ && generation.len > cached.generation.len
+ && cached.prefix_intact(file) =>
+ {
+ cached
+ }
+ _ => SessionScanState::fresh(generation),
+ }
}
};
// Position the shared cursor at the resume point. A fresh state rewinds
diff --git a/crates/pa-daemon/src/session_store/info_sidecar.rs b/crates/pa-daemon/src/session_store/info_sidecar.rs
new file mode 100644
index 0000000000..2138a9ecd0
--- /dev/null
+++ b/crates/pa-daemon/src/session_store/info_sidecar.rs
@@ -0,0 +1,90 @@
+//! The persisted scan-state sidecar: `<stem>.info-cache.json`, written
+//! beside the session file when the runtime lease is released and loaded
+//! on a process-cache miss, so a warm resume folds only the appended tail
+//! instead of rescanning the whole file. pa-daemon owns the sidecar:
+//! the scan state is this crate's type, and it certifies differently from
+//! pa-core's window snapshot (an exact generation there, a grown-file
+//! resume with a prefix check here). Only the lease holder writes (the
+//! worker at release); every reader loads.
+
+use std::io::{self, Write};
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+use super::info::{session_info_cache, SessionScanState};
+
+/// The sidecar format version: a sidecar serves only at exactly this
+/// version; any other version (an older or a newer build's) is a cold
+/// scan, the behavior without a sidecar. Bump on any change to
+/// [`SessionScanAccumulator`](super::info::SessionScanAccumulator) or
+/// [`UsageScan`](crate::session_usage::UsageScan) - the persisted fold's
+/// fields or semantics.
+const INFO_SIDECAR_VERSION: u32 = 1;
+
+/// The on-disk envelope: the version gate plus the scan state.
+#[derive(Serialize, Deserialize)]
+struct InfoSidecar {
+ version: u32,
+ state: SessionScanState,
+}
+
+fn sidecar_path(path: &Path) -> PathBuf {
+ path.with_extension("info-cache.json")
+}
+
+/// Load the persisted scan state for `path`: `None` on any failure - a
+/// missing sidecar, an unparsable one, or a version this build does not
+/// serve - so the caller scans cold, exactly as it does without one.
+#[must_use]
+pub(super) fn load(path: &Path) -> Option<SessionScanState> {
+ let data = std::fs::read(sidecar_path(path)).ok()?;
+ let sidecar: InfoSidecar = serde_json::from_slice(&data).ok()?;
+ (sidecar.version == INFO_SIDECAR_VERSION).then_some(sidecar.state)
+}
+
+/// The lease-release write: persist the cached scan state for `path` (the
+/// path form the lease holder opened and read the file by - the scan
+/// cache's key, and the form the load derives the sidecar path from) so
+/// the next process that opens the file folds only what was appended
+/// since. A fresh temp file, then the rename - a torn write never
+/// replaces a loadable sidecar, and a reader that races the rename sees
+/// either the old or the new whole file. A miss writes nothing; a failed
+/// write costs the next open its warm resume, nothing more - the same
+/// error policy as the window sidecar's flush.
+pub(crate) fn persist_info_sidecar(path: &Path) {
+ let Some(state) = session_info_cache().lock().ok().and_then(|cache| {
+ cache
+ .states
+ .get(path)
+ .map(SessionScanState::clone_for_resume)
+ }) else {
+ return;
+ };
+ let temp = path.with_extension(format!("info-cache-{}.tmp", uuid::Uuid::new_v4()));
+ let result = (|| {
+ // Buffered: the serialized state is megabytes of small map
+ // entries, and an unbuffered file writer would turn every
+ // serialized fragment into its own write syscall.
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create_new(true);
+ // The sidecar carries message text (the search corpus, the first
+ // message): the temp is owner-only like the session files
+ // (`persist.rs`'s writer), and the rename carries the mode onto
+ // the sidecar.
+ pa_core::platform::perms::set_private_mode(&mut options);
+ let mut file = io::BufWriter::new(options.open(&temp)?);
+ serde_json::to_writer(
+ &mut file,
+ &InfoSidecar {
+ version: INFO_SIDECAR_VERSION,
+ state,
+ },
+ )?;
+ file.flush()?;
+ pa_core::platform::rename_onto(&temp, &sidecar_path(path))
+ })();
+ if result.is_err() {
+ let _ = std::fs::remove_file(&temp);
+ }
+}
diff --git a/crates/pa-daemon/src/session_store_info_tests.rs b/crates/pa-daemon/src/session_store_info_tests.rs
index 5492f77926..af996a9d3c 100644
--- a/crates/pa-daemon/src/session_store_info_tests.rs
+++ b/crates/pa-daemon/src/session_store_info_tests.rs
@@ -475,6 +475,145 @@ fn a_failed_prefix_check_rescans_from_byte_zero() {
assert_fold_matches(&path);
}
+/// The persisted scan-state sidecar: a state written at lease release and
+/// loaded on a process-cache miss resumes the fold of the appended tail -
+/// whole-row equality against the full fold, including a prefix-targeted
+/// attribution (the resumed fold must find the prefix id in the persisted
+/// per-id map). A replacement file (a new inode) rejects the stale sidecar
+/// and rescans whole. Unix-only: a state is certified into the process
+/// cache (and so persistable) only on Unix - `read_session_info_from`'s
+/// store gate - so no sidecar exists to load elsewhere.
+#[cfg(unix)]
+#[test]
+fn a_persisted_scan_state_resumes_like_the_full_fold() {
+ let dir = test_dir();
+ let path = dir.join("sidecar.jsonl");
+ let usage = |cost: f64| {
+ json!({
+ "input": 100, "output": 10, "cacheRead": 0, "cacheWrite": 0, "totalTokens": 110,
+ "cost": { "input": 0.0, "output": cost, "cacheRead": 0.0, "cacheWrite": 0.0, "total": cost },
+ })
+ };
+ let assistant = |id: &str, cost: f64| {
+ json!({
+ "type": "message", "id": id, "timestamp": "2026-09-23T00:00:00.000Z",
+ "message": {
+ "role": "assistant", "content": format!("answer {id}"),
+ "timestamp": 1_790_110_000_000_u64, "usage": usage(cost),
+ },
+ })
+ };
+ let attribution = |id: &str, target: &str, child: f64, aggregate: f64| {
+ json!({
+ "type": "child_usage_attributed", "id": id, "timestamp": "2026-09-23T00:00:00.000Z",
+ "targetId": target, "childUsage": usage(child), "aggregateUsage": usage(aggregate),
+ })
+ };
+ append_rows(
+ &path,
+ &[
+ json!({"type":"session","id":"sc","timestamp":"2026-09-23T00:00:00.000Z","cwd":"/test"}),
+ assistant("a1", 0.1),
+ assistant("a2", 0.2),
+ assistant("a3", 0.3),
+ json!({"type":"compaction","id":"c1","timestamp":"2026-09-23T00:00:00.000Z","summary":"s","usage":usage(0.25)}),
+ attribution("x1", "a2", 0.05, 0.45),
+ ],
+ );
+ assert_fold_matches(&path);
+ // The lease-release write persists the certified state beside the
+ // file; the in-process copy is gone, so the next read can only be
+ // served by the sidecar.
+ super::persist_info_sidecar(&path);
+ assert!(
+ path.with_extension("info-cache.json").is_file(),
+ "the release write persists the state"
+ );
+ // The sidecar carries message text (the search corpus, the first
+ // message): it is owner-only like the session files it derives from.
+ assert_eq!(
+ pa_core::platform::perms::file_mode(&path.with_extension("info-cache.json")),
+ Some(pa_core::platform::perms::PRIVATE_FILE_MODE)
+ );
+ super::session_info_cache()
+ .lock()
+ .unwrap()
+ .drop_state(&path);
+ append_rows(
+ &path,
+ &[attribution("x2", "a2", 0.02, 0.52), assistant("a4", 0.4)],
+ );
+ assert_fold_matches(&path);
+ // A replacement file (a new inode): the stale sidecar fails the
+ // same-file ladder and the scan runs cold from byte zero.
+ let replacement = dir.join("replacement.jsonl");
+ append_rows(
+ &replacement,
+ &[
+ json!({"type":"session","id":"sc2","timestamp":"2026-09-23T00:00:00.000Z","cwd":"/test"}),
+ assistant("b1", 0.5),
+ ],
+ );
+ fs::rename(&replacement, &path).unwrap();
+ super::session_info_cache()
+ .lock()
+ .unwrap()
+ .drop_state(&path);
+ assert_fold_matches(&path);
+ fs::remove_dir_all(dir).unwrap();
+}
+
+/// The sidecar round trip through a real lease, for a session opened by
+/// a symlinked dir (macOS `/var`, a symlinked `~/.prime`): the release
+/// persists what the holder's raw-path reads cached, though the lease
+/// keys the file canonically. The next read then serves a valid sidecar
+/// (here a name the file does not carry - a cold scan cannot produce
+/// it), and scans cold past a corrupt one or one at another version.
+/// Unix-only like its sibling: only Unix certifies a state to persist.
+#[cfg(unix)]
+#[test]
+fn a_symlinked_lease_release_persists_a_sidecar_the_next_read_serves() {
+ let dir = test_dir();
+ let real_dir = dir.join("real");
+ fs::create_dir_all(&real_dir).unwrap();
+ std::os::unix::fs::symlink(&real_dir, dir.join("linked")).unwrap();
+ let path = dir.join("linked").join("s.jsonl");
+ append_rows(
+ &path,
+ &[
+ json!({"type":"session","id":"sl","timestamp":"2026-09-23T00:00:00.000Z","cwd":"/test"}),
+ json!({"type":"message","id":"u1","timestamp":"2026-09-23T00:00:00.000Z",
+ "message":{"role":"user","content":"hi","timestamp":1_790_110_000_000_u64}}),
+ ],
+ );
+ let lease = crate::lease::acquire_runtime_session_lease(&path, &dir).unwrap();
+ let cold = read_session_info(&path).unwrap();
+ drop(lease);
+ let sidecar = real_dir.join("s.info-cache.json");
+ assert!(sidecar.is_file(), "the release persists the raw-path state");
+ let mut valid: Value = serde_json::from_slice(&fs::read(&sidecar).unwrap()).unwrap();
+ valid["state"]["acc"]["name"] = json!("from the sidecar");
+ let mut other_version = valid.clone();
+ other_version["version"] = json!(valid["version"].as_u64().unwrap() + 1);
+ let served = SessionInfo {
+ name: Some("from the sidecar".to_string()),
+ ..cold.clone()
+ };
+ for (contents, expected) in [
+ (valid.to_string(), &served),
+ (other_version.to_string(), &cold),
+ ("{".to_string(), &cold),
+ ] {
+ fs::write(&sidecar, contents).unwrap();
+ super::session_info_cache()
+ .lock()
+ .unwrap()
+ .drop_state(&path);
+ assert_eq!(read_session_info(&path).as_ref(), Some(expected));
+ }
+ fs::remove_dir_all(dir).unwrap();
+}
+
#[test]
fn a_valid_unterminated_final_line_folds_into_the_snapshot() {
let dir = test_dir();
diff --git a/crates/pa-daemon/src/session_usage.rs b/crates/pa-daemon/src/session_usage.rs
index 51015cbdbb..234173f42d 100644
--- a/crates/pa-daemon/src/session_usage.rs
+++ b/crates/pa-daemon/src/session_usage.rs
@@ -96,6 +96,30 @@ impl AssistantUsageById {
}
}
+/// The persisted sidecar's per-assistant map: the entries vec in its
+/// insertion order (the fold's float-sum order — the index rebuilds from
+/// it on load, exactly what `set` maintains).
+impl Serialize for AssistantUsageById {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.collect_seq(
+ self.entries
+ .iter()
+ .map(|(id, usage)| (id.as_str(), PersistedUsage::from(*usage))),
+ )
+ }
+}
+
+impl<'de> Deserialize<'de> for AssistantUsageById {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let entries = Vec::<(String, PersistedUsage)>::deserialize(deserializer)?;
+ let mut map = AssistantUsageById::default();
+ for (id, usage) in entries {
+ map.set(&id, Usage::from(usage));
+ }
+ Ok(map)
+ }
+}
+
/// The scan-side wire shape of a usage block. Persisted files carry
/// partial objects (`{input, output, totalTokens}` without
/// `cacheRead`/`cacheWrite`/`cost`), and TS `JSON.parse` never rejects
@@ -163,15 +187,103 @@ pub struct SessionUsageTotals {
pub total: Usage,
}
+/// The persisted form of one usage block (the scan-state sidecar's
+/// encoding): token counts unchanged, the five cost floats as
+/// `to_bits()` integers. The workspace's `serde_json` runs without
+/// `float_roundtrip`, and its decimal parse need not round-trip every
+/// shortest-repr float — a one-ulp drift in a persisted block would make
+/// a resumed fold's sums differ from a full scan's. The window sidecar
+/// encodes its floats the same way (pa-core `window_cache::float_bits`).
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct PersistedUsage {
+ input: u64,
+ output: u64,
+ cache_read: u64,
+ cache_write: u64,
+ total_tokens: u64,
+ cost_input: u64,
+ cost_output: u64,
+ cost_cache_read: u64,
+ cost_cache_write: u64,
+ cost_total: u64,
+}
+
+impl From<Usage> for PersistedUsage {
+ fn from(usage: Usage) -> Self {
+ Self {
+ input: usage.input,
+ output: usage.output,
+ cache_read: usage.cache_read,
+ cache_write: usage.cache_write,
+ total_tokens: usage.total_tokens,
+ cost_input: usage.cost.input.as_f64().to_bits(),
+ cost_output: usage.cost.output.as_f64().to_bits(),
+ cost_cache_read: usage.cost.cache_read.as_f64().to_bits(),
+ cost_cache_write: usage.cost.cache_write.as_f64().to_bits(),
+ cost_total: usage.cost.total.as_f64().to_bits(),
+ }
+ }
+}
+
+impl From<PersistedUsage> for Usage {
+ fn from(persisted: PersistedUsage) -> Self {
+ Usage {
+ input: persisted.input,
+ output: persisted.output,
+ cache_read: persisted.cache_read,
+ cache_write: persisted.cache_write,
+ total_tokens: persisted.total_tokens,
+ cost: UsageCost {
+ input: JsNumber(f64::from_bits(persisted.cost_input)),
+ output: JsNumber(f64::from_bits(persisted.cost_output)),
+ cache_read: JsNumber(f64::from_bits(persisted.cost_cache_read)),
+ cache_write: JsNumber(f64::from_bits(persisted.cost_cache_write)),
+ total: JsNumber(f64::from_bits(persisted.cost_total)),
+ },
+ }
+ }
+}
+
+/// `#[serde(with)]` for every persisted `Usage` field: the bits encoding
+/// above, behind the plain `Usage` field type.
+mod usage_bits {
+ use super::{PersistedUsage, Usage};
+ use serde::{Deserialize, Deserializer, Serialize, Serializer};
+
+ // serde's `serialize_with` contract pins `&T` - the lint's by-value
+ // form would not be callable as a serde attribute helper.
+ #[allow(clippy::trivially_copy_pass_by_ref)]
+ pub(super) fn serialize<S: Serializer>(
+ value: &Usage,
+ serializer: S,
+ ) -> Result<S::Ok, S::Error> {
+ PersistedUsage::from(*value).serialize(serializer)
+ }
+
+ pub(super) fn deserialize<'de, D: Deserializer<'de>>(
+ deserializer: D,
+ ) -> Result<Usage, D::Error> {
+ PersistedUsage::deserialize(deserializer).map(Usage::from)
+ }
+}
+
/// The streaming whole-file own-usage accumulator: feed one entry at a
/// time in file order, then read [`summary`](Self::summary). Line order is
/// the fold's authority — an attribution folds only when its target is
/// already in the map (the assistant entry precedes its children's settle
-/// in the file).
-#[derive(Default, Clone)]
+/// in the file). Serialize is the persisted sidecar's form: every cost
+/// float rides as `to_bits()` ([`PersistedUsage`]) so a resumed fold sums
+/// bit-identical floats to a full scan. Persisted in
+/// `<stem>.info-cache.json`: any change to this fold's semantics or fields
+/// must bump `info_sidecar::INFO_SIDECAR_VERSION`, or old sessions keep
+/// the old build's prefix fold.
+#[derive(Default, Clone, Serialize, Deserialize)]
pub struct UsageScan {
assistant_usage_by_id: AssistantUsageById,
+ #[serde(with = "usage_bits")]
attributed_child_usage: Usage,
+ #[serde(with = "usage_bits")]
summarization_usage: Usage,
}