Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(transcripts): classify torn prefixes by typed EOF, not Display text

koeria4534e9fe981a
diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rs
index 207c3b88f..bb28fdde0 100644
--- a/crates/host-core/src/transcripts.rs
+++ b/crates/host-core/src/transcripts.rs
@@ -291,7 +291,7 @@ pub fn find_message_position(
match decoded {
Ok(identity) if identity.id == message_id => return Ok(Some(position)),
Ok(_) => {}
- Err(error) if invalid_utf8 || is_torn_prefix(&error) => {
+ Err(error) if invalid_utf8 || error.is_eof() => {
tracing::warn!(%error, "skipping invalid indexed transcript identity");
}
Err(error) => return Err(error).context("decode indexed transcript message identity"),
@@ -323,7 +323,7 @@ pub fn read_tool_call(
}
let identity: Value = match serde_json::from_str(&line) {
Ok(value) => value,
- Err(error) if invalid_utf8 || is_torn_prefix(&error) => {
+ Err(error) if invalid_utf8 || error.is_eof() => {
tracing::warn!(%error, "skipping invalid indexed transcript tool-call identity");
continue;
}
@@ -359,10 +359,12 @@ pub fn read_tool_call(
apply_tool_review_states(std::slice::from_mut(&mut record), &updates);
return Ok(Some(record));
}
- Err(error) if binary_storage::is_error(&error) && !is_torn_prefix(&error) => {
+ Err(error)
+ if binary_storage::is_error(&error) && !binary_storage::is_torn_eof(&error) =>
+ {
return Err(error)
}
- Err(error) if invalid_utf8 || is_torn_prefix(&error) => {
+ Err(error) if invalid_utf8 || binary_storage::is_torn_eof(&error) => {
tracing::warn!(%error, "skipping invalid indexed tool-call message");
}
Err(error) => {
@@ -429,21 +431,6 @@ thread_local! {
static LAYOUT_LINE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
-/// Whether a decode failure on a transcript line is a crash-truncated prefix.
-///
-/// `append_line` terminates a torn tail with a newline before appending, which
-/// promotes the torn bytes into a complete line. The line still sniffs as its
-/// leading `type` (the discriminator precedes the truncation point), so the
-/// layout indexes it and even the sequential path classifies it as a message
-/// line, but it can never decode: serde reports the missing tail as an
-/// EOF-category parse error, which surfaces verbatim for plain lines and
-/// inside the `invalid binary storage` reason for encoded ones. Such a line
-/// is unrecoverable -- its tail was lost to a killed process -- so readers
-/// skip it with a warning instead of failing every subsequent read forever.
-fn is_torn_prefix(error: &impl std::fmt::Display) -> bool {
- error.to_string().contains("EOF while parsing")
-}
-
/// Whether a JSON string for this value is the value itself.
///
/// serde_json escapes only the quote, the backslash and the C0 controls, so a
@@ -1148,20 +1135,24 @@ pub fn read_transcript_window_with_layout(
match kind {
"message" => match binary_storage::read::<MessageRecord>(trimmed) {
Ok(record) => out.messages.push(record),
- Err(error) if binary_storage::is_error(&error) && !is_torn_prefix(&error) => {
+ Err(error)
+ if binary_storage::is_error(&error) && !binary_storage::is_torn_eof(&error) =>
+ {
return Err(error)
}
- Err(error) if invalid_utf8 || is_torn_prefix(&error) => {
+ Err(error) if invalid_utf8 || binary_storage::is_torn_eof(&error) => {
tracing::warn!(path = %path.display(), %error, "skipping invalid indexed message line");
}
Err(error) => return Err(error).context("decode indexed transcript message"),
},
"compaction" => match binary_storage::read::<CompactionRecord>(trimmed) {
Ok(record) => out.compactions.push(record),
- Err(error) if binary_storage::is_error(&error) && !is_torn_prefix(&error) => {
+ Err(error)
+ if binary_storage::is_error(&error) && !binary_storage::is_torn_eof(&error) =>
+ {
return Err(error)
}
- Err(error) if invalid_utf8 || is_torn_prefix(&error) => {
+ Err(error) if invalid_utf8 || binary_storage::is_torn_eof(&error) => {
tracing::warn!(path = %path.display(), %error, "skipping invalid indexed compaction line");
}
Err(error) => {
@@ -1231,7 +1222,8 @@ pub fn read_transcript_window(
match binary_storage::read::<MessageRecord>(line.trim()) {
Ok(record) => out.messages.push(record),
Err(error)
- if binary_storage::is_error(&error) && !is_torn_prefix(&error) =>
+ if binary_storage::is_error(&error)
+ && !binary_storage::is_torn_eof(&error) =>
{
return Err(error)
}
@@ -1243,7 +1235,9 @@ pub fn read_transcript_window(
}
"compaction" => match binary_storage::read::<CompactionRecord>(line.trim()) {
Ok(record) => out.compactions.push(record),
- Err(error) if binary_storage::is_error(&error) && !is_torn_prefix(&error) => {
+ Err(error)
+ if binary_storage::is_error(&error) && !binary_storage::is_torn_eof(&error) =>
+ {
return Err(error)
}
Err(error) => {
@@ -1865,6 +1859,45 @@ mod tests {
assert_eq!(sequential_ids, ["m1", "m2"]);
}
+ /// Corruption that merely contains "EOF while parsing" as a *value* must
+ /// stay a hard error: a complete, newline-terminated message whose
+ /// binaryStorage version field is that string decodes as InvalidStorage on
+ /// main, and must not be silently dropped as a torn prefix (#2298).
+ #[test]
+ fn complete_encoded_line_with_eof_text_value_is_a_hard_error() {
+ let dir = tempdir().unwrap();
+ append_message(
+ dir.path(),
+ "s1",
+ "2026-07-26T00:00:00Z",
+ &record("m1", "one"),
+ )
+ .unwrap();
+ let path = dir.path().join("sessions").join("s1.jsonl");
+ let mut body = fs::read_to_string(&path).unwrap();
+ body.push_str(
+ r#"{"type":"message","id":"bad","binaryStorage":{"version":"EOF while parsing","data":[],"refs":[],"texts":[]}}"#,
+ );
+ body.push('\n');
+ body.push_str(&tagged("message", &record("m2", "two")).unwrap());
+ body.push('\n');
+ fs::write(&path, body).unwrap();
+ let layout = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();
+
+ let indexed = read_transcript_window_with_layout(dir.path(), "s1", &layout, 0, None);
+ assert!(
+ indexed.is_err(),
+ "a complete structurally-invalid encoded line must fail the read, \
+ not be skipped as a torn prefix"
+ );
+
+ let sequential = read_transcript_window(dir.path(), "s1", 0, None);
+ assert!(
+ sequential.is_err(),
+ "the sequential read must keep the same hard-error behavior"
+ );
+ }
+
fn record(id: &str, text: &str) -> MessageRecord {
MessageRecord {
id: id.into(),
diff --git a/crates/host-core/src/transcripts/binary_storage.rs b/crates/host-core/src/transcripts/binary_storage.rs
index b06f51c49..622425701 100644
--- a/crates/host-core/src/transcripts/binary_storage.rs
+++ b/crates/host-core/src/transcripts/binary_storage.rs
@@ -8,11 +8,33 @@ use std::collections::{HashMap, HashSet};
#[derive(Debug, thiserror::Error)]
#[error("invalid binary storage: {0}")]
struct InvalidStorage(String);
+/// `InvalidStorage` caused by a serde EOF parse error on the encoded line
+/// itself — a crash-truncated torn prefix, not data corruption. Same category
+/// and Display as `InvalidStorage` (so writes keep blocking on it), but
+/// separately downcastable so readers can skip it.
+#[derive(Debug, thiserror::Error)]
+#[error("invalid binary storage: {0}")]
+struct InvalidStorageEof(String);
fn invalid(reason: impl Into<String>) -> anyhow::Error {
InvalidStorage(reason.into()).into()
}
+fn invalid_eof(reason: impl Into<String>) -> anyhow::Error {
+ InvalidStorageEof(reason.into()).into()
+}
pub(super) fn is_error(error: &anyhow::Error) -> bool {
error.downcast_ref::<InvalidStorage>().is_some()
+ || error.downcast_ref::<InvalidStorageEof>().is_some()
+}
+/// Typed classification of a crash-truncated line: either a wrapped
+/// `InvalidStorageEof` from the encoded-line path, or a direct
+/// `serde_json::Error` in the EOF category kept downcastable by `parse_line`.
+/// Never searches `Display` text, so corruption errors that merely contain
+/// "EOF while parsing" as a value stay hard errors.
+pub(super) fn is_torn_eof(error: &anyhow::Error) -> bool {
+ error.downcast_ref::<InvalidStorageEof>().is_some()
+ || error
+ .downcast_ref::<serde_json::Error>()
+ .is_some_and(serde_json::Error::is_eof)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
@@ -639,9 +661,17 @@ pub(crate) fn decode(mut value: Value) -> Result<Value> {
fn parse_line(text: &str) -> Result<Value> {
serde_json::from_str(text).map_err(|e| {
if text.contains("\"binaryStorage\"") {
- invalid(e.to_string())
+ // Keep the EOF category typed so a crash-truncated torn prefix can
+ // be distinguished from real corruption by `is_torn_eof`, instead
+ // of searching the Display text for "EOF while parsing".
+ if e.is_eof() {
+ invalid_eof(e.to_string())
+ } else {
+ invalid(e.to_string())
+ }
} else {
- anyhow!(e)
+ // Store the serde error itself so its EOF category stays typed.
+ anyhow::Error::new(e)
}
})
}