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
This commit is contained in:
Adam Perry @ OpenAI
2026-12-02 01:59:55 +00:00
committed by copyberry
parent 55ea9a4620
commit e1e967cd46
17 changed files with 373 additions and 158 deletions
+15
View File
@@ -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"
+2
View File
@@ -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" }
+1
View File
@@ -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 }
@@ -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<Mutex<BTreeMap<PathBuf, Option<String>>>> =
/// Environment values visible to the model.
#[derive(Clone, Debug, Default)]
pub(crate) struct EnvironmentsState {
environments: BTreeMap<String, EnvironmentState>,
environments: BTreeMap<RegisteredEnvironmentId, EnvironmentState>,
// Keep each environment named and its rules grouped together, even when there is only one.
per_environment: bool,
shell_version: Option<String>,
@@ -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::<BTreeMap<_, _>>();
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<String, EnvironmentSnapshot>,
environments: BTreeMap<RegisteredEnvironmentId, EnvironmentSnapshot>,
#[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<String> {
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<String, EnvironmentState> {
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::<BTreeMap<_, _>>();
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<Item = EnvironmentState> + '_ {
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<String, EnvironmentState>) -> bool {
fn is_legacy_single(environments: &BTreeMap<RegisteredEnvironmentId, EnvironmentState>) -> bool {
environments.len() == 1
&& environments
.values()
@@ -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>) -> (String, EnvironmentState) {
fn environment(
id: &str,
cwd: PathUri,
shell: impl Into<String>,
) -> (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>) -> (String, Env
}
fn environment_state(
environments: impl IntoIterator<Item = (String, EnvironmentState)>,
environments: impl IntoIterator<Item = (RegisteredEnvironmentId, EnvironmentState)>,
current_date: Option<String>,
timezone: Option<String>,
network: Option<NetworkContext>,
@@ -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
@@ -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<EnvironmentState> {
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,
+40 -15
View File
@@ -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<TurnEnvironmentResult>,
@@ -1308,16 +1319,34 @@ pub struct TurnEnvironmentSnapshot {
}
impl TurnEnvironmentSnapshot {
pub(crate) fn registered_ids(&self) -> impl Iterator<Item = RegisteredEnvironmentId> + '_ {
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<Vec<EnvironmentIdPair>> {
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<SelectedCapabilityRoot> {
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.
@@ -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<dyn codex_state::SessionModelIdStore> =
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::<Vec<_>>(),
[
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()
+6
View File
@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "environment-id",
crate_name = "codex_environment_id",
)
+23
View File
@@ -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"] }
@@ -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(), &registered);
drop(ids);
let reopened = StateRuntime::init(config, "test".into()).await?;
let ids = SessionModelIdMapping::new(session, Ok(reopened));
assert_eq!(
ids.get_or_assign::<EnvironmentIdPair>(registered).await?,
id
);
Ok(())
}
+37
View File
@@ -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;
+1
View File
@@ -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;
+30
View File
@@ -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<ModelIdMap>) -> ModelIdStoreFuture<'_, ()>;
}
/// Stable model-facing names for external objects referenced by a session and its workers.
pub struct SessionModelIdMapping {
session_id: SessionId,
store: Result<Arc<dyn SessionModelIdStore>>,
}
impl SessionModelIdMapping {
/// Defer store errors until a caller actually needs a mapped ID.
pub fn new(session_id: SessionId, store: Result<Arc<dyn SessionModelIdStore>>) -> 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<I: ModelIdKind>(&self, key: I::Key) -> Result<I> {
let stored_key = ModelIdKey::new::<I>(&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,
@@ -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));
+10 -5
View File
@@ -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<ModelFacingId>;
/// 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<K: ModelIdKind>(key: &K) -> serde_json::Result<Self> {
pub fn new<I: ModelIdKind>(key: &I::Key) -> serde_json::Result<Self> {
let mut key = serde_json::to_value(key)?;
key.sort_all_objects();
Ok(Self {
kind: K::PREFIX,
kind: I::PREFIX,
key: key.to_string(),
})
}
@@ -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<ModelFacingId> for ModelEnvironmentId {