Reduce SQLite lock contention in agent jobs

High-fanout agent-job runs were opening many StateRuntime instances against the same state_5.sqlite during subagent and session startup. That amplified SQLite writer contention and caused spawn_agents_on_csv to fail immediately with database-locked errors before workers could run.

Fix this by caching rollout StateRuntime handles per (sqlite_home, provider) so subagents reuse one SQLite runtime instead of opening a new pool. Also retry transient SQLite lock errors around agent-job DB operations, replace per-thread reclaim lookups with one running-items query, and map cancelled background tool tasks to normal tool failures instead of panicking the turn drain path.

Add rollout tests covering cache reuse and concurrent initialization.
This commit is contained in:
Dave Aitel
2026-05-24 01:57:16 +00:00
committed by michael mcgrew
parent 2df8e623ba
commit f3cc9d1c48
9 changed files with 524 additions and 164 deletions
+64 -14
View File
@@ -15,11 +15,15 @@ pub use codex_state::LogEntry;
use codex_state::ThreadMetadataBuilder;
use codex_utils_path::normalize_for_path_comparison;
use serde_json::Value;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::OnceCell;
use tracing::info;
use tracing::warn;
@@ -35,6 +39,53 @@ const STARTUP_BACKFILL_WAIT_TIMEOUT: Duration = Duration::from_secs(30);
#[cfg(test)]
const STARTUP_BACKFILL_WAIT_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
struct StateDbCacheKey {
sqlite_home: PathBuf,
default_provider: String,
}
type StateDbRuntimeCell = Arc<OnceCell<StateDbHandle>>;
static STATE_DB_RUNTIME_CACHE: LazyLock<Mutex<HashMap<StateDbCacheKey, StateDbRuntimeCell>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
fn cache_key(sqlite_home: &Path, default_provider: &str) -> StateDbCacheKey {
StateDbCacheKey {
sqlite_home: normalize_for_path_comparison(sqlite_home)
.unwrap_or_else(|_| sqlite_home.to_path_buf()),
default_provider: default_provider.to_string(),
}
}
fn cached_runtime_cell(sqlite_home: &Path, default_provider: &str) -> StateDbRuntimeCell {
let key = cache_key(sqlite_home, default_provider);
let mut cache = STATE_DB_RUNTIME_CACHE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(cell) = cache.get(&key) {
return Arc::clone(cell);
}
let cell = Arc::new(OnceCell::new());
cache.insert(key, Arc::clone(&cell));
cell
}
async fn shared_state_db_runtime(
sqlite_home: &Path,
default_provider: &str,
) -> anyhow::Result<StateDbHandle> {
let cell = cached_runtime_cell(sqlite_home, default_provider);
let runtime = cell
.get_or_try_init(|| async {
codex_state::StateRuntime::init(sqlite_home.to_path_buf(), default_provider.to_string())
.await
})
.await?;
Ok(Arc::clone(runtime))
}
/// Initialize the state runtime for thread state persistence.
///
/// This is the process entry point for local state: it opens the SQLite-backed
@@ -107,15 +158,17 @@ async fn try_init_with_roots_inner(
default_model_provider_id: String,
backfill_lease_seconds: Option<i64>,
) -> anyhow::Result<StateDbHandle> {
let runtime =
codex_state::StateRuntime::init(sqlite_home.clone(), default_model_provider_id.clone())
.await
.map_err(|err| {
anyhow::anyhow!(
"failed to initialize state runtime at {}: {err}",
sqlite_home.display()
)
})?;
let runtime = shared_state_db_runtime(
sqlite_home.as_path(),
default_model_provider_id.as_str(),
)
.await
.map_err(|err| {
anyhow::anyhow!(
"failed to initialize state runtime at {}: {err}",
sqlite_home.display()
)
})?;
let backfill_gate_started = Instant::now();
let backfill_gate_result = wait_for_backfill_gate(
runtime.as_ref(),
@@ -221,11 +274,8 @@ pub async fn get_state_db(config: &impl RolloutConfigView) -> Option<StateDbHand
);
return None;
}
let runtime = match codex_state::StateRuntime::init(
config.sqlite_home().to_path_buf(),
config.model_provider_id().to_string(),
)
.await
let runtime = match shared_state_db_runtime(config.sqlite_home(), config.model_provider_id())
.await
{
Ok(runtime) => runtime,
Err(_) => {
+81
View File
@@ -7,6 +7,8 @@ use chrono::NaiveDateTime;
use chrono::Timelike;
use chrono::Utc;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::sync::Arc;
use tempfile::TempDir;
#[test]
@@ -24,6 +26,85 @@ fn cursor_to_anchor_normalizes_timestamp_format() {
assert_eq!(anchor.ts, expected_ts);
}
fn test_config(home: &Path) -> RolloutConfig {
RolloutConfig {
codex_home: home.to_path_buf(),
sqlite_home: home.to_path_buf(),
cwd: home.to_path_buf(),
model_provider_id: "test-provider".to_string(),
generate_memories: false,
}
}
#[tokio::test]
async fn init_reuses_cached_runtime_for_same_home() {
let temp = TempDir::new().expect("temp dir");
let config = test_config(temp.path());
let first = init(&config).await.expect("state db init should succeed");
first
.mark_backfill_complete(/*last_watermark*/ None)
.await
.expect("backfill should be marked complete");
let second = init(&config)
.await
.expect("cached state db init should succeed");
assert!(Arc::ptr_eq(&first, &second));
}
#[tokio::test]
async fn get_state_db_reuses_cached_runtime() {
let temp = TempDir::new().expect("temp dir");
let config = test_config(temp.path());
let first = init(&config).await.expect("state db init should succeed");
first
.mark_backfill_complete(/*last_watermark*/ None)
.await
.expect("backfill should be marked complete");
let reopened = get_state_db(&config)
.await
.expect("cached state db should be returned");
assert!(Arc::ptr_eq(&first, &reopened));
assert_eq!(reopened.codex_home(), config.sqlite_home.as_path());
}
#[tokio::test]
async fn concurrent_init_reuses_single_cached_runtime() {
let temp = TempDir::new().expect("temp dir");
let config = Arc::new(test_config(temp.path()));
let mut handles = Vec::new();
for _ in 0..8 {
let config = Arc::clone(&config);
handles.push(tokio::spawn(async move {
init(config.as_ref())
.await
.expect("state db init should succeed")
}));
}
let mut runtimes = Vec::new();
for handle in handles {
runtimes.push(handle.await.expect("task should join"));
}
let first = runtimes
.first()
.cloned()
.expect("at least one runtime should exist");
first
.mark_backfill_complete(/*last_watermark*/ None)
.await
.expect("backfill should be marked complete");
for runtime in runtimes.iter().skip(1) {
assert!(Arc::ptr_eq(&first, runtime));
}
}
#[tokio::test]
async fn try_init_waits_for_concurrent_startup_backfill() -> anyhow::Result<()> {
let home = TempDir::new().expect("temp dir");