From 9fddcaddfdd171d1fdee7286e1430551d11caa10 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Sat, 20 Jun 2026 14:00:25 -0700 Subject: [PATCH] codex: keep world state diffing in memory (#29249) --- .../core/src/context/environment_context.rs | 15 +- .../src/context/world_state/environment.rs | 15 +- .../context/world_state/environment_tests.rs | 61 ------- codex-rs/core/src/context/world_state/mod.rs | 151 +----------------- .../context/world_state/world_state_tests.rs | 90 ----------- 5 files changed, 9 insertions(+), 323 deletions(-) delete mode 100644 codex-rs/core/src/context/world_state/world_state_tests.rs diff --git a/codex-rs/core/src/context/environment_context.rs b/codex-rs/core/src/context/environment_context.rs index 57958921db..6cf6659099 100644 --- a/codex-rs/core/src/context/environment_context.rs +++ b/codex-rs/core/src/context/environment_context.rs @@ -6,26 +6,22 @@ use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSpecialPath; use codex_utils_absolute_path::AbsolutePathBuf; use indexmap::IndexMap; -use serde::Deserialize; -use serde::Serialize; use std::path::PathBuf; -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct FileSystemContext { workspace_roots: IndexMap, permission_profile: FileSystemPermissionProfileContext, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, Clone, PartialEq, Eq)] enum FileSystemPermissionProfileContext { Managed(ManagedFileSystemContext), Disabled, External, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, Clone, PartialEq, Eq)] enum ManagedFileSystemContext { Restricted { entries: IndexMap, @@ -218,13 +214,12 @@ pub(crate) fn push_xml_escaped_text(rendered: &mut String, value: &str) { } } -#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct NetworkContext { domains: IndexMap, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] enum NetworkDomainAccess { Allow, Deny, diff --git a/codex-rs/core/src/context/world_state/environment.rs b/codex-rs/core/src/context/world_state/environment.rs index d5c84b67f0..f79f655704 100644 --- a/codex-rs/core/src/context/world_state/environment.rs +++ b/codex-rs/core/src/context/world_state/environment.rs @@ -10,23 +10,16 @@ use codex_protocol::protocol::TurnContextItem; use codex_protocol::protocol::TurnContextNetworkItem; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; -use serde::Deserialize; -use serde::Serialize; use std::collections::BTreeMap; /// Environment values visible to the model. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[derive(Clone, Debug, Default)] pub(crate) struct EnvironmentsState { environments: BTreeMap, - #[serde(default, skip_serializing_if = "Option::is_none")] current_date: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] timezone: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] network: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] filesystem: Option, - #[serde(skip)] subagents: Option, } @@ -139,8 +132,6 @@ impl EnvironmentsState { } impl WorldStateSection for EnvironmentsState { - const NAME: &'static str = "environments"; - fn render_diff(&self, previous: &Self) -> Option { let turn_context_values_changed = self.current_date != previous.current_date || self.timezone != previous.timezone @@ -304,12 +295,10 @@ fn push_optional_element(rendered: &mut String, name: &str, value: Option<&str>) rendered.push_str(">\n"); } -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug)] struct EnvironmentState { cwd: PathUri, - #[serde(skip)] status: Option, - #[serde(skip)] shell: Option, } diff --git a/codex-rs/core/src/context/world_state/environment_tests.rs b/codex-rs/core/src/context/world_state/environment_tests.rs index ae39d2f42f..708759c56b 100644 --- a/codex-rs/core/src/context/world_state/environment_tests.rs +++ b/codex-rs/core/src/context/world_state/environment_tests.rs @@ -6,7 +6,6 @@ use codex_protocol::models::ContentItem; use codex_protocol::models::PermissionProfile; use codex_protocol::permissions::NetworkSandboxPolicy; use pretty_assertions::assert_eq; -use serde_json::json; #[test] fn renders_full_environment_state() -> Result<()> { @@ -218,66 +217,6 @@ fn removed_legacy_environment_renders_unavailable() -> Result<()> { Ok(()) } -#[test] -fn loaded_environment_state_produces_no_diff_with_live_state() -> Result<()> { - let live_state = EnvironmentsState { - environments: [ - ("laptop".to_string(), available("file:///repo", "zsh")?), - ("devbox".to_string(), starting("file:///workspace")?), - ] - .into_iter() - .collect(), - current_date: Some("2026-06-20".to_string()), - timezone: Some("America/Los_Angeles".to_string()), - network: Some(NetworkContext::new( - vec!["api.example.com".to_string()], - vec!["blocked.example.com".to_string()], - )), - filesystem: Some(FileSystemContext::from_permission_profile( - &PermissionProfile::Disabled, - &[], - )), - subagents: Some("task_1: running".to_string()), - }; - - let stored = serde_json::to_value(&live_state)?; - assert_eq!( - json!({ - "environments": { - "devbox": { - "cwd": "file:///workspace", - }, - "laptop": { - "cwd": "file:///repo", - }, - }, - "current_date": "2026-06-20", - "timezone": "America/Los_Angeles", - "network": { - "domains": { - "api.example.com": "allow", - "blocked.example.com": "deny", - }, - }, - "filesystem": { - "workspace_roots": {}, - "permission_profile": "disabled", - }, - }), - stored, - ); - let loaded_state = serde_json::from_value::(stored)?; - let mut live_world = WorldState::default(); - live_world.add_section(live_state); - let mut loaded_world = WorldState::default(); - loaded_world.add_section(loaded_state); - assert_eq!( - Vec::::new(), - live_world.render_diff(&loaded_world), - ); - Ok(()) -} - fn available(cwd: &str, shell: &str) -> Result { Ok(EnvironmentState { cwd: PathUri::parse(cwd)?, diff --git a/codex-rs/core/src/context/world_state/mod.rs b/codex-rs/core/src/context/world_state/mod.rs index 8ca0bfbf03..17d94a4369 100644 --- a/codex-rs/core/src/context/world_state/mod.rs +++ b/codex-rs/core/src/context/world_state/mod.rs @@ -2,22 +2,14 @@ mod environment; use codex_protocol::models::ResponseItem; use indexmap::IndexMap; -use serde::Serialize; -use serde::de::DeserializeOwned; -use serde_json::Value; use std::any::Any; use std::any::TypeId; -use std::collections::BTreeMap; pub(crate) use environment::EnvironmentsState; trait ErasedWorldStateSection: Send + Sync { fn as_any(&self) -> &dyn Any; - fn name(&self) -> &'static str; - - fn json(&self) -> serde_json::Result; - fn render_diff(&self, previous: Option<&dyn Any>) -> Option; } @@ -26,14 +18,6 @@ impl ErasedWorldStateSection for S { self } - fn name(&self) -> &'static str { - S::NAME - } - - fn json(&self) -> serde_json::Result { - serde_json::to_value(self) - } - fn render_diff(&self, previous: Option<&dyn Any>) -> Option { match previous { Some(previous) => { @@ -50,47 +34,11 @@ impl ErasedWorldStateSection for S { /// A typed portion of the state visible to the model. /// /// Implementations own how their current state is rendered relative to an -/// earlier value of the same section type. `NAME` is the stable key used in -/// persisted JSON and must be registered in `SECTION_REGISTRY`. -pub(crate) trait WorldStateSection: - Any + Default + DeserializeOwned + Serialize + Send + Sync -{ - const NAME: &'static str; - +/// earlier value of the same section type. +pub(crate) trait WorldStateSection: Any + Default + Send + Sync { fn render_diff(&self, previous: &Self) -> Option; } -type LoadSection = fn(Value) -> serde_json::Result>; - -struct SectionRegistration { - name: &'static str, - load: LoadSection, -} - -const SECTION_REGISTRY: &[SectionRegistration] = &[ - SectionRegistration { - name: EnvironmentsState::NAME, - load: load_section::, - }, - #[cfg(test)] - SectionRegistration { - name: tests::AlphaSection::NAME, - load: load_section::, - }, - #[cfg(test)] - SectionRegistration { - name: tests::BetaSection::NAME, - load: load_section::, - }, -]; - -fn load_section( - value: Value, -) -> serde_json::Result> { - serde_json::from_value::(value) - .map(|section| Box::new(section) as Box) -} - /// A snapshot of the model-visible world with one section per concrete type. #[derive(Default)] pub(crate) struct WorldState { @@ -102,48 +50,6 @@ impl WorldState { self.sections.insert(TypeId::of::(), Box::new(section)); } - pub(crate) fn json_full(&self) -> serde_json::Result { - let mut sections = BTreeMap::new(); - for section in self.sections.values() { - sections.insert(section.name(), section.json()?); - } - serde_json::to_value(sections) - } - - /// Returns the JSON Merge Patch that transforms `previous` into this state. - pub(crate) fn json_diff(&self, previous: &Self) -> serde_json::Result { - Ok(json_merge_patch_diff( - &previous.json_full()?, - &self.json_full()?, - )) - } - - pub(crate) fn from_json(json: Value) -> serde_json::Result { - let stored_sections = serde_json::from_value::>(json)?; - let mut world_state = Self::default(); - for (name, value) in stored_sections { - let Some(registration) = SECTION_REGISTRY - .iter() - .find(|registration| registration.name == name) - else { - continue; - }; - let section = (registration.load)(value)?; - world_state - .sections - .insert(section.as_any().type_id(), section); - } - Ok(world_state) - } - - /// Applies a persisted diff, discarding values that are not represented in JSON. - pub(crate) fn apply_json_diff(&mut self, diff: &Value) -> serde_json::Result<()> { - let mut json = self.json_full()?; - apply_json_merge_patch(&mut json, diff); - *self = Self::from_json(json)?; - Ok(()) - } - pub(crate) fn render_full(&self) -> Vec { self.render_diff(&Self::default()) } @@ -161,56 +67,3 @@ impl WorldState { .collect() } } - -fn json_merge_patch_diff(previous: &Value, current: &Value) -> Value { - if previous == current { - return Value::Object(serde_json::Map::new()); - } - - let (Value::Object(previous), Value::Object(current)) = (previous, current) else { - return current.clone(); - }; - - let mut diff = serde_json::Map::new(); - for key in previous.keys() { - if !current.contains_key(key) { - diff.insert(key.clone(), Value::Null); - } - } - for (key, current) in current { - match previous.get(key) { - Some(previous) if previous == current => {} - Some(previous) => { - diff.insert(key.clone(), json_merge_patch_diff(previous, current)); - } - None => { - diff.insert(key.clone(), current.clone()); - } - } - } - Value::Object(diff) -} - -fn apply_json_merge_patch(target: &mut Value, patch: &Value) { - let Value::Object(patch) = patch else { - *target = patch.clone(); - return; - }; - if !target.is_object() { - *target = Value::Object(serde_json::Map::new()); - } - let Value::Object(target) = target else { - unreachable!("target was initialized as an object"); - }; - for (key, value) in patch { - if value.is_null() { - target.remove(key); - } else { - apply_json_merge_patch(target.entry(key.clone()).or_insert(Value::Null), value); - } - } -} - -#[cfg(test)] -#[path = "world_state_tests.rs"] -mod tests; diff --git a/codex-rs/core/src/context/world_state/world_state_tests.rs b/codex-rs/core/src/context/world_state/world_state_tests.rs deleted file mode 100644 index 2fb2b6b533..0000000000 --- a/codex-rs/core/src/context/world_state/world_state_tests.rs +++ /dev/null @@ -1,90 +0,0 @@ -use super::*; -use anyhow::Result; -use pretty_assertions::assert_eq; -use serde::Deserialize; -use serde::Serialize; -use serde_json::json; - -#[derive(Debug, Default, Deserialize, Eq, PartialEq, Serialize)] -pub(super) struct AlphaSection { - value: String, -} - -impl AlphaSection { - fn new(value: &str) -> Self { - Self { - value: value.to_string(), - } - } -} - -impl WorldStateSection for AlphaSection { - const NAME: &'static str = "alpha"; - - fn render_diff(&self, _previous: &Self) -> Option { - None - } -} - -#[derive(Debug, Default, Deserialize, Eq, PartialEq, Serialize)] -pub(super) struct BetaSection { - value: String, -} - -impl BetaSection { - fn new(value: &str) -> Self { - Self { - value: value.to_string(), - } - } -} - -impl WorldStateSection for BetaSection { - const NAME: &'static str = "beta"; - - fn render_diff(&self, _previous: &Self) -> Option { - None - } -} - -#[test] -fn full_json_reloads_registered_sections() -> Result<()> { - let mut state = WorldState::default(); - state.add_section(BetaSection::new("two")); - state.add_section(AlphaSection::new("one")); - - let full = state.json_full()?; - assert_eq!( - json!({ - "alpha": { "value": "one" }, - "beta": { "value": "two" }, - }), - full, - ); - - let loaded = WorldState::from_json(full.clone())?; - assert_eq!(full, loaded.json_full()?); - Ok(()) -} - -#[test] -fn json_diff_reconstructs_current_state() -> Result<()> { - let mut previous = WorldState::default(); - previous.add_section(AlphaSection::new("old")); - previous.add_section(BetaSection::new("removed")); - let mut current = WorldState::default(); - current.add_section(AlphaSection::new("new")); - - let diff = current.json_diff(&previous)?; - assert_eq!( - json!({ - "alpha": { "value": "new" }, - "beta": null, - }), - diff, - ); - - previous.apply_json_diff(&diff)?; - assert_eq!(current.json_full()?, previous.json_full()?); - Ok(()) -}