From ca445e08998a4a9f5c37560acb0bb73129f6a066 Mon Sep 17 00:00:00 2001 From: Tom Wiltzius Date: Thu, 4 Jun 2026 21:40:44 -0700 Subject: [PATCH] add thread history projection observers --- codex-rs/Cargo.lock | 12 + codex-rs/Cargo.toml | 2 + codex-rs/app-server-protocol/Cargo.toml | 1 + .../src/protocol/lifecycle_projection.rs | 114 ++++++ .../protocol/lifecycle_projection_tests.rs | 82 ++++ .../app-server-protocol/src/protocol/mod.rs | 4 + .../src/protocol/thread_history.rs | 83 ++-- .../src/protocol/thread_history_builder.rs | 69 ++++ .../src/protocol/thread_item_projection.rs | 359 ++++++++++++++++++ .../protocol/thread_item_projection_tests.rs | 87 +++++ .../src/protocol/turn_summary_projection.rs | 209 ++++++++++ .../protocol/turn_summary_projection_tests.rs | 74 ++++ .../app-server/tests/suite/v2/thread_read.rs | 2 + codex-rs/core/src/session/session.rs | 11 +- codex-rs/thread-store-protocol/BUILD.bazel | 6 + codex-rs/thread-store-protocol/Cargo.toml | 21 + codex-rs/thread-store-protocol/src/lib.rs | 71 ++++ codex-rs/thread-store-protocol/src/tests.rs | 27 ++ codex-rs/thread-store/Cargo.toml | 1 + codex-rs/thread-store/src/in_memory.rs | 11 +- codex-rs/thread-store/src/lib.rs | 6 + codex-rs/thread-store/src/live_thread.rs | 29 +- .../thread-store/src/local/live_writer.rs | 11 +- codex-rs/thread-store/src/local/mod.rs | 9 + codex-rs/thread-store/src/types.rs | 5 +- 25 files changed, 1263 insertions(+), 43 deletions(-) create mode 100644 codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs create mode 100644 codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs create mode 100644 codex-rs/app-server-protocol/src/protocol/thread_history_builder.rs create mode 100644 codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs create mode 100644 codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs create mode 100644 codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs create mode 100644 codex-rs/app-server-protocol/src/protocol/turn_summary_projection_tests.rs create mode 100644 codex-rs/thread-store-protocol/BUILD.bazel create mode 100644 codex-rs/thread-store-protocol/Cargo.toml create mode 100644 codex-rs/thread-store-protocol/src/lib.rs create mode 100644 codex-rs/thread-store-protocol/src/tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 2183d91b64..067a4176ef 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2041,6 +2041,7 @@ dependencies = [ "codex-experimental-api-macros", "codex-protocol", "codex-shell-command", + "codex-thread-store-protocol", "codex-utils-absolute-path", "codex-utils-cargo-bin", "inventory", @@ -3813,6 +3814,7 @@ dependencies = [ "codex-protocol", "codex-rollout", "codex-state", + "codex-thread-store-protocol", "codex-utils-path", "pretty_assertions", "serde", @@ -3824,6 +3826,16 @@ dependencies = [ "uuid", ] +[[package]] +name = "codex-thread-store-protocol" +version = "0.0.0" +dependencies = [ + "codex-protocol", + "pretty_assertions", + "serde", + "serde_json", +] + [[package]] name = "codex-tools" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 59d161958d..d77268442c 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -111,6 +111,7 @@ members = [ "terminal-detection", "test-binary-support", "thread-manager-sample", + "thread-store-protocol", "thread-store", "uds", "codex-experimental-api-macros", @@ -217,6 +218,7 @@ codex-stdio-to-uds = { path = "stdio-to-uds" } codex-terminal-detection = { path = "terminal-detection" } codex-test-binary-support = { path = "test-binary-support" } codex-thread-store = { path = "thread-store" } +codex-thread-store-protocol = { path = "thread-store-protocol" } codex-tools = { path = "tools" } codex-tui = { path = "tui" } codex-uds = { path = "uds" } diff --git a/codex-rs/app-server-protocol/Cargo.toml b/codex-rs/app-server-protocol/Cargo.toml index 0749b07e08..01b9cd2240 100644 --- a/codex-rs/app-server-protocol/Cargo.toml +++ b/codex-rs/app-server-protocol/Cargo.toml @@ -18,6 +18,7 @@ clap = { workspace = true, features = ["derive"] } codex-experimental-api-macros = { workspace = true } codex-protocol = { workspace = true } codex-shell-command = { workspace = true } +codex-thread-store-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } schemars = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs new file mode 100644 index 0000000000..cff2580c3e --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection.rs @@ -0,0 +1,114 @@ +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_thread_store_protocol::LifecycleMutation; +use codex_thread_store_protocol::ThreadHistoryMutation; +use codex_thread_store_protocol::ThreadHistoryMutationMetadata; +use codex_thread_store_protocol::ThreadHistoryProjectionObserver; +use serde_json::json; + +#[cfg(test)] +#[path = "lifecycle_projection_tests.rs"] +mod tests; + +/// Observes append batches and emits only thread lifecycle mutations. +pub struct LifecycleProjectionObserver; + +impl Default for LifecycleProjectionObserver { + fn default() -> Self { + Self::new() + } +} + +impl LifecycleProjectionObserver { + pub fn new() -> Self { + Self + } + + pub fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec { + source_rollout_items(persisted_rollout_items, projection_source_events) + .iter() + .filter_map(lifecycle_mutation) + .collect() + } +} + +impl ThreadHistoryProjectionObserver for LifecycleProjectionObserver { + fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec { + LifecycleProjectionObserver::observe_append( + self, + persisted_rollout_items, + projection_source_events, + ) + } +} + +fn lifecycle_mutation(rollout_item: &RolloutItem) -> Option { + let RolloutItem::EventMsg(event) = rollout_item else { + return None; + }; + let (event_type, turn_id, payload) = match event { + EventMsg::TurnStarted(payload) => ( + "turn.started", + Some(payload.turn_id.clone()), + json!({ + "startedAt": payload.started_at, + }), + ), + EventMsg::TurnComplete(payload) => ( + "turn.completed", + Some(payload.turn_id.clone()), + json!({ + "completedAt": payload.completed_at, + "durationMs": payload.duration_ms, + }), + ), + EventMsg::TurnAborted(payload) => ( + "turn.cancelled", + payload.turn_id.clone(), + json!({ + "reason": payload.reason, + "completedAt": payload.completed_at, + "durationMs": payload.duration_ms, + }), + ), + EventMsg::ThreadRolledBack(payload) => ( + "thread.rolled_back", + None, + json!({ + "numTurns": payload.num_turns, + }), + ), + _ => return None, + }; + Some(ThreadHistoryMutation::Lifecycle(LifecycleMutation { + metadata: mutation_metadata(), + payload: json!({ + "eventType": event_type, + "turnId": turn_id, + "payload": payload, + }), + })) +} + +fn mutation_metadata() -> ThreadHistoryMutationMetadata { + ThreadHistoryMutationMetadata { schema_version: 1 } +} + +fn source_rollout_items<'a>( + persisted_rollout_items: &'a [RolloutItem], + projection_source_events: &'a [RolloutItem], +) -> &'a [RolloutItem] { + if projection_source_events.is_empty() { + persisted_rollout_items + } else { + projection_source_events + } +} diff --git a/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs new file mode 100644 index 0000000000..e118685da8 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/lifecycle_projection_tests.rs @@ -0,0 +1,82 @@ +use super::*; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::ThreadRolledBackEvent; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnStartedEvent; +use codex_protocol::protocol::UserMessageEvent; +use pretty_assertions::assert_eq; +use serde_json::json; + +#[test] +fn emits_lifecycle_mutations_from_lifecycle_events_only() { + let mut observer = LifecycleProjectionObserver::new(); + let persisted_rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-a".into(), + trace_id: None, + started_at: Some(10), + model_context_window: None, + collaboration_mode_kind: Default::default(), + })), + RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, + message: "hello".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + ..Default::default() + })), + RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-a".into(), + last_agent_message: None, + completed_at: Some(11), + duration_ms: Some(1_000), + time_to_first_token_ms: None, + })), + RolloutItem::EventMsg(EventMsg::ThreadRolledBack(ThreadRolledBackEvent { + num_turns: 1, + })), + ]; + let mutations = observer.observe_append(&persisted_rollout_items, &[]); + + assert_eq!( + lifecycle_payloads(mutations), + vec![ + json!({ + "eventType": "turn.started", + "turnId": "turn-a", + "payload": { + "startedAt": 10, + }, + }), + json!({ + "eventType": "turn.completed", + "turnId": "turn-a", + "payload": { + "completedAt": 11, + "durationMs": 1_000, + }, + }), + json!({ + "eventType": "thread.rolled_back", + "turnId": null, + "payload": { + "numTurns": 1, + }, + }), + ] + ); +} + +fn lifecycle_payloads(mutations: Vec) -> Vec { + mutations + .into_iter() + .map(|mutation| match mutation { + ThreadHistoryMutation::Lifecycle(mutation) => mutation.payload, + ThreadHistoryMutation::ThreadItem(_) | ThreadHistoryMutation::TurnSummary(_) => { + panic!("lifecycle observer emitted non-lifecycle mutation") + } + }) + .collect() +} diff --git a/codex-rs/app-server-protocol/src/protocol/mod.rs b/codex-rs/app-server-protocol/src/protocol/mod.rs index 592944b35f..4402dad0b2 100644 --- a/codex-rs/app-server-protocol/src/protocol/mod.rs +++ b/codex-rs/app-server-protocol/src/protocol/mod.rs @@ -4,8 +4,12 @@ pub mod common; pub mod event_mapping; pub mod item_builders; +mod lifecycle_projection; mod mappers; mod serde_helpers; pub mod thread_history; +mod thread_history_builder; +mod thread_item_projection; +mod turn_summary_projection; pub mod v1; pub mod v2; diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index aa65f9ab9d..a25173ab53 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -58,6 +58,11 @@ use std::collections::HashMap; use tracing::warn; use uuid::Uuid; +pub use super::lifecycle_projection::*; +pub use super::thread_history_builder::*; +pub use super::thread_item_projection::*; +pub use super::turn_summary_projection::*; + #[cfg(test)] use crate::protocol::v2::CommandAction; #[cfg(test)] @@ -71,19 +76,7 @@ use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus; #[cfg(test)] use codex_protocol::protocol::PatchApplyStatus as CorePatchApplyStatus; -/// Convert persisted [`RolloutItem`] entries into a sequence of [`Turn`] values. -/// -/// When available, this uses `TurnContext.turn_id` as the canonical turn id so -/// resumed/rebuilt thread history preserves the original turn identifiers. -pub fn build_turns_from_rollout_items(items: &[RolloutItem]) -> Vec { - let mut builder = ThreadHistoryBuilder::new(); - for item in items { - builder.handle_rollout_item(item); - } - builder.finish() -} - -pub struct ThreadHistoryBuilder { +pub(super) struct ThreadHistoryState { turns: Vec, current_turn: Option, next_item_index: i64, @@ -91,14 +84,8 @@ pub struct ThreadHistoryBuilder { next_rollout_index: usize, } -impl Default for ThreadHistoryBuilder { - fn default() -> Self { - Self::new() - } -} - -impl ThreadHistoryBuilder { - pub fn new() -> Self { +impl ThreadHistoryState { + pub(super) fn new() -> Self { Self { turns: Vec::new(), current_turn: None, @@ -108,27 +95,31 @@ impl ThreadHistoryBuilder { } } - pub fn reset(&mut self) { - *self = Self::new(); - } - - pub fn finish(mut self) -> Vec { + pub(super) fn finish(mut self) -> Vec { self.finish_current_turn(); self.turns } - pub fn active_turn_snapshot(&self) -> Option { + pub(super) fn active_turn_snapshot(&self) -> Option { self.current_turn .as_ref() .map(Turn::from) .or_else(|| self.turns.last().cloned()) } + pub(super) fn turns_snapshot(&self) -> Vec { + let mut turns = self.turns.clone(); + if let Some(turn) = self.current_turn.as_ref() { + turns.push(Turn::from(turn)); + } + turns + } + /// Returns the index of the active turn snapshot within the finished turn list. /// /// When a turn is still open, this is the index it will occupy after /// `finish`. When no turn is open, it is the index of the last finished turn. - pub fn active_turn_position(&self) -> Option { + pub(super) fn active_turn_position(&self) -> Option { if self.current_turn.is_some() { Some(self.turns.len()) } else if self.turns.is_empty() { @@ -138,29 +129,49 @@ impl ThreadHistoryBuilder { } } - pub fn has_active_turn(&self) -> bool { + pub(super) fn has_active_turn(&self) -> bool { self.current_turn.is_some() } - pub fn active_turn_id_if_explicit(&self) -> Option { + pub(super) fn active_turn_id_if_explicit(&self) -> Option { self.current_turn .as_ref() .filter(|turn| turn.opened_explicitly) .map(|turn| turn.id.clone()) } - pub fn active_turn_start_index(&self) -> Option { + pub(super) fn active_turn_start_index(&self) -> Option { self.current_turn .as_ref() .map(|turn| turn.rollout_start_index) } + pub(super) fn set_next_item_index(&mut self, next_item_index: i64) { + self.next_item_index = next_item_index; + } + + pub(super) fn next_item_index(&self) -> i64 { + self.next_item_index + } + + pub(super) fn current_turn_id(&self) -> Option { + self.current_turn.as_ref().map(|turn| turn.id.clone()) + } + + pub(super) fn restore_current_turn(&mut self, turn_id: String) { + self.current_turn = Some( + self.new_turn(Some(turn_id)) + .with_status(TurnStatus::InProgress) + .opened_explicitly(), + ); + } + /// Shared reducer for persisted rollout replay and in-memory current-turn /// tracking used by running thread resume/rejoin. /// /// This function should handle all EventMsg variants that can be persisted in a rollout file. /// See `should_persist_event_msg` in `codex-rs/core/rollout/policy.rs`. - pub fn handle_event(&mut self, event: &EventMsg) { + pub(super) fn handle_event(&mut self, event: &EventMsg) { match event { EventMsg::UserMessage(payload) => self.handle_user_message(payload), EventMsg::AgentMessage(payload) => self.handle_agent_message( @@ -225,7 +236,7 @@ impl ThreadHistoryBuilder { } } - pub fn handle_rollout_item(&mut self, item: &RolloutItem) { + pub(super) fn handle_rollout_item(&mut self, item: &RolloutItem) { self.current_rollout_index = self.next_rollout_index; self.next_rollout_index += 1; match item { @@ -236,6 +247,12 @@ impl ThreadHistoryBuilder { } } + pub(super) fn handle_rollout_items(&mut self, items: &[RolloutItem]) { + for item in items { + self.handle_rollout_item(item); + } + } + fn handle_response_item(&mut self, item: &codex_protocol::models::ResponseItem) { let codex_protocol::models::ResponseItem::Message { role, content, id, .. diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history_builder.rs b/codex-rs/app-server-protocol/src/protocol/thread_history_builder.rs new file mode 100644 index 0000000000..adbdab45fd --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/thread_history_builder.rs @@ -0,0 +1,69 @@ +use crate::protocol::thread_history::ThreadHistoryState; +use crate::protocol::v2::Turn; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; + +/// Convert persisted [`RolloutItem`] entries into a sequence of [`Turn`] values. +/// +/// When available, this uses `TurnContext.turn_id` as the canonical turn id so +/// resumed/rebuilt thread history preserves the original turn identifiers. +pub fn build_turns_from_rollout_items(items: &[RolloutItem]) -> Vec { + let mut state = ThreadHistoryState::new(); + state.handle_rollout_items(items); + state.finish() +} + +/// Full-history compatibility adapter over the event-to-turn reducer. +pub struct ThreadHistoryBuilder { + state: ThreadHistoryState, +} + +impl Default for ThreadHistoryBuilder { + fn default() -> Self { + Self::new() + } +} + +impl ThreadHistoryBuilder { + pub fn new() -> Self { + Self { + state: ThreadHistoryState::new(), + } + } + + pub fn reset(&mut self) { + self.state = ThreadHistoryState::new(); + } + + pub fn finish(self) -> Vec { + self.state.finish() + } + + pub fn active_turn_snapshot(&self) -> Option { + self.state.active_turn_snapshot() + } + + pub fn active_turn_position(&self) -> Option { + self.state.active_turn_position() + } + + pub fn has_active_turn(&self) -> bool { + self.state.has_active_turn() + } + + pub fn active_turn_id_if_explicit(&self) -> Option { + self.state.active_turn_id_if_explicit() + } + + pub fn active_turn_start_index(&self) -> Option { + self.state.active_turn_start_index() + } + + pub fn handle_event(&mut self, event: &EventMsg) { + self.state.handle_event(event); + } + + pub fn handle_rollout_item(&mut self, item: &RolloutItem) { + self.state.handle_rollout_item(item); + } +} diff --git a/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs b/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs new file mode 100644 index 0000000000..813c927a05 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/thread_item_projection.rs @@ -0,0 +1,359 @@ +use crate::protocol::thread_history::ThreadHistoryState; +use crate::protocol::v2::CollabAgentToolCallStatus; +use crate::protocol::v2::CommandExecutionStatus; +use crate::protocol::v2::DynamicToolCallStatus; +use crate::protocol::v2::McpToolCallStatus; +use crate::protocol::v2::PatchApplyStatus; +use crate::protocol::v2::ThreadItem; +use crate::protocol::v2::Turn; +use codex_protocol::protocol::RolloutItem; +use codex_thread_store_protocol::ThreadHistoryMutation; +use codex_thread_store_protocol::ThreadHistoryMutationMetadata; +use codex_thread_store_protocol::ThreadHistoryProjectionObserver; +use codex_thread_store_protocol::ThreadItemMutation; +use serde::Deserialize; +use serde::Serialize; +use serde_json::json; +use std::collections::HashMap; + +#[cfg(test)] +#[path = "thread_item_projection_tests.rs"] +mod tests; + +/// Incremental thread-item materialization state that a durable store can persist between appends. +/// +/// Persisting it lets the next append reuse stable item ordinals and update non-terminal +/// ThreadItems without replaying the full rollout history first. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ThreadItemProjectionCheckpoint { + pub next_thread_item_ordinal: i64, + /// Next fallback `item-N` ThreadItem id index used when the source event has no durable id. + pub next_generated_thread_item_id_index: i64, + pub current_turn: Option, + pub current_reasoning_item: Option, + pub open_items: HashMap, +} + +/// Active turn fields needed by incremental thread item projection. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CurrentTurnThreadItemState { + pub turn_id: String, +} + +/// Last reasoning item while reasoning deltas are still coalescing. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ReasoningAccumulator { + pub turn_id: String, + pub item_key: String, +} + +/// Latest durable identity for an item that may receive a later upsert. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct OpenThreadItemState { + pub turn_id: String, + pub item_ordinal: i64, +} + +/// Thread-item mutations emitted after applying one materialization batch. +#[derive(Clone, Debug)] +pub struct ThreadItemProjectionOutputBatch { + pub updated_checkpoint: ThreadItemProjectionCheckpoint, + pub thread_history_mutations: Vec, +} + +/// One raw append item reduced into before/after thread-history snapshots. +#[derive(Clone, Debug)] +struct ThreadItemProjectionObservation { + before_turns: Vec, + after_turns: Vec, +} + +/// Incrementally applies the event-to-turn reduction needed by ThreadItem materialization. +struct ThreadItemProjectionReducer { + state: ThreadHistoryState, +} + +impl ThreadItemProjectionReducer { + fn new() -> Self { + Self { + state: ThreadHistoryState::new(), + } + } + + fn materialized_turns(&self) -> Vec { + self.state.turns_snapshot() + } + + fn reduce_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec { + source_rollout_items(persisted_rollout_items, projection_source_events) + .iter() + .map(|item| { + let before_turns = self.state.turns_snapshot(); + self.state.handle_rollout_item(item); + ThreadItemProjectionObservation { + before_turns, + after_turns: self.state.turns_snapshot(), + } + }) + .collect() + } +} + +/// Observes append batches and emits only ThreadItem upserts and tombstones. +pub struct ThreadItemProjectionObserver { + reducer: ThreadItemProjectionReducer, + checkpoint: ThreadItemProjectionCheckpoint, + item_ordinals: HashMap, +} + +impl Default for ThreadItemProjectionObserver { + fn default() -> Self { + Self::new() + } +} + +impl ThreadItemProjectionObserver { + pub fn new() -> Self { + Self { + reducer: ThreadItemProjectionReducer::new(), + checkpoint: ThreadItemProjectionCheckpoint { + next_thread_item_ordinal: 1, + next_generated_thread_item_id_index: 1, + ..Default::default() + }, + item_ordinals: HashMap::new(), + } + } + + pub fn from_checkpoint(checkpoint: ThreadItemProjectionCheckpoint) -> Self { + let checkpoint = ThreadItemProjectionCheckpoint { + next_thread_item_ordinal: checkpoint.next_thread_item_ordinal.max(1), + next_generated_thread_item_id_index: checkpoint + .next_generated_thread_item_id_index + .max(1), + ..checkpoint + }; + let item_ordinals = checkpoint + .open_items + .iter() + .map(|(item_key, item)| (item_key.clone(), item.item_ordinal)) + .collect(); + let mut reducer = ThreadItemProjectionReducer::new(); + reducer + .state + .set_next_item_index(checkpoint.next_generated_thread_item_id_index); + if let Some(current_turn) = checkpoint.current_turn.as_ref() { + reducer + .state + .restore_current_turn(current_turn.turn_id.clone()); + } + Self { + reducer, + checkpoint, + item_ordinals, + } + } + + pub fn checkpoint(&self) -> &ThreadItemProjectionCheckpoint { + &self.checkpoint + } + + pub fn materialized_turns(&self) -> Vec { + self.reducer.materialized_turns() + } + + pub fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> ThreadItemProjectionOutputBatch { + let mut thread_history_mutations = Vec::new(); + for observation in self + .reducer + .reduce_append(persisted_rollout_items, projection_source_events) + { + self.emit_upserted_thread_items(&observation, &mut thread_history_mutations); + self.emit_removed_thread_items(&observation, &mut thread_history_mutations); + } + self.refresh_checkpoint(); + ThreadItemProjectionOutputBatch { + updated_checkpoint: self.checkpoint.clone(), + thread_history_mutations, + } + } + + fn emit_upserted_thread_items( + &mut self, + observation: &ThreadItemProjectionObservation, + mutations: &mut Vec, + ) { + for turn in &observation.after_turns { + let previous_turn = observation + .before_turns + .iter() + .find(|previous| previous.id == turn.id); + for item in &turn.items { + let previous_item = previous_turn + .and_then(|previous| previous.items.iter().find(|old| old.id() == item.id())); + if previous_item == Some(item) { + continue; + } + let item_key = item.id().to_string(); + let item_ordinal = + *self + .item_ordinals + .entry(item_key.clone()) + .or_insert_with(|| { + let item_ordinal = self.checkpoint.next_thread_item_ordinal; + self.checkpoint.next_thread_item_ordinal += 1; + item_ordinal + }); + mutations.push(thread_item_mutation(json!({ + "turnId": turn.id, + "itemKey": item_key, + "itemOrdinal": item_ordinal, + "mutationKind": "upsert", + "isOpen": is_open_item(item), + "materializedThreadItem": item, + }))); + } + } + } + + fn emit_removed_thread_items( + &self, + observation: &ThreadItemProjectionObservation, + mutations: &mut Vec, + ) { + for turn in &observation.before_turns { + let current_turn = observation + .after_turns + .iter() + .find(|current| current.id == turn.id); + for item in &turn.items { + if current_turn + .and_then(|current| current.items.iter().find(|new| new.id() == item.id())) + .is_some() + { + continue; + } + let item_key = item.id().to_string(); + let Some(item_ordinal) = self.item_ordinals.get(&item_key).copied() else { + continue; + }; + mutations.push(thread_item_mutation(json!({ + "turnId": turn.id, + "itemKey": item_key, + "itemOrdinal": item_ordinal, + "mutationKind": "tombstone", + "isOpen": false, + "materializedThreadItem": item, + }))); + } + } + } + + fn refresh_checkpoint(&mut self) { + let turns = self.reducer.materialized_turns(); + self.checkpoint.next_generated_thread_item_id_index = self.reducer.state.next_item_index(); + self.checkpoint.current_turn = self + .reducer + .state + .current_turn_id() + .map(|turn_id| CurrentTurnThreadItemState { turn_id }); + self.checkpoint.current_reasoning_item = turns.last().and_then(|turn| { + let item = turn.items.last()?; + matches!(item, ThreadItem::Reasoning { .. }).then(|| ReasoningAccumulator { + turn_id: turn.id.clone(), + item_key: item.id().to_string(), + }) + }); + self.checkpoint.open_items = turns + .iter() + .flat_map(|turn| { + turn.items.iter().filter_map(|item| { + if !is_open_item(item) { + return None; + } + let item_key = item.id().to_string(); + let item_ordinal = self.item_ordinals.get(&item_key).copied()?; + Some(( + item_key, + OpenThreadItemState { + turn_id: turn.id.clone(), + item_ordinal, + }, + )) + }) + }) + .collect(); + } +} + +impl ThreadHistoryProjectionObserver for ThreadItemProjectionObserver { + fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec { + ThreadItemProjectionObserver::observe_append( + self, + persisted_rollout_items, + projection_source_events, + ) + .thread_history_mutations + } +} + +fn thread_item_mutation(payload: serde_json::Value) -> ThreadHistoryMutation { + ThreadHistoryMutation::ThreadItem(ThreadItemMutation { + metadata: mutation_metadata(), + payload, + }) +} + +fn mutation_metadata() -> ThreadHistoryMutationMetadata { + ThreadHistoryMutationMetadata { schema_version: 1 } +} + +fn source_rollout_items<'a>( + persisted_rollout_items: &'a [RolloutItem], + projection_source_events: &'a [RolloutItem], +) -> &'a [RolloutItem] { + if projection_source_events.is_empty() { + persisted_rollout_items + } else { + projection_source_events + } +} + +fn is_open_item(item: &ThreadItem) -> bool { + match item { + ThreadItem::CommandExecution { status, .. } => { + matches!(status, CommandExecutionStatus::InProgress) + } + ThreadItem::McpToolCall { status, .. } => matches!(status, McpToolCallStatus::InProgress), + ThreadItem::DynamicToolCall { status, .. } => { + matches!(status, DynamicToolCallStatus::InProgress) + } + ThreadItem::CollabAgentToolCall { status, .. } => { + matches!(status, CollabAgentToolCallStatus::InProgress) + } + ThreadItem::WebSearch { action, .. } => action.is_none(), + ThreadItem::ImageGeneration { status, .. } => status.is_empty(), + ThreadItem::FileChange { status, .. } => matches!(status, PatchApplyStatus::InProgress), + ThreadItem::UserMessage { .. } + | ThreadItem::HookPrompt { .. } + | ThreadItem::AgentMessage { .. } + | ThreadItem::Plan { .. } + | ThreadItem::Reasoning { .. } + | ThreadItem::ImageView { .. } + | ThreadItem::EnteredReviewMode { .. } + | ThreadItem::ExitedReviewMode { .. } + | ThreadItem::ContextCompaction { .. } => false, + } +} diff --git a/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs b/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs new file mode 100644 index 0000000000..9197b52820 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/thread_item_projection_tests.rs @@ -0,0 +1,87 @@ +use super::*; +use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::ExecCommandSource; +use codex_protocol::protocol::ExecCommandStatus as CoreExecCommandStatus; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::TurnStartedEvent; +use codex_utils_absolute_path::test_support::PathBufExt; +use codex_utils_absolute_path::test_support::test_path_buf; +use pretty_assertions::assert_eq; +use serde_json::Value; +use std::time::Duration; + +#[test] +fn reuses_thread_item_ordinal_for_open_item_upserts() { + let mut observer = ThreadItemProjectionObserver::new(); + let begin_projection_source_events = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-a".into(), + trace_id: None, + started_at: None, + model_context_window: None, + collaboration_mode_kind: Default::default(), + })), + RolloutItem::EventMsg(EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id: "exec-1".into(), + process_id: Some("pid-1".into()), + turn_id: "turn-a".into(), + started_at_ms: 0, + command: vec!["echo".into(), "hello".into()], + cwd: test_path_buf("/tmp").abs(), + parsed_cmd: vec![ParsedCommand::Unknown { + cmd: "echo hello".into(), + }], + source: ExecCommandSource::Agent, + interaction_input: None, + })), + ]; + let begin_mutations = observer + .observe_append(&[], &begin_projection_source_events) + .thread_history_mutations; + let checkpoint = observer.checkpoint().clone(); + let mut resumed_observer = ThreadItemProjectionObserver::from_checkpoint(checkpoint); + let end_projection_source_events = vec![RolloutItem::EventMsg(EventMsg::ExecCommandEnd( + ExecCommandEndEvent { + call_id: "exec-1".into(), + process_id: Some("pid-1".into()), + turn_id: "turn-a".into(), + completed_at_ms: 1, + command: vec!["echo".into(), "hello".into()], + cwd: test_path_buf("/tmp").abs(), + parsed_cmd: vec![ParsedCommand::Unknown { + cmd: "echo hello".into(), + }], + source: ExecCommandSource::Agent, + interaction_input: None, + stdout: "hello\n".into(), + stderr: String::new(), + aggregated_output: "hello\n".into(), + exit_code: 0, + duration: Duration::from_millis(1), + formatted_output: "hello\n".into(), + status: CoreExecCommandStatus::Completed, + }, + ))]; + let end_mutations = resumed_observer + .observe_append(&[], &end_projection_source_events) + .thread_history_mutations; + + let begin_payload = only_thread_item_payload(begin_mutations); + let end_payload = only_thread_item_payload(end_mutations); + assert_eq!(begin_payload["itemOrdinal"], end_payload["itemOrdinal"]); + assert_eq!(begin_payload["isOpen"], true); + assert_eq!(end_payload["isOpen"], false); +} + +fn only_thread_item_payload(mutations: Vec) -> Value { + let mut payloads = mutations.into_iter().filter_map(|mutation| match mutation { + ThreadHistoryMutation::ThreadItem(mutation) => Some(mutation.payload), + ThreadHistoryMutation::TurnSummary(_) | ThreadHistoryMutation::Lifecycle(_) => None, + }); + let payload = payloads.next().expect("thread item mutation"); + assert!(payloads.next().is_none()); + payload +} diff --git a/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs b/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs new file mode 100644 index 0000000000..7063f03b14 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/turn_summary_projection.rs @@ -0,0 +1,209 @@ +use crate::protocol::v2::TurnStatus; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_thread_store_protocol::ThreadHistoryMutation; +use codex_thread_store_protocol::ThreadHistoryMutationMetadata; +use codex_thread_store_protocol::ThreadHistoryProjectionObserver; +use codex_thread_store_protocol::TurnSummaryMutation; +use serde_json::json; +use std::collections::HashMap; + +#[cfg(test)] +#[path = "turn_summary_projection_tests.rs"] +mod tests; + +/// Observes append batches and emits only turn-summary mutations. +pub struct TurnSummaryProjectionObserver { + current_turn_id: Option, + turn_order: Vec, + summaries: HashMap, +} + +impl Default for TurnSummaryProjectionObserver { + fn default() -> Self { + Self::new() + } +} + +impl TurnSummaryProjectionObserver { + pub fn new() -> Self { + Self { + current_turn_id: None, + turn_order: Vec::new(), + summaries: HashMap::new(), + } + } + + pub fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec { + source_rollout_items(persisted_rollout_items, projection_source_events) + .iter() + .filter_map(|rollout_item| self.observe_item(rollout_item)) + .collect() + } + + fn observe_item(&mut self, rollout_item: &RolloutItem) -> Option { + let RolloutItem::EventMsg(event) = rollout_item else { + return None; + }; + let (turn_id, summary) = match event { + EventMsg::TurnStarted(payload) => { + let summary = TurnSummaryState { + status: TurnStatus::InProgress, + started_at: payload.started_at, + completed_at: None, + duration_ms: None, + }; + self.upsert_summary(payload.turn_id.clone(), summary.clone()); + self.current_turn_id = Some(payload.turn_id.clone()); + (payload.turn_id.clone(), summary) + } + EventMsg::TurnComplete(payload) => { + let turn_id = self + .summaries + .contains_key(&payload.turn_id) + .then(|| payload.turn_id.clone()) + .or_else(|| self.current_turn_id.clone())?; + let summary = self.update_summary(&turn_id, |summary| { + if matches!( + summary.status, + TurnStatus::Completed | TurnStatus::InProgress + ) { + summary.status = TurnStatus::Completed; + } + summary.completed_at = payload.completed_at; + summary.duration_ms = payload.duration_ms; + }); + if self.current_turn_id.as_deref() == Some(turn_id.as_str()) { + self.current_turn_id = None; + } + (turn_id, summary) + } + EventMsg::TurnAborted(payload) => { + let turn_id = payload + .turn_id + .clone() + .filter(|turn_id| self.summaries.contains_key(turn_id)) + .or_else(|| self.current_turn_id.clone())?; + let summary = self.update_summary(&turn_id, |summary| { + summary.status = TurnStatus::Interrupted; + summary.completed_at = payload.completed_at; + summary.duration_ms = payload.duration_ms; + }); + (turn_id, summary) + } + EventMsg::Error(payload) if payload.affects_turn_status() => { + let turn_id = self.current_turn_id.clone()?; + let summary = self.update_summary(&turn_id, |summary| { + summary.status = TurnStatus::Failed; + }); + (turn_id, summary) + } + EventMsg::ThreadRolledBack(payload) => { + self.roll_back(payload.num_turns); + return None; + } + _ => return None, + }; + Some(turn_summary_mutation(&turn_id, &summary)) + } + + fn upsert_summary(&mut self, turn_id: String, summary: TurnSummaryState) { + if !self.summaries.contains_key(&turn_id) { + self.turn_order.push(turn_id.clone()); + } + self.summaries.insert(turn_id, summary); + } + + fn update_summary( + &mut self, + turn_id: &str, + update: impl FnOnce(&mut TurnSummaryState), + ) -> TurnSummaryState { + let summary = self + .summaries + .entry(turn_id.to_string()) + .or_insert_with(TurnSummaryState::default); + update(summary); + summary.clone() + } + + fn roll_back(&mut self, num_turns: u32) { + let num_turns = usize::try_from(num_turns).unwrap_or(usize::MAX); + for _ in 0..num_turns.min(self.turn_order.len()) { + let Some(turn_id) = self.turn_order.pop() else { + return; + }; + self.summaries.remove(&turn_id); + if self.current_turn_id.as_deref() == Some(turn_id.as_str()) { + self.current_turn_id = None; + } + } + } +} + +impl ThreadHistoryProjectionObserver for TurnSummaryProjectionObserver { + fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec { + TurnSummaryProjectionObserver::observe_append( + self, + persisted_rollout_items, + projection_source_events, + ) + } +} + +#[derive(Clone)] +struct TurnSummaryState { + status: TurnStatus, + started_at: Option, + completed_at: Option, + duration_ms: Option, +} + +impl Default for TurnSummaryState { + fn default() -> Self { + Self { + status: TurnStatus::Completed, + started_at: None, + completed_at: None, + duration_ms: None, + } + } +} + +fn turn_summary_mutation(turn_id: &str, summary: &TurnSummaryState) -> ThreadHistoryMutation { + ThreadHistoryMutation::TurnSummary(TurnSummaryMutation { + metadata: mutation_metadata(), + payload: json!({ + "turnId": turn_id, + "mutation": { + "status": summary.status, + "startedAt": summary.started_at, + "completedAt": summary.completed_at, + "durationMs": summary.duration_ms, + }, + }), + }) +} + +fn mutation_metadata() -> ThreadHistoryMutationMetadata { + ThreadHistoryMutationMetadata { schema_version: 1 } +} + +fn source_rollout_items<'a>( + persisted_rollout_items: &'a [RolloutItem], + projection_source_events: &'a [RolloutItem], +) -> &'a [RolloutItem] { + if projection_source_events.is_empty() { + persisted_rollout_items + } else { + projection_source_events + } +} diff --git a/codex-rs/app-server-protocol/src/protocol/turn_summary_projection_tests.rs b/codex-rs/app-server-protocol/src/protocol/turn_summary_projection_tests.rs new file mode 100644 index 0000000000..03ba3bd047 --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/turn_summary_projection_tests.rs @@ -0,0 +1,74 @@ +use super::*; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::TurnCompleteEvent; +use codex_protocol::protocol::TurnStartedEvent; +use codex_protocol::protocol::UserMessageEvent; +use pretty_assertions::assert_eq; +use serde_json::json; + +#[test] +fn ignores_item_only_events_between_turn_summary_updates() { + let mut observer = TurnSummaryProjectionObserver::new(); + let persisted_rollout_items = vec![ + RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { + turn_id: "turn-a".into(), + trace_id: None, + started_at: Some(10), + model_context_window: None, + collaboration_mode_kind: Default::default(), + })), + RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { + client_id: None, + message: "hello".into(), + images: None, + text_elements: Vec::new(), + local_images: Vec::new(), + ..Default::default() + })), + RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent { + turn_id: "turn-a".into(), + last_agent_message: None, + completed_at: Some(11), + duration_ms: Some(1_000), + time_to_first_token_ms: None, + })), + ]; + let mutations = observer.observe_append(&persisted_rollout_items, &[]); + + assert_eq!( + turn_summary_payloads(mutations), + vec![ + json!({ + "turnId": "turn-a", + "mutation": { + "status": "inProgress", + "startedAt": 10, + "completedAt": null, + "durationMs": null, + }, + }), + json!({ + "turnId": "turn-a", + "mutation": { + "status": "completed", + "startedAt": 10, + "completedAt": 11, + "durationMs": 1_000, + }, + }), + ] + ); +} + +fn turn_summary_payloads(mutations: Vec) -> Vec { + mutations + .into_iter() + .map(|mutation| match mutation { + ThreadHistoryMutation::TurnSummary(mutation) => mutation.payload, + ThreadHistoryMutation::ThreadItem(_) | ThreadHistoryMutation::Lifecycle(_) => { + panic!("turn summary observer emitted non-turn-summary mutation") + } + }) + .collect() +} diff --git a/codex-rs/app-server/tests/suite/v2/thread_read.rs b/codex-rs/app-server/tests/suite/v2/thread_read.rs index 0a99d30ada..fce5ae0e3e 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_read.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_read.rs @@ -484,6 +484,7 @@ async fn thread_read_loaded_include_turns_reads_store_history_without_rollout_pa .append_items(AppendThreadItemsParams { thread_id, items: store_history_items(), + thread_history_mutations: Vec::new(), }) .await?; @@ -1374,6 +1375,7 @@ async fn seed_pathless_store_thread( .append_items(AppendThreadItemsParams { thread_id, items: store_history_items(), + thread_history_mutations: Vec::new(), }) .await?; store diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 07d249613a..6d5c90a291 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -594,7 +594,16 @@ impl Session { .await? } }; - Ok(Some(live_thread)) + let thread_history_projection_observers: Vec< + Box, + > = vec![ + Box::new(codex_app_server_protocol::ThreadItemProjectionObserver::new()), + Box::new(codex_app_server_protocol::TurnSummaryProjectionObserver::new()), + Box::new(codex_app_server_protocol::LifecycleProjectionObserver::new()), + ]; + Ok(Some(live_thread.with_thread_history_projection_observers( + thread_history_projection_observers, + ))) } } .instrument(info_span!( diff --git a/codex-rs/thread-store-protocol/BUILD.bazel b/codex-rs/thread-store-protocol/BUILD.bazel new file mode 100644 index 0000000000..df69af6fba --- /dev/null +++ b/codex-rs/thread-store-protocol/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "thread-store-protocol", + crate_name = "codex_thread_store_protocol", +) diff --git a/codex-rs/thread-store-protocol/Cargo.toml b/codex-rs/thread-store-protocol/Cargo.toml new file mode 100644 index 0000000000..17a04dcc4f --- /dev/null +++ b/codex-rs/thread-store-protocol/Cargo.toml @@ -0,0 +1,21 @@ +[package] +edition.workspace = true +license.workspace = true +name = "codex-thread-store-protocol" +version.workspace = true + +[lib] +name = "codex_thread_store_protocol" +path = "src/lib.rs" +doctest = false + +[lints] +workspace = true + +[dependencies] +codex-protocol = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } + +[dev-dependencies] +pretty_assertions = { workspace = true } diff --git a/codex-rs/thread-store-protocol/src/lib.rs b/codex-rs/thread-store-protocol/src/lib.rs new file mode 100644 index 0000000000..b7b13e2c45 --- /dev/null +++ b/codex-rs/thread-store-protocol/src/lib.rs @@ -0,0 +1,71 @@ +use codex_protocol::protocol::RolloutItem; +use serde::Deserialize; +use serde::Serialize; +use serde_json::Value; + +#[cfg(test)] +#[path = "tests.rs"] +mod tests; + +/// Metadata shared by one derived thread-history mutation. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct ThreadHistoryMutationMetadata { + pub schema_version: u32, +} + +/// One typed thread-item mutation emitted alongside a durable rollout append. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct ThreadItemMutation { + #[serde(flatten)] + pub metadata: ThreadHistoryMutationMetadata, + pub payload: Value, +} + +/// One typed turn-summary mutation emitted alongside a durable rollout append. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct TurnSummaryMutation { + #[serde(flatten)] + pub metadata: ThreadHistoryMutationMetadata, + pub payload: Value, +} + +/// One typed lifecycle mutation emitted alongside a durable rollout append. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct LifecycleMutation { + #[serde(flatten)] + pub metadata: ThreadHistoryMutationMetadata, + pub payload: Value, +} + +/// Derived thread-history mutation emitted alongside a durable rollout append. +/// +/// Store implementations match this finite union to route each mutation to its durable indexed +/// view. Payloads stay storage-neutral here because this crate cannot depend on app-server +/// `ThreadItem`; examples include thread-item materializations, turn summaries, and lifecycle +/// outbox rows derived from the same accepted rollout append. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum ThreadHistoryMutation { + ThreadItem(ThreadItemMutation), + TurnSummary(TurnSummaryMutation), + Lifecycle(LifecycleMutation), +} + +/// Observes a live append batch and derives typed thread-history mutations for the store. +/// +/// Implementations may materialize higher-level ThreadItem views from rollout items, but the +/// store boundary only receives storage-neutral mutation payloads. Examples include app-server +/// thread-item rows, turn summary rows, or lifecycle/search updates that should be committed +/// alongside the accepted canonical rollout append. +/// +/// `persisted_rollout_items` are the new canonical items that the store will append. +/// `projection_source_events` are the same append's new unfiltered raw rollout items so observers +/// can see filtered events such as exec begin; open/non-terminal projected items belong in the +/// observer's checkpoint, not in this append argument. +pub trait ThreadHistoryProjectionObserver: Send { + fn observe_append( + &mut self, + persisted_rollout_items: &[RolloutItem], + projection_source_events: &[RolloutItem], + ) -> Vec; +} diff --git a/codex-rs/thread-store-protocol/src/tests.rs b/codex-rs/thread-store-protocol/src/tests.rs new file mode 100644 index 0000000000..b2f289f9e8 --- /dev/null +++ b/codex-rs/thread-store-protocol/src/tests.rs @@ -0,0 +1,27 @@ +use super::*; +use pretty_assertions::assert_eq; +use serde_json::json; + +#[test] +fn thread_history_mutation_round_trips_typed_variant() { + let mutation = ThreadHistoryMutation::ThreadItem(ThreadItemMutation { + metadata: ThreadHistoryMutationMetadata { schema_version: 1 }, + payload: json!({ "itemKey": "item-1" }), + }); + let value = json!({ + "type": "thread_item", + "schema_version": 1, + "payload": { + "itemKey": "item-1", + }, + }); + + assert_eq!( + serde_json::to_value(&mutation).expect("serialize mutation"), + value + ); + assert_eq!( + serde_json::from_value::(value).expect("deserialize mutation"), + mutation + ); +} diff --git a/codex-rs/thread-store/Cargo.toml b/codex-rs/thread-store/Cargo.toml index 5a0608b4db..dd7d7af892 100644 --- a/codex-rs/thread-store/Cargo.toml +++ b/codex-rs/thread-store/Cargo.toml @@ -20,6 +20,7 @@ codex-install-context = { workspace = true } codex-protocol = { workspace = true } codex-rollout = { workspace = true } codex-state = { workspace = true } +codex-thread-store-protocol = { workspace = true } codex-utils-path = { workspace = true } serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } diff --git a/codex-rs/thread-store/src/in_memory.rs b/codex-rs/thread-store/src/in_memory.rs index b02fc15855..53d87a62a5 100644 --- a/codex-rs/thread-store/src/in_memory.rs +++ b/codex-rs/thread-store/src/in_memory.rs @@ -212,13 +212,14 @@ impl ThreadStore for InMemoryThreadStore { } async fn append_items(&self, params: AppendThreadItemsParams) -> ThreadStoreResult<()> { + let AppendThreadItemsParams { + thread_id, + items, + thread_history_mutations: _, + } = params; let mut state = self.state.lock().await; state.calls.append_items += 1; - state - .histories - .entry(params.thread_id) - .or_default() - .extend(params.items); + state.histories.entry(thread_id).or_default().extend(items); Ok(()) } diff --git a/codex-rs/thread-store/src/lib.rs b/codex-rs/thread-store/src/lib.rs index 157d13004f..ac2a87c0d1 100644 --- a/codex-rs/thread-store/src/lib.rs +++ b/codex-rs/thread-store/src/lib.rs @@ -12,6 +12,12 @@ mod store; mod thread_metadata_sync; mod types; +pub use codex_thread_store_protocol::LifecycleMutation; +pub use codex_thread_store_protocol::ThreadHistoryMutation; +pub use codex_thread_store_protocol::ThreadHistoryMutationMetadata; +pub use codex_thread_store_protocol::ThreadHistoryProjectionObserver; +pub use codex_thread_store_protocol::ThreadItemMutation; +pub use codex_thread_store_protocol::TurnSummaryMutation; pub use error::ThreadStoreError; pub use error::ThreadStoreResult; pub use in_memory::InMemoryThreadStore; diff --git a/codex-rs/thread-store/src/live_thread.rs b/codex-rs/thread-store/src/live_thread.rs index d1487860c1..5d24abe426 100644 --- a/codex-rs/thread-store/src/live_thread.rs +++ b/codex-rs/thread-store/src/live_thread.rs @@ -16,6 +16,7 @@ use crate::ReadThreadParams; use crate::ResumeThreadParams; use crate::StoredThread; use crate::StoredThreadHistory; +use crate::ThreadHistoryProjectionObserver; use crate::ThreadMetadataPatch; use crate::ThreadStore; use crate::ThreadStoreResult; @@ -32,6 +33,7 @@ pub struct LiveThread { thread_id: ThreadId, thread_store: Arc, metadata_sync: Arc>, + thread_history_projection_observers: Arc>>>, } /// Owns a live thread while session initialization is still fallible. @@ -95,6 +97,7 @@ impl LiveThread { thread_id, thread_store, metadata_sync: Arc::new(Mutex::new(metadata_sync)), + thread_history_projection_observers: default_thread_history_projection_observers(), }) } @@ -126,18 +129,37 @@ impl LiveThread { thread_id, thread_store, metadata_sync: Arc::new(Mutex::new(metadata_sync)), + thread_history_projection_observers: default_thread_history_projection_observers(), }) } + /// Installs append observers that derive typed thread-history mutations for this live thread. + pub fn with_thread_history_projection_observers( + mut self, + thread_history_projection_observers: Vec>, + ) -> Self { + self.thread_history_projection_observers = + Arc::new(Mutex::new(thread_history_projection_observers)); + self + } + pub async fn append_items(&self, items: &[RolloutItem]) -> ThreadStoreResult<()> { let canonical_items = persisted_rollout_items(items); - if canonical_items.is_empty() { + let thread_history_mutations = self + .thread_history_projection_observers + .lock() + .await + .iter_mut() + .flat_map(|observer| observer.observe_append(canonical_items.as_slice(), items)) + .collect::>(); + if canonical_items.is_empty() && thread_history_mutations.is_empty() { return Ok(()); } self.thread_store .append_items(AppendThreadItemsParams { thread_id: self.thread_id, items: canonical_items.clone(), + thread_history_mutations, }) .await?; let update = self @@ -294,3 +316,8 @@ impl LiveThread { Ok(()) } } + +fn default_thread_history_projection_observers() +-> Arc>>> { + Arc::new(Mutex::new(Vec::new())) +} diff --git a/codex-rs/thread-store/src/local/live_writer.rs b/codex-rs/thread-store/src/local/live_writer.rs index 0b31ae0ea8..36774b0cb2 100644 --- a/codex-rs/thread-store/src/local/live_writer.rs +++ b/codex-rs/thread-store/src/local/live_writer.rs @@ -77,11 +77,18 @@ pub(super) async fn append_items( store: &LocalThreadStore, params: AppendThreadItemsParams, ) -> ThreadStoreResult<()> { - let recorder = store.live_recorder(params.thread_id).await?; + let AppendThreadItemsParams { + thread_id, + items, + thread_history_mutations: _, + } = params; + let recorder = store.live_recorder(thread_id).await?; recorder - .record_canonical_items(params.items.as_slice()) + .record_canonical_items(items.as_slice()) .await .map_err(thread_store_io_error)?; + // TODO: Persist accepted thread-history mutations here if the local store grows durable + // ThreadItem, turn summary, or lifecycle tables. // LiveThread applies metadata immediately after append_items returns. Wait for the local // writer so SQLite never gets ahead of JSONL for accepted live appends. recorder.flush().await.map_err(thread_store_io_error) diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index 146bfbd843..77a331d207 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -329,6 +329,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("first live write")], + thread_history_mutations: Vec::new(), }) .await .expect("append live item"); @@ -351,6 +352,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("write after shutdown")], + thread_history_mutations: Vec::new(), }) .await .expect_err("shutdown should remove the live thread writer"); @@ -382,6 +384,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("raw append")], + thread_history_mutations: Vec::new(), }) .await .expect("append raw item"); @@ -666,6 +669,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("write after discard")], + thread_history_mutations: Vec::new(), }) .await .expect_err("discard should remove the live thread writer"); @@ -689,6 +693,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("before resume")], + thread_history_mutations: Vec::new(), }) .await .expect("append initial item"); @@ -724,6 +729,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("after resume")], + thread_history_mutations: Vec::new(), }) .await .expect("append resumed item"); @@ -835,6 +841,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("external history item")], + thread_history_mutations: Vec::new(), }) .await .expect("append live item"); @@ -921,6 +928,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("archived live history item")], + thread_history_mutations: Vec::new(), }) .await .expect("append live item"); @@ -979,6 +987,7 @@ mod tests { .append_items(AppendThreadItemsParams { thread_id, items: vec![user_message_item("path read")], + thread_history_mutations: Vec::new(), }) .await .expect("append item"); diff --git a/codex-rs/thread-store/src/types.rs b/codex-rs/thread-store/src/types.rs index 1ab42a3117..60347ab511 100644 --- a/codex-rs/thread-store/src/types.rs +++ b/codex-rs/thread-store/src/types.rs @@ -15,11 +15,11 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::ThreadMemoryMode as MemoryMode; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TokenUsage; +use codex_thread_store_protocol::ThreadHistoryMutation; use serde::Deserialize; use serde::Deserializer; use serde::Serialize; use serde::Serializer; - mod optional_option { use super::*; @@ -101,6 +101,9 @@ pub struct AppendThreadItemsParams { pub thread_id: ThreadId, /// Items to append in order. pub items: Vec, + /// Typed derived thread-history mutations committed with the canonical rollout append. + #[serde(default)] + pub thread_history_mutations: Vec, } /// Parameters for loading persisted history for resume, fork, rollback, and memory jobs.