Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/direct-tool-timing/BUILD.bazel
Normal file
6
codex-rs/direct-tool-timing/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "direct-tool-timing",
|
||||
crate_name = "codex_direct_tool_timing",
|
||||
)
|
||||
20
codex-rs/direct-tool-timing/Cargo.toml
Normal file
20
codex-rs/direct-tool-timing/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "codex-direct-tool-timing"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[dependencies]
|
||||
codex-utils-critical-path = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
test-case = "3.3.1"
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync"] }
|
||||
tokio-util = { workspace = true }
|
||||
317
codex-rs/direct-tool-timing/src/direct_tool_timing_tests.rs
Normal file
317
codex-rs/direct-tool-timing/src/direct_tool_timing_tests.rs
Normal file
@@ -0,0 +1,317 @@
|
||||
use super::*;
|
||||
use codex_utils_critical_path::PathDurations;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn parallel_winner_retains_its_review_and_shared_initial_path() {
|
||||
let now = Instant::now();
|
||||
let start = now - Duration::from_secs(10);
|
||||
let shared_initial_path =
|
||||
CriticalPath::default().work(start, start + Duration::from_secs(1), WorkKind::Sampling);
|
||||
let batch = ToolBatchTiming::default();
|
||||
let timings = DirectToolTimings::default();
|
||||
let losing = timings.start_direct_call(
|
||||
"loser",
|
||||
batch.clone(),
|
||||
start + Duration::from_secs(1),
|
||||
Some(shared_initial_path.clone()),
|
||||
);
|
||||
let winner = timings.start_direct_call(
|
||||
"winner",
|
||||
batch.clone(),
|
||||
start + Duration::from_secs(1),
|
||||
Some(shared_initial_path),
|
||||
);
|
||||
{
|
||||
let mut state = timings.state();
|
||||
let work = state.unique_work("winner").unwrap();
|
||||
work.record_until(start + Duration::from_secs(2));
|
||||
work.active_auto_reviews = vec![ReviewExecution::default()];
|
||||
work.record_until(start + Duration::from_secs(5));
|
||||
work.active_auto_reviews.clear();
|
||||
}
|
||||
drop(losing);
|
||||
assert!(batch.completed().is_none());
|
||||
drop(winner);
|
||||
let completed = batch.completed().unwrap();
|
||||
assert_eq!(
|
||||
completed.path.unwrap().durations(start, completed.ended_at),
|
||||
PathDurations {
|
||||
sampling: Duration::from_secs(1),
|
||||
auto_review: Duration::from_secs(3),
|
||||
auto_review_overhead: None,
|
||||
tools: completed.ended_at.duration_since(start) - Duration::from_secs(4),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_ids_and_late_review_drop_do_not_complete_another_invocation() {
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let start = Instant::now();
|
||||
let first =
|
||||
timings.start_direct_call("same", batch.clone(), start, Some(CriticalPath::default()));
|
||||
let review = first.start_review().unwrap();
|
||||
let second =
|
||||
timings.start_direct_call("same", batch.clone(), start, Some(CriticalPath::default()));
|
||||
|
||||
drop(first);
|
||||
drop(review);
|
||||
assert_eq!(
|
||||
timings
|
||||
.state()
|
||||
.unique_work("same")
|
||||
.unwrap()
|
||||
.active_auto_reviews
|
||||
.len(),
|
||||
0
|
||||
);
|
||||
assert!(batch.completed().is_none());
|
||||
drop(second);
|
||||
assert!(batch.completed().unwrap().path.is_none());
|
||||
assert!(timings.state().calls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_review_start_does_not_attach_to_reused_call_id() {
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let first = timings.start_direct_call(
|
||||
"same",
|
||||
batch.clone(),
|
||||
Instant::now(),
|
||||
Some(CriticalPath::default()),
|
||||
);
|
||||
let review = first.start_review().unwrap();
|
||||
first.finish().unwrap();
|
||||
let started_at = Instant::now();
|
||||
let second = timings.start_direct_call(
|
||||
"same",
|
||||
batch.clone(),
|
||||
started_at,
|
||||
Some(CriticalPath::default()),
|
||||
);
|
||||
assert!(first.start_review().is_none());
|
||||
drop(review);
|
||||
drop(first);
|
||||
assert!(batch.completed().is_none());
|
||||
drop(second);
|
||||
let completed = batch.completed().unwrap();
|
||||
assert_eq!(
|
||||
completed
|
||||
.path
|
||||
.unwrap()
|
||||
.durations(started_at, completed.ended_at),
|
||||
PathDurations {
|
||||
tools: completed.ended_at.duration_since(started_at),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
assert!(timings.state().calls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_completes_once_and_review_can_outlive_call() {
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let work = timings.start_direct_call(
|
||||
"cancelled",
|
||||
batch.clone(),
|
||||
Instant::now(),
|
||||
Some(CriticalPath::default()),
|
||||
);
|
||||
let review = work.start_review().unwrap();
|
||||
let first = work.finish().unwrap();
|
||||
drop(work);
|
||||
drop(review);
|
||||
assert_eq!(batch.completed().unwrap().ended_at, first.ended_at);
|
||||
assert!(timings.state().calls.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_dependency_remains_unknown() {
|
||||
let start = Instant::now() - Duration::from_secs(1);
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let work =
|
||||
timings.start_direct_call("call", batch.clone(), start, Some(CriticalPath::default()));
|
||||
timings.join(
|
||||
"call",
|
||||
start,
|
||||
start + Duration::from_millis(500),
|
||||
/*dependency*/ None,
|
||||
);
|
||||
drop(work);
|
||||
let completed = batch.completed().unwrap();
|
||||
assert_eq!(
|
||||
completed
|
||||
.path
|
||||
.unwrap()
|
||||
.durations(start, completed.ended_at)
|
||||
.unknown,
|
||||
Duration::from_millis(500)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn human_wait_takes_precedence_over_reviews_and_overlapping_waits() {
|
||||
let start = Instant::now();
|
||||
let at = |seconds| start + Duration::from_secs(seconds);
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let _guard = timings.start_direct_call("call", batch, start, Some(CriticalPath::default()));
|
||||
let mut state = timings.state();
|
||||
let work = state.unique_work("call").unwrap();
|
||||
work.record_until(at(1));
|
||||
work.active_auto_reviews = vec![ReviewExecution::default()];
|
||||
work.record_until(at(2));
|
||||
work.active_user_waits = 1;
|
||||
work.record_until(at(3));
|
||||
work.active_user_waits = 2;
|
||||
work.record_until(at(4));
|
||||
work.active_user_waits = 1;
|
||||
work.record_until(at(5));
|
||||
work.active_user_waits = 0;
|
||||
work.record_until(at(6));
|
||||
work.active_auto_reviews.clear();
|
||||
work.record_until(at(7));
|
||||
assert_eq!(
|
||||
work.path.as_ref().unwrap().durations(start, at(7)),
|
||||
PathDurations {
|
||||
tools: Duration::from_secs(2),
|
||||
auto_review: Duration::from_secs(2),
|
||||
auto_review_overhead: None,
|
||||
user_wait: Duration::from_secs(3),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_wait_guards_balance_and_do_not_follow_reused_call_ids() {
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let first = timings.start_direct_call(
|
||||
"call",
|
||||
batch.clone(),
|
||||
Instant::now(),
|
||||
Some(CriticalPath::default()),
|
||||
);
|
||||
let first_wait = first.start_user_wait().unwrap();
|
||||
let nested_wait = first.start_user_wait().unwrap();
|
||||
assert_eq!(
|
||||
timings
|
||||
.state()
|
||||
.unique_work("call")
|
||||
.unwrap()
|
||||
.active_user_waits,
|
||||
2
|
||||
);
|
||||
drop(nested_wait);
|
||||
assert_eq!(
|
||||
timings
|
||||
.state()
|
||||
.unique_work("call")
|
||||
.unwrap()
|
||||
.active_user_waits,
|
||||
1
|
||||
);
|
||||
first.finish().unwrap();
|
||||
let next = timings.start_direct_call(
|
||||
"call",
|
||||
batch.clone(),
|
||||
Instant::now(),
|
||||
Some(CriticalPath::default()),
|
||||
);
|
||||
assert!(first.start_user_wait().is_none());
|
||||
drop(first_wait);
|
||||
assert_eq!(
|
||||
timings
|
||||
.state()
|
||||
.unique_work("call")
|
||||
.unwrap()
|
||||
.active_user_waits,
|
||||
0
|
||||
);
|
||||
drop(next);
|
||||
assert!(batch.completed().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observed_cached_review_is_all_overhead_and_human_wait_has_no_observer() {
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let start = Instant::now();
|
||||
let invocation =
|
||||
timings.start_direct_call("cached", batch, start, Some(CriticalPath::default()));
|
||||
let first = invocation.start_review().unwrap();
|
||||
let second = invocation.start_review().unwrap();
|
||||
let first_observer = first.review_execution().unwrap();
|
||||
let second_observer = second.review_execution().unwrap();
|
||||
assert_ne!(first_observer, second_observer);
|
||||
let human = invocation.start_user_wait().unwrap();
|
||||
assert!(human.review_execution().is_none());
|
||||
drop(first);
|
||||
assert_eq!(
|
||||
timings
|
||||
.state()
|
||||
.unique_work("cached")
|
||||
.unwrap()
|
||||
.active_auto_reviews,
|
||||
vec![second_observer]
|
||||
);
|
||||
drop(human);
|
||||
drop(second);
|
||||
let completed = invocation.finish().unwrap();
|
||||
let durations = completed.path.unwrap().durations(start, completed.ended_at);
|
||||
assert_eq!(durations.auto_review_overhead, Some(durations.auto_review));
|
||||
assert!(durations.auto_review > Duration::ZERO);
|
||||
assert!(durations.user_wait > Duration::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invocation_finish_freezes_unfinished_review_and_id_reuse_gets_new_observation() {
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let start = Instant::now();
|
||||
let first =
|
||||
timings.start_direct_call("same", batch.clone(), start, Some(CriticalPath::default()));
|
||||
let old_guard = first.start_review().unwrap();
|
||||
let old_observer = old_guard.review_execution().unwrap();
|
||||
let child_start = Instant::now();
|
||||
old_observer.started(child_start);
|
||||
let first_result = first.finish().unwrap();
|
||||
let old_path = first_result.path.unwrap();
|
||||
let old_durations = old_path.durations(start, first_result.ended_at);
|
||||
assert_eq!(old_durations.auto_review_overhead, None);
|
||||
|
||||
let next_start = Instant::now();
|
||||
let next = timings.start_direct_call("same", batch, next_start, Some(CriticalPath::default()));
|
||||
let next_guard = next.start_review().unwrap();
|
||||
let next_observer = next_guard.review_execution().unwrap();
|
||||
assert_ne!(old_observer, next_observer);
|
||||
old_observer.completed(child_start, Instant::now());
|
||||
drop(old_guard);
|
||||
assert_eq!(
|
||||
old_path.durations(start, first_result.ended_at),
|
||||
old_durations
|
||||
);
|
||||
assert_eq!(
|
||||
timings
|
||||
.state()
|
||||
.unique_work("same")
|
||||
.unwrap()
|
||||
.active_auto_reviews,
|
||||
vec![next_observer]
|
||||
);
|
||||
drop(next_guard);
|
||||
let next_result = next.finish().unwrap();
|
||||
let durations = next_result
|
||||
.path
|
||||
.unwrap()
|
||||
.durations(next_start, next_result.ended_at);
|
||||
assert_eq!(durations.auto_review_overhead, Some(durations.auto_review));
|
||||
}
|
||||
13
codex-rs/direct-tool-timing/src/lib.rs
Normal file
13
codex-rs/direct-tool-timing/src/lib.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
mod recorder;
|
||||
|
||||
pub use recorder::CompletedWork;
|
||||
pub use recorder::DirectToolTimings;
|
||||
pub use recorder::ToolBatchTiming;
|
||||
pub use recorder::ToolBlockingTimingGuard;
|
||||
pub use recorder::ToolTimingGuard;
|
||||
|
||||
pub use recorder::AdmittedToolTiming;
|
||||
pub use recorder::ToolAdmission;
|
||||
pub use recorder::ToolGateTiming;
|
||||
|
||||
pub use codex_utils_critical_path::ReviewExecution;
|
||||
375
codex-rs/direct-tool-timing/src/recorder.rs
Normal file
375
codex-rs/direct-tool-timing/src/recorder.rs
Normal file
@@ -0,0 +1,375 @@
|
||||
//! Records direct-tool invocations, automated reviews, human waits, and batch completion.
|
||||
//!
|
||||
//! Prefixes and dependency paths can contain any work kind; this recorder adds tool and
|
||||
//! review and human-wait intervals, or Unknown for a dependency wait whose history is unavailable.
|
||||
//! Review callbacks must retain their invocation guard and bracket blocking automated
|
||||
//! reviews with the review guard's lifetime. Runtime lookup retains weak owners;
|
||||
//! execution-lock admission timing is separate.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Instant;
|
||||
|
||||
mod runtime;
|
||||
pub use runtime::AdmittedToolTiming;
|
||||
pub use runtime::ToolAdmission;
|
||||
pub use runtime::ToolGateTiming;
|
||||
|
||||
use codex_utils_critical_path::CriticalPath;
|
||||
use codex_utils_critical_path::ReviewExecution;
|
||||
use codex_utils_critical_path::WorkKind;
|
||||
|
||||
/// Completion time and dependency history for one direct invocation.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CompletedWork {
|
||||
pub ended_at: Instant,
|
||||
pub path: Option<CriticalPath>,
|
||||
}
|
||||
|
||||
/// Tracks the last-finishing invocation after every invocation in a batch completes.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ToolBatchTiming(Arc<Mutex<BatchState>>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct BatchState {
|
||||
pending: usize,
|
||||
latest: Option<CompletedWork>,
|
||||
}
|
||||
|
||||
impl ToolBatchTiming {
|
||||
/// Returns the batch result only when no invocation remains active.
|
||||
pub fn completed(&self) -> Option<CompletedWork> {
|
||||
let state = self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
(state.pending == 0).then(|| state.latest.clone()).flatten()
|
||||
}
|
||||
|
||||
fn started(&self) {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.pending += 1;
|
||||
}
|
||||
|
||||
fn record(&self, work: CompletedWork) {
|
||||
let mut state = self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.pending -= 1;
|
||||
if state
|
||||
.latest
|
||||
.as_ref()
|
||||
.is_none_or(|previous| previous.ended_at < work.ended_at)
|
||||
{
|
||||
state.latest = Some(work);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns direct invocations; duplicate external call IDs invalidate attribution.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DirectToolTimings(Arc<Mutex<State>>);
|
||||
|
||||
impl std::fmt::Debug for DirectToolTimings {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DirectToolTimings").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
calls: HashMap<String, Vec<DirectToolInvocation>>,
|
||||
}
|
||||
|
||||
struct DirectToolInvocation {
|
||||
runtime_owner: Option<(String, std::sync::Weak<ToolTimingGuard>)>,
|
||||
identity: Arc<()>,
|
||||
path: Option<CriticalPath>,
|
||||
segment_started_at: Instant,
|
||||
active_auto_reviews: Vec<ReviewExecution>,
|
||||
active_user_waits: usize,
|
||||
batch: ToolBatchTiming,
|
||||
}
|
||||
|
||||
/// Finishes this invocation on drop; later blocking-guard drops cannot affect another call.
|
||||
pub struct ToolTimingGuard {
|
||||
identity: Arc<()>,
|
||||
timings: DirectToolTimings,
|
||||
call_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum BlockingKind {
|
||||
AutoReview,
|
||||
UserWait,
|
||||
}
|
||||
|
||||
/// Records a blocking interval until dropped; user waits take precedence over reviews.
|
||||
pub struct ToolBlockingTimingGuard {
|
||||
kind: BlockingKind,
|
||||
review: Option<ReviewExecution>,
|
||||
identity: Arc<()>,
|
||||
timings: DirectToolTimings,
|
||||
call_id: String,
|
||||
}
|
||||
|
||||
impl DirectToolInvocation {
|
||||
fn record_until(&mut self, now: Instant) {
|
||||
// A human answer can block an automated review. Attribute that overlap once,
|
||||
// to the human wait; all remaining invocation time is elapsed tool work.
|
||||
let kind = if self.active_user_waits > 0 {
|
||||
WorkKind::UserWait
|
||||
} else if !self.active_auto_reviews.is_empty() {
|
||||
WorkKind::AutoReview
|
||||
} else {
|
||||
WorkKind::Tools
|
||||
};
|
||||
self.path = self.path.take().map(|path| {
|
||||
if matches!(kind, WorkKind::AutoReview) {
|
||||
path.auto_review(
|
||||
self.segment_started_at,
|
||||
now,
|
||||
self.active_auto_reviews.clone(),
|
||||
)
|
||||
} else {
|
||||
path.work(self.segment_started_at, now, kind)
|
||||
}
|
||||
});
|
||||
self.segment_started_at = now;
|
||||
}
|
||||
|
||||
fn join(&mut self, start: Instant, end: Instant, dependency: Option<CriticalPath>) {
|
||||
self.record_until(start);
|
||||
self.path = self.path.take().map(|path| match dependency {
|
||||
Some(dependency) => path.join(start, end, dependency),
|
||||
None => path.work(start, end, WorkKind::Unknown),
|
||||
});
|
||||
self.segment_started_at = end;
|
||||
}
|
||||
}
|
||||
|
||||
impl DirectToolTimings {
|
||||
fn state(&self) -> std::sync::MutexGuard<'_, State> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Starts an invocation with its causal prefix, or no attribution when unavailable.
|
||||
pub fn start_direct_call(
|
||||
&self,
|
||||
call_id: &str,
|
||||
batch: ToolBatchTiming,
|
||||
started_at: Instant,
|
||||
prefix: Option<CriticalPath>,
|
||||
) -> ToolTimingGuard {
|
||||
batch.started();
|
||||
let path = prefix.map(|path| {
|
||||
let previous = path.end().unwrap_or(started_at);
|
||||
path.work(previous, started_at, WorkKind::Tools)
|
||||
});
|
||||
let identity = Arc::new(());
|
||||
let mut state = self.state();
|
||||
let calls = state.calls.entry(call_id.to_string()).or_default();
|
||||
let path = if calls.is_empty() {
|
||||
path
|
||||
} else {
|
||||
// External call IDs are not guaranteed unique. Keep each guard's
|
||||
// completion separate, but do not guess which invocation a lookup names.
|
||||
for work in calls.iter_mut() {
|
||||
work.path = None;
|
||||
}
|
||||
None
|
||||
};
|
||||
calls.push(DirectToolInvocation {
|
||||
runtime_owner: None,
|
||||
identity: Arc::clone(&identity),
|
||||
path,
|
||||
segment_started_at: started_at,
|
||||
active_auto_reviews: Vec::new(),
|
||||
active_user_waits: 0,
|
||||
batch,
|
||||
});
|
||||
ToolTimingGuard {
|
||||
identity,
|
||||
timings: self.clone(),
|
||||
call_id: call_id.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a dependency wait for a unique call ID; missing history becomes unknown time.
|
||||
pub fn join(
|
||||
&self,
|
||||
call_id: &str,
|
||||
start: Instant,
|
||||
end: Instant,
|
||||
dependency: Option<CriticalPath>,
|
||||
) {
|
||||
if let Some(work) = self.state().unique_work(call_id) {
|
||||
work.join(start, end, dependency);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_turn_direct_call(
|
||||
&self,
|
||||
call_id: &str,
|
||||
turn_id: &str,
|
||||
batch: ToolBatchTiming,
|
||||
started_at: Instant,
|
||||
prefix: Option<CriticalPath>,
|
||||
) -> Arc<ToolTimingGuard> {
|
||||
let work = Arc::new(self.start_direct_call(call_id, batch, started_at, prefix));
|
||||
let mut state = self.state();
|
||||
if let Some(invocation) = state.calls.get_mut(call_id).and_then(|calls| {
|
||||
calls
|
||||
.iter_mut()
|
||||
.find(|invocation| Arc::ptr_eq(&invocation.identity, &work.identity))
|
||||
}) {
|
||||
invocation.runtime_owner = Some((turn_id.to_owned(), Arc::downgrade(&work)));
|
||||
}
|
||||
work
|
||||
}
|
||||
|
||||
pub fn start_review_for_turn(
|
||||
&self,
|
||||
call_id: &str,
|
||||
turn_id: &str,
|
||||
) -> Option<ToolBlockingTimingGuard> {
|
||||
self.owner_for_turn(call_id, turn_id)?.start_review()
|
||||
}
|
||||
|
||||
pub fn owner_for_turn(&self, call_id: &str, turn_id: &str) -> Option<Arc<ToolTimingGuard>> {
|
||||
let mut state = self.state();
|
||||
let (owner_turn, owner) = state.unique_work(call_id)?.runtime_owner.as_ref()?;
|
||||
if owner_turn != turn_id {
|
||||
return None;
|
||||
}
|
||||
// Retain the invocation identity across registry unlock and later ID reuse.
|
||||
owner.upgrade()
|
||||
}
|
||||
|
||||
fn finish(&self, call_id: &str, identity: &Arc<()>) -> Option<CompletedWork> {
|
||||
let mut state = self.state();
|
||||
let calls = state.calls.get_mut(call_id)?;
|
||||
let index = calls
|
||||
.iter()
|
||||
.position(|work| Arc::ptr_eq(&work.identity, identity))?;
|
||||
let mut work = calls.swap_remove(index);
|
||||
if calls.is_empty() {
|
||||
state.calls.remove(call_id);
|
||||
}
|
||||
let ended_at = Instant::now();
|
||||
work.record_until(ended_at);
|
||||
for review in &work.active_auto_reviews {
|
||||
review.seal();
|
||||
}
|
||||
let completed = CompletedWork {
|
||||
ended_at,
|
||||
path: work.path,
|
||||
};
|
||||
work.batch.record(completed.clone());
|
||||
Some(completed)
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn unique_work(&mut self, call_id: &str) -> Option<&mut DirectToolInvocation> {
|
||||
let [work] = self.calls.get_mut(call_id)?.as_mut_slice() else {
|
||||
return None;
|
||||
};
|
||||
Some(work)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolTimingGuard {
|
||||
/// Starts a review only for this invocation, including after external call ID reuse.
|
||||
pub fn start_review(&self) -> Option<ToolBlockingTimingGuard> {
|
||||
self.start_blocking(BlockingKind::AutoReview)
|
||||
}
|
||||
|
||||
/// Starts a human wait for this invocation, taking precedence over automated review.
|
||||
pub fn start_user_wait(&self) -> Option<ToolBlockingTimingGuard> {
|
||||
self.start_blocking(BlockingKind::UserWait)
|
||||
}
|
||||
|
||||
fn start_blocking(&self, kind: BlockingKind) -> Option<ToolBlockingTimingGuard> {
|
||||
let mut state = self.timings.state();
|
||||
let work = state
|
||||
.calls
|
||||
.get_mut(&self.call_id)?
|
||||
.iter_mut()
|
||||
.find(|work| Arc::ptr_eq(&work.identity, &self.identity))?;
|
||||
work.record_until(Instant::now());
|
||||
let review = match kind {
|
||||
BlockingKind::AutoReview => {
|
||||
let review = ReviewExecution::default();
|
||||
work.active_auto_reviews.push(review.clone());
|
||||
Some(review)
|
||||
}
|
||||
BlockingKind::UserWait => {
|
||||
work.active_user_waits += 1;
|
||||
None
|
||||
}
|
||||
};
|
||||
Some(ToolBlockingTimingGuard {
|
||||
kind,
|
||||
review,
|
||||
identity: Arc::clone(&self.identity),
|
||||
timings: self.timings.clone(),
|
||||
call_id: self.call_id.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Completes this invocation once; subsequent calls and drop have no effect.
|
||||
pub fn finish(&self) -> Option<CompletedWork> {
|
||||
self.timings.finish(&self.call_id, &self.identity)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ToolTimingGuard {
|
||||
fn drop(&mut self) {
|
||||
self.finish();
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolBlockingTimingGuard {
|
||||
/// Returns the observer for this exact review; human waits have no observer.
|
||||
/// Call before submitting child work, including when a cached review runs no child.
|
||||
pub fn review_execution(&self) -> Option<ReviewExecution> {
|
||||
let review = self.review.as_ref()?;
|
||||
review.observe();
|
||||
Some(review.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ToolBlockingTimingGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(review) = &self.review {
|
||||
review.seal();
|
||||
}
|
||||
if let Some(calls) = self.timings.state().calls.get_mut(&self.call_id)
|
||||
&& let Some(work) = calls
|
||||
.iter_mut()
|
||||
.find(|work| Arc::ptr_eq(&work.identity, &self.identity))
|
||||
{
|
||||
work.record_until(Instant::now());
|
||||
match self.kind {
|
||||
BlockingKind::AutoReview => {
|
||||
work.active_auto_reviews
|
||||
.retain(|review| Some(review) != self.review.as_ref());
|
||||
}
|
||||
BlockingKind::UserWait => {
|
||||
work.active_user_waits = work.active_user_waits.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "direct_tool_timing_tests.rs"]
|
||||
mod tests;
|
||||
90
codex-rs/direct-tool-timing/src/recorder/runtime.rs
Normal file
90
codex-rs/direct-tool-timing/src/recorder/runtime.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
//! Records runtime execution-lock handoffs.
|
||||
//!
|
||||
//! Admission guards must finish before their execution lock is released, so the
|
||||
//! next admitted invocation can inherit the completed dependency path.
|
||||
|
||||
use super::CompletedWork;
|
||||
use super::ToolTimingGuard;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Instant;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum ToolAdmission {
|
||||
Parallel,
|
||||
Exclusive,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct ToolGateTiming(Arc<Mutex<GateState>>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct GateState {
|
||||
latest: Option<CompletedWork>,
|
||||
writer: Option<CompletedWork>,
|
||||
}
|
||||
|
||||
pub struct AdmittedToolTiming {
|
||||
work: Arc<ToolTimingGuard>,
|
||||
gate: ToolGateTiming,
|
||||
admission: ToolAdmission,
|
||||
}
|
||||
|
||||
impl ToolGateTiming {
|
||||
pub fn admit(
|
||||
&self,
|
||||
work: Arc<ToolTimingGuard>,
|
||||
admission: ToolAdmission,
|
||||
started_at: Instant,
|
||||
) -> AdmittedToolTiming {
|
||||
let state = self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let dependency = match admission {
|
||||
ToolAdmission::Parallel => &state.writer,
|
||||
ToolAdmission::Exclusive => &state.latest,
|
||||
};
|
||||
if let Some(dependency) = dependency
|
||||
&& dependency.ended_at > started_at
|
||||
{
|
||||
work.timings.join(
|
||||
&work.call_id,
|
||||
started_at,
|
||||
Instant::now(),
|
||||
dependency.path.clone(),
|
||||
);
|
||||
}
|
||||
AdmittedToolTiming {
|
||||
work,
|
||||
gate: self.clone(),
|
||||
admission,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AdmittedToolTiming {
|
||||
fn drop(&mut self) {
|
||||
if let Some(completed) = self.work.finish() {
|
||||
let mut state = self
|
||||
.gate
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if matches!(self.admission, ToolAdmission::Exclusive) {
|
||||
state.writer = Some(completed.clone());
|
||||
}
|
||||
if state
|
||||
.latest
|
||||
.as_ref()
|
||||
.is_none_or(|previous| previous.ended_at < completed.ended_at)
|
||||
{
|
||||
state.latest = Some(completed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "runtime_tests.rs"]
|
||||
mod tests;
|
||||
101
codex-rs/direct-tool-timing/src/recorder/runtime_tests.rs
Normal file
101
codex-rs/direct-tool-timing/src/recorder/runtime_tests.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
#![cfg(test)]
|
||||
//! Verifies dependency publication at real execution-lock handoffs.
|
||||
|
||||
use super::super::DirectToolTimings;
|
||||
use super::super::ToolBatchTiming;
|
||||
use super::*;
|
||||
use codex_utils_critical_path::CriticalPath;
|
||||
use codex_utils_critical_path::PathDurations;
|
||||
use codex_utils_critical_path::ReviewExecution;
|
||||
use codex_utils_critical_path::WorkKind;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::future::Future;
|
||||
use std::task::Context;
|
||||
use std::task::Waker;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio_util::either::Either;
|
||||
|
||||
#[test_case::test_case(ToolAdmission::Parallel; "parallel_after_exclusive")]
|
||||
#[test_case::test_case(ToolAdmission::Exclusive; "exclusive_after_parallel")]
|
||||
#[tokio::test]
|
||||
async fn lock_handoff_publishes_review_history_before_admitting_waiter(admission: ToolAdmission) {
|
||||
let start = Instant::now() - Duration::from_secs(10);
|
||||
let tool_start = start + Duration::from_secs(1);
|
||||
let shared_initial_path = CriticalPath::default().work(start, tool_start, WorkKind::Sampling);
|
||||
let timings = DirectToolTimings::default();
|
||||
let batch = ToolBatchTiming::default();
|
||||
let gate = ToolGateTiming::default();
|
||||
let lock = RwLock::new(());
|
||||
let (releasing_lock, releasing_admission) = match admission {
|
||||
ToolAdmission::Parallel => (Either::Left(lock.write().await), ToolAdmission::Exclusive),
|
||||
ToolAdmission::Exclusive => (Either::Right(lock.read().await), ToolAdmission::Parallel),
|
||||
};
|
||||
let releasing_work = timings.start_turn_direct_call(
|
||||
"releasing",
|
||||
"turn",
|
||||
batch.clone(),
|
||||
tool_start,
|
||||
Some(shared_initial_path.clone()),
|
||||
);
|
||||
let releasing_timing = gate.admit(releasing_work, releasing_admission, tool_start);
|
||||
// Fixed historical boundaries keep attribution exact without sleeping for a review.
|
||||
{
|
||||
let mut state = timings.state();
|
||||
let work = state.unique_work("releasing").unwrap();
|
||||
work.record_until(start + Duration::from_secs(2));
|
||||
work.active_auto_reviews = vec![ReviewExecution::default()];
|
||||
work.record_until(start + Duration::from_secs(5));
|
||||
work.active_auto_reviews.clear();
|
||||
}
|
||||
let waiting_work = timings.start_turn_direct_call(
|
||||
"waiting",
|
||||
"turn",
|
||||
batch.clone(),
|
||||
tool_start,
|
||||
Some(shared_initial_path),
|
||||
);
|
||||
let acquire_waiting_lock = async {
|
||||
match admission {
|
||||
ToolAdmission::Parallel => Either::Left(lock.read().await),
|
||||
ToolAdmission::Exclusive => Either::Right(lock.write().await),
|
||||
}
|
||||
};
|
||||
tokio::pin!(acquire_waiting_lock);
|
||||
let mut context = Context::from_waker(Waker::noop());
|
||||
assert!(
|
||||
acquire_waiting_lock
|
||||
.as_mut()
|
||||
.poll(&mut context)
|
||||
.is_pending()
|
||||
);
|
||||
|
||||
// Runtime cleanup must publish the dependency while it still holds the execution lock.
|
||||
drop(releasing_timing);
|
||||
assert!(batch.completed().is_none());
|
||||
assert!(
|
||||
acquire_waiting_lock
|
||||
.as_mut()
|
||||
.poll(&mut context)
|
||||
.is_pending()
|
||||
);
|
||||
drop(releasing_lock);
|
||||
let waiting_lock = acquire_waiting_lock.await;
|
||||
let waiting_timing = gate.admit(waiting_work, admission, tool_start);
|
||||
assert!(batch.completed().is_none());
|
||||
drop(waiting_timing);
|
||||
drop(waiting_lock);
|
||||
|
||||
let completed = batch.completed().unwrap();
|
||||
assert_eq!(
|
||||
completed.path.unwrap().durations(start, completed.ended_at),
|
||||
PathDurations {
|
||||
sampling: Duration::from_secs(1),
|
||||
auto_review: Duration::from_secs(3),
|
||||
auto_review_overhead: None,
|
||||
tools: completed.ended_at.duration_since(start) - Duration::from_secs(4),
|
||||
..PathDurations::default()
|
||||
}
|
||||
);
|
||||
assert!(timings.state().calls.is_empty());
|
||||
}
|
||||
Reference in New Issue
Block a user