From e1e967cd46c2321cd032ae9728ade0b4ae6d8ece Mon Sep 17 00:00:00 2001 From: "Adam Perry @ OpenAI" Date: Tue, 1 Dec 2026 23:32:03 +0000 Subject: [PATCH] Add session-scoped aliases for registered environment IDs (#65140) ## What changed Pair each registered executor ID with a model-facing alias assigned on first use by the session's model ID store. Turn environment snapshots can resolve these pairs in selection order, including for executors that are still starting or have failed. Environment context snapshots and rendering continue to use registered IDs. ## Testing Cover alias assignment in selection order, stability across readiness updates, and reuse of the same ID pair after reopening the SQLite store. GitOrigin-RevId: e5fa6e5549ebb12fcf651e5bf7413402fb4db1b3 --- codex-rs/Cargo.lock | 15 ++ codex-rs/Cargo.toml | 2 + codex-rs/core/Cargo.toml | 1 + .../src/context/world_state/environment.rs | 156 +++++++++--------- .../world_state/environment_render_tests.rs | 21 ++- .../context/world_state/environment_tests.rs | 83 +++++----- codex-rs/core/src/environment_selection.rs | 55 ++++-- .../core/src/environment_selection_tests.rs | 23 +++ codex-rs/environment-id/BUILD.bazel | 6 + codex-rs/environment-id/Cargo.toml | 23 +++ .../src/environment_id_tests.rs | 31 ++++ codex-rs/environment-id/src/lib.rs | 37 +++++ codex-rs/state/src/lib.rs | 1 + codex-rs/state/src/runtime/model_ids.rs | 30 ++++ codex-rs/state/src/runtime/model_ids_tests.rs | 11 +- .../utils/model-facing-id/src/bindings.rs | 15 +- .../utils/model-facing-id/src/environment.rs | 21 +-- 17 files changed, 373 insertions(+), 158 deletions(-) create mode 100644 codex-rs/environment-id/BUILD.bazel create mode 100644 codex-rs/environment-id/Cargo.toml create mode 100644 codex-rs/environment-id/src/environment_id_tests.rs create mode 100644 codex-rs/environment-id/src/lib.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index bcad9112af..4ff6fc250e 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3117,6 +3117,7 @@ dependencies = [ "codex-core-plugins", "codex-diagnostics", "codex-direct-tool-timing", + "codex-environment-id", "codex-exec-server", "codex-exec-server-test-support", "codex-execpolicy", @@ -3367,6 +3368,20 @@ dependencies = [ "tokio-util", ] +[[package]] +name = "codex-environment-id" +version = "0.0.0" +dependencies = [ + "anyhow", + "codex-protocol", + "codex-state", + "codex-utils-absolute-path", + "codex-utils-model-facing-id", + "pretty_assertions", + "tempfile", + "tokio", +] + [[package]] name = "codex-exec" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 70b89bb7b2..013f64db9e 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -58,6 +58,7 @@ members = [ "http-client", "http-headers-helper", "secrets", + "environment-id", "exec", "file-system", "exec-server-protocol", @@ -244,6 +245,7 @@ codex-core-plugin-common = { path = "core-plugin-common" } codex-core-plugins = { path = "core-plugins" } codex-diagnostics = { path = "diagnostics" } codex-direct-tool-timing = { path = "direct-tool-timing" } +codex-environment-id = { path = "environment-id" } codex-exec = { path = "exec" } codex-file-system = { path = "file-system" } codex-exec-server-protocol = { path = "exec-server-protocol" } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 90937d2b8f..9025eb5086 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -36,6 +36,7 @@ codex-config = { workspace = true } codex-core-plugins = { workspace = true } codex-diagnostics = { workspace = true } codex-direct-tool-timing = { workspace = true } +codex-environment-id = { workspace = true } codex-exec-server = { workspace = true } codex-extension-api = { workspace = true } codex-extension-items = { workspace = true } diff --git a/codex-rs/core/src/context/world_state/environment.rs b/codex-rs/core/src/context/world_state/environment.rs index 6a263ee8bf..07cd4525d8 100644 --- a/codex-rs/core/src/context/world_state/environment.rs +++ b/codex-rs/core/src/context/world_state/environment.rs @@ -13,6 +13,7 @@ use crate::environment_selection::TurnEnvironmentSnapshot; use crate::environment_selection::TurnEnvironmentState; use crate::session::turn_context::TurnContext; use crate::shell::ShellType; +use codex_environment_id::RegisteredEnvironmentId; use codex_features::Feature; use codex_protocol::AgentPath; use codex_protocol::models::ContentItem; @@ -38,7 +39,7 @@ static POWERSHELL_VERSIONS: LazyLock>>> = /// Environment values visible to the model. #[derive(Clone, Debug, Default)] pub(crate) struct EnvironmentsState { - environments: BTreeMap, + environments: BTreeMap, // Keep each environment named and its rules grouped together, even when there is only one. per_environment: bool, shell_version: Option, @@ -82,7 +83,14 @@ impl EnvironmentsState { None }; Self { - environments: environment_states(environments, per_environment, filesystem_format), + environments: environments + .registered_ids() + .zip(environment_states( + environments, + per_environment, + filesystem_format, + )) + .collect(), per_environment, shell_version, current_date_is_utc: current_date.is_some() @@ -135,7 +143,10 @@ impl EnvironmentsState { .environments .iter() .map(|(id, environment)| { - (id.clone(), EnvironmentUpdate::Current(environment.clone())) + ( + id.to_string(), + EnvironmentUpdate::Current(environment.clone()), + ) }) .collect(), legacy_single: !self.per_environment && is_legacy_single(&self.environments), @@ -220,14 +231,19 @@ impl WorldStateSection for EnvironmentsState { || !environment.has_same_diff_value(previous) }) }) - .map(|(id, environment)| (id.clone(), EnvironmentUpdate::Current(environment.clone()))) + .map(|(id, environment)| { + ( + id.to_string(), + EnvironmentUpdate::Current(environment.clone()), + ) + }) .collect::>(); updates.extend( previous .environments .keys() .filter(|id| !self.environments.contains_key(*id)) - .map(|id| (id.clone(), EnvironmentUpdate::Unavailable)), + .map(|id| (id.to_string(), EnvironmentUpdate::Unavailable)), ); let legacy_single = !self.per_environment && is_legacy_single(&self.environments) @@ -473,7 +489,7 @@ struct EnvironmentState { #[derive(Default, Deserialize, Serialize)] pub(crate) struct EnvironmentsSnapshot { - environments: BTreeMap, + environments: BTreeMap, #[serde(default, skip_serializing_if = "std::ops::Not::not")] per_environment: bool, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -567,88 +583,76 @@ async fn powershell_version(shell_path: &Path) -> Option { version } +/// Project every selection in order, so either set of IDs can be paired with the result. fn environment_states( snapshot: &TurnEnvironmentSnapshot, per_environment: bool, filesystem_format: FileSystemFormat, -) -> BTreeMap { - let mut environments = snapshot - .turn_environments() - .enumerate() - .map(|(index, environment)| { - ( - environment.selection.environment_id.clone(), - EnvironmentState { - cwd: environment.cwd().clone(), - status: EnvironmentStatus::Available, - error: None, - shell: environment - .shell - .as_ref() - .map(|shell| shell.name().to_string()), - is_primary: index == 0, - // These are this captured environment's rules, not the primary's defaults. - filesystem: per_environment.then(|| { - FileSystemContext::from_permission_profile( - environment.permission_profile(), - environment.workspace_roots(), - filesystem_format, - ) - .render() - }), - network_access: per_environment.then(|| { - if environment - .permission_profile() - .network_sandbox_policy() - .is_enabled() - { - NetworkAccess::Enabled - } else { - NetworkAccess::Restricted - } - }), - }, - ) - }) - .collect::>(); - for environment in snapshot.starting() { - environments - .entry(environment.selection.environment_id.clone()) - .or_insert_with(|| EnvironmentState { - cwd: environment.selection.cwd.clone(), - status: EnvironmentStatus::Starting, +) -> impl Iterator + '_ { + let mut error_budget = ErrorContextBudget::default(); + let mut first_ready = true; + snapshot.environments.iter().map(move |state| match state { + TurnEnvironmentState::Ready(environment) => { + let is_primary = first_ready; + first_ready = false; + EnvironmentState { + cwd: environment.cwd().clone(), + status: EnvironmentStatus::Available, error: None, + shell: environment + .shell + .as_ref() + .map(|shell| shell.name().to_string()), + is_primary, + // These are this captured environment's rules, not the primary's defaults. + filesystem: per_environment.then(|| { + FileSystemContext::from_permission_profile( + environment.permission_profile(), + environment.workspace_roots(), + filesystem_format, + ) + .render() + }), + network_access: per_environment.then(|| { + if environment + .permission_profile() + .network_sandbox_policy() + .is_enabled() + { + NetworkAccess::Enabled + } else { + NetworkAccess::Restricted + } + }), + } + } + TurnEnvironmentState::Starting(environment) => EnvironmentState { + cwd: environment.selection.cwd.clone(), + status: EnvironmentStatus::Starting, + error: None, + shell: None, + is_primary: false, + filesystem: None, + network_access: None, + }, + TurnEnvironmentState::Failed { + selection, error, .. + } => { + let detail = error_budget.take(error); + EnvironmentState { + cwd: selection.cwd.clone(), + status: EnvironmentStatus::Failed, shell: None, + error: (!detail.is_empty()).then(|| detail.to_owned()), is_primary: false, filesystem: None, network_access: None, - }); - } - let mut error_budget = ErrorContextBudget::default(); - for environment in &snapshot.environments { - if let TurnEnvironmentState::Failed { - selection, error, .. - } = environment - { - let detail = error_budget.take(error); - environments.insert( - selection.environment_id.clone(), - EnvironmentState { - cwd: selection.cwd.clone(), - status: EnvironmentStatus::Failed, - shell: None, - error: (!detail.is_empty()).then(|| detail.to_owned()), - is_primary: false, - filesystem: None, - network_access: None, - }, - ); + } } - } - environments + }) } -fn is_legacy_single(environments: &BTreeMap) -> bool { +fn is_legacy_single(environments: &BTreeMap) -> bool { environments.len() == 1 && environments .values() diff --git a/codex-rs/core/src/context/world_state/environment_render_tests.rs b/codex-rs/core/src/context/world_state/environment_render_tests.rs index 3d9fcb46e6..bb7b39dc93 100644 --- a/codex-rs/core/src/context/world_state/environment_render_tests.rs +++ b/codex-rs/core/src/context/world_state/environment_render_tests.rs @@ -30,9 +30,13 @@ fn test_abs_path(unix_path: &str) -> AbsolutePathBuf { test_path_buf(unix_path).abs() } -fn environment(id: &str, cwd: PathUri, shell: impl Into) -> (String, EnvironmentState) { +fn environment( + id: &str, + cwd: PathUri, + shell: impl Into, +) -> (RegisteredEnvironmentId, EnvironmentState) { ( - id.to_string(), + RegisteredEnvironmentId::new(id), EnvironmentState { cwd, status: EnvironmentStatus::Available, @@ -46,7 +50,7 @@ fn environment(id: &str, cwd: PathUri, shell: impl Into) -> (String, Env } fn environment_state( - environments: impl IntoIterator, + environments: impl IntoIterator, current_date: Option, timezone: Option, network: Option, @@ -115,7 +119,10 @@ fn serialize_environment_context_with_foreign_windows_cwd() { /*subagents*/ None, ); context.per_environment = true; - let environment = context.environments.get_mut("remote").unwrap(); + let environment = context + .environments + .get_mut(&RegisteredEnvironmentId::new("remote")) + .unwrap(); environment.network_access = Some(NetworkAccess::Enabled); environment.filesystem = Some( FileSystemContext::from_permission_profile( @@ -473,7 +480,11 @@ fn shell_version_diff_restates_shell_from_legacy_snapshot() { .0 .unwrap(); previous.shell_version = None; - previous.environments.get_mut("local").expect("local").shell = None; + previous + .environments + .get_mut(&RegisteredEnvironmentId::new("local")) + .expect("local") + .shell = None; let rendered = current .render_fragment_diff(PreviousSectionState::Known(&previous)) .1 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 5e6a93dcd8..5657b0b4a0 100644 --- a/codex-rs/core/src/context/world_state/environment_tests.rs +++ b/codex-rs/core/src/context/world_state/environment_tests.rs @@ -16,11 +16,12 @@ fn snapshots() -> Result<()> { use PreviousSectionState::Known; use PreviousSectionState::Unknown; + let registered = RegisteredEnvironmentId::new; let full = EnvironmentsState { environments: [ - ("laptop".to_string(), primary("file:///repo", "zsh")?), + (registered("laptop"), primary("file:///repo", "zsh")?), ( - "devbox".to_string(), + registered("devbox"), available("file:///workspace", "bash")?, ), ] @@ -30,9 +31,9 @@ fn snapshots() -> Result<()> { }; let before_environment_changes = EnvironmentsState { environments: [ - ("laptop".to_string(), primary("file:///repo", "bash")?), - ("devbox".to_string(), starting("file:///workspace")?), - ("old".to_string(), available("file:///old", "sh")?), + (registered("laptop"), primary("file:///repo", "bash")?), + (registered("devbox"), starting("file:///workspace")?), + (registered("old"), available("file:///old", "sh")?), ] .into_iter() .collect(), @@ -40,12 +41,12 @@ fn snapshots() -> Result<()> { }; let after_environment_changes = EnvironmentsState { environments: [ - ("laptop".to_string(), primary("file:///repo", "zsh")?), + (registered("laptop"), primary("file:///repo", "zsh")?), ( - "devbox".to_string(), + registered("devbox"), available("file:///workspace", "powershell")?, ), - ("remote".to_string(), starting("file:///remote")?), + (registered("remote"), starting("file:///remote")?), ] .into_iter() .collect(), @@ -53,7 +54,7 @@ fn snapshots() -> Result<()> { }; let environments = EnvironmentsState { environments: [( - LOCAL_ENVIRONMENT_ID.to_string(), + registered(LOCAL_ENVIRONMENT_ID), available("file:///repo", "zsh")?, )] .into_iter() @@ -92,7 +93,7 @@ fn snapshots() -> Result<()> { }; let foreign_windows = EnvironmentsState { environments: [( - "remote".to_string(), + registered("remote"), available("file:///C:/windows", "powershell")?, )] .into_iter() @@ -106,7 +107,7 @@ fn snapshots() -> Result<()> { }; let unknown_shell = EnvironmentsState { environments: [( - LOCAL_ENVIRONMENT_ID.to_string(), + registered(LOCAL_ENVIRONMENT_ID), EnvironmentState { cwd: PathUri::parse("file:///repo")?, status: EnvironmentStatus::Available, @@ -123,7 +124,7 @@ fn snapshots() -> Result<()> { }; let known_shell = EnvironmentsState { environments: [( - LOCAL_ENVIRONMENT_ID.to_string(), + registered(LOCAL_ENVIRONMENT_ID), available("file:///repo", "zsh")?, )] .into_iter() @@ -132,7 +133,7 @@ fn snapshots() -> Result<()> { }; let legacy_environment = EnvironmentsState { environments: [( - LOCAL_ENVIRONMENT_ID.to_string(), + registered(LOCAL_ENVIRONMENT_ID), available("file:///repo", "bash")?, )] .into_iter() @@ -162,10 +163,11 @@ fn snapshots() -> Result<()> { #[test] fn changing_primary_environment_updates_model_context_and_persisted_state() -> Result<()> { + let registered = RegisteredEnvironmentId::new; let before = EnvironmentsState { environments: [ - ("local".to_string(), primary("file:///local", "bash")?), - ("remote".to_string(), available("file:///remote", "zsh")?), + (registered("local"), primary("file:///local", "bash")?), + (registered("remote"), available("file:///remote", "zsh")?), ] .into_iter() .collect(), @@ -173,8 +175,8 @@ fn changing_primary_environment_updates_model_context_and_persisted_state() -> R }; let after = EnvironmentsState { environments: [ - ("local".to_string(), available("file:///local", "bash")?), - ("remote".to_string(), primary("file:///remote", "zsh")?), + (registered("local"), available("file:///local", "bash")?), + (registered("remote"), primary("file:///remote", "zsh")?), ] .into_iter() .collect(), @@ -223,17 +225,23 @@ fn changing_primary_environment_updates_model_context_and_persisted_state() -> R Ok(()) } -#[test] -fn legacy_single_environment_snapshot_preserves_environment_and_refreshes_date() -> Result<()> { +#[test_case::test_case("local")] +#[test_case::test_case("env007"; "registered name resembles an alias")] +fn legacy_single_environment_snapshot_preserves_environment_and_refreshes_date( + registered: &str, +) -> Result<()> { let environment = EnvironmentsState { - environments: [("local".to_string(), primary("file:///repo", "bash")?)] - .into_iter() - .collect(), + environments: [( + RegisteredEnvironmentId::new(registered), + primary("file:///repo", "bash")?, + )] + .into_iter() + .collect(), ..Default::default() }; let mut legacy_value = json!({ "environments": { - "local": { + (registered): { "cwd": PathUri::parse("file:///repo")?.inferred_native_path_string(), "status": "available", "shell": "bash", @@ -254,12 +262,8 @@ fn legacy_single_environment_snapshot_preserves_environment_and_refreshes_date() .render_fragment_diff(PreviousSectionState::Absent) .0 .unwrap() - )?["environments"]["local"], - json!({ - "cwd": PathUri::parse("file:///repo")?.inferred_native_path_string(), - "status": "available", - "shell": "bash", - }) + )?["environments"], + legacy_value["environments"] ); let environment = EnvironmentsState { @@ -300,8 +304,9 @@ fn legacy_single_environment_snapshot_preserves_environment_and_refreshes_date() #[test] fn crossing_single_environment_boundary_restates_current_environments() -> Result<()> { + let registered = RegisteredEnvironmentId::new; let single = EnvironmentsState { - environments: [("local".to_string(), primary("file:///local", "bash")?)] + environments: [(registered("local"), primary("file:///local", "bash")?)] .into_iter() .collect(), ..Default::default() @@ -313,14 +318,14 @@ fn crossing_single_environment_boundary_restates_current_environments() -> Resul let multiple = EnvironmentsState { environments: [ ( - "local".to_string(), + registered("local"), EnvironmentState { is_primary: local_is_primary, ..available("file:///local", "bash")? }, ), ( - "remote".to_string(), + registered("remote"), EnvironmentState { is_primary: remote_is_primary, ..available("file:///remote", "zsh")? @@ -407,7 +412,7 @@ fn starting(cwd: &str) -> Result { fn failure_context_is_escaped_incremental_and_cleared_on_recovery() -> Result<()> { let failed = EnvironmentsState { environments: [( - "remote".to_string(), + RegisteredEnvironmentId::new("remote"), EnvironmentState { cwd: PathUri::parse("file:///workspace")?, status: EnvironmentStatus::Failed, @@ -445,7 +450,7 @@ fn failure_context_is_escaped_incremental_and_cleared_on_recovery() -> Result<() ); let recovered = EnvironmentsState { environments: [( - "remote".to_string(), + RegisteredEnvironmentId::new("remote"), available("file:///workspace", "bash")?, )] .into_iter() @@ -488,15 +493,13 @@ fn failure_context_limits_total_detail_bytes_at_utf8_boundaries() { }) .collect(), }; - let states = environment_states( + let states: Vec<_> = environment_states( &snapshot, /*per_environment*/ false, FileSystemFormat::Full, - ); - let details: Vec<_> = states - .values() - .map(|state| state.error.as_deref()) - .collect(); + ) + .collect(); + let details: Vec<_> = states.iter().map(|state| state.error.as_deref()).collect(); let truncated = "界".repeat(85); assert_eq!( details, diff --git a/codex-rs/core/src/environment_selection.rs b/codex-rs/core/src/environment_selection.rs index 5059bd4132..7192d4a7ba 100644 --- a/codex-rs/core/src/environment_selection.rs +++ b/codex-rs/core/src/environment_selection.rs @@ -8,6 +8,8 @@ use std::sync::PoisonError; use async_channel::Receiver; use async_channel::Sender; +use codex_environment_id::EnvironmentIdPair; +use codex_environment_id::RegisteredEnvironmentId; use codex_exec_server::Environment; use codex_exec_server::EnvironmentInfo; use codex_exec_server::EnvironmentManager; @@ -26,6 +28,7 @@ use codex_protocol::protocol::Event; use codex_protocol::protocol::TurnEnvironmentRequest; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_skills_extension::EnvironmentSkillRequirements; +use codex_state::SessionModelIdMapping; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use futures::FutureExt; @@ -1251,6 +1254,14 @@ pub(crate) enum TurnEnvironmentState { } impl TurnEnvironmentState { + fn selection(&self) -> &TurnEnvironmentSelection { + match self { + Self::Ready(environment) => &environment.selection, + Self::Starting(environment) => &environment.selection, + Self::Failed { selection, .. } => selection, + } + } + fn from_resolution( starting: StartingTurnEnvironment, resolved: Option, @@ -1308,16 +1319,34 @@ pub struct TurnEnvironmentSnapshot { } impl TurnEnvironmentSnapshot { + pub(crate) fn registered_ids(&self) -> impl Iterator + '_ { + self.environments + .iter() + .map(|state| RegisteredEnvironmentId::new(&state.selection().environment_id)) + } + + /// Resolve aliases in captured selection order, including starting and failed executors. + pub async fn environment_ids( + &self, + mapping: &SessionModelIdMapping, + ) -> CodexResult> { + let mut ids = Vec::with_capacity(self.environments.len()); + for registered in self.registered_ids() { + let id = mapping.get_or_assign(registered).await.map_err(|error| { + CodexErr::Fatal(format!("failed to assign environment ID: {error:#}")) + })?; + ids.push(id); + } + Ok(ids) + } + /// Keeps the original root order for child threads and saved history. pub(crate) fn selected_capability_roots(&self) -> Vec { - EnvironmentCapabilityRoots::collect(self.environments.iter().map(|environment| { - let selection = match environment { - TurnEnvironmentState::Ready(environment) => &environment.selection, - TurnEnvironmentState::Starting(environment) => &environment.selection, - TurnEnvironmentState::Failed { selection, .. } => selection, - }; - &selection.selected_capability_roots - })) + EnvironmentCapabilityRoots::collect( + self.environments + .iter() + .map(|environment| &environment.selection().selected_capability_roots), + ) } pub(crate) fn has_full_access( @@ -1412,13 +1441,9 @@ impl TurnEnvironmentSnapshot { /// Returns the first selection's executor paths, even when setup is not ready yet. pub(crate) fn primary_workspace_root_uris(&self) -> &[PathUri] { - let selection = match self.environments.first() { - Some(TurnEnvironmentState::Ready(environment)) => &environment.selection, - Some(TurnEnvironmentState::Starting(environment)) => &environment.selection, - Some(TurnEnvironmentState::Failed { selection, .. }) => selection, - None => return &[], - }; - &selection.workspace_roots + self.environments + .first() + .map_or(&[], |state| &state.selection().workspace_roots) } /// Returns the primary environment's resolved permissions, or the provided fallback. diff --git a/codex-rs/core/src/environment_selection_tests.rs b/codex-rs/core/src/environment_selection_tests.rs index ae0a6ed779..9e33b98705 100644 --- a/codex-rs/core/src/environment_selection_tests.rs +++ b/codex-rs/core/src/environment_selection_tests.rs @@ -20,6 +20,7 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::TurnEnvironmentRequest; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::sandbox::SandboxType; +use codex_state::SessionModelIdMapping; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; use futures::SinkExt; @@ -551,6 +552,10 @@ async fn snapshot_refreshes_readiness_in_selection_order( /*non_blocking_snapshots*/ true, /*executor_discovery*/ None, ); + let session = codex_protocol::SessionId::new(); + let store: Arc = + Arc::new(codex_state::MemoryModelIdStore::default()); + let mapping = SessionModelIdMapping::new(session, Ok(Arc::clone(&store))); turn_environments.update_selections(std::slice::from_ref(&local)); let resolution = turn_environments.state.lock().unwrap().environments[0] .resolution @@ -558,6 +563,23 @@ async fn snapshot_refreshes_readiness_in_selection_order( resolution.await.expect("local environment should resolve"); turn_environments.update_selections(&[remote.clone(), local.clone()]); let initial = turn_environments.snapshot().await; + let ids = initial.environment_ids(&mapping).await.unwrap(); + assert_eq!( + store.snapshot(session).await.unwrap()[0].keys, + [ + serde_json::to_string(&remote.environment_id).unwrap(), + serde_json::to_string(&local.environment_id).unwrap() + ], + ); + assert_eq!( + ids.iter() + .map(|id| id.registered().as_str()) + .collect::>(), + [ + remote.environment_id.as_str(), + local.environment_id.as_str() + ] + ); assert_eq!( initial.primary().expect("local environment").config(), &EnvironmentConfig { @@ -572,6 +594,7 @@ async fn snapshot_refreshes_readiness_in_selection_order( turn_environments.set_active_thread_defaults(expected_config.clone()); let starting = turn_environments.snapshot().await; + assert_eq!(starting.environment_ids(&mapping).await.unwrap(), ids); let resolved_remote = TurnEnvironmentSelection { config: EnvironmentConfigState::Ready(expected_config.clone()), ..remote.clone() diff --git a/codex-rs/environment-id/BUILD.bazel b/codex-rs/environment-id/BUILD.bazel new file mode 100644 index 0000000000..9074a0d0e9 --- /dev/null +++ b/codex-rs/environment-id/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "environment-id", + crate_name = "codex_environment_id", +) diff --git a/codex-rs/environment-id/Cargo.toml b/codex-rs/environment-id/Cargo.toml new file mode 100644 index 0000000000..465573fc75 --- /dev/null +++ b/codex-rs/environment-id/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "codex-environment-id" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +doctest = false + +[lints] +workspace = true + +[dependencies] +codex-utils-model-facing-id.workspace = true + +[dev-dependencies] +anyhow.workspace = true +codex-protocol.workspace = true +codex-state.workspace = true +codex-utils-absolute-path.workspace = true +pretty_assertions.workspace = true +tempfile.workspace = true +tokio = { workspace = true, features = ["macros", "rt"] } diff --git a/codex-rs/environment-id/src/environment_id_tests.rs b/codex-rs/environment-id/src/environment_id_tests.rs new file mode 100644 index 0000000000..0f6c1a6acd --- /dev/null +++ b/codex-rs/environment-id/src/environment_id_tests.rs @@ -0,0 +1,31 @@ +#![cfg(test)] + +use super::*; +use anyhow::Result; +use codex_protocol::SessionId; +use codex_state::SessionModelIdMapping; +use codex_state::SqliteConfig; +use codex_state::StateRuntime; +use codex_utils_absolute_path::test_support::PathExt; +use pretty_assertions::assert_eq; + +#[tokio::test] +async fn session_resolves_the_same_environment_pair_after_restart() -> Result<()> { + let home = tempfile::tempdir()?; + let config = SqliteConfig::new_for_testing(home.path().abs()); + let session = SessionId::new(); + let registered = RegisteredEnvironmentId::new("remote"); + let store = StateRuntime::init(config.clone(), "test".into()).await?; + let ids = SessionModelIdMapping::new(session, Ok(store)); + let id: EnvironmentIdPair = ids.get_or_assign(registered.clone()).await?; + assert_eq!(id.registered(), ®istered); + drop(ids); + + let reopened = StateRuntime::init(config, "test".into()).await?; + let ids = SessionModelIdMapping::new(session, Ok(reopened)); + assert_eq!( + ids.get_or_assign::(registered).await?, + id + ); + Ok(()) +} diff --git a/codex-rs/environment-id/src/lib.rs b/codex-rs/environment-id/src/lib.rs new file mode 100644 index 0000000000..e80a6308eb --- /dev/null +++ b/codex-rs/environment-id/src/lib.rs @@ -0,0 +1,37 @@ +//! Pairs each registered executor ID with the alias assigned by its session's store. + +use codex_utils_model_facing_id::ModelIdKind; + +pub use codex_utils_model_facing_id::ModelEnvironmentId; +pub use codex_utils_model_facing_id::RegisteredEnvironmentId; + +/// An executor's routing ID and its model-facing ID within one session. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct EnvironmentIdPair { + registered: RegisteredEnvironmentId, + model: ModelEnvironmentId, +} + +impl EnvironmentIdPair { + pub fn registered(&self) -> &RegisteredEnvironmentId { + &self.registered + } + + pub fn model(&self) -> ModelEnvironmentId { + self.model + } +} + +impl ModelIdKind for EnvironmentIdPair { + const PREFIX: &'static str = ModelEnvironmentId::PREFIX; + type Key = RegisteredEnvironmentId; + type Alias = ModelEnvironmentId; + + fn from_parts(registered: Self::Key, model: Self::Alias) -> Self { + Self { registered, model } + } +} + +#[cfg(test)] +#[path = "environment_id_tests.rs"] +mod tests; diff --git a/codex-rs/state/src/lib.rs b/codex-rs/state/src/lib.rs index 4ae3394ed6..823aaf22ce 100644 --- a/codex-rs/state/src/lib.rs +++ b/codex-rs/state/src/lib.rs @@ -108,6 +108,7 @@ pub use runtime::collect_runtime_db_backups; pub use runtime::is_sqlite_corruption_error; pub use runtime::model_ids::MemoryModelIdStore; pub use runtime::model_ids::ModelIdStoreFuture; +pub use runtime::model_ids::SessionModelIdMapping; pub use runtime::model_ids::SessionModelIdStore; pub use runtime::open_thread_history_db; pub use runtime::recovery::RuntimeDbBackup; diff --git a/codex-rs/state/src/runtime/model_ids.rs b/codex-rs/state/src/runtime/model_ids.rs index e216c3caf4..b875e24a6a 100644 --- a/codex-rs/state/src/runtime/model_ids.rs +++ b/codex-rs/state/src/runtime/model_ids.rs @@ -3,6 +3,7 @@ use std::collections::HashMap; use std::future::Future; use std::pin::Pin; +use std::sync::Arc; use std::sync::Mutex; use anyhow::Result; @@ -11,6 +12,7 @@ use codex_utils_model_facing_id::ModelFacingId; use codex_utils_model_facing_id::ModelFacingIdGenerator; use codex_utils_model_facing_id::ModelFacingIdGeneratorState; use codex_utils_model_facing_id::ModelIdKey; +use codex_utils_model_facing_id::ModelIdKind; use codex_utils_model_facing_id::ModelIdMap; use sqlx::SqliteConnection; use sqlx::types::Json; @@ -37,6 +39,34 @@ pub trait SessionModelIdStore: Send + Sync { fn initialize(&self, session: SessionId, maps: Vec) -> ModelIdStoreFuture<'_, ()>; } +/// Stable model-facing names for external objects referenced by a session and its workers. +pub struct SessionModelIdMapping { + session_id: SessionId, + store: Result>, +} + +impl SessionModelIdMapping { + /// Defer store errors until a caller actually needs a mapped ID. + pub fn new(session_id: SessionId, store: Result>) -> Self { + Self { session_id, store } + } + + pub fn session_id(&self) -> SessionId { + self.session_id + } + + /// Assign an alias on first use and pair it with the original external key. + pub async fn get_or_assign(&self, key: I::Key) -> Result { + let stored_key = ModelIdKey::new::(&key)?; + let store = self + .store + .as_ref() + .map_err(|err| anyhow::anyhow!("session model ID store: {err:#}"))?; + let alias = store.get_or_assign(self.session_id, stored_key).await?; + Ok(I::from_parts(key, alias.into())) + } +} + impl SessionModelIdStore for StateRuntime { fn lookup( &self, diff --git a/codex-rs/state/src/runtime/model_ids_tests.rs b/codex-rs/state/src/runtime/model_ids_tests.rs index a6ebaae498..3ed9909be4 100644 --- a/codex-rs/state/src/runtime/model_ids_tests.rs +++ b/codex-rs/state/src/runtime/model_ids_tests.rs @@ -3,7 +3,6 @@ use super::*; use crate::SqliteConfig; use codex_utils_absolute_path::test_support::PathExt; -use codex_utils_model_facing_id::RegisteredEnvironmentId; use pretty_assertions::assert_eq; /// Concurrent writers reserve a key once, and an independent connection observes the winner. @@ -14,13 +13,19 @@ async fn concurrent_assignments_share_a_durable_alias() -> Result<()> { let a = StateRuntime::init(config.clone(), "test".into()).await?; let b = StateRuntime::init(config, "test".into()).await?; let session = SessionId::new(); - let key = ModelIdKey::new(&RegisteredEnvironmentId::new("first"))?; + let key = ModelIdKey { + kind: "env", + key: serde_json::to_string("first")?, + }; let (left, right) = tokio::try_join!( a.get_or_assign(session, key.clone()), b.get_or_assign(session, key.clone()), )?; assert_eq!(left, right); - let second = ModelIdKey::new(&RegisteredEnvironmentId::new("second"))?; + let second = ModelIdKey { + kind: "env", + key: serde_json::to_string("second")?, + }; let next = b.get_or_assign(session, second.clone()).await?; assert_ne!(left, next); assert_eq!(a.lookup(session, key.clone()).await?, Some(left)); diff --git a/codex-rs/utils/model-facing-id/src/bindings.rs b/codex-rs/utils/model-facing-id/src/bindings.rs index d44c6018aa..a389e5261a 100644 --- a/codex-rs/utils/model-facing-id/src/bindings.rs +++ b/codex-rs/utils/model-facing-id/src/bindings.rs @@ -10,11 +10,16 @@ use crate::ModelFacingIdGenerator; use crate::ModelFacingIdGeneratorState; use crate::RestoreError; -/// The key type selects the alias type and a unique, stable prefix. Its JSON encoding must -/// distinguish unequal keys and remain stable across releases. -pub trait ModelIdKind: Eq + Hash + Serialize + DeserializeOwned { +/// Associates a mapped ID with its external key and model-facing alias. +/// The prefix must uniquely identify the kind. Key encodings must remain stable across +/// releases and distinguish unequal keys. +pub trait ModelIdKind: Sized { const PREFIX: &'static str; + type Key: Eq + Hash + Serialize + DeserializeOwned; type Alias: From; + + /// Pair the key with the alias assigned by the session store. + fn from_parts(key: Self::Key, alias: Self::Alias) -> Self; } #[derive(Clone)] @@ -24,11 +29,11 @@ pub struct ModelIdKey { } impl ModelIdKey { - pub fn new(key: &K) -> serde_json::Result { + pub fn new(key: &I::Key) -> serde_json::Result { let mut key = serde_json::to_value(key)?; key.sort_all_objects(); Ok(Self { - kind: K::PREFIX, + kind: I::PREFIX, key: key.to_string(), }) } diff --git a/codex-rs/utils/model-facing-id/src/environment.rs b/codex-rs/utils/model-facing-id/src/environment.rs index 0007ea9cc3..85f7d02175 100644 --- a/codex-rs/utils/model-facing-id/src/environment.rs +++ b/codex-rs/utils/model-facing-id/src/environment.rs @@ -6,10 +6,9 @@ use serde::Deserialize; use serde::Serialize; use crate::ModelFacingId; -use crate::ModelIdKind; /// An ID assigned to an executor by the client. -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct RegisteredEnvironmentId(String); @@ -33,20 +32,14 @@ impl fmt::Display for RegisteredEnvironmentId { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ModelEnvironmentId(u64); -impl fmt::Display for ModelEnvironmentId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}{}", - RegisteredEnvironmentId::PREFIX, - crate::padded_digits(self.0) - ) - } +impl ModelEnvironmentId { + pub const PREFIX: &'static str = "env"; } -impl ModelIdKind for RegisteredEnvironmentId { - const PREFIX: &'static str = "env"; - type Alias = ModelEnvironmentId; +impl fmt::Display for ModelEnvironmentId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}{}", Self::PREFIX, crate::padded_digits(self.0)) + } } impl From for ModelEnvironmentId {