Skip to content

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

refactor(web_chat): derive turn deadlines from a shared backstop

Steven Enamakelc8630d78aef5
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
index 65cbe28483..afeff15409 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_span_tree_tests.rs
@@ -610,185 +610,3 @@ fn envelope_for_maps_configured_backend() {
SpanEnvelope::Langfuse
);
}
-
-// ── tool spans: failure class + model attribution ───────────────────────────
-
-fn failed_tool_completed(call_id: &str, tool: &str, output: &str) -> AgentProgress {
- AgentProgress::ToolCallCompleted {
- call_id: call_id.to_string(),
- tool_name: tool.to_string(),
- success: false,
- output_chars: output.chars().count(),
- output: output.to_string(),
- arguments: None,
- elapsed_ms: 5,
- iteration: 1,
- failure: Some(crate::tools::status::classify(output, false)),
- display_label: None,
- display_detail: None,
- structured: None,
- }
-}
-
-/// A plain non-zero command exit and a harness failure both close as an error
-/// span, so the class rides the span (content-free, so not gated on capture):
-/// it is what separates "the program exited 1" from "the harness failed" in
-/// Langfuse until the exporter can set a WARNING level.
-#[test]
-fn failed_tool_span_carries_its_failure_class() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 3,
- },
- 1,
- ),
- (tool_started("c1", "shell", 1), 2),
- (
- failed_tool_completed(
- "c1",
- "shell",
- "Command failed (exit code 1)\n[stderr]\nollama: timed out",
- ),
- 3,
- ),
- (tool_started("c2", "shell", 1), 4),
- (
- failed_tool_completed(
- "c2",
- "shell",
- "invalid arguments for tool `shell`: missing `command`; expected schema: {}",
- ),
- 5,
- ),
- (tool_started("c3", "web_search", 1), 6),
- (tool_completed("c3", "web_search", true, 3, 1), 7),
- ]);
- c.finish(100);
- let class_of = |call: &str| {
- c.spans()
- .iter()
- .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
- .and_then(|s| s.attributes.get("tool.failure_class").cloned())
- };
- assert_eq!(class_of("c1"), Some(serde_json::json!("CommandFailed")));
- assert_eq!(class_of("c2"), Some(serde_json::json!("InvalidArguments")));
- assert_eq!(class_of("c3"), None, "a successful call carries no class");
-}
-
-/// Tool observations name the model whose call requested them, so tool errors
-/// correlate to a model without joining against the generation span.
-#[test]
-fn tool_spans_carry_the_model_that_requested_them() {
- let mut c = collect(&[
- (AgentProgress::TurnStarted, 0),
- (
- AgentProgress::IterationStarted {
- iteration: 1,
- max_iterations: 3,
- },
- 1,
- ),
- (tool_started("early", "shell", 1), 2),
- (tool_completed("early", "shell", true, 1, 1), 3),
- (model_call("chat-v1", 0, 0), 4),
- (tool_started("c1", "shell", 1), 5),
- (
- failed_tool_completed("c1", "shell", "Command failed (exit code 2)"),
- 6,
- ),
- (spawn("task-1", "Researcher"), 7),
- (
- AgentProgress::SubagentIterationStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- iteration: 1,
- max_iterations: 8,
- extended_policy: false,
- },
- 8,
- ),
- (
- AgentProgress::ModelCallCompleted {
- model: "scout-v2".to_string(),
- provider_id: "openai".to_string(),
- subagent_task_id: Some("task-1".to_string()),
- input: None,
- output: None,
- iteration: 1,
- input_tokens: 10,
- output_tokens: 1,
- cached_input_tokens: 0,
- cache_creation_tokens: 0,
- reasoning_tokens: 0,
- cost_usd: 0.0,
- },
- 9,
- ),
- (
- AgentProgress::SubagentToolCallStarted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "file_read".to_string(),
- arguments: serde_json::Value::Null,
- iteration: 1,
- display_label: None,
- display_detail: None,
- },
- 10,
- ),
- (
- AgentProgress::SubagentToolCallCompleted {
- agent_id: "researcher".to_string(),
- task_id: "task-1".to_string(),
- call_id: "sc-1".to_string(),
- tool_name: "file_read".to_string(),
- success: false,
- output_chars: 0,
- output: String::new(),
- arguments: None,
- elapsed_ms: 1,
- iteration: 1,
- failure: Some(crate::tools::status::classify(
- "Command failed (exit code 1)",
- false,
- )),
- display_label: None,
- display_detail: None,
- structured: None,
- },
- 11,
- ),
- (tool_started("c2", "shell", 2), 12),
- ]);
- c.finish(100);
- let attr = |call: &str, key: &str| {
- c.spans()
- .iter()
- .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
- .and_then(|s| s.attributes.get(key).cloned())
- };
- assert_eq!(attr("early", "tool.model"), None, "no model call seen yet");
- assert_eq!(
- attr("c1", "tool.model"),
- Some(serde_json::json!("managed.chat-v1"))
- );
- assert_eq!(
- attr("sc-1", "tool.model"),
- Some(serde_json::json!("openai.scout-v2")),
- "a child tool names the child's model, not the parent's"
- );
- assert_eq!(
- attr("sc-1", "tool.failure_class"),
- Some(serde_json::json!("CommandFailed")),
- "a child tool span carries its failure class too"
- );
- assert_eq!(
- attr("c2", "tool.model"),
- Some(serde_json::json!("managed.chat-v1")),
- "the parent keeps its own model after a child ran"
- );
-}
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs
index 1e2b669915..3679447873 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tests.rs
@@ -149,5 +149,7 @@ mod attribution_tests;
mod content_gate_tests;
#[path = "progress_tracing_span_tree_tests.rs"]
mod span_tree_tests;
+#[path = "progress_tracing_tool_span_tests.rs"]
+mod tool_span_tests;
#[path = "progress_tracing_ttft_tests.rs"]
mod ttft_tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tool_span_tests.rs b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tool_span_tests.rs
new file mode 100644
index 0000000000..b96133971b
--- /dev/null
+++ b/crates/openhuman-core/src/agent/progress_tracing/progress_tracing_tool_span_tests.rs
@@ -0,0 +1,186 @@
+//! Tool-span attributes: the classified failure class and the model whose
+//! call requested the tool.
+
+use super::*;
+
+// ── tool spans: failure class + model attribution ───────────────────────────
+
+fn failed_tool_completed(call_id: &str, tool: &str, output: &str) -> AgentProgress {
+ AgentProgress::ToolCallCompleted {
+ call_id: call_id.to_string(),
+ tool_name: tool.to_string(),
+ success: false,
+ output_chars: output.chars().count(),
+ output: output.to_string(),
+ arguments: None,
+ elapsed_ms: 5,
+ iteration: 1,
+ failure: Some(crate::tools::status::classify(output, false)),
+ display_label: None,
+ display_detail: None,
+ structured: None,
+ }
+}
+
+/// A plain non-zero command exit and a harness failure both close as an error
+/// span, so the class rides the span (content-free, so not gated on capture):
+/// it is what separates "the program exited 1" from "the harness failed" in
+/// Langfuse until the exporter can set a WARNING level.
+#[test]
+fn failed_tool_span_carries_its_failure_class() {
+ let mut c = collect(&[
+ (AgentProgress::TurnStarted, 0),
+ (
+ AgentProgress::IterationStarted {
+ iteration: 1,
+ max_iterations: 3,
+ },
+ 1,
+ ),
+ (tool_started("c1", "shell", 1), 2),
+ (
+ failed_tool_completed(
+ "c1",
+ "shell",
+ "Command failed (exit code 1)\n[stderr]\nollama: timed out",
+ ),
+ 3,
+ ),
+ (tool_started("c2", "shell", 1), 4),
+ (
+ failed_tool_completed(
+ "c2",
+ "shell",
+ "invalid arguments for tool `shell`: missing `command`; expected schema: {}",
+ ),
+ 5,
+ ),
+ (tool_started("c3", "web_search", 1), 6),
+ (tool_completed("c3", "web_search", true, 3, 1), 7),
+ ]);
+ c.finish(100);
+ let class_of = |call: &str| {
+ c.spans()
+ .iter()
+ .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
+ .and_then(|s| s.attributes.get("tool.failure_class").cloned())
+ };
+ assert_eq!(class_of("c1"), Some(serde_json::json!("CommandFailed")));
+ assert_eq!(class_of("c2"), Some(serde_json::json!("InvalidArguments")));
+ assert_eq!(class_of("c3"), None, "a successful call carries no class");
+}
+
+/// Tool observations name the model whose call requested them, so tool errors
+/// correlate to a model without joining against the generation span.
+#[test]
+fn tool_spans_carry_the_model_that_requested_them() {
+ let mut c = collect(&[
+ (AgentProgress::TurnStarted, 0),
+ (
+ AgentProgress::IterationStarted {
+ iteration: 1,
+ max_iterations: 3,
+ },
+ 1,
+ ),
+ (tool_started("early", "shell", 1), 2),
+ (tool_completed("early", "shell", true, 1, 1), 3),
+ (model_call("chat-v1", 0, 0), 4),
+ (tool_started("c1", "shell", 1), 5),
+ (
+ failed_tool_completed("c1", "shell", "Command failed (exit code 2)"),
+ 6,
+ ),
+ (spawn("task-1", "Researcher"), 7),
+ (
+ AgentProgress::SubagentIterationStarted {
+ agent_id: "researcher".to_string(),
+ task_id: "task-1".to_string(),
+ iteration: 1,
+ max_iterations: 8,
+ extended_policy: false,
+ },
+ 8,
+ ),
+ (
+ AgentProgress::ModelCallCompleted {
+ model: "scout-v2".to_string(),
+ provider_id: "openai".to_string(),
+ subagent_task_id: Some("task-1".to_string()),
+ input: None,
+ output: None,
+ iteration: 1,
+ input_tokens: 10,
+ output_tokens: 1,
+ cached_input_tokens: 0,
+ cache_creation_tokens: 0,
+ reasoning_tokens: 0,
+ cost_usd: 0.0,
+ },
+ 9,
+ ),
+ (
+ AgentProgress::SubagentToolCallStarted {
+ agent_id: "researcher".to_string(),
+ task_id: "task-1".to_string(),
+ call_id: "sc-1".to_string(),
+ tool_name: "file_read".to_string(),
+ arguments: serde_json::Value::Null,
+ iteration: 1,
+ display_label: None,
+ display_detail: None,
+ },
+ 10,
+ ),
+ (
+ AgentProgress::SubagentToolCallCompleted {
+ agent_id: "researcher".to_string(),
+ task_id: "task-1".to_string(),
+ call_id: "sc-1".to_string(),
+ tool_name: "file_read".to_string(),
+ success: false,
+ output_chars: 0,
+ output: String::new(),
+ arguments: None,
+ elapsed_ms: 1,
+ iteration: 1,
+ failure: Some(crate::tools::status::classify(
+ "Command failed (exit code 1)",
+ false,
+ )),
+ display_label: None,
+ display_detail: None,
+ structured: None,
+ },
+ 11,
+ ),
+ (tool_started("c2", "shell", 2), 12),
+ ]);
+ c.finish(100);
+ let attr = |call: &str, key: &str| {
+ c.spans()
+ .iter()
+ .find(|s| s.attributes.get("tool.call_id") == Some(&serde_json::json!(call)))
+ .and_then(|s| s.attributes.get(key).cloned())
+ };
+ assert_eq!(attr("early", "tool.model"), None, "no model call seen yet");
+ assert_eq!(
+ attr("c1", "tool.model"),
+ Some(serde_json::json!("managed.chat-v1"))
+ );
+ assert_eq!(
+ attr("sc-1", "tool.model"),
+ Some(serde_json::json!("openai.scout-v2")),
+ "a child tool names the child's model, not the parent's"
+ );
+ assert_eq!(
+ attr("sc-1", "tool.failure_class"),
+ Some(serde_json::json!("CommandFailed")),
+ "a child tool span carries its failure class too"
+ );
+ assert_eq!(
+ attr("c2", "tool.model"),
+ Some(serde_json::json!("managed.chat-v1")),
+ "the parent keeps its own model after a child ran"
+ );
+}
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
index 1fe830f4f8..ef91bf8014 100644
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@ -8,28 +8,33 @@ use tokio_util::sync::CancellationToken;
use super::super::types::WebChatTaskResult;
-/// Default wall-clock backstop for a single web chat turn, in seconds.
-///
-/// This is the OUTER safety net (issue #4746). The primary, root-cause guard is
-/// the harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`,
-/// default 600s), which interrupts a hung/slow model or tool/sub-agent call
-/// mid-flight and returns a proper `Timeout` → `chat_error`. This channel-level
-/// backstop sits ABOVE that (900s) and only fires if a turn wedges OUTSIDE the
-/// harness run entirely (e.g. session assembly / persistence plumbing), so the
-/// client still always gets a terminal event instead of an empty reply / an
-/// endless `inference_heartbeat` stream. Deliberately generous — a hang
-/// backstop, not a UX deadline. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`;
-/// set it to `0` to disable the backstop.
-const DEFAULT_WEB_TURN_TIMEOUT_SECS: u64 = 900;
-
/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled
/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`).
+///
+/// This is the OUTER safety net (issue #4746), and the single source of truth
+/// for the turn's deadlines (`agent::turn_deadline`, default 900s). The
+/// harness derives two earlier points from it:
+///
+/// * **wind-down** at backstop minus `min(120s, backstop/5)`, 780s by default.
+/// The harness pauses the run at its next safe point, and the session driver
+/// writes the grounded close from the work already done, so a long turn
+/// still delivers an answer.
+/// * **hard stop** at backstop minus `min(60s, backstop/10)`, 840s by default.
+/// The harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`,
+/// 3600s on its own) is clamped to it, so a tool or sub-agent call that runs
+/// across the wind-down point ends in the harness's own typed `Timeout` →
+/// `chat_error`.
+///
+/// So this backstop only fires if a turn wedges OUTSIDE the harness run, e.g.
+/// in session assembly, the grounded close or the persistence plumbing. The
+/// client then still gets a terminal `turn_timeout` event instead of an empty
+/// reply or an endless `inference_heartbeat` stream. Before the derived
+/// deadlines existed, the harness ceiling sat at 3600s, *after* this 900s
+/// backstop. Long orchestrator turns were then dropped here, mid-work, with
+/// nothing delivered. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`; set it to
+/// `0` to disable the backstop and the derived deadlines with it.
fn web_turn_deadline() -> Option<Duration> {
- let secs = std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS")
- .ok()
- .and_then(|v| v.trim().parse::<u64>().ok())
- .unwrap_or(DEFAULT_WEB_TURN_TIMEOUT_SECS);
- (secs > 0).then(|| Duration::from_secs(secs))
+ crate::agent::turn_deadline::configured_backstop()
}
/// Drive a chat-turn future under the wall-clock backstop.
@@ -47,12 +52,23 @@ where
F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
{
match deadline {
- Some(d) => match tokio::time::timeout(d, fut).await {
+ // Scope the deadline on the task so the session turn hands it to the
+ // harness (`agent::turn_deadline`), which winds down before `d`.
+ Some(d) => match tokio::time::timeout(
+ d,
+ crate::agent::turn_deadline::with_turn_deadline(
+ Some(crate::agent::turn_deadline::TurnDeadline::starting_now(d)),
+ fut,
+ ),
+ )
+ .await
+ {
Ok(res) => res,
Err(_elapsed) => {
log::warn!(
- "[web-channel] turn wall-clock backstop fired after {}s with no terminal event; \
- emitting graceful turn_timeout chat_error (issue #4746)",
+ "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \
+ (the harness wind-down did not close the turn in time); emitting graceful \
+ turn_timeout chat_error (issue #4746)",
d.as_secs()
);
Err(super::super::web_errors::turn_timeout_error_message(
@@ -166,3 +182,7 @@ pub(crate) fn timeout_bound_tag(detailed: &str) -> &'static str {
"none"
}
}
+
+#[cfg(test)]
+#[path = "turn_guards_tests.rs"]
+mod tests;