mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
add thread history projection observers
This commit is contained in:
Generated
+12
@@ -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"
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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<ThreadHistoryMutation> {
|
||||
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<ThreadHistoryMutation> {
|
||||
LifecycleProjectionObserver::observe_append(
|
||||
self,
|
||||
persisted_rollout_items,
|
||||
projection_source_events,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn lifecycle_mutation(rollout_item: &RolloutItem) -> Option<ThreadHistoryMutation> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<ThreadHistoryMutation>) -> Vec<serde_json::Value> {
|
||||
mutations
|
||||
.into_iter()
|
||||
.map(|mutation| match mutation {
|
||||
ThreadHistoryMutation::Lifecycle(mutation) => mutation.payload,
|
||||
ThreadHistoryMutation::ThreadItem(_) | ThreadHistoryMutation::TurnSummary(_) => {
|
||||
panic!("lifecycle observer emitted non-lifecycle mutation")
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Turn> {
|
||||
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<Turn>,
|
||||
current_turn: Option<PendingTurn>,
|
||||
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<Turn> {
|
||||
pub(super) fn finish(mut self) -> Vec<Turn> {
|
||||
self.finish_current_turn();
|
||||
self.turns
|
||||
}
|
||||
|
||||
pub fn active_turn_snapshot(&self) -> Option<Turn> {
|
||||
pub(super) fn active_turn_snapshot(&self) -> Option<Turn> {
|
||||
self.current_turn
|
||||
.as_ref()
|
||||
.map(Turn::from)
|
||||
.or_else(|| self.turns.last().cloned())
|
||||
}
|
||||
|
||||
pub(super) fn turns_snapshot(&self) -> Vec<Turn> {
|
||||
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<usize> {
|
||||
pub(super) fn active_turn_position(&self) -> Option<usize> {
|
||||
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<String> {
|
||||
pub(super) fn active_turn_id_if_explicit(&self) -> Option<String> {
|
||||
self.current_turn
|
||||
.as_ref()
|
||||
.filter(|turn| turn.opened_explicitly)
|
||||
.map(|turn| turn.id.clone())
|
||||
}
|
||||
|
||||
pub fn active_turn_start_index(&self) -> Option<usize> {
|
||||
pub(super) fn active_turn_start_index(&self) -> Option<usize> {
|
||||
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<String> {
|
||||
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, ..
|
||||
|
||||
@@ -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<Turn> {
|
||||
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<Turn> {
|
||||
self.state.finish()
|
||||
}
|
||||
|
||||
pub fn active_turn_snapshot(&self) -> Option<Turn> {
|
||||
self.state.active_turn_snapshot()
|
||||
}
|
||||
|
||||
pub fn active_turn_position(&self) -> Option<usize> {
|
||||
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<String> {
|
||||
self.state.active_turn_id_if_explicit()
|
||||
}
|
||||
|
||||
pub fn active_turn_start_index(&self) -> Option<usize> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<CurrentTurnThreadItemState>,
|
||||
pub current_reasoning_item: Option<ReasoningAccumulator>,
|
||||
pub open_items: HashMap<String, OpenThreadItemState>,
|
||||
}
|
||||
|
||||
/// 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<ThreadHistoryMutation>,
|
||||
}
|
||||
|
||||
/// One raw append item reduced into before/after thread-history snapshots.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ThreadItemProjectionObservation {
|
||||
before_turns: Vec<Turn>,
|
||||
after_turns: Vec<Turn>,
|
||||
}
|
||||
|
||||
/// 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<Turn> {
|
||||
self.state.turns_snapshot()
|
||||
}
|
||||
|
||||
fn reduce_append(
|
||||
&mut self,
|
||||
persisted_rollout_items: &[RolloutItem],
|
||||
projection_source_events: &[RolloutItem],
|
||||
) -> Vec<ThreadItemProjectionObservation> {
|
||||
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<String, i64>,
|
||||
}
|
||||
|
||||
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<Turn> {
|
||||
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<ThreadHistoryMutation>,
|
||||
) {
|
||||
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<ThreadHistoryMutation>,
|
||||
) {
|
||||
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<ThreadHistoryMutation> {
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -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<ThreadHistoryMutation>) -> 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
|
||||
}
|
||||
@@ -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<String>,
|
||||
turn_order: Vec<String>,
|
||||
summaries: HashMap<String, TurnSummaryState>,
|
||||
}
|
||||
|
||||
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<ThreadHistoryMutation> {
|
||||
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<ThreadHistoryMutation> {
|
||||
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<ThreadHistoryMutation> {
|
||||
TurnSummaryProjectionObserver::observe_append(
|
||||
self,
|
||||
persisted_rollout_items,
|
||||
projection_source_events,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TurnSummaryState {
|
||||
status: TurnStatus,
|
||||
started_at: Option<i64>,
|
||||
completed_at: Option<i64>,
|
||||
duration_ms: Option<i64>,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<ThreadHistoryMutation>) -> Vec<serde_json::Value> {
|
||||
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()
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -594,7 +594,16 @@ impl Session {
|
||||
.await?
|
||||
}
|
||||
};
|
||||
Ok(Some(live_thread))
|
||||
let thread_history_projection_observers: Vec<
|
||||
Box<dyn codex_thread_store::ThreadHistoryProjectionObserver>,
|
||||
> = 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!(
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "thread-store-protocol",
|
||||
crate_name = "codex_thread_store_protocol",
|
||||
)
|
||||
@@ -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 }
|
||||
@@ -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<ThreadHistoryMutation>;
|
||||
}
|
||||
@@ -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::<ThreadHistoryMutation>(value).expect("deserialize mutation"),
|
||||
mutation
|
||||
);
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<dyn ThreadStore>,
|
||||
metadata_sync: Arc<Mutex<ThreadMetadataSync>>,
|
||||
thread_history_projection_observers: Arc<Mutex<Vec<Box<dyn ThreadHistoryProjectionObserver>>>>,
|
||||
}
|
||||
|
||||
/// 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<Box<dyn ThreadHistoryProjectionObserver>>,
|
||||
) -> 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::<Vec<_>>();
|
||||
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<Mutex<Vec<Box<dyn ThreadHistoryProjectionObserver>>>> {
|
||||
Arc::new(Mutex::new(Vec::new()))
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<RolloutItem>,
|
||||
/// Typed derived thread-history mutations committed with the canonical rollout append.
|
||||
#[serde(default)]
|
||||
pub thread_history_mutations: Vec<ThreadHistoryMutation>,
|
||||
}
|
||||
|
||||
/// Parameters for loading persisted history for resume, fork, rollback, and memory jobs.
|
||||
|
||||
Reference in New Issue
Block a user