mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Add a crate for one-shot turn milestone watches (#64920)
## What changed Add `codex-turn-milestones` to the Cargo and Bazel builds. A single turn can take each registration, which can watch published assistant text and direct Apps tool starts independently. Callers match text candidates or resolved resource URIs and can claim each watch once. The API lets callers match outside the timing lock, claim the watch while capturing the timing snapshot, and deliver the owned observation after releasing the lock. Observations include the thread, turn, and source identities, elapsed time, and a caller-supplied critical-path snapshot. ## Testing Unit tests cover single-turn ownership and verify that two concurrent matching tool starts yield one successful claim while leaving the assistant-text watch available. GitOrigin-RevId: c42c032f320752a5963eb6b0ea2aa4a2c85a2342
This commit is contained in:
Generated
+8
@@ -5573,6 +5573,14 @@ dependencies = [
|
||||
"zbus",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-turn-milestones"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"codex-protocol",
|
||||
"pretty_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "codex-uds"
|
||||
version = "0.0.0"
|
||||
|
||||
@@ -119,6 +119,7 @@ members = [
|
||||
"otel-trace-websocket",
|
||||
"tcp-tunnel",
|
||||
"tui",
|
||||
"turn-milestones",
|
||||
"user-input",
|
||||
"user-verification",
|
||||
"tool-call-id",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "turn-milestones",
|
||||
crate_name = "codex_turn_milestones",
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "codex-turn-milestones"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[dependencies]
|
||||
codex-protocol = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions.workspace = true
|
||||
@@ -0,0 +1,173 @@
|
||||
//! One optional watch per milestone source on a turn. The caller evaluates a
|
||||
//! predicate before taking its timing lock, claims the watch while freezing
|
||||
//! the snapshot, and delivers the owned observation after releasing the lock.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
/// Assistant text at publication, with its stream or finalized item identity.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct AssistantTextCandidate<'a> {
|
||||
pub text: &'a str,
|
||||
pub response_id: Option<&'a str>,
|
||||
pub item_id: &'a str,
|
||||
}
|
||||
|
||||
/// Host predicates should be fast and side-effect free. Concurrent candidates
|
||||
/// may both pass a predicate before one claims the watch.
|
||||
#[derive(Default)]
|
||||
pub struct MilestoneWatches {
|
||||
pub assistant_text: Option<AssistantText>,
|
||||
pub direct_apps_tool_start: Option<DirectAppsToolStart>,
|
||||
}
|
||||
|
||||
pub struct AssistantText(Box<dyn Fn(AssistantTextCandidate<'_>) -> bool + Send + Sync>);
|
||||
|
||||
impl AssistantText {
|
||||
pub fn new(
|
||||
predicate: impl Fn(AssistantTextCandidate<'_>) -> bool + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self(Box::new(predicate))
|
||||
}
|
||||
}
|
||||
|
||||
/// Matches the resolved resource URI at direct Apps dispatch.
|
||||
pub struct DirectAppsToolStart(Box<dyn Fn(&str) -> bool + Send + Sync>);
|
||||
|
||||
impl DirectAppsToolStart {
|
||||
pub fn new(predicate: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self {
|
||||
Self(Box::new(predicate))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum MilestoneSourceId {
|
||||
AssistantText {
|
||||
response_id: Option<String>,
|
||||
item_id: String,
|
||||
},
|
||||
DirectToolStart {
|
||||
call_id: String,
|
||||
resource_uri: String,
|
||||
/// Local stream identity for correlation when the provider response ID arrives later.
|
||||
response_attempt_id: Option<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Timing through the source cutoff, owned independently of the running turn.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MilestoneObservation<T> {
|
||||
pub thread_id: ThreadId,
|
||||
pub turn_id: String,
|
||||
pub source: MilestoneSourceId,
|
||||
/// Monotonic and meaningful only in the current process.
|
||||
pub cutoff: Instant,
|
||||
pub elapsed: Duration,
|
||||
pub critical_path: T,
|
||||
}
|
||||
|
||||
/// Attach a fresh registration to each opted-in turn's input extension data.
|
||||
/// Only the first regular turn to bind the registration uses its watches.
|
||||
#[derive(Debug)]
|
||||
pub struct TurnMilestoneWatches<T>(Mutex<Option<Box<ActiveMilestoneWatches<T>>>>);
|
||||
|
||||
/// Watches and observer owned by the turn that took the registration.
|
||||
pub struct ActiveMilestoneWatches<T> {
|
||||
assistant_text: Option<Watch<AssistantText>>,
|
||||
direct_apps_tool_start: Option<Watch<DirectAppsToolStart>>,
|
||||
observer: Box<dyn Fn(MilestoneObservation<T>) + Send + Sync>,
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for ActiveMilestoneWatches<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ActiveMilestoneWatches")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> TurnMilestoneWatches<T> {
|
||||
/// The observer runs synchronously outside the timing locks. It should
|
||||
/// return promptly and queue any asynchronous work.
|
||||
pub fn new(
|
||||
watches: MilestoneWatches,
|
||||
observer: impl Fn(MilestoneObservation<T>) + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
Self(Mutex::new(Some(Box::new(ActiveMilestoneWatches {
|
||||
assistant_text: watches.assistant_text.map(Watch::new),
|
||||
direct_apps_tool_start: watches.direct_apps_tool_start.map(Watch::new),
|
||||
observer: Box::new(observer),
|
||||
}))))
|
||||
}
|
||||
|
||||
/// Transfers this registration to at most one turn.
|
||||
pub fn take(&self) -> Option<Box<ActiveMilestoneWatches<T>>> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.take()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ActiveMilestoneWatches<T> {
|
||||
pub fn assistant_text(&self) -> Option<&Watch<AssistantText>> {
|
||||
self.assistant_text
|
||||
.as_ref()
|
||||
.filter(|watch| watch.is_pending())
|
||||
}
|
||||
|
||||
pub fn direct_apps_tool_start(&self) -> Option<&Watch<DirectAppsToolStart>> {
|
||||
self.direct_apps_tool_start
|
||||
.as_ref()
|
||||
.filter(|watch| watch.is_pending())
|
||||
}
|
||||
|
||||
pub fn deliver(&self, observation: MilestoneObservation<T>) {
|
||||
(self.observer)(observation);
|
||||
}
|
||||
}
|
||||
|
||||
/// A configured predicate and its independent one-shot latch.
|
||||
pub struct Watch<P> {
|
||||
predicate: P,
|
||||
pending: AtomicBool,
|
||||
}
|
||||
|
||||
impl<P> Watch<P> {
|
||||
fn new(predicate: P) -> Self {
|
||||
Self {
|
||||
predicate,
|
||||
pending: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_pending(&self) -> bool {
|
||||
self.pending.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Claim a matching candidate under the caller's timing lock, after
|
||||
/// validating its cutoff. The latch only arbitrates ownership.
|
||||
pub fn try_claim(&self) -> bool {
|
||||
self.pending.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Watch<AssistantText> {
|
||||
pub fn matches(&self, candidate: AssistantTextCandidate<'_>) -> bool {
|
||||
(self.predicate.0)(candidate)
|
||||
}
|
||||
}
|
||||
|
||||
impl Watch<DirectAppsToolStart> {
|
||||
pub fn matches(&self, resource_uri: &str) -> bool {
|
||||
(self.predicate.0)(resource_uri)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "milestones_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,64 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use std::sync::Barrier;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
const TEXT: AssistantTextCandidate<'static> = AssistantTextCandidate {
|
||||
text: "answer",
|
||||
response_id: Some("response-a"),
|
||||
item_id: "message",
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn unspent_watches_can_only_be_taken_by_one_turn() {
|
||||
let registration = TurnMilestoneWatches::<()>::new(
|
||||
MilestoneWatches {
|
||||
assistant_text: Some(AssistantText::new(|_| true)),
|
||||
direct_apps_tool_start: None,
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
let watches = registration.take().unwrap();
|
||||
assert!(watches.assistant_text().is_some());
|
||||
assert!(watches.direct_apps_tool_start().is_none());
|
||||
assert!(registration.take().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_matching_uris_claim_one_tool_watch_and_leave_text_pending() {
|
||||
let watches = TurnMilestoneWatches::<()>::new(
|
||||
MilestoneWatches {
|
||||
assistant_text: Some(AssistantText::new(|candidate| candidate.text == TEXT.text)),
|
||||
direct_apps_tool_start: Some(DirectAppsToolStart::new(|uri| {
|
||||
matches!(uri, "app://link-a/send" | "app://link-b/send")
|
||||
})),
|
||||
},
|
||||
|_| {},
|
||||
)
|
||||
.take()
|
||||
.unwrap();
|
||||
|
||||
let tool = watches.direct_apps_tool_start().unwrap();
|
||||
assert!(!tool.matches("app://link-a/read"));
|
||||
let barrier = Barrier::new(2);
|
||||
let attempt = |uri| {
|
||||
let matches = tool.matches(uri);
|
||||
barrier.wait();
|
||||
(matches, matches && tool.try_claim())
|
||||
};
|
||||
let ((first_match, first_claim), (second_match, second_claim)) = std::thread::scope(|scope| {
|
||||
let other = scope.spawn(|| attempt("app://link-b/send"));
|
||||
(attempt("app://link-a/send"), other.join().unwrap())
|
||||
});
|
||||
assert_eq!((first_match, second_match), (true, true));
|
||||
assert_ne!(first_claim, second_claim);
|
||||
assert!(watches.direct_apps_tool_start().is_none());
|
||||
|
||||
let text = watches.assistant_text().unwrap();
|
||||
assert!(text.matches(TEXT));
|
||||
assert!(text.try_claim());
|
||||
assert!(watches.assistant_text().is_none());
|
||||
}
|
||||
Reference in New Issue
Block a user