Skip to content

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

fix(reaper): handle empty replay buffer in reaper agent

Steven Enamakel15b76319eb1c
diff --git a/crates/openhuman-core/src/agent/tinyagents/reaper.rs b/crates/openhuman-core/src/agent/tinyagents/reaper.rs
index 8898017dc4..6f8f1ac7ef 100644
--- a/crates/openhuman-core/src/agent/tinyagents/reaper.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/reaper.rs
@@ -1,132 +1,27 @@
//! Startup reconciliation for orphaned agent runs.
//!
-//! The core is a single in-process runtime. When it exits — a crash, a restart,
-//! or a deploy — any run still in a non-terminal state (`Pending` / `Running` /
-//! `Interrupted`) in the durable status store is *orphaned*: no executor will
-//! ever advance it, yet it lingers in the "active runs" listing
-//! (`openhuman.agent_runs_active`) indefinitely. A long-lived instance was
-//! observed carrying 50 such zombies, all invisible to any cancel path because
-//! the task that owned each run no longer exists.
-//!
-//! On startup we sweep every still-active run to the terminal `Cancelled` state
-//! with an explanatory error so the active listing reflects reality. This is
-//! the one *writer* over the status seam that
-//! [`crate::agent::tinyagents::journal`] exposes; the replay/status
-//! controllers ([`super::replay`]) stay strictly read-only.
+//! The sweep itself (`tinyagents_harness::observability::reap_orphaned_runs`)
+//! lives upstream; this host adapter only opens the workspace's durable status
+//! store. It is the one *writer* over the status seam that
+//! [`crate::agent::tinyagents::journal`] exposes; the replay/status controllers
+//! ([`super::replay`]) stay strictly read-only.
use std::path::Path;
-use std::time::SystemTime;
-
-use tinyagents_harness::events::HarnessRunStatus;
-use tinyagents_harness::ids::{ExecutionStatus, HarnessPhase};
-use tinyagents_harness::observability::HarnessStatusStore;
-use crate::agent::tinyagents::journal::FileStatusStore;
+use tinyagents_harness::observability::FileStatusStore;
use tinyagents_session::transcript::import::ops::open_session_stores;
-/// Error recorded on a run reaped by the startup sweep. Stable + grep-friendly
-/// so an operator (or a test) can tell a reaped run from a genuinely failed one.
-pub(crate) const ORPHAN_REAP_REASON: &str =
- "run orphaned: core restarted while the run was in flight";
+pub(crate) use tinyagents_harness::observability::ORPHAN_REAP_REASON;
-/// Reap every run left non-terminal by a previous process.
-///
-/// Opens the durable status store under `workspace`, lists the still-active
-/// runs, and moves each to the terminal `Cancelled` state. Best-effort: a
-/// per-run persistence failure is logged and does not abort the sweep, and a
-/// failure to open/list the store logs and yields `0` rather than blocking
-/// boot. Returns the number of runs reaped.
+/// Reap every run left non-terminal by a previous process, returning the number
+/// of runs moved to `Cancelled`. Best-effort; never blocks boot.
pub(crate) async fn reap_orphaned_runs(workspace: &Path) -> usize {
- // One id for the whole sweep so every line below can be tied to the same
- // boot — a restart loop otherwise interleaves two sweeps' lines with nothing
- // to tell them apart. Derived from the clock rather than a uuid so it stays
- // ordered in a log tail.
- let sweep_id = SystemTime::now()
- .duration_since(SystemTime::UNIX_EPOCH)
- .map(|d| d.as_millis())
- .unwrap_or(0);
log::debug!(
- "[agent] startup run sweep entry sweep_id={sweep_id} workspace={}",
+ "[agent] startup run sweep workspace={}",
workspace.display()
);
-
- let stores = open_session_stores(workspace);
- let store = FileStatusStore::new(stores.kv);
-
- let active = match store.list_active().await {
- Ok(runs) => runs,
- Err(err) => {
- log::warn!(
- "[agent] startup run sweep exit sweep_id={sweep_id} branch=list-failed: {err}"
- );
- return 0;
- }
- };
-
- if active.is_empty() {
- log::debug!("[agent] startup run sweep exit sweep_id={sweep_id} branch=none-active");
- return 0;
- }
- log::debug!(
- "[agent] startup run sweep sweep_id={sweep_id} active={} to reap",
- active.len()
- );
-
- let mut reaped = 0usize;
- for mut status in active {
- let run_id = status.run_id.as_str().to_string();
- // The source state is read before the mutation, not assumed: `list_active`
- // returns whatever non-terminal state a run was left in, and logging a
- // presumed `Running` would misreport a run that died mid-`Queued`.
- let from_status = format!("{:?}", status.status);
- mark_orphaned(&mut status);
- let to_status = format!("{:?}", status.status);
- log::debug!(
- "[agent] startup run sweep sweep_id={sweep_id} run_id={run_id} \
- transition={from_status}->{to_status} phase=Done persisting"
- );
- match store.put_status(status).await {
- Ok(()) => {
- reaped += 1;
- log::debug!(
- "[agent] startup run sweep sweep_id={sweep_id} run_id={run_id} \
- transition={from_status}->{to_status} persisted"
- );
- }
- Err(err) => {
- log::warn!(
- "[agent] startup run sweep sweep_id={sweep_id} run_id={run_id} \
- transition={from_status}->{to_status} failed: {err}"
- );
- }
- }
- }
- // One operator-visible line for the whole sweep, and only when it did
- // something: a clean boot is the normal case and says nothing.
- if reaped > 0 {
- log::info!("[agent] startup run sweep sweep_id={sweep_id} reaped {reaped} orphaned run(s)");
- } else {
- log::debug!("[agent] startup run sweep exit sweep_id={sweep_id} branch=nothing-reaped");
- }
- reaped
-}
-
-/// Move a run to the terminal `Cancelled` state with the orphan reason.
-///
-/// tinyagents exposes `mark_completed` / `mark_failed` / `mark_interrupted` but
-/// no `mark_cancelled`; the `HarnessRunStatus` fields are public, so we set the
-/// terminal state directly here rather than take a cross-repo dependency on a
-/// new helper. `Cancelled` (not `Failed`) is deliberate: a restart is not a run
-/// failure, and marking it `Failed` would render every reaped run as a red
-/// error row in the UI. Mirrors the field writes `mark_failed` performs
-/// (terminal status + `Done` phase + `error` + `ended_at`/`updated_at`).
-fn mark_orphaned(status: &mut HarnessRunStatus) {
- status.status = ExecutionStatus::Cancelled;
- status.current_phase = HarnessPhase::Done;
- status.error = Some(ORPHAN_REAP_REASON.to_string());
- let now = SystemTime::now();
- status.ended_at = Some(now);
- status.updated_at = now;
+ let store = FileStatusStore::new(open_session_stores(workspace).kv);
+ tinyagents_harness::observability::reap_orphaned_runs(&store).await
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs b/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
index e6b7987caf..4d7f2f5c45 100644
--- a/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/reaper_tests.rs
@@ -2,83 +2,33 @@ use super::*;
use tinyagents_harness::ids::ComponentId;
-use crate::agent::tinyagents::journal::mint_run_id;
+use tinyagents_harness::observability::{mint_run_id, HarnessStatusStore};
-/// Build a fresh status in the given non-terminal state and persist it.
+/// Build a fresh status in a non-terminal state and persist it.
async fn seed_status(store: &FileStatusStore, status_kind: ExecutionStatus) -> String {
let run_id = mint_run_id();
let mut status =
HarnessRunStatus::new(run_id.clone(), ComponentId::new("mock-model".to_string()));
match status_kind {
- ExecutionStatus::Pending => { /* fresh status is already Pending */ }
ExecutionStatus::Running => status.mark_running(HarnessPhase::Model),
- ExecutionStatus::Interrupted => status.mark_interrupted(),
- other => panic!("seed_status only seeds non-terminal states, got {other:?}"),
+ other => panic!("seed_status only seeds Running here, got {other:?}"),
}
store.put_status(status).await.unwrap();
run_id.as_str().to_string()
}
-/// The sweep reaps every non-terminal run to `Cancelled` with the reason,
-/// leaves terminal runs untouched, and empties the active listing.
+/// The workspace adapter reaps a seeded orphan and a missing workspace reaps
+/// nothing (the sweep logic itself is tested upstream).
#[tokio::test]
-async fn reap_cancels_every_active_run_and_spares_terminal_ones() {
+async fn workspace_adapter_reaps_and_empty_workspace_is_a_noop() {
let tmp = std::env::temp_dir().join(format!("oh-reaper-{}", uuid::Uuid::new_v4()));
- let store = FileStatusStore::new(open_session_stores(&tmp).kv);
-
- let pending = seed_status(&store, ExecutionStatus::Pending).await;
- let running = seed_status(&store, ExecutionStatus::Running).await;
- let interrupted = seed_status(&store, ExecutionStatus::Interrupted).await;
-
- // A run that already finished must survive the sweep unchanged.
- let done = mint_run_id();
- let mut done_status =
- HarnessRunStatus::new(done.clone(), ComponentId::new("mock-model".to_string()));
- done_status.mark_running(HarnessPhase::Model);
- done_status.mark_completed();
- store.put_status(done_status).await.unwrap();
-
- let reaped = reap_orphaned_runs(&tmp).await;
- assert_eq!(reaped, 3, "the three non-terminal runs were reaped");
-
- // Every orphan is now terminal-cancelled with the stable reason.
- for run_id in [&pending, &running, &interrupted] {
- let status = store
- .get_status(run_id)
- .await
- .unwrap()
- .expect("status present");
- assert_eq!(status.status, ExecutionStatus::Cancelled);
- assert_eq!(status.current_phase, HarnessPhase::Done);
- assert_eq!(status.error.as_deref(), Some(ORPHAN_REAP_REASON));
- assert!(status.ended_at.is_some(), "reaped run has an end time");
- }
-
- // The completed run is left exactly as it was.
- let done_after = store
- .get_status(done.as_str())
- .await
- .unwrap()
- .expect("done present");
- assert_eq!(done_after.status, ExecutionStatus::Completed);
- assert!(done_after.error.is_none());
-
- // The active listing is now empty — a second sweep is a no-op.
- assert!(store.list_active().await.unwrap().is_empty());
- assert_eq!(
- reap_orphaned_runs(&tmp).await,
- 0,
- "idempotent: nothing left to reap"
- );
-
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// A workspace that never hosted a run reaps nothing and does not error.
-#[tokio::test]
-async fn reap_on_empty_workspace_is_a_noop() {
- let tmp = std::env::temp_dir().join(format!("oh-reaper-empty-{}", uuid::Uuid::new_v4()));
assert_eq!(reap_orphaned_runs(&tmp).await, 0);
+ let store = FileStatusStore::new(open_session_stores(&tmp).kv);
+ let run = seed_status(&store, ExecutionStatus::Running).await;
+ assert_eq!(reap_orphaned_runs(&tmp).await, 1);
+ let status = store.get_status(&run).await.unwrap().expect("present");
+ assert_eq!(status.status, ExecutionStatus::Cancelled);
+ assert_eq!(status.error.as_deref(), Some(ORPHAN_REAP_REASON));
let _ = std::fs::remove_dir_all(&tmp);
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/replay/ops.rs b/crates/openhuman-core/src/agent/tinyagents/replay/ops.rs
index c3e723b515..0475a0d46a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/replay/ops.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/replay/ops.rs
@@ -1,171 +1,52 @@
//! Read-only business logic for the agent replay/status RPC surface
-//! (workstream 05.x). Every function here is a *reader* over the C4 durable
-//! journal + status seams built in
-//! [`crate::agent::tinyagents::journal`] — it opens the same
-//! `{workspace}/tinyagents_store/{kv,journal}` stores and never writes, mutates,
-//! or bypasses any security/approval/sandbox gate.
-//!
-//! The controller layer ([`super::schemas`]) resolves the configured workspace
-//! and delegates here; these functions take an explicit `workspace` path so they
-//! are unit-testable against a temp store (mirroring the `journal.rs` tests).
+//! (workstream 05.x): a workspace-to-store adapter over the upstream readers in
+//! `tinyagents_harness::observability::replay`. Every function opens the same
+//! `{workspace}/tinyagents_store/{kv,journal}` stores the turn journal writes
+//! and never writes, mutates, or bypasses any security/approval/sandbox gate.
use std::path::Path;
use tinyagents_harness::events::HarnessRunStatus;
-use tinyagents_harness::ids::ExecutionStatus;
-use tinyagents_harness::observability::{
- AgentObservation, HarnessEventJournal, HarnessStatusStore, StoreEventJournal,
-};
-
-use crate::agent::tinyagents::journal::FileStatusStore;
+use tinyagents_harness::observability::replay;
+use tinyagents_harness::observability::{FileStatusStore, StoreEventJournal};
use tinyagents_session::transcript::import::ops::open_session_stores;
-/// Default page size for [`read_run_events_page`] when the caller omits `limit`.
-pub(crate) const DEFAULT_EVENTS_LIMIT: u64 = 200;
-
-/// Hard cap on a single replay page so one RPC can never fan a whole run into a
-/// single response.
-pub(crate) const MAX_EVENTS_LIMIT: u64 = 1000;
-
-/// One page of a run's durable event stream.
-///
-/// `events` are [`AgentObservation`]s (the crate's durable observability
-/// envelope — `event_id` / `run_id` / lineage / `offset` / `ts_ms` / typed
-/// `event`) in ascending `offset` order. `next_offset` is the `offset` to pass
-/// back to fetch the following page, or `None` once the stream is drained.
-pub(crate) struct RunEventsPage {
- pub events: Vec<AgentObservation>,
- pub next_offset: Option<u64>,
-}
+pub(crate) use replay::{RunEventsPage, DEFAULT_EVENTS_LIMIT, MAX_EVENTS_LIMIT};
-/// Paged late-attach replay reader over the durable journal.
-///
-/// Returns up to `limit` observations for `run_id` whose stream offset is
-/// `>= offset`, in order, plus a `next_offset` cursor (`None` when the last page
-/// drained the stream). Backed by the C4 journal seam
-/// ([`StoreEventJournal::read_from`], the same reader
-/// [`crate::agent::tinyagents::journal::read_run_events`] uses). Best-effort:
-/// a missing store or unknown run yields an empty page, not an error.
+/// Paged late-attach replay reader over the durable journal under `workspace`.
pub(crate) async fn read_run_events_page(
workspace: &Path,
run_id: &str,
offset: u64,
limit: u64,
) -> anyhow::Result<RunEventsPage> {
- // Guard the page size: clamp a zero/absurd limit into [1, MAX].
- let effective_limit = limit.clamp(1, MAX_EVENTS_LIMIT);
- log::debug!(
- "[agent] replay read_run_events_page run_id={run_id} offset={offset} \
- limit={limit} effective_limit={effective_limit}"
- );
-
- let stores = open_session_stores(workspace);
- let journal = StoreEventJournal::new(stores.journal);
- // Read one extra record to detect whether a further page exists without a
- // second store round-trip.
- let mut events = journal.read_from(run_id, offset).await.map_err(|e| {
- anyhow::anyhow!("[agent] replay read_run_events_page failed run_id={run_id}: {e}")
- })?;
-
- let has_more = events.len() as u64 > effective_limit;
- if has_more {
- events.truncate(effective_limit as usize);
- }
- // Offsets are monotonic within a run, so the cursor is simply "one past the
- // last returned offset". `None` when this page drained the stream.
- let next_offset = if has_more {
- events.last().map(|obs| obs.offset + 1)
- } else {
- None
- };
-
- log::debug!(
- "[agent] replay read_run_events_page run_id={run_id} returned={} next_offset={:?}",
- events.len(),
- next_offset
- );
- Ok(RunEventsPage {
- events,
- next_offset,
- })
+ let journal = StoreEventJournal::new(open_session_stores(workspace).journal);
+ replay::read_run_events_page(&journal, run_id, offset, limit)
+ .await
+ .map_err(|e| {
+ anyhow::anyhow!("[agent] replay read_run_events_page failed run_id={run_id}: {e}")
+ })
}
-/// Latest durable [`HarnessRunStatus`] for `run_id`, or `None` when the run is
-/// unknown. Backed by the C4 status seam
-/// ([`crate::agent::tinyagents::journal::read_run_status`] /
-/// [`FileStatusStore::get_status`]).
+/// Latest durable status for `run_id`, or `None` when the run is unknown.
pub(crate) async fn read_run_status(
workspace: &Path,
run_id: &str,
) -> anyhow::Result<Option<HarnessRunStatus>> {
- log::debug!("[agent] replay read_run_status run_id={run_id}");
- let stores = open_session_stores(workspace);
- let store = FileStatusStore::new(stores.kv);
- let status = store.get_status(run_id).await.map_err(|e| {
+ let store = FileStatusStore::new(open_session_stores(workspace).kv);
+ replay::read_run_status(&store, run_id).await.map_err(|e| {
anyhow::anyhow!("[agent] replay read_run_status failed run_id={run_id}: {e}")
- })?;
- log::debug!(
- "[agent] replay read_run_status run_id={run_id} found={}",
- status.is_some()
- );
- Ok(status)
-}
-
-/// Is a run still live (i.e. eligible for the "active" listing)?
-///
-/// Mirrors the liveness predicate the crate's status store uses for
-/// `list_active` (Pending / Running / Interrupted).
-fn is_active(status: &HarnessRunStatus) -> bool {
- matches!(
- status.status,
- ExecutionStatus::Pending | ExecutionStatus::Running | ExecutionStatus::Interrupted
- )
+ })
}
/// Active runs, optionally filtered by `thread_id` and/or `root_run_id`.
-///
-/// Backed by the C4 status seam:
-/// - no filter → [`FileStatusStore::list_active`]
-/// - `thread_id` → [`FileStatusStore::list_by_thread`]
-/// - `root_run_id` → [`FileStatusStore::list_by_root`]
-///
-/// The thread/root store queries return *all* runs (active and terminal), so the
-/// active-liveness predicate is always applied on top — this controller only
-/// ever surfaces live runs. When both filters are supplied, the base query uses
-/// `thread_id` and the result is further restricted to `root_run_id`.
pub(crate) async fn list_active_runs(
workspace: &Path,
thread_id: Option<&str>,
root_run_id: Option<&str>,
) -> anyhow::Result<Vec<HarnessRunStatus>> {
- log::debug!(
- "[agent] replay list_active_runs thread_id={:?} root_run_id={:?}",
- thread_id,
- root_run_id
- );
- let stores = open_session_stores(workspace);
- let store = FileStatusStore::new(stores.kv);
-
- let base = match (thread_id, root_run_id) {
- (Some(thread), _) => store.list_by_thread(thread).await,
- (None, Some(root)) => store.list_by_root(root).await,
- (None, None) => store.list_active().await,
- }
- .map_err(|e| anyhow::anyhow!("[agent] replay list_active_runs failed: {e}"))?;
-
- let mut runs: Vec<HarnessRunStatus> = base.into_iter().filter(is_active).collect();
- // If a caller supplied BOTH a thread and a root, the thread query drove the
- // base list; narrow it to the requested root as well.
- if thread_id.is_some() {
- if let Some(root) = root_run_id {
- runs.retain(|s| s.root_run_id.as_str() == root);
- }
- }
-
- log::debug!("[agent] replay list_active_runs returned={}", runs.len());
- Ok(runs)
+ let store = FileStatusStore::new(open_session_stores(workspace).kv);
+ replay::list_active_runs(&store, thread_id, root_run_id)
+ .await
+ .map_err(|e| anyhow::anyhow!("[agent] replay list_active_runs failed: {e}"))
}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/replay/ops_tests.rs b/crates/openhuman-core/src/agent/tinyagents/replay/ops_tests.rs
deleted file mode 100644
index acd7d75612..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/replay/ops_tests.rs
+++ /dev/null
@@ -1,132 +0,0 @@
-use super::*;
-use std::sync::Arc;
-
-use tinyagents_harness::events::{AgentEvent, EventSink};
-use tinyagents_harness::ids::{ComponentId, HarnessPhase, ThreadId};
-use tinyagents_harness::observability::{FanOutSink, JournalSink, StoreEventJournal};
-
-use crate::agent::tinyagents::journal::mint_run_id;
-
-/// Seed `count` durable events for a fresh run under `workspace`, returning
-/// the run id. Mirrors the seam wiring in the `journal.rs` tests: a run
-/// [`EventSink`] seeded with the run id (so persisted `event_id`s are the
-/// stable `{run_id}-evt-{offset}`) fanning out into a [`StoreEventJournal`].
-async fn seed_run_events(workspace: &Path, count: usize) -> String {
- let stores = open_session_stores(workspace);
- let run_id = mint_run_id();
- let journal: Arc<dyn HarnessEventJournal> = Arc::new(StoreEventJournal::new(stores.journal));
- let sink = EventSink::with_stream_id(run_id.as_str());
- let journal_sink = JournalSink::new(journal, run_id.clone());
- sink.subscribe(Arc::new(FanOutSink::new().with(Arc::new(journal_sink))));
- for i in 0..count {
- sink.emit(AgentEvent::ToolStarted {
- call_id: format!("c{i}").into(),
- tool_name: format!("tool-{i}"),
- input: None,
- });
- }
- run_id.as_str().to_string()
-}
-
-/// Paging boundary: a page smaller than the stream reports a `next_offset`
-/// cursor; the final page drains to `None` and never over-reads.
-#[tokio::test]
-async fn read_run_events_page_pages_and_drains() {
- let tmp = std::env::temp_dir().join(format!("oh-replay-page-{}", uuid::Uuid::new_v4()));
- let run_id = seed_run_events(&tmp, 3).await;
-
- // First page (limit 2) returns offsets 0,1 with a cursor at offset 2.
- let page1 = read_run_events_page(&tmp, &run_id, 0, 2).await.unwrap();
- assert_eq!(page1.events.len(), 2);
- assert_eq!(page1.events[0].offset, 0);
- assert_eq!(page1.events[1].offset, 1);
- assert_eq!(page1.next_offset, Some(2), "more events remain");
-
- // Second page resumes at the cursor and drains → next_offset None.
- let page2 = read_run_events_page(&tmp, &run_id, page1.next_offset.unwrap(), 2)
- .await
- .unwrap();
- assert_eq!(page2.events.len(), 1);
- assert_eq!(page2.events[0].offset, 2);
- assert_eq!(page2.next_offset, None, "stream drained on the last page");
-
- // A page exactly the size of the remaining stream still drains to None
- // (no phantom extra page).
- let exact = read_run_events_page(&tmp, &run_id, 0, 3).await.unwrap();
- assert_eq!(exact.events.len(), 3);
- assert_eq!(exact.next_offset, None);
-
- // Unknown run → empty page, not an error.
- let empty = read_run_events_page(&tmp, "run.does-not-exist", 0, 10)
- .await
- .unwrap();
- assert!(empty.events.is_empty());
- assert_eq!(empty.next_offset, None);
-
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// Status reader returns `None` for a run that was never recorded.
-#[tokio::test]
-async fn read_run_status_none_for_unknown_run() {
- let tmp = std::env::temp_dir().join(format!("oh-replay-status-{}", uuid::Uuid::new_v4()));
- let missing = read_run_status(&tmp, "run.nope").await.unwrap();
- assert!(missing.is_none());
- let _ = std::fs::remove_dir_all(&tmp);
-}
-
-/// Active listing surfaces a started run and filters by thread; a completed
-/// run is excluded.
-#[tokio::test]
-async fn list_active_runs_returns_started_and_filters_by_thread() {
- let tmp = std::env::temp_dir().join(format!("oh-replay-active-{}", uuid::Uuid::new_v4()));
- let store = FileStatusStore::new(open_session_stores(&tmp).kv);
-
- // A running run on thread-A.
- let run_a = mint_run_id();
- let mut status_a =
- HarnessRunStatus::new(run_a.clone(), ComponentId::new("mock-model".to_string()))
- .with_thread(ThreadId::new("thread-A"));
- status_a.mark_running(HarnessPhase::Model);
- store.put_status(status_a).await.unwrap();
-
- // A completed run on thread-B (must NOT appear in the active listing).
- let run_b = mint_run_id();
- let mut status_b =
- HarnessRunStatus::new(run_b.clone(), ComponentId::new("mock-model".to_string()))
- .with_thread(ThreadId::new("thread-B"));
- status_b.mark_running(HarnessPhase::Model);
- status_b.mark_completed();
- store.put_status(status_b).await.unwrap();
-
- // No filter: only the running run.
- let active = list_active_runs(&tmp, None, None).await.unwrap();
- assert_eq!(active.len(), 1);
- assert_eq!(active[0].run_id.as_str(), run_a.as_str());
-
- // Filter by thread-A: the running run is returned.
- let by_thread_a = list_active_runs(&tmp, Some("thread-A"), None)
- .await
- .unwrap();
- assert_eq!(by_thread_a.len(), 1);
- assert_eq!(by_thread_a[0].run_id.as_str(), run_a.as_str());
-
- // Filter by thread-B: the only run there is completed → excluded.
- let by_thread_b = list_active_runs(&tmp, Some("thread-B"), None)
- .await
- .unwrap();
- assert!(by_thread_b.is_empty());
-
- // Filter by an unknown thread: empty.
- let by_thread_none = list_active_runs(&tmp, Some("nope"), None).await.unwrap();
- assert!(by_thread_none.is_empty());
-
- // Filter by root_run_id (a top-level run's root equals its own id).
- let by_root = list_active_runs(&tmp, None, Some(run_a.as_str()))
- .await
- .unwrap();
- assert_eq!(by_root.len(), 1);
- assert_eq!(by_root[0].run_id.as_str(), run_a.as_str());
-
- let _ = std::fs::remove_dir_all(&tmp);
-}