Skip to content

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

perf(store): scope the append idempotency lookup to core-minted ids

Shanu1fd788f95af5
diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.md
index fd327d54ad..78a27cc951 100644
--- a/gitbooks/developing/architecture/agent-harness.md
+++ b/gitbooks/developing/architecture/agent-harness.md
@@ -288,7 +288,7 @@ The child run itself still uses the same runner:
`wait_subagent` and `steer_subagent` accept either the durable `subagent_session_id` or the transient `task_id`; durable ids are preferred across turns. `list_subagents` shows reusable children for the current parent thread, and `close_subagent` marks a worker non-reusable and cancels it if it is still running. Inline blocking is explicit via `blocking: true`; it is no longer the default.
-The synthesized archetype delegations (`delegate_*`, `build_workflow`, and the other `delegate_name` tools) follow the same contract: they route through the durable async path by default, returning an `[async_subagent_ref]` (with `subagent_session_id` + `task_id`) immediately, and the finished result is inserted into the parent chat as a new system turn via `background_completions`/`background_delivery`. That delivery turn (`task_dispatcher::run_system_turn_on_thread`, the same runner autonomous task sessions use) persists its own closing message — `sender: "agent"`, id `agent:<run_id>`, `extraMetadata.requestId = run_id` — **before** it emits `chat_done` as `client_id: "system"`; the frontend reuses that id for system turns, so its usual `chat_done` append collapses onto the same row (the conversation store is idempotent by message id) instead of persisting the delivered result a second time (#5933). They fall back to inline blocking automatically when there is no parent agent turn or no chat thread to deliver into (cron/CLI), or when `blocking: true` is passed. Cross-turn continuity comes from three pieces: the per-turn `[active_subagents]` roster merges the live in-memory registry with the durable `subagent_sessions` store (so a cold-booted orchestrator still sees earlier workers); `continue_subagent` falls back from pause checkpoints to the durable store, resuming an idle worker with its persisted history; and a `workflow_proposal` payload found in a finished child's history is persisted as a parent-thread message (`extraMetadata.scope = "workflow_proposal"`) that the frontend rehydrates into the proposal card on thread load.
+The synthesized archetype delegations (`delegate_*`, `build_workflow`, and the other `delegate_name` tools) follow the same contract: they route through the durable async path by default, returning an `[async_subagent_ref]` (with `subagent_session_id` + `task_id`) immediately, and the finished result is inserted into the parent chat as a new system turn via `background_completions`/`background_delivery`. That delivery turn (`task_dispatcher::run_system_turn_on_thread`, the same runner autonomous task sessions use) persists its own closing message — `sender: "agent"`, id `agent:<run_id>`, `extraMetadata.requestId = run_id` — **before** it emits `chat_done` as `client_id: "system"`; the frontend reuses that id for system turns, so its usual `chat_done` append collapses onto the same row (the conversation store is idempotent for these deterministic `agent:`-prefixed ids; every other id is UUID-fresh and keeps the constant-time append path) instead of persisting the delivered result a second time (#5933). They fall back to inline blocking automatically when there is no parent agent turn or no chat thread to deliver into (cron/CLI), or when `blocking: true` is passed. Cross-turn continuity comes from three pieces: the per-turn `[active_subagents]` roster merges the live in-memory registry with the durable `subagent_sessions` store (so a cold-booted orchestrator still sees earlier workers); `continue_subagent` falls back from pause checkpoints to the durable store, resuming an idle worker with its persisted history; and a `workflow_proposal` payload found in a finished child's history is persisted as a parent-thread message (`extraMetadata.scope = "workflow_proposal"`) that the frontend rehydrates into the proposal card on thread load.
### Spawn hierarchy and tiers
diff --git a/src/openhuman/agent/task_session.rs b/src/openhuman/agent/task_session.rs
index 032ff4d8a8..f2014e32fd 100644
--- a/src/openhuman/agent/task_session.rs
+++ b/src/openhuman/agent/task_session.rs
@@ -30,7 +30,7 @@ use serde_json::json;
use crate::openhuman::agent::task_board::TaskBoardCard;
use crate::openhuman::memory::conversations::{
- self as conversations, ConversationMessage, CreateConversationThread,
+ self as conversations, run_reply_message_id, ConversationMessage, CreateConversationThread,
};
/// Label that lands a thread in the Conversations → Tasks tab. Mirrors the
@@ -124,7 +124,9 @@ fn session_title(card: &TaskBoardCard) -> String {
/// the closing `agent` message, so a reopened session shows the outcome.
/// No-op on an empty response. Best-effort: a store failure is logged only.
///
-/// The row is keyed `agent:<run_id>` on purpose. A client viewing the thread
+/// The row is keyed [`run_reply_message_id`] (`agent:<run_id>`) on purpose — a
+/// deterministic id, which is also what makes the store's idempotency lookup
+/// apply to it. A client viewing the thread
/// persists the same reply again from the `chat_done` the run announces, and it
/// reuses this id for `client_id: "system"` turns (`ChatRuntimeProvider`), so
/// the conversation store's id idempotency collapses both writes onto one row
@@ -149,7 +151,7 @@ pub(crate) fn append_final(
workspace_dir,
thread_id,
ConversationMessage {
- id: format!("agent:{run_id}"),
+ id: run_reply_message_id(run_id),
content,
message_type: "text".to_string(),
extra_metadata: json!({
diff --git a/src/openhuman/memory/conversations/mod.rs b/src/openhuman/memory/conversations/mod.rs
index 550635119f..e6eb369aff 100644
--- a/src/openhuman/memory/conversations/mod.rs
+++ b/src/openhuman/memory/conversations/mod.rs
@@ -53,8 +53,8 @@ mod store;
pub use bus::register_conversation_persistence_subscriber;
pub use store::{
- append_message, delete_thread, ensure_thread, get_messages, list_threads, purge_threads,
- update_message, update_thread_labels, update_thread_title, ConversationMessage,
- ConversationMessagePatch, ConversationPurgeStats, ConversationStore, ConversationThread,
- CreateConversationThread, CrossThreadHit,
+ append_message, delete_thread, ensure_thread, get_messages, is_deterministic_message_id,
+ list_threads, purge_threads, run_reply_message_id, update_message, update_thread_labels,
+ update_thread_title, ConversationMessage, ConversationMessagePatch, ConversationPurgeStats,
+ ConversationStore, ConversationThread, CreateConversationThread, CrossThreadHit,
};
diff --git a/src/openhuman/memory/conversations/store/mod.rs b/src/openhuman/memory/conversations/store/mod.rs
index 795989ebab..c775c9a8b6 100644
--- a/src/openhuman/memory/conversations/store/mod.rs
+++ b/src/openhuman/memory/conversations/store/mod.rs
@@ -86,6 +86,6 @@ pub use store::{
ConversationStore,
};
pub use types::{
- ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
- CrossThreadHit,
+ is_deterministic_message_id, run_reply_message_id, ConversationMessage,
+ ConversationMessagePatch, ConversationThread, CreateConversationThread, CrossThreadHit,
};
diff --git a/src/openhuman/memory/conversations/store/store.rs b/src/openhuman/memory/conversations/store/store.rs
index 4dd82060eb..354a5a5bb8 100644
--- a/src/openhuman/memory/conversations/store/store.rs
+++ b/src/openhuman/memory/conversations/store/store.rs
@@ -275,6 +275,36 @@ where
Ok(items)
}
+/// Find one message in a thread's JSONL log by id, without materializing the
+/// whole transcript.
+///
+/// Only the lines whose raw text carries the quoted id are deserialized, so a
+/// lookup costs one parse rather than one per stored message; a line that
+/// merely quotes the id inside its own content is rejected by the `id` check.
+/// Mirrors [`read_jsonl`]'s tolerance of blank and corrupt lines.
+pub(super) fn find_message_by_id(
+ path: &Path,
+ id: &str,
+) -> Result<Option<ConversationMessage>, String> {
+ if !path.exists() {
+ return Ok(None);
+ }
+ let needle = serde_json::to_string(id).map_err(|e| format!("encode message id {id}: {e}"))?;
+ let file = File::open(path).map_err(|e| format!("open {}: {e}", path.display()))?;
+ for (line_no, line) in BufReader::new(file).lines().enumerate() {
+ let line =
+ line.map_err(|e| format!("read {} line {}: {e}", path.display(), line_no + 1))?;
+ if !line.contains(&needle) {
+ continue;
+ }
+ match serde_json::from_str::<ConversationMessage>(&line) {
+ Ok(message) if message.id == id => return Ok(Some(message)),
+ _ => continue,
+ }
+ }
+ Ok(None)
+}
+
/// Append one serialized value as a JSONL line, fsync'd before returning.
pub(super) fn append_jsonl<T>(path: &Path, value: &T) -> Result<(), String>
where
diff --git a/src/openhuman/memory/conversations/store/store_ops.rs b/src/openhuman/memory/conversations/store/store_ops.rs
index d657f75a8f..a96322dc58 100644
--- a/src/openhuman/memory/conversations/store/store_ops.rs
+++ b/src/openhuman/memory/conversations/store/store_ops.rs
@@ -6,13 +6,13 @@
use std::fs;
use super::super::types::{
- ConversationMessage, ConversationMessagePatch, ConversationThread, CreateConversationThread,
- CrossThreadHit,
+ is_deterministic_message_id, ConversationMessage, ConversationMessagePatch, ConversationThread,
+ CreateConversationThread, CrossThreadHit,
};
use super::{
- append_jsonl, normalize_labels, read_jsonl, rewrite_jsonl, ConversationPurgeStats,
- ConversationStore, ThreadLogEntry, CONVERSATION_INDEX_CACHE, CONVERSATION_STORE_LOCK,
- THREADS_FILENAME,
+ append_jsonl, find_message_by_id, normalize_labels, read_jsonl, rewrite_jsonl,
+ ConversationPurgeStats, ConversationStore, ThreadLogEntry, CONVERSATION_INDEX_CACHE,
+ CONVERSATION_STORE_LOCK, THREADS_FILENAME,
};
impl ConversationStore {
@@ -116,14 +116,21 @@ impl ConversationStore {
/// that stat trail against the message file, repairing a crash between the
/// two appends.
///
- /// Idempotent by `message.id`: when the thread already holds a row with
- /// that id, nothing is written (no message row, no stat bump, no index
+ /// Idempotent for the ids the core mints deterministically
+ /// ([`is_deterministic_message_id`]): when the thread already holds a row
+ /// with that id, nothing is written (no message row, no stat bump, no index
/// insert) and the stored row is returned exactly as a fresh append would
/// return its input. Two writers can legitimately persist the same reply —
/// an autonomous run's `task_session::append_final` and the client that
/// also persists the `chat_done` it announced (#5933) — and a thread must
/// never carry two messages under one id (the frontend keys React and
/// assistant-ui resources by it).
+ ///
+ /// The lookup is deliberately narrow. Every other id in the store is
+ /// UUID-fresh by construction and cannot be re-presented, so it must not
+ /// pay to have that verified: a lookup on *every* append would put a scan
+ /// of the thread's transcript on the hot write path, under the
+ /// process-wide store lock, and make growing a thread quadratic.
pub fn append_message(
&self,
thread_id: &str,
@@ -134,11 +141,8 @@ impl ConversationStore {
return Err(format!("thread {} not found", thread_id));
}
let path = self.thread_messages_path(thread_id);
- if path.exists() {
- if let Some(existing) = read_jsonl::<ConversationMessage>(&path)?
- .into_iter()
- .find(|stored| stored.id == message.id)
- {
+ if is_deterministic_message_id(&message.id) {
+ if let Some(existing) = find_message_by_id(&path, &message.id)? {
return Ok(existing);
}
}
diff --git a/src/openhuman/memory/conversations/store/store_tests.rs b/src/openhuman/memory/conversations/store/store_tests.rs
index d00357271e..a9a982c07d 100644
--- a/src/openhuman/memory/conversations/store/store_tests.rs
+++ b/src/openhuman/memory/conversations/store/store_tests.rs
@@ -100,6 +100,87 @@ fn append_message_is_idempotent_by_message_id() {
assert_eq!(threads[0].last_message_at, "2026-04-10T12:01:00Z");
}
+#[test]
+fn append_message_does_not_dedupe_client_generated_ids() {
+ // The idempotency lookup is scoped to the ids the core mints
+ // deterministically. Client-generated ids are UUID-fresh per message, so
+ // paying a transcript scan to verify that on every append would put a
+ // quadratic write path under the process-wide store lock — the store takes
+ // them at face value instead.
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t".to_string(),
+ title: "Conversation".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+ let message = ConversationMessage {
+ id: "user:5f1d0c3e-1f8b-4c1a-9c2e-2a7b6d4e8f90".to_string(),
+ content: "hello".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ };
+ store.append_message("t", message.clone()).expect("append");
+ store.append_message("t", message).expect("append again");
+
+ assert_eq!(store.get_messages("t").expect("get messages").len(), 2);
+}
+
+#[test]
+fn append_message_idempotency_ignores_an_id_quoted_inside_content() {
+ // The lookup narrows candidate lines by raw text before parsing them; a
+ // message that merely *quotes* another message's id must not be mistaken
+ // for that message and swallow the real append.
+ let (_temp, store) = make_store();
+ store
+ .ensure_thread(CreateConversationThread {
+ parent_thread_id: None,
+ id: "t".to_string(),
+ title: "Conversation".to_string(),
+ created_at: "2026-04-10T12:00:00Z".to_string(),
+ labels: None,
+ personality_id: None,
+ })
+ .expect("ensure thread");
+ store
+ .append_message(
+ "t",
+ ConversationMessage {
+ id: "user:1".to_string(),
+ content: "agent:run-9".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "user".to_string(),
+ created_at: "2026-04-10T12:01:00Z".to_string(),
+ },
+ )
+ .expect("append quoting message");
+ let stored = store
+ .append_message(
+ "t",
+ ConversationMessage {
+ id: "agent:run-9".to_string(),
+ content: "the real reply".to_string(),
+ message_type: "text".to_string(),
+ extra_metadata: json!({}),
+ sender: "agent".to_string(),
+ created_at: "2026-04-10T12:02:00Z".to_string(),
+ },
+ )
+ .expect("append reply");
+
+ assert_eq!(stored.content, "the real reply");
+ let messages = store.get_messages("t").expect("get messages");
+ assert_eq!(messages.len(), 2);
+ assert_eq!(messages[1].id, "agent:run-9");
+}
+
#[test]
fn get_messages_for_new_empty_thread_returns_empty_list() {
let (_temp, store) = make_store();
diff --git a/src/openhuman/memory/conversations/store/types.rs b/src/openhuman/memory/conversations/store/types.rs
index e81ec16e68..665938f86d 100644
--- a/src/openhuman/memory/conversations/store/types.rs
+++ b/src/openhuman/memory/conversations/store/types.rs
@@ -115,6 +115,38 @@ pub struct CrossThreadHit {
pub score: f64,
}
+/// Prefix of the message ids the core mints **deterministically** rather than
+/// from a fresh UUID.
+///
+/// Only such an id can be presented to the store twice by two different
+/// writers, so it is also the marker
+/// [`is_deterministic_message_id`] keys the store's idempotency lookup on.
+pub const DETERMINISTIC_MESSAGE_ID_PREFIX: &str = "agent:";
+
+/// The id an autonomous run's closing reply is stored under.
+///
+/// Two writers legitimately persist that one reply — the core's
+/// `task_session::append_final` and the client that also persists the
+/// `chat_done` the run announces (`ChatRuntimeProvider` mirrors this shape for
+/// `client_id: "system"` turns) — so both must derive the same id and the store
+/// must collapse the second write onto the first (#5933).
+pub fn run_reply_message_id(run_id: &str) -> String {
+ format!("{DETERMINISTIC_MESSAGE_ID_PREFIX}{run_id}")
+}
+
+/// Whether `id` is one the core mints deterministically, i.e. one a second
+/// writer can legitimately present again.
+///
+/// This is what buys back the constant-time append path: every other id in the
+/// store is UUID-fresh by construction (`user:<uuid>`, `<sender>:<uuid>`), can
+/// never be re-presented, and so must not pay for a duplicate lookup. The
+/// `agent:<uuid>` ids the subagent/worker-thread writers mint do match — they
+/// pay for a lookup they can never hit, which is one cheap scan of a
+/// two-message worker transcript.
+pub fn is_deterministic_message_id(id: &str) -> bool {
+ id.starts_with(DETERMINISTIC_MESSAGE_ID_PREFIX)
+}
+
#[cfg(test)]
#[path = "types_tests.rs"]
mod tests;
diff --git a/src/openhuman/memory/conversations/store/types_tests.rs b/src/openhuman/memory/conversations/store/types_tests.rs
index 50fee0305a..eb14f876fe 100644
--- a/src/openhuman/memory/conversations/store/types_tests.rs
+++ b/src/openhuman/memory/conversations/store/types_tests.rs
@@ -63,3 +63,24 @@ fn create_thread_optional_fields_roundtrip() {
);
assert!(decoded.parent_thread_id.is_none());
}
+
+#[test]
+fn run_reply_id_is_deterministic_and_recognised_as_such() {
+ // The producer (`task_session::append_final`) and the predicate the store
+ // gates its idempotency lookup on must agree, or the two writers of an
+ // autonomous reply stop collapsing onto one row (#5933).
+ assert_eq!(run_reply_message_id("run-7"), "agent:run-7");
+ assert!(is_deterministic_message_id(&run_reply_message_id("run-7")));
+}
+
+#[test]
+fn client_generated_ids_are_not_deterministic() {
+ // These are UUID-fresh per message, so they can never be re-presented and
+ // must keep the constant-time append path.
+ assert!(!is_deterministic_message_id(
+ "user:5f1d0c3e-1f8b-4c1a-9c2e-2a7b6d4e8f90"
+ ));
+ assert!(!is_deterministic_message_id(
+ "assistant:5f1d0c3e-1f8b-4c1a-9c2e-2a7b6d4e8f90"
+ ));
+}