mirror of
https://github.com/openai/codex.git
synced 2026-11-30 00:10:49 +00:00
codex: keep world state diffing in memory (#29249)
This commit is contained in:
@@ -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<String, bool>,
|
||||
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<String, FileSystemSandboxEntry>,
|
||||
@@ -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<String, NetworkDomainAccess>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum NetworkDomainAccess {
|
||||
Allow,
|
||||
Deny,
|
||||
|
||||
@@ -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<String, EnvironmentState>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
current_date: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
timezone: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
network: Option<NetworkContext>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
filesystem: Option<FileSystemContext>,
|
||||
#[serde(skip)]
|
||||
subagents: Option<String>,
|
||||
}
|
||||
|
||||
@@ -139,8 +132,6 @@ impl EnvironmentsState {
|
||||
}
|
||||
|
||||
impl WorldStateSection for EnvironmentsState {
|
||||
const NAME: &'static str = "environments";
|
||||
|
||||
fn render_diff(&self, previous: &Self) -> Option<ResponseItem> {
|
||||
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<EnvironmentStatus>,
|
||||
#[serde(skip)]
|
||||
shell: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -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::<EnvironmentsState>(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::<ResponseItem>::new(),
|
||||
live_world.render_diff(&loaded_world),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn available(cwd: &str, shell: &str) -> Result<EnvironmentState> {
|
||||
Ok(EnvironmentState {
|
||||
cwd: PathUri::parse(cwd)?,
|
||||
|
||||
@@ -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<Value>;
|
||||
|
||||
fn render_diff(&self, previous: Option<&dyn Any>) -> Option<ResponseItem>;
|
||||
}
|
||||
|
||||
@@ -26,14 +18,6 @@ impl<S: WorldStateSection> ErasedWorldStateSection for S {
|
||||
self
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
S::NAME
|
||||
}
|
||||
|
||||
fn json(&self) -> serde_json::Result<Value> {
|
||||
serde_json::to_value(self)
|
||||
}
|
||||
|
||||
fn render_diff(&self, previous: Option<&dyn Any>) -> Option<ResponseItem> {
|
||||
match previous {
|
||||
Some(previous) => {
|
||||
@@ -50,47 +34,11 @@ impl<S: WorldStateSection> 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<ResponseItem>;
|
||||
}
|
||||
|
||||
type LoadSection = fn(Value) -> serde_json::Result<Box<dyn ErasedWorldStateSection>>;
|
||||
|
||||
struct SectionRegistration {
|
||||
name: &'static str,
|
||||
load: LoadSection,
|
||||
}
|
||||
|
||||
const SECTION_REGISTRY: &[SectionRegistration] = &[
|
||||
SectionRegistration {
|
||||
name: EnvironmentsState::NAME,
|
||||
load: load_section::<EnvironmentsState>,
|
||||
},
|
||||
#[cfg(test)]
|
||||
SectionRegistration {
|
||||
name: tests::AlphaSection::NAME,
|
||||
load: load_section::<tests::AlphaSection>,
|
||||
},
|
||||
#[cfg(test)]
|
||||
SectionRegistration {
|
||||
name: tests::BetaSection::NAME,
|
||||
load: load_section::<tests::BetaSection>,
|
||||
},
|
||||
];
|
||||
|
||||
fn load_section<S: WorldStateSection>(
|
||||
value: Value,
|
||||
) -> serde_json::Result<Box<dyn ErasedWorldStateSection>> {
|
||||
serde_json::from_value::<S>(value)
|
||||
.map(|section| Box::new(section) as Box<dyn ErasedWorldStateSection>)
|
||||
}
|
||||
|
||||
/// 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::<S>(), Box::new(section));
|
||||
}
|
||||
|
||||
pub(crate) fn json_full(&self) -> serde_json::Result<Value> {
|
||||
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<Value> {
|
||||
Ok(json_merge_patch_diff(
|
||||
&previous.json_full()?,
|
||||
&self.json_full()?,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn from_json(json: Value) -> serde_json::Result<Self> {
|
||||
let stored_sections = serde_json::from_value::<BTreeMap<String, 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<ResponseItem> {
|
||||
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;
|
||||
|
||||
@@ -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<ResponseItem> {
|
||||
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<ResponseItem> {
|
||||
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(())
|
||||
}
|
||||
Reference in New Issue
Block a user