Skip to content

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

Rust

skip malformed lines in the rlm spawn ledger instead of failing the read (#3221)

Sebastian Müllerf5612d860f0b
diff --git a/.changes/ledger-skip-bad-lines.md b/.changes/ledger-skip-bad-lines.md
new file mode 100644
index 0000000000..bdfb408258
--- /dev/null
+++ b/.changes/ledger-skip-bad-lines.md
@@ -0,0 +1 @@
+- A corrupted line in the RLM spawn ledger is now skipped and logged instead of failing every ledger read, so session listings and new subagent spawns keep working.
diff --git a/crates/pa-daemon/src/rlm_ledger.rs b/crates/pa-daemon/src/rlm_ledger.rs
index 547f2a5704..8ebeae67e6 100644
--- a/crates/pa-daemon/src/rlm_ledger.rs
+++ b/crates/pa-daemon/src/rlm_ledger.rs
@@ -3,8 +3,9 @@
//! (parent/child edges, depths, names) is read back from this file instead of
//! being re-derived from session files, so historical and non-resident
//! children stay roster-visible after passivation. Mirrors the record
-//! grammar, bounds, replay semantics, and legacy-registry seeding of the
-//! TS `modes/daemon/rlm-ledger.ts`.
+//! grammar, bounds, and legacy-registry seeding of the TS
+//! `modes/daemon/rlm-ledger.ts`; unlike TS, replay logs and skips a
+//! malformed line instead of failing the whole read.
//!
//! Writers: the supervisor appends at admission moments (spawn at child
//! create, rename at subagent rename, delete at subagent delete). Readers:
@@ -16,7 +17,7 @@
use std::collections::{HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
-use std::io::Write;
+use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
@@ -190,8 +191,8 @@ impl RlmSpawnLedger {
/// Returns an error when the spawn input is invalid (an empty child
/// id, parent, or child session path, or a zero depth), when another
/// live edge already claims the child session path, when the ledger
- /// replay fails (an oversized or malformed ledger), or when the
- /// record cannot be appended.
+ /// replay fails (an oversized ledger), or when the record cannot
+ /// be appended.
pub fn append_spawn(&self, input: &RlmSpawnInput) -> Result<()> {
if input.child_id.is_empty()
|| input.parent.is_empty()
@@ -256,8 +257,8 @@ impl RlmSpawnLedger {
///
/// # Errors
///
- /// Returns an error when the replay fails (an oversized or malformed
- /// ledger) or one of the rename records cannot be appended.
+ /// Returns an error when the replay fails (an oversized ledger)
+ /// or one of the rename records cannot be appended.
pub fn append_rename_by_child_path(&self, child: &str, name: &str) -> Result<()> {
let target = canonical_session_path(Path::new(child));
let state = self.replay_cached()?;
@@ -324,7 +325,7 @@ impl RlmSpawnLedger {
let child_path = canonical_session_path(Path::new(child));
// The writer never records what the reader refuses: replay
// rejects a negative or NaN usage cost outright, which would
- // make the whole ledger unreadable. That includes negative
+ // drop the whole tombstone record. That includes negative
// zero - `is_sign_negative()` is how replay reads it, and
// `>= 0.0` alone would have passed `-0.0` through. A session
// file may carry such a cost (the file's own summary read
@@ -413,8 +414,8 @@ impl RlmSpawnLedger {
///
/// # Errors
///
- /// Returns an error when the ledger replay fails (an oversized or
- /// malformed ledger).
+ /// Returns an error when the ledger replay fails (an oversized
+ /// ledger).
pub fn deleted_descendant_usage_by_parent(
&self,
) -> Result<HashMap<String, crate::session_usage::SessionUsageSummary>> {
@@ -548,8 +549,8 @@ impl RlmSpawnLedger {
///
/// # Errors
///
- /// Returns an error when the ledger replay fails (an oversized or
- /// malformed ledger); a missing ledger replays empty.
+ /// Returns an error when the ledger replay fails (an oversized
+ /// ledger); a missing ledger replays empty.
pub fn edges(&self, include_deleted: bool) -> Result<Vec<RlmLedgerEdge>> {
self.seed_once()?;
let state = self.replay_cached()?;
@@ -572,9 +573,9 @@ impl RlmSpawnLedger {
///
/// # Errors
///
- /// Returns an error when the ledger replay fails (an oversized or
- /// malformed ledger); a missing ledger replays empty, and only the
- /// liveness resolution drops edges.
+ /// Returns an error when the ledger replay fails (an oversized
+ /// ledger); a missing ledger replays empty, and only the liveness
+ /// resolution drops edges.
pub fn live_edges(&self) -> Result<Vec<RlmLedgerEdge>> {
self.seed_once()?;
let state = self.replay_cached()?;
@@ -607,8 +608,8 @@ impl RlmSpawnLedger {
/// a seed was mid-read never writes its row. The child id is
/// matched together with the child path: ids can be shared by
/// edges with different paths, and only the exact edge a seed
- /// snapshotted counts as live. A broken ledger reads as not-live,
- /// like every other read here degrades to nothing.
+ /// snapshotted counts as live. An unreadable (oversized) ledger reads
+ /// as not-live.
pub fn edge_is_live(&self, child_id: &str, child: &str) -> bool {
let child = canonical_session_path(Path::new(child));
self.seed_once().is_ok()
@@ -659,15 +660,18 @@ impl RlmSpawnLedger {
}
fn replay(&self) -> Result<ReplayState> {
- let Ok(content) = fs::read_to_string(&self.path) else {
+ let Ok(bytes) = fs::read(&self.path) else {
return Ok(ReplayState::default());
};
- if content.len() as u64 > RLM_LEDGER_MAX_BYTES {
+ if bytes.len() as u64 > RLM_LEDGER_MAX_BYTES {
bail!(
"RLM ledger {} exceeds {RLM_LEDGER_MAX_BYTES} bytes; refusing to read",
self.path.display()
);
}
+ // A torn write inside a multibyte name must spoil one line, not
+ // the whole file.
+ let content = String::from_utf8_lossy(&bytes);
let mut state = ReplayState::default();
let mut records = 0usize;
for (index, line) in content.lines().enumerate() {
@@ -681,14 +685,22 @@ impl RlmSpawnLedger {
self.path.display()
);
}
- let Some(record) = parse_ledger_line(line, index)
- .with_context(|| format!("RLM ledger {}", self.path.display()))?
- else {
- self.log(&format!(
- "RLM ledger: skipped record with unknown op on line {}",
- index + 1
- ));
- continue;
+ let record = match parse_ledger_line(line, index) {
+ Ok(Some(record)) => record,
+ Ok(None) => {
+ self.log(&format!(
+ "RLM ledger: skipped record with unknown op on line {}",
+ index + 1
+ ));
+ continue;
+ }
+ Err(error) => {
+ self.log(&format!(
+ "RLM ledger {}: skipped {error:#}",
+ self.path.display()
+ ));
+ continue;
+ }
};
match record {
LedgerRecord::Spawn {
@@ -772,6 +784,7 @@ impl RlmSpawnLedger {
line.push('\n');
let mut file = OpenOptions::new()
.create(true)
+ .read(true)
.append(true)
.open(&self.path)
.with_context(|| format!("open RLM ledger {}", self.path.display()))?;
@@ -785,6 +798,16 @@ impl RlmSpawnLedger {
let mut header = serde_json::to_string(&meta)?;
header.push('\n');
file.write_all(header.as_bytes())?;
+ } else {
+ // A crash can leave the final record torn short of its
+ // newline: start on a fresh line so this record never glues
+ // onto it.
+ let mut last = [0u8; 1];
+ file.seek(SeekFrom::End(-1))?;
+ file.read_exact(&mut last)?;
+ if last[0] != b'\n' {
+ line.insert(0, '\n');
+ }
}
file.write_all(line.as_bytes())?;
file.sync_all()?;
diff --git a/crates/pa-daemon/src/rlm_ledger/replay.rs b/crates/pa-daemon/src/rlm_ledger/replay.rs
index e1e8586f5e..d8815ef894 100644
--- a/crates/pa-daemon/src/rlm_ledger/replay.rs
+++ b/crates/pa-daemon/src/rlm_ledger/replay.rs
@@ -39,7 +39,7 @@ fn str_field(record: &Value, key: &str) -> Option<String> {
/// Parse one delete record's usage snapshot (TS `SessionUsageSummary`
/// wire shape). A present-but-malformed snapshot is a corrupt record: the
-/// ledger fails loudly rather than billing a partial number.
+/// record is rejected rather than billing a partial number.
fn parse_deleted_usage(
usage: &Value,
line_no: usize,
@@ -73,8 +73,8 @@ fn parse_deleted_usage(
/// Parse one ledger line: `v:1` records with a known op, `None` for a known
/// version with an unknown op (forward compatibility), an error for anything
-/// else - silently skipping records a reader cannot understand would corrupt
-/// topology, so version violations fail loudly.
+/// else - which replay logs and skips: one bad line costs one record, never
+/// the ledger.
pub(super) fn parse_ledger_line(line: &str, index: usize) -> Result<Option<LedgerRecord>> {
let line_no = index + 1;
let record: Value = serde_json::from_str(line.trim())
diff --git a/crates/pa-daemon/src/rlm_ledger/tests.rs b/crates/pa-daemon/src/rlm_ledger/tests.rs
index 7d1db47e3e..da3a7e7e02 100644
--- a/crates/pa-daemon/src/rlm_ledger/tests.rs
+++ b/crates/pa-daemon/src/rlm_ledger/tests.rs
@@ -272,7 +272,7 @@ fn moved_edge_paths_resolve_through_the_session_id() {
}
#[test]
-fn duplicate_child_path_and_bad_records_fail_loudly() {
+fn duplicate_child_path_and_bad_spawn_inputs_fail_but_bad_lines_skip() {
let dir = temp_dir("dup");
let ledger = ledger_for(&dir);
let parent = dir.join("p.jsonl");
@@ -304,12 +304,23 @@ fn duplicate_child_path_and_bad_records_fail_loudly() {
name: "w".into(),
});
assert!(depth_zero.is_err());
- // A malformed record corrupts topology: the read fails closed.
+ // A torn tail or bad line costs that record only; later appends still land.
let path = ledger.ledger_path().to_path_buf();
let mut content = fs::read_to_string(&path).unwrap();
- content.push_str("{\"v\":1,\"op\":\"spawn\"}\n");
+ content.push_str("{\"v\":1,\"op\":\"spawn\"}\n{\"v\":1,\"op\":\"spa");
fs::write(&path, content).unwrap();
- assert!(ledger.edges(false).is_err());
+ ledger
+ .append_spawn(&RlmSpawnInput {
+ child_id: "sub-4".into(),
+ parent: parent.to_string_lossy().into(),
+ child: dir.join("c4.jsonl").to_string_lossy().into(),
+ depth: 1,
+ name: "w".into(),
+ })
+ .unwrap();
+ let edges = ledger.edges(false).unwrap();
+ let ids: Vec<_> = edges.into_iter().map(|edge| edge.child_id).collect();
+ assert_eq!(ids, ["sub-1", "sub-4"]);
}
#[test]