aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,615 @@
//! Reducer coverage for exclusive attribution, parallel joins, ties, and incomplete evidence.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn join_replaces_overlapping_work_with_the_full_winning_branch() {
let turn_start = Instant::now();
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
let shared_initial_path = CriticalPath::default().work(
time_after_turn_start(0),
time_after_turn_start(100),
WorkKind::Sampling,
);
let reviewed_tool_path = shared_initial_path
.clone()
.work(
time_after_turn_start(100),
time_after_turn_start(300),
WorkKind::AutoReview,
)
.work(
time_after_turn_start(300),
time_after_turn_start(400),
WorkKind::Tools,
);
let parallel_tool_path = shared_initial_path.clone().work(
time_after_turn_start(100),
time_after_turn_start(700),
WorkKind::Tools,
);
let critical_path = shared_initial_path
.work(
time_after_turn_start(100),
time_after_turn_start(200),
WorkKind::Sampling,
)
.join(
time_after_turn_start(200),
time_after_turn_start(700),
reviewed_tool_path.latest(parallel_tool_path),
);
assert_eq!(
critical_path.durations(time_after_turn_start(0), time_after_turn_start(700)),
PathDurations {
sampling: Duration::from_millis(100),
tools: Duration::from_millis(600),
..PathDurations::default()
}
);
}
#[test]
fn nested_serial_dependencies_preserve_exclusive_categories() {
let turn_start = Instant::now();
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
let shared_initial_path = CriticalPath::default().work(
time_after_turn_start(0),
time_after_turn_start(100),
WorkKind::Sampling,
);
let child_path = shared_initial_path
.clone()
.work(
time_after_turn_start(100),
time_after_turn_start(300),
WorkKind::AutoReview,
)
.work(
time_after_turn_start(300),
time_after_turn_start(400),
WorkKind::Tools,
)
.work(
time_after_turn_start(400),
time_after_turn_start(500),
WorkKind::Compaction,
);
let critical_path = shared_initial_path
.work(
time_after_turn_start(100),
time_after_turn_start(200),
WorkKind::Sampling,
)
.join(
time_after_turn_start(200),
time_after_turn_start(600),
child_path,
);
assert_eq!(
critical_path.durations(time_after_turn_start(0), time_after_turn_start(600)),
PathDurations {
sampling: Duration::from_millis(100),
compaction: Duration::from_millis(100),
auto_review: Duration::from_millis(200),
auto_review_overhead: None,
tools: Duration::from_millis(200),
..PathDurations::default()
}
);
}
#[test]
fn equal_finish_times_select_one_path_without_double_counting() {
let turn_start = Instant::now();
let turn_end = turn_start + Duration::from_millis(100);
let reviewed_tool_path =
CriticalPath::default().work(turn_start, turn_end, WorkKind::AutoReview);
let inference_path = CriticalPath::default().work(turn_start, turn_end, WorkKind::Sampling);
// A tie has multiple valid paths. Stable left selection does not sum both.
assert_eq!(
reviewed_tool_path
.clone()
.latest(inference_path)
.durations(turn_start, turn_end),
reviewed_tool_path.durations(turn_start, turn_end)
);
}
#[test]
fn path_retention_exhaustion_marks_unknown_instead_of_claiming_zero() {
let turn_start = Instant::now();
let mut critical_path = CriticalPath::default();
for segment_index in 0..=MAX_PATH_DEPTH {
critical_path = critical_path.work(
turn_start + Duration::from_micros(segment_index as u64),
turn_start + Duration::from_micros(segment_index as u64 + 1),
WorkKind::Sampling,
);
}
let turn_end = turn_start + Duration::from_micros(MAX_PATH_DEPTH as u64 + 1);
assert_eq!(
critical_path.durations(turn_start, turn_end),
PathDurations {
unknown: turn_end.duration_since(turn_start),
auto_review_overhead: None,
..Default::default()
}
);
}
#[test]
fn reviewed_branch_wins_even_when_some_review_overlapped_parent_inference() {
let turn_start = Instant::now();
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
let shared_initial_path = CriticalPath::default().work(
time_after_turn_start(0),
time_after_turn_start(100),
WorkKind::Sampling,
);
let reviewed_tool_path = shared_initial_path
.clone()
.work(
time_after_turn_start(100),
time_after_turn_start(300),
WorkKind::AutoReview,
)
.work(
time_after_turn_start(300),
time_after_turn_start(400),
WorkKind::Tools,
);
let parallel_tool_path = shared_initial_path.clone().work(
time_after_turn_start(100),
time_after_turn_start(350),
WorkKind::Tools,
);
let critical_path = shared_initial_path
.work(
time_after_turn_start(100),
time_after_turn_start(200),
WorkKind::Sampling,
)
.join(
time_after_turn_start(200),
time_after_turn_start(400),
reviewed_tool_path.latest(parallel_tool_path),
);
assert_eq!(
critical_path.durations(time_after_turn_start(0), time_after_turn_start(400)),
PathDurations {
sampling: Duration::from_millis(100),
auto_review: Duration::from_millis(200),
auto_review_overhead: None,
tools: Duration::from_millis(100),
..Default::default()
}
);
}
#[test]
fn durations_clip_work_to_the_window_and_attribute_gaps_to_overhead() {
let turn_start = Instant::now();
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
let critical_path = CriticalPath::default()
.work(
time_after_turn_start(10),
time_after_turn_start(30),
WorkKind::Sampling,
)
.work(
time_after_turn_start(50),
time_after_turn_start(90),
WorkKind::AutoReview,
);
assert_eq!(
critical_path.durations(time_after_turn_start(0), time_after_turn_start(100)),
PathDurations {
sampling: Duration::from_millis(20),
auto_review: Duration::from_millis(40),
auto_review_overhead: None,
overhead: Duration::from_millis(40),
..PathDurations::default()
}
);
assert_eq!(
critical_path.durations(time_after_turn_start(20), time_after_turn_start(80)),
PathDurations {
sampling: Duration::from_millis(10),
auto_review: Duration::from_millis(30),
auto_review_overhead: None,
overhead: Duration::from_millis(20),
..PathDurations::default()
}
);
}
#[test]
fn overlapping_work_only_attributes_time_after_the_existing_path() {
let turn_start = Instant::now();
let time_after_turn_start = |milliseconds| turn_start + Duration::from_millis(milliseconds);
let critical_path = CriticalPath::default()
.work(
time_after_turn_start(0),
time_after_turn_start(10),
WorkKind::Sampling,
)
.work(
time_after_turn_start(5),
time_after_turn_start(20),
WorkKind::Tools,
);
assert_eq!(
critical_path.durations(time_after_turn_start(0), time_after_turn_start(20)),
PathDurations {
sampling: Duration::from_millis(10),
tools: Duration::from_millis(10),
..PathDurations::default()
}
);
assert_eq!(
critical_path.clone().work(
time_after_turn_start(5),
time_after_turn_start(15),
WorkKind::AutoReview
),
critical_path
);
assert_eq!(
critical_path.clone().work(
time_after_turn_start(20),
time_after_turn_start(20),
WorkKind::Unknown
),
critical_path
);
}
#[test]
fn long_path_debug_output_is_bounded_on_a_small_stack() {
// Match a typical 2 MiB worker stack rather than nextest's larger test stack.
std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(|| {
let start = Instant::now();
let mut path = CriticalPath::default();
for index in 0..10_000 {
path = path.work(
start + Duration::from_micros(index),
start + Duration::from_micros(index + 1),
WorkKind::Sampling,
);
}
assert!(format!("{path:?}").len() < 512);
assert!(format!("{path:#?}").len() < 512);
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn retained_prefixes_can_be_released_concurrently_on_small_stacks() {
for _ in 0..8 {
let start = Instant::now();
let mut path = CriticalPath::default();
let mut prefixes = [Vec::new(), Vec::new()];
for index in 0..MAX_PATH_DEPTH {
path = path.work(
start + Duration::from_micros(index as u64),
start + Duration::from_micros(index as u64 + 1),
WorkKind::Sampling,
);
prefixes[index % 2].push(path.clone());
}
// Only the workers retain nodes when they begin releasing prefixes.
drop(path);
let ready = Arc::new(std::sync::Barrier::new(3));
let workers = prefixes.map(|mut prefixes| {
let ready = Arc::clone(&ready);
std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(move || {
ready.wait();
// Release newest first so adjacent retained prefixes race
// to become the last owner of the shared chain.
while let Some(prefix) = prefixes.pop() {
drop(prefix);
}
})
.unwrap()
});
ready.wait();
for worker in workers {
worker.join().unwrap();
}
}
}
#[test]
fn human_wait_is_retained_only_on_the_selected_parallel_path() {
let start = Instant::now();
let time_after_turn_start = |milliseconds| start + Duration::from_millis(milliseconds);
let prefix =
CriticalPath::default().work(start, time_after_turn_start(100), WorkKind::Sampling);
let reviewed_tool = prefix
.clone()
.work(
time_after_turn_start(100),
time_after_turn_start(200),
WorkKind::AutoReview,
)
.work(
time_after_turn_start(200),
time_after_turn_start(500),
WorkKind::UserWait,
)
.work(
time_after_turn_start(500),
time_after_turn_start(600),
WorkKind::Tools,
);
let parallel_tool = prefix.clone().work(
time_after_turn_start(100),
time_after_turn_start(400),
WorkKind::Tools,
);
let path = prefix.join(
time_after_turn_start(100),
time_after_turn_start(600),
parallel_tool.latest(reviewed_tool),
);
assert_eq!(
path.durations(start, time_after_turn_start(600)),
PathDurations {
sampling: Duration::from_millis(100),
auto_review: Duration::from_millis(100),
auto_review_overhead: None,
user_wait: Duration::from_millis(300),
tools: Duration::from_millis(100),
..PathDurations::default()
}
);
}
fn observed_review(intervals: &[(Instant, Instant)]) -> ReviewExecution {
let review = ReviewExecution::default();
review.observe();
for &(start, end) in intervals {
review.started(start);
review.completed(start, end);
}
review.seal();
review
}
#[test]
fn review_overhead_is_the_execution_complement_and_clips_to_the_requested_window() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
let review = observed_review(&[(at(1000), at(4633))]);
let path = CriticalPath::default().auto_review(start, at(5000), vec![review]);
assert_eq!(
path.durations(start, at(5000)),
PathDurations {
auto_review: Duration::from_millis(5000),
auto_review_overhead: Some(Duration::from_millis(1367)),
..Default::default()
}
);
assert_eq!(
path.durations(at(500), at(4800)),
PathDurations {
auto_review: Duration::from_millis(4300),
auto_review_overhead: Some(Duration::from_millis(667)),
..Default::default()
}
);
}
#[test]
fn overlapping_reviews_and_retries_subtract_a_clipped_union_once() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
let first = observed_review(&[(at(0), at(30)), (at(25), at(50))]);
let second = observed_review(&[(at(40), at(60)), (at(80), at(120))]);
let path = CriticalPath::default().auto_review(at(10), at(100), vec![first, second]);
assert_eq!(
path.durations(at(10), at(100)),
PathDurations {
auto_review: Duration::from_millis(90),
auto_review_overhead: Some(Duration::from_millis(20)),
..Default::default()
}
);
}
#[test]
fn human_wait_overlap_is_excluded_from_both_review_components() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
let review = observed_review(&[(at(20), at(80))]);
let path = CriticalPath::default()
.auto_review(start, at(40), vec![review.clone()])
.work(at(40), at(70), WorkKind::UserWait)
.auto_review(at(70), at(100), vec![review]);
assert_eq!(
path.durations(start, at(100)),
PathDurations {
auto_review: Duration::from_millis(70),
auto_review_overhead: Some(Duration::from_millis(40)),
user_wait: Duration::from_millis(30),
..Default::default()
}
);
}
#[test]
fn cached_review_has_only_overhead_and_losing_review_has_no_contribution() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
let reviewed = CriticalPath::default().auto_review(start, at(10), vec![observed_review(&[])]);
assert_eq!(
reviewed.durations(start, at(10)),
PathDurations {
auto_review: Duration::from_millis(10),
auto_review_overhead: Some(Duration::from_millis(10)),
..Default::default()
}
);
let winner = CriticalPath::default().work(start, at(20), WorkKind::Tools);
assert_eq!(
reviewed.latest(winner).durations(start, at(20)),
PathDurations {
tools: Duration::from_millis(20),
..Default::default()
}
);
}
#[test]
fn incomplete_or_unobserved_reviews_leave_the_subcomponent_unknown() {
let start = Instant::now();
let end = start + Duration::from_millis(10);
let unobserved = ReviewExecution::default();
let canceled = ReviewExecution::default();
canceled.observe();
canceled.started(start);
let missing = ReviewExecution::default();
missing.observe();
missing.mark_unknown();
for review in [unobserved, canceled, missing] {
review.seal();
let path = CriticalPath::default().auto_review(start, end, vec![review.clone()]);
let expected = PathDurations {
auto_review: Duration::from_millis(10),
auto_review_overhead: None,
..Default::default()
};
assert_eq!(path.durations(start, end), expected);
review.observe();
review.completed(start, end);
assert_eq!(path.durations(start, end), expected);
}
}
#[test]
fn one_completed_retry_does_not_hide_another_canceled_attempt() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
let review = ReviewExecution::default();
review.observe();
review.started(at(1));
review.started(at(2));
review.completed(at(2), at(5));
review.seal();
assert_eq!(
CriticalPath::default()
.auto_review(start, at(10), vec![review])
.durations(start, at(10)),
PathDurations {
auto_review: Duration::from_millis(10),
auto_review_overhead: None,
..Default::default()
}
);
}
#[test]
fn indistinguishable_concurrent_attempts_remain_unknown_after_one_completes() {
let start = Instant::now();
let end = start + Duration::from_millis(10);
let review = ReviewExecution::default();
review.observe();
review.started(start);
review.started(start);
review.completed(start, end);
review.seal();
assert_eq!(
CriticalPath::default()
.auto_review(start, end, vec![review])
.durations(start, end),
PathDurations {
auto_review: Duration::from_millis(10),
auto_review_overhead: None,
..Default::default()
}
);
}
#[test]
fn sealing_before_submission_starts_freezes_unknown_attribution() {
let start = Instant::now();
let end = start + Duration::from_millis(10);
let review = ReviewExecution::default();
review.observe();
let attempt = review.start_attempt();
review.seal();
let path = CriticalPath::default().auto_review(start, end, vec![review.clone()]);
let expected = PathDurations {
auto_review: Duration::from_millis(10),
auto_review_overhead: None,
..Default::default()
};
assert_eq!(path.durations(start, end), expected);
review.started(start);
review.completed(start, end);
attempt.finish(/*known*/ true);
assert_eq!(path.durations(start, end), expected);
}
#[test]
fn completed_attempts_resolve_only_when_all_submissions_have_known_outcomes() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
for known in [true, false] {
let review = ReviewExecution::default();
review.observe();
let first = review.start_attempt();
let second = review.start_attempt();
review.started(at(2));
review.completed(at(2), at(7));
first.finish(/*known*/ true);
let path = CriticalPath::default().auto_review(start, at(10), vec![review.clone()]);
assert_eq!(path.durations(start, at(10)).auto_review_overhead, None);
second.finish(known);
review.seal();
assert_eq!(
path.durations(start, at(10)),
PathDurations {
auto_review: Duration::from_millis(10),
auto_review_overhead: known.then_some(Duration::from_millis(5)),
..Default::default()
}
);
}
}
#[test]
fn incomplete_attempt_does_not_label_unobserved_execution_as_overhead() {
for completed in [false, true] {
let execution = ReviewExecution::default();
execution.observe();
let attempt = execution.start_attempt();
let start = Instant::now();
let end = start + Duration::from_millis(100);
if completed {
execution.started(start);
execution.completed(start, end);
attempt.finish(/*known*/ true);
} else {
drop(attempt);
}
execution.seal();
let totals = CriticalPath::default()
.auto_review(start, end, vec![execution])
.durations(start, end);
assert_eq!(
totals.auto_review_overhead,
completed.then_some(Duration::ZERO)
);
}
}

