[codex-analytics] add goal turn participation events

This commit is contained in:
Mark Steinbrick
2026-06-02 22:49:07 -07:00
parent d36a3ead3c
commit a44cec2934
15 changed files with 747 additions and 50 deletions
@@ -8,6 +8,7 @@ use crate::events::CodexAppUsedEventRequest;
use crate::events::CodexCommandExecutionEventParams;
use crate::events::CodexCommandExecutionEventRequest;
use crate::events::CodexCompactionEventRequest;
use crate::events::CodexGoalEventRequest;
use crate::events::CodexHookRunEventRequest;
use crate::events::CodexPluginEventRequest;
use crate::events::CodexPluginUsedEventRequest;
@@ -43,6 +44,7 @@ use crate::facts::AppInvocation;
use crate::facts::AppMentionedInput;
use crate::facts::AppUsedInput;
use crate::facts::CodexCompactionEvent;
use crate::facts::CodexGoalEvent;
use crate::facts::CompactionImplementation;
use crate::facts::CompactionPhase;
use crate::facts::CompactionReason;
@@ -50,6 +52,8 @@ use crate::facts::CompactionStatus;
use crate::facts::CompactionStrategy;
use crate::facts::CompactionTrigger;
use crate::facts::CustomAnalyticsFact;
use crate::facts::GoalEventKind;
use crate::facts::GoalStatus;
use crate::facts::HookRunFact;
use crate::facts::HookRunInput;
use crate::facts::InputError;
@@ -3229,6 +3233,80 @@ async fn reducer_ingests_plugin_state_changed_fact() {
);
}
#[test]
fn goal_turn_participated_event_serializes_expected_shape() {
let event = TrackEventRequest::Goal(Box::new(CodexGoalEventRequest {
event_type: "codex_goal_event",
event_params: crate::events::codex_goal_event_params(
CodexGoalEvent {
thread_id: "thread-1".to_string(),
turn_id: Some("turn-1".to_string()),
goal_id: "goal-1".to_string(),
event_kind: GoalEventKind::TurnParticipated,
goal_status: GoalStatus::Complete,
has_token_budget: true,
},
"session-thread-1".to_string(),
sample_app_server_client_metadata(),
sample_runtime_metadata(),
Some(ThreadSource::User),
/*subagent_source*/ None,
/*parent_thread_id*/ None,
),
}));
let payload = serde_json::to_value(&event).expect("serialize goal event");
let params = &payload["event_params"];
assert_eq!(payload["event_type"], "codex_goal_event");
assert_eq!(params["thread_id"], "thread-1");
assert_eq!(params["session_id"], "session-thread-1");
assert_eq!(params["turn_id"], "turn-1");
assert_eq!(params["goal_id"], "goal-1");
assert_eq!(params["event_kind"], "turn_participated");
assert_eq!(params["goal_status"], "complete");
assert_eq!(params["has_token_budget"], true);
assert!(params.get("tokens_used").is_none());
assert!(params.get("time_used_seconds").is_none());
assert!(params.get("turn_tokens_used").is_none());
assert!(params.get("turn_active_time_ms").is_none());
assert!(params.get("token_usage_complete").is_none());
assert!(params.get("token_budget").is_none());
assert!(params.get("objective").is_none());
}
#[test]
fn goal_lifecycle_event_serializes_expected_shape() {
let event = TrackEventRequest::Goal(Box::new(CodexGoalEventRequest {
event_type: "codex_goal_event",
event_params: crate::events::codex_goal_event_params(
CodexGoalEvent {
thread_id: "thread-1".to_string(),
turn_id: None,
goal_id: "goal-1".to_string(),
event_kind: GoalEventKind::Cleared,
goal_status: GoalStatus::Active,
has_token_budget: false,
},
"session-thread-1".to_string(),
sample_app_server_client_metadata(),
sample_runtime_metadata(),
Some(ThreadSource::User),
/*subagent_source*/ None,
/*parent_thread_id*/ None,
),
}));
let payload = serde_json::to_value(&event).expect("serialize goal event");
let params = &payload["event_params"];
assert_eq!(params["event_kind"], "cleared");
assert_eq!(params["turn_id"], serde_json::Value::Null);
assert!(params.get("turn_tokens_used").is_none());
assert!(params.get("turn_active_time_ms").is_none());
assert!(params.get("token_usage_complete").is_none());
}
#[test]
fn turn_event_serializes_expected_shape() {
let event = TrackEventRequest::TurnEvent(Box::new(CodexTurnEventRequest {
+7
View File
@@ -9,6 +9,7 @@ use crate::facts::AnalyticsJsonRpcError;
use crate::facts::AppInvocation;
use crate::facts::AppMentionedInput;
use crate::facts::AppUsedInput;
use crate::facts::CodexGoalEvent;
use crate::facts::CustomAnalyticsFact;
use crate::facts::HookRunFact;
use crate::facts::HookRunInput;
@@ -245,6 +246,12 @@ impl AnalyticsEventsClient {
)));
}
pub fn track_goal_event(&self, event: CodexGoalEvent) {
self.record_fact(AnalyticsFact::Custom(CustomAnalyticsFact::Goal(Box::new(
event,
))));
}
pub fn track_turn_resolved_config(&self, fact: TurnResolvedConfigFact) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::TurnResolvedConfig(Box::new(fact)),
+51
View File
@@ -4,12 +4,15 @@ use crate::facts::AcceptedLineFingerprint;
use crate::facts::AppInvocation;
use crate::facts::CodexCompactionEvent;
use crate::facts::CodexErrKind;
use crate::facts::CodexGoalEvent;
use crate::facts::CompactionImplementation;
use crate::facts::CompactionPhase;
use crate::facts::CompactionReason;
use crate::facts::CompactionStatus;
use crate::facts::CompactionStrategy;
use crate::facts::CompactionTrigger;
use crate::facts::GoalEventKind;
use crate::facts::GoalStatus;
use crate::facts::HookRunFact;
use crate::facts::InvocationType;
use crate::facts::PluginState;
@@ -63,6 +66,7 @@ pub(crate) enum TrackEventRequest {
AppUsed(CodexAppUsedEventRequest),
HookRun(CodexHookRunEventRequest),
Compaction(Box<CodexCompactionEventRequest>),
Goal(Box<CodexGoalEventRequest>),
TurnEvent(Box<CodexTurnEventRequest>),
TurnSteer(CodexTurnSteerEventRequest),
CommandExecution(CodexCommandExecutionEventRequest),
@@ -768,6 +772,28 @@ pub(crate) struct CodexCompactionEventRequest {
pub(crate) event_params: CodexCompactionEventParams,
}
#[derive(Serialize)]
pub(crate) struct CodexGoalEventParams {
pub(crate) thread_id: String,
pub(crate) session_id: String,
pub(crate) turn_id: Option<String>,
pub(crate) app_server_client: CodexAppServerClientMetadata,
pub(crate) runtime: CodexRuntimeMetadata,
pub(crate) thread_source: Option<ThreadSource>,
pub(crate) subagent_source: Option<String>,
pub(crate) parent_thread_id: Option<String>,
pub(crate) goal_id: String,
pub(crate) event_kind: GoalEventKind,
pub(crate) goal_status: GoalStatus,
pub(crate) has_token_budget: bool,
}
#[derive(Serialize)]
pub(crate) struct CodexGoalEventRequest {
pub(crate) event_type: &'static str,
pub(crate) event_params: CodexGoalEventParams,
}
#[derive(Serialize)]
pub(crate) struct CodexTurnEventParams {
pub(crate) thread_id: String,
@@ -967,6 +993,31 @@ pub(crate) fn codex_compaction_event_params(
}
}
pub(crate) fn codex_goal_event_params(
input: CodexGoalEvent,
session_id: String,
app_server_client: CodexAppServerClientMetadata,
runtime: CodexRuntimeMetadata,
thread_source: Option<ThreadSource>,
subagent_source: Option<String>,
parent_thread_id: Option<String>,
) -> CodexGoalEventParams {
CodexGoalEventParams {
thread_id: input.thread_id,
session_id,
turn_id: input.turn_id,
app_server_client,
runtime,
thread_source,
subagent_source,
parent_thread_id,
goal_id: input.goal_id,
event_kind: input.event_kind,
goal_status: input.goal_status,
has_token_budget: input.has_token_budget,
}
}
pub(crate) fn codex_plugin_used_metadata(
tracking: &TrackEventsContext,
plugin: PluginTelemetryMetadata,
+31
View File
@@ -421,6 +421,36 @@ pub struct CodexCompactionEvent {
pub duration_ms: Option<u64>,
}
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GoalEventKind {
Created,
TurnParticipated,
StatusChanged,
Cleared,
}
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GoalStatus {
Active,
Paused,
Blocked,
UsageLimited,
BudgetLimited,
Complete,
}
#[derive(Clone)]
pub struct CodexGoalEvent {
pub thread_id: String,
pub turn_id: Option<String>,
pub goal_id: String,
pub event_kind: GoalEventKind,
pub goal_status: GoalStatus,
pub has_token_budget: bool,
}
#[allow(dead_code)]
pub(crate) enum AnalyticsFact {
Initialize {
@@ -472,6 +502,7 @@ pub(crate) enum AnalyticsFact {
pub(crate) enum CustomAnalyticsFact {
SubAgentThreadStarted(SubAgentThreadStartedInput),
Compaction(Box<CodexCompactionEvent>),
Goal(Box<CodexGoalEvent>),
GuardianReview(Box<GuardianReviewEventParams>),
TurnResolvedConfig(Box<TurnResolvedConfigFact>),
TurnTokenUsage(Box<TurnTokenUsageFact>),
+3
View File
@@ -24,6 +24,7 @@ pub use facts::AcceptedLineFingerprint;
pub use facts::AnalyticsJsonRpcError;
pub use facts::AppInvocation;
pub use facts::CodexCompactionEvent;
pub use facts::CodexGoalEvent;
pub use facts::CodexTurnSteerEvent;
pub use facts::CompactionImplementation;
pub use facts::CompactionPhase;
@@ -31,6 +32,8 @@ pub use facts::CompactionReason;
pub use facts::CompactionStatus;
pub use facts::CompactionStrategy;
pub use facts::CompactionTrigger;
pub use facts::GoalEventKind;
pub use facts::GoalStatus;
pub use facts::HookRunFact;
pub use facts::InputError;
pub use facts::InvocationType;
+36
View File
@@ -15,6 +15,7 @@ use crate::events::CodexDynamicToolCallEventParams;
use crate::events::CodexDynamicToolCallEventRequest;
use crate::events::CodexFileChangeEventParams;
use crate::events::CodexFileChangeEventRequest;
use crate::events::CodexGoalEventRequest;
use crate::events::CodexHookRunEventRequest;
use crate::events::CodexImageGenerationEventParams;
use crate::events::CodexImageGenerationEventRequest;
@@ -51,6 +52,7 @@ use crate::events::TrackEventRequest;
use crate::events::WebSearchActionKind;
use crate::events::codex_app_metadata;
use crate::events::codex_compaction_event_params;
use crate::events::codex_goal_event_params;
use crate::events::codex_hook_run_metadata;
use crate::events::codex_plugin_metadata;
use crate::events::codex_plugin_used_metadata;
@@ -62,6 +64,7 @@ use crate::facts::AnalyticsJsonRpcError;
use crate::facts::AppMentionedInput;
use crate::facts::AppUsedInput;
use crate::facts::CodexCompactionEvent;
use crate::facts::CodexGoalEvent;
use crate::facts::CustomAnalyticsFact;
use crate::facts::HookRunInput;
use crate::facts::PluginState;
@@ -190,6 +193,16 @@ impl<'a> AnalyticsDropSite<'a> {
}
}
fn goal(input: &'a CodexGoalEvent) -> Self {
Self {
event_name: "goal",
thread_id: &input.thread_id,
turn_id: input.turn_id.as_deref(),
review_id: None,
item_id: None,
}
}
fn tool_item(
notification: &'a codex_app_server_protocol::ItemCompletedNotification,
item_id: &'a str,
@@ -455,6 +468,9 @@ impl AnalyticsReducer {
CustomAnalyticsFact::Compaction(input) => {
self.ingest_compaction(*input, out);
}
CustomAnalyticsFact::Goal(input) => {
self.ingest_goal(*input, out);
}
CustomAnalyticsFact::GuardianReview(input) => {
self.ingest_guardian_review(*input, out);
}
@@ -1327,6 +1343,26 @@ impl AnalyticsReducer {
)));
}
fn ingest_goal(&mut self, input: CodexGoalEvent, out: &mut Vec<TrackEventRequest>) {
let Some((connection_state, thread_metadata)) =
self.thread_context_or_warn(AnalyticsDropSite::goal(&input))
else {
return;
};
out.push(TrackEventRequest::Goal(Box::new(CodexGoalEventRequest {
event_type: "codex_goal_event",
event_params: codex_goal_event_params(
input,
thread_metadata.session_id.clone(),
connection_state.app_server_client.clone(),
connection_state.runtime.clone(),
thread_metadata.thread_source,
thread_metadata.subagent_source.clone(),
thread_metadata.parent_thread_id.clone(),
),
})));
}
fn ingest_guardian_review_completed(
&mut self,
notification: codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification,
@@ -316,14 +316,15 @@ impl ThreadGoalRequestProcessor {
let thread_state = thread_state.lock().await;
thread_state.listener_command_tx()
};
let cleared = state_db
let cleared_goal = state_db
.thread_goals()
.delete_thread_goal(thread_id)
.await
.map_err(|err| internal_error(format!("failed to clear thread goal: {err}")))?;
let cleared = cleared_goal.is_some();
if cleared && let Some(thread) = running_thread.as_ref() {
thread.apply_external_goal_clear().await;
if let (Some(thread), Some(goal)) = (running_thread.as_ref(), cleared_goal) {
thread.apply_external_goal_clear(goal).await;
}
self.outgoing
@@ -155,6 +155,43 @@ pub(crate) async fn wait_for_analytics_event(
.await?
}
pub(crate) async fn wait_for_goal_event(
server: &MockServer,
read_timeout: Duration,
event_kind: &str,
goal_status: &str,
) -> Result<Value> {
timeout(read_timeout, async {
loop {
let Some(requests) = server.received_requests().await else {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
};
for request in &requests {
if request.method != "POST"
|| request.url.path() != "/codex/analytics-events/events"
{
continue;
}
let payload: Value = serde_json::from_slice(&request.body)
.map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"))?;
let Some(events) = payload["events"].as_array() else {
continue;
};
if let Some(event) = events.iter().find(|event| {
event["event_type"] == "codex_goal_event"
&& event["event_params"]["event_kind"] == event_kind
&& event["event_params"]["goal_status"] == goal_status
}) {
return Ok::<Value, anyhow::Error>(event.clone());
}
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?
}
pub(crate) fn thread_initialized_event(payload: &Value) -> Result<&Value> {
let events = payload["events"]
.as_array()
@@ -103,6 +103,7 @@ use super::analytics::assert_basic_thread_initialized_event;
use super::analytics::mount_analytics_capture;
use super::analytics::thread_initialized_event;
use super::analytics::wait_for_analytics_payload;
use super::analytics::wait_for_goal_event;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
@@ -1364,6 +1365,138 @@ async fn thread_goal_clear_deletes_goal_and_notifies() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn goal_turn_participated_event_tracks_goal_turn_and_lifecycle() -> Result<()> {
let server = create_mock_responses_server_sequence_unchecked(vec![responses::sse(vec![
responses::ev_response_created("goal-continuation"),
responses::ev_completed_with_tokens("goal-continuation", /*total_tokens*/ 200),
])])
.await;
let codex_home = TempDir::new()?;
create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?;
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
&config_path,
config.replace("personality = true\n", "personality = true\ngoals = true\n"),
)?;
mount_analytics_capture(&server, codex_home.path()).await?;
let thread_id = create_fake_rollout(
codex_home.path(),
"2025-01-05T12-00-00",
"2025-01-05T12:00:00Z",
"",
Some("mock_provider"),
/*git_info*/ None,
)?;
let mut mcp = TestAppServer::new_without_managed_config(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread_id.clone(),
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
)
.await??;
let _resume: ThreadResumeResponse = to_response(resume_resp)?;
let set_id = mcp
.send_raw_request(
"thread/goal/set",
Some(json!({
"threadId": thread_id,
"objective": "do not serialize this objective",
"status": "active",
"tokenBudget": 100,
})),
)
.await?;
let set_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(set_id)),
)
.await??;
let _set: ThreadGoalSetResponse = to_response(set_resp)?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("thread/goal/updated"),
)
.await??;
let created = wait_for_goal_event(&server, DEFAULT_READ_TIMEOUT, "created", "active").await?;
let goal_id = created["event_params"]["goal_id"]
.as_str()
.expect("created goal id");
assert_eq!(created["event_params"]["thread_id"], thread_id);
assert_eq!(created["event_params"]["turn_id"], serde_json::Value::Null);
let turn_participated = wait_for_goal_event(
&server,
DEFAULT_READ_TIMEOUT,
"turn_participated",
"budget_limited",
)
.await?;
assert_eq!(turn_participated["event_params"]["goal_id"], goal_id);
assert!(
turn_participated["event_params"]["turn_id"]
.as_str()
.is_some(),
"turn participation must retain causal turn attribution"
);
assert_eq!(turn_participated["event_params"]["has_token_budget"], true);
let budget_limited = wait_for_goal_event(
&server,
DEFAULT_READ_TIMEOUT,
"status_changed",
"budget_limited",
)
.await?;
assert_eq!(budget_limited["event_params"]["goal_id"], goal_id);
assert_eq!(
budget_limited["event_params"]["turn_id"],
turn_participated["event_params"]["turn_id"]
);
let clear_id = mcp
.send_raw_request(
"thread/goal/clear",
Some(json!({
"threadId": thread_id,
})),
)
.await?;
let clear_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(clear_id)),
)
.await??;
let clear: ThreadGoalClearResponse = to_response(clear_resp)?;
assert!(clear.cleared);
let cleared =
wait_for_goal_event(&server, DEFAULT_READ_TIMEOUT, "cleared", "budget_limited").await?;
assert_eq!(cleared["event_params"]["goal_id"], goal_id);
assert_eq!(cleared["event_params"]["turn_id"], serde_json::Value::Null);
for event in [&created, &turn_participated, &budget_limited, &cleared] {
assert!(event["event_params"].get("objective").is_none());
assert!(event["event_params"].get("token_budget").is_none());
assert!(event["event_params"].get("tokens_used").is_none());
assert!(event["event_params"].get("time_used_seconds").is_none());
assert!(event["event_params"].get("turn_tokens_used").is_none());
assert!(event["event_params"].get("turn_active_time_ms").is_none());
assert!(event["event_params"].get("token_usage_complete").is_none());
}
Ok(())
}
#[tokio::test]
async fn thread_resume_emits_restored_token_usage_before_next_turn() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
+2 -2
View File
@@ -203,11 +203,11 @@ impl CodexThread {
}
}
pub async fn apply_external_goal_clear(&self) {
pub async fn apply_external_goal_clear(&self, goal: codex_state::ThreadGoal) {
if let Err(err) = self
.codex
.session
.goal_runtime_apply(GoalRuntimeEvent::ExternalClear)
.goal_runtime_apply(GoalRuntimeEvent::ExternalClear { goal })
.await
{
tracing::warn!("failed to apply external goal clear runtime effects: {err}");
+196 -37
View File
@@ -4,6 +4,10 @@
//! goal mutations, converts between state and protocol shapes, emits goal-update
//! events, and owns helper hooks used by goal lifecycle behavior.
mod turn_participation;
use self::turn_participation::GoalTurnParticipant;
use self::turn_participation::GoalTurnParticipationTracker;
use crate::StateDbHandle;
use crate::context::ContextualUserFragment;
use crate::context::InternalContextSource;
@@ -16,6 +20,9 @@ use crate::state::TurnState;
use crate::tasks::RegularTask;
use crate::tools::handlers::goal_spec::UPDATE_GOAL_TOOL_NAME;
use anyhow::Context;
use codex_analytics::CodexGoalEvent;
use codex_analytics::GoalEventKind;
use codex_analytics::GoalStatus;
use codex_features::Feature;
use codex_otel::GOAL_BLOCKED_METRIC;
use codex_otel::GOAL_BUDGET_LIMITED_METRIC;
@@ -140,7 +147,9 @@ pub(crate) enum GoalRuntimeEvent<'a> {
ExternalSet {
external_set: ExternalGoalSet,
},
ExternalClear,
ExternalClear {
goal: codex_state::ThreadGoal,
},
ThreadResumed,
}
@@ -180,6 +189,7 @@ struct GoalTurnAccountingSnapshot {
turn_id: String,
last_accounted_token_usage: TokenUsage,
active_goal_id: Option<String>,
participation: GoalTurnParticipationTracker,
}
impl GoalRuntimeState {
@@ -206,10 +216,16 @@ impl GoalTurnAccountingSnapshot {
turn_id: turn_id.into(),
last_accounted_token_usage: token_usage,
active_goal_id: None,
participation: GoalTurnParticipationTracker::new(),
}
}
fn mark_active_goal(&mut self, goal_id: impl Into<String>) {
fn mark_active_goal(&mut self, goal: &codex_state::ThreadGoal) {
self.mark_goal_for_accounting(goal.goal_id.clone());
self.participation.mark_active_goal(goal);
}
fn mark_goal_for_accounting(&mut self, goal_id: impl Into<String>) {
self.active_goal_id = Some(goal_id.into());
}
@@ -225,6 +241,14 @@ impl GoalTurnAccountingSnapshot {
self.active_goal_id = None;
}
fn update_goal(&mut self, goal: &codex_state::ThreadGoal) {
self.participation.update_goal(goal);
}
fn into_participants(self) -> Vec<GoalTurnParticipant> {
self.participation.into_participants()
}
fn reset_baseline(&mut self, token_usage: TokenUsage) {
self.last_accounted_token_usage = token_usage;
}
@@ -384,7 +408,8 @@ impl Session {
self.apply_external_thread_goal_status(external_set).await;
Ok(())
}),
GoalRuntimeEvent::ExternalClear => Box::pin(async move {
GoalRuntimeEvent::ExternalClear { goal } => Box::pin(async move {
self.track_goal_lifecycle_event(&goal, None, GoalEventKind::Cleared);
self.clear_stopped_thread_goal_runtime_state().await;
Ok(())
}),
@@ -515,7 +540,6 @@ impl Session {
.await;
}
let goal_status = goal.status;
let goal_id = goal.goal_id.clone();
let previous_status_for_goal = if replacing_goal {
None
} else {
@@ -523,10 +547,19 @@ impl Session {
};
if replacing_goal {
self.emit_goal_created_metric();
self.track_goal_lifecycle_event(
&goal,
Some(turn_context.sub_id.clone()),
GoalEventKind::Created,
);
}
self.emit_goal_resumed_metric_if_status_changed(previous_status_for_goal, goal_status);
self.emit_goal_terminal_metrics_if_status_changed(previous_status_for_goal, &goal);
let goal = protocol_goal_from_state(goal);
self.track_goal_status_change(
&goal,
previous_status_for_goal,
Some(turn_context.sub_id.clone()),
);
*self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
let newly_active_goal = goal_status == codex_state::ThreadGoalStatus::Active
&& (replacing_goal
@@ -535,14 +568,19 @@ impl Session {
if newly_active_goal {
let current_token_usage = self.total_token_usage().await.unwrap_or_default();
self.mark_active_goal_accounting(
goal_id,
Some(turn_context.sub_id.clone()),
&goal,
(!should_ignore_goal_for_mode(turn_context.collaboration_mode.mode))
.then(|| turn_context.sub_id.clone()),
current_token_usage,
)
.await;
} else if goal_status != codex_state::ThreadGoalStatus::Active {
self.update_goal_turn_participant(turn_context, &goal).await;
self.clear_active_goal_accounting(turn_context).await;
} else {
self.update_goal_turn_participant(turn_context, &goal).await;
}
let goal = protocol_goal_from_state(goal);
self.send_event(
turn_context,
EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
@@ -601,19 +639,24 @@ impl Session {
goal.objective.as_str(),
)
.await;
let goal_id = goal.goal_id.clone();
self.emit_goal_created_metric();
let goal = protocol_goal_from_state(goal);
self.track_goal_lifecycle_event(
&goal,
Some(turn_context.sub_id.clone()),
GoalEventKind::Created,
);
*self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
let current_token_usage = self.total_token_usage().await.unwrap_or_default();
self.mark_active_goal_accounting(
goal_id,
Some(turn_context.sub_id.clone()),
&goal,
(!should_ignore_goal_for_mode(turn_context.collaboration_mode.mode))
.then(|| turn_context.sub_id.clone()),
current_token_usage,
)
.await;
let goal = protocol_goal_from_state(goal);
self.send_event(
turn_context,
EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
@@ -640,6 +683,7 @@ impl Session {
.is_some_and(|previous_goal| previous_goal.goal_id != goal.goal_id);
if previous_goal.is_none() || replaced_existing_goal {
self.emit_goal_created_metric();
self.track_goal_lifecycle_event(&goal, None, GoalEventKind::Created);
}
let objective_changed = previous_goal
.as_ref()
@@ -649,17 +693,17 @@ impl Session {
.and_then(|previous_goal| (!replaced_existing_goal).then_some(previous_goal.status));
self.emit_goal_resumed_metric_if_status_changed(previous_status, goal.status);
self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
self.track_goal_status_change(&goal, previous_status, None);
let goal_for_steering = objective_changed.then(|| protocol_goal_from_state(goal.clone()));
let goal_id = goal.goal_id;
let status = goal.status;
match status {
codex_state::ThreadGoalStatus::Active => {
let turn_id = self
.active_turn_context()
.await
.map(|turn_context| turn_context.sub_id.clone());
let turn_id = self.active_turn_context().await.and_then(|turn_context| {
(!should_ignore_goal_for_mode(turn_context.collaboration_mode.mode))
.then(|| turn_context.sub_id.clone())
});
let current_token_usage = self.total_token_usage().await.unwrap_or_default();
self.mark_active_goal_accounting(goal_id, turn_id, current_token_usage)
self.mark_active_goal_accounting(&goal, turn_id, current_token_usage)
.await;
if let Some(goal) = goal_for_steering {
let item = goal_context_input_item(objective_updated_prompt(&goal));
@@ -672,6 +716,7 @@ impl Session {
self.maybe_continue_goal_if_idle_runtime().await;
}
codex_state::ThreadGoalStatus::BudgetLimited => {
self.update_active_goal_turn_participant(&goal).await;
if self.active_turn_context().await.is_none() {
self.clear_stopped_thread_goal_runtime_state().await;
}
@@ -680,6 +725,7 @@ impl Session {
| codex_state::ThreadGoalStatus::Blocked
| codex_state::ThreadGoalStatus::UsageLimited
| codex_state::ThreadGoalStatus::Complete => {
self.update_active_goal_turn_participant(&goal).await;
self.clear_stopped_thread_goal_runtime_state().await;
}
}
@@ -704,9 +750,29 @@ impl Session {
accounting.wall_clock.clear_active_goal();
}
async fn update_goal_turn_participant(
&self,
turn_context: &TurnContext,
goal: &codex_state::ThreadGoal,
) {
let mut accounting = self.goal_runtime.accounting.lock().await;
if let Some(turn) = accounting.turn.as_mut()
&& turn.turn_id == turn_context.sub_id
{
turn.update_goal(goal);
}
}
async fn update_active_goal_turn_participant(&self, goal: &codex_state::ThreadGoal) {
let mut accounting = self.goal_runtime.accounting.lock().await;
if let Some(turn) = accounting.turn.as_mut() {
turn.update_goal(goal);
}
}
async fn mark_active_goal_accounting(
&self,
goal_id: String,
goal: &codex_state::ThreadGoal,
turn_id: Option<String>,
token_usage: TokenUsage,
) {
@@ -715,16 +781,16 @@ impl Session {
match accounting.turn.as_mut() {
Some(turn) if turn.turn_id == turn_id => {
turn.reset_baseline(token_usage);
turn.mark_active_goal(goal_id.clone());
turn.mark_active_goal(goal);
}
_ => {
let mut turn = GoalTurnAccountingSnapshot::new(turn_id, token_usage);
turn.mark_active_goal(goal_id.clone());
turn.mark_active_goal(goal);
accounting.turn = Some(turn);
}
}
}
accounting.wall_clock.mark_active_goal(goal_id);
accounting.wall_clock.mark_active_goal(goal.goal_id.clone());
}
fn emit_goal_created_metric(&self) {
@@ -857,7 +923,11 @@ impl Session {
if let Some(turn) = accounting.turn.as_mut()
&& turn.turn_id == turn_context.sub_id
{
turn.mark_active_goal(goal.goal_id.clone());
if goal.status == codex_state::ThreadGoalStatus::Active {
turn.mark_active_goal(&goal);
} else {
turn.mark_goal_for_accounting(goal.goal_id.clone());
}
}
accounting.wall_clock.mark_active_goal(goal.goal_id);
}
@@ -903,13 +973,20 @@ impl Session {
}
if turn_completed {
let mut accounting = self.goal_runtime.accounting.lock().await;
if accounting
.turn
.as_ref()
.is_some_and(|turn| turn.turn_id == turn_context.sub_id)
{
accounting.turn = None;
let turn = {
let mut accounting = self.goal_runtime.accounting.lock().await;
if accounting
.turn
.as_ref()
.is_some_and(|turn| turn.turn_id == turn_context.sub_id)
{
accounting.turn.take()
} else {
None
}
};
if let Some(turn) = turn {
self.track_goal_turn_participation(turn);
}
}
}
@@ -926,13 +1003,20 @@ impl Session {
{
tracing::warn!("failed to account thread goal progress after abort: {err}");
}
let mut accounting = self.goal_runtime.accounting.lock().await;
if accounting
.turn
.as_ref()
.is_some_and(|turn| turn.turn_id == turn_context.sub_id)
{
accounting.turn = None;
let turn = {
let mut accounting = self.goal_runtime.accounting.lock().await;
if accounting
.turn
.as_ref()
.is_some_and(|turn| turn.turn_id == turn_context.sub_id)
{
accounting.turn.take()
} else {
None
}
};
if let Some(turn) = turn {
self.track_goal_turn_participation(turn);
}
}
}
@@ -1014,6 +1098,7 @@ impl Session {
.filter(|turn| turn.turn_id == turn_context.sub_id)
{
turn.mark_accounted(current_token_usage);
turn.update_goal(&goal);
if clear_active_goal {
turn.clear_active_goal();
}
@@ -1026,6 +1111,11 @@ impl Session {
if matches!(terminal_metric_emission, TerminalMetricEmission::Emit) {
self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
}
self.track_goal_status_change(
&goal,
previous_status,
Some(turn_context.sub_id.clone()),
);
goal
}
codex_state::GoalAccountingOutcome::Unchanged(_) => return Ok(()),
@@ -1180,9 +1270,11 @@ impl Session {
return Ok(());
};
self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
let goal = protocol_goal_from_state(goal);
self.track_goal_status_change(&goal, previous_status, Some(turn_context.sub_id.clone()));
self.update_goal_turn_participant(turn_context, &goal).await;
*self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
self.clear_active_goal_accounting(turn_context).await;
let goal = protocol_goal_from_state(goal);
self.send_event(
turn_context,
EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
@@ -1397,6 +1489,62 @@ impl Session {
items: vec![goal_context_input_item(continuation_prompt(&goal))],
})
}
fn track_goal_turn_participation(&self, turn: GoalTurnAccountingSnapshot) {
let turn_id = turn.turn_id.clone();
for participant in turn.into_participants() {
self.services
.analytics_events_client
.track_goal_event(CodexGoalEvent {
thread_id: self.conversation_id.to_string(),
turn_id: Some(turn_id.clone()),
goal_id: participant.goal_id,
event_kind: GoalEventKind::TurnParticipated,
goal_status: analytics_goal_status(participant.goal_status),
has_token_budget: participant.has_token_budget,
});
}
}
fn track_goal_lifecycle_event(
&self,
goal: &codex_state::ThreadGoal,
turn_id: Option<String>,
event_kind: GoalEventKind,
) {
self.services
.analytics_events_client
.track_goal_event(CodexGoalEvent {
thread_id: self.conversation_id.to_string(),
turn_id,
goal_id: goal.goal_id.clone(),
event_kind,
goal_status: analytics_goal_status(goal.status),
has_token_budget: goal.token_budget.is_some(),
});
}
fn track_goal_status_change(
&self,
goal: &codex_state::ThreadGoal,
previous_status: Option<codex_state::ThreadGoalStatus>,
turn_id: Option<String>,
) {
if previous_status.is_some_and(|status| status != goal.status) {
self.track_goal_lifecycle_event(goal, turn_id, GoalEventKind::StatusChanged);
}
}
}
fn analytics_goal_status(status: codex_state::ThreadGoalStatus) -> GoalStatus {
match status {
codex_state::ThreadGoalStatus::Active => GoalStatus::Active,
codex_state::ThreadGoalStatus::Paused => GoalStatus::Paused,
codex_state::ThreadGoalStatus::Blocked => GoalStatus::Blocked,
codex_state::ThreadGoalStatus::UsageLimited => GoalStatus::UsageLimited,
codex_state::ThreadGoalStatus::BudgetLimited => GoalStatus::BudgetLimited,
codex_state::ThreadGoalStatus::Complete => GoalStatus::Complete,
}
}
impl Session {
@@ -1559,6 +1707,7 @@ pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 {
#[cfg(test)]
mod tests {
use super::GoalTurnAccountingSnapshot;
use super::goal_context_input_item;
use super::goal_token_delta_for_usage;
use super::should_ignore_goal_for_mode;
@@ -1590,6 +1739,16 @@ mod tests {
assert_eq!(580, goal_token_delta_for_usage(&usage));
}
#[test]
fn accounting_only_goal_does_not_create_turn_participant() {
let mut snapshot = GoalTurnAccountingSnapshot::new("turn-1", TokenUsage::default());
snapshot.mark_goal_for_accounting("goal-1");
assert!(snapshot.active_this_turn());
assert!(snapshot.into_participants().is_empty());
}
#[test]
fn wall_clock_accounting_advances_by_persisted_seconds() {
let mut snapshot = super::GoalWallClockAccountingSnapshot::new();
@@ -0,0 +1,57 @@
use std::collections::HashMap;
#[derive(Debug)]
pub(super) struct GoalTurnParticipationTracker {
participants: HashMap<String, GoalTurnParticipant>,
}
#[derive(Debug)]
pub(super) struct GoalTurnParticipant {
pub(super) goal_id: String,
pub(super) goal_status: codex_state::ThreadGoalStatus,
pub(super) has_token_budget: bool,
}
impl GoalTurnParticipationTracker {
pub(super) fn new() -> Self {
Self {
participants: HashMap::new(),
}
}
pub(super) fn mark_active_goal(&mut self, goal: &codex_state::ThreadGoal) {
self.participants
.entry(goal.goal_id.clone())
.and_modify(|participant| participant.update_goal(goal))
.or_insert_with(|| GoalTurnParticipant::new(goal));
}
pub(super) fn update_goal(&mut self, goal: &codex_state::ThreadGoal) {
if let Some(participant) = self.participants.get_mut(goal.goal_id.as_str()) {
participant.update_goal(goal);
}
}
pub(super) fn into_participants(self) -> Vec<GoalTurnParticipant> {
self.participants.into_values().collect()
}
}
impl GoalTurnParticipant {
fn new(goal: &codex_state::ThreadGoal) -> Self {
Self {
goal_id: goal.goal_id.clone(),
goal_status: goal.status,
has_token_budget: goal.token_budget.is_some(),
}
}
fn update_goal(&mut self, goal: &codex_state::ThreadGoal) {
self.goal_status = goal.status;
self.has_token_budget = goal.token_budget.is_some();
}
}
#[cfg(test)]
#[path = "turn_participation_tests.rs"]
mod tests;
@@ -0,0 +1,88 @@
use super::GoalTurnParticipationTracker;
use chrono::Utc;
use codex_protocol::ThreadId;
use pretty_assertions::assert_eq;
fn test_goal(
goal_id: &str,
status: codex_state::ThreadGoalStatus,
token_budget: Option<i64>,
) -> codex_state::ThreadGoal {
let now = Utc::now();
codex_state::ThreadGoal {
thread_id: ThreadId::new(),
goal_id: goal_id.to_string(),
objective: "test objective".to_string(),
status,
token_budget,
tokens_used: 0,
time_used_seconds: 0,
created_at: now,
updated_at: now,
}
}
#[test]
fn retains_participant_after_goal_becomes_terminal() {
let mut goal = test_goal("goal-1", codex_state::ThreadGoalStatus::Active, None);
let mut tracker = GoalTurnParticipationTracker::new();
tracker.mark_active_goal(&goal);
goal.status = codex_state::ThreadGoalStatus::Complete;
tracker.update_goal(&goal);
let [participant] = tracker
.into_participants()
.try_into()
.expect("one goal should participate");
assert_eq!("goal-1", participant.goal_id);
assert_eq!(
codex_state::ThreadGoalStatus::Complete,
participant.goal_status
);
}
#[test]
fn emits_one_participant_when_same_goal_is_marked_active_repeatedly() {
let mut goal = test_goal("goal-1", codex_state::ThreadGoalStatus::Active, None);
let mut tracker = GoalTurnParticipationTracker::new();
tracker.mark_active_goal(&goal);
goal.token_budget = Some(1_000);
tracker.mark_active_goal(&goal);
let [participant] = tracker
.into_participants()
.try_into()
.expect("one goal should participate");
assert_eq!("goal-1", participant.goal_id);
assert!(participant.has_token_budget);
}
#[test]
fn retains_multiple_goal_participants() {
let first_goal = test_goal("goal-1", codex_state::ThreadGoalStatus::Active, None);
let second_goal = test_goal("goal-2", codex_state::ThreadGoalStatus::Active, Some(1_000));
let mut tracker = GoalTurnParticipationTracker::new();
tracker.mark_active_goal(&first_goal);
tracker.mark_active_goal(&second_goal);
let mut participants = tracker.into_participants();
participants.sort_by(|left, right| left.goal_id.cmp(&right.goal_id));
assert_eq!(2, participants.len());
assert_eq!("goal-1", participants[0].goal_id);
assert!(!participants[0].has_token_budget);
assert_eq!("goal-2", participants[1].goal_id);
assert!(participants[1].has_token_budget);
}
#[test]
fn ignores_updates_for_goals_that_did_not_participate() {
let goal = test_goal("goal-1", codex_state::ThreadGoalStatus::Complete, None);
let mut tracker = GoalTurnParticipationTracker::new();
tracker.update_goal(&goal);
assert!(tracker.into_participants().is_empty());
}
+2 -1
View File
@@ -235,7 +235,7 @@ impl GoalService {
tracing::warn!("failed to prepare external goal mutation: {err}");
}
let cleared = state_db
let cleared_goal = state_db
.thread_goals()
.delete_thread_goal(thread_id)
.await
@@ -243,6 +243,7 @@ impl GoalService {
GoalServiceError::Internal(format!("failed to clear thread goal: {err}"))
})?;
let cleared = cleared_goal.is_some();
if cleared
&& let Some(runtime) = self.runtime_for_thread(thread_id)
&& let Err(err) = runtime.apply_external_goal_clear().await
+22 -7
View File
@@ -368,18 +368,31 @@ WHERE thread_id = ?
self.get_thread_goal(thread_id).await
}
pub async fn delete_thread_goal(&self, thread_id: ThreadId) -> anyhow::Result<bool> {
let result = sqlx::query(
pub async fn delete_thread_goal(
&self,
thread_id: ThreadId,
) -> anyhow::Result<Option<crate::ThreadGoal>> {
let row = sqlx::query(
r#"
DELETE FROM thread_goals
WHERE thread_id = ?
RETURNING
thread_id,
goal_id,
objective,
status,
token_budget,
tokens_used,
time_used_seconds,
created_at_ms,
updated_at_ms
"#,
)
.bind(thread_id.to_string())
.execute(self.pool.as_ref())
.fetch_optional(self.pool.as_ref())
.await?;
Ok(result.rows_affected() > 0)
row.map(|row| thread_goal_from_row(&row)).transpose()
}
pub async fn account_thread_goal_usage(
@@ -613,7 +626,8 @@ mod tests {
assert_eq!(0, replaced.tokens_used);
assert_eq!(0, replaced.time_used_seconds);
assert!(
assert_eq!(
Some(replaced),
runtime
.thread_goals()
.delete_thread_goal(thread_id)
@@ -628,8 +642,9 @@ mod tests {
.await
.unwrap()
);
assert!(
!runtime
assert_eq!(
None,
runtime
.thread_goals()
.delete_thread_goal(thread_id)
.await