diff --git a/docs/tap-records.md b/docs/tap-records.md index 07f8014..d35e1c2 100644 --- a/docs/tap-records.md +++ b/docs/tap-records.md @@ -18,6 +18,8 @@ Identity scopes remain separate: - Capture attempt: `(run_id, exchange, step)` when the step is known; `(run_id, exchange)` identifies the exchange even for anonymous or unread traffic. - Graph nodes named `exchange:` and `step:.` are scoped to the enclosing line's `run_id`; their bare names are not globally unique. +Record-order waits, continuation history and tool-call matching use `(adapter, thread)`: equal native ids from different adapters do not link or wait on each other. Native ids and emitted edge names remain unchanged. The thread and open-call memory bounds below are shared across all adapters, not allocated per adapter. + The capture identity is independent of native harness sessions and wrapper run attribution. Diagnostic `--shape-file` output has its own format and carries none of `run_id`, `schema_version` or `sequence`. ## Delivery cursor diff --git a/src/exchange/exchanges.rs b/src/exchange/exchanges.rs index 36f7272..1f21a86 100644 --- a/src/exchange/exchanges.rs +++ b/src/exchange/exchanges.rs @@ -50,7 +50,7 @@ impl Exchanges { let exchange = self.next_exchange(); let identity = opening.adapter.identity(opening.head); // Joined before the parser is built, so nothing widens the gap between the id and the place in line - let steps = Steps::join(&self.threads, exchange, &identity); + let steps = Steps::join(&self.threads, exchange, &identity, opening.adapter.name()); let recorder = Recorder::start(self.output.clone(), exchange, opening.adapter.name(), identity.clone()); let parser: Box = match &self.shapes { Some(log) => Box::new(ShapedParser::new(log.clone(), opening.parser, exchange, opening.head)), diff --git a/src/exchange/tests.rs b/src/exchange/tests.rs index 0b87b82..551c295 100644 --- a/src/exchange/tests.rs +++ b/src/exchange/tests.rs @@ -758,7 +758,7 @@ async fn a_result_in_a_later_request_writes_one_calls_edge_for_its_call() { } #[tokio::test] -async fn a_claude_and_a_codex_exchange_write_these_exact_records_and_edges() { +async fn two_exchanges_of_one_adapter_write_these_exact_records_and_edges() { // It pins every field of the record and edge payloads a thread's two exchanges write use crate::common::*; use crate::message::{Block, Message, Output}; @@ -861,6 +861,177 @@ async fn a_claude_and_a_codex_exchange_write_these_exact_records_and_edges() { ); } +#[tokio::test] +async fn adapter_scoped_threads_keep_separate_continuation_chains() { + // Equal native thread ids continue only earlier steps from the same adapter. + let claude = Named("claude", on_thread("t1")); + let codex = Named("codex", on_thread("t1")); + let mut capture = Capture::new(); + + let first_claude = capture.run(&claude, None, closed_reply()).await; + let first_codex = capture.run(&codex, None, closed_reply()).await; + let next_claude = capture.run(&claude, None, closed_reply()).await; + let next_codex = capture.run(&codex, None, closed_reply()).await; + + assert!(step_edges(&first_claude).is_empty()); + assert!(step_edges(&first_codex).is_empty()); + assert_eq!(step_edges(&next_claude), [edge("continues", "step:3.1", "step:1.1")]); + assert_eq!(step_edges(&next_codex), [edge("continues", "step:4.1", "step:2.1")]); + for (name, lines) in [("claude", next_claude), ("codex", next_codex)] { + assert!(lines + .iter() + .all(|line| line["adapter"] == name && line["thread"] == "t1")); + assert_eq!(record_of(&lines)["payload"]["thread"], "t1"); + } +} + +#[tokio::test] +async fn adapter_scoped_threads_do_not_share_or_overwrite_reply_ids() { + // A foreign reply id is unknown; identical reply ids still resolve to each adapter's own step. + let claude = Named("claude", on_thread("t1")); + let codex = Named("codex", on_thread("t1")); + let reply = || { + vec![ + conversation(Value::Null, Value::Null, Vec::new()), + reply_end_of_message(Value::Null, json!("m1")), + ] + }; + let following = || { + let mut events = reply(); + events[0].event.conversation_mut().previous_message_id = Some("m1".into()); + events + }; + let mut capture = Capture::new(); + + capture.run(&claude, None, reply()).await; + let foreign = capture.run(&codex, None, following()).await; + let next_claude = capture.run(&claude, None, following()).await; + let next_codex = capture.run(&codex, None, following()).await; + + assert!(step_edges(&foreign).is_empty()); + assert_eq!(step_edges(&next_claude), [edge("continues", "step:3.1", "step:1.1")]); + assert_eq!(step_edges(&next_codex), [edge("continues", "step:4.1", "step:2.1")]); +} + +#[tokio::test] +async fn adapter_scoped_threads_match_and_close_only_their_own_calls() { + // Foreign results consume nothing, and equal call ids can be answered once in each adapter. + use crate::common::{BlockKind, BlockStart}; + use crate::message::{Block, Message, Output}; + let claude = Named("claude", on_thread("t1")); + let codex = Named("codex", on_thread("t1")); + let calling = || { + vec![ + conversation(Value::Null, Value::Null, Vec::new()), + block_start(BlockStart { + index: 0, + kind: BlockKind::ToolCall, + id: json!("c1"), + name: Value::Null, + }), + block_stop(0), + reply_end_of_message(Value::Null, Value::Null), + ] + }; + let answering = || { + vec![ + conversation( + Value::Null, + Value::Null, + vec![Message::user(vec![Block::ToolResult { + call_id: json!("c1"), + is_error: false, + output: Output::Raw(Value::Null), + }])], + ), + reply_end_of_message(Value::Null, Value::Null), + ] + }; + let calls = |lines: &[Value]| -> Vec { + step_edges(lines) + .into_iter() + .filter(|(kind, _, _)| kind == "calls") + .collect() + }; + let mut capture = Capture::new(); + + capture.run(&claude, None, calling()).await; + let foreign = capture.run(&codex, None, answering()).await; + capture.run(&codex, None, calling()).await; + let own_claude = capture.run(&claude, None, answering()).await; + let own_codex = capture.run(&codex, None, answering()).await; + let resent = capture.run(&codex, None, answering()).await; + + assert!(calls(&foreign).is_empty()); + assert_eq!(calls(&own_claude), [edge("calls", "call:c1", "result:c1")]); + assert_eq!(calls(&own_codex), [edge("calls", "call:c1", "result:c1")]); + assert!(calls(&resent).is_empty()); +} + +#[tokio::test] +async fn adapter_scoped_threads_do_not_wait_for_another_adapter() { + // An unfinished exchange cannot delay a record belonging to another adapter's same native thread id. + let claude = Named("claude", on_thread("t1")); + let codex = Named("codex", on_thread("t1")); + let mut capture = Capture::new(); + let earlier = capture.begin( + &claude, + None, + Emits { + events: Vec::new(), + release: None, + }, + ); + + let finished = tokio::time::timeout(Duration::from_millis(500), capture.run(&codex, None, closed_reply())).await; + drop(earlier); + + assert!(finished.is_ok()); + let lines = finished.unwrap(); + assert_eq!(record_of(&lines)["exchange"], 2); + assert!(step_edges(&lines).is_empty()); +} + +#[tokio::test] +async fn adapter_scoped_threads_still_wait_for_their_own_earlier_exchange() { + // The same adapter still writes its earlier record and edges before the later record. + let who = Named("claude", on_thread("t1")); + let mut capture = Capture::new(); + let earlier = capture.begin( + &who, + None, + Emits { + events: closed_reply(), + release: None, + }, + ); + let later = capture.begin( + &who, + None, + Emits { + events: closed_reply(), + release: None, + }, + ); + + later.end(Side::Response); + let_the_tasks_run().await; + let premature_record = + std::iter::from_fn(|| capture.drained.try_recv().ok()).any(|line| line.entry.event() == "record"); + earlier.end(Side::Response); + drop((earlier, later)); + let lines = capture.ended(2).await; + + assert!(!premature_record); + let record_order: Vec = lines + .iter() + .filter(|line| line["event"] == "record") + .map(|line| line["exchange"].as_u64().unwrap()) + .collect(); + assert_eq!(record_order, [1, 2]); + assert_eq!(step_edges(&lines), [edge("continues", "step:2.1", "step:1.1")]); +} + type Edge = (String, String, String); fn edge(kind: &str, from: &str, to: &str) -> Edge { @@ -1230,6 +1401,23 @@ async fn a_stalled_parser_gives_an_incomplete_record_that_counts_the_dropped_inp struct Identifying(Identity); +struct Named(&'static str, Identifying); + +impl Adapter for Named { + fn name(&self) -> &'static str { + self.0 + } + fn hosts(&self) -> &[String] { + &[] + } + fn claim(&self, _head: &RequestHead) -> Option> { + None + } + fn identity(&self, head: &RequestHead) -> Identity { + self.1.identity(head) + } +} + impl Adapter for Identifying { fn name(&self) -> &'static str { "test" diff --git a/src/graph/calls.rs b/src/graph/calls.rs index 30ec633..f82d89e 100644 --- a/src/graph/calls.rs +++ b/src/graph/calls.rs @@ -1,3 +1,4 @@ +use super::Thread; use crate::common::{Edge, EdgeKind}; use std::collections::{HashMap, VecDeque}; @@ -7,8 +8,8 @@ pub const CALL_BOUND: usize = 4096; /// Remembers the tool calls a reply made until a request carries their result. #[derive(Default)] pub struct Calls { - open: HashMap<(String, String), u64>, - order: VecDeque<((String, String), u64)>, + open: HashMap<(Thread, String), u64>, + order: VecDeque<((Thread, String), u64)>, next: u64, } @@ -16,20 +17,20 @@ impl Calls { /// The `calls` edges one step adds: one for each result in its request that answers an open /// call of the thread, which then closes, so a result resent in a later request adds nothing. /// The step's own calls are remembered after its results, as the request comes first. - pub fn edges(&mut self, thread: &str, results: &[String], calls: &[String]) -> Vec { + pub fn edges(&mut self, thread: &Thread, results: &[String], calls: &[String]) -> Vec { let mut edges = Vec::new(); for id in results.iter().filter(|id| !id.is_empty()) { - if self.open.remove(&(thread.to_string(), id.clone())).is_some() { + if self.open.remove(&(thread.clone(), id.clone())).is_some() { edges.push(Edge::new(EdgeKind::Calls, format!("call:{id}"), format!("result:{id}"))); } } for id in calls.iter().filter(|id| !id.is_empty()) { - self.remember((thread.to_string(), id.clone())); + self.remember((thread.clone(), id.clone())); } edges } - fn remember(&mut self, key: (String, String)) { + fn remember(&mut self, key: (Thread, String)) { self.next += 1; self.open.insert(key.clone(), self.next); self.order.push_back((key, self.next)); @@ -65,8 +66,8 @@ mod tests { // The reply makes the call, the next request carries the result let mut calls = Calls::default(); - let reply = calls.edges("t1", &[], &ids(&["c1"])); - let next = calls.edges("t1", &ids(&["c1"]), &[]); + let reply = calls.edges(&Thread::new("test", "t1"), &[], &ids(&["c1"])); + let next = calls.edges(&Thread::new("test", "t1"), &ids(&["c1"]), &[]); assert!(reply.is_empty()); assert_eq!(pairs(&next), [("call:c1", "result:c1")]); @@ -77,10 +78,10 @@ mod tests { fn a_result_resent_in_a_later_request_gives_no_second_edge() { // Every request resends the whole conversation, so old results come again let mut calls = Calls::default(); - calls.edges("t1", &[], &ids(&["c1"])); - calls.edges("t1", &ids(&["c1"]), &[]); + calls.edges(&Thread::new("test", "t1"), &[], &ids(&["c1"])); + calls.edges(&Thread::new("test", "t1"), &ids(&["c1"]), &[]); - assert!(calls.edges("t1", &ids(&["c1"]), &[]).is_empty()); + assert!(calls.edges(&Thread::new("test", "t1"), &ids(&["c1"]), &[]).is_empty()); } #[test] @@ -88,62 +89,68 @@ mod tests { // An unknown result is ignored, and a call that never gets a result adds nothing let mut calls = Calls::default(); - assert!(calls.edges("t1", &ids(&["gone"]), &ids(&["c1"])).is_empty()); + assert!(calls + .edges(&Thread::new("test", "t1"), &ids(&["gone"]), &ids(&["c1"])) + .is_empty()); } #[test] fn an_empty_id_is_ignored() { // An empty id names nothing, so it cannot pair unrelated calls and results let mut calls = Calls::default(); - calls.edges("t1", &[], &ids(&[""])); + calls.edges(&Thread::new("test", "t1"), &[], &ids(&[""])); - assert!(calls.edges("t1", &ids(&[""]), &[]).is_empty()); + assert!(calls.edges(&Thread::new("test", "t1"), &ids(&[""]), &[]).is_empty()); } #[test] fn a_result_matches_only_a_call_of_its_own_thread() { // Another thread may have used the same call id let mut calls = Calls::default(); - calls.edges("t1", &[], &ids(&["c1"])); + calls.edges(&Thread::new("test", "t1"), &[], &ids(&["c1"])); - assert!(calls.edges("t2", &ids(&["c1"]), &[]).is_empty()); - assert_eq!(calls.edges("t1", &ids(&["c1"]), &[]).len(), 1); + assert!(calls.edges(&Thread::new("test", "t2"), &ids(&["c1"]), &[]).is_empty()); + assert_eq!(calls.edges(&Thread::new("test", "t1"), &ids(&["c1"]), &[]).len(), 1); } #[test] fn several_results_in_one_request_each_give_an_edge() { // A reply may call several tools at once let mut calls = Calls::default(); - calls.edges("t1", &[], &ids(&["c1", "c2"])); + calls.edges(&Thread::new("test", "t1"), &[], &ids(&["c1", "c2"])); - let edges = calls.edges("t1", &ids(&["c1", "c2"]), &[]); + let edges = calls.edges(&Thread::new("test", "t1"), &ids(&["c1", "c2"]), &[]); assert_eq!(pairs(&edges), [("call:c1", "result:c1"), ("call:c2", "result:c2")]); } #[test] - fn the_oldest_open_call_is_forgotten_past_the_bound() { - // It keeps at most CALL_BOUND open calls, so unanswered calls cannot grow without limit + fn the_oldest_open_call_is_forgotten_past_the_global_bound_across_adapters() { + // Both adapters share CALL_BOUND, so a new adapter does not multiply retained calls. let mut calls = Calls::default(); + let thread = |n| Thread::new(if n % 2 == 0 { "claude" } else { "codex" }, "t1"); for n in 0..=CALL_BOUND { - calls.edges("t1", &[], &[format!("c{n}")]); + calls.edges(&thread(n), &[], &[format!("c{n}")]); } - assert!(calls.edges("t1", &ids(&["c0"]), &[]).is_empty()); - assert_eq!(calls.edges("t1", &[format!("c{CALL_BOUND}")], &[]).len(), 1); + assert!(calls.edges(&thread(0), &ids(&["c0"]), &[]).is_empty()); + assert_eq!( + calls.edges(&thread(CALL_BOUND), &[format!("c{CALL_BOUND}")], &[]).len(), + 1 + ); } #[test] fn answered_calls_do_not_make_the_order_list_grow_without_limit() { // A long run of answered calls behind one unanswered call keeps memory bounded let mut calls = Calls::default(); - calls.edges("t1", &[], &ids(&["first"])); + calls.edges(&Thread::new("test", "t1"), &[], &ids(&["first"])); for n in 0..CALL_BOUND * 4 { - calls.edges("t1", &[], &[format!("c{n}")]); - calls.edges("t1", &[format!("c{n}")], &[]); + calls.edges(&Thread::new("test", "t1"), &[], &[format!("c{n}")]); + calls.edges(&Thread::new("test", "t1"), &[format!("c{n}")], &[]); } assert!(calls.order.len() <= 2 * CALL_BOUND + 1); - assert_eq!(calls.edges("t1", &ids(&["first"]), &[]).len(), 1); + assert_eq!(calls.edges(&Thread::new("test", "t1"), &ids(&["first"]), &[]).len(), 1); } } diff --git a/src/graph/mod.rs b/src/graph/mod.rs index e8f78a3..c4fcde7 100644 --- a/src/graph/mod.rs +++ b/src/graph/mod.rs @@ -60,19 +60,32 @@ struct Seen { replies: HashMap, } +/// Native thread identity is scoped to the adapter that supplied it, not the capture epoch. +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct Thread { + adapter: &'static str, + id: String, +} + +impl Thread { + fn new(adapter: &'static str, id: &str) -> Self { + Self { adapter, id: id.into() } + } +} + /// Remembers the last step and the open tool calls of each thread, bounded, so a step can say which /// step it continues and which call its results answer. #[derive(Default)] struct Threads { - seen: HashMap, - order: VecDeque, + seen: HashMap, + order: VecDeque, calls: Calls, queue: Arc, } impl Threads { /// Puts an exchange in line among the exchanges of its thread, so its records can wait for earlier ones. - fn join(&self, thread: &str, exchange: u64) -> Place { + fn join(&self, thread: &Thread, exchange: u64) -> Place { self.queue.join(thread, exchange) } @@ -210,7 +223,7 @@ mod tests { fn step(thread: &str, exchange: u64, n: u64) -> Step { Step { - thread: Some(thread.into()), + thread: Some(Thread::new("test", thread)), exchange, n, turn: None, diff --git a/src/graph/place.rs b/src/graph/place.rs index c433d4d..3f4238d 100644 --- a/src/graph/place.rs +++ b/src/graph/place.rs @@ -1,3 +1,4 @@ +use super::Thread; use std::collections::{BTreeSet, HashMap}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; @@ -9,23 +10,23 @@ use tokio::time::timeout; /// written in the order their exchanges began. #[derive(Default)] pub(super) struct Queue { - waiting: Mutex>>, + waiting: Mutex>>, changed: Notify, } impl Queue { - pub(super) fn join(self: &Arc, thread: &str, exchange: u64) -> Place { + pub(super) fn join(self: &Arc, thread: &Thread, exchange: u64) -> Place { let mut waiting = self.waiting.lock().unwrap_or_else(PoisonError::into_inner); - waiting.entry(thread.to_owned()).or_default().insert(exchange); + waiting.entry(thread.clone()).or_default().insert(exchange); Place { queue: self.clone(), - thread: thread.to_owned(), + thread: thread.clone(), exchange, left: AtomicBool::new(false), } } - fn is_clear_before(&self, thread: &str, exchange: u64) -> bool { + fn is_clear_before(&self, thread: &Thread, exchange: u64) -> bool { let waiting = self.waiting.lock().unwrap_or_else(PoisonError::into_inner); waiting .get(thread) @@ -33,7 +34,7 @@ impl Queue { .is_none_or(|first| *first >= exchange) } - fn leave(&self, thread: &str, exchange: u64) { + fn leave(&self, thread: &Thread, exchange: u64) { let mut waiting = self.waiting.lock().unwrap_or_else(PoisonError::into_inner); if let Some(exchanges) = waiting.get_mut(thread) { exchanges.remove(&exchange); @@ -49,7 +50,7 @@ impl Queue { /// An exchange's place in line among the exchanges of its thread, held until the exchange ends. pub(super) struct Place { queue: Arc, - thread: String, + thread: Thread, exchange: u64, left: AtomicBool, } @@ -102,8 +103,8 @@ mod tests { async fn the_first_exchange_of_a_thread_does_not_wait() { // It goes ahead at once when no earlier exchange of its thread is in line let queue = Arc::::default(); - let first = queue.join("t1", 1); - let _second = queue.join("t1", 2); + let first = queue.join(&Thread::new("test", "t1"), 1); + let _second = queue.join(&Thread::new("test", "t1"), 2); assert!(took_less_than(SHORT, first.wait_for_turn(LONG)).await); } @@ -112,8 +113,8 @@ mod tests { async fn a_later_exchange_waits_until_the_earlier_one_leaves() { // It is held while the earlier exchange is in line, and goes ahead once that one leaves let queue = Arc::::default(); - let first = queue.join("t1", 1); - let second = queue.join("t1", 2); + let first = queue.join(&Thread::new("test", "t1"), 1); + let second = queue.join(&Thread::new("test", "t1"), 2); assert!(!took_less_than(SHORT, second.wait_for_turn(LONG)).await); first.leave(); @@ -125,8 +126,8 @@ mod tests { async fn a_later_exchange_goes_ahead_when_the_earlier_one_is_dropped() { // It does not wait for an exchange that ended without leaving let queue = Arc::::default(); - let first = queue.join("t1", 1); - let second = queue.join("t1", 2); + let first = queue.join(&Thread::new("test", "t1"), 1); + let second = queue.join(&Thread::new("test", "t1"), 2); drop(first); @@ -137,8 +138,8 @@ mod tests { async fn another_thread_does_not_hold_an_exchange_back() { // It orders exchanges only within their own thread let queue = Arc::::default(); - let _other = queue.join("t1", 1); - let mine = queue.join("t2", 2); + let _other = queue.join(&Thread::new("test", "t1"), 1); + let mine = queue.join(&Thread::new("test", "t2"), 2); assert!(took_less_than(SHORT, mine.wait_for_turn(LONG)).await); } @@ -147,8 +148,8 @@ mod tests { async fn a_waiting_exchange_is_woken_when_the_earlier_one_leaves() { // It goes ahead after the wait began, not only when it checks first let queue = Arc::::default(); - let first = queue.join("t1", 1); - let second = queue.join("t1", 2); + let first = queue.join(&Thread::new("test", "t1"), 1); + let second = queue.join(&Thread::new("test", "t1"), 2); let waiting = tokio::spawn(async move { second.wait_for_turn(LONG).await }); tokio::task::yield_now().await; @@ -161,8 +162,8 @@ mod tests { async fn an_exchange_that_has_left_does_not_wait_again() { // It lets the later records of an exchange through while an earlier exchange is still in line let queue = Arc::::default(); - let _first = queue.join("t1", 1); - let second = queue.join("t1", 2); + let _first = queue.join(&Thread::new("test", "t1"), 1); + let second = queue.join(&Thread::new("test", "t1"), 2); second.leave(); assert!(took_less_than(SHORT, second.wait_for_turn(LONG)).await); @@ -172,8 +173,8 @@ mod tests { async fn an_exchange_goes_ahead_after_the_limit_when_the_earlier_one_never_leaves() { // It stops waiting for an exchange that stays in line let queue = Arc::::default(); - let _first = queue.join("t1", 1); - let second = queue.join("t1", 2); + let _first = queue.join(&Thread::new("test", "t1"), 1); + let second = queue.join(&Thread::new("test", "t1"), 2); assert!(took_less_than(LONG, second.wait_for_turn(SHORT)).await); } diff --git a/src/graph/step.rs b/src/graph/step.rs index 0c06fe3..61e9278 100644 --- a/src/graph/step.rs +++ b/src/graph/step.rs @@ -1,4 +1,4 @@ -use super::Identity; +use super::Thread; use crate::event::Conversation; use crate::message::{Block, Message}; use crate::record::Record; @@ -7,7 +7,7 @@ use serde_json::Value; /// One request and its reply: the unit `turn` and `continues` link. #[derive(Clone, Debug, PartialEq)] pub(super) struct Step { - pub(super) thread: Option, + pub(super) thread: Option, pub(super) exchange: u64, pub(super) n: u64, pub(super) turn: Option, @@ -22,13 +22,18 @@ pub(super) struct Step { impl Step { /// The step a finished record describes, or none when the record has no request. A first step /// that names no turn is in the header turn; a later one may be in a new turn, so it has none. - pub(super) fn of_record(record: &Record, identity: &Identity, exchange: u64) -> Option { + pub(super) fn of_record( + record: &Record, + thread: Option<&Thread>, + header_turn: Option<&str>, + exchange: u64, + ) -> Option { let conversation = record.conversation.as_ref()?; let n = claimed_step(conversation); let text = |value: &Value| value.as_str().map(String::from); - let header_turn = (n == 1).then(|| identity.turn.clone()).flatten(); + let header_turn = header_turn.filter(|_| n == 1).map(str::to_owned); Some(Step { - thread: identity.thread.clone(), + thread: thread.cloned(), exchange, n, turn: conversation.turn.clone().or(header_turn), @@ -96,30 +101,23 @@ mod tests { } } - fn identity(turn: Option<&str>) -> Identity { - Identity { - thread: Some("t1".into()), - turn: turn.map(Into::into), - ..Identity::default() - } - } - #[test] fn a_first_step_that_names_no_turn_takes_the_header_turn() { // The header turn is the first request's let record = step_record(1, None); + let thread = Thread::new("test", "t1"); - let step = Step::of_record(&record, &identity(Some("h1")), 7).unwrap(); + let step = Step::of_record(&record, Some(&thread), Some("h1"), 7).unwrap(); assert_eq!(step.turn.as_deref(), Some("h1")); - assert_eq!((step.thread.as_deref(), step.exchange, step.n), (Some("t1"), 7, 1)); + assert_eq!((step.thread, step.exchange, step.n), (Some(thread), 7, 1)); } #[test] fn an_explicit_turn_beats_the_header_turn() { // A Codex step names its own turn, whichever step it is - let first = Step::of_record(&step_record(1, Some("u2")), &identity(Some("h1")), 7).unwrap(); - let later = Step::of_record(&step_record(3, Some("u2")), &identity(Some("h1")), 7).unwrap(); + let first = Step::of_record(&step_record(1, Some("u2")), None, Some("h1"), 7).unwrap(); + let later = Step::of_record(&step_record(3, Some("u2")), None, Some("h1"), 7).unwrap(); assert_eq!(first.turn.as_deref(), Some("u2")); assert_eq!(later.turn.as_deref(), Some("u2")); @@ -128,7 +126,7 @@ mod tests { #[test] fn a_later_step_that_names_no_turn_gets_none() { // The header turn does not carry past the first step - let step = Step::of_record(&step_record(2, None), &identity(Some("h1")), 7).unwrap(); + let step = Step::of_record(&step_record(2, None), None, Some("h1"), 7).unwrap(); assert_eq!(step.turn, None); } @@ -136,7 +134,7 @@ mod tests { #[test] fn a_record_without_a_request_gives_no_step() { // A reply with no request in front of it cannot be linked - assert_eq!(Step::of_record(&Record::empty(), &identity(Some("h1")), 7), None); + assert_eq!(Step::of_record(&Record::empty(), None, Some("h1"), 7), None); } #[test] @@ -163,7 +161,7 @@ mod tests { Block::text("y"), ]); - let step = Step::of_record(&record, &identity(None), 7).unwrap(); + let step = Step::of_record(&record, None, None, 7).unwrap(); assert_eq!(step.previous_message_id.as_deref(), Some("m1")); assert_eq!(step.message_id.as_deref(), Some("m2")); @@ -174,7 +172,7 @@ mod tests { #[test] fn a_record_with_none_of_the_ids_gives_a_bare_step() { // Missing ids are absent, not empty - let step = Step::of_record(&step_record(1, None), &Identity::default(), 7).unwrap(); + let step = Step::of_record(&step_record(1, None), None, None, 7).unwrap(); assert_eq!( step, diff --git a/src/graph/steps.rs b/src/graph/steps.rs index bf7c373..8ad0ee1 100644 --- a/src/graph/steps.rs +++ b/src/graph/steps.rs @@ -1,6 +1,6 @@ use super::place::Place; use super::step::{claimed_step, Step}; -use super::{Identity, Threads}; +use super::{Identity, Thread, Threads}; use crate::common::Edge; use crate::event::Event; use crate::record::Record; @@ -18,15 +18,17 @@ pub(crate) struct Tracker(Arc>); pub(crate) struct Steps { tracker: Tracker, place: Option, - identity: Identity, + thread: Option, + header_turn: Option, exchange: u64, open: Option, } impl Steps { /// Puts the exchange in line among the exchanges of its thread, so its records wait for earlier ones. - pub(crate) fn join(tracker: &Tracker, exchange: u64, identity: &Identity) -> Self { - let place = identity.thread.as_deref().map(|thread| { + pub(crate) fn join(tracker: &Tracker, exchange: u64, identity: &Identity, adapter: &'static str) -> Self { + let thread = identity.thread.as_deref().map(|id| Thread::new(adapter, id)); + let place = thread.as_ref().map(|thread| { tracker .0 .lock() @@ -36,7 +38,8 @@ impl Steps { Self { tracker: tracker.clone(), place, - identity: identity.clone(), + thread, + header_turn: identity.turn.clone(), exchange, open: None, } @@ -60,7 +63,8 @@ impl Steps { if let Some(place) = &self.place { place.wait_for_turn(TURN_WAIT).await; } - let Some(step) = Step::of_record(record, &self.identity, self.exchange) else { + let Some(step) = Step::of_record(record, self.thread.as_ref(), self.header_turn.as_deref(), self.exchange) + else { return Vec::new(); }; record.step = Some(step.n); @@ -126,7 +130,7 @@ mod tests { #[test] fn a_live_line_carries_the_step_of_the_request_it_is_folded_into() { // The request line and every line up to its reply end show its step; a line with no request open shows none - let mut steps = Steps::join(&Tracker::default(), 7, &Identity::default()); + let mut steps = Steps::join(&Tracker::default(), 7, &Identity::default(), "test"); let usage = Event::Usage(Default::default()); let before = steps.of_line(&usage); @@ -144,7 +148,7 @@ mod tests { #[test] fn a_request_that_states_no_step_opens_step_one() { // A Claude exchange is one request, so its lines show step 1 - let mut steps = Steps::join(&Tracker::default(), 7, &Identity::default()); + let mut steps = Steps::join(&Tracker::default(), 7, &Identity::default(), "test"); assert_eq!(steps.of_line(&Event::Conversation(request(None, None))), Some(1)); } @@ -152,7 +156,7 @@ mod tests { #[tokio::test] async fn a_request_that_states_its_step_and_turn_gives_them_to_the_record() { // It copies the step and turn of the conversation onto the record - let steps = Steps::join(&Tracker::default(), 7, &header_turn("h1")); + let steps = Steps::join(&Tracker::default(), 7, &header_turn("h1"), "test"); let mut record = record_of(Some(request(Some(3), Some("u2")))); steps.link(&mut record).await; @@ -163,8 +167,8 @@ mod tests { #[tokio::test] async fn a_request_that_states_no_step_is_step_one_of_the_header_turn() { // A Claude exchange is one request, so the record is step 1 in the turn its headers name, or none - let named = Steps::join(&Tracker::default(), 7, &header_turn("h1")); - let unnamed = Steps::join(&Tracker::default(), 7, &Identity::default()); + let named = Steps::join(&Tracker::default(), 7, &header_turn("h1"), "test"); + let unnamed = Steps::join(&Tracker::default(), 7, &Identity::default(), "test"); let mut in_turn = record_of(Some(request(None, None))); let mut no_turn = record_of(Some(request(None, None))); @@ -185,6 +189,7 @@ mod tests { thread: Some("t1".into()), ..header_turn("h1") }, + "test", ); let mut record = record_of(None); @@ -198,8 +203,8 @@ mod tests { async fn a_later_exchange_of_a_thread_continues_the_step_of_an_earlier_one() { // Exchanges that share a tracker link their steps across exchanges let tracker = Tracker::default(); - let first = Steps::join(&tracker, 1, &on_thread("t1")); - let second = Steps::join(&tracker, 2, &on_thread("t1")); + let first = Steps::join(&tracker, 1, &on_thread("t1"), "test"); + let second = Steps::join(&tracker, 2, &on_thread("t1"), "test"); first.link(&mut record_of(Some(request(None, None)))).await; first.leave(); @@ -207,4 +212,25 @@ mod tests { assert_eq!(edges, [Edge::new(EdgeKind::Continues, "step:2.1", "step:1.1")]); } + + #[tokio::test] + async fn the_thread_bound_is_shared_across_adapters() { + // Activity across both adapters evicts the oldest thread under one global bound. + let tracker = Tracker::default(); + let first = Steps::join(&tracker, 1, &on_thread("first"), "claude"); + first.link(&mut record_of(Some(request(None, None)))).await; + first.leave(); + + for exchange in 2..=super::super::THREAD_BOUND as u64 + 1 { + let adapter = if exchange % 2 == 0 { "claude" } else { "codex" }; + let identity = on_thread(&format!("t{}", exchange / 2)); + let steps = Steps::join(&tracker, exchange, &identity, adapter); + steps.link(&mut record_of(Some(request(None, None)))).await; + steps.leave(); + } + let revisited = Steps::join(&tracker, 9999, &on_thread("first"), "claude"); + let edges = revisited.link(&mut record_of(Some(request(None, None)))).await; + + assert!(edges.is_empty()); + } }