View File

@@ -0,0 +1,235 @@
//! Persistent dependency paths and exclusive attribution over the observed turn interval.
//! History is depth-limited; formatting and destruction never recurse through the chain.
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
mod review_execution;
pub use review_execution::ReviewExecution;
pub use review_execution::ReviewExecutionAttempt;
const MAX_PATH_DEPTH: usize = 16_384;
/// Category attributed to an observed segment of dependency work.
#[derive(Clone, Copy, Debug)]
pub enum WorkKind {
/// Model sampling work on the selected dependency path.
Sampling,
/// Compaction work, including its local bookkeeping.
Compaction,
/// Automatic review work, such as reviewing a tool call before execution.
AutoReview,
/// Time awaiting a human answer or approval on the selected dependency path.
UserWait,
/// Tool execution work, including work after a dependency join resumes.
/// This is an aggregate category; tool-specific subtypes such as browser or
/// computer use are not represented by this calculator.
Tools,
/// Time within the observed turn interval not covered by a recorded work segment.
Overhead,
/// Work whose category is unavailable, including history collapsed at the depth limit.
Unknown,
}
/// A persistent observed dependency path. Review observers must be sealed before
/// publishing completed paths. Forks share their prefix; a join
/// retains only the dependency that actually released the waiting operation.
/// Equality compares path identity rather than the contents of each segment.
#[derive(Clone, Default)]
pub struct CriticalPath(Option<Arc<Node>>);
impl std::fmt::Debug for CriticalPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Summarize the tail without traversing shared dependency history.
f.debug_struct("CriticalPath")
.field("depth", &self.0.as_ref().map_or(0, |node| node.depth))
.field("end", &self.end())
.finish()
}
}
impl PartialEq for CriticalPath {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
}
}
}
impl Eq for CriticalPath {}
struct Node {
previous: CriticalPath,
kind: WorkKind,
reviews: Vec<ReviewExecution>,
start: Instant,
end: Instant,
origin: Instant,
depth: usize,
}
/// Exclusive time attributed to each category within the requested interval.
#[derive(Debug, PartialEq, Eq)]
pub struct PathDurations {
pub sampling: Duration,
pub compaction: Duration,
pub auto_review: Duration,
/// Subcomponent of auto_review excluding the union of observed child execution.
/// None means review attribution or dependency history is incomplete.
pub auto_review_overhead: Option<Duration>,
pub user_wait: Duration,
pub tools: Duration,
pub overhead: Duration,
pub unknown: Duration,
}
impl Default for PathDurations {
fn default() -> Self {
Self {
sampling: Duration::ZERO,
compaction: Duration::ZERO,
auto_review: Duration::ZERO,
auto_review_overhead: Some(Duration::ZERO),
user_wait: Duration::ZERO,
tools: Duration::ZERO,
overhead: Duration::ZERO,
unknown: Duration::ZERO,
}
}
}
impl PathDurations {
fn record(&mut self, kind: WorkKind, duration: Duration) {
if matches!(kind, WorkKind::Unknown) {
self.auto_review_overhead = None;
}
let total = match kind {
WorkKind::Sampling => &mut self.sampling,
WorkKind::Compaction => &mut self.compaction,
WorkKind::AutoReview => &mut self.auto_review,
WorkKind::UserWait => &mut self.user_wait,
WorkKind::Tools => &mut self.tools,
WorkKind::Overhead => &mut self.overhead,
WorkKind::Unknown => &mut self.unknown,
};
*total = total.saturating_add(duration);
}
}
impl CriticalPath {
/// End of the last recorded segment, or `None` for an empty path.
pub fn end(&self) -> Option<Instant> {
self.0.as_ref().map(|node| node.end)
}
/// Retain the later-finishing path, choosing `self` on a tie.
pub fn latest(self, other: Self) -> Self {
if other.end() > self.end() {
other
} else {
self
}
}
/// Append work after the existing path ends, clipping overlap and ignoring empty segments.
/// Exceeding the history limit collapses the retained interval into unknown work.
pub fn work(self, start: Instant, end: Instant, kind: WorkKind) -> Self {
self.append(start, end, kind, Vec::new())
}
/// Adds review time with the exact reviews active during this segment. Their
/// child execution union is clipped to the segment and requested window.
pub fn auto_review(self, start: Instant, end: Instant, reviews: Vec<ReviewExecution>) -> Self {
self.append(start, end, WorkKind::AutoReview, reviews)
}
fn append(
self,
start: Instant,
end: Instant,
kind: WorkKind,
reviews: Vec<ReviewExecution>,
) -> Self {
let start = self.end().map_or(start, |previous| previous.max(start));
if start >= end {
return self;
}
let origin = self.0.as_ref().map_or(start, |node| node.origin);
let previous_depth = self.0.as_ref().map_or(0, |node| node.depth);
let depth = previous_depth + 1;
if depth > MAX_PATH_DEPTH {
return Self::default().work(origin, end, WorkKind::Unknown);
}
Self(Some(Arc::new(Node {
previous: self,
kind,
reviews,
start,
end,
origin,
depth,
})))
}
/// Select the full branch that released this join, not just its exposed
/// waiting tail. Both branches carry their common causal prefix.
pub fn join(self, start: Instant, end: Instant, dependency: Self) -> Self {
let path = self.latest(dependency);
let resumed_at = path.end().unwrap_or(start).max(start);
path.work(resumed_at, end, WorkKind::Tools)
}
/// Attribute the requested interval exclusively, counting unrecorded gaps as overhead.
pub fn durations(&self, start: Instant, end: Instant) -> PathDurations {
let mut totals = PathDurations::default();
let mut path = self;
let mut end = end;
while let Some(node) = path.0.as_ref() {
if end <= start {
break;
}
let segment_end = end.min(node.end);
let segment_start = start.max(node.start);
if end > node.end {
totals.record(WorkKind::Overhead, end.duration_since(start.max(node.end)));
}
if segment_start < segment_end {
totals.record(node.kind, segment_end.duration_since(segment_start));
if matches!(node.kind, WorkKind::AutoReview) {
totals.auto_review_overhead = totals.auto_review_overhead.and_then(|total| {
review_execution::overhead(&node.reviews, segment_start, segment_end)
.map(|overhead| total.saturating_add(overhead))
});
}
}
end = end.min(node.start);
path = &node.previous;
}
if start < end {
totals.record(WorkKind::Overhead, end.duration_since(start));
}
totals
}
}
// Long sequential turns must not recursively destroy one Arc per operation.
// into_inner consumes each reference atomically: concurrent releases cannot
// leave an Err(Arc) whose subsequent drop recursively destroys the next node.
impl Drop for Node {
fn drop(&mut self) {
let mut previous = self.previous.0.take();
while let Some(node) = previous {
let Some(mut node) = Arc::into_inner(node) else {
break;
};
previous = node.previous.0.take();
}
}
}
#[cfg(test)]
#[path = "critical_path_tests.rs"]
mod tests;

