mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:50:52 +00:00
narrow config rpc serialization around file transactions
This commit is contained in:
@@ -999,7 +999,7 @@ client_request_definitions! {
|
||||
|
||||
ConfigRead => "config/read" {
|
||||
params: v2::ConfigReadParams,
|
||||
serialization: global_shared_read("config"),
|
||||
serialization: global_shared_read("config-file"),
|
||||
response: v2::ConfigReadResponse,
|
||||
},
|
||||
ExternalAgentConfigDetect => "externalAgentConfig/detect" {
|
||||
@@ -1014,20 +1014,20 @@ client_request_definitions! {
|
||||
},
|
||||
ConfigValueWrite => "config/value/write" {
|
||||
params: v2::ConfigValueWriteParams,
|
||||
serialization: global("config"),
|
||||
serialization: global("config-file"),
|
||||
manual_payload_conversion: manual,
|
||||
response: v2::ConfigWriteResponse,
|
||||
},
|
||||
ConfigBatchWrite => "config/batchWrite" {
|
||||
params: v2::ConfigBatchWriteParams,
|
||||
serialization: global("config"),
|
||||
serialization: global("config-file"),
|
||||
manual_payload_conversion: manual,
|
||||
response: v2::ConfigWriteResponse,
|
||||
},
|
||||
|
||||
ConfigRequirementsRead => "configRequirements/read" {
|
||||
params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>,
|
||||
serialization: global("config"),
|
||||
serialization: global_shared_read("config-file"),
|
||||
response: v2::ConfigRequirementsReadResponse,
|
||||
},
|
||||
|
||||
@@ -1815,7 +1815,49 @@ mod tests {
|
||||
};
|
||||
assert_eq!(
|
||||
config_read.serialization_scope(),
|
||||
Some(ClientRequestSerializationScope::GlobalSharedRead("config"))
|
||||
Some(ClientRequestSerializationScope::GlobalSharedRead(
|
||||
"config-file"
|
||||
))
|
||||
);
|
||||
|
||||
let config_value_write = ClientRequest::ConfigValueWrite {
|
||||
request_id: request_id(),
|
||||
params: v2::ConfigValueWriteParams {
|
||||
key_path: "model".to_string(),
|
||||
value: json!("gpt-5"),
|
||||
merge_strategy: v2::MergeStrategy::Replace,
|
||||
file_path: None,
|
||||
expected_version: None,
|
||||
},
|
||||
};
|
||||
assert_eq!(
|
||||
config_value_write.serialization_scope(),
|
||||
Some(ClientRequestSerializationScope::Global("config-file"))
|
||||
);
|
||||
|
||||
let config_batch_write = ClientRequest::ConfigBatchWrite {
|
||||
request_id: request_id(),
|
||||
params: v2::ConfigBatchWriteParams {
|
||||
edits: Vec::new(),
|
||||
file_path: None,
|
||||
expected_version: None,
|
||||
reload_user_config: false,
|
||||
},
|
||||
};
|
||||
assert_eq!(
|
||||
config_batch_write.serialization_scope(),
|
||||
Some(ClientRequestSerializationScope::Global("config-file"))
|
||||
);
|
||||
|
||||
let config_requirements_read = ClientRequest::ConfigRequirementsRead {
|
||||
request_id: request_id(),
|
||||
params: None,
|
||||
};
|
||||
assert_eq!(
|
||||
config_requirements_read.serialization_scope(),
|
||||
Some(ClientRequestSerializationScope::GlobalSharedRead(
|
||||
"config-file"
|
||||
))
|
||||
);
|
||||
|
||||
let account_read = ClientRequest::GetAccount {
|
||||
|
||||
@@ -16,16 +16,15 @@ use codex_config::ConfigLayerEntry;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::ConfigLayerStackOrdering;
|
||||
use codex_config::ConfigRequirementsToml;
|
||||
use codex_config::ConfigWriteGuard;
|
||||
use codex_config::ConfigWriteLock;
|
||||
use codex_config::config_toml::ConfigToml;
|
||||
use codex_config::merge_toml_values;
|
||||
use codex_config::with_config_write_lock;
|
||||
use codex_core::config::deserialize_config_toml_with_base;
|
||||
use codex_core::config::edit::ConfigEdit;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_core::config::validate_feature_requirements_for_config_toml;
|
||||
use codex_core::path_utils;
|
||||
use codex_core::path_utils::SymlinkWritePaths;
|
||||
use codex_core::path_utils::resolve_symlink_write_paths;
|
||||
use codex_core::path_utils::write_atomically;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde_json::Value as JsonValue;
|
||||
@@ -111,6 +110,7 @@ impl ConfigManager {
|
||||
&self,
|
||||
params: ConfigReadParams,
|
||||
) -> Result<ConfigReadResponse, ConfigManagerError> {
|
||||
let _config_write_guard = self.lock_user_config().await?;
|
||||
let layers = match params.cwd.as_deref() {
|
||||
Some(cwd) => {
|
||||
let cwd = AbsolutePathBuf::try_from(PathBuf::from(cwd)).map_err(|err| {
|
||||
@@ -154,6 +154,7 @@ impl ConfigManager {
|
||||
pub(crate) async fn read_requirements(
|
||||
&self,
|
||||
) -> Result<Option<ConfigRequirementsToml>, ConfigManagerError> {
|
||||
let _config_write_guard = self.lock_user_config().await?;
|
||||
let layers = self
|
||||
.load_thread_agnostic_config()
|
||||
.await
|
||||
@@ -212,13 +213,17 @@ impl ConfigManager {
|
||||
));
|
||||
}
|
||||
|
||||
let config_write_guard = ConfigWriteLock::new(provided_path.as_path())
|
||||
.map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?
|
||||
.lock()
|
||||
.await;
|
||||
let layers = self
|
||||
.load_thread_agnostic_config()
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::io("failed to load configuration", err))?;
|
||||
let user_layer = match layers.get_active_user_layer() {
|
||||
Some(layer) => Cow::Borrowed(layer),
|
||||
None => Cow::Owned(create_empty_user_layer(&allowed_path).await?),
|
||||
None => Cow::Owned(create_empty_user_layer(&allowed_path, &config_write_guard).await?),
|
||||
};
|
||||
|
||||
if let Some(expected) = expected_version.as_deref()
|
||||
@@ -325,7 +330,7 @@ impl ConfigManager {
|
||||
if !config_edits.is_empty() {
|
||||
ConfigEditsBuilder::for_config_path(provided_path.as_path())
|
||||
.with_edits(config_edits)
|
||||
.apply()
|
||||
.apply_with_write_lock(config_write_guard)
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::anyhow("failed to persist config.toml", err))?;
|
||||
}
|
||||
@@ -359,23 +364,31 @@ impl ConfigManager {
|
||||
async fn load_thread_agnostic_config(&self) -> std::io::Result<ConfigLayerStack> {
|
||||
self.load_config_layers(/*cwd*/ None).await
|
||||
}
|
||||
|
||||
async fn lock_user_config(&self) -> Result<ConfigWriteGuard, ConfigManagerError> {
|
||||
let user_config_path = self
|
||||
.user_config_path()
|
||||
.map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?;
|
||||
Ok(ConfigWriteLock::new(user_config_path.as_path())
|
||||
.map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?
|
||||
.lock()
|
||||
.await)
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_empty_user_layer(
|
||||
config_toml: &AbsolutePathBuf,
|
||||
config_write_guard: &ConfigWriteGuard,
|
||||
) -> Result<ConfigLayerEntry, ConfigManagerError> {
|
||||
let SymlinkWritePaths {
|
||||
read_path,
|
||||
write_path,
|
||||
} = resolve_symlink_write_paths(config_toml.as_path())
|
||||
.map_err(|err| ConfigManagerError::io("failed to resolve user config path", err))?;
|
||||
let write_paths = config_write_guard.write_paths();
|
||||
let read_path = write_paths.read_path.as_ref();
|
||||
let toml_value = match read_path {
|
||||
Some(path) => match tokio::fs::read_to_string(&path).await {
|
||||
Ok(contents) => toml::from_str(&contents).map_err(|e| {
|
||||
ConfigManagerError::toml("failed to parse existing user config.toml", e)
|
||||
})?,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
|
||||
write_empty_user_config(write_path.clone()).await?;
|
||||
write_empty_user_config(config_write_guard).await?;
|
||||
TomlValue::Table(toml::map::Map::new())
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -386,7 +399,7 @@ async fn create_empty_user_layer(
|
||||
}
|
||||
},
|
||||
None => {
|
||||
write_empty_user_config(write_path).await?;
|
||||
write_empty_user_config(config_write_guard).await?;
|
||||
TomlValue::Table(toml::map::Map::new())
|
||||
}
|
||||
};
|
||||
@@ -399,15 +412,14 @@ async fn create_empty_user_layer(
|
||||
))
|
||||
}
|
||||
|
||||
async fn write_empty_user_config(write_path: PathBuf) -> Result<(), ConfigManagerError> {
|
||||
task::spawn_blocking(move || {
|
||||
with_config_write_lock(&write_path, |write_paths| {
|
||||
write_atomically(&write_paths.write_path, "")
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::anyhow("config persistence task panicked", err.into()))?
|
||||
.map_err(|err| ConfigManagerError::io("failed to create empty user config.toml", err))
|
||||
async fn write_empty_user_config(
|
||||
config_write_guard: &ConfigWriteGuard,
|
||||
) -> Result<(), ConfigManagerError> {
|
||||
let write_path = config_write_guard.write_paths().write_path.clone();
|
||||
task::spawn_blocking(move || write_atomically(&write_path, ""))
|
||||
.await
|
||||
.map_err(|err| ConfigManagerError::anyhow("config persistence task panicked", err.into()))?
|
||||
.map_err(|err| ConfigManagerError::io("failed to create empty user config.toml", err))
|
||||
}
|
||||
|
||||
fn parse_value(value: JsonValue) -> Result<Option<TomlValue>, String> {
|
||||
|
||||
@@ -537,6 +537,59 @@ async fn version_conflict_rejected() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_writes_with_same_version_allow_only_one_success() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
let user_path = tmp.path().join(CONFIG_TOML_FILE);
|
||||
std::fs::write(&user_path, "model = \"user\"").unwrap();
|
||||
|
||||
let service = ConfigManager::without_managed_config_for_tests(tmp.path().to_path_buf());
|
||||
let read = service
|
||||
.read(ConfigReadParams {
|
||||
include_layers: false,
|
||||
cwd: None,
|
||||
})
|
||||
.await
|
||||
.expect("read config");
|
||||
let version = read
|
||||
.origins
|
||||
.get("model")
|
||||
.expect("model origin")
|
||||
.version
|
||||
.clone();
|
||||
let first = service.write_value(ConfigValueWriteParams {
|
||||
file_path: Some(user_path.display().to_string()),
|
||||
key_path: "model".to_string(),
|
||||
value: serde_json::json!("gpt-first"),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
expected_version: Some(version.clone()),
|
||||
});
|
||||
let second = service.write_value(ConfigValueWriteParams {
|
||||
file_path: Some(user_path.display().to_string()),
|
||||
key_path: "model".to_string(),
|
||||
value: serde_json::json!("gpt-second"),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
expected_version: Some(version),
|
||||
});
|
||||
|
||||
let outcomes = tokio::join!(first, second);
|
||||
assert_eq!(
|
||||
[&outcomes.0, &outcomes.1]
|
||||
.into_iter()
|
||||
.filter(|outcome| outcome.is_ok())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
[&outcomes.0, &outcomes.1]
|
||||
.into_iter()
|
||||
.filter_map(|outcome| outcome.as_ref().err())
|
||||
.map(ConfigManagerError::write_error_code)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![Some(ConfigWriteErrorCode::ConfigVersionConflict)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn write_value_defaults_to_user_config_path() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::path_utils::write_atomically;
|
||||
use anyhow::Context;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::ConfigWriteGuard;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_config::types::SessionPickerViewMode;
|
||||
use codex_config::types::ToolSuggestDisabledTool;
|
||||
@@ -10,6 +11,8 @@ use codex_protocol::config_types::Personality;
|
||||
use codex_protocol::config_types::ServiceTier;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_utils_path::SymlinkWritePaths;
|
||||
use codex_utils_path::resolve_symlink_write_paths;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
@@ -702,45 +705,50 @@ fn apply_blocking_to_resolved_file(
|
||||
}
|
||||
|
||||
with_config_write_lock(resolved_config_file, |write_paths| {
|
||||
let serialized = match write_paths.read_path.as_ref() {
|
||||
Some(path) => match std::fs::read_to_string(path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
|
||||
Err(err) => return Err(err.into()),
|
||||
},
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
let doc = if serialized.is_empty() {
|
||||
DocumentMut::new()
|
||||
} else {
|
||||
serialized.parse::<DocumentMut>()?
|
||||
};
|
||||
|
||||
let mut document = ConfigDocument::new(doc);
|
||||
let mut mutated = false;
|
||||
|
||||
for edit in edits {
|
||||
mutated |= document.apply(edit)?;
|
||||
}
|
||||
|
||||
if !mutated {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
write_atomically(&write_paths.write_path, &document.doc.to_string()).with_context(
|
||||
|| {
|
||||
format!(
|
||||
"failed to persist config at {}",
|
||||
write_paths.write_path.display()
|
||||
)
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
apply_blocking_to_write_paths(write_paths, edits)
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_blocking_to_write_paths(
|
||||
write_paths: &SymlinkWritePaths,
|
||||
edits: &[ConfigEdit],
|
||||
) -> anyhow::Result<()> {
|
||||
let serialized = match write_paths.read_path.as_ref() {
|
||||
Some(path) => match std::fs::read_to_string(path) {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
|
||||
Err(err) => return Err(err.into()),
|
||||
},
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
let doc = if serialized.is_empty() {
|
||||
DocumentMut::new()
|
||||
} else {
|
||||
serialized.parse::<DocumentMut>()?
|
||||
};
|
||||
|
||||
let mut document = ConfigDocument::new(doc);
|
||||
let mut mutated = false;
|
||||
|
||||
for edit in edits {
|
||||
mutated |= document.apply(edit)?;
|
||||
}
|
||||
|
||||
if !mutated {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
write_atomically(&write_paths.write_path, &document.doc.to_string()).with_context(|| {
|
||||
format!(
|
||||
"failed to persist config at {}",
|
||||
write_paths.write_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist edits asynchronously by offloading the blocking writer.
|
||||
///
|
||||
pub async fn apply(codex_home: &Path, edits: Vec<ConfigEdit>) -> anyhow::Result<()> {
|
||||
@@ -986,6 +994,19 @@ impl ConfigEditsBuilder {
|
||||
.await
|
||||
.context("config persistence task panicked")?
|
||||
}
|
||||
|
||||
/// Apply edits using a config write guard already acquired for this builder's path.
|
||||
pub async fn apply_with_write_lock(self, write_guard: ConfigWriteGuard) -> anyhow::Result<()> {
|
||||
task::spawn_blocking(move || {
|
||||
let write_paths = resolve_symlink_write_paths(&self.config_path)?;
|
||||
if write_paths.write_path != write_guard.write_paths().write_path {
|
||||
anyhow::bail!("config write guard does not match builder path");
|
||||
}
|
||||
apply_blocking_to_write_paths(write_guard.write_paths(), &self.edits)
|
||||
})
|
||||
.await
|
||||
.context("config persistence task panicked")?
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1286,6 +1286,30 @@ model_reasoning_effort = "high"
|
||||
assert_eq!(contents, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn builder_rejects_write_guard_for_different_config_path() {
|
||||
let tmp = tempdir().expect("tmpdir");
|
||||
let first_path = tmp.path().join("first.toml");
|
||||
let second_path = tmp.path().join("second.toml");
|
||||
let write_guard = codex_config::ConfigWriteLock::new(&first_path)
|
||||
.expect("write lock")
|
||||
.lock()
|
||||
.await;
|
||||
|
||||
let error = ConfigEditsBuilder::for_config_path(&second_path)
|
||||
.set_model(Some("gpt-5.4"), Some(ReasoningEffort::High))
|
||||
.apply_with_write_lock(write_guard)
|
||||
.await
|
||||
.expect_err("mismatched write guard should fail");
|
||||
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"config write guard does not match builder path"
|
||||
);
|
||||
assert!(!first_path.exists());
|
||||
assert!(!second_path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocking_builder_set_model_round_trips_back_and_forth() {
|
||||
let tmp = tempdir().expect("tmpdir");
|
||||
|
||||
Reference in New Issue
Block a user