Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): keep replayed transcript rows' request id and failure flag on resume

M3gA-Minddb5611b78044
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
index a93023f153..42f9644711 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
+++ b/crates/openhuman-core/src/agent/harness/session/runtime/resume.rs
@@ -54,7 +54,7 @@ impl Agent {
Vec::with_capacity(prior.len() + 1);
cached.push(crate::agent::messages::ChatMessage::system(system_prompt));
for (role, content) in prior {
- let chat = match role.as_str() {
+ let mut chat = match role.as_str() {
"user" => crate::agent::messages::ChatMessage::user(content),
"agent" | "assistant" => crate::agent::messages::ChatMessage::assistant(content),
// Fall back to user role for unknown senders rather than
@@ -62,6 +62,10 @@ impl Agent {
// mislabelling a system/tool message.
_ => crate::agent::messages::ChatMessage::user(content),
};
+ // The conversation log records no request id for these rows, and
+ // they belong to earlier turns: mark them so persisting them with the
+ // next turn does not attribute them to that turn's request (#6282).
+ crate::agent::harness::session::transcript::attach_replayed_metadata(&mut chat, None);
cached.push(chat);
}
diff --git a/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
index a8bedc2344..62a0956019 100644
--- a/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
@@ -357,6 +357,62 @@ fn seed_resume_from_messages_primes_cached_transcript() {
assert_eq!(cached[2].content, "$80,000");
}
+/// #6282: rows seeded from the conversation log belong to earlier turns and
+/// carry no request id, so persisting them together with the next turn must
+/// not stamp them with that turn's request.
+#[test]
+fn prose_seeded_rows_are_not_restamped_with_the_resuming_request() {
+ use crate::agent::harness::session::transcript::{
+ append_transcript_turn, read_transcript_display, DisplayRecord,
+ };
+ use crate::agent::messages::ChatMessage;
+
+ let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
+ agent
+ .seed_resume_from_messages(
+ vec![
+ ("user".to_string(), "install it".to_string()),
+ ("agent".to_string(), "Something went wrong.".to_string()),
+ ],
+ "what happened?",
+ )
+ .expect("seed");
+ let mut messages = agent
+ .cached_transcript_messages
+ .clone()
+ .expect("cache populated");
+ messages.push(ChatMessage::user("what happened?"));
+
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let path = dir.path().join("seeded.jsonl");
+ append_transcript_turn(
+ &path,
+ &[],
+ &messages,
+ &fake_transcript_meta("thr_seeded"),
+ None,
+ Some("req-now"),
+ )
+ .expect("persist seeded turn");
+
+ let rows: Vec<(String, Option<String>)> = read_transcript_display(&path)
+ .expect("display read")
+ .records
+ .into_iter()
+ .filter_map(|record| match record {
+ DisplayRecord::Message(m) => Some((m.message.content, m.request_id)),
+ _ => None,
+ })
+ .collect();
+ let ids: Vec<Option<&str>> = rows.iter().map(|(_, id)| id.as_deref()).collect();
+ assert_eq!(
+ ids,
+ vec![Some("req-now"), None, None, Some("req-now")],
+ "only this turn's rows (the freshly built system prompt and the new user \
+ message) take its request id: {rows:?}"
+ );
+}
+
/// `seed_resume_from_messages` must not stomp the existing context if
/// the agent has already been warmed (in-process session cache hit).
/// Otherwise the cache-miss branch in the web channel would erase
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript.rs b/crates/openhuman-core/src/agent/harness/session/transcript.rs
index a7f12b4304..cd217e606e 100644
--- a/crates/openhuman-core/src/agent/harness/session/transcript.rs
+++ b/crates/openhuman-core/src/agent/harness/session/transcript.rs
@@ -117,6 +117,7 @@ mod types;
mod writer;
pub use legacy_md::read_transcript_legacy_md;
+pub(crate) use metadata::attach_replayed_metadata;
pub(crate) use metadata::attach_tool_failure_metadata;
#[cfg(test)]
pub(crate) use metadata::attach_turn_usage_metadata;
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs b/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
index d213f543ae..0ef25ea1e5 100644
--- a/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/jsonl.rs
@@ -2,7 +2,10 @@
//! conversions between them and the public [`ChatMessage`] /
//! [`TranscriptMeta`] / [`DisplayMessage`] types.
-use super::metadata::{attach_turn_usage_metadata, take_tool_failure};
+use super::metadata::{
+ attach_replayed_metadata, attach_tool_failure_metadata, attach_turn_usage_metadata,
+ take_replayed_request_id, take_tool_failure,
+};
use super::types::{
DisplayMessage, MessageUsage, TranscriptMeta, TurnUsage, TRANSCRIPT_SCHEMA_VERSION,
};
@@ -185,6 +188,12 @@ pub(super) fn build_message_line(
Some((failed, detail)) => (failed, detail),
None => (false, None),
};
+ // A row replayed from an earlier turn keeps the request it was first
+ // written under; only this turn's own rows take `request_id` (#6282).
+ let request_id = match take_replayed_request_id(&mut extra_metadata) {
+ Some(original) => original,
+ None => request_id.map(str::to_string),
+ };
let message_reasoning = (msg.role == "assistant")
.then(|| {
extra_metadata
@@ -229,7 +238,7 @@ pub(super) fn build_message_line(
}),
iteration: assistant_usage.map(|tu| tu.iteration),
ts: assistant_usage.map(|tu| tu.ts.clone()),
- request_id: request_id.map(str::to_string),
+ request_id,
interrupted,
failure,
failure_detail,
@@ -312,6 +321,8 @@ fn turn_usage_from_line(ml: &MessageLine) -> Option<TurnUsage> {
/// metadata so the round-trip is lossless for the model-context path.
pub(super) fn message_from_line(ml: MessageLine) -> ChatMessage {
let turn_usage = turn_usage_from_line(&ml);
+ let failure_detail = ml.failure.then(|| ml.failure_detail.clone());
+ let request_id = ml.request_id.clone();
let mut message = ChatMessage {
id: ml.id,
role: ml.role,
@@ -322,6 +333,17 @@ pub(super) fn message_from_line(ml: MessageLine) -> ChatMessage {
if let Some(turn_usage) = turn_usage.as_ref() {
attach_turn_usage_metadata(&mut message, turn_usage);
}
+ // Carry what the line recorded about the turn that wrote it back onto the
+ // message, so re-persisting it (a resume into a fresh transcript) writes the
+ // same `failure` flag and `request_id` instead of losing the flag and
+ // restamping the row with the resuming request (#6282). A line with neither
+ // reads back exactly as it was written.
+ if let Some(detail) = failure_detail {
+ attach_tool_failure_metadata(&mut message, detail.as_deref());
+ }
+ if let Some(request_id) = request_id.as_deref() {
+ attach_replayed_metadata(&mut message, Some(request_id));
+ }
message
}
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs b/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
index 882a293ea6..c3c65fc21b 100644
--- a/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
+++ b/crates/openhuman-core/src/agent/harness/session/transcript/metadata.rs
@@ -17,40 +17,72 @@ const TURN_USAGE_METADATA_KEY: &str = "openhuman_turn_usage";
/// fields and strips it from the persisted `extra_metadata`.
const TOOL_FAILURE_METADATA_KEY: &str = "openhuman_tool_failure";
-/// Stamp a tool-result [`ChatMessage`] with its failure outcome so the
-/// transcript writer can persist an explicit failure flag. `detail` is an
-/// optional short, single-line reason (e.g. the head of the error output).
-/// No-op semantics: pass this only for genuinely failed tool calls.
-pub(crate) fn attach_tool_failure_metadata(message: &mut ChatMessage, detail: Option<&str>) {
- let mut payload = serde_json::Map::new();
- payload.insert("failure".to_string(), serde_json::Value::Bool(true));
- if let Some(detail) = detail.map(str::trim).filter(|s| !s.is_empty()) {
- payload.insert(
- "detail".to_string(),
- serde_json::Value::String(detail.to_string()),
- );
- }
- let marker = serde_json::Value::Object(payload);
+/// `extra_metadata` key marking a message **replayed from an earlier turn**: a
+/// row read back from a transcript, or a message seeded from the conversation
+/// log on cold boot. It carries the `request_id` the row was first written with
+/// (`null` when it had none). The writer stamps a replayed row with that
+/// original id instead of the current turn's, so resuming a thread into a fresh
+/// transcript file does not re-attribute every earlier turn's rows to the
+/// resuming request (#6282). Stripped from the persisted `extra_metadata`, like
+/// the failure marker.
+const REPLAYED_METADATA_KEY: &str = "openhuman_replayed";
+/// Insert `value` under `key` in `message.extra_metadata`, wrapping a
+/// non-object value under `"value"` so nothing already there is lost.
+fn insert_metadata(message: &mut ChatMessage, key: &str, value: serde_json::Value) {
match message.extra_metadata.take() {
Some(serde_json::Value::Object(mut map)) => {
- map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);
+ map.insert(key.to_string(), value);
message.extra_metadata = Some(serde_json::Value::Object(map));
}
Some(existing) => {
let mut map = serde_json::Map::new();
map.insert("value".to_string(), existing);
- map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);
+ map.insert(key.to_string(), value);
message.extra_metadata = Some(serde_json::Value::Object(map));
}
None => {
let mut map = serde_json::Map::new();
- map.insert(TOOL_FAILURE_METADATA_KEY.to_string(), marker);
+ map.insert(key.to_string(), value);
message.extra_metadata = Some(serde_json::Value::Object(map));
}
}
}
+/// Pop `key` out of a cloned `extra_metadata` map. If removing it emptied the
+/// object, drop `extra_metadata` entirely so a legacy-identical line stays
+/// legacy-identical.
+fn take_metadata(extra: &mut Option<serde_json::Value>, key: &str) -> Option<serde_json::Value> {
+ let serde_json::Value::Object(map) = extra.as_mut()? else {
+ return None;
+ };
+ let value = map.remove(key)?;
+ if map.is_empty() {
+ *extra = None;
+ }
+ Some(value)
+}
+
+/// Stamp a tool-result [`ChatMessage`] with its failure outcome so the
+/// transcript writer can persist an explicit failure flag. `detail` is an
+/// optional short, single-line reason (e.g. the head of the error output).
+/// No-op semantics: pass this only for genuinely failed tool calls.
+pub(crate) fn attach_tool_failure_metadata(message: &mut ChatMessage, detail: Option<&str>) {
+ let mut payload = serde_json::Map::new();
+ payload.insert("failure".to_string(), serde_json::Value::Bool(true));
+ if let Some(detail) = detail.map(str::trim).filter(|s| !s.is_empty()) {
+ payload.insert(
+ "detail".to_string(),
+ serde_json::Value::String(detail.to_string()),
+ );
+ }
+ insert_metadata(
+ message,
+ TOOL_FAILURE_METADATA_KEY,
+ serde_json::Value::Object(payload),
+ );
+}
+
/// Pop the tool-failure marker out of a cloned `extra_metadata` map, returning
/// `Some((true, detail))` when it was present. Strips the key so it is not
/// duplicated into the persisted `extra_metadata` alongside the top-level
@@ -58,15 +90,7 @@ pub(crate) fn attach_tool_failure_metadata(message: &mut ChatMessage, detail: Op
pub(super) fn take_tool_failure(
extra: &mut Option<serde_json::Value>,
) -> Option<(bool, Option<String>)> {
- let serde_json::Value::Object(map) = extra.as_mut()? else {
- return None;
- };
- let marker = map.remove(TOOL_FAILURE_METADATA_KEY)?;
- // If removing the marker emptied the object, drop `extra_metadata` entirely
- // so a legacy-identical line stays legacy-identical.
- if map.is_empty() {
- *extra = None;
- }
+ let marker = take_metadata(extra, TOOL_FAILURE_METADATA_KEY)?;
let detail = marker
.get("detail")
.and_then(|d| d.as_str())
@@ -74,29 +98,38 @@ pub(super) fn take_tool_failure(
Some((true, detail))
}
+/// Mark `message` as replayed from an earlier turn whose request was
+/// `request_id` (`None` when that turn recorded none). See
+/// [`REPLAYED_METADATA_KEY`].
+pub(crate) fn attach_replayed_metadata(message: &mut ChatMessage, request_id: Option<&str>) {
+ insert_metadata(
+ message,
+ REPLAYED_METADATA_KEY,
+ serde_json::json!({ "request_id": request_id }),
+ );
+}
+
+/// Pop the replayed marker out of a cloned `extra_metadata` map, returning
+/// `Some(original_request_id)` when the message was replayed and `None` when it
+/// belongs to the turn being written.
+pub(super) fn take_replayed_request_id(
+ extra: &mut Option<serde_json::Value>,
+) -> Option<Option<String>> {
+ let marker = take_metadata(extra, REPLAYED_METADATA_KEY)?;
+ Some(
+ marker
+ .get("request_id")
+ .and_then(|id| id.as_str())
+ .map(str::to_string),
+ )
+}
+
pub(crate) fn attach_turn_usage_metadata(message: &mut ChatMessage, turn_usage: &TurnUsage) {
let Ok(payload) = serde_json::to_value(turn_usage) else {
log::warn!("[transcript] failed to serialize turn usage metadata");
return;
};
-
- match message.extra_metadata.take() {
- Some(serde_json::Value::Object(mut map)) => {
- map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);
- message.extra_metadata = Some(serde_json::Value::Object(map));
- }
- Some(existing) => {
- let mut map = serde_json::Map::new();
- map.insert("value".to_string(), existing);
- map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);
- message.extra_metadata = Some(serde_json::Value::Object(map));
- }
- None => {
- let mut map = serde_json::Map::new();
- map.insert(TURN_USAGE_METADATA_KEY.to_string(), payload);
- message.extra_metadata = Some(serde_json::Value::Object(map));
- }
- }
+ insert_metadata(message, TURN_USAGE_METADATA_KEY, payload);
}
pub(crate) fn turn_usage_extra_metadata(turn_usage: &TurnUsage) -> Option<serde_json::Value> {
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs
index 2266501126..1b67a47604 100644
--- a/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/transcript_thread_and_append_tests.rs
@@ -523,6 +523,69 @@ fn request_id_stamped_on_every_line() {
assert_eq!(msgs[2].message.content, "a2");
}
+/// #6282: rows read back from a transcript and persisted into a fresh file (a
+/// resume into a rebuilt agent) keep the request they were first written under
+/// and their tool-failure flag; only the resuming turn's own rows take its
+/// request id.
+#[test]
+fn resumed_rows_keep_their_request_id_and_failure_flag() {
+ let dir = TempDir::new().unwrap();
+ let meta = sample_meta();
+
+ let mut failed_tool =
+ ChatMessage::tool(r#"{"tool_call_id":"call-1","content":"install failed"}"#);
+ attach_tool_failure_metadata(&mut failed_tool, Some("install failed"));
+ let first = dir.path().join("first.jsonl");
+ let turn1 = vec![
+ ChatMessage::system("sys"),
+ ChatMessage::user("install it"),
+ failed_tool,
+ ChatMessage::assistant("it failed"),
+ ];
+ AppendHarness::new(first.clone()).turn(&turn1, &meta, None, Some("req-1"));
+
+ // Resume into a rebuilt agent: the prior rows come back through the
+ // model-context reader and are persisted into a new file with the next turn.
+ let mut resumed = read_transcript(&first).unwrap().messages;
+ resumed.push(ChatMessage::user("what happened?"));
+ let second = dir.path().join("second.jsonl");
+ AppendHarness::new(second.clone()).turn(&resumed, &meta, None, Some("req-2"));
+
+ let msgs: Vec<DisplayMessage> = read_transcript_display(&second)
+ .unwrap()
+ .records
+ .into_iter()
+ .filter_map(|r| match r {
+ DisplayRecord::Message(m) => Some(m),
+ _ => None,
+ })
+ .collect();
+ let ids: Vec<Option<&str>> = msgs.iter().map(|m| m.request_id.as_deref()).collect();
+ assert_eq!(
+ ids,
+ vec![
+ Some("req-1"),
+ Some("req-1"),
+ Some("req-1"),
+ Some("req-1"),
+ Some("req-2")
+ ],
+ "replayed rows keep the request that wrote them"
+ );
+ let tool = msgs
+ .iter()
+ .find(|m| m.message.role == "tool")
+ .expect("replayed tool row");
+ assert!(tool.failure, "a replayed failed tool row stays failed");
+ assert_eq!(tool.failure_detail.as_deref(), Some("install failed"));
+ // The markers are an in-memory side-channel: neither reaches the file.
+ let raw = fs::read_to_string(&second).unwrap();
+ assert!(
+ !raw.contains("openhuman_replayed") && !raw.contains("openhuman_tool_failure"),
+ "side-channel markers must not be persisted: {raw}"
+ );
+}
+
/// An interrupted partial is appended to the file, is visible in the display
/// read flagged `interrupted`, and is SKIPPED by the model-context read (a
/// resumed context never carries a truncated answer).
diff --git a/crates/openhuman-core/src/agent/session_import/live_tests.rs b/crates/openhuman-core/src/agent/session_import/live_tests.rs
index e046eeb542..3e50eb3981 100644
--- a/crates/openhuman-core/src/agent/session_import/live_tests.rs
+++ b/crates/openhuman-core/src/agent/session_import/live_tests.rs
@@ -76,11 +76,10 @@ fn turn_usage() -> TurnUsage {
/// A multi-turn session whose messages carry the sidecar `extra_metadata` the
/// single-turn happy-path fixture cannot express: a system message, a failed
/// `tool` message tagged with `openhuman_tool_failure`, two assistant turns, and
-/// the trailing assistant that this turn's usage attaches to. The tool-failure
-/// marker is the deterministic asymmetry for #6149 — `write_transcript` strips it
-/// onto the line's top-level `failure`/`failure_detail` fields and the read-back
-/// never restores it to `extra_metadata`, so an in-memory reconstruction keeps a
-/// key the legacy JSONL round-trip has dropped.
+/// the trailing assistant that this turn's usage attaches to. The writer lifts
+/// the tool-failure marker onto the line's top-level `failure`/`failure_detail`
+/// fields, and since #6282 the read-back restores it to `extra_metadata`, so the
+/// marker round-trips.
fn rich_base_messages() -> Vec<ChatMessage> {
let mut failed_tool = ChatMessage::tool("read_file failed: boom");
attach_tool_failure_metadata(&mut failed_tool, Some("boom"));
@@ -279,11 +278,15 @@ async fn shadow_read_roundtrip_matches_legacy() {
/// Regression guard for #6149. Building the store record from the *in-memory*
/// turn — the pre-fix `maybe_dual_write_session_store` behaviour — instead of
/// mirroring `read_transcript` diverges on sidecar `extra_metadata` even though
-/// every message body, id and role is byte-identical. Here the
-/// `openhuman_tool_failure` marker survives on the in-memory tool message while
-/// the legacy JSONL round-trip drops it, so the shadow reader reports a
-/// divergence at that message. The fix mirrors the round-tripped read, which is
-/// why `shadow_read_roundtrip_matches_legacy` above stays a clean `Match`.
+/// every message body, id and role is byte-identical. The read-back carries
+/// sidecar state the in-memory turn never had: every row persisted under a
+/// request id reads back with the `openhuman_replayed` provenance marker (#6282),
+/// so the shadow reader reports a divergence from the first row. The fix mirrors
+/// the round-tripped read, which is why `shadow_read_roundtrip_matches_legacy`
+/// above stays a clean `Match`.
+///
+/// This used to pin the tool-failure marker instead, which the read-back
+/// dropped; #6282 made that marker round-trip, removing that asymmetry.
#[tokio::test]
async fn in_memory_store_reconstruction_diverges_from_legacy_on_sidecar_metadata() {
let ws = TempDir::new().expect("tempdir");
@@ -294,7 +297,17 @@ async fn in_memory_store_reconstruction_diverges_from_legacy_on_sidecar_metadata
let meta = meta("t-root");
let usage = turn_usage();
- write_transcript(&jsonl_path, &base_messages, &meta, Some(&usage)).expect("legacy write");
+ // Legacy write the way `persist_session_transcript` does it: append-only,
+ // stamped with the turn's request id.
+ crate::agent::harness::session::transcript::append_transcript_turn(
+ &jsonl_path,
+ &[],
+ &base_messages,
+ &meta,
+ Some(&usage),
+ Some("req-1"),
+ )
+ .expect("legacy write");
// Pre-fix store construction: clone the in-memory turn, attach usage to the
// last assistant, and mirror THAT — never round-tripping through the JSONL,
@@ -316,25 +329,29 @@ async fn in_memory_store_reconstruction_diverges_from_legacy_on_sidecar_metadata
let legacy = read_transcript(&jsonl_path).expect("read legacy transcript");
let outcome = shadow_read_compare(ws.path(), stem, &legacy).await;
- // Pin the divergence to the tool-failure message specifically. `Some(_)`
- // would also accept a mismatch at any other index — including a count
- // mismatch, which `first_diff` reports as the shorter length — so it could
- // pass for a reason that has nothing to do with the dropped sidecar key.
- // Both sides must render every fixture message, and the first difference
- // must be the `tool` message carrying `openhuman_tool_failure`.
+ // Pin the divergence to the provenance marker specifically. `Some(_)`
+ // would also accept a count mismatch, which `first_diff` reports as the
+ // shorter length, so it could pass for a reason unrelated to sidecar
+ // metadata. Both sides must render every fixture message, the first
+ // difference must be the first row, and that row's only legacy-side extra
+ // must be the `openhuman_replayed` marker.
let rendered = base_messages.len();
- let tool_failure_idx = base_messages
- .iter()
- .position(|m| m.role == "tool")
- .expect("tool message present");
+ assert!(
+ legacy.messages[0]
+ .extra_metadata
+ .as_ref()
+ .is_some_and(|meta| meta.get("openhuman_replayed").is_some()),
+ "the legacy read-back must carry the replayed provenance marker: {:?}",
+ legacy.messages[0].extra_metadata
+ );
assert_eq!(
outcome,
ShadowReadOutcome::Divergence {
legacy: rendered,
shadow: rendered,
- first_diff: Some(tool_failure_idx),
+ first_diff: Some(0),
},
- "the in-memory reconstruction must diverge on the dropped tool-failure marker at index {tool_failure_idx}, with both sides rendering {rendered} messages"
+ "the in-memory reconstruction must diverge on the replayed provenance marker at index 0, with both sides rendering {rendered} messages"
);
}