View File

@@ -0,0 +1,168 @@
//! Collects exact child execution intervals for one automatic review, then seals them.
use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
/// Observes child turn execution for one review, including concurrent or retried turns.
/// The owner must seal observations before publishing the completed dependency path.
/// Equality compares review identity, not its collected intervals.
#[derive(Clone, Debug, Default)]
pub struct ReviewExecution(Arc<Mutex<State>>);
/// Resolves one submission exactly once, including cancellation before acknowledgement.
#[must_use = "keep the attempt alive until submission completes"]
pub struct ReviewExecutionAttempt {
execution: ReviewExecution,
finished: bool,
}
impl ReviewExecutionAttempt {
/// Records whether the submitted child's execution boundaries are known.
pub fn finish(mut self, known: bool) {
self.execution.attempt_finished(known);
self.finished = true;
}
}
impl Drop for ReviewExecutionAttempt {
fn drop(&mut self) {
if !self.finished {
self.execution.attempt_finished(/*known*/ false);
}
}
}
#[derive(Debug, Default)]
struct State {
observed: bool,
sealed: bool,
unknown: bool,
pending: BTreeSet<Instant>,
pending_attempts: usize,
intervals: Vec<(Instant, Instant)>,
}
impl ReviewExecution {
/// Declares that this review's child executions are instrumented, even if none run.
pub fn observe(&self) {
let mut state = self.state();
if !state.sealed {
state.observed = true;
}
}
/// Registers an unresolved submission before asynchronous work can be detached.
pub fn start_attempt(&self) -> ReviewExecutionAttempt {
let mut state = self.state();
if !state.sealed {
state.pending_attempts += 1;
}
ReviewExecutionAttempt {
execution: self.clone(),
finished: false,
}
}
/// Resolves one submission. Unknown execution remains unknown after it finishes.
fn attempt_finished(&self, known: bool) {
let mut state = self.state();
if state.sealed {
return;
}
if let Some(pending) = state.pending_attempts.checked_sub(1) {
state.pending_attempts = pending;
} else {
state.unknown = true;
}
state.unknown |= !known;
}
/// Records the actual child turn start, before it can be canceled.
pub fn started(&self, started_at: Instant) {
let mut state = self.state();
if !state.sealed && !state.pending.insert(started_at) {
// Equal clock readings cannot distinguish two concurrent attempts.
state.unknown = true;
}
}
/// Records exact turn bounds. Repeated completion notifications are harmless.
pub fn completed(&self, started_at: Instant, completed_at: Instant) {
let mut state = self.state();
if state.sealed {
return;
}
state.pending.remove(&started_at);
if completed_at < started_at {
state.unknown = true;
} else {
state.intervals.push((started_at, completed_at));
}
}
/// Marks unavailable child attribution, rather than reporting it as review overhead.
pub fn mark_unknown(&self) {
let mut state = self.state();
if !state.sealed {
state.unknown = true;
}
}
/// Freezes this review's evidence. Later callbacks cannot change a completed path.
pub fn seal(&self) {
self.state().sealed = true;
}
fn state(&self) -> std::sync::MutexGuard<'_, State> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
pub(crate) fn overhead(
reviews: &[ReviewExecution],
start: Instant,
end: Instant,
) -> Option<Duration> {
if reviews.is_empty() {
return None;
}
let mut intervals = Vec::new();
for review in reviews {
let state = review.state();
if !state.observed
|| state.unknown
|| !state.pending.is_empty()
|| state.pending_attempts > 0
{
return None;
}
intervals.extend(state.intervals.iter().filter_map(|&(left, right)| {
let left = left.max(start);
let right = right.min(end);
(left < right).then_some((left, right))
}));
}
intervals.sort_unstable();
let mut execution = Duration::ZERO;
let mut covered_until = start;
for (left, right) in intervals {
if right > covered_until {
execution += right.duration_since(left.max(covered_until));
covered_until = right;
}
}
Some(end.duration_since(start).saturating_sub(execution))
}
impl PartialEq for ReviewExecution {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for ReviewExecution {}