Skip to content

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

chore: files changed crates/openhuman-core/src/agent/session_host/runtime_session.rs,crates/openhuma

Steven Enamakel07e8806744a7
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index ced685c839..dfd4a8cd64 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -9,6 +9,7 @@
mod attachment_input;
mod memory_ingest;
mod permanent;
+mod post_commit;
mod tool_rules;
#[path = "runtime_session_turn.rs"]
mod turn;
@@ -59,6 +60,10 @@ pub(super) struct OpenHumanSessionState {
pub(super) reply_language_directive: Option<String>,
pub(super) time_zone: Option<String>,
prelude: Option<OpenHumanTurnPrelude>,
+ /// The previous turn's deferred post-commit work (thread-goal
+ /// accounting). The next turn awaits it before loading the goal
+ /// (`post_commit::await_pending`).
+ pending_post_commit: Option<tokio::task::JoinHandle<()>>,
}
/// Owned host-only inputs used by the async runtime preparation hook.
@@ -1098,6 +1103,14 @@ impl OpenHumanSessionHost {
"OpenHumanTurnPrelude",
)
})?;
+ // The previous turn's goal accounting was deferred past
+ // its completion; settle it before this turn reads the goal.
+ let pending_post_commit = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .pending_post_commit
+ .take();
+ post_commit::await_pending(pending_post_commit).await;
let new_session = !view.resumed && view.history.is_empty();
prelude
.refresh_turn_boundary(new_session)
@@ -1228,13 +1241,7 @@ impl OpenHumanSessionHost {
let agent_id = agent_id.clone();
let channel = channel.clone();
Box::pin(async move {
- let iterations = receipt
- .outcome
- .history
- .iter()
- .filter(|message| matches!(message, Message::Assistant(_)))
- .count()
- .max(1) as u32;
+ let commit_started = std::time::Instant::now();
let output = receipt.outcome.output.clone().unwrap_or_default();
// Skips compaction checkpoints (user-role, not the user's words).
let input =
@@ -1248,6 +1255,20 @@ impl OpenHumanSessionHost {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
+ // This turn's model calls, not every assistant row of the
+ // whole conversation (`post_commit::turn_iterations`).
+ let iterations = post_commit::turn_iterations(
+ sidecar.model_calls,
+ &receipt.outcome.history,
+ );
+ tracing::debug!(
+ session_id = %session_id,
+ iterations,
+ commit_ms = ?sidecar
+ .driver_finished_at
+ .map(|at| commit_started.saturating_duration_since(at).as_millis() as u64),
+ "[session-runtime] post-commit: durable commit done; finalizing turn"
+ );
let usage = holistic_last_turn_usage(&sidecar);
let interrupted = sidecar.hit_cap || receipt.outcome.interrupted;
let tool_calls = sidecar
@@ -1269,33 +1290,59 @@ impl OpenHumanSessionHost {
.duration
.map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
.unwrap_or_default();
- let prelude = state
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .prelude
- .clone();
+ // State the caller reads as soon as `run_turn` returns.
+ let prelude = {
+ let mut state = state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ state.last_turn_hit_cap = interrupted;
+ state.last_turn_usage = Some(usage);
+ state.prelude.clone()
+ };
+ // Completion first: `TurnCompleted` is the progress
+ // bridge's drain fence, and nothing below gates it. Goal
+ // accounting runs after it in the background; the next
+ // turn awaits it before reading the goal.
+ let goal_accounting = {
+ let prelude = prelude.clone();
+ let thread_id = receipt.options.context.thread_id.clone();
+ let sidecar = sidecar.clone();
+ async move {
+ let Some(prelude) = prelude else {
+ return;
+ };
+ let started = std::time::Instant::now();
+ account_committed_turn_against_goal(
+ &prelude.workspace_dir,
+ thread_id.as_deref(),
+ &sidecar,
+ )
+ .await;
+ tracing::debug!(
+ elapsed_ms = post_commit::elapsed_ms(started),
+ "[session-runtime] post-commit: goal accounting done"
+ );
+ }
+ };
+ let (_, pending) = post_commit::complete_then_defer(
+ progress::send_receipt_progress(&receipt, &input, &output, iterations),
+ goal_accounting,
+ )
+ .await;
if let Some(prelude) = prelude {
+ let started = std::time::Instant::now();
prelude.finalize_after_durable_commit(&receipt).await;
- account_committed_turn_against_goal(
- &prelude.workspace_dir,
- receipt.options.context.thread_id.as_deref(),
- &sidecar,
- )
- .await;
+ tracing::debug!(
+ elapsed_ms = post_commit::elapsed_ms(started),
+ "[session-runtime] post-commit: finalize hooks done"
+ );
}
- let _ =
- progress::send_receipt_progress(&receipt, &input, &output, iterations)
- .await;
- state
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .last_commit = Some(receipt);
{
let mut state = state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
- state.last_turn_hit_cap = interrupted;
- state.last_turn_usage = Some(usage);
+ state.last_commit = Some(receipt);
+ state.pending_post_commit = Some(pending);
}
crate::agent::hooks::fire_hooks(
&post_turn_hooks,
@@ -1310,6 +1357,11 @@ impl OpenHumanSessionHost {
iteration_count: iterations as usize,
},
);
+ tracing::debug!(
+ session_id = %session_id,
+ elapsed_ms = post_commit::elapsed_ms(commit_started),
+ "[session-runtime] post-commit: after_commit hook done"
+ );
Ok(())
})
}
diff --git a/crates/openhuman-core/src/modules/search/proxy_tests.rs b/crates/openhuman-core/src/modules/search/proxy_tests.rs
index 74bf6d4a9a..3a4509c241 100644
--- a/crates/openhuman-core/src/modules/search/proxy_tests.rs
+++ b/crates/openhuman-core/src/modules/search/proxy_tests.rs
@@ -38,3 +38,91 @@ async fn configured_calls_keep_the_lock_through_invocation() {
b.await.unwrap();
assert_eq!(*active.lock().unwrap(), "B");
}
+
+/// A search module whose `ExecuteTool` takes `delay` to answer, like a
+/// provider synthesizing a `web_answer_tool` reply.
+struct SlowSearch {
+ delay: std::time::Duration,
+}
+
+#[async_trait::async_trait]
+impl tinybus::service::Interface for SlowSearch {
+ fn name(&self) -> tinybus::InterfaceName {
+ tinybus::InterfaceName::new(names::INTERFACE).expect("contract interface")
+ }
+
+ fn members(&self) -> Vec<tinybus::MemberName> {
+ vec![tinybus::MemberName::new(names::methods::EXECUTE_TOOL).expect("contract member")]
+ }
+
+ async fn call(
+ &self,
+ _member: &tinybus::MemberName,
+ _args: serde_json::Value,
+ ) -> tinybus::Result<serde_json::Value> {
+ tokio::time::sleep(self.delay).await;
+ Ok(serde_json::json!({ "answered": true }))
+ }
+}
+
+async fn slow_search_proxy(delay: std::time::Duration) -> tinybus::Proxy {
+ use tinybus::transport::memory::MemoryBus;
+ let bus = MemoryBus::new();
+ tinybus::broker::Broker::new().spawn(bus.clone());
+ let service = tinybus::Connection::connect(bus.connect().await.expect("service transport"))
+ .await
+ .expect("service");
+ service
+ .serve_at(
+ tinybus::ObjectPath::new(names::OBJECT_PATH).expect("contract path"),
+ SlowSearch { delay },
+ )
+ .await
+ .expect("serve");
+ service.request_name(names::INTERFACE).await.expect("name");
+ let client = tinybus::Connection::connect(bus.connect().await.expect("client transport"))
+ .await
+ .expect("client");
+ // Keep the service connection alive for the test's duration.
+ std::mem::forget(service);
+ client
+ .proxy(names::INTERFACE, names::OBJECT_PATH, names::INTERFACE)
+ .expect("proxy")
+}
+
+fn web_answer_request() -> ExecuteToolRequest {
+ ExecuteToolRequest {
+ name: "web_answer_tool".into(),
+ arguments: serde_json::json!({ "query": "q" }),
+ }
+}
+
+#[tokio::test(start_paused = true)]
+async fn execute_tool_outlives_the_bus_default_timeout() {
+ // Production: `web_answer_tool` / `web_search_tool` failed at the 30 s bus
+ // default while the module was still working.
+ let delay = tinybus::connection::DEFAULT_TIMEOUT + std::time::Duration::from_secs(15);
+ assert!(delay < EXECUTE_TOOL_TIMEOUT);
+
+ // Control: the bus default really does cut this call off.
+ let proxy = slow_search_proxy(delay).await;
+ let cut_off = proxy
+ .clone()
+ .call::<serde_json::Value>(names::methods::EXECUTE_TOOL, (web_answer_request(),))
+ .await;
+ assert!(cut_off.is_err(), "the default deadline must fire: {cut_off:?}");
+
+ let answered: serde_json::Value = call_execute_tool(proxy, web_answer_request())
+ .await
+ .expect("ExecuteTool runs under its own longer deadline");
+ assert_eq!(answered["answered"], true);
+}
+
+#[test]
+fn the_execute_tool_deadline_stays_under_the_harness_tool_deadline() {
+ assert!(EXECUTE_TOOL_TIMEOUT > tinybus::connection::DEFAULT_TIMEOUT);
+ assert!(
+ EXECUTE_TOOL_TIMEOUT.as_secs() < crate::tools::timeout::DEFAULT_TIMEOUT_SECS,
+ "the harness would kill the call before the module could answer"
+ );
+}