Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
//! Read-only queries against an existing state database.
use anyhow::Result;
use codex_protocol::ThreadId;
use sqlx::Row;
use std::path::PathBuf;
use std::time::Duration;
use crate::SqliteConfig;
/// Minimal thread metadata used by read-only state database audits.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadStateAuditRow {
pub id: String,
pub rollout_path: PathBuf,
pub archived: bool,
pub source: String,
pub model_provider: String,
}
/// Read persisted thread rows from a state DB without creating, migrating, or repairing it.
pub async fn read_thread_state_audit_rows(
sqlite: &SqliteConfig,
) -> Result<Vec<ThreadStateAuditRow>> {
let pool = sqlite
.open_read_only_pool(&sqlite.state_db_path(), /*busy_timeout*/ None)
.await?;
let rows = sqlx::query(
r#"
SELECT id, rollout_path, archived, source, model_provider
FROM threads
"#,
)
.fetch_all(&pool)
.await?;
pool.close().await;
rows.into_iter()
.map(|row| {
let archived: i64 = row.try_get("archived")?;
Ok(ThreadStateAuditRow {
id: row.try_get("id")?,
rollout_path: PathBuf::from(row.try_get::<String, _>("rollout_path")?),
archived: archived != 0,
source: row.try_get("source")?,
model_provider: row.try_get("model_provider")?,
})
})
.collect()
}
/// Reads only the thread IDs and selected paths, without creating or migrating the state DB.
pub async fn read_thread_rollout_paths(sqlite: &SqliteConfig) -> Result<Vec<(ThreadId, PathBuf)>> {
// Migration can scan the rollout headers immediately if the index is locked.
let pool = sqlite
.open_read_only_pool(&sqlite.state_db_path(), Some(Duration::ZERO))
.await?;
let rows = sqlx::query_as::<_, (String, String)>("SELECT id, rollout_path FROM threads")
.fetch_all(&pool)
.await?;
pool.close().await;
rows.into_iter()
.map(|(id, path)| Ok((ThreadId::from_string(&id)?, PathBuf::from(path))))
.collect()
}

View File

@@ -0,0 +1,32 @@
//! Display-only previews for recognized delegated inputs; model content is never rewritten.
use codex_protocol::items::FunctionCallOutputItem;
/// Extract the task text from a delegated input, ignoring unrelated tool outputs.
pub fn delegated_output_preview(output: &FunctionCallOutputItem) -> Option<String> {
if !matches!(output.namespace.as_deref(), Some("codex_app" | "codex_tui"))
|| !matches!(
output.name.as_str(),
"create_thread" | "send_message_to_thread"
)
{
return None;
}
let text = output.output.to_text()?;
let preview = text
.strip_prefix("<codex_delegation>\n <source_thread_id>")
.and_then(|delegation| delegation.split_once("</source_thread_id>\n <input>"))
.and_then(|(_, input)| input.strip_suffix("</input>\n</codex_delegation>"))
.map(|input| {
input
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&amp;", "&")
})
.unwrap_or(text);
(!preview.trim().is_empty()).then_some(preview)
}
#[cfg(test)]
#[path = "delegated_preview_tests.rs"]
mod tests;

View File

@@ -0,0 +1,49 @@
//! Verify delegated preview decoding and tool identity filtering.
use super::delegated_output_preview;
use codex_protocol::items::FunctionCallOutputItem;
use codex_protocol::models::FunctionCallOutputBody;
use pretty_assertions::assert_eq;
#[test]
fn delegated_previews_unwrap_only_recognized_inputs() {
let wrapped = "<codex_delegation>\n <source_thread_id>source</source_thread_id>\n <input>Check &lt;main&gt; &amp; &amp;lt;literal&amp;gt;</input>\n</codex_delegation>";
for (namespace, name, text, expected) in [
(
Some("codex_app"),
"create_thread",
wrapped,
Some("Check <main> & &lt;literal&gt;"),
),
(
Some("codex_tui"),
"send_message_to_thread",
wrapped,
Some("Check <main> & &lt;literal&gt;"),
),
(
Some("codex_app"),
"create_thread",
"plain &lt;text&gt;",
Some("plain &lt;text&gt;"),
),
(Some("codex_tui"), "create_thread", " ", None),
(Some("other"), "create_thread", wrapped, None),
(None, "create_thread", wrapped, None),
(Some("codex_app"), "shell", wrapped, None),
(
Some("codex_app"),
"create_thread",
"<codex_delegation>incomplete",
Some("<codex_delegation>incomplete"),
),
] {
let output = FunctionCallOutputItem {
id: "output".to_string(),
name: name.to_string(),
namespace: namespace.map(str::to_string),
output: FunctionCallOutputBody::Text(text.to_string()),
};
assert_eq!(delegated_output_preview(&output).as_deref(), expected);
}
}

View File

@@ -0,0 +1,882 @@
use crate::model::ThreadMetadata;
use codex_history::RolloutItem;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::TurnContextItem;
use codex_protocol::protocol::UserMessageEvent;
use codex_protocol::protocol::strip_user_message_prefix;
use codex_protocol::protocol::user_message_preview;
use serde::Serialize;
use serde_json::Value;
pub const GUARDIAN_THREAD_TITLE: &str = "Guardian review";
pub const GUARDIAN_THREAD_PREVIEW: &str = "Approval review";
/// Identifies internal review threads whose user messages are synthetic approval prompts.
pub fn is_guardian_review_source(source: &SessionSource) -> bool {
matches!(
source,
SessionSource::SubAgent(SubAgentSource::Other(name)) if name == "guardian"
)
}
/// Apply a rollout item to the metadata structure.
pub fn apply_rollout_item(
metadata: &mut ThreadMetadata,
item: &RolloutItem,
default_provider: &str,
) {
match item {
RolloutItem::SessionMeta(meta_line) => apply_session_meta_from_item(metadata, meta_line),
RolloutItem::TurnContext(turn_ctx) => apply_turn_context(metadata, turn_ctx),
RolloutItem::EventMsg(event) => apply_event_msg(metadata, event),
RolloutItem::ResponseItem(item) => apply_response_item(metadata, &item.item),
RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. } => {}
RolloutItem::Compacted(_) => {}
RolloutItem::WorldState(_) => {}
RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_) => {}
RolloutItem::RealtimeItem(_) => {}
RolloutItem::TokenUsageRecord(_) => {}
}
if metadata.model_provider.is_empty() {
metadata.model_provider = default_provider.to_string();
}
}
/// Return whether this rollout item can mutate thread metadata stored in SQLite.
pub fn rollout_item_affects_thread_metadata(item: &RolloutItem) -> bool {
match item {
RolloutItem::SessionMeta(_) | RolloutItem::TurnContext(_) => true,
RolloutItem::EventMsg(
EventMsg::TokenCount(_)
| EventMsg::UserMessage(_)
| EventMsg::ThreadGoalUpdated(_)
| EventMsg::ThreadSettingsApplied(_),
) => true,
RolloutItem::EventMsg(EventMsg::ItemCompleted(event))
if matches!(
event.item,
TurnItem::UserMessage(_) | TurnItem::FunctionCallOutput(_)
) =>
{
true
}
RolloutItem::EventMsg(_)
| RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::Compacted(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::WorldState(_) => false,
}
}
fn apply_session_meta_from_item(metadata: &mut ThreadMetadata, meta_line: &SessionMetaLine) {
if metadata.id != meta_line.meta.id {
// Ignore session_meta lines that don't match the canonical thread ID,
// e.g., forked rollouts that embed the source session metadata.
return;
}
metadata.creator_user_id = metadata
.creator_user_id
.take()
.or_else(|| meta_line.meta.creator_user_id.clone());
metadata.creator_account_id = metadata
.creator_account_id
.take()
.or_else(|| meta_line.meta.creator_account_id.clone());
metadata.id = meta_line.meta.id;
metadata.attached_thread_parent_id = meta_line
.meta
.forked_from_id
.filter(|_| meta_line.meta.attached_thread);
metadata.source = enum_to_string(&meta_line.meta.source);
if metadata.originator.is_none() && !meta_line.meta.originator.is_empty() {
metadata.originator = Some(meta_line.meta.originator.clone());
}
// Later SessionMeta lines do not redefine the canonical history_mode.
metadata.thread_source = meta_line.meta.thread_source.clone();
metadata.agent_nickname = meta_line.meta.agent_nickname.clone();
metadata.agent_role = meta_line.meta.agent_role.clone();
metadata.agent_path = meta_line.meta.agent_path.clone();
if let Some(provider) = meta_line.meta.model_provider.as_deref() {
metadata.model_provider = provider.to_string();
}
if !meta_line.meta.cli_version.is_empty() {
metadata.cli_version = meta_line.meta.cli_version.clone();
}
if !meta_line.meta.cwd.as_os_str().is_empty() {
metadata.cwd = meta_line.meta.cwd.clone();
}
if let Some(git) = meta_line.git.as_ref() {
metadata.git_sha = git.commit_hash.as_ref().map(|sha| sha.0.clone());
metadata.git_branch = git.branch.clone();
metadata.git_origin_url = git.repository_url.clone();
}
}
fn apply_turn_context(metadata: &mut ThreadMetadata, turn_ctx: &TurnContextItem) {
if metadata.cwd.as_os_str().is_empty() {
metadata.cwd = turn_ctx.cwd.clone().into_path_buf();
}
metadata.model = Some(turn_ctx.model.clone());
metadata.reasoning_effort = turn_ctx.effort.clone();
metadata.sandbox_policy =
serde_json::to_string(&turn_ctx.permission_profile).unwrap_or_default();
metadata.approval_mode = enum_to_string(&turn_ctx.approval_policy);
}
fn apply_event_msg(metadata: &mut ThreadMetadata, event: &EventMsg) {
match event {
EventMsg::TokenCount(token_count) => {
if let Some(info) = token_count.info.as_ref() {
metadata.tokens_used = info.total_token_usage.total_tokens.max(0);
}
}
EventMsg::UserMessage(user) if !metadata_is_guardian_review(metadata) => {
apply_user_message(metadata, user);
}
EventMsg::ItemCompleted(event) => {
if let TurnItem::UserMessage(user) = &event.item
&& !metadata_is_guardian_review(metadata)
{
apply_user_message(metadata, &user.as_legacy_user_message_event());
} else if let TurnItem::FunctionCallOutput(output) = &event.item
&& !metadata_is_guardian_review(metadata)
{
// Delegated turns have no user message, but must still be discoverable.
let preview = crate::delegated_output_preview(output);
set_preview_if_empty(metadata, preview);
}
}
EventMsg::ThreadGoalUpdated(event) if !metadata_is_guardian_review(metadata) => {
let objective = event.goal.objective.trim();
if !objective.is_empty() {
set_preview_if_empty(metadata, Some(objective.to_string()));
}
}
EventMsg::ThreadSettingsApplied(event) => {
let settings = &event.thread_settings;
metadata.model = Some(settings.model.clone());
metadata.model_provider = settings.model_provider_id.clone();
metadata.reasoning_effort = settings.reasoning_effort.clone();
metadata.cwd = settings.cwd.clone().into_path_buf();
metadata.sandbox_policy =
serde_json::to_string(&settings.permission_profile).unwrap_or_default();
metadata.approval_mode = enum_to_string(&settings.approval_policy);
}
_ => {}
}
}
fn apply_response_item(_metadata: &mut ThreadMetadata, _item: &ResponseItem) {}
pub(crate) fn metadata_is_guardian_review(metadata: &ThreadMetadata) -> bool {
serde_json::from_str::<SessionSource>(metadata.source.as_str())
.as_ref()
.is_ok_and(is_guardian_review_source)
}
fn apply_user_message(metadata: &mut ThreadMetadata, user: &UserMessageEvent) {
let preview = user_message_preview(user);
if metadata.first_user_message.is_none() {
metadata.first_user_message = preview.clone();
}
set_preview_if_empty(metadata, preview);
if metadata.title.is_empty() {
let title = strip_user_message_prefix(user.message.as_str());
if !title.is_empty() {
metadata.title = title.to_string();
}
}
}
fn set_preview_if_empty(metadata: &mut ThreadMetadata, preview: Option<String>) {
if metadata.preview.is_none() {
metadata.preview = preview;
}
}
pub(crate) fn enum_to_string<T: Serialize>(value: &T) -> String {
match serde_json::to_value(value) {
Ok(Value::String(s)) => s,
Ok(other) => other.to_string(),
Err(_) => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::apply_rollout_item;
use super::rollout_item_affects_thread_metadata;
use crate::ThreadMetadataBuilder;
use crate::model::ThreadMetadata;
use chrono::DateTime;
use chrono::Utc;
use codex_history::RolloutItem;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::Settings;
use codex_protocol::items::TurnItem;
use codex_protocol::items::UserMessageItem;
use codex_protocol::models::ContentItem;
use codex_protocol::models::PermissionProfile;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::ThreadSettingsAppliedEvent;
use codex_protocol::protocol::ThreadSettingsSnapshot;
use codex_protocol::protocol::TurnContextItem;
use codex_protocol::protocol::USER_MESSAGE_BEGIN;
use codex_protocol::protocol::UserMessageEvent;
use codex_protocol::user_input::UserInput;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
use uuid::Uuid;
#[test]
fn response_item_user_messages_do_not_set_title_or_first_user_message() {
let mut metadata = metadata_for_test();
let item = RolloutItem::ResponseItem(
ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: "hello from response item".to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}
.into(),
);
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(metadata.first_user_message, None);
assert_eq!(metadata.preview, None);
assert_eq!(metadata.title, "");
}
#[test]
fn event_msg_user_messages_set_title_and_first_user_message() {
let mut metadata = metadata_for_test();
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: format!("{USER_MESSAGE_BEGIN} actual user request"),
images: Some(vec![]),
local_images: vec![],
text_elements: vec![],
..Default::default()
}));
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(
metadata.first_user_message.as_deref(),
Some("actual user request")
);
assert_eq!(metadata.preview.as_deref(), Some("actual user request"));
assert_eq!(metadata.title, "actual user request");
}
#[test]
fn delegated_turn_preview_preserves_user_message_metadata() {
let mut metadata = metadata_for_test();
let mut expected = metadata.clone();
for text in [" ", "delegated task", "later output"] {
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: metadata.id,
turn_id: "turn-1".to_string(),
item: TurnItem::FunctionCallOutput(codex_protocol::items::FunctionCallOutputItem {
id: "output-1".to_string(),
name: "create_thread".to_string(),
namespace: Some("codex_app".to_string()),
output: codex_protocol::models::FunctionCallOutputBody::Text(text.to_string()),
}),
started_at_ms: Some(0),
completed_at_ms: 0,
}));
assert!(rollout_item_affects_thread_metadata(&item));
apply_rollout_item(&mut metadata, &item, "test-provider");
if text == "delegated task" {
expected.preview = Some(text.to_string());
}
assert_eq!(metadata, expected);
}
let user_item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
message: "actual user follow-up".to_string(),
..Default::default()
}));
apply_rollout_item(&mut metadata, &user_item, "test-provider");
expected.first_user_message = Some("actual user follow-up".to_string());
expected.title = "actual user follow-up".to_string();
assert_eq!(metadata, expected);
}
#[test]
fn completed_user_message_items_set_title_and_first_user_message() {
let mut metadata = metadata_for_test();
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::default(),
turn_id: "turn-1".to_string(),
item: TurnItem::UserMessage(UserMessageItem::new(&[UserInput::Text {
text: format!("{USER_MESSAGE_BEGIN} actual user request"),
text_elements: Vec::new(),
}])),
started_at_ms: Some(0),
completed_at_ms: 0,
}));
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(
metadata.first_user_message.as_deref(),
Some("actual user request")
);
assert_eq!(metadata.preview.as_deref(), Some("actual user request"));
assert_eq!(metadata.title, "actual user request");
}
#[test]
fn guardian_projection_skips_prompts_and_preserves_custom_names() {
let thread_id = ThreadId::new();
let source = SessionSource::SubAgent(SubAgentSource::Other("guardian".to_string()));
let mut metadata =
ThreadMetadataBuilder::new(thread_id, PathBuf::new(), Utc::now(), source.clone())
.build("test-provider");
let session_meta = RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: SessionMeta {
session_id: thread_id.into(),
id: thread_id,
source,
..Default::default()
},
git: None,
}));
apply_rollout_item(&mut metadata, &session_meta, "test-provider");
let mut expected = metadata.clone();
expected.title = super::GUARDIAN_THREAD_TITLE.to_string();
expected.name = None;
expected.preview = Some(super::GUARDIAN_THREAD_PREVIEW.to_string());
expected.first_user_message = None;
let user = UserMessageItem::new(&[UserInput::Text {
text: "large synthetic guardian prompt".to_string(),
text_elements: Vec::new(),
}]);
for event in [
EventMsg::UserMessage(user.as_legacy_user_message_event()),
EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id,
turn_id: "turn-1".to_string(),
item: TurnItem::UserMessage(user),
started_at_ms: Some(0),
completed_at_ms: 0,
}),
] {
apply_rollout_item(
&mut metadata,
&RolloutItem::EventMsg(event),
"test-provider",
);
assert_eq!(metadata, expected);
}
let mut existing = metadata.clone();
existing.title = "Named Guardian review".to_string();
metadata.prefer_existing_explicit_title(&existing);
assert_eq!(metadata, existing);
metadata.name = Some("Named Guardian review".to_string());
let expected = metadata.clone();
apply_rollout_item(&mut metadata, &session_meta, "test-provider");
assert_eq!(metadata, expected);
}
#[test]
fn event_msg_image_only_user_message_sets_image_placeholder_preview() {
let mut metadata = metadata_for_test();
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: String::new(),
images: Some(vec!["https://example.com/image.png".to_string()]),
local_images: vec![],
text_elements: vec![],
..Default::default()
}));
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(metadata.first_user_message.as_deref(), Some("[Image]"));
assert_eq!(metadata.preview.as_deref(), Some("[Image]"));
assert_eq!(metadata.title, "");
}
#[test]
fn event_msg_audio_only_user_message_sets_audio_placeholder_preview() {
let mut metadata = metadata_for_test();
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: String::new(),
images: None,
local_images: vec![],
audio: Some(vec!["https://example.com/audio.mp3".to_string()]),
local_audio: vec![],
text_elements: vec![],
..Default::default()
}));
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(metadata.first_user_message.as_deref(), Some("[Audio]"));
assert_eq!(metadata.preview.as_deref(), Some("[Audio]"));
assert_eq!(metadata.title, "");
}
#[test]
fn event_msg_blank_user_message_without_images_keeps_first_user_message_empty() {
let mut metadata = metadata_for_test();
let item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: " ".to_string(),
images: Some(vec![]),
local_images: vec![],
text_elements: vec![],
..Default::default()
}));
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(metadata.first_user_message, None);
assert_eq!(metadata.preview, None);
assert_eq!(metadata.title, "");
}
#[test]
fn event_msg_thread_goal_sets_preview_only_and_later_user_sets_message_title() {
let mut metadata = metadata_for_test();
let goal_item =
RolloutItem::EventMsg(EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
thread_id: metadata.id,
turn_id: None,
goal: ThreadGoal {
thread_id: metadata.id,
objective: "optimize the benchmark".to_string(),
status: ThreadGoalStatus::Active,
token_budget: None,
tokens_used: 0,
time_used_seconds: 0,
created_at: 1,
updated_at: 1,
},
}));
apply_rollout_item(&mut metadata, &goal_item, "test-provider");
assert_eq!(metadata.preview.as_deref(), Some("optimize the benchmark"));
assert_eq!(metadata.first_user_message, None);
assert_eq!(metadata.title, "");
let user_item = RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
client_id: None,
message: format!("{USER_MESSAGE_BEGIN} next normal prompt"),
images: Some(vec![]),
local_images: vec![],
text_elements: vec![],
..Default::default()
}));
apply_rollout_item(&mut metadata, &user_item, "test-provider");
assert_eq!(metadata.preview.as_deref(), Some("optimize the benchmark"));
assert_eq!(
metadata.first_user_message.as_deref(),
Some("next normal prompt")
);
assert_eq!(metadata.title, "next normal prompt");
}
#[test]
fn turn_context_does_not_override_session_cwd() {
let mut metadata = metadata_for_test();
metadata.cwd = PathBuf::new();
let thread_id = metadata.id;
apply_rollout_item(
&mut metadata,
&RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: SessionMeta {
account_scoped: false,
creator_user_id: None,
attached_thread: false,
creator_account_id: None,
session_id: thread_id.into(),
id: thread_id,
forked_from_id: Some(
ThreadId::from_string(&Uuid::now_v7().to_string()).expect("thread id"),
),
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: "2026-02-26T00:00:00.000Z".to_string(),
cwd: PathBuf::from("/child/worktree"),
runtime_workspace_roots: None,
originator: "codex_cli_rs".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: Some("openai".to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: Default::default(),
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
},
git: None,
})),
"test-provider",
);
apply_rollout_item(
&mut metadata,
&RolloutItem::TurnContext(TurnContextItem {
turn_id: Some("turn-1".to_string()),
root_turn_id: None,
direct_only_tool_namespaces: None,
disabled_plugin_ids: None,
cwd: serde_json::from_value(serde_json::json!(
std::env::current_dir()
.expect("current directory")
.join("parent/workspace")
))
.expect("absolute parent cwd"),
approval_policy: AskForApproval::Never,
approvals_reviewer: None,
permission_profile: PermissionProfile::Disabled,
active_permission_profile: None,
model: "gpt-5".to_string(),
comp_hash: None,
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: None,
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
}),
"test-provider",
);
assert_eq!(metadata.cwd, PathBuf::from("/child/worktree"));
let permission_profile: PermissionProfile = PermissionProfile::Disabled;
assert_eq!(
metadata.sandbox_policy,
serde_json::to_string(&permission_profile).expect("serialize permission profile")
);
assert_eq!(metadata.approval_mode, "never");
}
#[test]
fn turn_context_sets_permission_profile_metadata() {
let mut metadata = metadata_for_test();
let permission_profile = PermissionProfile::workspace_write();
apply_rollout_item(
&mut metadata,
&RolloutItem::TurnContext(TurnContextItem {
turn_id: Some("turn-1".to_string()),
root_turn_id: None,
direct_only_tool_namespaces: None,
disabled_plugin_ids: None,
cwd: serde_json::from_value(serde_json::json!(
std::env::current_dir()
.expect("current directory")
.join("workspace")
))
.expect("absolute workspace cwd"),
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: None,
permission_profile: permission_profile.clone(),
active_permission_profile: None,
model: "gpt-5".to_string(),
comp_hash: None,
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: None,
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
}),
"test-provider",
);
assert_eq!(
metadata.sandbox_policy,
serde_json::to_string(&permission_profile).expect("serialize permission profile")
);
}
#[test]
fn turn_context_sets_cwd_when_session_cwd_missing() {
let mut metadata = metadata_for_test();
metadata.cwd = PathBuf::new();
let fallback_cwd = std::env::current_dir()
.expect("current directory")
.join("fallback/workspace");
apply_rollout_item(
&mut metadata,
&RolloutItem::TurnContext(TurnContextItem {
turn_id: Some("turn-1".to_string()),
root_turn_id: None,
direct_only_tool_namespaces: None,
disabled_plugin_ids: None,
cwd: serde_json::from_value(serde_json::json!(&fallback_cwd))
.expect("absolute fallback cwd"),
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: None,
permission_profile: PermissionProfile::read_only(),
active_permission_profile: None,
model: "gpt-5".to_string(),
comp_hash: None,
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: Some(ReasoningEffort::High),
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
}),
"test-provider",
);
assert_eq!(metadata.cwd, fallback_cwd);
}
#[test]
fn turn_context_sets_model_and_reasoning_effort() {
let mut metadata = metadata_for_test();
apply_rollout_item(
&mut metadata,
&RolloutItem::TurnContext(TurnContextItem {
turn_id: Some("turn-1".to_string()),
root_turn_id: None,
direct_only_tool_namespaces: None,
disabled_plugin_ids: None,
cwd: serde_json::from_value(serde_json::json!(
std::env::current_dir()
.expect("current directory")
.join("fallback/workspace")
))
.expect("absolute fallback cwd"),
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: None,
permission_profile: PermissionProfile::read_only(),
active_permission_profile: None,
model: "gpt-5".to_string(),
comp_hash: None,
collaboration_mode: None,
multi_agent_version: None,
realtime_active: None,
cyber_access_program: None,
effort: Some(ReasoningEffort::High),
summary: Some(codex_protocol::config_types::ReasoningSummary::Auto),
}),
"test-provider",
);
assert_eq!(metadata.model.as_deref(), Some("gpt-5"));
assert_eq!(metadata.reasoning_effort, Some(ReasoningEffort::High));
}
#[test]
fn thread_settings_applied_updates_resume_metadata() {
let mut metadata = metadata_for_test();
let permission_profile = PermissionProfile::workspace_write();
let cwd = std::env::current_dir()
.expect("current directory")
.join("updated/workspace");
let item = RolloutItem::EventMsg(EventMsg::ThreadSettingsApplied(
ThreadSettingsAppliedEvent {
thread_id: None,
thread_settings: ThreadSettingsSnapshot {
disabled_plugin_ids: Vec::new(),
model: "gpt-5.2-codex".to_string(),
model_provider_id: "updated-provider".to_string(),
service_tier: None,
approval_policy: AskForApproval::Never,
approvals_reviewer: ApprovalsReviewer::User,
requested_approvals_reviewer: None,
permission_profile: permission_profile.clone(),
active_permission_profile: None,
cwd: cwd.clone().try_into().expect("absolute settings cwd"),
runtime_workspace_roots: None,
reasoning_effort: Some(ReasoningEffort::Ultra),
reasoning_summary: Some(ReasoningSummary::Auto),
personality: None,
collaboration_mode: CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "gpt-5.2-codex".to_string(),
reasoning_effort: Some(ReasoningEffort::Ultra),
developer_instructions: None,
},
},
},
},
));
assert!(rollout_item_affects_thread_metadata(&item));
apply_rollout_item(&mut metadata, &item, "test-provider");
assert_eq!(metadata.model.as_deref(), Some("gpt-5.2-codex"));
assert_eq!(metadata.model_provider, "updated-provider");
assert_eq!(metadata.reasoning_effort, Some(ReasoningEffort::Ultra));
assert_eq!(metadata.cwd, cwd);
assert_eq!(metadata.approval_mode, "never");
assert_eq!(
metadata.sandbox_policy,
serde_json::to_string(&permission_profile)
.expect("permission profile should serialize")
);
}
#[test]
fn session_meta_does_not_set_model_or_reasoning_effort() {
let mut metadata = metadata_for_test();
metadata.history_mode = ThreadHistoryMode::Paginated;
let thread_id = metadata.id;
apply_rollout_item(
&mut metadata,
&RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: SessionMeta {
account_scoped: false,
creator_user_id: None,
attached_thread: false,
creator_account_id: None,
session_id: thread_id.into(),
id: thread_id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: "2026-02-26T00:00:00.000Z".to_string(),
cwd: PathBuf::from("/workspace"),
runtime_workspace_roots: None,
originator: "codex_cli_rs".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::Cli,
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: Some("openai".to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: ThreadHistoryMode::Legacy,
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
},
git: None,
})),
"test-provider",
);
assert_eq!(metadata.model, None);
assert_eq!(metadata.reasoning_effort, None);
assert_eq!(metadata.history_mode, ThreadHistoryMode::Paginated);
}
fn metadata_for_test() -> ThreadMetadata {
let id = ThreadId::from_string(&Uuid::from_u128(42).to_string()).expect("thread id");
let created_at = DateTime::<Utc>::from_timestamp(1_735_689_600, 0).expect("timestamp");
ThreadMetadata {
creator_user_id: None,
attached_thread_parent_id: None,
creator_account_id: None,
originator: None,
id,
rollout_path: PathBuf::from("/tmp/a.jsonl"),
created_at,
updated_at: created_at,
recency_at: created_at,
source: "cli".to_string(),
history_mode: Default::default(),
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: "openai".to_string(),
model: None,
reasoning_effort: None,
cwd: PathBuf::from("/tmp"),
cli_version: "0.0.0".to_string(),
title: String::new(),
name: None,
preview: None,
sandbox_policy: "read-only".to_string(),
approval_mode: "on-request".to_string(),
tokens_used: 1,
first_user_message: None,
archived_at: None,
section: None,
section_position: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
git_sha: None,
git_branch: None,
git_origin_url: None,
}
}
#[test]
fn diff_fields_detects_changes() {
let mut base = metadata_for_test();
base.id = ThreadId::from_string(&Uuid::now_v7().to_string()).expect("thread id");
base.title = "hello".to_string();
let mut other = base.clone();
other.tokens_used = 2;
other.title = "world".to_string();
let diffs = base.diff_fields(&other);
assert_eq!(diffs, vec!["title", "tokens_used"]);
}
}

172
codex-rs/state/src/lib.rs Normal file
View File

@@ -0,0 +1,172 @@
//! SQLite-backed state for rollout metadata.
//!
//! This crate is intentionally small and focused: it extracts rollout metadata
//! from JSONL rollouts and mirrors it into a local SQLite database. Backfill
//! orchestration and rollout scanning live in `codex-core`.
const _: () = assert!(
libsqlite3_sys::SQLITE_VERSION_NUMBER >= 3_051_003,
"bundled SQLite must include the WAL-reset corruption fix",
);
mod audit;
mod delegated_preview;
mod extract;
pub mod log_db;
mod migrations;
mod model;
mod nfs_migration;
mod paths;
mod runtime;
mod sqlite;
mod telemetry;
pub use log_db::LogWriteFailureReporter;
pub use model::CreatedProject;
pub use model::LogEntry;
pub use model::LogQuery;
pub use model::LogRow;
pub use model::Phase2JobClaimOutcome;
pub use model::Project;
pub use model::ProjectRoot;
pub use model::ProjectSortKey;
pub use model::ProjectsPage;
pub use model::QueuedUserSubmissionRecord;
pub use model::RolloutMigrationCursor;
pub use model::RolloutMigrationSkippedRollout;
pub use model::RolloutMigrationState;
pub use nfs_migration::NfsDbMigration;
pub use nfs_migration::NfsDbMigrationOutcome;
pub use runtime::GuardianReviewRecord;
pub use runtime::MAX_GUARDIAN_REVIEW_BYTES;
pub use runtime::MAX_GUARDIAN_REVIEW_RECORDS;
pub use runtime::MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD;
/// Preferred entrypoint: owns configuration and metrics.
pub use runtime::StateRuntime;
pub use sqlite::SqliteConfig;
pub use sqlite::SqlitePoolWriteExt;
pub use audit::ThreadStateAuditRow;
pub use audit::read_thread_rollout_paths;
pub use audit::read_thread_state_audit_rows;
pub use delegated_preview::delegated_output_preview;
pub use extract::GUARDIAN_THREAD_PREVIEW;
pub use extract::GUARDIAN_THREAD_TITLE;
/// Low-level storage engine: useful for focused tests.
///
/// Most consumers should prefer [`StateRuntime`].
pub use extract::apply_rollout_item;
pub use extract::is_guardian_review_source;
pub use extract::rollout_item_affects_thread_metadata;
pub use model::AddThreadAttachmentOutcome;
pub use model::Anchor;
pub use model::BackfillState;
pub use model::BackfillStats;
pub use model::BackfillStatus;
pub use model::DirectionalThreadSpawnEdgeStatus;
pub use model::ExtractionOutcome;
pub use model::RemoveThreadAttachmentOutcome;
pub use model::SortDirection;
pub use model::SortKey;
pub use model::Stage1JobClaim;
pub use model::Stage1JobClaimOutcome;
pub use model::Stage1Output;
pub use model::Stage1StartupClaimParams;
pub use model::ThreadAttachment;
pub use model::ThreadAttachmentArchiveFilter;
pub use model::ThreadAttachmentOwner;
pub use model::ThreadAttachmentOwnerPage;
pub use model::ThreadAttachmentPage;
pub use model::ThreadGoal;
pub use model::ThreadGoalStatus;
pub use model::ThreadMetadata;
pub use model::ThreadMetadataBuilder;
pub use model::ThreadRelationFilter;
pub use model::ThreadSection;
pub use model::ThreadSectionAppearance;
pub use model::ThreadSectionsPage;
pub use model::ThreadsPage;
pub use runtime::ExternalAgentConfigImportDetailsRecord;
pub use runtime::ExternalAgentConfigImportFailureRecord;
pub use runtime::ExternalAgentConfigImportHistoryRecord;
pub use runtime::ExternalAgentConfigImportSuccessRecord;
pub use runtime::GoalAccountingMode;
pub use runtime::GoalAccountingOutcome;
pub use runtime::GoalStore;
pub use runtime::GoalUpdate;
pub use runtime::MemoryStore;
pub use runtime::ReadStateOperation;
pub use runtime::ReadStateUpdate;
pub use runtime::RemoteControlEnrollmentRecord;
pub use runtime::SqliteIntegrityCheck;
pub use runtime::SqliteQueueStore;
pub use runtime::ThreadFilterOptions;
pub use runtime::ThreadReadState;
pub use runtime::backup_runtime_db_for_fresh_start;
pub use runtime::collect_runtime_db_backups;
pub use runtime::is_sqlite_corruption_error;
pub use runtime::open_thread_history_db;
pub use runtime::recovery::RuntimeDbBackup;
pub use runtime::runtime_db_path_for_corruption_error;
pub use runtime::sqlite_error_detail_is_lock;
pub use runtime::sqlite_integrity_check;
pub use sqlite::RuntimeDbPath;
pub use telemetry::DbTelemetry;
pub use telemetry::DbTelemetryHandle;
pub use telemetry::install_process_db_telemetry;
pub use telemetry::record_backfill_gate;
pub use telemetry::record_fallback;
/// Maximum number of pending user submissions permitted for one thread.
pub const MAX_QUEUE_ITEMS: usize = 100;
/// Maximum serialized size of one persisted thread-attachment payload.
pub const MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES: usize = 64 * 1024;
/// Maximum byte length of a persisted attachment type.
pub const MAX_THREAD_ATTACHMENT_TYPE_BYTES: usize = 256;
/// Maximum byte length of a persisted stable attachment identity key.
pub const MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES: usize = 256;
/// Maximum number of attachments returned in one page.
pub const MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE: usize = 100;
/// Maximum number of active attachments retained for one thread.
pub const MAX_THREAD_ATTACHMENTS_PER_THREAD: usize = 100;
/// Stable UUIDv7 identifying the built-in pinned thread section.
pub const PINNED_THREAD_SECTION_ID: &str = "01984de2-8f74-7c91-a3b2-5c5e937cf318";
/// User-facing name of the built-in pinned thread section.
pub const PINNED_THREAD_SECTION_NAME: &str = "Pinned";
/// Environment variable for overriding the SQLite state database home directory.
pub const SQLITE_HOME_ENV: &str = "CODEX_SQLITE_HOME";
/// Errors encountered during DB operations. Tags: [stage]
pub const DB_ERROR_METRIC: &str = "codex.db.error";
/// Metrics on backfill process. Tags: [status]
pub const DB_METRIC_BACKFILL: &str = "codex.db.backfill";
/// Metrics on backfill duration. Tags: [status]
pub const DB_METRIC_BACKFILL_DURATION_MS: &str = "codex.db.backfill.duration_ms";
/// Confirmed SQLite quick-check corruption findings. Tags: [db]
pub const DB_CORRUPTION_METRIC: &str = "codex.sqlite.corruption.count";
/// SQLite initialization attempts. Tags: [status, phase, db, error]
pub const DB_INIT_METRIC: &str = "codex.sqlite.init.count";
/// SQLite initialization latency. Tags: [status, phase, db, error]
pub const DB_INIT_DURATION_METRIC: &str = "codex.sqlite.init.duration_ms";
/// Rollout fallback attempts. Tags: [caller, reason]
pub const DB_FALLBACK_METRIC: &str = "codex.sqlite.fallback.count";
/// SQLite log batch write attempts. Tags: [status, error]
pub const LOG_WRITE_METRIC: &str = "codex.sqlite.logs.write.count";
/// SQLite log batch write latency. Tags: [status, error]
pub const LOG_WRITE_DURATION_METRIC: &str = "codex.sqlite.logs.write.duration_ms";
/// Estimated bytes in each SQLite log batch. Tags: [status, error]
pub const LOG_WRITE_BYTES_METRIC: &str = "codex.sqlite.logs.write.bytes";
/// Number of entries in each SQLite log batch. Tags: [status, error]
pub const LOG_WRITE_ENTRIES_METRIC: &str = "codex.sqlite.logs.write.entries";
/// Largest estimated entry size in each SQLite log batch. Tags: [status, error]
pub const LOG_WRITE_MAX_ENTRY_BYTES_METRIC: &str = "codex.sqlite.logs.write.max_entry_bytes";
/// SQLite log entries discarded before they can be queued. Tags: [reason]
pub const LOG_QUEUE_DROPPED_METRIC: &str = "codex.sqlite.logs.queue.dropped";

View File

@@ -0,0 +1,977 @@
//! Tracing log export into the local SQLite log database.
//!
//! This module provides a `tracing_subscriber::Layer` that captures events,
//! formats each one into a `LogEntry`, and sends entries to a bounded background
//! queue. The background task inserts into the dedicated `logs` SQLite database
//! in batches to keep logging overhead low.
//! SQLx events are excluded so database writes cannot generate more writes.
//! Flush failures go to the supplied failure reporter without re-entering tracing.
//!
//! ## Usage
//!
//! ```no_run
//! use codex_state::log_db;
//! use tracing_subscriber::prelude::*;
//!
//! # async fn example(state_db: std::sync::Arc<codex_state::StateRuntime>, reporter: std::sync::Arc<dyn codex_state::LogWriteFailureReporter>) {
//! let layer = log_db::start(state_db, reporter);
//! let _ = tracing_subscriber::registry()
//! .with(layer)
//! .try_init();
//! # }
//! ```
use std::future::Future;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::RwLock;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tracing::Event;
use tracing::field::Field;
use tracing::field::Visit;
use tracing::level_filters::LevelFilter;
use tracing::span::Attributes;
use tracing::span::Id;
use tracing::span::Record;
use tracing_subscriber::Layer;
use tracing_subscriber::field::RecordFields;
use tracing_subscriber::filter::Targets;
use tracing_subscriber::fmt::FormatFields;
use tracing_subscriber::fmt::FormattedFields;
use tracing_subscriber::fmt::format::DefaultFields;
use tracing_subscriber::registry::LookupSpan;
use uuid::Uuid;
use crate::LogEntry;
use crate::StateRuntime;
const LOG_QUEUE_CAPACITY: usize = 2048;
const LOG_BATCH_SIZE: usize = 512;
const LOG_FLUSH_INTERVAL: Duration = Duration::from_secs(10);
const SQLX_LOG_TARGETS: [&str; 3] = ["sqlx", "sqlx_core", "sqlx_sqlite"];
pub fn default_filter() -> Targets {
Targets::new()
.with_default(LevelFilter::TRACE)
.with_target("h2", LevelFilter::WARN)
.with_target("hyper_util", LevelFilter::WARN)
.with_target("log", LevelFilter::OFF)
// Avoid constructing backend diagnostics when no other layer needs them.
.with_targets(SQLX_LOG_TARGETS.map(|target| (format!("{target}::"), LevelFilter::OFF)))
.with_target("codex_rmcp_client", LevelFilter::INFO)
.with_target("opentelemetry-otlp", LevelFilter::OFF)
.with_target("opentelemetry-http", LevelFilter::OFF)
.with_target("tonic::transport", LevelFilter::WARN)
.with_target("tower::buffer", LevelFilter::WARN)
.with_target("codex_otel.log_only", LevelFilter::OFF)
.with_target("codex_otel.trace_safe", LevelFilter::OFF)
.with_target("rmcp", LevelFilter::INFO)
.with_target("tokio::", LevelFilter::INFO)
.with_target("runtime::", LevelFilter::INFO)
.with_target("tokio_graceful::guard", LevelFilter::DEBUG)
.with_target("tokio_graceful::trigger", LevelFilter::DEBUG)
.with_target("codex_api::responses_websocket_timing", LevelFilter::OFF)
.with_target("codex_core::post_sampling_token_estimate", LevelFilter::OFF)
// Full model request bodies and streamed response payloads overwhelm the
// SQLite log database, but remain available to explicit TRACE subscribers.
.with_target("codex_http_client::transport", LevelFilter::DEBUG)
.with_target("codex_api::sse", LevelFilter::DEBUG)
// Per-chunk streaming traces otherwise flood the bounded SQLite log queue.
.with_target("codex_tui::streaming::controller", LevelFilter::DEBUG)
.with_target("codex_tui::streaming::table_holdback", LevelFilter::DEBUG)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LogSinkQueueConfig {
pub queue_capacity: usize,
pub batch_size: usize,
pub flush_interval: Duration,
}
impl Default for LogSinkQueueConfig {
fn default() -> Self {
Self {
queue_capacity: LOG_QUEUE_CAPACITY,
batch_size: LOG_BATCH_SIZE,
flush_interval: LOG_FLUSH_INTERVAL,
}
}
}
impl LogSinkQueueConfig {
fn normalized(self) -> Self {
Self {
queue_capacity: self.queue_capacity.max(1),
batch_size: self.batch_size.max(1),
flush_interval: if self.flush_interval.is_zero() {
LOG_FLUSH_INTERVAL
} else {
self.flush_interval
},
}
}
}
/// A tracing log writer that can flush entries accepted by its queue.
///
/// Implementations should keep `Layer::on_event` non-blocking for ordinary log
/// events. `flush` should wait for entries accepted before the flush command to
/// be processed by the writer.
pub trait LogWriter<S>: Layer<S>
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
fn flush(&self) -> impl Future<Output = ()> + Send + '_;
}
/// Receives a formatted, redacted diagnostic when a SQLite log batch is lost
/// this propagatest to telemetry and feedback memory buffer to avoid lost reports
pub trait LogWriteFailureReporter: Send + Sync {
fn report_failure(&self, diagnostic: &str);
}
pub struct LogDbLayer {
sender: mpsc::Sender<LogDbCommand>,
has_write_failure: Arc<AtomicBool>,
failure_reporter: Arc<RwLock<Arc<dyn LogWriteFailureReporter>>>,
process_uuid: String,
}
/// Starts the SQLite log writer with a shared, independent failure reporter.
pub fn start(
state_db: std::sync::Arc<StateRuntime>,
failure_reporter: Arc<dyn LogWriteFailureReporter>,
) -> LogDbLayer {
LogDbLayer::start(state_db, failure_reporter)
}
impl Clone for LogDbLayer {
fn clone(&self) -> Self {
Self {
sender: self.sender.clone(),
has_write_failure: self.has_write_failure.clone(),
failure_reporter: self.failure_reporter.clone(),
process_uuid: self.process_uuid.clone(),
}
}
}
impl LogDbLayer {
pub fn start(
state_db: std::sync::Arc<StateRuntime>,
failure_reporter: Arc<dyn LogWriteFailureReporter>,
) -> Self {
Self::start_with_config(state_db, failure_reporter, LogSinkQueueConfig::default())
}
pub fn start_with_config(
state_db: std::sync::Arc<StateRuntime>,
failure_reporter: Arc<dyn LogWriteFailureReporter>,
config: LogSinkQueueConfig,
) -> Self {
let config = config.normalized();
let (sender, receiver) = mpsc::channel(config.queue_capacity);
let has_write_failure = Arc::new(AtomicBool::new(false));
let failure_reporter = Arc::new(RwLock::new(failure_reporter));
tokio::spawn(run_inserter(
state_db,
receiver,
config,
failure_reporter.clone(),
has_write_failure.clone(),
));
Self {
sender,
has_write_failure,
failure_reporter,
process_uuid: current_process_log_uuid().to_string(),
}
}
/// Replaces the startup reporter once the client notification destination is available.
pub fn set_failure_reporter(&self, reporter: Arc<dyn LogWriteFailureReporter>) {
*self
.failure_reporter
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = reporter;
}
/// Whether this writer has lost logs, making SQLite incomplete for feedback.
pub fn has_write_failure(&self) -> bool {
self.has_write_failure.load(Ordering::Relaxed)
}
pub async fn flush(&self) {
let (tx, rx) = oneshot::channel();
if self.sender.send(LogDbCommand::Flush(tx)).await.is_ok() {
let _ = rx.await;
}
}
fn try_send(&self, entry: LogEntry) {
if let Err(error) = self.sender.try_send(LogDbCommand::Entry(Box::new(entry))) {
let reason = match error {
mpsc::error::TrySendError::Full(_) => "full",
mpsc::error::TrySendError::Closed(_) => "closed",
};
crate::telemetry::record_log_queue_drop(reason, /*telemetry*/ None);
}
}
}
impl<S> Layer<S> for LogDbLayer
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
fn on_new_span(
&self,
attrs: &Attributes<'_>,
id: &Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut visitor = SpanFieldVisitor::default();
attrs.record(&mut visitor);
if let Some(span) = ctx.span(id) {
span.extensions_mut().insert(SpanLogContext {
name: span.metadata().name().to_string(),
formatted_fields: format_fields(attrs),
thread_id: visitor.thread_id,
});
}
}
fn on_record(
&self,
id: &Id,
values: &Record<'_>,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
let mut visitor = SpanFieldVisitor::default();
values.record(&mut visitor);
if let Some(span) = ctx.span(id) {
let mut extensions = span.extensions_mut();
if let Some(log_context) = extensions.get_mut::<SpanLogContext>() {
if let Some(thread_id) = visitor.thread_id {
log_context.thread_id = Some(thread_id);
}
append_fields(&mut log_context.formatted_fields, values);
} else {
extensions.insert(SpanLogContext {
name: span.metadata().name().to_string(),
formatted_fields: format_fields(values),
thread_id: visitor.thread_id,
});
}
}
}
fn on_event(&self, event: &Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
let metadata = event.metadata();
let target = metadata.target();
// SQLx can emit from both the inserter task and its separate worker threads.
// This guard must remain local to the sink and independent of optional filters.
if target
.split("::")
.next()
.is_some_and(|target| SQLX_LOG_TARGETS.contains(&target))
{
return;
}
// Channel sends and timer polls from this sink must not enqueue more
// SQLite writes when Tokio runtime tracing is enabled.
if *metadata.level() == tracing::Level::TRACE
&& matches!(target.split("::").next(), Some("tokio" | "runtime"))
{
return;
}
// `tracing-log` checks filters with the original log target before
// dispatching an event whose tracing target is `log`, so the outer
// target filter cannot reliably reject these bridged events.
// OTLP exporters and their HTTP adapters log every export. Recording
// those events would create another SQLite-write metric and keep the
// exporter active indefinitely, including when its queue is full.
if matches!(target, "log" | "opentelemetry-otlp" | "opentelemetry-http") {
return;
}
// The SDK emits DEBUG timer meta-events every second per process; these
// were over 30% of retained logs in measured high-fanout Codex environments.
if target == "opentelemetry_sdk"
&& matches!(
*metadata.level(),
tracing::Level::TRACE | tracing::Level::DEBUG
)
{
return;
}
let mut visitor = MessageVisitor::default();
event.record(&mut visitor);
// OTLP gRPC connections run on their own task, so an unsolicited PING
// ACK can emit this benign warning after every otherwise successful
// export. Drop only that warning before queue/drop accounting; other
// HTTP/2 diagnostics must remain available to unrelated clients.
if target == "h2::proto::ping_pong"
&& visitor
.message
.as_deref()
.is_some_and(|message| message.starts_with("recv PING ack that we never sent: "))
{
return;
}
let thread_id = visitor
.thread_id
.clone()
.or_else(|| event_thread_id(event, &ctx));
let feedback_log_body = format_feedback_log_body(event, &ctx);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|_| Duration::from_secs(0));
let entry = LogEntry {
ts: now.as_secs() as i64,
ts_nanos: now.subsec_nanos() as i64,
level: metadata.level().as_str().to_string(),
target: metadata.target().to_string(),
message: visitor.message,
feedback_log_body: Some(feedback_log_body),
thread_id,
process_uuid: Some(self.process_uuid.clone()),
module_path: metadata.module_path().map(ToString::to_string),
file: metadata.file().map(ToString::to_string),
line: metadata.line().map(|line| line as i64),
};
self.try_send(entry);
}
}
impl<S> LogWriter<S> for LogDbLayer
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
fn flush(&self) -> impl Future<Output = ()> + Send + '_ {
LogDbLayer::flush(self)
}
}
enum LogDbCommand {
Entry(Box<LogEntry>),
Flush(oneshot::Sender<()>),
}
#[derive(Debug)]
struct SpanLogContext {
name: String,
formatted_fields: String,
thread_id: Option<String>,
}
#[derive(Default)]
struct SpanFieldVisitor {
thread_id: Option<String>,
}
impl SpanFieldVisitor {
fn record_field(&mut self, field: &Field, value: String) {
if field.name() == "thread_id" && self.thread_id.is_none() {
self.thread_id = Some(value);
}
}
}
impl Visit for SpanFieldVisitor {
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_field(field, value.to_string());
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_field(field, value.to_string());
}
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_field(field, value.to_string());
}
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_field(field, value.to_string());
}
fn record_str(&mut self, field: &Field, value: &str) {
self.record_field(field, value.to_string());
}
fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
self.record_field(field, value.to_string());
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.record_field(field, format!("{value:?}"));
}
}
fn event_thread_id<S>(
event: &Event<'_>,
ctx: &tracing_subscriber::layer::Context<'_, S>,
) -> Option<String>
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
let mut thread_id = None;
if let Some(scope) = ctx.event_scope(event) {
for span in scope.from_root() {
let extensions = span.extensions();
if let Some(log_context) = extensions.get::<SpanLogContext>()
&& log_context.thread_id.is_some()
{
thread_id = log_context.thread_id.clone();
}
}
}
thread_id
}
fn format_feedback_log_body<S>(
event: &Event<'_>,
ctx: &tracing_subscriber::layer::Context<'_, S>,
) -> String
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
let mut feedback_log_body = String::new();
if let Some(scope) = ctx.event_scope(event) {
for span in scope.from_root() {
let extensions = span.extensions();
if let Some(log_context) = extensions.get::<SpanLogContext>() {
feedback_log_body.push_str(&log_context.name);
if !log_context.formatted_fields.is_empty() {
feedback_log_body.push('{');
feedback_log_body.push_str(&log_context.formatted_fields);
feedback_log_body.push('}');
}
} else {
feedback_log_body.push_str(span.metadata().name());
}
feedback_log_body.push(':');
}
if !feedback_log_body.is_empty() {
feedback_log_body.push(' ');
}
}
feedback_log_body.push_str(&format_fields(event));
feedback_log_body
}
fn format_fields<R>(fields: R) -> String
where
R: RecordFields,
{
let formatter = DefaultFields::default();
let mut formatted = FormattedFields::<DefaultFields>::new(String::new());
let _ = formatter.format_fields(formatted.as_writer(), fields);
formatted.fields
}
fn append_fields(fields: &mut String, values: &Record<'_>) {
let formatter = DefaultFields::default();
let mut formatted = FormattedFields::<DefaultFields>::new(std::mem::take(fields));
let _ = formatter.add_fields(&mut formatted, values);
*fields = formatted.fields;
}
fn current_process_log_uuid() -> &'static str {
static PROCESS_LOG_UUID: OnceLock<String> = OnceLock::new();
PROCESS_LOG_UUID.get_or_init(|| {
let pid = std::process::id();
let process_uuid = Uuid::new_v4();
format!("pid:{pid}:{process_uuid}")
})
}
async fn run_inserter(
state_db: std::sync::Arc<StateRuntime>,
mut receiver: mpsc::Receiver<LogDbCommand>,
config: LogSinkQueueConfig,
failure_reporter: Arc<RwLock<Arc<dyn LogWriteFailureReporter>>>,
has_write_failure: Arc<AtomicBool>,
) {
let mut buffer = Vec::with_capacity(config.batch_size);
let mut ticker = tokio::time::interval(config.flush_interval);
// Consume the immediate startup tick so entries flush after the interval.
ticker.tick().await;
loop {
tokio::select! {
maybe_command = receiver.recv() => {
match maybe_command {
Some(LogDbCommand::Entry(entry)) => {
buffer.push(*entry);
if buffer.len() >= config.batch_size {
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
}
}
Some(LogDbCommand::Flush(reply)) => {
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
let _ = reply.send(());
}
None => {
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
break;
}
}
}
_ = ticker.tick() => {
flush(&state_db, &mut buffer, failure_reporter.as_ref(), &has_write_failure).await;
}
}
}
}
async fn flush(
state_db: &StateRuntime,
buffer: &mut Vec<LogEntry>,
failure_reporter: &RwLock<Arc<dyn LogWriteFailureReporter>>,
has_write_failure: &AtomicBool,
) {
if buffer.is_empty() {
return;
}
let entries = buffer.split_off(0);
let started = Instant::now();
let result = state_db.insert_logs(entries.as_slice()).await;
let duration = started.elapsed();
// if log flushing failed it means that likely something is wrong with the logs database,
// so store the logs in the memory buffer to avoid them being lost during /feedback
// the entries are dropped because the in memory buffer has it's own space-constrainted rules for preserving logs
if let Err(error) = &result {
let error = crate::telemetry::classify_error(error);
let timestamp =
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, /*use_z*/ true);
let entry_count = entries.len();
has_write_failure.store(true, Ordering::Relaxed);
failure_reporter.read().unwrap_or_else(std::sync::PoisonError::into_inner).report_failure(&format!(
"{timestamp} ERROR failed to flush logs to SQLite error={error:?} entries={entry_count}\n"
));
}
crate::telemetry::record_log_write(
/*telemetry*/ None,
duration,
entries.as_slice(),
&result,
);
}
#[derive(Default)]
struct MessageVisitor {
message: Option<String>,
thread_id: Option<String>,
}
impl MessageVisitor {
fn record_field(&mut self, field: &Field, value: String) {
if field.name() == "message" && self.message.is_none() {
self.message = Some(value.clone());
}
if field.name() == "thread_id" && self.thread_id.is_none() {
self.thread_id = Some(value);
}
}
}
impl Visit for MessageVisitor {
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_field(field, value.to_string());
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_field(field, value.to_string());
}
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_field(field, value.to_string());
}
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_field(field, value.to_string());
}
fn record_str(&mut self, field: &Field, value: &str) {
self.record_field(field, value.to_string());
}
fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
self.record_field(field, value.to_string());
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.record_field(field, format!("{value:?}"));
}
}
#[cfg(test)]
#[path = "log_db_filter_tests.rs"]
mod filter_tests;
#[cfg(test)]
#[path = "log_db_failure_tests.rs"]
mod failure_tests;
#[cfg(test)]
mod tests {
use std::io;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tracing_subscriber::filter::Targets;
use tracing_subscriber::fmt::writer::MakeWriter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use super::*;
fn temp_codex_home() -> std::path::PathBuf {
std::env::temp_dir().join(format!("codex-state-log-db-{}", Uuid::new_v4()))
}
async fn wait_for_log_count(runtime: &StateRuntime, expected: usize) -> Vec<crate::LogRow> {
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
loop {
let rows = runtime
.query_logs(&crate::LogQuery::default())
.await
.expect("query logs");
if rows.len() == expected {
return rows;
}
assert!(
tokio::time::Instant::now() < deadline,
"timed out waiting for {expected} logs; saw {}",
rows.len()
);
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
}
fn test_entry(message: &str) -> LogEntry {
LogEntry {
ts: 1,
ts_nanos: 2,
level: "INFO".to_string(),
target: "test".to_string(),
message: Some(message.to_string()),
feedback_log_body: Some(message.to_string()),
thread_id: Some("thread-1".to_string()),
process_uuid: Some("process-1".to_string()),
module_path: Some("module".to_string()),
file: Some("file.rs".to_string()),
line: Some(7),
}
}
#[derive(Clone, Default)]
pub(super) struct SharedWriter {
bytes: Arc<Mutex<Vec<u8>>>,
}
impl SharedWriter {
pub(super) fn snapshot(&self) -> String {
String::from_utf8(self.bytes.lock().expect("writer mutex poisoned").clone())
.expect("valid utf-8")
}
}
pub(super) struct SharedWriterGuard {
bytes: Arc<Mutex<Vec<u8>>>,
}
impl LogWriteFailureReporter for SharedWriter {
fn report_failure(&self, diagnostic: &str) {
std::io::Write::write_all(&mut self.make_writer(), diagnostic.as_bytes())
.expect("write diagnostic to test buffer");
}
}
impl<'a> MakeWriter<'a> for SharedWriter {
type Writer = SharedWriterGuard;
fn make_writer(&'a self) -> Self::Writer {
SharedWriterGuard {
bytes: Arc::clone(&self.bytes),
}
}
}
impl io::Write for SharedWriterGuard {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.bytes
.lock()
.expect("writer mutex poisoned")
.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn sqlite_feedback_logs_match_feedback_formatter_shape() {
let codex_home = temp_codex_home();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let writer = SharedWriter::default();
let layer = start(runtime.clone(), Arc::new(SharedWriter::default()));
let subscriber = tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_writer(writer.clone())
.with_ansi(false)
.with_target(false)
.with_filter(default_filter()),
)
.with(layer.clone().with_filter(default_filter()));
let guard = subscriber.set_default();
tracing::trace!("threadless-before");
tracing::info_span!("feedback-thread", thread_id = "thread-1", turn = 1).in_scope(|| {
tracing::info!(foo = 2, "thread-scoped");
});
tracing::debug!("threadless-after");
layer.flush().await;
drop(guard);
let feedback_logs = writer.snapshot();
let without_timestamps = |logs: &str| {
logs.lines()
.map(|line| match line.split_once(' ') {
Some((_, rest)) => rest,
None => line,
})
.collect::<Vec<_>>()
.join("\n")
};
let sqlite_logs = String::from_utf8(
runtime
.query_feedback_logs("thread-1")
.await
.expect("query feedback logs"),
)
.expect("valid utf-8");
assert_eq!(
without_timestamps(&sqlite_logs),
without_timestamps(&feedback_logs)
);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn flush_persists_logs_for_query() {
let codex_home = temp_codex_home();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let layer = start(runtime.clone(), Arc::new(SharedWriter::default()));
let guard = tracing_subscriber::registry()
.with(
layer
.clone()
.with_filter(Targets::new().with_default(tracing::Level::TRACE)),
)
.set_default();
tracing::info!("buffered-log");
layer.flush().await;
drop(guard);
let after_flush = runtime
.query_logs(&crate::LogQuery::default())
.await
.expect("query logs after flush");
assert_eq!(after_flush.len(), 1);
assert_eq!(after_flush[0].message.as_deref(), Some("buffered-log"));
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn configured_batch_size_flushes_without_explicit_flush() {
let codex_home = temp_codex_home();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let layer = LogDbLayer::start_with_config(
runtime.clone(),
Arc::new(SharedWriter::default()),
LogSinkQueueConfig {
queue_capacity: 8,
batch_size: 2,
flush_interval: std::time::Duration::from_secs(60),
},
);
let guard = tracing_subscriber::registry()
.with(
layer
.clone()
.with_filter(Targets::new().with_default(tracing::Level::TRACE)),
)
.set_default();
tracing::info!("first-batch-log");
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
assert_eq!(
runtime
.query_logs(&crate::LogQuery::default())
.await
.expect("query logs before batch fills")
.len(),
0
);
tracing::info!("second-batch-log");
let after_batch = wait_for_log_count(&runtime, /*expected*/ 2).await;
drop(guard);
assert_eq!(
after_batch
.iter()
.map(|row| row.message.as_deref())
.collect::<Vec<_>>(),
vec![Some("first-batch-log"), Some("second-batch-log")]
);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn configured_flush_interval_persists_buffered_logs() {
let codex_home = temp_codex_home();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let layer = LogDbLayer::start_with_config(
runtime.clone(),
Arc::new(SharedWriter::default()),
LogSinkQueueConfig {
queue_capacity: 8,
batch_size: 128,
flush_interval: std::time::Duration::from_millis(10),
},
);
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
let guard = tracing_subscriber::registry()
.with(
layer
.clone()
.with_filter(Targets::new().with_default(tracing::Level::TRACE)),
)
.set_default();
tracing::info!("interval-log");
let after_interval = wait_for_log_count(&runtime, /*expected*/ 1).await;
drop(guard);
assert_eq!(after_interval[0].message.as_deref(), Some("interval-log"));
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn event_queue_drops_new_entries_when_full() {
let (sender, mut receiver) = mpsc::channel(1);
let layer = LogDbLayer {
sender,
has_write_failure: Arc::new(AtomicBool::new(false)),
failure_reporter: Arc::new(RwLock::new(Arc::new(SharedWriter::default()))),
process_uuid: "process-1".to_string(),
};
layer.try_send(test_entry("first-queued-log"));
layer.try_send(test_entry("dropped-log"));
match receiver.try_recv().expect("first entry queued") {
LogDbCommand::Entry(entry) => {
assert_eq!(entry.message.as_deref(), Some("first-queued-log"));
}
LogDbCommand::Flush(_) => panic!("expected queued entry"),
}
assert!(receiver.try_recv().is_err());
}
#[tokio::test]
async fn flush_waits_for_queue_capacity_and_receiver_processing() {
let (sender, mut receiver) = mpsc::channel(1);
let layer = LogDbLayer {
sender,
has_write_failure: Arc::new(AtomicBool::new(false)),
failure_reporter: Arc::new(RwLock::new(Arc::new(SharedWriter::default()))),
process_uuid: "process-1".to_string(),
};
layer.try_send(test_entry("queued-before-flush"));
let mut flush_task = tokio::spawn({
let layer = layer.clone();
async move {
layer.flush().await;
}
});
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
assert!(!flush_task.is_finished());
match receiver.recv().await.expect("queued entry") {
LogDbCommand::Entry(entry) => {
assert_eq!(entry.message.as_deref(), Some("queued-before-flush"));
}
LogDbCommand::Flush(_) => panic!("expected queued entry"),
}
match receiver.recv().await.expect("flush command") {
LogDbCommand::Flush(reply) => {
assert!(!flush_task.is_finished());
let _ = reply.send(());
}
LogDbCommand::Entry(_) => panic!("expected flush command"),
}
tokio::time::timeout(std::time::Duration::from_secs(1), &mut flush_task)
.await
.expect("flush task completes")
.expect("flush task succeeds");
}
}

View File

@@ -0,0 +1,86 @@
//! Regression coverage for flush diagnostics, recovery, and sink recursion prevention.
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use super::tests::SharedWriter;
use super::*;
#[tokio::test]
async fn failed_batch_is_reported_once_and_later_writes_recover() {
let codex_home =
std::env::temp_dir().join(format!("codex-state-log-failure-{}", Uuid::new_v4()));
let _cleanup = scopeguard::guard(codex_home.clone(), |codex_home| {
let _ = std::fs::remove_dir_all(codex_home);
});
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
.await
.expect("initialize runtime");
let pool = sqlite
.open_read_write_pool(&sqlite.logs_db_path())
.await
.expect("open logs database");
sqlx::query("CREATE TRIGGER fail_log_insert BEFORE INSERT ON logs BEGIN SELECT RAISE(ABORT, 'synthetic-secret'); END")
.execute(&pool)
.await
.expect("install failure trigger");
let diagnostics = SharedWriter::default();
let layer = start(runtime.clone(), Arc::new(diagnostics.clone()));
assert_eq!(layer.has_write_failure(), false);
let writer = SharedWriter::default();
let guard = tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_writer(writer.clone())
.without_time()
.with_level(/*display_level*/ false)
.with_target(/*display_target*/ false)
.with_ansi(/*ansi*/ false)
.with_filter(LevelFilter::ERROR),
)
// No diagnostic filter is needed: the diagnostic writer bypasses tracing.
.with(layer.clone())
.set_default();
tracing::info!("sensitive log body");
layer.flush().await;
assert_eq!(layer.has_write_failure(), true);
let diagnostic = diagnostics.snapshot();
assert_eq!(
diagnostic.split_once(" ERROR ").unwrap().1,
"failed to flush logs to SQLite error=\"constraint\" entries=1\n"
);
assert_eq!(writer.snapshot(), "");
// Reporting the first failure must not enqueue a second failing batch.
layer.flush().await;
assert_eq!(diagnostics.snapshot(), diagnostic);
assert_eq!(writer.snapshot(), "");
sqlx::query("DROP TRIGGER fail_log_insert")
.execute(&pool)
.await
.expect("remove failure trigger");
tracing::info!("recovered log");
layer.flush().await;
assert_eq!(diagnostics.snapshot(), diagnostic);
assert_eq!(writer.snapshot(), "");
assert_eq!(layer.has_write_failure(), true);
drop(guard);
let logs = runtime
.query_logs(&crate::LogQuery::default())
.await
.expect("query logs");
assert_eq!(
logs.iter()
.map(|log| log.message.as_deref())
.collect::<Vec<_>>(),
vec![Some("recovered log")]
);
pool.close().await;
runtime.close().await;
}

View File

@@ -0,0 +1,174 @@
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use uuid::Uuid;
use super::*;
#[tokio::test]
async fn sqlite_sink_filters_noisy_targets_without_dropping_useful_diagnostics() {
let codex_home =
std::env::temp_dir().join(format!("codex-state-log-db-filter-{}", Uuid::new_v4()));
let _cleanup = scopeguard::guard(codex_home.clone(), |codex_home| {
let _ = std::fs::remove_dir_all(codex_home);
});
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let layer = start(
runtime.clone(),
Arc::new(super::tests::SharedWriter::default()),
);
let guard = tracing_subscriber::registry()
.with(layer.clone().with_filter(default_filter()))
.set_default();
tracing::trace!(target: "opentelemetry_sdk", "dropped-trace");
tracing::debug!(target: "opentelemetry_sdk", "dropped-debug");
tracing::info!(target: "opentelemetry_sdk", "retained-info");
tracing::warn!(target: "sqlx::query", "dropped-slow-query-warning");
tracing::warn!(target: "sqlx::pool::acquire", "dropped-slow-acquire-warning");
tracing::warn!(target: "sqlx::other", "dropped-sqlx-warning");
tracing::info!(target: "sqlx_application", "retained-unrelated-target");
tracing::debug!(target: "opentelemetry-otlp", "dropped-otlp-export");
tracing::error!(target: "opentelemetry-http", "dropped-http-export");
tracing::trace!(target: "h2::proto::streams", "dropped-http2-trace");
tracing::debug!(target: "tonic::transport::channel", "dropped-grpc-transport-debug");
tracing::debug!(target: "tower::buffer::worker", "dropped-grpc-buffer-debug");
tracing::warn!(
target: "h2::proto::ping_pong",
"recv PING ack that we never sent: {:?}",
"synthetic-ack"
);
tracing::warn!(target: "h2::proto::ping_pong", "retained-http2-ping-warning");
tracing::warn!(target: "h2::proto::streams", "retained-http2-warning");
tracing::debug!(target: "rmcp::transport", "dropped-rmcp-debug");
tracing::info!(target: "rmcp::transport", "retained-rmcp-info");
tracing::trace!(target: "tokio_graceful::guard", "dropped-guard-trace");
tracing::debug!(target: "tokio_graceful::guard", "retained-guard-debug");
tracing::trace!(target: "tokio_graceful::trigger", "dropped-trigger-trace");
tracing::debug!(target: "tokio_graceful::trigger", "retained-trigger-debug");
tracing::trace!(target: "tokio_graceful::shutdown", "retained-shutdown-trace");
tracing::debug!(
target: "codex_rmcp_client::oauth",
"dropped-codex-rmcp-client-debug"
);
tracing::info!(
target: "codex_rmcp_client::oauth",
"retained-codex-rmcp-client-info"
);
tracing::trace!(target: "codex_http_client::transport", "dropped-request-body");
tracing::debug!(target: "codex_http_client::transport", "retained-request-diagnostic");
tracing::trace!(target: "codex_api::sse", "dropped-sse-parent");
tracing::trace!(target: "codex_api::sse::responses", "dropped-sse-payload");
tracing::debug!(target: "codex_api::sse::responses", "retained-sse-diagnostic");
tracing::trace!(target: "codex_state", "retained-trace");
tracing::trace!(
target: "codex_tui::streaming::controller",
"dropped-controller-trace"
);
tracing::debug!(
target: "codex_tui::streaming::controller",
"retained-controller-debug"
);
tracing::trace!(
target: "codex_tui::streaming::table_holdback",
"dropped-table-holdback-trace"
);
tracing::debug!(
target: "codex_tui::streaming::table_holdback",
"retained-table-holdback-debug"
);
tracing::trace!(
target: "codex_tui::streaming::commit_tick",
"retained-commit-tick-trace"
);
tracing::trace!(
target: "codex_api::responses_websocket_timing",
payload = "complete timing payload",
"dropped-websocket-timing"
);
layer.flush().await;
drop(guard);
let logs = runtime
.query_logs(&crate::LogQuery::default())
.await
.expect("query logs after flush");
assert_eq!(
logs.iter()
.map(|row| (
row.level.as_str(),
row.target.as_str(),
row.message.as_deref()
))
.collect::<Vec<_>>(),
vec![
("INFO", "opentelemetry_sdk", Some("retained-info")),
(
"INFO",
"sqlx_application",
Some("retained-unrelated-target")
),
(
"WARN",
"h2::proto::ping_pong",
Some("retained-http2-ping-warning")
),
("WARN", "h2::proto::streams", Some("retained-http2-warning")),
("INFO", "rmcp::transport", Some("retained-rmcp-info")),
(
"DEBUG",
"tokio_graceful::guard",
Some("retained-guard-debug")
),
(
"DEBUG",
"tokio_graceful::trigger",
Some("retained-trigger-debug")
),
(
"TRACE",
"tokio_graceful::shutdown",
Some("retained-shutdown-trace")
),
(
"INFO",
"codex_rmcp_client::oauth",
Some("retained-codex-rmcp-client-info")
),
(
"DEBUG",
"codex_http_client::transport",
Some("retained-request-diagnostic")
),
(
"DEBUG",
"codex_api::sse::responses",
Some("retained-sse-diagnostic")
),
("TRACE", "codex_state", Some("retained-trace")),
(
"DEBUG",
"codex_tui::streaming::controller",
Some("retained-controller-debug"),
),
(
"DEBUG",
"codex_tui::streaming::table_holdback",
Some("retained-table-holdback-debug"),
),
(
"TRACE",
"codex_tui::streaming::commit_tick",
Some("retained-commit-tick-trace"),
),
]
);
}

View File

@@ -0,0 +1,147 @@
use std::sync::Mutex;
use std::time::Duration;
use pretty_assertions::assert_eq;
use super::DbTelemetry;
use super::record_log_queue_drop;
use super::record_log_write;
use crate::LOG_QUEUE_DROPPED_METRIC;
use crate::LOG_WRITE_BYTES_METRIC;
use crate::LOG_WRITE_DURATION_METRIC;
use crate::LOG_WRITE_ENTRIES_METRIC;
use crate::LOG_WRITE_MAX_ENTRY_BYTES_METRIC;
use crate::LOG_WRITE_METRIC;
use crate::LogEntry;
type MetricEvent = (String, i64, Vec<(String, String)>);
#[derive(Default)]
struct TestTelemetry(Mutex<Vec<MetricEvent>>);
impl TestTelemetry {
fn record(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
self.0.lock().expect("telemetry lock").push((
name.to_string(),
value,
tags.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect(),
));
}
}
impl DbTelemetry for TestTelemetry {
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
self.record(name, inc, tags);
}
fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
self.record(name, value, tags);
}
fn record_duration(&self, name: &str, duration: Duration, tags: &[(&str, &str)]) {
self.record(name, duration.as_millis() as i64, tags);
}
}
fn log_entry(message: &str, feedback_log_body: Option<&str>) -> LogEntry {
LogEntry {
ts: 1,
ts_nanos: 2,
level: "INFO".to_string(),
target: "t".to_string(),
message: Some(message.to_string()),
feedback_log_body: feedback_log_body.map(str::to_string),
thread_id: None,
process_uuid: None,
module_path: Some("m".to_string()),
file: Some("f".to_string()),
line: None,
}
}
fn expected_events(metrics: &[(&str, i64)], tags: &[(&str, &str)]) -> Vec<MetricEvent> {
metrics
.iter()
.map(|(name, value)| {
(
(*name).to_string(),
*value,
tags.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect(),
)
})
.collect()
}
#[test]
fn records_successful_log_write_duration_batch_size_and_largest_entry() {
let telemetry = TestTelemetry::default();
let entries = [
log_entry("abc", /*feedback_log_body*/ None),
log_entry("ignored", Some("longer")),
];
record_log_write(
Some(&telemetry),
Duration::from_millis(17),
&entries,
&Ok(()),
);
assert_eq!(
*telemetry.0.lock().expect("telemetry lock"),
expected_events(
&[
(LOG_WRITE_METRIC, 1),
(LOG_WRITE_DURATION_METRIC, 17),
(LOG_WRITE_BYTES_METRIC, 23),
(LOG_WRITE_ENTRIES_METRIC, 2),
(LOG_WRITE_MAX_ENTRY_BYTES_METRIC, 13),
],
&[("status", "success"), ("error", "none")],
),
);
}
#[test]
fn records_failed_log_write_with_bounded_sqlite_error() {
let telemetry = TestTelemetry::default();
let entries = [log_entry("abc", /*feedback_log_body*/ None)];
let result = Err(anyhow::Error::from(sqlx::Error::PoolTimedOut));
record_log_write(
Some(&telemetry),
Duration::from_millis(35),
&entries,
&result,
);
assert_eq!(
*telemetry.0.lock().expect("telemetry lock"),
expected_events(
&[
(LOG_WRITE_METRIC, 1),
(LOG_WRITE_DURATION_METRIC, 35),
(LOG_WRITE_BYTES_METRIC, 10),
(LOG_WRITE_ENTRIES_METRIC, 1),
(LOG_WRITE_MAX_ENTRY_BYTES_METRIC, 10),
],
&[("status", "failed"), ("error", "pool_timeout")],
),
);
}
#[test]
fn records_queue_drop_reason() {
let telemetry = TestTelemetry::default();
record_log_queue_drop("full", Some(&telemetry));
assert_eq!(
*telemetry.0.lock().expect("telemetry lock"),
expected_events(&[(LOG_QUEUE_DROPPED_METRIC, 1)], &[("reason", "full")]),
);
}

View File

@@ -0,0 +1,123 @@
use std::borrow::Cow;
use crate::sqlite::SqliteWriteQueryExt;
use sqlx::migrate::Migrator;
use sqlx_sqlite::SqlitePool;
pub(crate) static STATE_MIGRATOR: Migrator = sqlx_macros::migrate!("./migrations");
pub(crate) static LOGS_MIGRATOR: Migrator = sqlx_macros::migrate!("./logs_migrations");
pub(crate) static GOALS_MIGRATOR: Migrator = sqlx_macros::migrate!("./goals_migrations");
pub(crate) static MEMORIES_MIGRATOR: Migrator = sqlx_macros::migrate!("./memory_migrations");
pub(crate) static QUEUE_MIGRATOR: Migrator = sqlx_macros::migrate!("./queue_migrations");
pub(crate) static THREAD_HISTORY_MIGRATOR: Migrator =
sqlx_macros::migrate!("./thread_history_migrations");
/// Allow an older Codex binary to open a database that has already been
/// migrated by a newer binary running in parallel.
///
/// We intentionally ignore applied migration versions that are newer than the
/// embedded migration set. Known migration versions are still validated by
/// checksum, so this only relaxes the "database is ahead of me" case.
fn runtime_migrator(base: &'static Migrator) -> Migrator {
Migrator {
migrations: Cow::Borrowed(base.migrations.as_ref()),
ignore_missing: true,
locking: base.locking,
no_tx: base.no_tx,
table_name: base.table_name.clone(),
create_schemas: base.create_schemas.clone(),
}
}
pub(crate) fn runtime_state_migrator() -> Migrator {
runtime_migrator(&STATE_MIGRATOR)
}
pub(crate) fn runtime_logs_migrator() -> Migrator {
runtime_migrator(&LOGS_MIGRATOR)
}
pub(crate) fn runtime_goals_migrator() -> Migrator {
runtime_migrator(&GOALS_MIGRATOR)
}
pub(crate) fn runtime_memories_migrator() -> Migrator {
runtime_migrator(&MEMORIES_MIGRATOR)
}
pub(crate) fn runtime_queue_migrator() -> Migrator {
runtime_migrator(&QUEUE_MIGRATOR)
}
// The paginated history projector will call this when it takes ownership of opening the database.
#[allow(dead_code)]
pub(crate) fn runtime_thread_history_migrator() -> Migrator {
runtime_migrator(&THREAD_HISTORY_MIGRATOR)
}
pub(crate) async fn repair_legacy_recency_migration_version(
pool: &SqlitePool,
migrator: &Migrator,
) -> anyhow::Result<()> {
let Some(recency_migration) = migrator
.migrations
.iter()
.find(|migration| migration.version == 39)
else {
return Ok(());
};
let migrations_table_exists = sqlx::query_scalar::<_, i64>(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = '_sqlx_migrations'",
)
.fetch_optional(pool)
.await?
.is_some();
if !migrations_table_exists {
return Ok(());
}
let legacy_recency_needs_repair = sqlx::query_scalar::<_, i64>(
r#"
SELECT 1
FROM _sqlx_migrations
WHERE version = ?
AND checksum = ?
AND NOT EXISTS (
SELECT 1 FROM _sqlx_migrations WHERE version = ?
)
"#,
)
.bind(38_i64)
.bind(recency_migration.checksum.as_ref())
.bind(recency_migration.version)
.fetch_optional(pool)
.await?
.is_some();
if !legacy_recency_needs_repair {
return Ok(());
}
sqlx::query(
r#"
UPDATE _sqlx_migrations
SET version = ?, description = ?
WHERE version = ?
AND checksum = ?
AND NOT EXISTS (
SELECT 1 FROM _sqlx_migrations WHERE version = ?
)
"#,
)
.bind(recency_migration.version)
.bind(recency_migration.description.as_ref())
.bind(38_i64)
.bind(recency_migration.checksum.as_ref())
.bind(recency_migration.version)
.execute_with_busy_retry(pool)
.await?;
Ok(())
}
#[cfg(test)]
#[path = "migrations_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,73 @@
use anyhow::Result;
use chrono::DateTime;
use chrono::Utc;
use sqlx::Row;
use sqlx::sqlite::SqliteRow;
/// Persisted lifecycle state for rollout metadata backfill.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackfillState {
/// Current lifecycle status.
pub status: BackfillStatus,
/// Last processed rollout watermark.
pub last_watermark: Option<String>,
/// Last successful completion time.
pub last_success_at: Option<DateTime<Utc>>,
}
impl Default for BackfillState {
fn default() -> Self {
Self {
status: BackfillStatus::Pending,
last_watermark: None,
last_success_at: None,
}
}
}
impl BackfillState {
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
let status: String = row.try_get("status")?;
let last_success_at = row
.try_get::<Option<i64>, _>("last_success_at")?
.map(epoch_seconds_to_datetime)
.transpose()?;
Ok(Self {
status: BackfillStatus::parse(status.as_str())?,
last_watermark: row.try_get("last_watermark")?,
last_success_at,
})
}
}
/// Backfill lifecycle status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackfillStatus {
Pending,
Running,
Complete,
}
impl BackfillStatus {
pub const fn as_str(self) -> &'static str {
match self {
BackfillStatus::Pending => "pending",
BackfillStatus::Running => "running",
BackfillStatus::Complete => "complete",
}
}
pub fn parse(value: &str) -> Result<Self> {
match value {
"pending" => Ok(Self::Pending),
"running" => Ok(Self::Running),
"complete" => Ok(Self::Complete),
_ => Err(anyhow::anyhow!("invalid backfill status: {value}")),
}
}
}
fn epoch_seconds_to_datetime(secs: i64) -> Result<DateTime<Utc>> {
DateTime::<Utc>::from_timestamp(secs, 0)
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp: {secs}"))
}

View File

@@ -0,0 +1,11 @@
use strum::AsRefStr;
use strum::Display;
use strum::EnumString;
/// Status attached to a directional thread-spawn edge.
#[derive(Debug, Clone, Copy, PartialEq, Eq, AsRefStr, Display, EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum DirectionalThreadSpawnEdgeStatus {
Open,
Closed,
}

View File

@@ -0,0 +1,57 @@
use serde::Serialize;
use sqlx_macros::FromRow;
#[derive(Clone, Debug, Serialize)]
pub struct LogEntry {
pub ts: i64,
pub ts_nanos: i64,
pub level: String,
pub target: String,
pub message: Option<String>,
pub feedback_log_body: Option<String>,
pub thread_id: Option<String>,
pub process_uuid: Option<String>,
pub module_path: Option<String>,
pub file: Option<String>,
pub line: Option<i64>,
}
impl LogEntry {
pub(crate) fn estimated_bytes(&self) -> i64 {
let feedback_log_body = self.feedback_log_body.as_ref().or(self.message.as_ref());
feedback_log_body.map_or(0, String::len) as i64
+ self.level.len() as i64
+ self.target.len() as i64
+ self.module_path.as_ref().map_or(0, String::len) as i64
+ self.file.as_ref().map_or(0, String::len) as i64
}
}
#[derive(Clone, Debug, FromRow)]
pub struct LogRow {
pub id: i64,
pub ts: i64,
pub ts_nanos: i64,
pub level: String,
pub target: String,
pub message: Option<String>,
pub thread_id: Option<String>,
pub process_uuid: Option<String>,
pub file: Option<String>,
pub line: Option<i64>,
}
#[derive(Clone, Debug, Default)]
pub struct LogQuery {
pub levels_upper: Vec<String>,
pub from_ts: Option<i64>,
pub to_ts: Option<i64>,
pub module_like: Vec<String>,
pub file_like: Vec<String>,
pub thread_ids: Vec<String>,
pub search: Option<String>,
pub include_threadless: bool,
pub after_id: Option<i64>,
pub limit: Option<usize>,
pub descending: bool,
}

View File

@@ -0,0 +1,69 @@
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::ThreadId;
use std::path::PathBuf;
use super::ThreadMetadata;
/// Stored stage-1 memory extraction output for a single thread.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stage1Output {
pub thread_id: ThreadId,
pub rollout_path: PathBuf,
pub source_updated_at: DateTime<Utc>,
pub raw_memory: String,
pub rollout_summary: String,
pub rollout_slug: Option<String>,
pub cwd: PathBuf,
pub git_branch: Option<String>,
pub generated_at: DateTime<Utc>,
}
/// Result of trying to claim a stage-1 memory extraction job.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Stage1JobClaimOutcome {
/// The caller owns the job and should continue with extraction.
Claimed { ownership_token: String },
/// Existing output is already newer than or equal to the source rollout.
SkippedUpToDate,
/// Another worker currently owns a fresh lease for this job.
SkippedRunning,
/// The job is in backoff and should not be retried yet.
SkippedRetryBackoff,
/// The job has exhausted retries and should not be retried automatically.
SkippedRetryExhausted,
}
/// Claimed stage-1 job with thread metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stage1JobClaim {
pub thread: ThreadMetadata,
pub ownership_token: String,
}
#[derive(Debug, Clone, Copy)]
pub struct Stage1StartupClaimParams<'a> {
pub scan_limit: usize,
pub max_claimed: usize,
pub max_age_days: i64,
pub min_rollout_idle_hours: i64,
pub allowed_sources: &'a [String],
pub lease_seconds: i64,
}
/// Result of trying to claim a phase-2 consolidation job.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Phase2JobClaimOutcome {
/// The caller owns the global lock and may inspect the memory workspace.
Claimed {
ownership_token: String,
/// Snapshot of `input_watermark` at claim time.
input_watermark: i64,
},
/// The global job is in retry backoff.
SkippedRetryUnavailable,
/// The global job completed recently enough that consolidation is cooling down.
SkippedCooldown,
/// Another worker currently owns a fresh global consolidation lease.
SkippedRunning,
}

View File

@@ -0,0 +1,59 @@
mod backfill_state;
mod graph;
mod log;
mod memories;
mod project;
mod queued_item;
mod rollout_migration_state;
mod thread_attachment;
mod thread_goal;
mod thread_metadata;
pub use backfill_state::BackfillState;
pub use backfill_state::BackfillStatus;
pub use graph::DirectionalThreadSpawnEdgeStatus;
pub use log::LogEntry;
pub use log::LogQuery;
pub use log::LogRow;
pub use memories::Phase2JobClaimOutcome;
pub use memories::Stage1JobClaim;
pub use memories::Stage1JobClaimOutcome;
pub use memories::Stage1Output;
pub use memories::Stage1StartupClaimParams;
pub use project::CreatedProject;
pub use project::Project;
pub use project::ProjectRoot;
pub use project::ProjectSortKey;
pub use project::ProjectsPage;
pub use queued_item::QueuedUserSubmissionRecord;
pub use rollout_migration_state::RolloutMigrationCursor;
pub use rollout_migration_state::RolloutMigrationSkippedRollout;
pub use rollout_migration_state::RolloutMigrationState;
pub use thread_attachment::AddThreadAttachmentOutcome;
pub use thread_attachment::RemoveThreadAttachmentOutcome;
pub use thread_attachment::ThreadAttachment;
pub use thread_attachment::ThreadAttachmentArchiveFilter;
pub use thread_attachment::ThreadAttachmentOwner;
pub use thread_attachment::ThreadAttachmentOwnerPage;
pub use thread_attachment::ThreadAttachmentPage;
pub use thread_goal::ThreadGoal;
pub use thread_goal::ThreadGoalStatus;
pub use thread_metadata::Anchor;
pub use thread_metadata::BackfillStats;
pub use thread_metadata::ExtractionOutcome;
pub use thread_metadata::SortDirection;
pub use thread_metadata::SortKey;
pub use thread_metadata::ThreadMetadata;
pub use thread_metadata::ThreadMetadataBuilder;
pub use thread_metadata::ThreadRelationFilter;
pub use thread_metadata::ThreadSection;
pub use thread_metadata::ThreadSectionAppearance;
pub use thread_metadata::ThreadSectionsPage;
pub use thread_metadata::ThreadsPage;
pub(crate) use thread_goal::ThreadGoalRow;
pub(crate) use thread_metadata::ThreadRow;
pub(crate) use thread_metadata::anchor_from_item;
pub(crate) use thread_metadata::datetime_to_epoch_millis;
pub(crate) use thread_metadata::datetime_to_epoch_seconds;
pub(crate) use thread_metadata::epoch_millis_to_datetime;

View File

@@ -0,0 +1,39 @@
use std::collections::BTreeMap;
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectRoot {
pub path: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Project {
pub id: String,
pub name: String,
pub roots: Vec<ProjectRoot>,
pub metadata: BTreeMap<String, String>,
pub position: i64,
pub created_at_ms: i64,
pub updated_at_ms: i64,
pub recency_at_ms: Option<i64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectSortKey {
Position,
RecencyAt,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreatedProject {
pub project: Project,
pub created: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectsPage {
pub projects: Vec<Project>,
pub next_cursor: Option<String>,
}

View File

@@ -0,0 +1,22 @@
use anyhow::Result;
use codex_protocol::ThreadId;
use sqlx::Row;
use sqlx::sqlite::SqliteRow;
/// One durable, ordered user submission for a thread.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueuedUserSubmissionRecord {
pub id: String,
pub thread_id: ThreadId,
pub payload: String,
}
impl QueuedUserSubmissionRecord {
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
Ok(Self {
id: row.try_get("id")?,
thread_id: ThreadId::try_from(row.try_get::<String, _>("thread_id")?)?,
payload: row.try_get("payload_json")?,
})
}
}

View File

@@ -0,0 +1,67 @@
//! SQLite-backed bookkeeping types shared by rollout migrations.
//!
//! A migration cursor says “everything through this creation-ordered thread was checked.” A
//! skipped rollout stores enough file fingerprint information to tell whether a previously
//! unmigratable rollout is still unchanged.
//!
//! These types are intentionally generic so future rollout migrations can reuse the same state
//! shape without depending on legacy -> paginated policy.
use anyhow::Result;
use sqlx::Row;
use sqlx::sqlite::SqliteRow;
/// Creation-ordered thread frontier checked by one rollout migration.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct RolloutMigrationCursor {
pub thread_created_at: i64,
pub thread_id: String,
}
/// Persisted progress for one rollout migration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RolloutMigrationState {
pub last_checked_thread: Option<RolloutMigrationCursor>,
}
impl RolloutMigrationState {
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
let thread_created_at = row.try_get("last_checked_thread_created_at")?;
let thread_id = row.try_get("last_checked_thread_id")?;
let last_checked_thread = match (thread_created_at, thread_id) {
(Some(thread_created_at), Some(thread_id)) => Some(RolloutMigrationCursor {
thread_created_at,
thread_id,
}),
(None, None) => None,
_ => {
return Err(anyhow::anyhow!(
"rollout migration state has incomplete last checked thread"
));
}
};
Ok(Self {
last_checked_thread,
})
}
}
/// An unchanged rollout that one migration can safely skip.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RolloutMigrationSkippedRollout {
pub rollout_path: String,
pub rollout_size_bytes: i64,
pub rollout_modified_at_ns: i64,
pub skip_reason: String,
}
impl RolloutMigrationSkippedRollout {
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
Ok(Self {
rollout_path: row.try_get("rollout_path")?,
rollout_size_bytes: row.try_get("rollout_size_bytes")?,
rollout_modified_at_ns: row.try_get("rollout_modified_at_ns")?,
skip_reason: row.try_get("skip_reason")?,
})
}
}

View File

@@ -0,0 +1,70 @@
//! Thread attachment records and outcomes; membership changes independently of resource contents.
use codex_protocol::ThreadId;
use serde_json::Value;
/// A bounded attachment durably associated with one thread.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadAttachment {
/// Stable, server-assigned UUIDv7 attachment identity.
pub id: String,
/// Thread that owns this attachment.
pub thread_id: ThreadId,
/// Client-defined attachment category.
pub attachment_type: String,
/// Client-defined stable identity within the owning thread and attachment category.
pub identity_key: String,
/// Bounded, client-defined attachment metadata.
pub payload: Value,
/// Integer Unix timestamp in seconds when the attachment was attached.
pub created_at: i64,
}
/// Result of attaching one uniquely identified thread attachment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AddThreadAttachmentOutcome {
/// A new durable attachment was created.
Created(ThreadAttachment),
/// The attachment was already attached; its payload and creation time are unchanged.
Existing(ThreadAttachment),
}
/// Result of removing a thread attachment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RemoveThreadAttachmentOutcome {
/// An attached attachment was removed.
Removed(ThreadAttachment),
/// No attachment with the requested identity was attached.
NotFound,
}
/// One deterministically ordered page of attachments across selected threads.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadAttachmentPage {
/// Attachments ordered by thread identity, creation time, and attachment identity.
pub attachments: Vec<ThreadAttachment>,
/// Opaque cursor for the next page, or `None` when the selection is exhausted.
pub next_cursor: Option<String>,
}
/// Selects attachment owners by their persisted archive state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThreadAttachmentArchiveFilter {
All,
NonArchived,
Archived,
}
/// A thread whose current attachment membership contains the requested resource.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadAttachmentOwner {
pub thread_id: ThreadId,
pub archived: bool,
}
/// One page of attachment owners, ordered by thread ID.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadAttachmentOwnerPage {
pub threads: Vec<ThreadAttachmentOwner>,
pub next_cursor: Option<String>,
}

View File

@@ -0,0 +1,117 @@
use anyhow::Result;
use anyhow::anyhow;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::ThreadId;
use serde::Serialize;
use sqlx::Row;
use sqlx::sqlite::SqliteRow;
use super::epoch_millis_to_datetime;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ThreadGoalStatus {
Active,
Paused,
Blocked,
UsageLimited,
BudgetLimited,
Complete,
}
impl ThreadGoalStatus {
pub fn as_str(self) -> &'static str {
match self {
Self::Active => "active",
Self::Paused => "paused",
Self::Blocked => "blocked",
Self::UsageLimited => "usage_limited",
Self::BudgetLimited => "budget_limited",
Self::Complete => "complete",
}
}
pub fn is_active(self) -> bool {
self == Self::Active
}
pub fn is_terminal(self) -> bool {
matches!(self, Self::BudgetLimited | Self::Complete)
}
}
impl TryFrom<&str> for ThreadGoalStatus {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self> {
match value {
"active" => Ok(Self::Active),
"paused" => Ok(Self::Paused),
"blocked" => Ok(Self::Blocked),
"usage_limited" => Ok(Self::UsageLimited),
"budget_limited" => Ok(Self::BudgetLimited),
"complete" => Ok(Self::Complete),
other => Err(anyhow!("unknown thread goal status `{other}`")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadGoal {
pub thread_id: ThreadId,
pub goal_id: String,
pub objective: String,
pub status: ThreadGoalStatus,
pub token_budget: Option<i64>,
pub tokens_used: i64,
pub time_used_seconds: i64,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
pub(crate) struct ThreadGoalRow {
pub thread_id: String,
pub goal_id: String,
pub objective: String,
pub status: String,
pub token_budget: Option<i64>,
pub tokens_used: i64,
pub time_used_seconds: i64,
pub created_at_ms: i64,
pub updated_at_ms: i64,
}
impl ThreadGoalRow {
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
Ok(Self {
thread_id: row.try_get("thread_id")?,
goal_id: row.try_get("goal_id")?,
objective: row.try_get("objective")?,
status: row.try_get("status")?,
token_budget: row.try_get("token_budget")?,
tokens_used: row.try_get("tokens_used")?,
time_used_seconds: row.try_get("time_used_seconds")?,
created_at_ms: row.try_get("created_at_ms")?,
updated_at_ms: row.try_get("updated_at_ms")?,
})
}
}
impl TryFrom<ThreadGoalRow> for ThreadGoal {
type Error = anyhow::Error;
fn try_from(row: ThreadGoalRow) -> Result<Self> {
Ok(Self {
thread_id: ThreadId::try_from(row.thread_id)?,
goal_id: row.goal_id,
objective: row.objective,
status: ThreadGoalStatus::try_from(row.status.as_str())?,
token_budget: row.token_budget,
tokens_used: row.tokens_used,
time_used_seconds: row.time_used_seconds,
created_at: epoch_millis_to_datetime(row.created_at_ms)?,
updated_at: epoch_millis_to_datetime(row.updated_at_ms)?,
})
}
}

View File

@@ -0,0 +1,901 @@
use anyhow::Result;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::SanitizedGitUrl;
use codex_protocol::ThreadId;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::ThreadSource;
use serde::Deserialize;
use serde::Serialize;
use sqlx::Row;
use sqlx::sqlite::SqliteRow;
use std::collections::HashMap;
use std::path::PathBuf;
/// The sort key to use when listing threads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
/// Sort by the thread's creation timestamp.
CreatedAt,
/// Sort by the thread's last update timestamp.
UpdatedAt,
/// Sort by the thread's product recency timestamp.
RecencyAt,
/// Sort by the thread's stable position within its user-selected section.
SectionPosition,
}
/// Sort direction to use when listing threads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortDirection {
Asc,
Desc,
}
/// Thread relationship used to filter thread listings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThreadRelationFilter {
/// Return only threads whose immediate parent is the given thread.
DirectChildrenOf(ThreadId),
/// Return every thread transitively descended from the given thread.
DescendantsOf(ThreadId),
/// Return only saved threads attached to this parent.
AttachedThreadsOf(ThreadId),
}
/// A pagination anchor used for keyset pagination.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Anchor {
/// The timestamp component of the anchor.
pub ts: DateTime<Utc>,
/// The thread ID component used to disambiguate equal recency timestamps.
pub id: Option<ThreadId>,
}
/// Visual presentation metadata owned by a thread section.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ThreadSectionAppearance {
pub icon: Option<String>,
pub color: Option<String>,
}
/// An independently persisted thread section and its user-facing presentation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThreadSection {
/// Opaque UUIDv7 identifying the section independently of its name.
pub id: String,
/// User-facing section name.
pub name: String,
#[serde(default)]
pub appearance: Option<ThreadSectionAppearance>,
}
impl ThreadSection {
pub(crate) fn from_row(
(id, name, appearance): (String, String, Option<String>),
) -> Result<Self> {
Ok(Self {
id,
name,
appearance: appearance
.map(|appearance| serde_json::from_str(&appearance))
.transpose()?,
})
}
}
/// A cursor-paginated page of independently persisted thread sections.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadSectionsPage {
/// Sections in ascending identifier order.
pub sections: Vec<ThreadSection>,
/// Identifier after which the next page starts, if any.
pub next_cursor: Option<String>,
}
/// A single page of thread metadata results.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadsPage {
/// The thread metadata items in this page.
pub items: Vec<ThreadMetadata>,
/// Immediate parents for page items found through the persisted spawn graph.
pub parent_thread_ids: HashMap<ThreadId, ThreadId>,
/// The next anchor to use for pagination, if any.
pub next_anchor: Option<Anchor>,
/// The number of rows scanned to produce this page.
pub num_scanned_rows: usize,
}
/// The outcome of extracting metadata from a rollout.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractionOutcome {
/// The extracted thread metadata.
pub metadata: ThreadMetadata,
/// The explicit thread memory mode from rollout metadata, if present.
pub memory_mode: Option<String>,
/// The number of rollout lines that failed to parse.
pub parse_errors: usize,
}
/// Canonical persisted thread metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadMetadata {
/// The parent of an attached thread, derived from canonical rollout metadata.
pub attached_thread_parent_id: Option<ThreadId>,
/// Originator recorded at creation, if available.
pub originator: Option<String>,
/// ChatGPT user that created the thread, if known.
pub creator_user_id: Option<String>,
/// ChatGPT account at creation, if known.
pub creator_account_id: Option<String>,
/// The thread identifier.
pub id: ThreadId,
/// The absolute rollout path on disk.
pub rollout_path: PathBuf,
/// The creation timestamp.
pub created_at: DateTime<Utc>,
/// The last update timestamp.
pub updated_at: DateTime<Utc>,
/// The product recency timestamp.
pub recency_at: DateTime<Utc>,
/// The session source (stringified enum).
pub source: String,
/// Persisted thread history contract selected when this thread was created.
pub history_mode: ThreadHistoryMode,
/// Optional analytics source classification for this thread.
pub thread_source: Option<ThreadSource>,
/// Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
pub agent_nickname: Option<String>,
/// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
pub agent_role: Option<String>,
/// Optional canonical agent path assigned to an AgentControl-spawned sub-agent.
pub agent_path: Option<String>,
/// The model provider identifier.
pub model_provider: String,
/// The latest observed model for the thread.
pub model: Option<String>,
/// The latest observed reasoning effort for the thread.
pub reasoning_effort: Option<ReasoningEffort>,
/// The working directory for the thread.
pub cwd: PathBuf,
/// Version of the CLI that created the thread.
pub cli_version: String,
/// A best-effort thread title.
pub title: String,
/// Explicit user-facing thread name, if one was set.
pub name: Option<String>,
/// Best available user-facing preview for discovery and list display.
pub preview: Option<String>,
/// The sandbox policy (stringified enum).
pub sandbox_policy: String,
/// The approval mode (stringified enum).
pub approval_mode: String,
/// The last observed token usage.
pub tokens_used: i64,
/// First user message observed for this thread, if any.
pub first_user_message: Option<String>,
/// The archive timestamp, if the thread is archived.
pub archived_at: Option<DateTime<Utc>>,
/// The user-selected section for this thread, if any.
pub section: Option<ThreadSection>,
/// The stable sparse ordering rank within the user-selected section.
pub section_position: Option<i64>,
/// The time when the thread most recently entered its current section.
pub section_entered_at: Option<DateTime<Utc>>,
/// Canonical project assignment owned by app-server, if any.
pub project_id: Option<String>,
/// User-selected Daybreak preference, absent until explicitly set.
pub daybreak_enabled: Option<bool>,
/// The git commit SHA, if known.
pub git_sha: Option<String>,
/// The git branch name, if known.
pub git_branch: Option<String>,
/// The git origin URL, if known.
pub git_origin_url: Option<SanitizedGitUrl>,
}
/// Builder data required to construct [`ThreadMetadata`] without parsing filenames.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadMetadataBuilder {
/// Originator recorded at creation, if available.
pub originator: Option<String>,
/// ChatGPT user that created the thread, if known.
pub creator_user_id: Option<String>,
/// ChatGPT account at creation, if known.
pub creator_account_id: Option<String>,
/// The thread identifier.
pub id: ThreadId,
/// The absolute rollout path on disk.
pub rollout_path: PathBuf,
/// The creation timestamp.
pub created_at: DateTime<Utc>,
/// The last update timestamp, if known.
pub updated_at: Option<DateTime<Utc>>,
/// The product recency timestamp, if known.
pub recency_at: Option<DateTime<Utc>>,
/// The session source.
pub source: SessionSource,
/// Persisted thread history contract selected when this thread was created.
pub history_mode: ThreadHistoryMode,
/// Optional analytics source classification for this thread.
pub thread_source: Option<ThreadSource>,
/// Optional random unique nickname assigned to the session.
pub agent_nickname: Option<String>,
/// Optional role (agent_role) assigned to the session.
pub agent_role: Option<String>,
/// Optional canonical agent path assigned to the session.
pub agent_path: Option<String>,
/// The model provider identifier, if known.
pub model_provider: Option<String>,
/// The working directory for the thread.
pub cwd: PathBuf,
/// Version of the CLI that created the thread.
pub cli_version: Option<String>,
/// The sandbox policy.
pub sandbox_policy: SandboxPolicy,
/// The approval mode.
pub approval_mode: AskForApproval,
/// The archive timestamp, if the thread is archived.
pub archived_at: Option<DateTime<Utc>>,
/// The git commit SHA, if known.
pub git_sha: Option<String>,
/// The git branch name, if known.
pub git_branch: Option<String>,
/// The git origin URL, if known.
pub git_origin_url: Option<SanitizedGitUrl>,
}
impl ThreadMetadataBuilder {
/// Create a new builder with required fields and sensible defaults.
pub fn new(
id: ThreadId,
rollout_path: PathBuf,
created_at: DateTime<Utc>,
source: SessionSource,
) -> Self {
Self {
id,
rollout_path,
created_at,
updated_at: None,
recency_at: None,
originator: None,
creator_user_id: None,
creator_account_id: None,
source,
history_mode: ThreadHistoryMode::Legacy,
thread_source: None,
agent_nickname: None,
agent_role: None,
agent_path: None,
model_provider: None,
cwd: PathBuf::new(),
cli_version: None,
sandbox_policy: SandboxPolicy::new_read_only_policy(),
approval_mode: AskForApproval::OnRequest,
archived_at: None,
git_sha: None,
git_branch: None,
git_origin_url: None,
}
}
/// Build canonical thread metadata, filling missing values from defaults.
pub fn build(&self, default_provider: &str) -> ThreadMetadata {
let source = crate::extract::enum_to_string(&self.source);
let sandbox_policy = crate::extract::enum_to_string(&self.sandbox_policy);
let approval_mode = crate::extract::enum_to_string(&self.approval_mode);
let created_at = canonicalize_datetime(self.created_at);
let updated_at = self
.updated_at
.map(canonicalize_datetime)
.unwrap_or(created_at);
let recency_at = self
.recency_at
.map(canonicalize_datetime)
.unwrap_or(updated_at);
let guardian_review = crate::is_guardian_review_source(&self.source);
ThreadMetadata {
attached_thread_parent_id: None,
originator: self.originator.clone(),
creator_user_id: self.creator_user_id.clone(),
creator_account_id: self.creator_account_id.clone(),
id: self.id,
rollout_path: self.rollout_path.clone(),
created_at,
updated_at,
recency_at,
source,
history_mode: self.history_mode,
thread_source: self.thread_source.clone(),
agent_nickname: self.agent_nickname.clone(),
agent_role: self.agent_role.clone(),
agent_path: self
.agent_path
.clone()
.or_else(|| self.source.get_agent_path().map(Into::into)),
model_provider: self
.model_provider
.clone()
.unwrap_or_else(|| default_provider.to_string()),
model: None,
reasoning_effort: None,
cwd: self.cwd.clone(),
cli_version: self.cli_version.clone().unwrap_or_default(),
title: if guardian_review {
crate::GUARDIAN_THREAD_TITLE.to_string()
} else {
String::new()
},
name: (guardian_review && self.history_mode == ThreadHistoryMode::Paginated)
.then(|| crate::GUARDIAN_THREAD_TITLE.to_string()),
preview: guardian_review.then(|| crate::GUARDIAN_THREAD_PREVIEW.to_string()),
sandbox_policy,
approval_mode,
tokens_used: 0,
first_user_message: None,
archived_at: self.archived_at.map(canonicalize_datetime),
section: None,
section_position: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
git_sha: self.git_sha.clone(),
git_branch: self.git_branch.clone(),
git_origin_url: self.git_origin_url.clone(),
}
}
}
impl ThreadMetadata {
/// Preserve SQLite-owned Git fields when rollout-derived metadata is reconciled.
pub fn prefer_existing_git_info(&mut self, existing: &Self) {
if matches!(self.history_mode, ThreadHistoryMode::Paginated)
&& matches!(existing.history_mode, ThreadHistoryMode::Paginated)
{
// `self` was rebuilt from the rollout's initial SessionMeta. `existing` is the
// current SQLite row. Once that row says paginated, metadata updates are SQLite-only,
// so a NULL is an explicit clear, not missing data. Copy the whole tuple or the stale
// rollout value would be written back during reconciliation.
self.git_sha = existing.git_sha.clone();
self.git_branch = existing.git_branch.clone();
self.git_origin_url = existing.git_origin_url.clone();
return;
}
if existing.git_sha.is_some() {
self.git_sha = existing.git_sha.clone();
}
if existing.git_branch.is_some() {
self.git_branch = existing.git_branch.clone();
}
if existing.git_origin_url.is_some() {
self.git_origin_url = existing.git_origin_url.clone();
}
}
/// Preserve an existing user-facing title when reconciling rollout-derived metadata.
pub fn prefer_existing_explicit_title(&mut self, existing: &Self) {
let existing_title = existing.title.trim();
if existing_title.is_empty()
|| existing.first_user_message.as_deref().map(str::trim) == Some(existing_title)
{
return;
}
let title = self.title.trim();
if title.is_empty()
|| self.first_user_message.as_deref().map(str::trim) == Some(title)
|| (title == crate::GUARDIAN_THREAD_TITLE
&& crate::extract::metadata_is_guardian_review(self))
{
self.title = existing.title.clone();
}
}
/// Return the list of field names that differ between `self` and `other`.
pub fn diff_fields(&self, other: &Self) -> Vec<&'static str> {
let mut diffs = Vec::new();
if self.id != other.id {
diffs.push("id");
}
if self.rollout_path != other.rollout_path {
diffs.push("rollout_path");
}
if self.created_at != other.created_at {
diffs.push("created_at");
}
if self.updated_at != other.updated_at {
diffs.push("updated_at");
}
if self.source != other.source {
diffs.push("source");
}
if self.creator_user_id != other.creator_user_id {
diffs.push("creator_user_id");
}
if self.creator_account_id != other.creator_account_id {
diffs.push("creator_account_id");
}
if self.originator != other.originator {
diffs.push("originator");
}
if self.agent_nickname != other.agent_nickname {
diffs.push("agent_nickname");
}
if self.agent_role != other.agent_role {
diffs.push("agent_role");
}
if self.agent_path != other.agent_path {
diffs.push("agent_path");
}
if self.model_provider != other.model_provider {
diffs.push("model_provider");
}
if self.model != other.model {
diffs.push("model");
}
if self.reasoning_effort != other.reasoning_effort {
diffs.push("reasoning_effort");
}
if self.cwd != other.cwd {
diffs.push("cwd");
}
if self.cli_version != other.cli_version {
diffs.push("cli_version");
}
if self.title != other.title {
diffs.push("title");
}
if self.name != other.name {
diffs.push("name");
}
if self.preview != other.preview {
diffs.push("preview");
}
if self.sandbox_policy != other.sandbox_policy {
diffs.push("sandbox_policy");
}
if self.approval_mode != other.approval_mode {
diffs.push("approval_mode");
}
if self.tokens_used != other.tokens_used {
diffs.push("tokens_used");
}
if self.first_user_message != other.first_user_message {
diffs.push("first_user_message");
}
if self.archived_at != other.archived_at {
diffs.push("archived_at");
}
if self.section != other.section {
diffs.push("section");
}
if self.section_position != other.section_position {
diffs.push("section_position");
}
if self.section_entered_at != other.section_entered_at {
diffs.push("section_entered_at");
}
if self.project_id != other.project_id {
diffs.push("project_id");
}
if self.daybreak_enabled != other.daybreak_enabled {
diffs.push("daybreak_enabled");
}
if self.git_sha != other.git_sha {
diffs.push("git_sha");
}
if self.git_branch != other.git_branch {
diffs.push("git_branch");
}
if self.git_origin_url != other.git_origin_url {
diffs.push("git_origin_url");
}
diffs
}
}
fn canonicalize_datetime(dt: DateTime<Utc>) -> DateTime<Utc> {
epoch_millis_to_datetime(datetime_to_epoch_millis(dt)).unwrap_or(dt)
}
#[derive(Debug)]
pub(crate) struct ThreadRow {
attached_thread_parent_id: Option<String>,
originator: Option<String>,
creator_user_id: Option<String>,
creator_account_id: Option<String>,
id: String,
rollout_path: String,
created_at: i64,
updated_at: i64,
recency_at: i64,
source: String,
history_mode: String,
thread_source: Option<String>,
agent_nickname: Option<String>,
agent_role: Option<String>,
agent_path: Option<String>,
model_provider: String,
model: Option<String>,
reasoning_effort: Option<String>,
cwd: String,
cli_version: String,
title: String,
name: Option<String>,
preview: String,
sandbox_policy: String,
approval_mode: String,
tokens_used: i64,
first_user_message: String,
archived_at: Option<i64>,
section: Option<String>,
section_name: Option<String>,
section_appearance: Option<String>,
section_position: Option<i64>,
section_entered_at_ms: Option<i64>,
project_id: Option<String>,
daybreak_enabled: Option<bool>,
git_sha: Option<String>,
git_branch: Option<String>,
git_origin_url: Option<String>,
}
impl ThreadRow {
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
Ok(Self {
attached_thread_parent_id: row.try_get("attached_thread_parent_id")?,
originator: row.try_get("originator")?,
creator_user_id: row.try_get("creator_user_id")?,
creator_account_id: row.try_get("creator_account_id")?,
id: row.try_get("id")?,
rollout_path: row.try_get("rollout_path")?,
created_at: row.try_get("created_at")?,
updated_at: row.try_get("updated_at")?,
recency_at: row.try_get("recency_at")?,
source: row.try_get("source")?,
history_mode: row.try_get("history_mode")?,
thread_source: row.try_get("thread_source")?,
agent_nickname: row.try_get("agent_nickname")?,
agent_role: row.try_get("agent_role")?,
agent_path: row.try_get("agent_path")?,
model_provider: row.try_get("model_provider")?,
model: row.try_get("model")?,
reasoning_effort: row.try_get("reasoning_effort")?,
cwd: row.try_get("cwd")?,
cli_version: row.try_get("cli_version")?,
title: row.try_get("title")?,
name: row.try_get("name")?,
preview: row.try_get("preview")?,
sandbox_policy: row.try_get("sandbox_policy")?,
approval_mode: row.try_get("approval_mode")?,
tokens_used: row.try_get("tokens_used")?,
first_user_message: row.try_get("first_user_message")?,
archived_at: row.try_get("archived_at")?,
section: row.try_get("section")?,
section_name: row.try_get("section_name")?,
section_appearance: row.try_get("section_appearance")?,
section_position: row.try_get("section_position")?,
section_entered_at_ms: row.try_get("section_entered_at_ms")?,
project_id: row.try_get("project_id")?,
daybreak_enabled: row.try_get("daybreak_enabled")?,
git_sha: row.try_get("git_sha")?,
git_branch: row.try_get("git_branch")?,
git_origin_url: row.try_get("git_origin_url")?,
})
}
}
impl TryFrom<ThreadRow> for ThreadMetadata {
type Error = anyhow::Error;
fn try_from(row: ThreadRow) -> std::result::Result<Self, Self::Error> {
let ThreadRow {
attached_thread_parent_id,
originator,
creator_user_id,
creator_account_id,
id,
rollout_path,
created_at,
updated_at,
recency_at,
source,
history_mode,
thread_source,
agent_nickname,
agent_role,
agent_path,
model_provider,
model,
reasoning_effort,
cwd,
cli_version,
title,
name,
preview,
sandbox_policy,
approval_mode,
tokens_used,
first_user_message,
archived_at,
section,
section_name,
section_appearance,
section_position,
section_entered_at_ms,
project_id,
daybreak_enabled,
git_sha,
git_branch,
git_origin_url,
} = row;
let thread_source = thread_source
.map(|thread_source| thread_source.parse())
.transpose()
.map_err(anyhow::Error::msg)?;
let history_mode = history_mode.parse().map_err(anyhow::Error::msg)?;
let section = match (section, section_name) {
(Some(id), Some(name)) => {
Some(ThreadSection::from_row((id, name, section_appearance))?)
}
(None, None) => None,
(Some(id), None) => {
return Err(anyhow::anyhow!(
"thread references an unknown section: {id}"
));
}
(None, Some(name)) => {
return Err(anyhow::anyhow!(
"thread has a section name without a section id: {name}"
));
}
};
Ok(Self {
id: ThreadId::try_from(id)?,
attached_thread_parent_id: attached_thread_parent_id
.map(ThreadId::try_from)
.transpose()?,
originator,
creator_user_id,
creator_account_id,
rollout_path: PathBuf::from(rollout_path),
created_at: epoch_millis_to_datetime(created_at)?,
updated_at: epoch_millis_to_datetime(updated_at)?,
recency_at: epoch_millis_to_datetime(recency_at)?,
source,
history_mode,
thread_source,
agent_nickname,
agent_role,
agent_path,
model_provider,
model,
reasoning_effort: reasoning_effort
.and_then(|value| value.parse::<ReasoningEffort>().ok()),
cwd: PathBuf::from(cwd),
cli_version,
title,
name,
preview: (!preview.is_empty()).then_some(preview),
sandbox_policy,
approval_mode,
tokens_used,
first_user_message: (!first_user_message.is_empty()).then_some(first_user_message),
archived_at: archived_at.map(epoch_seconds_to_datetime).transpose()?,
section,
section_position,
section_entered_at: section_entered_at_ms
.map(epoch_millis_to_datetime)
.transpose()?,
project_id,
daybreak_enabled,
git_sha,
git_branch,
git_origin_url: git_origin_url
.and_then(|origin_url| SanitizedGitUrl::try_from(origin_url).ok()),
})
}
}
pub(crate) fn anchor_from_item(item: &ThreadMetadata, sort_key: SortKey) -> Option<Anchor> {
let ts = match sort_key {
SortKey::CreatedAt => item.created_at,
SortKey::UpdatedAt => item.updated_at,
SortKey::RecencyAt => item.recency_at,
SortKey::SectionPosition => DateTime::<Utc>::from_timestamp_millis(item.section_position?)?,
};
Some(Anchor {
ts,
id: Some(item.id),
})
}
pub(crate) fn datetime_to_epoch_millis(dt: DateTime<Utc>) -> i64 {
dt.timestamp_millis()
}
pub(crate) fn datetime_to_epoch_seconds(dt: DateTime<Utc>) -> i64 {
dt.timestamp()
}
pub(crate) fn epoch_millis_to_datetime(value: i64) -> Result<DateTime<Utc>> {
// Values older than 2020 if interpreted as milliseconds are legacy second-precision rows.
// Convert them in memory so old state DBs keep ordering correctly after new writes use ms.
const MIN_EPOCH_MILLIS: i64 = 1_577_836_800_000;
let millis = if value < MIN_EPOCH_MILLIS {
value.saturating_mul(1000)
} else {
value
};
DateTime::<Utc>::from_timestamp_millis(millis)
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp millis: {value}"))
}
pub(crate) fn epoch_seconds_to_datetime(value: i64) -> Result<DateTime<Utc>> {
DateTime::<Utc>::from_timestamp(value, 0)
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp seconds: {value}"))
}
/// Statistics about a backfill operation.
#[derive(Debug, Clone)]
pub struct BackfillStats {
/// The number of rollout files scanned.
pub scanned: usize,
/// The number of rows upserted successfully.
pub upserted: usize,
/// The number of rows that failed to upsert.
pub failed: usize,
}
#[cfg(test)]
mod tests {
use super::ThreadMetadata;
use super::ThreadRow;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::SanitizedGitUrl;
use codex_protocol::ThreadId;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::ThreadHistoryMode;
use pretty_assertions::assert_eq;
use std::path::PathBuf;
fn thread_row(reasoning_effort: Option<&str>) -> ThreadRow {
ThreadRow {
attached_thread_parent_id: None,
originator: None,
creator_user_id: None,
creator_account_id: None,
id: "00000000-0000-0000-0000-000000000123".to_string(),
rollout_path: "/tmp/rollout-123.jsonl".to_string(),
created_at: 1_700_000_000,
updated_at: 1_700_000_100,
recency_at: 1_700_000_100,
source: "cli".to_string(),
history_mode: "legacy".to_string(),
thread_source: None,
agent_nickname: None,
agent_role: None,
agent_path: None,
model_provider: "openai".to_string(),
model: Some("gpt-5".to_string()),
reasoning_effort: reasoning_effort.map(str::to_string),
cwd: "/tmp/workspace".to_string(),
cli_version: "0.0.0".to_string(),
title: String::new(),
name: None,
preview: String::new(),
sandbox_policy: "read-only".to_string(),
approval_mode: "on-request".to_string(),
tokens_used: 1,
first_user_message: String::new(),
archived_at: None,
section: None,
section_name: None,
section_appearance: None,
section_position: None,
section_entered_at_ms: None,
project_id: None,
daybreak_enabled: None,
git_sha: None,
git_branch: None,
git_origin_url: None,
}
}
fn expected_thread_metadata(reasoning_effort: Option<ReasoningEffort>) -> ThreadMetadata {
ThreadMetadata {
attached_thread_parent_id: None,
originator: None,
creator_user_id: None,
creator_account_id: None,
id: ThreadId::from_string("00000000-0000-0000-0000-000000000123")
.expect("valid thread id"),
rollout_path: PathBuf::from("/tmp/rollout-123.jsonl"),
created_at: DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("timestamp"),
updated_at: DateTime::<Utc>::from_timestamp(1_700_000_100, 0).expect("timestamp"),
recency_at: DateTime::<Utc>::from_timestamp(1_700_000_100, 0).expect("timestamp"),
source: "cli".to_string(),
history_mode: ThreadHistoryMode::Legacy,
thread_source: None,
agent_nickname: None,
agent_role: None,
agent_path: None,
model_provider: "openai".to_string(),
model: Some("gpt-5".to_string()),
reasoning_effort,
cwd: PathBuf::from("/tmp/workspace"),
cli_version: "0.0.0".to_string(),
title: String::new(),
name: None,
preview: None,
sandbox_policy: "read-only".to_string(),
approval_mode: "on-request".to_string(),
tokens_used: 1,
first_user_message: None,
archived_at: None,
section: None,
section_position: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
git_sha: None,
git_branch: None,
git_origin_url: None,
}
}
#[test]
fn thread_row_parses_reasoning_effort() {
let metadata = ThreadMetadata::try_from(thread_row(Some("high")))
.expect("thread metadata should parse");
assert_eq!(
metadata,
expected_thread_metadata(Some(ReasoningEffort::High))
);
}
#[test]
fn thread_row_preserves_model_defined_reasoning_effort_values() {
let metadata = ThreadMetadata::try_from(thread_row(Some("future")))
.expect("thread metadata should parse");
assert_eq!(
metadata,
expected_thread_metadata(Some(ReasoningEffort::Custom("future".to_string())))
);
}
#[test]
fn thread_row_rejects_unknown_history_mode() {
let mut row = thread_row(/*reasoning_effort*/ None);
row.history_mode = "future".to_string();
assert!(ThreadMetadata::try_from(row).is_err());
}
#[test]
fn paginated_rollout_git_info_keeps_rollout_values_until_sqlite_mode_is_paginated() {
let mut reconciled = expected_thread_metadata(/*reasoning_effort*/ None);
reconciled.history_mode = ThreadHistoryMode::Paginated;
reconciled.git_sha = Some("rollout-sha".to_string());
reconciled.git_branch = Some("rollout-branch".to_string());
reconciled.git_origin_url = Some(
SanitizedGitUrl::try_from("https://example.com/rollout-origin")
.expect("valid git remote URL"),
);
let existing = expected_thread_metadata(/*reasoning_effort*/ None);
let expected = reconciled.clone();
reconciled.prefer_existing_git_info(&existing);
assert_eq!(reconciled, expected);
}
}

View File

@@ -0,0 +1,363 @@
//! Converts WAL databases to DELETE mode while preserving recoverable WAL backups.
//! Callers serialize startup and migration with the directory lock. Other SQLite clients
//! must remain stopped during replacement; NFS must enforce cross-client POSIX locks.
//! Migration requires write access to the directory and its persistent migration lock.
//! Relaxed file permissions do not establish cross-user database sharing.
use anyhow::Context;
use anyhow::ensure;
use sqlx::ConnectOptions;
use sqlx::Connection;
use sqlx::SqliteConnection;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::sqlite::SqliteJournalMode;
use sqlx::sqlite::SqliteLockingMode;
use sqlx::sqlite::SqliteSynchronous;
use std::fs::File;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
mod replacement;
use replacement::Recovery;
use replacement::Replacement;
use replacement::regular_file_exists;
/// Holds the directory lock shared by automatic startup and the migration command.
pub struct NfsDbMigration {
_lock: File,
}
/// Result of checking or converting a database, for caller-owned reporting.
pub enum NfsDbMigrationOutcome {
Missing,
AlreadyDelete,
Migrated { backup_directory: PathBuf },
}
impl NfsDbMigration {
/// Inspect the on-disk journal mode without accessing WAL shared memory.
/// Use SQLite's descriptor so closing it cannot release another connection's locks.
#[expect(
clippy::disallowed_methods,
reason = "NFS inspection needs an immutable connection without shared memory"
)]
pub async fn needs_migration(source: &Path) -> anyhow::Result<bool> {
if !regular_file_exists(source)? {
let replacement = Replacement::new(source)?;
return Ok(regular_file_exists(&replacement.backup_database)?
|| regular_file_exists(&replacement.replacement_path())?);
}
let mut connection = SqliteConnection::connect_with(
&SqliteConnectOptions::new()
.filename(source)
.read_only(true)
.immutable(true)
.disable_statement_logging(),
)
.await?;
let inspected: anyhow::Result<bool> = async {
let mut handle = connection.lock_handle().await?;
let mut file: *mut libsqlite3_sys::sqlite3_file = std::ptr::null_mut();
// SAFETY: SQLx's guard excludes its worker. FILE_POINTER writes a borrowed
// sqlite3_file pointer, valid while this connection and guard remain alive.
let status = unsafe {
libsqlite3_sys::sqlite3_file_control(
handle.as_raw_handle().as_ptr(),
c"main".as_ptr(),
libsqlite3_sys::SQLITE_FCNTL_FILE_POINTER,
(&raw mut file).cast(),
)
};
ensure!(
status == libsqlite3_sys::SQLITE_OK && !file.is_null(),
"cannot inspect database header"
);
// SAFETY: FILE_POINTER returned a live file owned by the guarded connection.
let methods = unsafe { (*file).pMethods };
ensure!(!methods.is_null(), "database VFS has no file methods");
let mut header = [0u8; 20];
// SAFETY: the built-in file VFS supplies xRead; the guarded file is live,
// and the buffer has space for exactly the requested 20 bytes.
let status = unsafe {
let read = (*methods).xRead.context("database VFS cannot read")?;
read(
file,
header.as_mut_ptr().cast(),
/*iAmt*/ 20,
/*iOfst*/ 0,
)
};
ensure!(
status == libsqlite3_sys::SQLITE_OK,
"cannot read database header: {status}"
);
ensure!(
&header[..16] == b"SQLite format 3\0",
"invalid database header"
);
// SQLite file-format read/write versions are 1 for rollback and 2 for WAL.
Ok(header[18] == 2 || header[19] == 2)
}
.await;
let closed = connection.close().await;
let needed = inspected?;
closed?;
Ok(needed)
}
pub fn lock(sqlite_home: &Path) -> anyhow::Result<Self> {
ensure!(
cfg!(unix),
"NFS database migration requires Unix filesystem locking and directory fsync"
);
// Never remove the lock: concurrent openers must lock the same inode.
let lock = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(sqlite_home.join(".codex-nfs-migration.lock"))?;
lock.try_lock()
.context("another database migration is running")?;
Ok(Self { _lock: lock })
}
/// Whether source or recovery files have permission bits other than 0600.
/// Only inspect metadata: opening WAL databases can create shared-memory files.
pub fn needs_permission_confirmation(source: &Path) -> anyhow::Result<bool> {
let replacement = Replacement::new(source)?;
for path in [
source.to_path_buf(),
replacement.backup_database.clone(),
replacement.replacement_path(),
] {
if !regular_file_exists(&path)? {
continue;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if std::fs::metadata(path)?.permissions().mode() & 0o777 != 0o600 {
return Ok(true);
}
}
}
Ok(false)
}
/// Convert an existing WAL database or resume an interrupted replacement.
/// All other clients must remain stopped until this returns successfully.
/// Callers must obtain consent or require unsafe migration through managed policy.
/// The replacement preserves mode bits, but belongs to the current user and does not
/// copy the original owner, group, or extended ACLs.
#[expect(
clippy::disallowed_methods,
reason = "Migration needs a dedicated exclusive connection, not a runtime pool"
)]
pub async fn migrate(
&mut self,
source: &Path,
staging_dir: &Path,
) -> anyhow::Result<NfsDbMigrationOutcome> {
let replacement = Replacement::new(source)?;
if let Recovery::Installed = replacement.resume().await? {
return Ok(NfsDbMigrationOutcome::Migrated {
backup_directory: replacement.backup_directory,
});
}
let exists = regular_file_exists(source)?;
for suffix in ["-wal", "-shm", "-journal"] {
let mut path = source.as_os_str().to_owned();
path.push(suffix);
let sidecar_exists = regular_file_exists(Path::new(&path))?;
ensure!(
exists || !sidecar_exists,
"database is missing but a SQLite sidecar exists"
);
}
if !exists {
return Ok(NfsDbMigrationOutcome::Missing);
}
let options = SqliteConnectOptions::new()
.filename(source)
// Set this mode before SQLite first accesses the WAL.
// SQLite then locks the database file without shared memory across NFS client kernels.
.locking_mode(SqliteLockingMode::Exclusive)
.synchronous(SqliteSynchronous::Full)
.busy_timeout(Duration::from_secs(/*secs*/ 5))
.disable_statement_logging();
let mut connection = SqliteConnection::connect_with(&options).await.context(
"cannot open source database exclusively; close its SQLite clients on all hosts",
)?;
// Closing any descriptor for an inode can release this process's POSIX record locks
// for that inode.
// Keep both source files open until SQLite closes its connection, including after an error.
let mut source_files = Vec::new();
let result: anyhow::Result<bool> = async {
{
let mut handle = connection.lock_handle().await?;
// SAFETY: SQLx's guard prevents its worker from accessing this open connection.
// This db_config option accepts an int and an optional output pointer to an int.
let status = unsafe {
libsqlite3_sys::sqlite3_db_config(
handle.as_raw_handle().as_ptr(),
libsqlite3_sys::SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,
/*onoff*/ 1,
std::ptr::null_mut::<i32>(),
)
};
ensure!(
status == libsqlite3_sys::SQLITE_OK,
"cannot disable source checkpoint on close: {status}"
);
}
let mode: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&mut connection)
.await
.context(
"cannot access source database exclusively; close its SQLite clients on all hosts",
)?;
if mode == "delete" {
ensure!(
!regular_file_exists(&replacement.replacement_path())?,
"unfinished backup exists"
);
return Ok(false);
}
ensure!(
mode == "wal",
"source database must be in WAL mode (found {mode})"
);
// BEGIN EXCLUSIVE alone blocks only WAL writers. EXCLUSIVE locking_mode also blocks readers.
// The mode keeps the database lock after ROLLBACK.
sqlx::raw_sql("BEGIN EXCLUSIVE; ROLLBACK;")
.execute(&mut connection)
.await
.context(
"cannot lock source database exclusively; close its SQLite clients on all hosts",
)?;
// A DELETE no-op must not open raw descriptors: closing them could release
// POSIX locks held by another pool in this process.
source_files.push(File::open(source)?);
let source_permissions = source_files[0].metadata()?.permissions();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
ensure!(
source_permissions.mode() & 0o600 == 0o600,
"database owner permissions must include read and write so the replacement remains accessible to its new owner"
);
}
// The private directory protects WAL contents even on a shared /tmp.
let staging = tempfile::Builder::new()
.prefix("codex-nfs-migration-")
.tempdir_in(staging_dir)
.context("cannot create local staging directory")?;
let staged_database = staging.path().join("database.sqlite");
let mut wal_path = source.as_os_str().to_owned();
wal_path.push("-wal");
match File::open(wal_path) {
Ok(file) => source_files.push(file),
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => return Err(error).context("cannot open source WAL"),
}
for (file, name) in source_files
.iter_mut()
.zip(["database.sqlite", "database.sqlite-wal"])
{
let mut target = File::create(staging.path().join(name))?;
copy_buffered(file, &mut target).context("cannot stage source database and WAL")?;
}
let mut copy = SqliteConnection::connect_with(
&SqliteConnectOptions::new()
.filename(&staged_database)
.locking_mode(SqliteLockingMode::Exclusive)
.journal_mode(SqliteJournalMode::Delete)
.synchronous(SqliteSynchronous::Full)
.disable_statement_logging(),
)
.await
.context("cannot convert staged database to DELETE")?;
let validated = validate_delete_database(&mut copy)
.await
.context("staged database failed validation");
let closed = copy.close().await;
validated?;
closed?;
replacement.prepare_backup_directory()?;
let mut temporary = tempfile::NamedTempFile::new_in(&replacement.backup_directory)?;
copy_buffered(&mut File::open(&staged_database)?, temporary.as_file_mut())
.context("cannot write replacement copy")?;
// Use the open handle. Closing another source descriptor can release SQLite's locks.
temporary
.as_file()
.set_permissions(source_permissions)?;
temporary.as_file().sync_all()?;
temporary
.into_temp_path()
.persist_noclobber(replacement.replacement_path())
.context("cannot save replacement copy")?;
File::open(&replacement.backup_directory)?.sync_all()?;
for file in &source_files {
file.sync_all()?;
}
replacement.move_original_to_backup()?;
Ok(true)
}
.await;
let closed = connection.close().await;
drop(source_files);
let changed = result?;
closed.context("cannot close source database. Keep clients stopped")?;
if changed {
replacement.install()?;
return Ok(NfsDbMigrationOutcome::Migrated {
backup_directory: replacement.backup_directory,
});
}
Ok(NfsDbMigrationOutcome::AlreadyDelete)
}
}
async fn validate_delete_database(connection: &mut SqliteConnection) -> anyhow::Result<()> {
let mode: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&mut *connection)
.await?;
ensure!(
mode == "delete",
"database did not enter DELETE journal mode"
);
let integrity: String = sqlx::query_scalar("PRAGMA integrity_check(1)")
.fetch_one(connection)
.await
.context("database failed integrity check")?;
ensure!(
integrity == "ok",
"database failed integrity check: {integrity}"
);
Ok(())
}
fn copy_buffered(source: &mut File, destination: &mut File) -> std::io::Result<()> {
// Use large reads to avoid the fallback to small reads for copy_file_range on NFSv4.1.
let mut buffer = vec![0; 1024 * 1024];
loop {
let bytes = match source.read(&mut buffer) {
Err(error) if error.kind() == ErrorKind::Interrupted => continue,
result => result?,
};
if bytes == 0 {
return Ok(());
}
destination.write_all(&buffer[..bytes])?;
}
}

View File

@@ -0,0 +1,244 @@
//! Move the WAL files into a backup directory, then install the validated DELETE copy.
//! Resume an interrupted replacement from the files that remain on disk.
//! All clients must remain stopped. The caller must hold the migration lock.
//! Sync both directories after each step before changing more files.
use anyhow::Context;
use anyhow::ensure;
use sqlx::ConnectOptions;
use sqlx::Connection;
use sqlx::SqliteConnection;
use sqlx::sqlite::SqliteConnectOptions;
use std::fs;
use std::fs::File;
use std::io::ErrorKind;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
const MARKER: &[u8] = b"codex-nfs-migration-v1\n";
const SIDECARS: [&str; 3] = ["-wal", "-shm", "-journal"];
pub(super) enum Recovery {
// The caller must check and lock the source before starting a new replacement.
InspectSource,
// Recovery installed the saved copy. No new replacement is necessary.
Installed,
}
pub(super) struct Replacement {
source: PathBuf,
pub(super) backup_directory: PathBuf,
pub(super) backup_database: PathBuf,
}
impl Replacement {
pub(super) fn new(source: &Path) -> anyhow::Result<Self> {
let name = source.file_name().context("database needs a file name")?;
let mut directory = source.as_os_str().to_owned();
directory.push("_wal_migration_backup");
let directory = PathBuf::from(directory);
Ok(Self {
source: source.to_path_buf(),
backup_database: directory.join(name),
backup_directory: directory,
})
}
pub(super) fn replacement_path(&self) -> PathBuf {
self.backup_directory.join("delete.sqlite")
}
// Call only while the original database is locked. Rebuild an unused copy on every attempt.
pub(super) fn prepare_backup_directory(&self) -> anyhow::Result<()> {
if self.backup_directory.try_exists()? {
ensure!(
!regular_file_exists(&self.backup_database)?,
"WAL backup already exists"
);
if regular_file_exists(&self.replacement_path())? {
fs::remove_file(self.replacement_path())?;
}
} else {
let builder = fs::DirBuilder::new();
#[cfg(unix)]
let builder = {
use std::os::unix::fs::DirBuilderExt;
let mut builder = builder;
builder.mode(0o700);
builder
};
builder.create(&self.backup_directory)?;
let mut marker = File::create_new(self.backup_directory.join("migration-v1"))?;
marker.write_all(MARKER)?;
marker.sync_all()?;
}
self.sync_directories()
}
pub(super) fn move_original_to_backup(&self) -> anyhow::Result<()> {
ensure!(
!regular_file_exists(&self.backup_database)?,
"WAL backup already exists"
);
// Move the main file first. An incomplete switch must not look like an intact source.
fs::rename(&self.source, &self.backup_database)?;
self.sync_directories()?;
self.move_sidecars_to_backup()
}
fn move_sidecars_to_backup(&self) -> anyhow::Result<()> {
for suffix in SIDECARS {
let source = with_suffix(&self.source, suffix);
let destination = with_suffix(&self.backup_database, suffix);
if regular_file_exists(&source)? {
ensure!(
!regular_file_exists(&destination)?,
"backup sidecar already exists: {}",
destination.display()
);
fs::rename(source, destination)?;
}
}
self.sync_directories()
}
pub(super) fn install(&self) -> anyhow::Result<()> {
for suffix in ["", "-wal", "-shm", "-journal"] {
ensure!(
!regular_file_exists(&with_suffix(&self.source, suffix))?,
"database or sidecar already exists at the installation path"
);
}
// A hard link installs the file atomically without replacing an unexpected database.
fs::hard_link(self.replacement_path(), &self.source)?;
self.finish_installation()
}
fn finish_installation(&self) -> anyhow::Result<()> {
self.sync_directories()?;
fs::remove_file(self.replacement_path())?;
self.sync_directories()
}
fn sync_directories(&self) -> anyhow::Result<()> {
File::open(&self.backup_directory)?.sync_all()?;
File::open(
self.source
.parent()
.context("database needs a parent directory")?,
)?
.sync_all()?;
Ok(())
}
#[expect(
clippy::disallowed_methods,
reason = "Inspect the prepared copy without runtime initialization"
)]
pub(super) async fn resume(&self) -> anyhow::Result<Recovery> {
match fs::symlink_metadata(&self.backup_directory) {
Err(error) if error.kind() == ErrorKind::NotFound => {
return Ok(Recovery::InspectSource);
}
Err(error) => return Err(error.into()),
Ok(metadata) => ensure!(
metadata.is_dir(),
"backup path already exists and is not a directory"
),
}
let marker = self.backup_directory.join("migration-v1");
ensure!(
regular_file_exists(&marker)? && fs::read(&marker)? == MARKER,
"backup directory already exists without a valid migration marker: {}",
self.backup_directory.display()
);
let backup_exists = regular_file_exists(&self.backup_database)?;
let replacement_exists = regular_file_exists(&self.replacement_path())?;
let source_exists = regular_file_exists(&self.source)?;
// No original files moved yet. The caller must lock the source and rebuild the copy.
if !backup_exists {
for suffix in SIDECARS {
ensure!(
!regular_file_exists(&with_suffix(&self.backup_database, suffix))?,
"backup has a SQLite sidecar without its original database"
);
}
ensure!(
source_exists,
"original database is missing from both source and backup"
);
return Ok(Recovery::InspectSource);
}
// Installation finished, or the replacement is missing. The caller must check the source.
if !replacement_exists {
ensure!(
source_exists,
"replacement is missing. Preserve the WAL backup and restore it before retrying"
);
return Ok(Recovery::InspectSource);
}
// An existing source must be the link installed before the interruption.
if source_exists {
let same_file = {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let source = fs::metadata(&self.source)?;
let prepared = fs::metadata(self.replacement_path())?;
(source.dev(), source.ino()) == (prepared.dev(), prepared.ino())
}
#[cfg(not(unix))]
{
false
}
};
ensure!(
same_file,
"another database already exists at the installation path"
);
self.finish_installation()?;
return Ok(Recovery::Installed);
}
// The original is in the backup. Check the replacement before installing it.
let mut copy = SqliteConnection::connect_with(
&SqliteConnectOptions::new()
.filename(self.replacement_path())
.read_only(true)
.immutable(true)
.disable_statement_logging(),
)
.await?;
let checked = super::validate_delete_database(&mut copy)
.await
.context("saved replacement failed validation");
let closed = copy.close().await;
checked?;
closed?;
self.move_sidecars_to_backup()?;
self.install()?;
Ok(Recovery::Installed)
}
}
pub(super) fn regular_file_exists(path: &Path) -> anyhow::Result<bool> {
match fs::symlink_metadata(path) {
Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
Ok(metadata) => {
ensure!(
metadata.is_file(),
"path already exists and is not a regular file: {}",
path.display()
);
Ok(true)
}
}
}
fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
let mut value = path.as_os_str().to_owned();
value.push(suffix);
value.into()
}

View File

@@ -0,0 +1,9 @@
use chrono::DateTime;
use chrono::Utc;
use std::path::Path;
pub(crate) async fn file_modified_time_utc(path: &Path) -> Option<DateTime<Utc>> {
let modified = tokio::fs::metadata(path).await.ok()?.modified().ok()?;
let updated_at: DateTime<Utc> = modified.into();
Some(updated_at)
}

View File

@@ -0,0 +1,773 @@
use crate::LogEntry;
use crate::LogQuery;
use crate::LogRow;
use crate::SortKey;
use crate::SqliteConfig;
use crate::ThreadMetadata;
use crate::ThreadMetadataBuilder;
use crate::ThreadsPage;
use crate::apply_rollout_item;
use crate::migrations::runtime_goals_migrator;
use crate::migrations::runtime_logs_migrator;
use crate::migrations::runtime_memories_migrator;
use crate::migrations::runtime_queue_migrator;
use crate::migrations::runtime_state_migrator;
use crate::migrations::runtime_thread_history_migrator;
use crate::model::ThreadRow;
use crate::model::anchor_from_item;
use crate::model::datetime_to_epoch_millis;
use crate::model::datetime_to_epoch_seconds;
use crate::model::epoch_millis_to_datetime;
use crate::paths::file_modified_time_utc;
use crate::sqlite::SqliteWriteQueryExt;
use crate::telemetry::DbKind;
use crate::telemetry::DbTelemetry;
use chrono::DateTime;
use chrono::Utc;
use codex_history::RolloutItem;
use codex_protocol::ThreadId;
use serde_json::Value;
use sqlx::QueryBuilder;
use sqlx::Row;
use sqlx::Sqlite;
use sqlx::SqliteConnection;
use sqlx::SqlitePool;
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicI64;
use std::time::Instant;
use tracing::warn;
mod backfill;
mod external_agent_config_imports;
mod goals;
mod guardian_feedback;
mod logs;
mod logs_maintenance;
mod memories;
mod memory_versions;
mod projects;
mod queued_items;
pub(crate) mod reclamation;
pub(crate) mod recovery;
mod remote_control;
mod rollout_migration;
#[cfg(test)]
pub(crate) mod test_support;
mod thread_attachments;
mod thread_metadata;
mod thread_read_state;
mod thread_section_order;
mod thread_sections;
mod threads;
pub use external_agent_config_imports::ExternalAgentConfigImportDetailsRecord;
pub use external_agent_config_imports::ExternalAgentConfigImportFailureRecord;
pub use external_agent_config_imports::ExternalAgentConfigImportHistoryRecord;
pub use external_agent_config_imports::ExternalAgentConfigImportSuccessRecord;
pub use goals::GoalAccountingMode;
pub use goals::GoalAccountingOutcome;
pub use goals::GoalStore;
pub use goals::GoalUpdate;
pub use guardian_feedback::GuardianReviewRecord;
pub use guardian_feedback::MAX_GUARDIAN_REVIEW_BYTES;
pub use guardian_feedback::MAX_GUARDIAN_REVIEW_RECORDS;
pub use guardian_feedback::MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD;
pub use memories::MemoryStore;
pub use queued_items::SqliteQueueStore;
pub use recovery::backup_runtime_db_for_fresh_start;
pub use recovery::collect_runtime_db_backups;
pub use recovery::is_sqlite_corruption_error;
pub use recovery::runtime_db_path_for_corruption_error;
pub use recovery::sqlite_error_detail_is_lock;
pub use remote_control::RemoteControlEnrollmentRecord;
pub use thread_read_state::ReadStateOperation;
pub use thread_read_state::ReadStateUpdate;
pub use thread_read_state::ThreadReadState;
pub use threads::ThreadFilterOptions;
// "Partition" is the retained-log-content bucket we cap at 10 MiB:
// - one bucket per non-null thread_id
// - one bucket per threadless (thread_id IS NULL) non-null process_uuid
// - one bucket for threadless rows with process_uuid IS NULL
// This budget tracks each row's persisted rendered log body plus non-body
// metadata, rather than the exact sum of all persisted SQLite column bytes.
const LOG_PARTITION_SIZE_LIMIT_BYTES: i64 = 10 * 1024 * 1024;
const LOG_PARTITION_ROW_LIMIT: i64 = 1_000;
#[derive(Clone)]
pub struct StateRuntime {
sqlite: SqliteConfig,
default_provider: String,
pool: Arc<sqlx::SqlitePool>,
logs_pool: Arc<sqlx::SqlitePool>,
thread_goals: GoalStore,
memories: MemoryStore,
memories_v2: Arc<tokio::sync::OnceCell<MemoryStore>>,
thread_queue: SqliteQueueStore,
thread_updated_at_millis: Arc<AtomicI64>,
thread_recency_at_millis: Arc<AtomicI64>,
reclamation: Arc<reclamation::SqliteReclamationWorker>,
}
impl StateRuntime {
/// Initialize the state runtime using the provided SQLite configuration and default provider.
///
/// This opens (and migrates) the SQLite databases under the configured
/// `sqlite_home`.
/// Logs and paginated thread history live in dedicated files to reduce
/// lock contention with the rest of the state store.
pub async fn init(sqlite: SqliteConfig, default_provider: String) -> anyhow::Result<Arc<Self>> {
Self::init_inner(sqlite, default_provider, /*telemetry_override*/ None).await
}
#[cfg(test)]
pub(crate) async fn init_with_telemetry_for_tests(
sqlite: SqliteConfig,
default_provider: String,
telemetry_override: &dyn DbTelemetry,
) -> anyhow::Result<Arc<Self>> {
Self::init_inner(sqlite, default_provider, Some(telemetry_override)).await
}
async fn init_inner(
sqlite: SqliteConfig,
default_provider: String,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<Arc<Self>> {
tokio::fs::create_dir_all(sqlite.home()).await?;
let state_migrator = runtime_state_migrator();
let logs_migrator = runtime_logs_migrator();
let goals_migrator = runtime_goals_migrator();
let memories_migrator = runtime_memories_migrator();
let queue_migrator = runtime_queue_migrator();
let state_path = sqlite.state_db_path();
let logs_path = sqlite.logs_db_path();
let goals_path = sqlite.goals_db_path();
let memories_path = sqlite.memories_db_path();
let queue_path = sqlite.queue_db_path();
let pool = match sqlite
.open_state_db(&state_migrator, telemetry_override)
.await
{
Ok(db) => Arc::new(db),
Err(err) => {
warn!("failed to open state db at {}: {err}", state_path.display());
return Err(err);
}
};
let has_memories_v2 = tokio::fs::try_exists(sqlite.memories_v2_db_path()).await?;
let logs_pool = match sqlite
.open_logs_db(&logs_migrator, telemetry_override)
.await
{
Ok(db) => Arc::new(db),
Err(err) => {
warn!("failed to open logs db at {}: {err}", logs_path.display());
close_sqlite_pools(&[pool.as_ref()]).await;
return Err(err);
}
};
let goals_pool = match sqlite
.open_goals_db(&goals_migrator, telemetry_override)
.await
{
Ok(db) => Arc::new(db),
Err(err) => {
warn!("failed to open goals db at {}: {err}", goals_path.display());
close_sqlite_pools(&[pool.as_ref(), logs_pool.as_ref()]).await;
return Err(err);
}
};
let memories_pool = match sqlite
.open_memories_db(&memories_migrator, telemetry_override)
.await
{
Ok(db) => Arc::new(db),
Err(err) => {
warn!(
"failed to open memories db at {}: {err}",
memories_path.display()
);
close_sqlite_pools(&[pool.as_ref(), logs_pool.as_ref(), goals_pool.as_ref()]).await;
return Err(err);
}
};
let queue_pool = match sqlite
.open_queue_db(&queue_migrator, telemetry_override)
.await
{
Ok(db) => Arc::new(db),
Err(err) => {
warn!("failed to open queue db at {}: {err}", queue_path.display());
close_sqlite_pools(&[
pool.as_ref(),
logs_pool.as_ref(),
goals_pool.as_ref(),
memories_pool.as_ref(),
])
.await;
return Err(err);
}
};
let started = Instant::now();
let backfill_state_result = ensure_backfill_state_row_in_pool(pool.as_ref()).await;
crate::telemetry::record_init_result(
telemetry_override,
DbKind::State,
"ensure_backfill_state",
started.elapsed(),
&backfill_state_result,
);
if let Err(err) = backfill_state_result {
close_sqlite_pools(&[
pool.as_ref(),
logs_pool.as_ref(),
goals_pool.as_ref(),
memories_pool.as_ref(),
queue_pool.as_ref(),
])
.await;
return Err(err);
}
let started = Instant::now();
let thread_timestamp_millis_result: anyhow::Result<(Option<i64>, Option<i64>)> =
sqlx::query_as(
"SELECT (SELECT MAX(updated_at_ms) FROM threads), (SELECT MAX(recency_at_ms) FROM threads)",
)
.fetch_one(pool.as_ref())
.await
.map_err(anyhow::Error::from);
crate::telemetry::record_init_result(
telemetry_override,
DbKind::State,
"post_init_query",
started.elapsed(),
&thread_timestamp_millis_result,
);
let (thread_updated_at_millis, thread_recency_at_millis) =
match thread_timestamp_millis_result {
Ok(value) => value,
Err(err) => {
close_sqlite_pools(&[
pool.as_ref(),
logs_pool.as_ref(),
goals_pool.as_ref(),
memories_pool.as_ref(),
queue_pool.as_ref(),
])
.await;
return Err(err);
}
};
let thread_updated_at_millis = thread_updated_at_millis.unwrap_or(0);
let thread_recency_at_millis = thread_recency_at_millis.unwrap_or(0);
let runtime = Arc::new(Self {
reclamation: reclamation::SqliteReclamationWorker::spawn(sqlite.clone()),
thread_goals: GoalStore::new(Arc::clone(&goals_pool)),
memories: MemoryStore::new(Arc::clone(&memories_pool), Arc::clone(&pool)),
memories_v2: Arc::new(tokio::sync::OnceCell::new()),
thread_queue: SqliteQueueStore::new(queue_pool),
pool,
logs_pool,
sqlite,
default_provider,
thread_updated_at_millis: Arc::new(AtomicI64::new(thread_updated_at_millis)),
thread_recency_at_millis: Arc::new(AtomicI64::new(thread_recency_at_millis)),
});
// Existing v2 state must participate in startup corruption recovery.
// Keep creation lazy for users who have never used v2.
if has_memories_v2
&& let Err(err) = runtime
.memories_for_version(codex_protocol::MemoryVersion::V2)
.await
{
runtime.close().await;
return Err(err);
}
runtime.start_periodic_logs_maintenance(std::time::Duration::from_secs(30 * 60));
Ok(runtime)
}
/// Return the SQLite configuration for this runtime.
pub fn sqlite(&self) -> &SqliteConfig {
&self.sqlite
}
pub fn thread_goals(&self) -> &GoalStore {
&self.thread_goals
}
pub fn memories(&self) -> &MemoryStore {
&self.memories
}
/// Return the durable, SQLite-backed user-message queue.
pub fn thread_queue(&self) -> &SqliteQueueStore {
&self.thread_queue
}
/// Close all SQLite pools and wait for outstanding pool workers to exit.
pub async fn close(&self) {
self.reclamation.close().await;
self.thread_queue.close().await;
self.memories.close().await;
if let Some(memories) = self.memories_v2.get() {
memories.close().await;
}
self.thread_goals.close().await;
self.logs_pool.close().await;
self.pool.close().await;
}
pub async fn clear_memory_data_in_sqlite_home(sqlite: &SqliteConfig) -> anyhow::Result<bool> {
let mut cleared = false;
for version in [
codex_protocol::MemoryVersion::V1,
codex_protocol::MemoryVersion::V2,
] {
let path = match version {
codex_protocol::MemoryVersion::V1 => sqlite.memories_db_path(),
codex_protocol::MemoryVersion::V2 => sqlite.memories_v2_db_path(),
};
if !tokio::fs::try_exists(path).await? {
continue;
}
let pool = match version {
codex_protocol::MemoryVersion::V1 => {
sqlite
.open_memories_db(
&runtime_memories_migrator(),
/*telemetry_override*/ None,
)
.await?
}
codex_protocol::MemoryVersion::V2 => sqlite.open_memories_v2_db().await?,
};
let result = memories::clear_memory_data_in_pool(&pool).await;
pool.close().await;
result?;
cleared = true;
}
Ok(cleared)
}
}
async fn close_sqlite_pools(pools: &[&SqlitePool]) {
for pool in pools {
pool.close().await;
}
}
/// Open and migrate the rebuildable paginated thread-history database.
pub async fn open_thread_history_db(sqlite: &SqliteConfig) -> anyhow::Result<SqlitePool> {
let migrator = runtime_thread_history_migrator();
sqlite
.open_thread_history_db(&migrator, /*telemetry_override*/ None)
.await
}
pub(super) async fn ensure_backfill_state_row_in_pool(
pool: &sqlx::SqlitePool,
) -> anyhow::Result<()> {
// Eagerly check if the operation would have no effect to avoid blocking waiting for a SQLite
// writer for no reason in the hot startup path.
if sqlx::query_scalar::<_, i64>("SELECT 1 FROM backfill_state WHERE id = 1")
.fetch_optional(pool)
.await?
.is_some()
{
return Ok(());
}
sqlx::query(
r#"
INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at)
VALUES (?, ?, NULL, NULL, ?)
ON CONFLICT(id) DO NOTHING
"#,
)
.bind(1_i64)
.bind(crate::BackfillStatus::Pending.as_str())
.bind(Utc::now().timestamp())
.execute_with_busy_retry(pool)
.await?;
Ok(())
}
/// Integrity-check rows, including those emitted before interruption.
#[derive(Debug, Eq, PartialEq)]
pub enum SqliteIntegrityCheck {
Complete(Vec<String>),
TimedOut(Vec<String>),
}
/// Run SQLite's built-in integrity check against an existing database file.
pub async fn sqlite_integrity_check(
sqlite: &SqliteConfig,
path: &Path,
deadline: Option<Instant>,
) -> anyhow::Result<SqliteIntegrityCheck> {
let pool = sqlite
.open_read_only_pool(
path,
deadline.map(|deadline| deadline.saturating_duration_since(Instant::now())),
)
.await?;
let mut connection = pool.acquire().await?;
if let Some(deadline) = deadline {
// Lock waits do not invoke the progress handler; share the remaining budget.
QueryBuilder::<Sqlite>::new("PRAGMA busy_timeout = ")
.push(
deadline
.saturating_duration_since(Instant::now())
.as_millis(),
)
.build()
.execute(&mut *connection)
.await?;
// Interrupt SQLite itself: dropping a timed-out future leaves its worker scanning.
connection
.lock_handle()
.await?
.set_progress_handler(/*num_ops*/ 1_000, move || Instant::now() < deadline);
}
let mut rows = Vec::<String>::new();
// Keep corruption rows even when a later step interrupts the scan.
let result = sqlx::query::<Sqlite>("PRAGMA integrity_check")
.try_map(|row| {
rows.push(row.try_get(/*index*/ 0)?);
Ok(())
})
.fetch_all(&mut *connection)
.await;
drop(connection);
pool.close().await;
match result {
Ok(_) => Ok(SqliteIntegrityCheck::Complete(rows)),
Err(sqlx::Error::Database(error))
if deadline.is_some()
&& error.code().is_some_and(|code| {
matches!(
code.parse::<i32>().ok().map(|code| code & 0xff),
Some(libsqlite3_sys::SQLITE_INTERRUPT | libsqlite3_sys::SQLITE_BUSY)
)
}) =>
{
Ok(SqliteIntegrityCheck::TimedOut(rows))
}
Err(error) => Err(error.into()),
}
}
#[cfg(test)]
mod tests {
use super::SqliteIntegrityCheck;
use super::StateRuntime;
use super::runtime_state_migrator;
use super::sqlite_integrity_check;
use super::test_support::test_thread_metadata;
use super::test_support::unique_temp_dir;
use crate::DB_INIT_METRIC;
use crate::DbTelemetry;
use crate::migrations::STATE_MIGRATOR;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::SqlitePool;
use sqlx::migrate::MigrateError;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
#[derive(Default)]
struct TestTelemetry {
counters: Mutex<Vec<MetricEvent>>,
}
#[derive(Debug, Eq, PartialEq)]
struct MetricEvent {
name: String,
tags: BTreeMap<String, String>,
}
impl TestTelemetry {
fn counters(&self) -> Vec<MetricEvent> {
self.counters
.lock()
.expect("telemetry lock")
.iter()
.map(|event| MetricEvent {
name: event.name.clone(),
tags: event.tags.clone(),
})
.collect()
}
}
impl DbTelemetry for TestTelemetry {
fn counter(&self, name: &str, _inc: i64, tags: &[(&str, &str)]) {
self.counters
.lock()
.expect("telemetry lock")
.push(MetricEvent {
name: name.to_string(),
tags: tags_to_map(tags),
});
}
fn record_duration(
&self,
_name: &str,
_duration: std::time::Duration,
_tags: &[(&str, &str)],
) {
}
fn histogram(&self, _name: &str, _value: i64, _tags: &[(&str, &str)]) {}
}
fn tags_to_map(tags: &[(&str, &str)]) -> BTreeMap<String, String> {
tags.iter()
.map(|(key, value)| ((*key).to_string(), (*value).to_string()))
.collect()
}
async fn open_db_pool(path: &Path) -> SqlitePool {
crate::SqliteConfig::new_for_testing(path.parent().unwrap_or(path).abs())
.open_read_write_pool(path)
.await
.expect("open sqlite pool")
}
#[tokio::test]
async fn sqlite_integrity_check_can_be_interrupted_and_retried() {
let codex_home = unique_temp_dir();
tokio::fs::create_dir_all(&codex_home)
.await
.expect("create codex home");
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
let path = sqlite.state_db_path();
let pool = sqlite
.open_read_write_pool(&path)
.await
.expect("open sqlite db");
sqlx::query("CREATE TABLE sample (id INTEGER PRIMARY KEY, value INTEGER, other INTEGER)")
.execute(&pool)
.await
.expect("create sample table");
sqlx::query("CREATE UNIQUE INDEX sample_value ON sample(value)")
.execute(&pool)
.await
.expect("create sample index");
sqlx::query(
"WITH RECURSIVE rows(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM rows WHERE id < 2048) INSERT INTO sample SELECT id, id, CASE WHEN id = 1 THEN 0 ELSE id END FROM rows",
)
.execute(&pool)
.await
.expect("populate enough rows to invoke the progress handler");
pool.close().await;
assert_eq!(
sqlite_integrity_check(&sqlite, &path, Some(Instant::now()))
.await
.expect("interrupt integrity check"),
SqliteIntegrityCheck::TimedOut(Vec::new()),
);
let result = sqlite_integrity_check(&sqlite, &path, /*deadline*/ None)
.await
.expect("integrity check should run");
assert_eq!(
result,
SqliteIntegrityCheck::Complete(vec!["ok".to_string()])
);
let pool = sqlite
.open_read_write_pool(&path)
.await
.expect("reopen sqlite db");
let mut connection = pool.acquire().await.expect("acquire writer");
// WAL readers do not wait on this writer, so use a rollback journal.
sqlx::query("PRAGMA journal_mode=DELETE; BEGIN EXCLUSIVE")
.execute(&mut *connection)
.await
.expect("hold an exclusive lock");
let started = Instant::now();
let result =
sqlite_integrity_check(&sqlite, &path, Some(started + Duration::from_millis(50)))
.await
.expect("interrupt lock wait");
let elapsed = started.elapsed();
sqlx::query("ROLLBACK")
.execute(&mut *connection)
.await
.expect("release lock");
assert_eq!(result, SqliteIntegrityCheck::TimedOut(Vec::new()));
assert!(elapsed < Duration::from_secs(1), "lock wait: {elapsed:?}");
// Misdescribe one index entry so SQLite emits an error before its first progress callback.
sqlx::query(
"PRAGMA writable_schema=ON; UPDATE sqlite_schema SET sql='CREATE UNIQUE INDEX sample_value ON sample(other)' WHERE name='sample_value'; PRAGMA writable_schema=OFF",
)
.execute(&mut *connection)
.await
.expect("introduce an index mismatch");
drop(connection);
pool.close().await;
assert_eq!(
sqlite_integrity_check(&sqlite, &path, Some(Instant::now()))
.await
.expect("retain corruption before interruption"),
SqliteIntegrityCheck::TimedOut(vec![
"row 1 missing from index sample_value".to_string()
]),
);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn open_state_sqlite_tolerates_newer_applied_migrations() {
let codex_home = unique_temp_dir();
tokio::fs::create_dir_all(&codex_home)
.await
.expect("create codex home");
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
let state_path = sqlite.state_db_path();
let pool = sqlite
.open_read_write_pool(&state_path)
.await
.expect("open state db");
STATE_MIGRATOR
.run(&pool)
.await
.expect("apply current state schema");
sqlx::query(
"INSERT INTO _sqlx_migrations (version, description, success, checksum, execution_time) VALUES (?, ?, ?, ?, ?)",
)
.bind(9_999_i64)
.bind("future migration")
.bind(true)
.bind(vec![1_u8, 2, 3, 4])
.bind(1_i64)
.execute(&pool)
.await
.expect("insert future migration record");
pool.close().await;
let strict_pool = open_db_pool(state_path.as_path()).await;
let strict_err = STATE_MIGRATOR
.run(&strict_pool)
.await
.expect_err("strict migrator should reject newer applied migrations");
assert!(matches!(strict_err, MigrateError::VersionMissing(9_999)));
strict_pool.close().await;
let tolerant_migrator = runtime_state_migrator();
let tolerant_pool = sqlite
.open_state_db(&tolerant_migrator, /*telemetry_override*/ None)
.await
.expect("runtime migrator should tolerate newer applied migrations");
tolerant_pool.close().await;
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn init_records_successful_sqlite_init_phases_to_explicit_telemetry() {
let codex_home = unique_temp_dir();
let telemetry = TestTelemetry::default();
let runtime = StateRuntime::init_with_telemetry_for_tests(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
&telemetry,
)
.await
.expect("state runtime should initialize");
let phases = telemetry
.counters()
.into_iter()
.filter(|event| event.name == DB_INIT_METRIC)
.filter(|event| event.tags.get("status").map(String::as_str) == Some("success"))
.filter_map(|event| event.tags.get("phase").cloned())
.collect::<BTreeSet<_>>();
let expected = [
"open_state",
"migrate_state",
"open_logs",
"migrate_logs",
"open_goals",
"migrate_goals",
"open_memories",
"migrate_memories",
"open_queue",
"migrate_queue",
"ensure_backfill_state",
"post_init_query",
]
.into_iter()
.map(str::to_string)
.collect::<BTreeSet<_>>();
assert_eq!(phases, expected);
runtime.close().await;
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn init_restores_independent_thread_timestamp_maxima() {
let codex_home = unique_temp_dir();
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
.await
.expect("state runtime should initialize");
for (thread_id, updated_at_ms, recency_at_ms) in [
("00000000-0000-0000-0000-000000000101", 3_000, 1_000),
("00000000-0000-0000-0000-000000000102", 1_000, 4_000),
] {
let thread_id = ThreadId::from_string(thread_id).expect("valid thread id");
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await
.expect("thread should be stored");
sqlx::query("UPDATE threads SET updated_at_ms = ?, recency_at_ms = ? WHERE id = ?")
.bind(updated_at_ms)
.bind(recency_at_ms)
.bind(thread_id.to_string())
.execute(runtime.pool.as_ref())
.await
.expect("thread timestamps should be updated");
}
runtime.close().await;
drop(runtime);
let runtime = StateRuntime::init(sqlite, "test-provider".to_string())
.await
.expect("state runtime should restore thread timestamps");
assert_eq!(
(
runtime.thread_updated_at_millis.load(Ordering::Relaxed),
runtime.thread_recency_at_millis.load(Ordering::Relaxed),
),
(3_000, 4_000)
);
runtime.close().await;
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
}

View File

@@ -0,0 +1,289 @@
use super::*;
use crate::sqlite::SqliteWriteQueryExt;
impl StateRuntime {
pub async fn get_backfill_state(&self) -> anyhow::Result<crate::BackfillState> {
self.ensure_backfill_state_row().await?;
let row = sqlx::query(
r#"
SELECT status, last_watermark, last_success_at
FROM backfill_state
WHERE id = 1
"#,
)
.fetch_one(self.pool.as_ref())
.await?;
crate::BackfillState::try_from_row(&row)
}
/// Attempt to claim ownership of rollout metadata backfill.
///
/// Returns `true` when this runtime claimed the backfill worker slot.
/// Returns `false` if backfill is already complete or currently owned by a
/// non-expired worker.
pub async fn try_claim_backfill(&self, lease_seconds: i64) -> anyhow::Result<bool> {
self.ensure_backfill_state_row().await?;
let now = Utc::now().timestamp();
let lease_cutoff = now.saturating_sub(lease_seconds.max(0));
let result = sqlx::query(
r#"
UPDATE backfill_state
SET status = ?, updated_at = ?
WHERE id = 1
AND status != ?
AND (status != ? OR updated_at <= ?)
"#,
)
.bind(crate::BackfillStatus::Running.as_str())
.bind(now)
.bind(crate::BackfillStatus::Complete.as_str())
.bind(crate::BackfillStatus::Running.as_str())
.bind(lease_cutoff)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(result.rows_affected() == 1)
}
/// Mark rollout metadata backfill as running.
pub async fn mark_backfill_running(&self) -> anyhow::Result<()> {
self.ensure_backfill_state_row().await?;
sqlx::query(
r#"
UPDATE backfill_state
SET status = ?, updated_at = ?
WHERE id = 1
"#,
)
.bind(crate::BackfillStatus::Running.as_str())
.bind(Utc::now().timestamp())
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
/// Persist rollout metadata backfill progress.
pub async fn checkpoint_backfill(&self, watermark: &str) -> anyhow::Result<()> {
self.ensure_backfill_state_row().await?;
sqlx::query(
r#"
UPDATE backfill_state
SET status = ?, last_watermark = ?, updated_at = ?
WHERE id = 1
"#,
)
.bind(crate::BackfillStatus::Running.as_str())
.bind(watermark)
.bind(Utc::now().timestamp())
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
/// Mark rollout metadata backfill as complete.
pub async fn mark_backfill_complete(&self, last_watermark: Option<&str>) -> anyhow::Result<()> {
self.ensure_backfill_state_row().await?;
let now = Utc::now().timestamp();
sqlx::query(
r#"
UPDATE backfill_state
SET
status = ?,
last_watermark = COALESCE(?, last_watermark),
last_success_at = ?,
updated_at = ?
WHERE id = 1
"#,
)
.bind(crate::BackfillStatus::Complete.as_str())
.bind(last_watermark)
.bind(now)
.bind(now)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
async fn ensure_backfill_state_row(&self) -> anyhow::Result<()> {
ensure_backfill_state_row_in_pool(self.pool.as_ref()).await
}
}
#[cfg(test)]
mod tests {
use super::StateRuntime;
use super::test_support::unique_temp_dir;
use chrono::Utc;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::Connection;
#[tokio::test]
async fn backfill_state_persists_progress_and_completion() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let initial = runtime
.get_backfill_state()
.await
.expect("get initial backfill state");
assert_eq!(initial.status, crate::BackfillStatus::Pending);
assert_eq!(initial.last_watermark, None);
assert_eq!(initial.last_success_at, None);
runtime
.mark_backfill_running()
.await
.expect("mark backfill running");
runtime
.checkpoint_backfill("sessions/2026/01/27/rollout-a.jsonl")
.await
.expect("checkpoint backfill");
let running = runtime
.get_backfill_state()
.await
.expect("get running backfill state");
assert_eq!(running.status, crate::BackfillStatus::Running);
assert_eq!(
running.last_watermark,
Some("sessions/2026/01/27/rollout-a.jsonl".to_string())
);
assert_eq!(running.last_success_at, None);
runtime
.mark_backfill_complete(Some("sessions/2026/01/28/rollout-b.jsonl"))
.await
.expect("mark backfill complete");
let completed = runtime
.get_backfill_state()
.await
.expect("get completed backfill state");
assert_eq!(completed.status, crate::BackfillStatus::Complete);
assert_eq!(
completed.last_watermark,
Some("sessions/2026/01/28/rollout-b.jsonl".to_string())
);
assert!(completed.last_success_at.is_some());
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn get_backfill_state_succeeds_while_another_connection_holds_writer_slot() {
let codex_home = unique_temp_dir();
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string())
.await
.expect("initialize runtime");
let write_pool = sqlite
.open_read_write_pool(&sqlite.state_db_path())
.await
.expect("open write pool");
let mut write_connection = write_pool.acquire().await.expect("open write connection");
let write_transaction = write_connection
.begin_with("BEGIN IMMEDIATE")
.await
.expect("acquire write lock");
let state = runtime
.get_backfill_state()
.await
.expect("get backfill state");
assert_eq!(state, crate::BackfillState::default());
write_transaction
.rollback()
.await
.expect("release write lock");
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn get_backfill_state_repairs_a_missing_singleton_row() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
sqlx::query("DELETE FROM backfill_state WHERE id = 1")
.execute(runtime.pool.as_ref())
.await
.expect("delete backfill state row");
let state = runtime
.get_backfill_state()
.await
.expect("get repaired backfill state");
assert_eq!(state, crate::BackfillState::default());
let row_count =
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM backfill_state WHERE id = 1")
.fetch_one(runtime.pool.as_ref())
.await
.expect("count repaired backfill state rows");
assert_eq!(row_count, 1);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn backfill_claim_is_singleton_until_stale_and_blocked_when_complete() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let claimed = runtime
.try_claim_backfill(/*lease_seconds*/ 3600)
.await
.expect("initial backfill claim");
assert_eq!(claimed, true);
let duplicate_claim = runtime
.try_claim_backfill(/*lease_seconds*/ 3600)
.await
.expect("duplicate backfill claim");
assert_eq!(duplicate_claim, false);
let stale_updated_at = Utc::now().timestamp().saturating_sub(10_000);
sqlx::query(
r#"
UPDATE backfill_state
SET status = ?, updated_at = ?
WHERE id = 1
"#,
)
.bind(crate::BackfillStatus::Running.as_str())
.bind(stale_updated_at)
.execute(runtime.pool.as_ref())
.await
.expect("force stale backfill lease");
let stale_claim = runtime
.try_claim_backfill(/*lease_seconds*/ 10)
.await
.expect("stale backfill claim");
assert_eq!(stale_claim, true);
runtime
.mark_backfill_complete(/*last_watermark*/ None)
.await
.expect("mark complete");
let claim_after_complete = runtime
.try_claim_backfill(/*lease_seconds*/ 3600)
.await
.expect("claim after complete");
assert_eq!(claim_after_complete, false);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
}

View File

@@ -0,0 +1,149 @@
use super::StateRuntime;
use crate::model::datetime_to_epoch_millis;
use crate::sqlite::SqliteWriteQueryExt;
use chrono::Utc;
use serde::Deserialize;
use serde::Serialize;
use sqlx::Row;
use std::path::PathBuf;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalAgentConfigImportSuccessRecord {
pub item_type: String,
pub cwd: Option<PathBuf>,
pub source: Option<String>,
pub target: Option<String>,
#[serde(default)]
pub title: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalAgentConfigImportFailureRecord {
pub item_type: String,
pub error_type: Option<String>,
#[serde(default)]
pub sub_error_type: Option<String>,
pub failure_stage: String,
pub message: String,
pub cwd: Option<PathBuf>,
pub source: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalAgentConfigImportDetailsRecord {
pub successes: Vec<ExternalAgentConfigImportSuccessRecord>,
pub failures: Vec<ExternalAgentConfigImportFailureRecord>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExternalAgentConfigImportHistoryRecord {
pub import_id: String,
pub provider_id: Option<String>,
pub completed_at_ms: i64,
pub successes: Vec<ExternalAgentConfigImportSuccessRecord>,
pub failures: Vec<ExternalAgentConfigImportFailureRecord>,
}
impl StateRuntime {
pub async fn record_external_agent_config_import_completed(
&self,
import_id: &str,
provider_id: Option<&str>,
successes: &[ExternalAgentConfigImportSuccessRecord],
failures: &[ExternalAgentConfigImportFailureRecord],
) -> anyhow::Result<()> {
sqlx::query(
r#"
INSERT INTO external_agent_config_imports (
import_id,
provider_id,
completed_at_ms,
successes,
failures
) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(import_id) DO UPDATE SET
provider_id = excluded.provider_id,
completed_at_ms = excluded.completed_at_ms,
successes = excluded.successes,
failures = excluded.failures
"#,
)
.bind(import_id)
.bind(provider_id)
.bind(datetime_to_epoch_millis(Utc::now()))
.bind(serde_json::to_string(successes)?)
.bind(serde_json::to_string(failures)?)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
pub async fn external_agent_config_import_details_record(
&self,
import_id: &str,
) -> anyhow::Result<Option<ExternalAgentConfigImportDetailsRecord>> {
let row = sqlx::query(
r#"
SELECT
successes,
failures
FROM external_agent_config_imports
WHERE import_id = ?
"#,
)
.bind(import_id)
.fetch_optional(self.pool.as_ref())
.await?;
row.map(|row| {
let successes: String = row.try_get("successes")?;
let failures: String = row.try_get("failures")?;
Ok(ExternalAgentConfigImportDetailsRecord {
successes: serde_json::from_str(&successes)?,
failures: serde_json::from_str(&failures)?,
})
})
.transpose()
}
pub async fn external_agent_config_import_history_records(
&self,
) -> anyhow::Result<Vec<ExternalAgentConfigImportHistoryRecord>> {
let rows = sqlx::query(
r#"
SELECT
import_id,
provider_id,
completed_at_ms,
successes,
failures
FROM external_agent_config_imports
ORDER BY completed_at_ms DESC, import_id ASC
"#,
)
.fetch_all(self.pool.as_ref())
.await?;
rows.into_iter()
.map(|row| {
let import_id: String = row.try_get("import_id")?;
let provider_id: Option<String> = row.try_get("provider_id")?;
let completed_at_ms: i64 = row.try_get("completed_at_ms")?;
let successes: String = row.try_get("successes")?;
let failures: String = row.try_get("failures")?;
Ok(ExternalAgentConfigImportHistoryRecord {
import_id,
provider_id,
completed_at_ms,
successes: serde_json::from_str(&successes)?,
failures: serde_json::from_str(&failures)?,
})
})
.collect()
}
}
#[cfg(test)]
#[path = "external_agent_config_imports_tests.rs"]
mod tests;

View File

@@ -0,0 +1,178 @@
use super::*;
use crate::runtime::test_support::unique_temp_dir;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn records_completion_by_import_id() -> anyhow::Result<()> {
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(unique_temp_dir().as_path().abs()),
"test-provider".to_string(),
)
.await?;
runtime
.record_external_agent_config_import_completed(
"import-1",
Some("provider-1"),
&[ExternalAgentConfigImportSuccessRecord {
item_type: "CONFIG".to_string(),
cwd: None,
source: Some("settings.json".to_string()),
target: Some("config.toml".to_string()),
title: None,
}],
&[],
)
.await?;
runtime
.record_external_agent_config_import_completed(
"import-1",
Some("provider-2"),
&[
ExternalAgentConfigImportSuccessRecord {
item_type: "CONFIG".to_string(),
cwd: None,
source: Some("settings.json".to_string()),
target: Some("config.toml".to_string()),
title: None,
},
ExternalAgentConfigImportSuccessRecord {
item_type: "MCP_SERVER_CONFIG".to_string(),
cwd: None,
source: Some("github".to_string()),
target: Some("github".to_string()),
title: None,
},
],
&[ExternalAgentConfigImportFailureRecord {
item_type: "MCP_SERVER_CONFIG".to_string(),
error_type: None,
sub_error_type: Some("failed_to_copy_plugin_file".to_string()),
failure_stage: "import".to_string(),
message: "failed".to_string(),
cwd: None,
source: Some("broken".to_string()),
}],
)
.await?;
assert_eq!(
runtime
.external_agent_config_import_details_record("import-1")
.await?,
Some(ExternalAgentConfigImportDetailsRecord {
successes: vec![
ExternalAgentConfigImportSuccessRecord {
item_type: "CONFIG".to_string(),
cwd: None,
source: Some("settings.json".to_string()),
target: Some("config.toml".to_string()),
title: None,
},
ExternalAgentConfigImportSuccessRecord {
item_type: "MCP_SERVER_CONFIG".to_string(),
cwd: None,
source: Some("github".to_string()),
target: Some("github".to_string()),
title: None,
}
],
failures: vec![ExternalAgentConfigImportFailureRecord {
item_type: "MCP_SERVER_CONFIG".to_string(),
error_type: None,
sub_error_type: Some("failed_to_copy_plugin_file".to_string()),
failure_stage: "import".to_string(),
message: "failed".to_string(),
cwd: None,
source: Some("broken".to_string()),
}],
})
);
assert_eq!(
runtime
.external_agent_config_import_history_records()
.await?
.into_iter()
.map(|record| (
record.import_id,
record.provider_id,
record.successes,
record.failures,
record.completed_at_ms > 0
))
.collect::<Vec<_>>(),
vec![(
"import-1".to_string(),
Some("provider-2".to_string()),
vec![
ExternalAgentConfigImportSuccessRecord {
item_type: "CONFIG".to_string(),
cwd: None,
source: Some("settings.json".to_string()),
target: Some("config.toml".to_string()),
title: None,
},
ExternalAgentConfigImportSuccessRecord {
item_type: "MCP_SERVER_CONFIG".to_string(),
cwd: None,
source: Some("github".to_string()),
target: Some("github".to_string()),
title: None,
}
],
vec![ExternalAgentConfigImportFailureRecord {
item_type: "MCP_SERVER_CONFIG".to_string(),
error_type: None,
sub_error_type: Some("failed_to_copy_plugin_file".to_string()),
failure_stage: "import".to_string(),
message: "failed".to_string(),
cwd: None,
source: Some("broken".to_string()),
}],
true
)]
);
Ok(())
}
#[tokio::test]
async fn reads_all_history_records() -> anyhow::Result<()> {
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(unique_temp_dir().as_path().abs()),
"test-provider".to_string(),
)
.await?;
runtime
.record_external_agent_config_import_completed(
"import-1",
/*provider_id*/ None,
&[],
&[],
)
.await?;
runtime
.record_external_agent_config_import_completed(
"import-2",
/*provider_id*/ None,
&[],
&[],
)
.await?;
let mut records = runtime
.external_agent_config_import_history_records()
.await?;
records.sort_by(|left, right| left.import_id.cmp(&right.import_id));
assert_eq!(
records
.into_iter()
.map(|record| record.import_id)
.collect::<Vec<_>>(),
vec!["import-1".to_string(), "import-2".to_string()]
);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,92 @@
//! Bounded failed-review evidence, retained independently of short-lived reviewers.
//! Insertion and eviction share one budget; deleting the reviewed thread cascades to its evidence.
use super::StateRuntime;
use codex_protocol::ThreadId;
use sqlx::Row;
use uuid::Uuid;
pub const MAX_GUARDIAN_REVIEW_RECORDS: usize = 64;
pub const MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD: usize = 8;
pub const MAX_GUARDIAN_REVIEW_BYTES: usize = 8 * 1024 * 1024;
/// One complete serialized review, ordered by its capture-time UUIDv7.
#[derive(Clone)]
pub struct GuardianReviewRecord {
pub id: String,
pub thread_id: ThreadId,
pub record: Vec<u8>,
}
impl GuardianReviewRecord {
pub fn new(thread_id: ThreadId, record: Vec<u8>) -> Self {
Self {
id: Uuid::now_v7().to_string(),
thread_id,
record,
}
}
}
impl StateRuntime {
/// Retain opt-in evidence for a persisted actor; the reviewer need not remain alive.
pub async fn record_guardian_review_failure(
&self,
record: &GuardianReviewRecord,
) -> anyhow::Result<()> {
anyhow::ensure!(
record.record.len() < MAX_GUARDIAN_REVIEW_BYTES,
"Guardian feedback record exceeds its size limit"
);
let mut transaction = self.pool.begin_with("BEGIN IMMEDIATE").await?;
sqlx::query(
"INSERT INTO guardian_review_feedback (id, thread_id, record) VALUES (?, ?, ?)",
)
.bind(&record.id)
.bind(record.thread_id.to_string())
.bind(&record.record)
.execute(&mut *transaction)
.await?;
sqlx::query(
"DELETE FROM guardian_review_feedback WHERE id IN \
(SELECT id FROM guardian_review_feedback WHERE thread_id = ? \
ORDER BY id DESC LIMIT -1 OFFSET ?)",
)
.bind(record.thread_id.to_string())
.bind(MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD as i64)
.execute(&mut *transaction)
.await?;
sqlx::query(
"DELETE FROM guardian_review_feedback WHERE id IN \
(SELECT id FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id DESC) AS n, \
SUM(length(record) + 1) OVER (ORDER BY id DESC) AS bytes \
FROM guardian_review_feedback) WHERE n > ? OR bytes > ?)",
)
.bind(MAX_GUARDIAN_REVIEW_RECORDS as i64)
.bind(MAX_GUARDIAN_REVIEW_BYTES as i64)
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(())
}
/// Read the bounded retained history, oldest first. Callers must scope exports to a task.
pub async fn list_guardian_review_records(&self) -> anyhow::Result<Vec<GuardianReviewRecord>> {
sqlx::query("SELECT id, thread_id, record FROM guardian_review_feedback ORDER BY id")
.fetch_all(self.pool.as_ref())
.await?
.into_iter()
.map(|row| {
Ok(GuardianReviewRecord {
id: row.try_get("id")?,
thread_id: ThreadId::from_string(row.try_get("thread_id")?)?,
record: row.try_get("record")?,
})
})
.collect()
}
}
#[cfg(test)]
#[path = "guardian_feedback_tests.rs"]
mod tests;

View File

@@ -0,0 +1,99 @@
//! Storage-level coverage for bounded review retention and actor deletion.
use super::*;
use crate::SqliteConfig;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn retention_survives_reopen_and_bounds_count_and_bytes() -> anyhow::Result<()> {
let home = unique_temp_dir();
let sqlite = SqliteConfig::new_for_testing(home.clone().try_into()?);
let state = StateRuntime::init(sqlite.clone(), "test".to_string()).await?;
let mut ids = Vec::new();
for _ in 0..=MAX_GUARDIAN_REVIEW_RECORDS {
let id = ThreadId::new();
state
.upsert_thread(&test_thread_metadata(&home, id, home.clone()))
.await?;
let record = GuardianReviewRecord::new(id, b"{}".to_vec());
state.record_guardian_review_failure(&record).await?;
ids.push(id);
}
state.close().await;
let state = StateRuntime::init(sqlite, "test".to_string()).await?;
assert_eq!(
state
.list_guardian_review_records()
.await?
.iter()
.map(|record| record.thread_id)
.collect::<Vec<_>>(),
ids[1..],
);
let id = ids[0];
for index in 0..12 {
state
.record_guardian_review_failure(&GuardianReviewRecord::new(
id,
index.to_string().into_bytes(),
))
.await?;
}
assert_eq!(
state
.list_guardian_review_records()
.await?
.into_iter()
.filter(|record| record.thread_id == id)
.map(|record| record.record)
.collect::<Vec<_>>(),
(4..12)
.map(|index| index.to_string().into_bytes())
.collect::<Vec<_>>(),
);
let payload = vec![b' '; MAX_GUARDIAN_REVIEW_BYTES / 3];
for _ in 0..4 {
state
.record_guardian_review_failure(&GuardianReviewRecord::new(id, payload.clone()))
.await?;
}
assert_eq!(
state
.list_guardian_review_records()
.await?
.into_iter()
.map(|record| (record.thread_id, record.record))
.collect::<Vec<_>>(),
vec![(id, payload.clone()), (id, payload)],
);
state.close().await;
std::fs::remove_dir_all(home)?;
Ok(())
}
#[tokio::test]
async fn deleting_an_actor_removes_evidence_and_rejects_late_captures() -> anyhow::Result<()> {
let home = unique_temp_dir();
let sqlite = SqliteConfig::new_for_testing(home.clone().try_into()?);
let state = StateRuntime::init(sqlite.clone(), "test".to_string()).await?;
let id = ThreadId::new();
state
.upsert_thread(&test_thread_metadata(&home, id, home.clone()))
.await?;
let record = GuardianReviewRecord::new(id, b"private review context".to_vec());
state.record_guardian_review_failure(&record).await?;
// Older binaries delete the actor without knowing about the review table.
sqlx::query("DELETE FROM threads WHERE id = ?")
.bind(id.to_string())
.execute(state.pool.as_ref())
.await?;
state.close().await;
let state = StateRuntime::init(sqlite, "test".to_string()).await?;
assert!(state.list_guardian_review_records().await?.is_empty());
assert!(state.record_guardian_review_failure(&record).await.is_err());
state.close().await;
std::fs::remove_dir_all(home)?;
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,99 @@
//! Prune current and legacy diagnostic logs immediately, then on a timer.
//! SQLite keeps freed pages for reuse.
use super::StateRuntime;
use chrono::Utc;
use sqlx::SqlitePool;
use std::sync::Arc;
use std::time::Duration;
const LOG_RETENTION_SECONDS: i64 = 10 * 24 * 60 * 60; // 10 days
const LOG_DATABASE_BUDGET_BYTES: i64 = 64 * 1024 * 1024; // 64 MiB
impl StateRuntime {
pub(super) fn start_periodic_logs_maintenance(self: &Arc<Self>, period: Duration) {
let runtime = Arc::downgrade(self);
tokio::spawn(async move {
let mut interval = tokio::time::interval_at(
/*start*/ tokio::time::Instant::now(),
/*period*/ period,
);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut first_sweep = true;
loop {
// Hold no strong runtime reference while waiting.
interval.tick().await;
let Some(runtime) = runtime.upgrade() else {
break;
};
if runtime.logs_pool.is_closed() {
break;
}
// Older versions write logs in sqlite_home. Keep the same retention policy
// there until those logs expire. Do not create a missing legacy database.
let legacy_pool = match runtime.sqlite.open_legacy_logs_for_cleanup().await {
Ok(pool) => pool,
Err(err) => {
tracing::warn!("failed to open legacy diagnostic logs for cleanup: {err}");
None
}
};
for pool in std::iter::once(runtime.logs_pool.as_ref()).chain(legacy_pool.as_ref())
{
if let Err(err) = prune_by_age_and_size(
pool,
Utc::now().timestamp(),
LOG_DATABASE_BUDGET_BYTES,
)
.await
{
tracing::warn!("failed to prune diagnostic logs: {err}");
}
if first_sweep {
// Preserve the startup checkpoint without waiting for readers or writers.
if let Err(err) = sqlx::query("PRAGMA wal_checkpoint(PASSIVE)")
.execute(pool)
.await
{
tracing::warn!("failed to checkpoint diagnostic logs: {err}");
}
}
}
if let Some(pool) = legacy_pool {
pool.close().await;
}
first_sweep = false;
}
});
}
}
async fn prune_by_age_and_size(
pool: &SqlitePool,
now: i64,
budget_bytes: i64,
) -> anyhow::Result<()> {
let mut retention_seconds = LOG_RETENTION_SECONDS;
loop {
sqlx::query("DELETE FROM logs WHERE ts < ?")
.bind(now.saturating_sub(retention_seconds))
.execute(pool)
.await?;
// Exclude free pages: SQLite reuses them without shrinking the file.
let occupied_bytes: i64 = sqlx::query_scalar(
"SELECT (page_count - freelist_count) * page_size \
FROM pragma_page_count(), pragma_freelist_count(), pragma_page_size()",
)
.fetch_one(pool)
.await?;
if occupied_bytes <= budget_bytes || retention_seconds == 1 {
return Ok(());
}
// Keep the newest second even if it exceeds the budget.
retention_seconds = (retention_seconds / 2).max(1);
}
}
#[cfg(test)]
#[path = "logs_maintenance_tests.rs"]
mod tests;

View File

@@ -0,0 +1,285 @@
//! Exercise age/size pruning and automatic cleanup of an idle runtime.
use super::LOG_RETENTION_SECONDS;
use super::StateRuntime;
use super::prune_by_age_and_size;
use crate::SqliteConfig;
use crate::migrations::LOGS_MIGRATOR;
use chrono::Utc;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::SqlitePool;
use std::path::PathBuf;
use std::time::Duration;
const NOW: i64 = 2_000_000_000;
const DAY: i64 = 24 * 60 * 60;
async fn database_with_logs(ages: &[i64]) -> (SqlitePool, PathBuf) {
let directory = super::super::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&directory).await.unwrap();
let pool = SqliteConfig::new_for_testing(directory.as_path().abs())
.open_read_write_pool(&directory.join("logs.sqlite"))
.await
.unwrap();
LOGS_MIGRATOR.run(&pool).await.unwrap();
for age in ages {
sqlx::query(
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body) \
VALUES (?, 0, 'INFO', 'retention-test', ?)",
)
.bind(NOW - age)
.bind("x".repeat(128 * 1024))
.execute(&pool)
.await
.unwrap();
}
(pool, directory)
}
async fn retained_ages(pool: &SqlitePool) -> Vec<i64> {
sqlx::query_scalar("SELECT ? - ts FROM logs ORDER BY ts DESC")
.bind(NOW)
.fetch_all(pool)
.await
.unwrap()
}
#[tokio::test]
async fn keeps_ten_day_boundary_when_under_budget() {
let (pool, directory) =
database_with_logs(&[0, LOG_RETENTION_SECONDS, LOG_RETENTION_SECONDS + 1]).await;
prune_by_age_and_size(&pool, NOW, /*budget_bytes*/ 1024 * 1024)
.await
.unwrap();
assert_eq!(retained_ages(&pool).await, vec![0, LOG_RETENTION_SECONDS]);
pool.close().await;
tokio::fs::remove_dir_all(directory).await.unwrap();
}
#[tokio::test]
async fn halves_again_when_first_halving_deletes_nothing() {
let (pool, directory) = database_with_logs(&[DAY, 2 * DAY, 4 * DAY]).await;
// Three payloads exceed this budget; two fit, including table/index pages.
prune_by_age_and_size(&pool, NOW, /*budget_bytes*/ 350 * 1024)
.await
.unwrap();
assert_eq!(retained_ages(&pool).await, vec![DAY, 2 * DAY]);
// A second cleanup must ignore free pages left in the file.
let allocated: i64 = sqlx::query_scalar(
"SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()",
)
.fetch_one(&pool)
.await
.unwrap();
assert!(allocated > 350 * 1024);
prune_by_age_and_size(&pool, NOW, /*budget_bytes*/ 350 * 1024)
.await
.unwrap();
assert_eq!(retained_ages(&pool).await, vec![DAY, 2 * DAY]);
pool.close().await;
tokio::fs::remove_dir_all(directory).await.unwrap();
}
#[tokio::test]
async fn stops_at_one_second_when_recent_rows_exceed_budget() {
let (pool, directory) = database_with_logs(&[-1, 0, 1, 2, DAY]).await;
prune_by_age_and_size(&pool, NOW, /*budget_bytes*/ 1)
.await
.unwrap();
assert_eq!(retained_ages(&pool).await, vec![-1, 0, 1]);
pool.close().await;
tokio::fs::remove_dir_all(directory).await.unwrap();
}
#[tokio::test]
async fn periodic_cleanup_prunes_without_new_log_writes_or_restart() {
let directory = super::super::test_support::unique_temp_dir();
let sqlite = SqliteConfig::new_for_testing(directory.as_path().abs());
let runtime = StateRuntime::init(
sqlite.clone().with_local_logs_home(directory.join("log")),
"test-provider".to_string(),
)
.await
.unwrap();
// An older process can create the legacy database after the new runtime starts.
let legacy_pool = sqlite
.open_logs_db(&LOGS_MIGRATOR, /*telemetry_override*/ None)
.await
.unwrap();
runtime.start_periodic_logs_maintenance(Duration::from_millis(10));
let now = Utc::now().timestamp();
for round in 1..=2 {
for pool in [runtime.logs_pool.as_ref(), &legacy_pool] {
for timestamp in [now - 11 * DAY, now] {
sqlx::query(
"INSERT INTO logs (ts, ts_nanos, level, target) VALUES (?, 0, 'INFO', 'test')",
)
.bind(timestamp)
.execute(pool)
.await
.unwrap();
}
}
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let current: Vec<i64> = sqlx::query_scalar("SELECT ts FROM logs ORDER BY ts")
.fetch_all(runtime.logs_pool.as_ref())
.await
.unwrap();
let legacy: Vec<i64> = sqlx::query_scalar("SELECT ts FROM logs ORDER BY ts")
.fetch_all(&legacy_pool)
.await
.unwrap();
if (current, legacy) == (vec![now; round], vec![now; round]) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("periodic cleanup should remove expired logs from both locations while idle");
}
legacy_pool.close().await;
runtime.close().await;
tokio::fs::remove_dir_all(directory).await.unwrap();
}
#[tokio::test]
async fn legacy_cleanup_skips_missing_and_shared_databases() -> anyhow::Result<()> {
let directory = super::super::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&directory).await?;
let sqlite = SqliteConfig::new_for_testing(directory.as_path().abs());
let legacy_path = sqlite.logs_db_path();
for logs_home in [directory.clone(), directory.join("log")] {
let sqlite = sqlite.clone().with_local_logs_home(logs_home);
assert!(sqlite.open_legacy_logs_for_cleanup().await?.is_none());
assert!(!legacy_path.exists());
}
let pool = sqlite
.open_logs_db(&LOGS_MIGRATOR, /*telemetry_override*/ None)
.await?;
assert!(sqlite.open_legacy_logs_for_cleanup().await?.is_none());
pool.close().await;
tokio::fs::remove_dir_all(directory).await?;
Ok(())
}
#[tokio::test]
async fn legacy_writer_does_not_block_current_cleanup_and_is_retried() -> anyhow::Result<()> {
let directory = super::super::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&directory).await?;
let sqlite = SqliteConfig::new_for_testing(directory.as_path().abs());
let legacy_pool = sqlite
.open_logs_db(&LOGS_MIGRATOR, /*telemetry_override*/ None)
.await?;
sqlx::query("INSERT INTO logs (ts, ts_nanos, level, target) VALUES (0, 0, 'INFO', 'test')")
.execute(&legacy_pool)
.await?;
let writer = legacy_pool.begin_with("BEGIN IMMEDIATE").await?;
let runtime = StateRuntime::init(
sqlite.with_local_logs_home(directory.join("log")),
"test-provider".to_string(),
)
.await?;
sqlx::query("INSERT INTO logs (ts, ts_nanos, level, target) VALUES (0, 0, 'INFO', 'test')")
.execute(runtime.logs_pool.as_ref())
.await?;
runtime.start_periodic_logs_maintenance(Duration::from_millis(10));
tokio::time::timeout(Duration::from_secs(5), async {
while sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM logs")
.fetch_one(runtime.logs_pool.as_ref())
.await
.unwrap()
!= 0
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await?;
assert_eq!(
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM logs")
.fetch_one(&legacy_pool)
.await?,
1
);
writer.rollback().await?;
tokio::time::timeout(Duration::from_secs(5), async {
while sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM logs")
.fetch_one(&legacy_pool)
.await
.unwrap()
!= 0
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await?;
legacy_pool.close().await;
runtime.close().await;
tokio::fs::remove_dir_all(directory).await?;
Ok(())
}
#[tokio::test]
async fn startup_cleanup_runs_without_waiting_for_the_period() {
for separate_logs in [false, true] {
let directory = super::super::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&directory).await.unwrap();
let sqlite = SqliteConfig::new_for_testing(directory.as_path().abs());
let legacy_path = sqlite.logs_db_path();
let legacy_pool = sqlite
.open_logs_db(&LOGS_MIGRATOR, /*telemetry_override*/ None)
.await
.unwrap();
let sqlite = if separate_logs {
sqlite.with_local_logs_home(directory.join("log"))
} else {
sqlite
};
let pool = sqlite
.open_logs_db(&LOGS_MIGRATOR, /*telemetry_override*/ None)
.await
.unwrap();
for pool in [&pool, &legacy_pool] {
sqlx::query(
"INSERT INTO logs (ts, ts_nanos, level, target) VALUES (0, 0, 'INFO', 'test')",
)
.execute(pool)
.await
.unwrap();
}
pool.close().await;
legacy_pool.close().await;
let runtime = StateRuntime::init(sqlite, "test-provider".to_string())
.await
.unwrap();
let legacy_pool = runtime
.sqlite
.open_read_only_pool(&legacy_path, /*busy_timeout*/ None)
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let current: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM logs")
.fetch_one(runtime.logs_pool.as_ref())
.await
.unwrap();
let legacy: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM logs")
.fetch_one(&legacy_pool)
.await
.unwrap();
if (current, legacy) == (0, 0) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("startup cleanup should prune both locations before the 30-minute interval");
legacy_pool.close().await;
runtime.close().await;
tokio::fs::remove_dir_all(directory).await.unwrap();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
//! Consolidation progress used to select a warmed memory pipeline.
use super::MemoryStore;
impl MemoryStore {
/// Largest number of distinct source threads included in a successful consolidation.
/// Kept across ordinary pruning, and cleared by an explicit memory reset.
pub async fn max_consolidated_thread_count(&self) -> anyhow::Result<u32> {
let count: i64 = sqlx::query_scalar(
"SELECT max_thread_count FROM consolidation_progress WHERE singleton = 1",
)
.fetch_one(self.pool.as_ref())
.await?;
Ok(u32::try_from(count)?)
}
}

View File

@@ -0,0 +1,56 @@
//! Creates isolated v2 memory state on demand while sharing the source thread catalog.
//! Reset and thread deletion always cover every existing version.
use super::MemoryStore;
use super::StateRuntime;
use codex_protocol::MemoryVersion;
use codex_protocol::ThreadId;
use std::sync::Arc;
impl StateRuntime {
pub async fn memories_for_version(
&self,
version: MemoryVersion,
) -> anyhow::Result<MemoryStore> {
match version {
MemoryVersion::V1 => Ok(self.memories.clone()),
MemoryVersion::V2 => self
.memories_v2
.get_or_try_init(|| async {
let pool = self.sqlite.open_memories_v2_db().await?;
Ok(MemoryStore::new(Arc::new(pool), Arc::clone(&self.pool)))
})
.await
.cloned(),
}
}
pub async fn clear_all_memory_data(&self) -> anyhow::Result<()> {
self.memories.clear_memory_data().await?;
if tokio::fs::try_exists(self.sqlite.memories_v2_db_path()).await? {
self.memories_for_version(MemoryVersion::V2)
.await?
.clear_memory_data()
.await?;
}
Ok(())
}
pub(super) async fn delete_versioned_thread_memory(
&self,
thread_id: ThreadId,
) -> anyhow::Result<()> {
self.memories.delete_thread_memory(thread_id).await?;
if tokio::fs::try_exists(self.sqlite.memories_v2_db_path()).await? {
self.memories_for_version(MemoryVersion::V2)
.await?
.delete_thread_memory(thread_id)
.await?;
}
Ok(())
}
}
#[cfg(test)]
#[path = "memory_versions_tests.rs"]
mod tests;

View File

@@ -0,0 +1,113 @@
use super::*;
use crate::SqliteConfig;
use crate::Stage1JobClaimOutcome;
use crate::runtime::test_support::test_thread_metadata;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn versions_isolate_jobs_outputs_and_reset_without_losing_threads() -> anyhow::Result<()> {
let home = crate::runtime::test_support::unique_temp_dir();
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let db = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
assert!(!sqlite.memories_v2_db_path().exists());
let thread_id = ThreadId::new();
let metadata = test_thread_metadata(home.as_path(), thread_id, home.as_path().join("project"));
db.upsert_thread(&metadata).await?;
for version in [MemoryVersion::V1, MemoryVersion::V2] {
let store = db.memories_for_version(version).await?;
let Stage1JobClaimOutcome::Claimed { ownership_token } = store
.try_claim_stage1_job(
thread_id,
thread_id,
metadata.updated_at.timestamp(),
/*lease_seconds*/ 60,
/*max_running_jobs*/ 1,
)
.await?
else {
panic!("each version must independently claim the same source")
};
assert!(
store
.mark_stage1_job_succeeded(
thread_id,
&ownership_token,
metadata.updated_at.timestamp(),
"raw",
version.directory_name(),
/*rollout_slug*/ None
)
.await?
);
}
for version in [MemoryVersion::V1, MemoryVersion::V2] {
let outputs = db
.memories_for_version(version)
.await?
.list_stage1_outputs_for_global(/*n*/ 10)
.await?;
assert_eq!(
outputs
.iter()
.map(|output| output.rollout_summary.as_str())
.collect::<Vec<_>>(),
vec![version.directory_name()]
);
}
// Reopening under v1 must still clear existing v2 state.
db.close().await;
let db = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
db.delete_thread(thread_id).await?;
for version in [MemoryVersion::V1, MemoryVersion::V2] {
assert!(
db.memories_for_version(version)
.await?
.list_stage1_outputs_for_global(/*n*/ 10)
.await?
.is_empty()
);
}
db.upsert_thread(&metadata).await?;
for version in [MemoryVersion::V1, MemoryVersion::V2] {
let store = db.memories_for_version(version).await?;
let Stage1JobClaimOutcome::Claimed { ownership_token } = store
.try_claim_stage1_job(
thread_id,
thread_id,
metadata.updated_at.timestamp(),
/*lease_seconds*/ 60,
/*max_running_jobs*/ 1,
)
.await?
else {
panic!("deletion must clear the job watermark")
};
store
.mark_stage1_job_succeeded(
thread_id,
&ownership_token,
metadata.updated_at.timestamp(),
"raw",
"summary",
/*rollout_slug*/ None,
)
.await?;
}
db.clear_all_memory_data().await?;
for version in [MemoryVersion::V1, MemoryVersion::V2] {
assert!(
db.memories_for_version(version)
.await?
.list_stage1_outputs_for_global(/*n*/ 10)
.await?
.is_empty()
);
}
assert!(db.get_thread(thread_id).await?.is_some());
db.close().await;
assert!(StateRuntime::clear_memory_data_in_sqlite_home(&sqlite).await?);
tokio::fs::remove_dir_all(home).await?;
Ok(())
}

View File

@@ -0,0 +1,574 @@
//! Persists projects and assignments, and lists projects with computed member recency.
//! Listing pagination precedes root hydration; cursor anchors preserve milliseconds and nulls.
use std::collections::BTreeMap;
use sqlx::QueryBuilder;
use sqlx::Row;
use sqlx::Sqlite;
use uuid::Uuid;
use super::StateRuntime;
use crate::CreatedProject;
use crate::Project;
use crate::ProjectRoot;
use crate::ProjectSortKey;
use crate::ProjectsPage;
use crate::SortDirection;
use crate::sqlite::SqlitePoolWriteExt;
const PROJECT_SELECT: &str = "SELECT projects.*,
(SELECT MAX(recency_at_ms) FROM threads
WHERE project_id = projects.id AND archived = 0) AS recency_at_ms
FROM projects";
impl StateRuntime {
pub async fn set_thread_project(
&self,
thread_id: &str,
project_id: Option<&str>,
) -> anyhow::Result<Option<Option<String>>> {
let mut tx = self.pool.begin_immediate().await?;
if let Some(project_id) = project_id {
let exists = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM projects WHERE id = ?")
.bind(project_id)
.fetch_one(&mut *tx)
.await?;
if exists == 0 {
tx.rollback().await?;
anyhow::bail!("project not found: {project_id}");
}
}
let previous =
sqlx::query_scalar::<_, Option<String>>("SELECT project_id FROM threads WHERE id = ?")
.bind(thread_id)
.fetch_optional(&mut *tx)
.await?;
let Some(previous) = previous else {
tx.rollback().await?;
return Ok(None);
};
if previous.as_deref() != project_id {
sqlx::query("UPDATE threads SET project_id = ? WHERE id = ?")
.bind(project_id)
.bind(thread_id)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(Some(previous))
}
pub async fn list_projects(
&self,
cursor: Option<&str>,
limit: usize,
sort_key: ProjectSortKey,
sort_direction: SortDirection,
) -> anyhow::Result<ProjectsPage> {
let mut query = project_list_query(cursor, limit, sort_key, sort_direction)?;
let rows = query.build().fetch_all(self.pool.as_ref()).await?;
let mut projects: Vec<Project> = Vec::new();
for row in rows {
let id: String = row.try_get("id")?;
if projects.last().is_none_or(|project| project.id != id) {
projects.push(project_from_row(&row, Vec::new())?);
}
if let Some(path) = row.try_get::<Option<String>, _>("root_path")? {
let project = projects
.last_mut()
.ok_or_else(|| anyhow::anyhow!("project missing for root"))?;
project.roots.push(ProjectRoot { path });
}
}
let next_cursor = (projects.len() > limit)
.then(|| project_cursor(&projects[limit - 1], sort_key, sort_direction));
projects.truncate(limit);
Ok(ProjectsPage {
projects,
next_cursor,
})
}
pub async fn get_project(&self, id: &str) -> anyhow::Result<Option<Project>> {
let mut tx = self.pool.begin().await?;
let row = QueryBuilder::<Sqlite>::new(PROJECT_SELECT)
.push(" WHERE id = ")
.push_bind(id)
.build()
.fetch_optional(&mut *tx)
.await?;
let project = match row {
Some(row) => Some(project_from_row_in_tx(&mut tx, &row).await?),
None => None,
};
tx.commit().await?;
Ok(project)
}
pub async fn get_project_by_idempotency_key(
&self,
idempotency_key: &str,
) -> anyhow::Result<Option<Project>> {
let mut tx = self.pool.begin().await?;
let project_id = sqlx::query_scalar::<_, String>(
"SELECT project_id FROM project_idempotency_keys WHERE key = ?",
)
.bind(idempotency_key)
.fetch_optional(&mut *tx)
.await?;
let Some(project_id) = project_id else {
tx.commit().await?;
return Ok(None);
};
let row = QueryBuilder::<Sqlite>::new(PROJECT_SELECT)
.push(" WHERE id = ")
.push_bind(&project_id)
.build()
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else {
tx.rollback().await?;
anyhow::bail!("idempotency key refers to deleted project: {idempotency_key}");
};
let project = project_from_row_in_tx(&mut tx, &row).await?;
tx.commit().await?;
Ok(Some(project))
}
pub async fn create_project(
&self,
name: String,
roots: Vec<ProjectRoot>,
metadata: BTreeMap<String, String>,
thread_ids: &[String],
idempotency_key: &str,
) -> anyhow::Result<CreatedProject> {
let mut tx = self.pool.begin_immediate().await?;
let existing_project_id = sqlx::query_scalar::<_, String>(
"SELECT project_id FROM project_idempotency_keys WHERE key = ?",
)
.bind(idempotency_key)
.fetch_optional(&mut *tx)
.await?;
if let Some(existing_project_id) = existing_project_id {
let row = QueryBuilder::<Sqlite>::new(PROJECT_SELECT)
.push(" WHERE id = ")
.push_bind(&existing_project_id)
.build()
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else {
tx.rollback().await?;
anyhow::bail!("idempotency key refers to deleted project: {idempotency_key}");
};
let project = project_from_row_in_tx(&mut tx, &row).await?;
tx.commit().await?;
return Ok(CreatedProject {
project,
created: false,
});
}
for thread_id in thread_ids {
let exists = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM threads WHERE id = ?")
.bind(thread_id)
.fetch_one(&mut *tx)
.await?;
if exists == 0 {
anyhow::bail!("thread not found: {thread_id}");
}
}
let id = Uuid::now_v7().to_string();
let now = chrono::Utc::now().timestamp_millis();
let position = sqlx::query_scalar::<_, Option<i64>>("SELECT MAX(position) FROM projects")
.fetch_one(&mut *tx)
.await?
.unwrap_or(-1)
.checked_add(1)
.ok_or_else(|| anyhow::anyhow!("project position overflow"))?;
let metadata_json = serde_json::to_string(&metadata)?;
sqlx::query(
"INSERT INTO projects (id, name, metadata, position, created_at_ms, updated_at_ms) VALUES (?, ?, ?, ?, ?, ?)",
)
.bind(&id)
.bind(&name)
.bind(&metadata_json)
.bind(position)
.bind(now)
.bind(now)
.execute(&mut *tx)
.await?;
replace_roots(&mut tx, &id, &roots).await?;
for thread_id in thread_ids {
sqlx::query("UPDATE threads SET project_id = ? WHERE id = ?")
.bind(&id)
.bind(thread_id)
.execute(&mut *tx)
.await?;
}
sqlx::query(
"INSERT INTO project_idempotency_keys (key, project_id, created_at_ms) VALUES (?, ?, ?)",
)
.bind(idempotency_key)
.bind(&id)
.bind(now)
.execute(&mut *tx)
.await?;
let row = QueryBuilder::<Sqlite>::new(PROJECT_SELECT)
.push(" WHERE id = ")
.push_bind(&id)
.build()
.fetch_one(&mut *tx)
.await?;
let project = project_from_row(&row, roots)?;
tx.commit().await?;
Ok(CreatedProject {
project,
created: true,
})
}
pub async fn update_project(
&self,
id: &str,
name: Option<String>,
roots: Option<Vec<ProjectRoot>>,
metadata: Option<BTreeMap<String, String>>,
) -> anyhow::Result<Option<(Project, bool)>> {
let mut tx = self.pool.begin_immediate().await?;
let row = QueryBuilder::<Sqlite>::new(PROJECT_SELECT)
.push(" WHERE id = ")
.push_bind(id)
.build()
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else {
tx.rollback().await?;
return Ok(None);
};
let current = project_from_row_in_tx(&mut tx, &row).await?;
let next_name = name.unwrap_or_else(|| current.name.clone());
let next_roots = roots.unwrap_or_else(|| current.roots.clone());
let next_metadata = metadata.unwrap_or_else(|| current.metadata.clone());
if next_name == current.name
&& next_roots == current.roots
&& next_metadata == current.metadata
{
tx.rollback().await?;
return Ok(Some((current, false)));
}
let now = chrono::Utc::now().timestamp_millis();
sqlx::query("UPDATE projects SET name = ?, metadata = ?, updated_at_ms = ? WHERE id = ?")
.bind(&next_name)
.bind(serde_json::to_string(&next_metadata)?)
.bind(now)
.bind(id)
.execute(&mut *tx)
.await?;
if next_roots != current.roots {
replace_roots(&mut tx, id, &next_roots).await?;
}
tx.commit().await?;
Ok(Some((
Project {
id: id.to_string(),
name: next_name,
roots: next_roots,
metadata: next_metadata,
position: current.position,
created_at_ms: current.created_at_ms,
updated_at_ms: now,
recency_at_ms: current.recency_at_ms,
},
true,
)))
}
/// Move a project before another project, or append it when the anchor is absent.
///
/// Returns None when the moved project does not exist and Some(false) for a no-op.
pub async fn move_project(
&self,
project_id: &str,
before_project_id: Option<&str>,
) -> anyhow::Result<Option<bool>> {
let mut tx = self.pool.begin_immediate().await?;
let mut project_ids = sqlx::query_scalar::<_, String>(
"SELECT id FROM projects ORDER BY position ASC, id ASC",
)
.fetch_all(&mut *tx)
.await?;
let Some(current_index) = project_ids.iter().position(|id| id == project_id) else {
tx.rollback().await?;
return Ok(None);
};
if before_project_id == Some(project_id) {
tx.rollback().await?;
anyhow::bail!("project {project_id} cannot be moved before itself");
}
let original_project_ids = project_ids.clone();
project_ids.remove(current_index);
let next_index = if let Some(before_project_id) = before_project_id {
project_ids
.iter()
.position(|id| id == before_project_id)
.ok_or_else(|| anyhow::anyhow!("before project not found: {before_project_id}"))?
} else {
project_ids.len()
};
project_ids.insert(next_index, project_id.to_string());
if project_ids == original_project_ids {
tx.rollback().await?;
return Ok(Some(false));
}
for (position, id) in project_ids.iter().enumerate() {
sqlx::query("UPDATE projects SET position = ? WHERE id = ?")
.bind(position as i64)
.bind(id)
.execute(&mut *tx)
.await?;
}
sqlx::query("UPDATE projects SET updated_at_ms = ? WHERE id = ?")
.bind(chrono::Utc::now().timestamp_millis())
.bind(project_id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(Some(true))
}
pub async fn delete_project(
&self,
id: &str,
) -> anyhow::Result<Option<(Vec<String>, Vec<String>)>> {
let mut tx = self.pool.begin_immediate().await?;
let exists = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM projects WHERE id = ?")
.bind(id)
.fetch_one(&mut *tx)
.await?;
if exists == 0 {
tx.rollback().await?;
return Ok(None);
}
let active_thread_ids = sqlx::query_scalar::<_, String>(
"SELECT id FROM threads WHERE project_id = ? AND archived = 0 ORDER BY id ASC",
)
.bind(id)
.fetch_all(&mut *tx)
.await?;
let archived_thread_ids = sqlx::query_scalar::<_, String>(
"SELECT id FROM threads WHERE project_id = ? AND archived = 1 ORDER BY id ASC",
)
.bind(id)
.fetch_all(&mut *tx)
.await?;
sqlx::query("UPDATE threads SET project_id = NULL WHERE project_id = ?")
.bind(id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM projects WHERE id = ?")
.bind(id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(Some((active_thread_ids, archived_thread_ids)))
}
}
async fn project_from_row_in_tx(
tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
row: &sqlx::sqlite::SqliteRow,
) -> anyhow::Result<Project> {
let id: String = row.try_get("id")?;
let roots =
sqlx::query("SELECT path FROM project_roots WHERE project_id = ? ORDER BY position ASC")
.bind(&id)
.fetch_all(&mut **tx)
.await?
.into_iter()
.map(|row| {
Ok(ProjectRoot {
path: row.try_get("path")?,
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
project_from_row(row, roots)
}
fn project_from_row(
row: &sqlx::sqlite::SqliteRow,
roots: Vec<ProjectRoot>,
) -> anyhow::Result<Project> {
Ok(Project {
id: row.try_get("id")?,
name: row.try_get("name")?,
roots,
metadata: serde_json::from_str(&row.try_get::<String, _>("metadata")?)?,
position: row.try_get("position")?,
created_at_ms: row.try_get("created_at_ms")?,
updated_at_ms: row.try_get("updated_at_ms")?,
recency_at_ms: row.try_get("recency_at_ms")?,
})
}
async fn replace_roots(
tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
project_id: &str,
roots: &[ProjectRoot],
) -> anyhow::Result<()> {
sqlx::query("DELETE FROM project_roots WHERE project_id = ?")
.bind(project_id)
.execute(&mut **tx)
.await?;
for (position, root) in roots.iter().enumerate() {
sqlx::query("INSERT INTO project_roots (project_id, position, path) VALUES (?, ?, ?)")
.bind(project_id)
.bind(position as i64)
.bind(&root.path)
.execute(&mut **tx)
.await?;
}
Ok(())
}
fn project_list_query(
cursor: Option<&str>,
limit: usize,
sort_key: ProjectSortKey,
sort_direction: SortDirection,
) -> anyhow::Result<QueryBuilder<Sqlite>> {
anyhow::ensure!(limit > 0, "project limit must be positive");
let query_limit = i64::try_from(limit)?
.checked_add(/*rhs*/ 1)
.ok_or_else(|| anyhow::anyhow!("project limit overflow"))?;
let column = match sort_key {
ProjectSortKey::Position => "p.position",
ProjectSortKey::RecencyAt => "p.recency_at_ms",
};
let operator = match sort_direction {
SortDirection::Asc => ">",
SortDirection::Desc => "<",
};
let mut query = QueryBuilder::new(format!(
"WITH project_activity AS ({PROJECT_SELECT}), page AS (SELECT * FROM project_activity p"
));
if let Some(cursor) = cursor {
let (value, id) = parse_project_cursor(cursor, sort_key, sort_direction)?;
if let Some(value) = value {
query
.push(format!(" WHERE ({column} {operator} "))
.push_bind(value);
query.push(format!(" OR ({column} = ")).push_bind(value);
query
.push(format!(" AND p.id {operator} "))
.push_bind(id)
.push(")");
if sort_key == ProjectSortKey::RecencyAt {
query.push(" OR p.recency_at_ms IS NULL");
}
query.push(")");
} else {
query
.push(format!(
" WHERE p.recency_at_ms IS NULL AND p.id {operator} "
))
.push_bind(id);
}
}
push_project_order(&mut query, sort_key, sort_direction);
query.push(" LIMIT ").push_bind(query_limit);
query.push(
") SELECT p.*, roots.path AS root_path FROM page p \
LEFT JOIN project_roots roots ON roots.project_id = p.id",
);
push_project_order(&mut query, sort_key, sort_direction);
query.push(", roots.position ASC");
Ok(query)
}
fn push_project_order(
query: &mut QueryBuilder<Sqlite>,
sort_key: ProjectSortKey,
sort_direction: SortDirection,
) {
let direction = match sort_direction {
SortDirection::Asc => "ASC",
SortDirection::Desc => "DESC",
};
query.push(" ORDER BY ");
match sort_key {
ProjectSortKey::Position => query.push("p.position"),
ProjectSortKey::RecencyAt => query.push("p.recency_at_ms IS NULL ASC, p.recency_at_ms"),
};
query.push(format!(" {direction}, p.id {direction}"));
}
fn project_cursor(project: &Project, sort_key: ProjectSortKey, direction: SortDirection) -> String {
if sort_key == ProjectSortKey::Position && direction == SortDirection::Asc {
// Retain the existing format for clients reconnecting to an older server.
return format!("{}|{}", project.position, project.id);
}
let (key, value) = match sort_key {
ProjectSortKey::Position => ("position", project.position.to_string()),
ProjectSortKey::RecencyAt => (
"recencyAt",
project
.recency_at_ms
.map_or_else(|| "null".to_string(), |value| value.to_string()),
),
};
let direction = match direction {
SortDirection::Asc => "asc",
SortDirection::Desc => "desc",
};
format!("v1|{key}|{direction}|{value}|{}", project.id)
}
fn parse_project_cursor(
cursor: &str,
sort_key: ProjectSortKey,
direction: SortDirection,
) -> anyhow::Result<(Option<i64>, String)> {
let invalid = || anyhow::anyhow!("invalid project cursor: malformed or mismatched sort anchor");
if cursor.len() > 128 {
return Err(invalid());
}
let parts: Vec<_> = cursor.split('|').collect();
let key = match sort_key {
ProjectSortKey::Position => "position",
ProjectSortKey::RecencyAt => "recencyAt",
};
let order = match direction {
SortDirection::Asc => "asc",
SortDirection::Desc => "desc",
};
let (value, id) = match parts.as_slice() {
[value, id] if sort_key == ProjectSortKey::Position && direction == SortDirection::Asc => {
(*value, *id)
}
["v1", cursor_key, cursor_order, value, id]
if *cursor_key == key && *cursor_order == order =>
{
(*value, *id)
}
_ => return Err(invalid()),
};
let value = if value == "null" && sort_key == ProjectSortKey::RecencyAt {
None
} else {
let parsed: i64 = value.parse().map_err(|_| invalid())?;
if parsed.to_string() != value || sort_key == ProjectSortKey::Position && parsed < 0 {
return Err(invalid());
}
Some(parsed)
};
let uuid = Uuid::parse_str(id).map_err(|_| invalid())?;
if uuid.to_string() != id {
return Err(invalid());
}
Ok((value, id.to_string()))
}
#[cfg(test)]
#[path = "projects_tests.rs"]
mod tests;

View File

@@ -0,0 +1,743 @@
use std::collections::BTreeMap;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use super::*;
use crate::ProjectSortKey;
use crate::SortDirection;
use crate::ThreadMetadataBuilder;
use crate::runtime::test_support::unique_temp_dir;
#[tokio::test]
async fn project_lifecycle_preserves_order_and_clears_assignments() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let thread_id = ThreadId::default();
let metadata = ThreadMetadataBuilder::new(
thread_id,
home.join("thread.jsonl"),
chrono::Utc::now(),
SessionSource::Cli,
)
.build("test-provider");
runtime.upsert_thread(&metadata).await?;
let roots = vec![
ProjectRoot {
path: "/tmp/one".to_string(),
},
ProjectRoot {
path: "/tmp/two".to_string(),
},
];
let project = runtime
.create_project(
"Work".to_string(),
roots.clone(),
BTreeMap::from([("color".to_string(), "blue".to_string())]),
&[thread_id.to_string()],
"state:project-lifecycle",
)
.await?
.project;
assert_eq!(project.position, 0);
assert_eq!(project.roots, roots);
assert_eq!(
runtime.get_thread(thread_id).await?.unwrap().project_id,
Some(project.id.clone())
);
let unchanged = runtime
.update_project(
&project.id,
/*name*/ None,
/*roots*/ None,
/*metadata*/ None,
)
.await?
.unwrap();
assert!(!unchanged.1);
assert_eq!(unchanged.0.updated_at_ms, project.updated_at_ms);
runtime
.touch_thread_updated_at(thread_id, chrono::Utc::now())
.await?;
assert_eq!(
runtime.get_project(&project.id).await?,
Some(project.clone())
);
runtime
.mark_archived(
thread_id,
home.join("archived.jsonl").as_path(),
chrono::Utc::now(),
)
.await?;
assert_eq!(
runtime.get_project(&project.id).await?,
Some(Project {
recency_at_ms: None,
..project.clone()
})
);
runtime
.mark_unarchived(thread_id, &metadata.rollout_path)
.await?;
assert_eq!(
runtime.get_project(&project.id).await?,
Some(project.clone())
);
runtime
.mark_archived(thread_id, &metadata.rollout_path, chrono::Utc::now())
.await?;
let active_thread_id = ThreadId::default();
let active_metadata = ThreadMetadataBuilder::new(
active_thread_id,
home.join("active.jsonl"),
chrono::Utc::now(),
SessionSource::Cli,
)
.build("test-provider");
runtime.upsert_thread(&active_metadata).await?;
runtime
.set_thread_project(&active_thread_id.to_string(), Some(&project.id))
.await?
.expect("active thread exists");
let active_recency = runtime
.get_thread(active_thread_id)
.await?
.unwrap()
.recency_at
.timestamp_millis();
runtime
.mark_unarchived(thread_id, &metadata.rollout_path)
.await?;
let active_project = Project {
recency_at_ms: Some(active_recency),
..project.clone()
};
assert_eq!(
runtime.get_project(&project.id).await?,
Some(active_project)
);
runtime
.set_thread_project(&active_thread_id.to_string(), /*project_id*/ None)
.await?;
assert_eq!(
runtime.get_project(&project.id).await?,
Some(project.clone())
);
runtime
.set_thread_project(&active_thread_id.to_string(), Some(&project.id))
.await?;
runtime.delete_thread(active_thread_id).await?;
assert_eq!(
runtime.get_project(&project.id).await?,
Some(project.clone())
);
// Restore the active fixture for the project-deletion assertions below.
runtime.upsert_thread(&active_metadata).await?;
runtime
.set_thread_project(&active_thread_id.to_string(), Some(&project.id))
.await?;
runtime
.mark_archived(thread_id, &metadata.rollout_path, chrono::Utc::now())
.await?;
let (affected_active_thread_ids, affected_archived_thread_ids) =
runtime.delete_project(&project.id).await?.unwrap();
assert_eq!(
affected_active_thread_ids,
vec![active_thread_id.to_string()]
);
assert_eq!(affected_archived_thread_ids, vec![thread_id.to_string()]);
assert_eq!(
runtime.get_thread(thread_id).await?.unwrap().project_id,
None
);
assert_eq!(
runtime
.get_thread(active_thread_id)
.await?
.unwrap()
.project_id,
None
);
assert_eq!(runtime.get_project(&project.id).await?, None);
Ok(())
}
#[tokio::test]
async fn project_idempotency_keys_replay_and_survive_deletion() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let created = runtime
.create_project(
"Imported".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"desktop:legacy-project",
)
.await?;
assert!(created.created);
assert_eq!(
runtime
.get_project_by_idempotency_key("desktop:legacy-project")
.await?,
Some(created.project.clone())
);
let replayed = runtime
.create_project(
"Changed payload".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"desktop:legacy-project",
)
.await?;
assert!(!replayed.created);
assert_eq!(replayed.project, created.project);
runtime.delete_project(&created.project.id).await?;
let lookup_error = runtime
.get_project_by_idempotency_key("desktop:legacy-project")
.await
.expect_err("deleted project keys must remain tombstoned");
assert!(
lookup_error
.to_string()
.contains("idempotency key refers to deleted project")
);
let error = runtime
.create_project(
"Recreated".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"desktop:legacy-project",
)
.await
.expect_err("deleted project keys must remain tombstoned");
assert!(
error
.to_string()
.contains("idempotency key refers to deleted project")
);
Ok(())
}
#[tokio::test]
async fn project_import_rejects_unknown_thread_without_partial_project() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let error = runtime
.create_project(
"Work".to_string(),
Vec::new(),
BTreeMap::new(),
&["00000000-0000-0000-0000-000000000123".to_string()],
"state:unknown-thread",
)
.await
.unwrap_err();
assert!(error.to_string().contains("thread not found"));
assert!(
runtime
.list_projects(
/*cursor*/ None,
/*limit*/ 10,
ProjectSortKey::Position,
SortDirection::Asc
)
.await?
.projects
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn project_updates_preserve_omitted_fields_across_concurrent_writers() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime_one = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let runtime_two = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let project = runtime_one
.create_project(
"Work".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"state:concurrent-update",
)
.await?
.project;
let (name_update, metadata_update) = tokio::join!(
runtime_one.update_project(
&project.id,
Some("Renamed".to_string()),
/*roots*/ None,
/*metadata*/ None,
),
runtime_two.update_project(
&project.id,
/*name*/ None,
/*roots*/ None,
Some(BTreeMap::from([("color".to_string(), "blue".to_string())])),
),
);
name_update?.expect("project exists");
metadata_update?.expect("project exists");
let updated = runtime_one
.get_project(&project.id)
.await?
.expect("project exists");
assert_eq!(updated.name, "Renamed");
assert_eq!(
updated.metadata,
BTreeMap::from([("color".to_string(), "blue".to_string())])
);
Ok(())
}
#[tokio::test]
async fn project_list_rejects_malformed_cursors() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
for cursor in [
"",
"123",
"+123|00000000-0000-0000-0000-000000000000",
"000123|00000000-0000-0000-0000-000000000000",
"-0|00000000-0000-0000-0000-000000000000",
"-1|00000000-0000-0000-0000-000000000000",
"123|not-a-uuid",
"123|00000000000000000000000000000000",
"123|00000000-0000-0000-0000-00000000000A",
"123|00000000-0000-0000-0000-000000000000|extra",
"not-a-position|00000000-0000-0000-0000-000000000000",
] {
let error = runtime
.list_projects(
Some(cursor),
/*limit*/ 10,
ProjectSortKey::Position,
SortDirection::Asc,
)
.await
.expect_err("malformed cursor should fail");
assert!(error.to_string().starts_with("invalid project cursor:"));
}
Ok(())
}
#[tokio::test]
async fn project_list_cursor_round_trips_across_pages() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
for name in ["One", "Two"] {
runtime
.create_project(name.to_string(), Vec::new(), BTreeMap::new(), &[], name)
.await?;
}
let first = runtime
.list_projects(
/*cursor*/ None,
/*limit*/ 1,
ProjectSortKey::Position,
SortDirection::Asc,
)
.await?;
assert_eq!(first.projects.len(), 1);
let cursor = first.next_cursor.expect("next cursor");
let second = runtime
.list_projects(
Some(&cursor),
/*limit*/ 1,
ProjectSortKey::Position,
SortDirection::Asc,
)
.await?;
assert_eq!(second.projects.len(), 1);
assert_ne!(first.projects[0].id, second.projects[0].id);
assert_eq!(second.next_cursor, None);
Ok(())
}
#[tokio::test]
async fn project_list_orders_and_pages_recency_with_roots_and_nulls() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let mut projects = Vec::new();
for (name, recency_at_ms, archived) in [
("older", Some(1_700_000_000_001), false),
("tie-a", Some(1_700_000_000_002), false),
("tie-b", Some(1_700_000_000_002), false),
("empty", None, false),
("archived", Some(1_700_000_010_000), true),
] {
let mut threads = Vec::new();
if let Some(timestamp) = recency_at_ms {
for timestamp in [timestamp - 1, timestamp] {
let id = ThreadId::default();
let mut metadata = ThreadMetadataBuilder::new(
id,
home.join(format!("{id}.jsonl")),
chrono::DateTime::from_timestamp_millis(timestamp).unwrap(),
SessionSource::Exec,
)
.build("test-provider");
metadata.archived_at = archived.then(chrono::Utc::now);
runtime.upsert_thread(&metadata).await?;
// Force exact ties despite the monotonic timestamp allocator.
sqlx::query("UPDATE threads SET recency_at_ms = ?, recency_at = ? WHERE id = ?")
.bind(timestamp)
.bind(timestamp / 1000)
.bind(id.to_string())
.execute(runtime.pool.as_ref())
.await?;
threads.push(id.to_string());
}
}
let project = runtime
.create_project(
name.to_string(),
vec![
ProjectRoot {
path: "/tmp/z".to_string(),
},
ProjectRoot {
path: "/tmp/a".to_string(),
},
],
BTreeMap::new(),
&threads,
name,
)
.await?
.project;
let expected = Project {
recency_at_ms: recency_at_ms.filter(|_| !archived),
..project.clone()
};
assert_eq!(project, expected);
assert_eq!(
runtime.get_project(&project.id).await?,
Some(expected.clone())
);
projects.push(expected);
}
let mut ties = projects[1..3].to_vec();
ties.sort_by(|a, b| a.id.cmp(&b.id));
let mut empty = projects[3..].to_vec();
empty.sort_by(|a, b| a.id.cmp(&b.id));
let ascending = [vec![projects[0].clone()], ties.clone(), empty.clone()].concat();
ties.reverse();
empty.reverse();
let descending = [ties, vec![projects[0].clone()], empty].concat();
for (key, direction, expected) in [
(
ProjectSortKey::Position,
SortDirection::Asc,
projects.clone(),
),
(
ProjectSortKey::Position,
SortDirection::Desc,
projects.into_iter().rev().collect(),
),
(ProjectSortKey::RecencyAt, SortDirection::Asc, ascending),
(
ProjectSortKey::RecencyAt,
SortDirection::Desc,
descending.clone(),
),
] {
for limit in [1, 2, 3, 10] {
let mut cursor = None;
let mut actual = Vec::new();
loop {
let page = runtime
.list_projects(cursor.as_deref(), limit, key, direction)
.await?;
actual.extend(page.projects);
assert!(
actual.len() <= expected.len(),
"pagination repeated a project"
);
cursor = page.next_cursor;
if cursor.is_none() {
break;
}
}
assert_eq!(actual, expected);
}
}
let first = runtime
.list_projects(
/*cursor*/ None,
/*limit*/ 1,
ProjectSortKey::RecencyAt,
SortDirection::Desc,
)
.await?;
runtime.delete_project(&first.projects[0].id).await?;
let rest = runtime
.list_projects(
first.next_cursor.as_deref(),
/*limit*/ 10,
ProjectSortKey::RecencyAt,
SortDirection::Desc,
)
.await?;
assert_eq!(
rest,
ProjectsPage {
projects: descending[1..].to_vec(),
next_cursor: None
}
);
let query = project_list_query(
/*cursor*/ None,
/*limit*/ 50,
ProjectSortKey::RecencyAt,
SortDirection::Desc,
)?;
let plan = QueryBuilder::<Sqlite>::new("EXPLAIN QUERY PLAN ")
.push(query.sql().as_str())
.build()
.bind(/*value*/ 51_i64)
.fetch_all(runtime.pool.as_ref())
.await?;
let details = plan
.iter()
.map(|row| row.get::<String, _>("detail"))
.collect::<Vec<_>>();
assert!(
details
.iter()
.any(|detail| detail.contains("USING COVERING INDEX idx_threads_project_recency")),
"{details:?}"
);
Ok(())
}
#[test]
fn project_list_rejects_cursor_sort_mismatches() {
for cursor in [
"1|00000000-0000-0000-0000-000000000000",
"v1|position|desc|1|00000000-0000-0000-0000-000000000000",
"v1|recencyAt|asc|1|00000000-0000-0000-0000-000000000000",
"v2|recencyAt|desc|1|00000000-0000-0000-0000-000000000000",
"v1|recencyAt|desc|01|00000000-0000-0000-0000-000000000000",
"v1|recencyAt|desc|null|not-a-uuid",
] {
assert!(
project_list_query(
Some(cursor),
/*limit*/ 10,
ProjectSortKey::RecencyAt,
SortDirection::Desc
)
.is_err()
);
}
}
#[tokio::test]
async fn project_move_reorders_projects_and_preserves_no_op_timestamp() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let one = runtime
.create_project(
"One".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"state:move-one",
)
.await?
.project;
let two = runtime
.create_project(
"Two".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"state:move-two",
)
.await?
.project;
let three = runtime
.create_project(
"Three".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"state:move-three",
)
.await?
.project;
assert_eq!(
runtime.move_project(&three.id, Some(&one.id)).await?,
Some(true)
);
let reordered = runtime
.list_projects(
/*cursor*/ None,
/*limit*/ 10,
ProjectSortKey::Position,
SortDirection::Asc,
)
.await?;
assert_eq!(
reordered
.projects
.iter()
.map(|project| project.id.as_str())
.collect::<Vec<_>>(),
vec![three.id.as_str(), one.id.as_str(), two.id.as_str()]
);
assert_eq!(
reordered
.projects
.iter()
.map(|project| project.position)
.collect::<Vec<_>>(),
vec![0, 1, 2]
);
let moved = runtime.get_project(&three.id).await?.unwrap();
assert_eq!(
runtime.move_project(&three.id, Some(&one.id)).await?,
Some(false)
);
assert_eq!(
runtime.get_project(&three.id).await?.unwrap().updated_at_ms,
moved.updated_at_ms
);
assert_eq!(
runtime
.move_project(&three.id, Some(&three.id))
.await
.unwrap_err()
.to_string(),
format!("project {} cannot be moved before itself", three.id)
);
assert_eq!(
runtime
.move_project(&three.id, Some("00000000-0000-0000-0000-000000000000"))
.await
.unwrap_err()
.to_string(),
"before project not found: 00000000-0000-0000-0000-000000000000"
);
assert_eq!(
runtime
.move_project(
"00000000-0000-0000-0000-000000000000",
/*before_project_id*/ None,
)
.await?,
None
);
Ok(())
}
#[tokio::test]
async fn initial_project_assignment_is_inserted_with_thread_row() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let project = runtime
.create_project(
"Work".to_string(),
Vec::new(),
BTreeMap::new(),
&[],
"state:initial-assignment",
)
.await?
.project;
let thread_id = ThreadId::default();
let mut metadata = ThreadMetadataBuilder::new(
thread_id,
home.join("thread.jsonl"),
chrono::Utc::now(),
SessionSource::Cli,
)
.build("test-provider");
metadata.project_id = Some(project.id.clone());
assert!(runtime.insert_thread_if_absent(&metadata).await?);
assert_eq!(
runtime.get_thread(thread_id).await?.unwrap().project_id,
Some(project.id.clone())
);
let missing_thread_id = ThreadId::default();
let mut missing_project_metadata = ThreadMetadataBuilder::new(
missing_thread_id,
home.join("missing-project.jsonl"),
chrono::Utc::now(),
SessionSource::Cli,
)
.build("test-provider");
missing_project_metadata.project_id = Some("00000000-0000-0000-0000-000000000000".to_string());
let error = runtime
.insert_thread_if_absent(&missing_project_metadata)
.await
.expect_err("unknown project must reject initial thread insert");
assert!(error.to_string().contains("FOREIGN KEY constraint failed"));
assert_eq!(runtime.get_thread(missing_thread_id).await?, None);
let deleted = runtime.delete_project(&project.id).await?.unwrap();
assert_eq!(deleted, (vec![thread_id.to_string()], Vec::new()));
Ok(())
}

View File

@@ -0,0 +1,217 @@
use super::*;
use crate::MAX_QUEUE_ITEMS;
use crate::QueuedUserSubmissionRecord;
use crate::sqlite::SqlitePoolWriteExt;
use crate::sqlite::SqliteWriteQueryExt;
use sqlx::Connection;
use tokio::sync::Mutex;
use uuid::Uuid;
/// SQLite-backed persistence for durable, thread-scoped user messages.
#[derive(Clone)]
pub struct SqliteQueueStore {
pool: Arc<SqlitePool>,
change_version_connection: Arc<Mutex<Option<SqliteConnection>>>,
}
impl SqliteQueueStore {
pub(crate) fn new(pool: Arc<SqlitePool>) -> Self {
Self {
pool,
change_version_connection: Arc::new(Mutex::new(None)),
}
}
pub(crate) async fn close(&self) {
let connection = self.change_version_connection.lock().await.take();
if let Some(connection) = connection
&& let Err(error) = connection.close().await
{
tracing::warn!(%error, "failed to close queue change-version connection");
}
self.pool.close().await;
}
/// Observe queue-database commits through one stable SQLite connection.
pub async fn change_version(&self) -> anyhow::Result<i64> {
let mut connection = Arc::clone(&self.change_version_connection)
.lock_owned()
.await;
if connection.is_none() {
*connection = Some(self.pool.acquire().await?.detach());
}
let Some(connection) = connection.as_mut() else {
unreachable!("queue change-version connection was initialized");
};
Ok(sqlx::query_scalar("PRAGMA data_version")
.fetch_one(connection)
.await?)
}
/// Return changed revisions only for the supplied loaded thread IDs.
pub async fn changes_since(
&self,
revision: i64,
thread_ids: &[ThreadId],
) -> anyhow::Result<Vec<(ThreadId, i64)>> {
if thread_ids.is_empty() {
return Ok(Vec::new());
}
let mut query = QueryBuilder::<Sqlite>::new(
"SELECT thread_id, revision FROM queued_thread_revisions WHERE revision > ",
);
query.push_bind(revision).push(" AND thread_id IN (");
let mut separated = query.separated(", ");
for thread_id in thread_ids {
separated.push_bind(thread_id.to_string());
}
separated.push_unseparated(") ORDER BY revision");
let rows = query
.build_query_as::<(String, i64)>()
.fetch_all(self.pool.as_ref())
.await?;
rows.into_iter()
.map(|(thread_id, revision)| Ok((ThreadId::try_from(thread_id)?, revision)))
.collect()
}
pub async fn enqueue(
&self,
thread_id: ThreadId,
payload_json: &str,
) -> anyhow::Result<QueuedUserSubmissionRecord> {
let now_ms = datetime_to_epoch_millis(Utc::now());
let row = sqlx::query(
"INSERT INTO queued_items (
id, thread_id, payload_json, queue_order,
created_at_ms, updated_at_ms
)
SELECT ?, ?, ?,
COALESCE((SELECT MAX(queue_order) FROM queued_items WHERE thread_id = ?), -1) + 1,
?, ?
WHERE (SELECT COUNT(*) FROM queued_items WHERE thread_id = ?) < ?
RETURNING id, thread_id, payload_json",
)
.bind(Uuid::now_v7().to_string())
.bind(thread_id.to_string())
.bind(payload_json)
.bind(thread_id.to_string())
.bind(now_ms)
.bind(now_ms)
.bind(thread_id.to_string())
.bind(i64::try_from(MAX_QUEUE_ITEMS)?)
.fetch_one_write(self.pool.as_ref())
.await?;
QueuedUserSubmissionRecord::try_from_row(&row)
}
pub async fn list_page(
&self,
thread_id: ThreadId,
offset: usize,
limit: usize,
) -> anyhow::Result<Vec<QueuedUserSubmissionRecord>> {
let rows = sqlx::query(
"SELECT id, thread_id, payload_json
FROM queued_items
WHERE thread_id = ?
ORDER BY queue_order LIMIT ? OFFSET ?",
)
.bind(thread_id.to_string())
.bind(i64::try_from(limit)?)
.bind(i64::try_from(offset)?)
.fetch_all(self.pool.as_ref())
.await?;
rows.iter()
.map(QueuedUserSubmissionRecord::try_from_row)
.collect()
}
pub async fn update(
&self,
thread_id: ThreadId,
item_id: &str,
payload_json: &str,
) -> anyhow::Result<Option<QueuedUserSubmissionRecord>> {
let row = sqlx::query(
"UPDATE queued_items
SET payload_json = ?, updated_at_ms = ?
WHERE thread_id = ? AND id = ?
RETURNING id, thread_id, payload_json",
)
.bind(payload_json)
.bind(datetime_to_epoch_millis(Utc::now()))
.bind(thread_id.to_string())
.bind(item_id)
.fetch_optional_write(self.pool.as_ref())
.await?;
row.as_ref()
.map(QueuedUserSubmissionRecord::try_from_row)
.transpose()
}
pub async fn delete(&self, thread_id: ThreadId, item_id: &str) -> anyhow::Result<bool> {
Ok(
sqlx::query("DELETE FROM queued_items WHERE thread_id = ? AND id = ?")
.bind(thread_id.to_string())
.bind(item_id)
.execute_with_busy_retry(self.pool.as_ref())
.await?
.rows_affected()
> 0,
)
}
pub async fn reorder(&self, thread_id: ThreadId, ordered_ids: &[String]) -> anyhow::Result<()> {
let mut transaction = self.pool.begin_immediate().await?;
let rows: Vec<(String, i64)> = sqlx::query_as(
"SELECT id, queue_order FROM queued_items
WHERE thread_id = ? ORDER BY queue_order",
)
.bind(thread_id.to_string())
.fetch_all(transaction.as_mut())
.await?;
let mut expected_ids = rows.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>();
let mut requested_ids = ordered_ids.to_vec();
expected_ids.sort();
requested_ids.sort();
if expected_ids != requested_ids {
transaction.rollback().await?;
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"queue reorder must include every queued submission exactly once",
)
.into());
}
let now_ms = datetime_to_epoch_millis(Utc::now());
let max_queue_order = rows.last().map_or(-1, |(_, queue_order)| *queue_order);
for (index, item_id) in ordered_ids.iter().enumerate() {
sqlx::query(
"UPDATE queued_items SET queue_order = ?, updated_at_ms = ?
WHERE thread_id = ? AND id = ?",
)
.bind(max_queue_order + i64::try_from(index)? + 1)
.bind(now_ms)
.bind(thread_id.to_string())
.bind(item_id)
.execute(transaction.as_mut())
.await?;
}
transaction.commit().await?;
Ok(())
}
pub(crate) async fn delete_thread_queue(&self, thread_id: ThreadId) -> anyhow::Result<bool> {
Ok(sqlx::query("DELETE FROM queued_items WHERE thread_id = ?")
.bind(thread_id.to_string())
.execute_with_busy_retry(self.pool.as_ref())
.await?
.rows_affected()
> 0)
}
}
#[cfg(test)]
#[path = "queued_items_tests.rs"]
mod tests;

View File

@@ -0,0 +1,278 @@
use super::*;
use crate::migrations::QUEUE_MIGRATOR;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::migrate::Migrator;
use std::borrow::Cow;
async fn runtime_with_thread() -> (Arc<StateRuntime>, ThreadId) {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("state runtime");
let thread_id = ThreadId::new();
let metadata = test_thread_metadata(home.as_path(), thread_id, home.clone());
runtime.upsert_thread(&metadata).await.unwrap();
(runtime, thread_id)
}
#[tokio::test]
async fn competing_runtimes_preserve_fifo_queue_order() {
let (runtime, thread_id) = runtime_with_thread().await;
let other = StateRuntime::init(runtime.sqlite().clone(), "test-provider".to_string())
.await
.unwrap();
let queue = runtime.thread_queue();
let other_queue = other.thread_queue();
let (first, second) = tokio::join!(
queue.enqueue(thread_id, r#"{"first":true}"#),
other_queue.enqueue(thread_id, r#"{"second":true}"#),
);
let mut expected = vec![first.unwrap(), second.unwrap()];
expected.sort_by(|first, second| first.id.cmp(&second.id));
let mut actual = queue
.list_page(thread_id, /*offset*/ 0, /*limit*/ 2)
.await
.unwrap();
actual.sort_by(|first, second| first.id.cmp(&second.id));
assert_eq!(expected, actual);
}
#[tokio::test]
async fn migrating_existing_queue_backfills_thread_revisions() {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await.unwrap();
let sqlite = crate::SqliteConfig::new_for_testing(home.as_path().abs());
let queue_path = sqlite.queue_db_path();
let old_queue_migrator = Migrator {
migrations: Cow::Owned(vec![QUEUE_MIGRATOR.migrations[0].clone()]),
ignore_missing: false,
locking: true,
no_tx: false,
table_name: QUEUE_MIGRATOR.table_name.clone(),
create_schemas: QUEUE_MIGRATOR.create_schemas.clone(),
};
let pool = sqlite.open_read_write_pool(&queue_path).await.unwrap();
old_queue_migrator.run(&pool).await.unwrap();
let thread_id = ThreadId::new();
let queued = QueuedUserSubmissionRecord {
id: Uuid::now_v7().to_string(),
thread_id,
payload: r#"{"existing":true}"#.to_string(),
};
sqlx::query(
"INSERT INTO queued_items
(id, thread_id, payload_json, queue_order, created_at_ms, updated_at_ms)
VALUES (?, ?, ?, 0, 0, 0)",
)
.bind(&queued.id)
.bind(thread_id.to_string())
.bind(&queued.payload)
.execute(&pool)
.await
.unwrap();
pool.close().await;
let runtime = StateRuntime::init(sqlite, "test-provider".to_string())
.await
.unwrap();
let queue = runtime.thread_queue();
assert_eq!(
vec![(thread_id, 1)],
queue
.changes_since(/*revision*/ 0, &[thread_id])
.await
.unwrap()
);
assert_eq!(
vec![queued],
queue
.list_page(thread_id, /*offset*/ 0, /*limit*/ 1)
.await
.unwrap()
);
}
#[tokio::test]
async fn queue_revisions_identify_changed_threads_after_updates_and_deletions() {
let (runtime, thread_id) = runtime_with_thread().await;
let queue = runtime.thread_queue();
let first = queue.enqueue(thread_id, r#"{"first":true}"#).await.unwrap();
let first_revision = queue
.changes_since(/*revision*/ 0, &[thread_id])
.await
.unwrap()[0]
.1;
queue
.update(thread_id, &first.id, r#"{"updated":true}"#)
.await
.unwrap();
let updated_revision = queue
.changes_since(first_revision, &[thread_id])
.await
.unwrap()[0]
.1;
let other_thread_id = ThreadId::new();
queue
.enqueue(other_thread_id, r#"{"other":true}"#)
.await
.unwrap();
let newly_loaded_changes = queue
.changes_since(/*revision*/ 0, &[other_thread_id])
.await
.unwrap();
assert_eq!(
vec![(thread_id, updated_revision), newly_loaded_changes[0]],
queue
.changes_since(first_revision, &[thread_id, other_thread_id])
.await
.unwrap()
);
assert!(queue.delete(thread_id, &first.id).await.unwrap());
assert!(
queue
.changes_since(updated_revision, &[thread_id])
.await
.unwrap()
.iter()
.any(|(changed_thread, _)| *changed_thread == thread_id)
);
}
#[tokio::test]
async fn fifo_dispatch_preserves_edits_reordering_and_pagination() {
let (runtime, thread_id) = runtime_with_thread().await;
let queue = runtime.thread_queue();
let first = queue.enqueue(thread_id, r#"{"n":1}"#).await.unwrap();
let second = queue.enqueue(thread_id, r#"{"n":2}"#).await.unwrap();
let third = queue.enqueue(thread_id, r#"{"n":3}"#).await.unwrap();
let updated = queue
.update(thread_id, &first.id, r#"{"n":"edited"}"#)
.await
.unwrap()
.unwrap();
assert_eq!(first.id, updated.id);
let error = queue
.reorder(thread_id, std::slice::from_ref(&first.id))
.await
.unwrap_err();
assert_eq!(
std::io::ErrorKind::InvalidInput,
error.downcast_ref::<std::io::Error>().unwrap().kind()
);
let ordered_ids = vec![third.id, first.id, second.id];
queue.reorder(thread_id, &ordered_ids).await.unwrap();
let items = queue
.list_page(thread_id, /*offset*/ 0, /*limit*/ 3)
.await
.unwrap();
let page = queue
.list_page(thread_id, /*offset*/ 1, /*limit*/ 1)
.await
.unwrap();
assert_eq!(vec![items[1].clone()], page);
assert_eq!(r#"{"n":"edited"}"#, items[1].payload);
for item in items {
assert!(queue.delete(thread_id, &item.id).await.unwrap());
}
assert!(
queue
.list_page(thread_id, /*offset*/ 0, /*limit*/ 1)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn queue_operations_cannot_mutate_another_threads_messages() {
let (runtime, thread_id) = runtime_with_thread().await;
let queue = runtime.thread_queue();
let first = queue.enqueue(thread_id, r#"{"n":1}"#).await.unwrap();
let other_thread_id = ThreadId::new();
let other = queue.enqueue(other_thread_id, r#"{"n":2}"#).await.unwrap();
let other_id = &other.id;
assert_eq!(
None,
queue
.update(thread_id, other_id, r#"{"n":3}"#)
.await
.unwrap()
);
assert!(!queue.delete(thread_id, other_id).await.unwrap());
assert!(
queue
.reorder(thread_id, std::slice::from_ref(other_id))
.await
.is_err()
);
let (items, other_items) = tokio::join!(
queue.list_page(thread_id, /*offset*/ 0, /*limit*/ 1),
queue.list_page(other_thread_id, /*offset*/ 0, /*limit*/ 1),
);
assert_eq!(
(vec![first], vec![other]),
(items.unwrap(), other_items.unwrap())
);
}
#[tokio::test]
async fn deleting_a_thread_removes_its_queue() {
let (runtime, thread_id) = runtime_with_thread().await;
runtime
.thread_queue()
.enqueue(thread_id, r#"{"n":1}"#)
.await
.unwrap();
assert_eq!(1, runtime.delete_thread(thread_id).await.unwrap());
assert!(
runtime
.thread_queue()
.list_page(thread_id, /*offset*/ 0, /*limit*/ 1)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn concurrent_inserts_enforce_the_queue_limit() {
let (runtime, thread_id) = runtime_with_thread().await;
let other = StateRuntime::init(runtime.sqlite().clone(), "test-provider".to_string())
.await
.unwrap();
for _ in 0..MAX_QUEUE_ITEMS - 1 {
runtime
.thread_queue()
.enqueue(thread_id, r#"{"n":1}"#)
.await
.unwrap();
}
let (first, second) = tokio::join!(
runtime.thread_queue().enqueue(thread_id, r#"{"n":2}"#),
other.thread_queue().enqueue(thread_id, r#"{"n":3}"#),
);
assert_ne!(first.is_ok(), second.is_ok());
assert_eq!(
MAX_QUEUE_ITEMS,
runtime
.thread_queue()
.list_page(thread_id, /*offset*/ 0, /*limit*/ MAX_QUEUE_ITEMS)
.await
.unwrap()
.len()
);
}

View File

@@ -0,0 +1,437 @@
//! Reclaims unused SQLite pages in opted-in databases, reducing batches after stalled passes.
//! Current and legacy log directories each retain their own maintenance lock.
//! NFS on Linux skips opening a maintenance connection.
use crate::RuntimeDbPath;
use crate::SqliteConfig;
use log::LevelFilter;
use sqlx::ConnectOptions;
use sqlx::Connection;
use sqlx::SqliteConnection;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::sqlite::SqliteSynchronous;
use std::collections::BTreeMap;
use std::fs::File;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::watch;
const IDLE_INTERVAL: Duration = Duration::from_secs(60);
const ACTIVE_INTERVAL: Duration = Duration::from_millis(50);
const CONTENTION_INTERVAL: Duration = Duration::from_millis(500);
const PASS_DURATION: Duration = Duration::from_millis(100);
const MIN_FREE_BYTES: i64 = 64 * 1024 * 1024;
const RESERVE_BYTES: i64 = 16 * 1024 * 1024;
const PASS_PAGES: u32 = 1024;
const BATCH_PAGES: u32 = 64;
/// Owns background reclamation for opted-in databases registered with `SqliteConfig`.
///
/// A per-home file lock elects one active worker, which visits databases serially
/// on individual retry schedules. Shutdown waits for the dedicated SQLite
/// connection to close before the worker releases the lock.
pub(crate) struct SqliteReclamationWorker {
shutdown: watch::Sender<()>,
finished: watch::Receiver<()>,
}
impl SqliteReclamationWorker {
pub(crate) fn spawn(sqlite: SqliteConfig) -> Arc<Self> {
let (shutdown, mut receiver) = watch::channel(());
let (finish, finished) = watch::channel(());
tokio::spawn(async move {
// Declared first so completion is signaled after all worker resources drop.
let _finish = finish;
let mut scheduled = sqlite
.reclamation_db_paths()
.into_iter()
.map(|db| (db, Instant::now(), ReclamationState::default()))
.collect::<Vec<_>>();
let mut owners = BTreeMap::new();
let mut delay = IDLE_INTERVAL;
loop {
tokio::select! {
_ = receiver.changed() => break,
_ = tokio::time::sleep(delay) => {}
}
delay = visit(&sqlite, &mut scheduled, &mut owners, &receiver).await;
}
});
Arc::new(Self { shutdown, finished })
}
pub(crate) async fn close(&self) {
self.shutdown.send_replace(());
// Every caller waits for task completion, even if another close is canceled.
let _ = self.finished.clone().changed().await;
}
}
async fn visit(
sqlite: &SqliteConfig,
scheduled: &mut [(RuntimeDbPath, Instant, ReclamationState)],
owners: &mut BTreeMap<PathBuf, File>,
shutdown: &watch::Receiver<()>,
) -> Duration {
for (db, due, state) in &mut *scheduled {
let started = Instant::now();
if shutdown.has_changed().unwrap_or(true) {
break;
}
if *due > started {
continue;
}
let Some(home) = db.path.parent() else {
continue;
};
if let std::collections::btree_map::Entry::Vacant(entry) = owners.entry(home.to_path_buf())
{
if let Ok(Some(owner)) = try_ownership(home).await {
entry.insert(owner);
} else {
*due = started + IDLE_INTERVAL;
continue;
}
}
let result = reclaim(
sqlite,
&db.path,
ReclamationOptions {
budget: Budget {
deadline: Some(started + PASS_DURATION),
pages: PASS_PAGES,
},
batch_pages: state.batch_pages,
},
shutdown,
)
.await;
crate::telemetry::record_reclamation(db.label, started.elapsed(), &result);
*due = Instant::now() + state.retry_after(&result);
}
scheduled
.iter()
.map(|(_, due, _)| due.saturating_duration_since(Instant::now()))
.min()
.unwrap_or(IDLE_INTERVAL)
}
async fn try_ownership(home: &Path) -> std::io::Result<Option<File>> {
let lock = tokio::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(home.join(".sqlite-maintenance.lock"))
.await?
.into_std()
.await;
match lock.try_lock() {
Ok(()) => Ok(Some(lock)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(error)) => Err(error),
}
}
pub(crate) struct ReclamationPass {
pub(crate) pages: u32,
outcome: PassOutcome,
}
#[derive(Debug, PartialEq, Eq)]
enum PassOutcome {
Idle,
Active,
Contended,
Interrupted,
Shutdown,
}
#[derive(Debug, PartialEq, Eq)]
struct ReclamationState {
batch_pages: u32,
stalled_passes: u32,
}
impl Default for ReclamationState {
fn default() -> Self {
Self {
batch_pages: BATCH_PAGES,
stalled_passes: 0,
}
}
}
impl ReclamationState {
fn retry_after(&mut self, result: &anyhow::Result<ReclamationPass>) -> Duration {
if let Ok(pass) = result
&& pass.outcome == PassOutcome::Interrupted
&& pass.pages == 0
{
self.stalled_passes = self.stalled_passes.saturating_add(1);
self.batch_pages = (self.batch_pages / 2).max(1);
// exponentially backoffs from CONTENTION_INTERVAL to IDLE_INTERVAL (500ms -> 60s)
return (CONTENTION_INTERVAL * (1 << (self.stalled_passes - 1).min(7)))
.min(IDLE_INTERVAL);
}
// Keep the smaller batch after progress; growing it would repeat the stall.
self.stalled_passes = 0;
match result {
Ok(pass) => match pass.outcome {
PassOutcome::Idle | PassOutcome::Shutdown => IDLE_INTERVAL,
PassOutcome::Active | PassOutcome::Interrupted => ACTIVE_INTERVAL,
PassOutcome::Contended => CONTENTION_INTERVAL,
},
Err(_) => IDLE_INTERVAL,
}
}
}
struct Budget {
deadline: Option<Instant>,
/// Amount of pages to reclaim per transaction
pages: u32,
}
struct ReclamationOptions {
budget: Budget,
batch_pages: u32,
}
impl From<Budget> for ReclamationOptions {
fn from(budget: Budget) -> Self {
Self {
budget,
batch_pages: BATCH_PAGES,
}
}
}
async fn reclaim(
sqlite: &SqliteConfig,
path: &Path,
options: impl Into<ReclamationOptions>,
shutdown: &watch::Receiver<()>,
) -> anyhow::Result<ReclamationPass> {
// Check the selected logs directory. An administrator can also select NFS.
let logs = path == sqlite.logs_db_path();
let is_nfs = if logs {
sqlite.logs_are_on_nfs().await?
} else {
sqlite.is_nfs().await?
};
if is_nfs {
return Ok(ReclamationPass {
pages: 0,
outcome: PassOutcome::Idle,
});
}
if !tokio::fs::try_exists(path).await? {
return Ok(ReclamationPass {
pages: 0,
outcome: PassOutcome::Idle,
});
}
#[expect(
clippy::disallowed_methods,
reason = "maintenance needs a dedicated connection with no busy wait or automatic checkpoints"
)]
let mut connection = match SqliteConnection::connect_with(
&SqliteConnectOptions::new()
.filename(path)
.create_if_missing(false)
.busy_timeout(Duration::ZERO)
.synchronous(SqliteSynchronous::Normal)
// Keep commits from doing checkpoint I/O while holding up writers.
.pragma("wal_autocheckpoint", "0")
// A 16 MiB cache reduced CPU time in large-database measurements.
.pragma("cache_size", "-16384")
.log_statements(LevelFilter::Off)
.log_slow_statements(LevelFilter::Off, Duration::ZERO),
)
.await
{
Ok(connection) => connection,
Err(error) => match outcome_after_error(&error) {
Some(outcome) => {
return Ok(ReclamationPass { pages: 0, outcome });
}
None => return Err(error.into()),
},
};
let result = reclaim_pages(&mut connection, options, shutdown).await;
connection.close().await?;
result
}
/// Reclaims free pages in short transactions while preserving a reusable reserve.
///
/// Each batch checks the reserve under `BEGIN IMMEDIATE` and commits before
/// checkpointing or sleeping. The pass bounds reclaimed freelist pages and checks
/// a cooperative deadline; storage I/O can overrun that deadline.
async fn reclaim_pages(
connection: &mut SqliteConnection,
options: impl Into<ReclamationOptions>,
shutdown: &watch::Receiver<()>,
) -> anyhow::Result<ReclamationPass> {
let ReclamationOptions {
budget,
batch_pages,
} = options.into();
if budget
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
|| shutdown.has_changed().unwrap_or(true)
{
return Ok(ReclamationPass {
pages: 0,
outcome: if shutdown.has_changed().unwrap_or(true) {
PassOutcome::Shutdown
} else {
PassOutcome::Interrupted
},
});
}
let mut reclaimed = 0;
let mut outcome = PassOutcome::Contended;
let result: Result<(), sqlx::Error> = async {
let stop = shutdown.clone();
connection
.lock_handle()
.await?
.set_progress_handler(/*num_ops*/ 1, move || {
!stop.has_changed().unwrap_or(true)
&& budget
.deadline
.is_none_or(|deadline| Instant::now() < deadline)
});
let (journal, mode, page_size, pages, free): (String, i64, i64, i64, i64) = sqlx::query_as(
"SELECT journal_mode, auto_vacuum, page_size, page_count, freelist_count \
FROM pragma_journal_mode, pragma_auto_vacuum, pragma_page_size, pragma_page_count, pragma_freelist_count",
)
.fetch_one(&mut *connection)
.await?;
// This worker's checkpoint and contention rules apply only to WAL mode.
// Require incremental auto-vacuum and at least 64 MiB and 25% free space.
if journal != "wal" || mode != 2 || free * page_size < MIN_FREE_BYTES || free < pages / 4 {
outcome = PassOutcome::Idle;
return Ok(());
}
if !checkpoint_complete(connection).await? {
return Ok(());
}
outcome = PassOutcome::Active;
let reserve = (RESERVE_BYTES / page_size).max(pages / 10);
let version: i64 = sqlx::query_scalar("PRAGMA data_version")
.fetch_one(&mut *connection)
.await?;
while reclaimed < budget.pages
&& budget
.deadline
.is_none_or(|deadline| Instant::now() < deadline)
&& !shutdown.has_changed().unwrap_or(true)
{
// Check inside the same write transaction, so a foreground writer cannot
// consume the reserve between our free-page check and vacuum.
let mut transaction = connection.begin_with("BEGIN IMMEDIATE").await?;
let free: i64 = sqlx::query_scalar("PRAGMA freelist_count")
.fetch_one(&mut *transaction)
.await?;
if free <= reserve {
transaction.rollback().await?;
outcome = PassOutcome::Idle;
break;
}
let batch = i64::from(batch_pages.min(budget.pages - reclaimed)).min(free - reserve);
sqlx::query(sqlx::AssertSqlSafe(format!(
"PRAGMA incremental_vacuum({batch})"
)))
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
reclaimed += batch as u32;
// A reader arriving after admission can pin at most one batch.
if !checkpoint_complete(connection).await? {
outcome = PassOutcome::Contended;
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
// Back off if another connection committed during this pass.
let current: i64 = sqlx::query_scalar("PRAGMA data_version")
.fetch_one(&mut *connection)
.await?;
if current != version {
outcome = PassOutcome::Contended;
break;
}
}
Ok(())
}
.await;
// Contention and deadlines defer work, including when a prefix has committed.
// The connection is dedicated and closed by the caller, so an interrupted
// transaction cannot leak into foreground work.
match result {
Ok(()) => {}
Err(error) => match outcome_after_error(&error) {
Some(reason) => outcome = reason,
None => return Err(error.into()),
},
}
if shutdown.has_changed().unwrap_or(true) {
outcome = PassOutcome::Shutdown;
} else if outcome == PassOutcome::Active
&& budget
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
{
// The deadline can also expire between statements, without SQLITE_INTERRUPT.
outcome = PassOutcome::Interrupted;
}
Ok(ReclamationPass {
pages: reclaimed,
outcome,
})
}
fn outcome_after_error(error: &sqlx::Error) -> Option<PassOutcome> {
error
.as_database_error()
.and_then(sqlx::error::DatabaseError::code)
.and_then(
|code| match code.parse::<i32>().ok().map(|code| code & 0xff) {
Some(libsqlite3_sys::SQLITE_BUSY | libsqlite3_sys::SQLITE_LOCKED) => {
Some(PassOutcome::Contended)
}
Some(libsqlite3_sys::SQLITE_INTERRUPT) => Some(PassOutcome::Interrupted),
_ => None,
},
)
}
async fn checkpoint_complete(connection: &mut SqliteConnection) -> Result<bool, sqlx::Error> {
// PASSIVE does not take the writer lock or wait for readers. It can still
// exceed the cooperative deadline on slow storage. Do not reject a large
// WAL forever: a quiet database may have no other writer to checkpoint it.
let (busy, frames, done): (i64, i64, i64) = sqlx::query_as("PRAGMA wal_checkpoint(PASSIVE)")
.fetch_one(connection)
.await?;
Ok(busy == 0 && frames >= 0 && frames == done)
}
#[cfg(test)]
#[path = "reclamation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,220 @@
use super::*;
use crate::migrations::runtime_logs_migrator;
use crate::runtime::test_support::unique_temp_dir;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn reclaims_current_and_legacy_logs_with_independent_directory_locks() -> anyhow::Result<()> {
let directory = unique_temp_dir();
tokio::fs::create_dir_all(&directory).await?;
let legacy = SqliteConfig::new_for_testing(directory.as_path().abs());
let sqlite = legacy.clone().with_local_logs_home(directory.join("log"));
let mut pools = Vec::new();
let mut sizes = Vec::new();
for config in [&sqlite, &legacy] {
let pool = config
.open_logs_db(&runtime_logs_migrator(), /*telemetry_override*/ None)
.await?;
sqlx::query(
"WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i < 4096) \
INSERT INTO logs(ts,ts_nanos,level,target,feedback_log_body) \
SELECT unixepoch(),0,'INFO','fixture',printf('%032768d',i) FROM n",
)
.execute(&pool)
.await?;
sqlx::query("DELETE FROM logs WHERE id%4 != 0")
.execute(&pool)
.await?;
sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
.execute(&pool)
.await?;
sizes.push(tokio::fs::metadata(config.logs_db_path()).await?.len());
pools.push(pool);
}
let rows = "SELECT id, feedback_log_body FROM logs ORDER BY id";
let expected: Vec<(i64, String)> = sqlx::query_as(rows).fetch_all(&pools[0]).await?;
let mut scheduled = sqlite
.reclamation_db_paths()
.into_iter()
.map(|db| (db, Instant::now(), ReclamationState::default()))
.collect::<Vec<_>>();
let mut owners = BTreeMap::new();
let (_shutdown, receiver) = watch::channel(());
// A legacy process owns its directory. Current logs must still be reclaimed.
let legacy_owner = try_ownership(legacy.home()).await?.unwrap();
for (index, config) in [&sqlite, &legacy].into_iter().enumerate() {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
for (_, due, _) in &mut scheduled {
*due = Instant::now();
}
visit(&sqlite, &mut scheduled, &mut owners, &receiver).await;
if config.logs_are_on_nfs().await.unwrap()
|| tokio::fs::metadata(config.logs_db_path())
.await
.unwrap()
.len()
< sizes[index]
{
break;
}
}
})
.await?;
if index == 0 {
assert_eq!(
tokio::fs::metadata(legacy.logs_db_path()).await?.len(),
sizes[1]
);
legacy_owner.unlock()?;
}
}
for pool in pools {
assert_eq!(
sqlx::query_as::<_, (i64, String)>(rows)
.fetch_all(&pool)
.await?,
expected
);
pool.close().await;
}
drop(owners);
drop(legacy_owner);
tokio::fs::remove_dir_all(directory).await?;
Ok(())
}
#[tokio::test]
async fn interrupted_reclamation_releases_writer_and_resumes_without_data_loss()
-> anyhow::Result<()> {
let sqlite = SqliteConfig::new_for_testing(unique_temp_dir().abs());
tokio::fs::create_dir_all(sqlite.home()).await?;
let pool = sqlite
.open_logs_db(&runtime_logs_migrator(), /*telemetry_override*/ None)
.await?;
sqlx::query(
"WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i < 4096) \
INSERT INTO logs(ts,ts_nanos,level,target,feedback_log_body,thread_id,process_uuid) \
SELECT unixepoch(),0,'INFO','fixture',printf('%032768d',i),'thread-'||i,'process-'||(i%17) FROM n",
)
.execute(&pool)
.await?;
sqlx::query("DELETE FROM logs WHERE id%4 != 0")
.execute(&pool)
.await?;
sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
.execute(&pool)
.await?;
let rows = "SELECT id, feedback_log_body FROM logs ORDER BY id";
let mut expected: Vec<(i64, String)> = sqlx::query_as(rows).fetch_all(&pool).await?;
let free_before: i64 = sqlx::query_scalar("PRAGMA freelist_count")
.fetch_one(&pool)
.await?;
let (shutdown, receiver) = watch::channel(());
let mut connection = pool.acquire().await?.detach();
sqlx::raw_sql(
"PRAGMA busy_timeout = 0; PRAGMA wal_autocheckpoint = 0; PRAGMA cache_size = -16384;",
)
.execute(&mut connection)
.await?;
// Request shutdown inside the first vacuum commit, while SQLite still owns the
// writer lock. The production progress handler must stop this pass safely.
connection.lock_handle().await?.set_commit_hook(move || {
shutdown.send_replace(());
true
});
let interrupted = reclaim_pages(
&mut connection,
Budget {
// Shutdown, rather than machine speed, determines the interruption point.
deadline: Some(Instant::now() + Duration::from_secs(30)),
pages: PASS_PAGES,
},
&receiver,
)
.await?;
assert!(receiver.has_changed()?, "must reach the vacuum commit");
assert!(interrupted.pages <= BATCH_PAGES);
connection.close().await?;
let free_after: i64 = sqlx::query_scalar("PRAGMA freelist_count")
.fetch_one(&pool)
.await?;
// An interruption at COMMIT may leave the first batch committed or rolled back.
assert!((0..=i64::from(BATCH_PAGES)).contains(&(free_before - free_after)));
assert_eq!(
sqlx::query_as::<_, (i64, String)>(rows)
.fetch_all(&pool)
.await?,
expected
);
// A foreground write must acquire the lock immediately, without a busy retry.
let mut writer = pool.acquire().await?;
sqlx::query("PRAGMA busy_timeout = 0")
.execute(&mut *writer)
.await?;
let mut transaction = writer.begin_with("BEGIN IMMEDIATE").await?;
expected[0].1 = "foreground write after interruption".to_string();
sqlx::query("UPDATE logs SET feedback_log_body = ? WHERE id = ?")
.bind(&expected[0].1)
.bind(expected[0].0)
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
drop(writer);
// Flush earlier writes so only the resumed pass can shrink the main file.
sqlx::query("PRAGMA wal_checkpoint(TRUNCATE)")
.execute(&pool)
.await?;
let bytes_before_retry = tokio::fs::metadata(sqlite.logs_db_path()).await?.len();
let free_before_retry: i64 = sqlx::query_scalar("PRAGMA freelist_count")
.fetch_one(&pool)
.await?;
let (_shutdown, receiver) = watch::channel(());
let resumed = reclaim(
&sqlite,
&sqlite.logs_db_path(),
Budget {
deadline: Some(Instant::now() + Duration::from_secs(30)),
pages: BATCH_PAGES,
},
&receiver,
)
.await?;
let free_after_retry: i64 = sqlx::query_scalar("PRAGMA freelist_count")
.fetch_one(&pool)
.await?;
assert_eq!(
free_before_retry - free_after_retry,
i64::from(resumed.pages)
);
let bytes_after_retry = tokio::fs::metadata(sqlite.logs_db_path()).await?.len();
if sqlite.is_nfs().await? {
assert_eq!(resumed.pages, 0);
assert_eq!(bytes_after_retry, bytes_before_retry);
} else {
assert!(resumed.pages > 0);
assert!(
bytes_after_retry < bytes_before_retry,
"reclamation must shrink the SQLite file: {bytes_before_retry} -> {bytes_after_retry} bytes"
);
}
assert_eq!(
sqlx::query_as::<_, (i64, String)>(rows)
.fetch_all(&pool)
.await?,
expected
);
assert_eq!(
sqlx::query_scalar::<_, String>("PRAGMA integrity_check")
.fetch_all(&pool)
.await?,
vec!["ok"]
);
pool.close().await;
tokio::fs::remove_dir_all(sqlite.home()).await?;
Ok(())
}

View File

@@ -0,0 +1,270 @@
//! Backup-and-rebuild support for Codex runtime SQLite databases.
//!
//! Codex keeps several independent runtime SQLite databases under one SQLite
//! home. When SQLite reports that one of them is corrupt, automatic recovery
//! moves only that database file and its sidecars into a backup folder so the
//! other databases keep their data. Startup callers may collect backups in a
//! task-local scope to notify users after recovery; backup behavior is unchanged
//! outside that scope.
use sqlx::error::DatabaseError;
use std::cell::RefCell;
use std::future::Future;
use std::path::Path;
use std::path::PathBuf;
const BACKUP_DIR_NAME: &str = "db-backups";
tokio::task_local! {
static RECOVERY_BACKUPS: RefCell<Vec<RuntimeDbBackup>>;
}
/// Collect backups made while polling startup, including recovery across retries.
///
/// The report is scoped to this task: unrelated processes and tasks are excluded.
/// Recovery in spawned tasks is not collected. Callers should report successful
/// recovery only after startup has completed successfully.
pub async fn collect_runtime_db_backups<T>(
startup: impl Future<Output = T>,
) -> (T, Vec<RuntimeDbBackup>) {
RECOVERY_BACKUPS
.scope(RefCell::new(Vec::new()), async {
let result = startup.await;
let backups = RECOVERY_BACKUPS.with(std::cell::RefCell::take);
(result, backups)
})
.await
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeDbBackup {
/// Path where the runtime database or sidecar lived before it was moved.
pub original_path: PathBuf,
/// Path where the runtime database or sidecar was backed up.
pub backup_path: PathBuf,
}
#[derive(Debug)]
pub(crate) struct RuntimeDbInitError {
label: &'static str,
operation: &'static str,
path: PathBuf,
source: anyhow::Error,
}
impl RuntimeDbInitError {
pub(crate) fn new(
label: &'static str,
operation: &'static str,
path: &Path,
source: anyhow::Error,
) -> Self {
Self {
label,
operation,
path: path.to_path_buf(),
source,
}
}
fn path(&self) -> &Path {
self.path.as_path()
}
}
impl std::fmt::Display for RuntimeDbInitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"failed to {} {} at {}: {}",
self.operation,
self.label,
self.path.display(),
self.source
)
}
}
impl std::error::Error for RuntimeDbInitError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.source.as_ref())
}
}
/// Move one Codex runtime SQLite database out of the way so that database can
/// be recreated without discarding unrelated runtime databases.
pub async fn backup_runtime_db_for_fresh_start(
db_path: &Path,
) -> std::io::Result<Vec<RuntimeDbBackup>> {
let sqlite_home = db_path.parent().ok_or_else(|| {
std::io::Error::other(format!(
"database path does not have a parent directory: {}",
db_path.display()
))
})?;
let backups = match tokio::fs::metadata(sqlite_home).await {
Ok(metadata) if metadata.is_dir() => backup_runtime_db_files(db_path).await,
Ok(_) => backup_blocking_sqlite_home(sqlite_home).await,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
tokio::fs::create_dir_all(sqlite_home).await?;
Err(std::io::Error::other(format!(
"no Codex runtime database files were found to back up for {}",
db_path.display()
)))
}
Err(err) => Err(err),
}?;
let _ = RECOVERY_BACKUPS.try_with(|report| report.borrow_mut().extend(backups.iter().cloned()));
Ok(backups)
}
pub fn runtime_db_path_for_corruption_error(err: &anyhow::Error) -> Option<PathBuf> {
if !is_sqlite_corruption_error(err) {
return None;
}
err.chain()
.find_map(|source| source.downcast_ref::<RuntimeDbInitError>())
.map(|err| err.path().to_path_buf())
}
pub fn is_sqlite_corruption_error(err: &anyhow::Error) -> bool {
err.chain().any(sqlite_error_source_is_corruption)
}
fn sqlite_error_source_is_corruption(source: &(dyn std::error::Error + 'static)) -> bool {
if let Some(err) = source.downcast_ref::<libsqlite3_sys::Error>() {
return matches!(
err.code,
libsqlite3_sys::ErrorCode::DatabaseCorrupt | libsqlite3_sys::ErrorCode::NotADatabase
);
}
let sqlite_error = source
.downcast_ref::<sqlx::sqlite::SqliteError>()
.or_else(|| {
source
.downcast_ref::<sqlx::Error>()?
.as_database_error()?
.try_downcast_ref::<sqlx::sqlite::SqliteError>()
});
let Some(err) = sqlite_error else {
return false;
};
// SQLx exposes SQLite's extended result code as a decimal string.
err.code()
.and_then(|code| code.parse::<i32>().ok())
.is_some_and(|code| {
matches!(
libsqlite3_sys::Error::new(code).code,
libsqlite3_sys::ErrorCode::DatabaseCorrupt
| libsqlite3_sys::ErrorCode::NotADatabase
)
})
}
pub fn sqlite_error_detail_is_lock(detail: &str) -> bool {
let detail = detail.to_ascii_lowercase();
detail.contains("database is locked") || detail.contains("database is busy")
}
async fn backup_runtime_db_files(db_path: &Path) -> std::io::Result<Vec<RuntimeDbBackup>> {
let sqlite_home = db_path.parent().ok_or_else(|| {
std::io::Error::other(format!(
"database path does not have a parent directory: {}",
db_path.display()
))
})?;
backup_sqlite_paths(sqlite_home, sqlite_paths(db_path)).await
}
async fn backup_sqlite_paths(
sqlite_home: &Path,
paths: impl IntoIterator<Item = PathBuf>,
) -> std::io::Result<Vec<RuntimeDbBackup>> {
let backup_dir = create_unique_backup_dir(sqlite_home.join(BACKUP_DIR_NAME).as_path()).await?;
let mut backups = Vec::new();
for path in paths {
if tokio::fs::try_exists(path.as_path()).await? {
let backup_path = backup_dir.join(file_name(path.as_path())?);
tokio::fs::rename(path.as_path(), backup_path.as_path()).await?;
backups.push(RuntimeDbBackup {
original_path: path,
backup_path,
});
}
}
if backups.is_empty() {
let _ = tokio::fs::remove_dir(backup_dir).await;
return Err(std::io::Error::other(
"no Codex runtime database files were found to back up",
));
}
Ok(backups)
}
async fn backup_blocking_sqlite_home(sqlite_home: &Path) -> std::io::Result<Vec<RuntimeDbBackup>> {
let parent = sqlite_home.parent().ok_or_else(|| {
std::io::Error::other(format!(
"cannot create a backup folder for {}",
sqlite_home.display()
))
})?;
let mut backup_dir_name = file_name(sqlite_home)?.to_os_string();
backup_dir_name.push(format!(".{BACKUP_DIR_NAME}"));
let backup_parent = parent.join(backup_dir_name);
let backup_dir = create_unique_backup_dir(backup_parent.as_path()).await?;
let backup_path = backup_dir.join(file_name(sqlite_home)?);
tokio::fs::rename(sqlite_home, backup_path.as_path()).await?;
tokio::fs::create_dir_all(sqlite_home).await?;
Ok(vec![RuntimeDbBackup {
original_path: sqlite_home.to_path_buf(),
backup_path,
}])
}
fn sqlite_paths(db_path: &Path) -> Vec<PathBuf> {
let mut wal_path = db_path.as_os_str().to_os_string();
wal_path.push("-wal");
let mut shm_path = db_path.as_os_str().to_os_string();
shm_path.push("-shm");
vec![
db_path.to_path_buf(),
PathBuf::from(wal_path),
PathBuf::from(shm_path),
]
}
async fn create_unique_backup_dir(backup_parent: &Path) -> std::io::Result<PathBuf> {
tokio::fs::create_dir_all(backup_parent).await?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |duration| duration.as_secs());
let mut sequence = 0_u32;
loop {
let backup_dir = backup_parent.join(format!("sqlite-{timestamp}-{sequence}"));
match tokio::fs::create_dir(backup_dir.as_path()).await {
Ok(()) => return Ok(backup_dir),
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
sequence += 1;
}
Err(err) => return Err(err),
}
}
}
fn file_name(path: &Path) -> std::io::Result<&std::ffi::OsStr> {
path.file_name().ok_or_else(|| {
std::io::Error::other(format!(
"cannot create a backup name for {}",
path.display()
))
})
}
#[cfg(test)]
#[path = "recovery_tests.rs"]
mod tests;

View File

@@ -0,0 +1,113 @@
use super::*;
use crate::runtime::test_support::unique_temp_dir;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn backup_moves_only_requested_runtime_db_files_to_backup_folder() -> std::io::Result<()> {
let sqlite_home = unique_temp_dir();
tokio::fs::create_dir_all(sqlite_home.as_path()).await?;
let sqlite = crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let runtime_paths = sqlite.runtime_db_paths();
let mut expected_paths = Vec::new();
for db_path in runtime_paths.iter().map(|db| db.path.as_path()) {
for path in sqlite_paths(db_path) {
tokio::fs::write(path.as_path(), path.display().to_string()).await?;
expected_paths.push(path);
}
}
let failed_db_path = sqlite.logs_db_path();
let failed_paths = sqlite_paths(failed_db_path.as_path());
let (result, report) =
collect_runtime_db_backups(backup_runtime_db_for_fresh_start(failed_db_path.as_path()))
.await;
let backups = result?;
assert_eq!(report, backups);
assert_eq!(backups.len(), failed_paths.len());
for path in &failed_paths {
assert!(!tokio::fs::try_exists(path.as_path()).await?);
}
for path in expected_paths
.iter()
.filter(|path| !failed_paths.contains(path))
{
assert!(tokio::fs::try_exists(path.as_path()).await?);
}
for backup in backups {
assert!(
backup
.backup_path
.starts_with(sqlite_home.join(BACKUP_DIR_NAME))
);
assert!(tokio::fs::try_exists(backup.backup_path.as_path()).await?);
}
Ok(())
}
#[tokio::test]
async fn backup_replaces_blocking_sqlite_home_file() -> std::io::Result<()> {
let temp_dir = unique_temp_dir();
tokio::fs::create_dir_all(temp_dir.as_path()).await?;
let sqlite_home = temp_dir.join("sqlite-home");
tokio::fs::write(sqlite_home.as_path(), b"not-a-directory").await?;
let backups = backup_runtime_db_for_fresh_start(
crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs())
.state_db_path()
.as_path(),
)
.await?;
assert_eq!(backups.len(), 1);
assert!(tokio::fs::metadata(sqlite_home.as_path()).await?.is_dir());
assert!(
backups[0]
.backup_path
.starts_with(temp_dir.join(format!("sqlite-home.{BACKUP_DIR_NAME}")))
);
assert!(tokio::fs::try_exists(backups[0].backup_path.as_path()).await?);
Ok(())
}
#[test]
fn sqlite_error_detail_classifies_lock_errors() {
assert!(sqlite_error_detail_is_lock("database is locked"));
assert!(sqlite_error_detail_is_lock("database is busy"));
}
#[tokio::test]
async fn runtime_db_path_for_corruption_error_returns_failed_database_path() -> std::io::Result<()>
{
let sqlite_home = unique_temp_dir();
tokio::fs::create_dir_all(sqlite_home.as_path()).await?;
let path = crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs()).state_db_path();
tokio::fs::write(path.as_path(), b"not sqlite").await?;
let err = match super::super::StateRuntime::init(
crate::SqliteConfig::new_for_testing(sqlite_home.as_path().abs()),
"openai".to_string(),
)
.await
{
Ok(_) => panic!("malformed sqlite should fail to initialize"),
Err(err) => err,
};
assert_eq!(runtime_db_path_for_corruption_error(&err), Some(path));
Ok(())
}
#[test]
fn runtime_db_path_for_corruption_error_ignores_corrupt_word_in_path() {
let path = PathBuf::from("/tmp/sqlite_corrupt/state_5.sqlite");
let err = anyhow::Error::new(RuntimeDbInitError::new(
"state DB",
"open",
path.as_path(),
anyhow::anyhow!("permission denied"),
));
assert_eq!(runtime_db_path_for_corruption_error(&err), None);
}

View File

@@ -0,0 +1,394 @@
use super::*;
use crate::sqlite::SqliteWriteQueryExt;
const REMOTE_CONTROL_APP_SERVER_CLIENT_NAME_NONE: &str = "";
/// Persisted remote-control server enrollment, including the lookup key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteControlEnrollmentRecord {
pub websocket_url: String,
pub account_id: String,
pub app_server_client_name: Option<String>,
pub server_id: String,
pub environment_id: String,
pub server_name: String,
pub remote_control_enabled: Option<bool>,
}
fn remote_control_app_server_client_name_key(app_server_client_name: Option<&str>) -> &str {
app_server_client_name.unwrap_or(REMOTE_CONTROL_APP_SERVER_CLIENT_NAME_NONE)
}
fn app_server_client_name_from_key(app_server_client_name: String) -> Option<String> {
if app_server_client_name.is_empty() {
None
} else {
Some(app_server_client_name)
}
}
impl StateRuntime {
pub async fn get_remote_control_enrollment(
&self,
websocket_url: &str,
account_id: &str,
app_server_client_name: Option<&str>,
) -> anyhow::Result<Option<RemoteControlEnrollmentRecord>> {
let row = sqlx::query(
r#"
SELECT websocket_url, account_id, app_server_client_name, server_id, environment_id, server_name,
remote_control_enabled
FROM remote_control_enrollments
WHERE websocket_url = ? AND account_id = ? AND app_server_client_name = ?
"#,
)
.bind(websocket_url)
.bind(account_id)
.bind(remote_control_app_server_client_name_key(
app_server_client_name,
))
.fetch_optional(self.pool.as_ref())
.await?;
row.map(|row| {
let app_server_client_name: String = row.try_get("app_server_client_name")?;
Ok(RemoteControlEnrollmentRecord {
websocket_url: row.try_get("websocket_url")?,
account_id: row.try_get("account_id")?,
app_server_client_name: app_server_client_name_from_key(app_server_client_name),
server_id: row.try_get("server_id")?,
environment_id: row.try_get("environment_id")?,
server_name: row.try_get("server_name")?,
remote_control_enabled: row.try_get("remote_control_enabled")?,
})
})
.transpose()
}
pub async fn upsert_remote_control_enrollment(
&self,
enrollment: &RemoteControlEnrollmentRecord,
) -> anyhow::Result<()> {
sqlx::query(
r#"
INSERT INTO remote_control_enrollments (
websocket_url,
account_id,
app_server_client_name,
server_id,
environment_id,
server_name,
remote_control_enabled,
updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(websocket_url, account_id, app_server_client_name) DO UPDATE SET
server_id = excluded.server_id,
environment_id = excluded.environment_id,
server_name = excluded.server_name,
updated_at = excluded.updated_at
"#,
)
.bind(&enrollment.websocket_url)
.bind(&enrollment.account_id)
.bind(remote_control_app_server_client_name_key(
enrollment.app_server_client_name.as_deref(),
))
.bind(&enrollment.server_id)
.bind(&enrollment.environment_id)
.bind(&enrollment.server_name)
.bind(enrollment.remote_control_enabled)
.bind(Utc::now().timestamp())
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
pub async fn set_remote_control_enabled(
&self,
websocket_url: &str,
account_id: &str,
app_server_client_name: Option<&str>,
remote_control_enabled: bool,
) -> anyhow::Result<u64> {
let result = sqlx::query(
r#"
UPDATE remote_control_enrollments
SET remote_control_enabled = ?, updated_at = ?
WHERE websocket_url = ? AND account_id = ? AND app_server_client_name = ?
"#,
)
.bind(remote_control_enabled)
.bind(Utc::now().timestamp())
.bind(websocket_url)
.bind(account_id)
.bind(remote_control_app_server_client_name_key(
app_server_client_name,
))
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(result.rows_affected())
}
pub async fn delete_remote_control_enrollment(
&self,
websocket_url: &str,
account_id: &str,
app_server_client_name: Option<&str>,
) -> anyhow::Result<u64> {
let result = sqlx::query(
r#"
DELETE FROM remote_control_enrollments
WHERE websocket_url = ? AND account_id = ? AND app_server_client_name = ?
"#,
)
.bind(websocket_url)
.bind(account_id)
.bind(remote_control_app_server_client_name_key(
app_server_client_name,
))
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(result.rows_affected())
}
}
#[cfg(test)]
mod tests {
use super::RemoteControlEnrollmentRecord;
use super::StateRuntime;
use super::test_support::unique_temp_dir;
use crate::migrations::STATE_MIGRATOR;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::migrate::Migrator;
use std::borrow::Cow;
#[tokio::test]
async fn remote_control_enrollment_round_trips_by_target_and_account() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
runtime
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
websocket_url: "wss://example.com/backend-api/wham/remote/control/server"
.to_string(),
account_id: "account-a".to_string(),
app_server_client_name: Some("desktop-client".to_string()),
server_id: "srv_e_first".to_string(),
environment_id: "env_first".to_string(),
server_name: "first-server".to_string(),
remote_control_enabled: Some(false),
})
.await
.expect("insert first enrollment");
runtime
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
websocket_url: "wss://example.com/backend-api/wham/remote/control/server"
.to_string(),
account_id: "account-b".to_string(),
app_server_client_name: Some("desktop-client".to_string()),
server_id: "srv_e_second".to_string(),
environment_id: "env_second".to_string(),
server_name: "second-server".to_string(),
remote_control_enabled: Some(true),
})
.await
.expect("insert second enrollment");
assert_eq!(
runtime
.get_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-a",
Some("desktop-client"),
)
.await
.expect("load first enrollment"),
Some(RemoteControlEnrollmentRecord {
websocket_url: "wss://example.com/backend-api/wham/remote/control/server"
.to_string(),
account_id: "account-a".to_string(),
app_server_client_name: Some("desktop-client".to_string()),
server_id: "srv_e_first".to_string(),
environment_id: "env_first".to_string(),
server_name: "first-server".to_string(),
remote_control_enabled: Some(false),
})
);
assert_eq!(
runtime
.get_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-missing",
Some("desktop-client"),
)
.await
.expect("load missing enrollment"),
None
);
assert_eq!(
runtime
.get_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-a",
Some("other-client"),
)
.await
.expect("load wrong client enrollment"),
None
);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn delete_remote_control_enrollment_removes_only_matching_entry() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
runtime
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
websocket_url: "wss://example.com/backend-api/wham/remote/control/server"
.to_string(),
account_id: "account-a".to_string(),
app_server_client_name: None,
server_id: "srv_e_first".to_string(),
environment_id: "env_first".to_string(),
server_name: "first-server".to_string(),
remote_control_enabled: Some(false),
})
.await
.expect("insert first enrollment");
runtime
.upsert_remote_control_enrollment(&RemoteControlEnrollmentRecord {
websocket_url: "wss://example.com/backend-api/wham/remote/control/server"
.to_string(),
account_id: "account-b".to_string(),
app_server_client_name: None,
server_id: "srv_e_second".to_string(),
environment_id: "env_second".to_string(),
server_name: "second-server".to_string(),
remote_control_enabled: Some(true),
})
.await
.expect("insert second enrollment");
assert_eq!(
runtime
.delete_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-a",
/*app_server_client_name*/ None,
)
.await
.expect("delete first enrollment"),
1
);
assert_eq!(
runtime
.get_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-a",
/*app_server_client_name*/ None,
)
.await
.expect("load deleted enrollment"),
None
);
assert_eq!(
runtime
.get_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-b",
/*app_server_client_name*/ None,
)
.await
.expect("load retained enrollment"),
Some(RemoteControlEnrollmentRecord {
websocket_url: "wss://example.com/backend-api/wham/remote/control/server"
.to_string(),
account_id: "account-b".to_string(),
app_server_client_name: None,
server_id: "srv_e_second".to_string(),
environment_id: "env_second".to_string(),
server_name: "second-server".to_string(),
remote_control_enabled: Some(true),
})
);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
#[tokio::test]
async fn migration_preserves_legacy_remote_control_preference_as_null() {
let codex_home = unique_temp_dir();
tokio::fs::create_dir_all(&codex_home)
.await
.expect("create codex home");
let old_state_migrator = Migrator {
migrations: Cow::Owned(
STATE_MIGRATOR
.migrations
.iter()
.filter(|migration| migration.version <= 36)
.cloned()
.collect(),
),
ignore_missing: false,
locking: true,
no_tx: false,
table_name: STATE_MIGRATOR.table_name.clone(),
create_schemas: STATE_MIGRATOR.create_schemas.clone(),
};
let sqlite = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs());
let pool = sqlite
.open_read_write_pool(&sqlite.state_db_path())
.await
.expect("open old state db");
old_state_migrator
.run(&pool)
.await
.expect("apply old state schema");
sqlx::query("INSERT INTO remote_control_enrollments (websocket_url, account_id, app_server_client_name, server_id, environment_id, server_name, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
.bind("wss://example.com/backend-api/wham/remote/control/server")
.bind("account-a")
.bind("desktop-client")
.bind("srv_e_first")
.bind("env_first")
.bind("first-server")
.bind(1_i64)
.execute(&pool)
.await
.expect("insert legacy enrollment");
pool.close().await;
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let actual = runtime
.get_remote_control_enrollment(
"wss://example.com/backend-api/wham/remote/control/server",
"account-a",
Some("desktop-client"),
)
.await
.expect("load migrated enrollment")
.expect("legacy enrollment should remain");
assert_eq!(actual.remote_control_enabled, None);
let _ = tokio::fs::remove_dir_all(codex_home).await;
}
}

View File

@@ -0,0 +1,150 @@
//! Persists generic rollout-migration progress in the state database.
//!
//! It stores a monotonic creation-ordered cursor for each migration and records fingerprinted
//! rollouts that the migration could not process. Thread-store uses this state to avoid rescanning
//! old rollouts on every startup while still retrying skipped files that later change.
use super::*;
use crate::sqlite::SqliteWriteQueryExt;
impl StateRuntime {
pub async fn get_rollout_migration_state(
&self,
migration_id: &str,
) -> anyhow::Result<Option<crate::RolloutMigrationState>> {
let row = sqlx::query(
r#"
SELECT last_checked_thread_created_at, last_checked_thread_id
FROM rollout_migration_state
WHERE migration_id = ?
"#,
)
.bind(migration_id)
.fetch_optional(self.pool.as_ref())
.await?;
row.as_ref()
.map(crate::RolloutMigrationState::try_from_row)
.transpose()
}
/// Advance one migration's checked frontier without letting concurrent startup checks move
/// it backward.
pub async fn advance_rollout_migration_state(
&self,
migration_id: &str,
last_checked_thread: Option<&crate::RolloutMigrationCursor>,
) -> anyhow::Result<()> {
let now = Utc::now().timestamp();
let (thread_created_at, thread_id) = last_checked_thread.map_or((None, None), |cursor| {
(
Some(cursor.thread_created_at),
Some(cursor.thread_id.as_str()),
)
});
sqlx::query(
r#"
INSERT INTO rollout_migration_state (
migration_id,
last_checked_thread_created_at,
last_checked_thread_id,
updated_at
)
VALUES (?, ?, ?, ?)
ON CONFLICT(migration_id) DO UPDATE SET
last_checked_thread_created_at = excluded.last_checked_thread_created_at,
last_checked_thread_id = excluded.last_checked_thread_id,
updated_at = excluded.updated_at
WHERE excluded.last_checked_thread_created_at IS NOT NULL
AND (
rollout_migration_state.last_checked_thread_created_at IS NULL
OR excluded.last_checked_thread_created_at
> rollout_migration_state.last_checked_thread_created_at
OR (
excluded.last_checked_thread_created_at
= rollout_migration_state.last_checked_thread_created_at
AND excluded.last_checked_thread_id > rollout_migration_state.last_checked_thread_id
)
)
"#,
)
.bind(migration_id)
.bind(thread_created_at)
.bind(thread_id)
.bind(now)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
pub async fn list_rollout_migration_skipped_rollouts(
&self,
migration_id: &str,
) -> anyhow::Result<Vec<crate::RolloutMigrationSkippedRollout>> {
let rows = sqlx::query(
r#"
SELECT rollout_path, rollout_size_bytes, rollout_modified_at_ns, skip_reason
FROM rollout_migration_skipped_rollouts
WHERE migration_id = ?
"#,
)
.bind(migration_id)
.fetch_all(self.pool.as_ref())
.await?;
rows.iter()
.map(crate::RolloutMigrationSkippedRollout::try_from_row)
.collect()
}
pub async fn record_rollout_migration_skip(
&self,
migration_id: &str,
skipped_rollout: &crate::RolloutMigrationSkippedRollout,
) -> anyhow::Result<()> {
let now = Utc::now().timestamp();
sqlx::query(
r#"
INSERT INTO rollout_migration_skipped_rollouts (
migration_id,
rollout_path,
rollout_size_bytes,
rollout_modified_at_ns,
skip_reason,
skipped_at
)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(migration_id, rollout_path) DO UPDATE SET
rollout_size_bytes = excluded.rollout_size_bytes,
rollout_modified_at_ns = excluded.rollout_modified_at_ns,
skip_reason = excluded.skip_reason,
skipped_at = excluded.skipped_at
"#,
)
.bind(migration_id)
.bind(skipped_rollout.rollout_path.as_str())
.bind(skipped_rollout.rollout_size_bytes)
.bind(skipped_rollout.rollout_modified_at_ns)
.bind(skipped_rollout.skip_reason.as_str())
.bind(now)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
pub async fn remove_rollout_migration_skip(
&self,
migration_id: &str,
rollout_path: &str,
) -> anyhow::Result<()> {
sqlx::query(
r#"
DELETE FROM rollout_migration_skipped_rollouts
WHERE migration_id = ? AND rollout_path = ?
"#,
)
.bind(migration_id)
.bind(rollout_path)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(())
}
}

View File

@@ -0,0 +1,85 @@
#[cfg(test)]
use chrono::DateTime;
#[cfg(test)]
use chrono::Utc;
#[cfg(test)]
use codex_protocol::ThreadId;
#[cfg(test)]
use codex_protocol::openai_models::ReasoningEffort;
#[cfg(test)]
use codex_protocol::protocol::AskForApproval;
#[cfg(test)]
use codex_protocol::protocol::SandboxPolicy;
#[cfg(test)]
use codex_protocol::protocol::ThreadHistoryMode;
#[cfg(test)]
use std::path::Path;
#[cfg(test)]
use std::path::PathBuf;
#[cfg(test)]
use std::time::SystemTime;
#[cfg(test)]
use std::time::UNIX_EPOCH;
#[cfg(test)]
use uuid::Uuid;
#[cfg(test)]
use crate::ThreadMetadata;
#[cfg(test)]
pub(crate) fn unique_temp_dir() -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_nanos());
std::env::temp_dir().join(format!(
"codex-state-runtime-test-{nanos}-{}",
Uuid::new_v4()
))
}
#[cfg(test)]
pub(super) fn test_thread_metadata(
codex_home: &Path,
thread_id: ThreadId,
cwd: PathBuf,
) -> ThreadMetadata {
let now = DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("timestamp");
ThreadMetadata {
creator_user_id: None,
attached_thread_parent_id: None,
creator_account_id: None,
originator: None,
id: thread_id,
rollout_path: codex_home.join(format!("rollout-{thread_id}.jsonl")),
created_at: now,
updated_at: now,
recency_at: now,
source: "cli".to_string(),
history_mode: ThreadHistoryMode::Legacy,
thread_source: None,
agent_nickname: None,
agent_role: None,
agent_path: None,
model_provider: "test-provider".to_string(),
model: Some("gpt-5".to_string()),
reasoning_effort: Some(ReasoningEffort::Medium),
cwd,
cli_version: "0.0.0".to_string(),
title: String::new(),
name: None,
preview: Some("hello".to_string()),
sandbox_policy: crate::extract::enum_to_string(&SandboxPolicy::new_read_only_policy()),
approval_mode: crate::extract::enum_to_string(&AskForApproval::OnRequest),
tokens_used: 0,
first_user_message: Some("hello".to_string()),
archived_at: None,
section: None,
section_position: None,
section_entered_at: None,
project_id: None,
daybreak_enabled: None,
git_sha: None,
git_branch: None,
git_origin_url: None,
}
}

View File

@@ -0,0 +1,388 @@
//! Transactional thread attachment storage using the attachment SQL schema.
use super::StateRuntime;
use crate::AddThreadAttachmentOutcome;
use crate::MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES;
use crate::MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE;
use crate::MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES;
use crate::MAX_THREAD_ATTACHMENT_TYPE_BYTES;
use crate::MAX_THREAD_ATTACHMENTS_PER_THREAD;
use crate::RemoveThreadAttachmentOutcome;
use crate::ThreadAttachment;
use crate::ThreadAttachmentArchiveFilter;
use crate::ThreadAttachmentOwner;
use crate::ThreadAttachmentOwnerPage;
use crate::ThreadAttachmentPage;
use crate::sqlite::SqlitePoolWriteExt;
use anyhow::Context;
use chrono::Utc;
use codex_protocol::ThreadId;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use sqlx::QueryBuilder;
use sqlx::Row;
use sqlx::Sqlite;
use sqlx::sqlite::SqliteRow;
use uuid::Uuid;
impl StateRuntime {
/// Atomically copies current membership into a new, empty fork, independent of history cutoffs.
pub async fn copy_thread_attachments(
&self,
source_thread_id: ThreadId,
destination_thread_id: ThreadId,
) -> anyhow::Result<()> {
let mut transaction = self.pool.begin_immediate().await?;
let destination = destination_thread_id.to_string();
let exists = sqlx::query_scalar::<_, i64>("SELECT 1 FROM threads WHERE id = ?")
.bind(&destination)
.fetch_optional(&mut *transaction)
.await?
.is_some();
if !exists {
anyhow::bail!("thread not found: {destination_thread_id}");
}
let rows = sqlx::query(
"SELECT attachment_type, identity_key, payload FROM thread_attachments WHERE thread_id = ? ORDER BY created_at, id",
)
.bind(source_thread_id.to_string())
.fetch_all(&mut *transaction)
.await?;
let created_at = Utc::now().timestamp();
for row in rows {
sqlx::query(
"INSERT INTO thread_attachments (id, thread_id, attachment_type, identity_key, payload, created_at) VALUES (?, ?, ?, ?, ?, ?)",
)
.bind(Uuid::now_v7().to_string())
.bind(&destination)
.bind(row.try_get::<String, _>("attachment_type")?)
.bind(row.try_get::<String, _>("identity_key")?)
.bind(row.try_get::<String, _>("payload")?)
.bind(created_at)
.execute(&mut *transaction)
.await?;
}
transaction.commit().await?;
Ok(())
}
/// Attach an attachment once, returning an existing attachment for repeated requests.
pub async fn add_thread_attachment(
&self,
thread_id: ThreadId,
attachment_type: &str,
identity_key: &str,
payload: &Value,
) -> anyhow::Result<AddThreadAttachmentOutcome> {
validate_attachment_identity(attachment_type, identity_key)?;
let serialized_payload = serde_json::to_string(payload).context(
"invalid thread attachment request: attachment payload cannot be serialized",
)?;
if serialized_payload.len() > MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES {
anyhow::bail!(
"invalid thread attachment request: attachment payload exceeds {MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES} bytes"
);
}
let mut transaction = self.pool.begin_immediate().await?;
let thread_id_string = thread_id.to_string();
let thread_exists = sqlx::query_scalar::<_, i64>("SELECT 1 FROM threads WHERE id = ?")
.bind(&thread_id_string)
.fetch_optional(&mut *transaction)
.await?
.is_some();
if !thread_exists {
anyhow::bail!("thread not found: {thread_id}");
}
let existing = sqlx::query(
"SELECT id, thread_id, attachment_type, identity_key, payload, created_at FROM thread_attachments WHERE thread_id = ? AND attachment_type = ? AND identity_key = ?",
)
.bind(&thread_id_string)
.bind(attachment_type)
.bind(identity_key)
.fetch_optional(&mut *transaction)
.await?;
if let Some(existing) = existing {
let attachment = attachment_from_row(&existing)?;
transaction.commit().await?;
return Ok(AddThreadAttachmentOutcome::Existing(attachment));
}
let identity_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM thread_attachments WHERE thread_id = ?",
)
.bind(&thread_id_string)
.fetch_one(&mut *transaction)
.await?;
if usize::try_from(identity_count)? >= MAX_THREAD_ATTACHMENTS_PER_THREAD {
anyhow::bail!(
"invalid thread attachment request: thread attachment identity count exceeds {MAX_THREAD_ATTACHMENTS_PER_THREAD}"
);
}
let attachment = ThreadAttachment {
id: Uuid::now_v7().to_string(),
thread_id,
attachment_type: attachment_type.to_string(),
identity_key: identity_key.to_string(),
payload: payload.clone(),
created_at: Utc::now().timestamp(),
};
sqlx::query(
"INSERT INTO thread_attachments (id, thread_id, attachment_type, identity_key, payload, created_at) VALUES (?, ?, ?, ?, ?, ?)",
)
.bind(&attachment.id)
.bind(&thread_id_string)
.bind(attachment_type)
.bind(identity_key)
.bind(&serialized_payload)
.bind(attachment.created_at)
.execute(&mut *transaction)
.await?;
transaction.commit().await?;
Ok(AddThreadAttachmentOutcome::Created(attachment))
}
/// Remove an attached attachment, immediately freeing its slot.
pub async fn remove_thread_attachment(
&self,
thread_id: ThreadId,
attachment_type: &str,
identity_key: &str,
) -> anyhow::Result<RemoveThreadAttachmentOutcome> {
validate_attachment_identity(attachment_type, identity_key)?;
let mut transaction = self.pool.begin_immediate().await?;
let thread_id_string = thread_id.to_string();
let thread_exists = sqlx::query_scalar::<_, i64>("SELECT 1 FROM threads WHERE id = ?")
.bind(&thread_id_string)
.fetch_optional(&mut *transaction)
.await?
.is_some();
if !thread_exists {
anyhow::bail!("thread not found: {thread_id}");
}
let removed = sqlx::query(
"DELETE FROM thread_attachments WHERE thread_id = ? AND attachment_type = ? AND identity_key = ? RETURNING id, thread_id, attachment_type, identity_key, payload, created_at",
)
.bind(&thread_id_string)
.bind(attachment_type)
.bind(identity_key)
.fetch_optional(&mut *transaction)
.await?;
let outcome = match removed {
Some(row) => RemoveThreadAttachmentOutcome::Removed(attachment_from_row(&row)?),
None => RemoveThreadAttachmentOutcome::NotFound,
};
transaction.commit().await?;
Ok(outcome)
}
/// Lists current owners of an exact attachment identity, including threads without previews.
/// `archive_filter` selects archived, non-archived, or all owners.
pub async fn list_thread_attachment_threads(
&self,
attachment_type: &str,
identity_key: &str,
archive_filter: ThreadAttachmentArchiveFilter,
cursor: Option<&str>,
limit: usize,
) -> anyhow::Result<ThreadAttachmentOwnerPage> {
validate_attachment_identity(attachment_type, identity_key)?;
if !(1..=MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE).contains(&limit) {
anyhow::bail!(
"invalid thread attachment request: page limit must be between 1 and {MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE}"
);
}
let archived = match archive_filter {
ThreadAttachmentArchiveFilter::All => None,
ThreadAttachmentArchiveFilter::NonArchived => Some(false),
ThreadAttachmentArchiveFilter::Archived => Some(true),
};
let anchor = cursor
.map(serde_json::from_str::<AttachmentThreadsCursor>)
.transpose()
.context("invalid thread attachment request: invalid pagination cursor")?;
if let Some(anchor) = &anchor
&& (anchor.attachment_type != attachment_type
|| anchor.identity_key != identity_key
|| anchor.archived != archived)
{
anyhow::bail!("invalid thread attachment request: invalid pagination cursor");
}
let mut query = QueryBuilder::<Sqlite>::new(
"SELECT thread_attachments.thread_id, threads.archived FROM thread_attachments \
JOIN threads ON threads.id = thread_attachments.thread_id \
WHERE thread_attachments.attachment_type = ",
);
query.push_bind(attachment_type);
query.push(" AND thread_attachments.identity_key = ");
query.push_bind(identity_key);
if let Some(archived) = archived {
query.push(" AND threads.archived = ");
query.push_bind(archived);
}
if let Some(anchor) = anchor {
query.push(" AND thread_attachments.thread_id > ");
query.push_bind(anchor.thread_id.to_string());
}
query.push(" ORDER BY thread_attachments.thread_id ASC LIMIT ");
query.push_bind(i64::try_from(limit + 1)?);
let rows = query.build().fetch_all(self.pool.as_ref()).await?;
let mut threads = rows
.iter()
.map(|row| -> anyhow::Result<ThreadAttachmentOwner> {
Ok(ThreadAttachmentOwner {
thread_id: ThreadId::from_string(row.try_get("thread_id")?)
.context("invalid persisted thread attachment owner")?,
archived: row.try_get("archived")?,
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
let next_cursor = if threads.len() > limit {
threads.pop();
threads
.last()
.map(|thread| {
serde_json::to_string(&AttachmentThreadsCursor {
attachment_type: attachment_type.to_owned(),
identity_key: identity_key.to_owned(),
archived,
thread_id: thread.thread_id,
})
})
.transpose()?
} else {
None
};
Ok(ThreadAttachmentOwnerPage {
threads,
next_cursor,
})
}
/// List one bounded page of attachments for one thread in stable keyset order.
pub async fn list_thread_attachments(
&self,
thread_id: ThreadId,
cursor: Option<&str>,
limit: usize,
) -> anyhow::Result<ThreadAttachmentPage> {
if !(1..=MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE).contains(&limit) {
anyhow::bail!(
"invalid thread attachment request: page limit must be between 1 and {MAX_THREAD_ATTACHMENT_LIST_PAGE_SIZE}"
);
}
let thread_id_string = thread_id.to_string();
let anchor = cursor.map(parse_attachment_cursor).transpose()?;
if let Some((cursor_thread_id, _, _)) = anchor.as_ref()
&& cursor_thread_id != &thread_id_string
{
anyhow::bail!("invalid thread attachment request: invalid pagination cursor");
}
let mut query = QueryBuilder::<Sqlite>::new(
"SELECT id, thread_id, attachment_type, identity_key, payload, created_at FROM thread_attachments WHERE thread_id = ",
);
query.push_bind(thread_id_string);
if let Some((_, created_at, attachment_id)) = anchor {
query.push(" AND (created_at, id) > (");
query.push_bind(created_at);
query.push(", ");
query.push_bind(attachment_id);
query.push(")");
}
query.push(" ORDER BY created_at ASC, id ASC LIMIT ");
query.push_bind(i64::try_from(limit + 1)?);
let rows = query.build().fetch_all(self.pool.as_ref()).await?;
let mut attachments = rows
.iter()
.map(attachment_from_row)
.collect::<anyhow::Result<Vec<_>>>()?;
let next_cursor = if attachments.len() > limit {
attachments.pop();
attachments.last().map(|attachment| {
format!(
"{}|{}|{}",
attachment.thread_id, attachment.created_at, attachment.id
)
})
} else {
None
};
Ok(ThreadAttachmentPage {
attachments,
next_cursor,
})
}
}
#[derive(Serialize, Deserialize)]
struct AttachmentThreadsCursor {
attachment_type: String,
identity_key: String,
archived: Option<bool>,
thread_id: ThreadId,
}
fn validate_attachment_identity(attachment_type: &str, identity_key: &str) -> anyhow::Result<()> {
if attachment_type.trim().is_empty() {
anyhow::bail!("invalid thread attachment request: attachment type must not be empty");
}
if attachment_type.len() > MAX_THREAD_ATTACHMENT_TYPE_BYTES {
anyhow::bail!(
"invalid thread attachment request: attachment type exceeds {MAX_THREAD_ATTACHMENT_TYPE_BYTES} bytes"
);
}
if identity_key.trim().is_empty() {
anyhow::bail!(
"invalid thread attachment request: attachment identity key must not be empty"
);
}
if identity_key.len() > MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES {
anyhow::bail!(
"invalid thread attachment request: attachment identity key exceeds {MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES} bytes"
);
}
Ok(())
}
fn parse_attachment_cursor(cursor: &str) -> anyhow::Result<(String, i64, String)> {
let mut segments = cursor.split('|');
let (Some(thread_id), Some(created_at), Some(attachment_id), None) = (
segments.next(),
segments.next(),
segments.next(),
segments.next(),
) else {
anyhow::bail!("invalid thread attachment request: invalid pagination cursor");
};
if ThreadId::from_string(thread_id).is_err() || Uuid::parse_str(attachment_id).is_err() {
anyhow::bail!("invalid thread attachment request: invalid pagination cursor");
}
let created_at = created_at
.parse::<i64>()
.context("invalid thread attachment request: invalid pagination cursor")?;
Ok((thread_id.to_string(), created_at, attachment_id.to_string()))
}
fn attachment_from_row(row: &SqliteRow) -> anyhow::Result<ThreadAttachment> {
let thread_id: String = row.try_get("thread_id")?;
let payload: String = row.try_get("payload")?;
Ok(ThreadAttachment {
id: row.try_get("id")?,
thread_id: ThreadId::from_string(&thread_id)
.context("invalid persisted thread attachment owner")?,
attachment_type: row.try_get("attachment_type")?,
identity_key: row.try_get("identity_key")?,
payload: serde_json::from_str(&payload)
.context("invalid persisted thread attachment payload")?,
created_at: row.try_get("created_at")?,
})
}
#[cfg(test)]
#[path = "thread_attachments_tests.rs"]
mod tests;

View File

@@ -0,0 +1,588 @@
//! Coverage for attachment identity, capacity, pagination, and durable lifecycle behavior.
use super::StateRuntime;
use crate::AddThreadAttachmentOutcome;
use crate::MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES;
use crate::MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES;
use crate::MAX_THREAD_ATTACHMENT_TYPE_BYTES;
use crate::MAX_THREAD_ATTACHMENTS_PER_THREAD;
use crate::RemoveThreadAttachmentOutcome;
use crate::ThreadAttachmentArchiveFilter;
use crate::ThreadAttachmentOwner;
use crate::ThreadAttachmentOwnerPage;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
use anyhow::Result;
use chrono::Utc;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::path::PathBuf;
use std::sync::Arc;
async fn runtime_with_threads(count: usize) -> Result<(Arc<StateRuntime>, PathBuf, Vec<ThreadId>)> {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let mut thread_ids = Vec::with_capacity(count);
for _ in 0..count {
let thread_id = ThreadId::new();
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await?;
thread_ids.push(thread_id);
}
Ok((runtime, codex_home, thread_ids))
}
#[tokio::test]
async fn copying_attachments_is_atomic_and_independent() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 2).await?;
let source = thread_ids[0];
let destination = thread_ids[1];
for key in ["first", "second"] {
runtime
.add_thread_attachment(source, "document", key, &json!({"path": key}))
.await?;
}
sqlx::query(
"CREATE TRIGGER fail_attachment_copy BEFORE INSERT ON thread_attachments WHEN NEW.identity_key = 'second' BEGIN SELECT RAISE(FAIL, 'copy failure'); END",
)
.execute(runtime.pool.as_ref())
.await?;
let error = runtime
.copy_thread_attachments(source, destination)
.await
.expect_err("a failed insert must roll back the entire copy");
assert!(error.to_string().contains("copy failure"));
assert!(
runtime
.list_thread_attachments(destination, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments
.is_empty()
);
sqlx::query("DROP TRIGGER fail_attachment_copy")
.execute(runtime.pool.as_ref())
.await?;
runtime.copy_thread_attachments(source, destination).await?;
let originals = runtime
.list_thread_attachments(source, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments;
let copied = runtime
.list_thread_attachments(destination, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments;
assert_eq!(copied.len(), originals.len());
for (original, copy) in originals.iter().zip(&copied) {
assert_ne!(copy.id, original.id);
assert_eq!(
copy,
&crate::ThreadAttachment {
id: copy.id.clone(),
thread_id: destination,
created_at: copy.created_at,
..original.clone()
}
);
}
runtime
.remove_thread_attachment(source, "document", "first")
.await?;
runtime.delete_thread(source).await?;
assert_eq!(
runtime
.list_thread_attachments(destination, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments,
copied
);
Ok(())
}
#[tokio::test]
async fn attachment_attachments_are_idempotent_and_scoped_to_their_thread() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 2).await?;
let first = runtime
.add_thread_attachment(
thread_ids[0],
"pull_request",
"openai/codex#123",
&json!({ "url": "https://github.com/openai/codex/pull/123" }),
)
.await?;
let AddThreadAttachmentOutcome::Created(first) = first else {
anyhow::bail!("first attachment should create an attachment");
};
assert_eq!(first.thread_id, thread_ids[0]);
let repeated = runtime
.add_thread_attachment(
thread_ids[0],
"pull_request",
"openai/codex#123",
&json!({ "url": "https://github.com/openai/codex/pull/456" }),
)
.await?;
assert_eq!(
repeated,
AddThreadAttachmentOutcome::Existing(first.clone())
);
let other = runtime
.add_thread_attachment(
thread_ids[1],
"pull_request",
"openai/codex#123",
&json!({ "url": "https://github.com/openai/codex/pull/123" }),
)
.await?;
let AddThreadAttachmentOutcome::Created(other) = other else {
anyhow::bail!("the same identity on another thread should create its own attachment");
};
assert_ne!(first.id, other.id);
assert_eq!(
runtime
.list_thread_attachments(thread_ids[0], /*cursor*/ None, /*limit*/ 10)
.await?
.attachments,
vec![first]
);
Ok(())
}
#[tokio::test]
async fn attachment_removals_return_not_found_or_the_removed_record() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 1).await?;
let thread_id = thread_ids[0];
let removed_before_attach = runtime
.remove_thread_attachment(thread_id, "pull_request", "openai/codex#123")
.await?;
assert_eq!(
removed_before_attach,
RemoveThreadAttachmentOutcome::NotFound
);
let explicit = runtime
.add_thread_attachment(
thread_id,
"pull_request",
"openai/codex#123",
&json!({ "url": "https://github.com/openai/codex/pull/123" }),
)
.await?;
let AddThreadAttachmentOutcome::Created(explicit) = explicit else {
anyhow::bail!("attachment should create an attachment");
};
assert_eq!(
runtime
.remove_thread_attachment(thread_id, "pull_request", "openai/codex#123")
.await?,
RemoveThreadAttachmentOutcome::Removed(explicit)
);
assert!(
runtime
.list_thread_attachments(thread_id, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn attachment_listing_scopes_pagination_to_one_thread() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 2).await?;
let mut expected = Vec::new();
for (thread_id, identity_key) in [
(thread_ids[0], "first"),
(thread_ids[0], "second"),
(thread_ids[0], "third"),
(thread_ids[1], "excluded"),
] {
let created = runtime
.add_thread_attachment(
thread_id,
"pull_request",
identity_key,
&json!({ "identity": identity_key }),
)
.await?;
if thread_id == thread_ids[0] {
let AddThreadAttachmentOutcome::Created(attachment) = created else {
anyhow::bail!("new identities should create attachments");
};
expected.push(attachment);
}
}
let first_page = runtime
.list_thread_attachments(thread_ids[0], /*cursor*/ None, /*limit*/ 2)
.await?;
assert_eq!(first_page.attachments, expected[..2]);
let other_thread_error = runtime
.list_thread_attachments(
thread_ids[1],
first_page.next_cursor.as_deref(),
/*limit*/ 2,
)
.await
.expect_err("a cursor from another thread must be rejected");
assert!(
other_thread_error
.to_string()
.contains("invalid pagination cursor")
);
let second_page = runtime
.list_thread_attachments(
thread_ids[0],
first_page.next_cursor.as_deref(),
/*limit*/ 2,
)
.await?;
assert_eq!(second_page.attachments, expected[2..]);
assert_eq!(second_page.next_cursor, None);
Ok(())
}
#[tokio::test]
async fn active_attachment_limit_is_freed_by_removal() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 1).await?;
let thread_id = thread_ids[0];
for index in 0..MAX_THREAD_ATTACHMENTS_PER_THREAD {
runtime
.add_thread_attachment(
thread_id,
"pull_request",
&format!("attachment-{index}"),
&json!({ "index": index }),
)
.await?;
}
let existing = runtime
.add_thread_attachment(
thread_id,
"pull_request",
"attachment-0",
&json!({ "index": "different" }),
)
.await?;
assert!(matches!(existing, AddThreadAttachmentOutcome::Existing(_)));
let attachment_limit = runtime
.add_thread_attachment(thread_id, "pull_request", "one-too-many", &json!({}))
.await
.expect_err("a new attachment must not exceed the per-thread limit");
assert!(
attachment_limit.to_string().contains(
"invalid thread attachment request: thread attachment identity count exceeds"
)
);
let removed = runtime
.remove_thread_attachment(thread_id, "pull_request", "attachment-0")
.await?;
assert!(matches!(removed, RemoveThreadAttachmentOutcome::Removed(_)));
assert_eq!(
runtime
.remove_thread_attachment(thread_id, "pull_request", "attachment-0")
.await?,
RemoveThreadAttachmentOutcome::NotFound
);
let replacement = runtime
.add_thread_attachment(thread_id, "pull_request", "one-too-many", &json!({}))
.await?;
assert!(matches!(
replacement,
AddThreadAttachmentOutcome::Created(_)
));
Ok(())
}
#[tokio::test]
async fn attachments_survive_restart_and_archive_but_cascade_on_thread_deletion() -> Result<()> {
let (runtime, codex_home, thread_ids) = runtime_with_threads(/*count*/ 1).await?;
let thread_id = thread_ids[0];
let AddThreadAttachmentOutcome::Created(attachment) = runtime
.add_thread_attachment(
thread_id,
"pull_request",
"openai/codex#123",
&json!({ "url": "https://github.com/openai/codex/pull/123" }),
)
.await?
else {
anyhow::bail!("first attachment should create an attachment");
};
let reopened = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
assert_eq!(
reopened
.list_thread_attachments(thread_id, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments,
vec![attachment.clone()]
);
let rollout_path = codex_home.join("archived.jsonl");
reopened
.mark_archived(thread_id, &rollout_path, Utc::now())
.await?;
reopened.mark_unarchived(thread_id, &rollout_path).await?;
assert_eq!(
reopened
.list_thread_attachments(thread_id, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments,
vec![attachment]
);
assert_eq!(reopened.delete_thread(thread_id).await?, 1);
assert!(
reopened
.list_thread_attachments(thread_id, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn attachment_requests_reject_invalid_identity_payload_and_cursor() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 1).await?;
let thread_id = thread_ids[0];
for (attachment_type, identity_key, expected) in [
(" ".to_string(), "pr".to_string(), "type must not be empty"),
(
"x".repeat(MAX_THREAD_ATTACHMENT_TYPE_BYTES + 1),
"pr".to_string(),
"type exceeds",
),
(
"pull_request".to_string(),
" ".to_string(),
"key must not be empty",
),
(
"pull_request".to_string(),
"x".repeat(MAX_THREAD_ATTACHMENT_IDENTITY_KEY_BYTES + 1),
"key exceeds",
),
] {
let error = runtime
.add_thread_attachment(thread_id, &attachment_type, &identity_key, &json!({}))
.await
.expect_err("invalid attachment identities must be rejected");
assert!(error.to_string().contains(expected));
}
let too_large = runtime
.add_thread_attachment(
thread_id,
"pull_request",
"pr",
&json!("x".repeat(MAX_THREAD_ATTACHMENT_PAYLOAD_BYTES)),
)
.await
.expect_err("oversized attachment payload must be rejected");
assert!(too_large.to_string().contains("payload exceeds"));
let invalid_cursor = runtime
.list_thread_attachments(thread_id, Some("not-a-cursor"), /*limit*/ 10)
.await
.expect_err("malformed cursor must be rejected");
assert!(
invalid_cursor
.to_string()
.contains("invalid pagination cursor")
);
let missing = ThreadId::new();
let missing_error = runtime
.add_thread_attachment(missing, "pull_request", "pr", &json!({}))
.await
.expect_err("missing owners must be rejected");
assert!(missing_error.to_string().contains("thread not found"));
Ok(())
}
#[tokio::test]
async fn concurrent_attachment_attachments_preserve_one_deterministic_identity() -> Result<()> {
let (runtime, _codex_home, thread_ids) = runtime_with_threads(/*count*/ 1).await?;
let thread_id = thread_ids[0];
let mut joins = Vec::new();
for _ in 0..8 {
let runtime = Arc::clone(&runtime);
joins.push(tokio::spawn(async move {
runtime
.add_thread_attachment(
thread_id,
"pull_request",
"openai/codex#123",
&json!({ "url": "https://github.com/openai/codex/pull/123" }),
)
.await
}));
}
let mut created = 0;
for join in joins {
match join.await?? {
AddThreadAttachmentOutcome::Created(_) => created += 1,
AddThreadAttachmentOutcome::Existing(_) => {}
}
}
assert_eq!(created, 1);
assert_eq!(
runtime
.list_thread_attachments(thread_id, /*cursor*/ None, /*limit*/ 10)
.await?
.attachments
.len(),
1
);
Ok(())
}
#[tokio::test]
async fn attachment_reverse_lookup_filters_pages_and_tracks_membership() -> Result<()> {
let (runtime, codex_home, mut thread_ids) = runtime_with_threads(/*count*/ 3).await?;
thread_ids.sort_by_key(ThreadId::to_string);
// Reference-backed forks may have attachments before their own first user message.
sqlx::query("UPDATE threads SET preview = '', first_user_message = ''")
.execute(runtime.pool.as_ref())
.await?;
for thread_id in &thread_ids[..2] {
runtime
.add_thread_attachment(*thread_id, "worktree", "repo|branch", &json!({}))
.await?;
}
runtime
.add_thread_attachment(thread_ids[2], "pull_request", "repo|branch", &json!({}))
.await?;
runtime
.add_thread_attachment(thread_ids[2], "worktree", "other", &json!({}))
.await?;
runtime
.mark_archived(
thread_ids[0],
&codex_home.join("archived.jsonl"),
Utc::now(),
)
.await?;
let archived_thread = ThreadAttachmentOwner {
thread_id: thread_ids[0],
archived: true,
};
let active_thread = ThreadAttachmentOwner {
thread_id: thread_ids[1],
archived: false,
};
let first_page = runtime
.list_thread_attachment_threads(
"worktree",
"repo|branch",
ThreadAttachmentArchiveFilter::All,
/*cursor*/ None,
/*limit*/ 1,
)
.await?;
assert_eq!(first_page.threads, vec![archived_thread.clone()]);
let cursor = first_page
.next_cursor
.expect("second owner requires continuation");
assert_eq!(
runtime
.list_thread_attachment_threads(
"worktree",
"repo|branch",
ThreadAttachmentArchiveFilter::All,
Some(&cursor),
/*limit*/ 1
)
.await?,
ThreadAttachmentOwnerPage {
threads: vec![active_thread.clone()],
next_cursor: None
}
);
for (attachment_type, identity_key, archive_filter) in [
(
"pull_request",
"repo|branch",
ThreadAttachmentArchiveFilter::All,
),
("worktree", "other", ThreadAttachmentArchiveFilter::All),
(
"worktree",
"repo|branch",
ThreadAttachmentArchiveFilter::NonArchived,
),
] {
let error = runtime
.list_thread_attachment_threads(
attachment_type,
identity_key,
archive_filter,
Some(&cursor),
/*limit*/ 1,
)
.await
.expect_err("cursor is bound to the complete lookup");
assert!(error.to_string().contains("invalid pagination cursor"));
}
for (archive_filter, expected) in [
(ThreadAttachmentArchiveFilter::Archived, archived_thread),
(ThreadAttachmentArchiveFilter::NonArchived, active_thread),
] {
assert_eq!(
runtime
.list_thread_attachment_threads(
"worktree",
"repo|branch",
archive_filter,
/*cursor*/ None,
/*limit*/ 1
)
.await?,
ThreadAttachmentOwnerPage {
threads: vec![expected],
next_cursor: None
}
);
}
runtime
.remove_thread_attachment(thread_ids[0], "worktree", "repo|branch")
.await?;
runtime.delete_thread(thread_ids[1]).await?;
assert_eq!(
runtime
.list_thread_attachment_threads(
"worktree",
"repo|branch",
ThreadAttachmentArchiveFilter::All,
/*cursor*/ None,
/*limit*/ 10
)
.await?,
ThreadAttachmentOwnerPage {
threads: Vec::new(),
next_cursor: None
}
);
Ok(())
}

View File

@@ -0,0 +1,50 @@
//! Batched metadata reads for best-effort thread enrichment. Missing or invalid rows are skipped
//! independently so one unreadable thread does not hide metadata for the rest of a page.
use std::collections::HashMap;
use codex_protocol::ThreadId;
use sqlx::QueryBuilder;
use sqlx::Sqlite;
use super::StateRuntime;
use super::threads::push_thread_select_columns;
use crate::ThreadMetadata;
use crate::model::ThreadRow;
const THREAD_METADATA_BATCH_SIZE: usize = 999;
impl StateRuntime {
/// Fetch metadata for multiple threads, omitting missing or invalid records.
pub async fn get_threads(
&self,
thread_ids: &[ThreadId],
) -> anyhow::Result<HashMap<ThreadId, ThreadMetadata>> {
let mut threads = HashMap::with_capacity(thread_ids.len());
// Keep each query within SQLite's bind limit, including for large search result sets.
for thread_ids in thread_ids.chunks(THREAD_METADATA_BATCH_SIZE) {
let mut builder = QueryBuilder::<Sqlite>::new("");
push_thread_select_columns(&mut builder);
builder.push(" FROM threads WHERE threads.id IN (");
let mut separated = builder.separated(", ");
for thread_id in thread_ids {
separated.push_bind(thread_id.to_string());
}
separated.push_unseparated(")");
let rows = builder.build().fetch_all(self.pool.as_ref()).await?;
for row in rows {
if let Ok(metadata) =
ThreadRow::try_from_row(&row).and_then(ThreadMetadata::try_from)
{
threads.insert(metadata.id, metadata);
}
}
}
Ok(threads)
}
}
#[cfg(test)]
#[path = "thread_metadata_tests.rs"]
mod tests;

View File

@@ -0,0 +1,48 @@
//! Regression coverage for batched metadata reads and independent row decoding failures.
use std::collections::HashMap;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use super::StateRuntime;
use crate::SqliteConfig;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
#[tokio::test]
async fn get_threads_preserves_valid_metadata_across_batches() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let mut ids = (0..1_001).map(|_| ThreadId::new()).collect::<Vec<_>>();
let mut expected = HashMap::new();
for id in [ids[0], ids[1_000]] {
let mut metadata = test_thread_metadata(&home, id, home.clone());
metadata.title = format!("Title for {id}");
metadata.name = Some(format!("Name for {id}"));
runtime.upsert_thread(&metadata).await?;
expected.insert(id, runtime.get_thread(id).await?.expect("persisted thread"));
}
// An unreadable record must not discard the other names in the same page.
let invalid = test_thread_metadata(&home, ids[1], home.clone());
runtime.upsert_thread(&invalid).await?;
sqlx::query("UPDATE threads SET created_at_ms = ? WHERE id = ?")
.bind(i64::MAX)
.bind(invalid.id.to_string())
.execute(runtime.pool.as_ref())
.await?;
assert!(runtime.get_thread(invalid.id).await.is_err());
ids.push(ids[0]);
assert_eq!(runtime.get_threads(&ids).await?, expected);
assert_eq!(runtime.get_threads(&[]).await?, HashMap::new());
runtime.close().await;
std::fs::remove_dir_all(home)?;
Ok(())
}

View File

@@ -0,0 +1,146 @@
//! One durable unread position per local thread, independent of rebuildable metadata.
//! Reads do not materialize state. Live terminal events are delivered serially per thread;
//! keep their last key across acknowledgements and reverts to suppress redelivery.
use std::collections::HashMap;
use codex_protocol::ThreadId;
use sqlx::QueryBuilder;
use sqlx::Row;
use sqlx::Sqlite;
use sqlx::SqliteConnection;
use uuid::Uuid;
use super::StateRuntime;
use crate::sqlite::SqlitePoolWriteExt;
use crate::sqlite::SqliteWriteQueryExt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ThreadReadState {
/// None is read; Some("") marks the whole thread unread, even if it has no turns.
pub first_unread_turn: Option<String>,
pub revision: String,
}
pub enum ReadStateOperation {
Read,
Unread,
}
#[derive(Debug, PartialEq, Eq)]
pub enum ReadStateUpdate {
Applied(ThreadReadState),
Conflict(ThreadReadState),
Unavailable,
}
impl StateRuntime {
/// Read just the requested page. Only durable metadata rows are eligible.
pub async fn thread_read_states(
&self,
ids: &[ThreadId],
) -> anyhow::Result<HashMap<ThreadId, ThreadReadState>> {
let mut conn = self.pool.acquire().await?;
read_states(&mut conn, ids).await
}
/// Publish a newly delivered terminal event only once, never on history replay.
/// Every newer result guards against an acknowledgement based on an older snapshot,
/// even if the first unread position stays the same.
pub async fn publish_thread_attention(
&self,
id: ThreadId,
turn_id: &str,
) -> anyhow::Result<bool> {
let changed = sqlx::query(
"INSERT INTO thread_read_receipts(thread_id,first_unread_turn,revision,last_published_turn)
SELECT id, ?, ?, ? FROM threads WHERE id=?
ON CONFLICT(thread_id) DO UPDATE SET
first_unread_turn=COALESCE(thread_read_receipts.first_unread_turn,excluded.first_unread_turn),
revision=excluded.revision,
last_published_turn=excluded.last_published_turn
WHERE thread_read_receipts.last_published_turn IS NOT excluded.last_published_turn",
)
.bind(turn_id)
.bind(Uuid::new_v4().to_string())
.bind(turn_id)
.bind(id.to_string())
.execute_with_busy_retry(self.pool.as_ref())
.await?
.rows_affected() != 0;
Ok(changed)
}
/// Both read and unread edits compare the snapshot the client actually saw. Never retry a
/// stale edit automatically: its author may not have seen a newer result or another mark.
pub async fn update_thread_read_state(
&self,
id: ThreadId,
expected_revision: &str,
operation: ReadStateOperation,
) -> anyhow::Result<ReadStateUpdate> {
let mut tx = self.pool.begin_immediate().await?;
let Some(before) = read_states(&mut tx, &[id]).await?.remove(&id) else {
return Ok(ReadStateUpdate::Unavailable);
};
if before.revision != expected_revision {
return Ok(ReadStateUpdate::Conflict(before));
}
let first_unread = match operation {
ReadStateOperation::Read => None,
ReadStateOperation::Unread => Some(""),
};
let revision = Uuid::new_v4().to_string();
sqlx::query(
"INSERT INTO thread_read_receipts(thread_id,first_unread_turn,revision)
VALUES(?,?,?) ON CONFLICT(thread_id) DO UPDATE
SET first_unread_turn=excluded.first_unread_turn, revision=excluded.revision",
)
.bind(id.to_string())
.bind(first_unread)
.bind(&revision)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(ReadStateUpdate::Applied(ThreadReadState {
first_unread_turn: first_unread.map(str::to_owned),
revision,
}))
}
}
async fn read_states(
conn: &mut SqliteConnection,
ids: &[ThreadId],
) -> anyhow::Result<HashMap<ThreadId, ThreadReadState>> {
let mut result = HashMap::new();
for ids in ids.chunks(998) {
let mut query = QueryBuilder::<Sqlite>::new(
"SELECT t.id, r.first_unread_turn, r.revision FROM threads t
LEFT JOIN thread_read_receipts r ON r.thread_id=t.id WHERE t.id IN (",
);
let mut separated = query.separated(", ");
for id in ids {
separated.push_bind(id.to_string());
}
separated.push_unseparated(")");
for row in query.build().fetch_all(&mut *conn).await? {
let id: String = row.try_get("id")?;
let revision: Option<String> = row.try_get("revision")?;
result.insert(
ThreadId::from_string(&id)?,
ThreadReadState {
first_unread_turn: row.try_get("first_unread_turn")?,
// No baseline write. Bind the initial revision to the thread so it cannot
// accidentally be used to edit another thread with no receipt yet.
revision: revision.unwrap_or_else(|| format!("initial:{id}")),
},
);
}
}
Ok(result)
}
#[cfg(test)]
#[path = "thread_read_state_tests.rs"]
mod tests;

View File

@@ -0,0 +1,167 @@
//! Live completion, cross-window edits and rebuildable-metadata isolation.
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use super::*;
use crate::SqliteConfig;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
#[tokio::test]
async fn a_stale_read_cannot_erase_a_later_completion_or_another_mark() -> anyhow::Result<()> {
let home = unique_temp_dir();
let runtime = StateRuntime::init(
SqliteConfig::new_for_testing(home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let id = ThreadId::new();
let other = ThreadId::new();
runtime
.upsert_thread(&test_thread_metadata(&home, id, home.clone()))
.await?;
runtime
.upsert_thread(&test_thread_metadata(&home, other, home.clone()))
.await?;
let baseline = runtime.thread_read_states(&[id]).await?[&id].clone();
assert_eq!(baseline.first_unread_turn, None);
assert_eq!(
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM thread_read_receipts")
.fetch_one(runtime.pool.as_ref())
.await?,
0
);
assert!(matches!(
runtime
.update_thread_read_state(other, &baseline.revision, ReadStateOperation::Unread)
.await?,
ReadStateUpdate::Conflict(_)
));
// A mark is meaningful even without any completed turn.
let ReadStateUpdate::Applied(marked) = runtime
.update_thread_read_state(id, &baseline.revision, ReadStateOperation::Unread)
.await?
else {
panic!("could not mark an empty thread unread")
};
assert_eq!(marked.first_unread_turn, Some(String::new()));
assert_eq!(
runtime
.update_thread_read_state(id, &baseline.revision, ReadStateOperation::Read)
.await?,
ReadStateUpdate::Conflict(marked.clone())
);
// Even another mark of an already-unread thread guards against an older explicit read.
let ReadStateUpdate::Applied(marked_again) = runtime
.update_thread_read_state(id, &marked.revision, ReadStateOperation::Unread)
.await?
else {
panic!("could not mark again")
};
assert_eq!(
runtime
.update_thread_read_state(id, &marked.revision, ReadStateOperation::Read)
.await?,
ReadStateUpdate::Conflict(marked_again.clone())
);
let ReadStateUpdate::Applied(read) = runtime
.update_thread_read_state(id, &marked_again.revision, ReadStateOperation::Read)
.await?
else {
panic!("could not read at current revision")
};
assert_eq!(read.first_unread_turn, None);
assert!(runtime.publish_thread_attention(id, "turn-1").await?);
let first = runtime.thread_read_states(&[id]).await?[&id].clone();
assert_eq!(first.first_unread_turn.as_deref(), Some("turn-1"));
assert!(!runtime.publish_thread_attention(id, "turn-1").await?);
assert_eq!(runtime.thread_read_states(&[id]).await?[&id], first);
assert!(runtime.publish_thread_attention(id, "turn-2").await?);
let second = runtime.thread_read_states(&[id]).await?[&id].clone();
assert_eq!(second.first_unread_turn.as_deref(), Some("turn-1"));
assert_ne!(second.revision, first.revision);
assert_eq!(
runtime
.update_thread_read_state(id, &first.revision, ReadStateOperation::Read)
.await?,
ReadStateUpdate::Conflict(second.clone())
);
assert_eq!(
runtime
.update_thread_read_state(id, &first.revision, ReadStateOperation::Unread)
.await?,
ReadStateUpdate::Conflict(second.clone())
);
let ReadStateUpdate::Applied(read) = runtime
.update_thread_read_state(id, &second.revision, ReadStateOperation::Read)
.await?
else {
panic!("could not acknowledge both visible results")
};
assert_eq!(read.first_unread_turn, None);
assert!(!runtime.publish_thread_attention(id, "turn-2").await?);
assert_eq!(runtime.thread_read_states(&[id]).await?[&id], read);
runtime.close().await;
std::fs::remove_dir_all(home)?;
Ok(())
}
#[tokio::test]
async fn position_and_dedupe_survive_metadata_rebuild_restart_and_revert() -> anyhow::Result<()> {
let home = unique_temp_dir();
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let runtime = StateRuntime::init(sqlite.clone(), "test-provider".to_string()).await?;
let id = ThreadId::new();
let metadata = test_thread_metadata(&home, id, home.clone());
runtime.upsert_thread(&metadata).await?;
let original_metadata = runtime.get_thread(id).await?;
assert!(runtime.publish_thread_attention(id, "removed-turn").await?);
let before = runtime.thread_read_states(&[id]).await?[&id].clone();
// After a revert the caller checks whether the position still exists, then clears by revision.
let ReadStateUpdate::Applied(removed) = runtime
.update_thread_read_state(id, &before.revision, ReadStateOperation::Read)
.await?
else {
panic!("could not retire the removed position")
};
assert_eq!(removed.first_unread_turn, None);
assert_eq!(runtime.get_thread(id).await?, original_metadata);
sqlx::query("DELETE FROM threads WHERE id=?")
.bind(id.to_string())
.execute(runtime.pool.as_ref())
.await?;
assert!(runtime.thread_read_states(&[id]).await?.is_empty());
runtime.upsert_thread(&metadata).await?;
runtime.close().await;
let reopened = StateRuntime::init(sqlite, "test-provider".to_string()).await?;
assert_eq!(reopened.thread_read_states(&[id]).await?[&id], removed);
assert!(
!reopened
.publish_thread_attention(id, "removed-turn")
.await?
);
assert_eq!(reopened.thread_read_states(&[id]).await?[&id], removed);
assert!(
reopened
.publish_thread_attention(id, "new-live-turn")
.await?
);
assert_eq!(
reopened.thread_read_states(&[id]).await?[&id]
.first_unread_turn
.as_deref(),
Some("new-live-turn")
);
reopened.delete_thread(id).await?;
assert!(!reopened.publish_thread_attention(id, "late").await?);
assert_eq!(
reopened
.update_thread_read_state(id, &removed.revision, ReadStateOperation::Unread)
.await?,
ReadStateUpdate::Unavailable
);
reopened.close().await;
std::fs::remove_dir_all(home)?;
Ok(())
}

View File

@@ -0,0 +1,285 @@
use super::StateRuntime;
use crate::sqlite::SqlitePoolWriteExt;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::ThreadId;
use sqlx::QueryBuilder;
use sqlx::Sqlite;
use std::collections::HashMap;
const SECTION_POSITION_GAP: i64 = 1_000_000;
impl StateRuntime {
/// Read persisted section ordering for multiple threads in one SQLite query.
pub async fn get_thread_section_ordering(
&self,
thread_ids: &[ThreadId],
) -> anyhow::Result<HashMap<ThreadId, (Option<i64>, Option<DateTime<Utc>>)>> {
if thread_ids.is_empty() {
return Ok(HashMap::new());
}
let mut builder = QueryBuilder::<Sqlite>::new(
"SELECT id, section_position, section_entered_at_ms FROM threads WHERE id IN (",
);
let mut separated = builder.separated(", ");
for thread_id in thread_ids {
separated.push_bind(thread_id.to_string());
}
separated.push_unseparated(")");
let rows = builder
.build_query_as::<(String, Option<i64>, Option<i64>)>()
.fetch_all(self.pool.as_ref())
.await?;
rows.into_iter()
.map(|(thread_id, section_position, section_entered_at_ms)| {
let thread_id = ThreadId::try_from(thread_id)?;
let section_entered_at = section_entered_at_ms
.map(|millis| {
DateTime::<Utc>::from_timestamp_millis(millis).ok_or_else(|| {
anyhow::anyhow!("invalid unix timestamp millis: {millis}")
})
})
.transpose()?;
Ok((thread_id, (section_position, section_entered_at)))
})
.collect()
}
/// Read an independently persisted thread section by its opaque identifier.
pub async fn get_thread_section(
&self,
id: &str,
) -> anyhow::Result<Option<crate::ThreadSection>> {
let row = sqlx::query_as::<_, (String, String, Option<String>)>(
"SELECT id, name, appearance FROM thread_sections WHERE id = ?",
)
.bind(id)
.fetch_optional(self.pool.as_ref())
.await?;
row.map(crate::ThreadSection::from_row).transpose()
}
/// List independently persisted sections in stable, cursor-paginated identifier order.
pub async fn list_thread_sections(
&self,
cursor: Option<&str>,
limit: usize,
) -> anyhow::Result<crate::ThreadSectionsPage> {
let page_size = limit.max(1);
let fetch_limit = i64::try_from(page_size.saturating_add(1))?;
let rows = sqlx::query_as::<_, (String, String, Option<String>)>(
r#"
SELECT id, name, appearance
FROM thread_sections
WHERE (? IS NULL OR id > ?)
ORDER BY id
LIMIT ?
"#,
)
.bind(cursor)
.bind(cursor)
.bind(fetch_limit)
.fetch_all(self.pool.as_ref())
.await?;
let mut sections = rows
.into_iter()
.map(crate::ThreadSection::from_row)
.collect::<anyhow::Result<Vec<_>>>()?;
let next_cursor = if sections.len() > page_size {
sections.pop();
sections.last().map(|section| section.id.clone())
} else {
None
};
Ok(crate::ThreadSectionsPage {
sections,
next_cursor,
})
}
/// Move a thread into or within a section, or clear its section.
///
/// Omitting `before_thread_id` appends the thread to its destination section.
pub async fn move_thread_to_section(
&self,
thread_id: ThreadId,
section: Option<&str>,
before_thread_id: Option<ThreadId>,
) -> anyhow::Result<bool> {
if section.is_none() && before_thread_id.is_some() {
return Err(anyhow::anyhow!(
"before thread cannot be specified without a section"
));
}
let mut tx = self.pool.begin_immediate().await?;
let thread_id = thread_id.to_string();
let current_section = sqlx::query_scalar::<_, Option<String>>(
"SELECT thread_section_id FROM threads WHERE id = ?",
)
.bind(&thread_id)
.fetch_optional(&mut *tx)
.await?;
let Some(current_section) = current_section else {
return Ok(false);
};
let Some(section) = section else {
sqlx::query(
"UPDATE threads SET thread_section_id = NULL, section_position = NULL, section_entered_at_ms = NULL WHERE id = ?",
)
.bind(&thread_id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
return Ok(true);
};
if sqlx::query_scalar::<_, i64>("SELECT 1 FROM thread_sections WHERE id = ?")
.bind(section)
.fetch_optional(&mut *tx)
.await?
.is_none()
{
return Err(anyhow::anyhow!("section {section} does not exist"));
}
let before_thread_id = before_thread_id.map(|id| id.to_string());
if before_thread_id.as_deref() == Some(thread_id.as_str()) {
return Err(anyhow::anyhow!(
"thread {thread_id} cannot be moved before itself"
));
}
if let Some(before_thread_id) = before_thread_id.as_deref() {
let before_section = sqlx::query_scalar::<_, Option<String>>(
"SELECT thread_section_id FROM threads WHERE id = ?",
)
.bind(before_thread_id)
.fetch_optional(&mut *tx)
.await?;
if before_section.flatten().as_deref() != Some(section) {
return Err(anyhow::anyhow!(
"before thread {before_thread_id} is not in section {section}"
));
}
}
let position =
section_move_position(&mut tx, section, &thread_id, before_thread_id.as_deref())
.await?;
if current_section.as_deref() == Some(section) {
sqlx::query("UPDATE threads SET section_position = ? WHERE id = ?")
.bind(position)
.bind(&thread_id)
.execute(&mut *tx)
.await?;
} else {
sqlx::query(
"UPDATE threads SET thread_section_id = ?, section_position = ?, section_entered_at_ms = ? WHERE id = ?",
)
.bind(section)
.bind(position)
.bind(Utc::now().timestamp_millis())
.bind(&thread_id)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(true)
}
}
async fn section_move_position(
tx: &mut sqlx::Transaction<'_, Sqlite>,
section: &str,
thread_id: &str,
before_thread_id: Option<&str>,
) -> anyhow::Result<i64> {
let mut renumbered = false;
loop {
let position = if let Some(before_thread_id) = before_thread_id {
let upper = sqlx::query_scalar::<_, Option<i64>>(
"SELECT section_position FROM threads WHERE id = ? AND thread_section_id = ?",
)
.bind(before_thread_id)
.bind(section)
.fetch_optional(&mut **tx)
.await?
.flatten()
.ok_or_else(|| {
anyhow::anyhow!("before thread {before_thread_id} is not in section {section}")
})?;
let lower = sqlx::query_scalar::<_, Option<i64>>(
"SELECT MAX(section_position) FROM threads WHERE thread_section_id = ? AND section_position < ? AND id <> ?",
)
.bind(section)
.bind(upper)
.bind(thread_id)
.fetch_one(&mut **tx)
.await?;
match lower {
Some(lower) if i128::from(upper) - i128::from(lower) > 1 => Some(i64::try_from(
i128::from(lower) + (i128::from(upper) - i128::from(lower)) / 2,
)?),
Some(_) => None,
None if upper > 1 => Some(upper / 2),
None => None,
}
} else {
let max_position = sqlx::query_scalar::<_, Option<i64>>(
"SELECT MAX(section_position) FROM threads WHERE thread_section_id = ? AND id <> ?",
)
.bind(section)
.bind(thread_id)
.fetch_one(&mut **tx)
.await?;
max_position
.unwrap_or_default()
.checked_add(SECTION_POSITION_GAP)
};
if let Some(position) = position {
return Ok(position);
}
if renumbered {
return Err(anyhow::anyhow!(
"section {section} has no remaining thread positions"
));
}
renumber_section_positions(tx, section, Some(thread_id)).await?;
renumbered = true;
}
}
async fn renumber_section_positions(
tx: &mut sqlx::Transaction<'_, Sqlite>,
section: &str,
excluded_thread_id: Option<&str>,
) -> anyhow::Result<()> {
sqlx::query(
r#"
UPDATE threads
SET section_position = ranked.position
FROM (
SELECT id,
ROW_NUMBER() OVER (ORDER BY section_position ASC, id ASC) * ? AS position
FROM threads
WHERE thread_section_id = ? AND (? IS NULL OR id <> ?)
) AS ranked
WHERE threads.id = ranked.id
"#,
)
.bind(SECTION_POSITION_GAP)
.bind(section)
.bind(excluded_thread_id)
.bind(excluded_thread_id)
.execute(&mut **tx)
.await?;
Ok(())
}
#[cfg(test)]
#[path = "thread_section_order_tests.rs"]
mod tests;

View File

@@ -0,0 +1,628 @@
use super::StateRuntime;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
use anyhow::Result;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
const CUSTOM_THREAD_SECTION_ID: &str = "01984de2-8f74-7c91-a3b2-5c5e937cf317";
const OTHER_THREAD_SECTION_ID: &str = "01984de2-8f74-7c91-a3b2-5c5e937cf319";
#[tokio::test]
async fn thread_section_ordering_batches_persisted_positions_and_entry_times() -> Result<()> {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let first = ThreadId::new();
let second = ThreadId::new();
let unsectioned = ThreadId::new();
let missing = ThreadId::new();
for thread_id in [first, second, unsectioned] {
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await?;
}
runtime
.move_thread_to_section(
first,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await?;
runtime
.move_thread_to_section(
second,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await?;
let first_entered_at = runtime
.get_thread(first)
.await?
.expect("first pinned thread should exist")
.section_entered_at;
let second_entered_at = runtime
.get_thread(second)
.await?
.expect("second pinned thread should exist")
.section_entered_at;
assert_eq!(
runtime
.get_thread_section_ordering(&[first, second, unsectioned, missing, first])
.await?,
HashMap::from([
(first, (Some(1_000_000), first_entered_at)),
(second, (Some(2_000_000), second_entered_at)),
(unsectioned, (None, None)),
])
);
assert_eq!(
runtime.get_thread_section_ordering(&[]).await?,
HashMap::new()
);
Ok(())
}
#[tokio::test]
async fn thread_sections_paginate_and_require_registered_identities() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("state db should initialize");
let before_pinned = crate::ThreadSection {
id: "01984de2-8f74-7c91-a3b2-5c5e937cf317".to_string(),
name: "Before pinned".to_string(),
appearance: None,
};
let pinned = crate::ThreadSection {
id: crate::PINNED_THREAD_SECTION_ID.to_string(),
name: crate::PINNED_THREAD_SECTION_NAME.to_string(),
appearance: None,
};
let after_pinned = crate::ThreadSection {
id: "01984de2-8f74-7c91-a3b2-5c5e937cf319".to_string(),
name: "After pinned".to_string(),
appearance: None,
};
for section in [&before_pinned, &after_pinned] {
sqlx::query("INSERT INTO thread_sections (id, name) VALUES (?, ?)")
.bind(&section.id)
.bind(&section.name)
.execute(runtime.pool.as_ref())
.await
.expect("custom test sections should be explicitly registered");
}
assert_eq!(
runtime
.get_thread_section(&pinned.id)
.await
.expect("built-in section should load"),
Some(pinned.clone())
);
assert_eq!(
runtime
.get_thread_section("01984de2-8f74-7c91-a3b2-5c5e937cf320")
.await
.expect("missing section lookup should succeed"),
None
);
assert_eq!(
runtime
.list_thread_sections(/*cursor*/ None, /*limit*/ 1)
.await
.expect("first section page should load"),
crate::ThreadSectionsPage {
sections: vec![before_pinned.clone()],
next_cursor: Some(before_pinned.id.clone()),
}
);
assert_eq!(
runtime
.list_thread_sections(Some(&before_pinned.id), /*limit*/ 1)
.await
.expect("pinned section page should load"),
crate::ThreadSectionsPage {
sections: vec![pinned.clone()],
next_cursor: Some(pinned.id.clone()),
}
);
assert_eq!(
runtime
.list_thread_sections(Some(&pinned.id), /*limit*/ 1)
.await
.expect("final section page should load"),
crate::ThreadSectionsPage {
sections: vec![after_pinned],
next_cursor: None,
}
);
let thread_id = ThreadId::new();
let mut metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone());
metadata.section = Some(before_pinned.clone());
runtime
.upsert_thread(&metadata)
.await
.expect("registered section should be accepted");
assert_eq!(
runtime
.get_thread(thread_id)
.await
.expect("sectioned thread should load")
.expect("sectioned thread should exist")
.section,
Some(before_pinned.clone())
);
assert!(
runtime
.move_thread_to_section(
thread_id,
/*section*/ Some("01984de2-8f74-7c91-a3b2-5c5e937cf320"),
/*before_thread_id*/ None,
)
.await
.is_err(),
"thread sections must be explicitly registered before assignment"
);
assert_eq!(
runtime
.get_thread(thread_id)
.await
.expect("thread should survive rejected section assignment")
.expect("thread should still exist")
.section,
Some(before_pinned)
);
}
#[tokio::test]
async fn thread_section_moves_round_trip_and_survive_rollout_reconciliation() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("state db should initialize");
let thread_id = ThreadId::new();
let metadata = test_thread_metadata(&codex_home, thread_id, codex_home.clone());
runtime
.upsert_thread(&metadata)
.await
.expect("thread insert should succeed");
assert_eq!(
runtime
.get_thread(thread_id)
.await
.unwrap()
.unwrap()
.section,
None
);
assert!(
runtime
.move_thread_to_section(
thread_id,
/*section*/ Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await
.unwrap()
);
let pinned = runtime.get_thread(thread_id).await.unwrap().unwrap();
assert_eq!(
(pinned.section.as_ref(), pinned.section_position),
(
Some(&crate::ThreadSection {
id: crate::PINNED_THREAD_SECTION_ID.to_string(),
name: crate::PINNED_THREAD_SECTION_NAME.to_string(),
appearance: None,
}),
Some(1_000_000),
)
);
assert!(pinned.section_entered_at.is_some());
assert!(
runtime
.move_thread_to_section(
thread_id,
/*section*/ Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await
.unwrap()
);
assert_eq!(
runtime.get_thread(thread_id).await.unwrap().unwrap(),
pinned
);
runtime
.upsert_thread(&metadata)
.await
.expect("stale rollout metadata should reconcile");
let reconciled = runtime.get_thread(thread_id).await.unwrap().unwrap();
assert_eq!(
(
reconciled.section,
reconciled.section_position,
reconciled.section_entered_at,
),
(
pinned.section,
pinned.section_position,
pinned.section_entered_at
)
);
assert!(
runtime
.move_thread_to_section(
thread_id, /*section*/ None, /*before_thread_id*/ None,
)
.await
.unwrap()
);
let unpinned = runtime.get_thread(thread_id).await.unwrap().unwrap();
assert_eq!(
(
unpinned.section,
unpinned.section_position,
unpinned.section_entered_at,
),
(None, None, None)
);
assert!(
!runtime
.move_thread_to_section(
ThreadId::new(),
/*section*/ Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await
.unwrap()
);
}
#[tokio::test]
async fn concurrent_section_moves_preserve_unique_positions() -> Result<()> {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let [first, second, third, fourth, fifth] = [
"00000000-0000-0000-0000-000000000071",
"00000000-0000-0000-0000-000000000072",
"00000000-0000-0000-0000-000000000073",
"00000000-0000-0000-0000-000000000074",
"00000000-0000-0000-0000-000000000075",
]
.map(|thread_id| ThreadId::from_string(thread_id).expect("valid thread id"));
for thread_id in [first, second, third, fourth, fifth] {
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await?;
}
let updated = tokio::try_join!(
runtime.move_thread_to_section(
first,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
),
runtime.move_thread_to_section(
second,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
),
runtime.move_thread_to_section(
third,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
),
runtime.move_thread_to_section(
fourth,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
),
)?;
assert_eq!(updated, (true, true, true, true));
let mut entered_at = HashMap::new();
for thread_id in [first, second, third, fourth] {
let thread = runtime
.get_thread(thread_id)
.await?
.expect("concurrently sectioned thread should exist");
entered_at.insert(
thread_id,
thread
.section_entered_at
.expect("section entry time should be recorded"),
);
}
let initial_positions = sqlx::query_scalar::<_, i64>(
"SELECT section_position FROM threads WHERE thread_section_id = ? ORDER BY section_position, id",
)
.bind(crate::PINNED_THREAD_SECTION_ID)
.fetch_all(runtime.pool.as_ref())
.await?;
assert_eq!(
initial_positions,
vec![1_000_000, 2_000_000, 3_000_000, 4_000_000]
);
let moved = tokio::try_join!(
runtime.move_thread_to_section(fourth, Some(crate::PINNED_THREAD_SECTION_ID), Some(first)),
runtime.move_thread_to_section(third, Some(crate::PINNED_THREAD_SECTION_ID), Some(first)),
)?;
assert_eq!(moved, (true, true));
let updated_and_moved = tokio::try_join!(
runtime.move_thread_to_section(
fifth,
Some(crate::PINNED_THREAD_SECTION_ID),
/*before_thread_id*/ None,
),
runtime.move_thread_to_section(first, Some(crate::PINNED_THREAD_SECTION_ID), Some(second)),
)?;
assert_eq!(updated_and_moved, (true, true));
let ordered_threads = sqlx::query_as::<_, (String, i64)>(
"SELECT id, section_position FROM threads WHERE thread_section_id = ? ORDER BY section_position, id",
)
.bind(crate::PINNED_THREAD_SECTION_ID)
.fetch_all(runtime.pool.as_ref())
.await?;
assert_eq!(ordered_threads.len(), 5);
assert!(
ordered_threads
.windows(2)
.all(|threads| threads[0].1 < threads[1].1),
"concurrent section mutations must preserve unique ordered positions: {ordered_threads:?}"
);
assert_eq!(
ordered_threads.last().map(|(thread_id, _)| thread_id),
Some(&fifth.to_string())
);
for (thread_id, original_entered_at) in entered_at {
assert_eq!(
runtime
.get_thread(thread_id)
.await?
.expect("moved thread should remain sectioned")
.section_entered_at,
Some(original_entered_at)
);
}
Ok(())
}
#[tokio::test]
async fn section_moves_preserve_entry_order_and_renumber_exhausted_ranks() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("state db should initialize");
for (section_id, section_name) in [
(CUSTOM_THREAD_SECTION_ID, "Custom section"),
(OTHER_THREAD_SECTION_ID, "Other section"),
] {
sqlx::query("INSERT INTO thread_sections (id, name) VALUES (?, ?)")
.bind(section_id)
.bind(section_name)
.execute(runtime.pool.as_ref())
.await
.expect("custom test sections should be explicitly registered");
}
let first = ThreadId::from_string("00000000-0000-0000-0000-000000000051").unwrap();
let second = ThreadId::from_string("00000000-0000-0000-0000-000000000052").unwrap();
let third = ThreadId::from_string("00000000-0000-0000-0000-000000000053").unwrap();
for thread_id in [first, second, third] {
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await
.unwrap();
assert!(
runtime
.move_thread_to_section(
thread_id,
/*section*/ Some(CUSTOM_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await
.unwrap()
);
}
let mut initial = Vec::new();
for thread_id in [first, second, third] {
initial.push(runtime.get_thread(thread_id).await.unwrap().unwrap());
}
assert_eq!(
initial
.iter()
.map(|thread| thread.section_position)
.collect::<Vec<_>>(),
vec![Some(1_000_000), Some(2_000_000), Some(3_000_000)]
);
assert!(
initial
.iter()
.all(|thread| thread.section_entered_at.is_some())
);
let original_entered_at = initial[2].section_entered_at;
runtime
.touch_thread_recency_at(
first,
DateTime::<Utc>::from_timestamp(1_800_000_000, 0).unwrap(),
)
.await
.unwrap();
runtime
.move_thread_to_section(third, Some(CUSTOM_THREAD_SECTION_ID), Some(second))
.await
.unwrap();
let moved = runtime.get_thread(third).await.unwrap().unwrap();
assert_eq!(moved.section_position, Some(1_500_000));
assert_eq!(moved.section_entered_at, original_entered_at);
runtime
.move_thread_to_section(
third,
Some(CUSTOM_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await
.unwrap();
assert_eq!(
runtime
.get_thread(third)
.await
.unwrap()
.unwrap()
.section_position,
Some(3_000_000)
);
for (thread_id, position) in [(first, 1_i64), (second, 2), (third, 3)] {
sqlx::query("UPDATE threads SET section_position = ? WHERE id = ?")
.bind(position)
.bind(thread_id.to_string())
.execute(runtime.pool.as_ref())
.await
.unwrap();
}
runtime
.move_thread_to_section(third, Some(CUSTOM_THREAD_SECTION_ID), Some(second))
.await
.unwrap();
let reordered = sqlx::query_scalar::<_, String>(
"SELECT id FROM threads WHERE thread_section_id = ? ORDER BY section_position, id",
)
.bind(CUSTOM_THREAD_SECTION_ID)
.fetch_all(runtime.pool.as_ref())
.await
.unwrap();
assert_eq!(
reordered,
vec![first.to_string(), third.to_string(), second.to_string()]
);
assert_eq!(
runtime
.get_thread(third)
.await
.unwrap()
.unwrap()
.section_position,
Some(1_500_000)
);
let unknown_section = "01984de2-8f74-7c91-a3b2-5c5e937cf320";
let error = runtime
.move_thread_to_section(third, Some(unknown_section), /*before_thread_id*/ None)
.await
.expect_err("unregistered destination sections should be rejected");
assert_eq!(
error.to_string(),
format!("section {unknown_section} does not exist")
);
runtime
.move_thread_to_section(
second,
/*section*/ Some(OTHER_THREAD_SECTION_ID),
/*before_thread_id*/ None,
)
.await
.unwrap();
sqlx::query("UPDATE threads SET section_entered_at_ms = ? WHERE id = ?")
.bind(1_i64)
.bind(third.to_string())
.execute(runtime.pool.as_ref())
.await
.unwrap();
runtime
.move_thread_to_section(third, Some(OTHER_THREAD_SECTION_ID), Some(second))
.await
.unwrap();
let moved_across_sections = runtime.get_thread(third).await.unwrap().unwrap();
assert_eq!(
moved_across_sections.section,
Some(crate::ThreadSection {
id: OTHER_THREAD_SECTION_ID.to_string(),
name: "Other section".to_string(),
appearance: None,
})
);
assert_eq!(moved_across_sections.section_position, Some(500_000));
assert!(
moved_across_sections
.section_entered_at
.is_some_and(|entered_at| entered_at.timestamp_millis() > 1)
);
let error = runtime
.move_thread_to_section(third, /*section*/ None, Some(second))
.await
.expect_err("clearing a section cannot accept a before-thread anchor");
assert_eq!(
error.to_string(),
"before thread cannot be specified without a section"
);
runtime
.move_thread_to_section(third, /*section*/ None, /*before_thread_id*/ None)
.await
.unwrap();
let cleared = runtime.get_thread(third).await.unwrap().unwrap();
assert_eq!(
(
cleared.section,
cleared.section_position,
cleared.section_entered_at
),
(None, None, None)
);
}

View File

@@ -0,0 +1,95 @@
use super::StateRuntime;
use crate::PINNED_THREAD_SECTION_ID;
use crate::ThreadSection;
use crate::ThreadSectionAppearance;
use crate::sqlite::SqlitePoolWriteExt;
use crate::sqlite::SqliteWriteQueryExt;
use uuid::Uuid;
impl StateRuntime {
/// Create a custom thread section with a stable, server-assigned UUIDv7.
pub async fn create_thread_section(
&self,
name: &str,
appearance: Option<ThreadSectionAppearance>,
) -> anyhow::Result<ThreadSection> {
let section = ThreadSection {
id: Uuid::now_v7().to_string(),
name: name.to_string(),
appearance,
};
sqlx::query("INSERT INTO thread_sections (id, name, appearance) VALUES (?, ?, ?)")
.bind(&section.id)
.bind(&section.name)
.bind(
section
.appearance
.as_ref()
.map(serde_json::to_string)
.transpose()?,
)
.execute_with_busy_retry(self.pool.as_ref())
.await?;
Ok(section)
}
/// Rename a custom thread section without changing its stable identity.
pub async fn rename_thread_section(
&self,
id: &str,
name: &str,
appearance: Option<Option<ThreadSectionAppearance>>,
) -> anyhow::Result<Option<ThreadSection>> {
if id == PINNED_THREAD_SECTION_ID {
anyhow::bail!("built-in pinned thread section cannot be renamed");
}
let replace_appearance = appearance.is_some();
let appearance = appearance
.flatten()
.map(|appearance| serde_json::to_string(&appearance))
.transpose()?;
let section = sqlx::query_as::<_, (String, String, Option<String>)>(
"UPDATE thread_sections SET name = ?, appearance = CASE WHEN ? THEN ? ELSE appearance END WHERE id = ? RETURNING id, name, appearance",
)
.bind(name)
.bind(replace_appearance)
.bind(appearance)
.bind(id)
.fetch_optional_write(self.pool.as_ref())
.await?;
section.map(ThreadSection::from_row).transpose()
}
/// Delete a custom section and return its threads to the unsectioned list.
pub async fn delete_thread_section(&self, id: &str) -> anyhow::Result<bool> {
if id == PINNED_THREAD_SECTION_ID {
anyhow::bail!("built-in pinned thread section cannot be deleted");
}
let mut tx = self.pool.begin_immediate().await?;
sqlx::query(
"UPDATE threads SET section_position = NULL, section_entered_at_ms = NULL WHERE thread_section_id = ?",
)
.bind(id)
.execute(&mut *tx)
.await?;
let deleted = sqlx::query("DELETE FROM thread_sections WHERE id = ?")
.bind(id)
.execute(&mut *tx)
.await?
.rows_affected()
> 0;
tx.commit().await?;
Ok(deleted)
}
}
#[cfg(test)]
#[path = "thread_sections_tests.rs"]
mod tests;

View File

@@ -0,0 +1,127 @@
use super::StateRuntime;
use crate::runtime::test_support::test_thread_metadata;
use crate::runtime::test_support::unique_temp_dir;
use anyhow::Result;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn deleting_custom_section_preserves_threads_and_clears_section_ordering() -> Result<()> {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let deleted_section = runtime
.create_thread_section(
"Research",
Some(crate::ThreadSectionAppearance {
icon: Some("folder".to_string()),
color: Some("purple".to_string()),
}),
)
.await?;
let retained_section = runtime
.create_thread_section("Planning", /*appearance*/ None)
.await?;
let first = ThreadId::new();
let second = ThreadId::new();
let retained = ThreadId::new();
for (thread_id, section_id) in [
(first, &deleted_section.id),
(second, &deleted_section.id),
(retained, &retained_section.id),
] {
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await?;
runtime
.move_thread_to_section(thread_id, Some(section_id), /*before_thread_id*/ None)
.await?;
}
assert!(runtime.delete_thread_section(&deleted_section.id).await?);
assert_eq!(runtime.get_thread_section(&deleted_section.id).await?, None);
for thread_id in [first, second] {
let thread = runtime
.get_thread(thread_id)
.await?
.expect("section deletion must preserve its member threads");
assert_eq!(
(
thread.section,
thread.section_position,
thread.section_entered_at
),
(None, None, None)
);
}
let retained_thread = runtime
.get_thread(retained)
.await?
.expect("unrelated section member should remain");
assert_eq!(retained_thread.section, Some(retained_section));
assert!(retained_thread.section_position.is_some());
assert!(retained_thread.section_entered_at.is_some());
Ok(())
}
#[tokio::test]
async fn concurrent_section_deletion_and_membership_moves_preserve_thread_invariants() -> Result<()>
{
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(
crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await?;
let section = runtime
.create_thread_section("Research", /*appearance*/ None)
.await?;
let thread_id = ThreadId::new();
runtime
.upsert_thread(&test_thread_metadata(
&codex_home,
thread_id,
codex_home.clone(),
))
.await?;
let (deleted, moved) = tokio::join!(
runtime.delete_thread_section(&section.id),
runtime.move_thread_to_section(
thread_id,
Some(&section.id),
/*before_thread_id*/ None
),
);
assert!(deleted?);
if let Err(error) = moved {
assert!(error.to_string().contains("does not exist"));
}
let thread = runtime
.get_thread(thread_id)
.await?
.expect("concurrent section deletion must preserve the thread");
assert_eq!(
(
thread.section,
thread.section_position,
thread.section_entered_at
),
(None, None, None)
);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,613 @@
//! Shared SQLite connection configuration.
//! New databases use DELETE on NFS and WAL elsewhere.
//! Writable pools preserve existing settings unless managed policy requires DELETE on NFS.
//! Startup retries SQLITE_BUSY and reports other errors to callers.
//! Schema version checks and migrations share one transaction and retry contention together.
//! The configured logs directory is created and locked only when opening its database.
#![expect(
clippy::disallowed_methods,
reason = "this is the centralized SQLite connection shim"
)]
use crate::DbTelemetry;
use crate::migrations::repair_legacy_recency_migration_version;
use crate::runtime::recovery::RuntimeDbInitError;
use crate::telemetry;
use crate::telemetry::DbKind;
use codex_file_system::LocalLogsDir;
use codex_utils_absolute_path::AbsolutePathBuf;
use log::LevelFilter;
use sqlx::ConnectOptions;
use sqlx::Error;
use sqlx::SqlitePool;
use sqlx::migrate::Migrator;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::sqlite::SqliteSynchronous;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::OnceCell;
mod busy_retry;
mod connection;
mod nfs;
mod validation;
pub use busy_retry::SqlitePoolWriteExt;
pub(crate) use busy_retry::SqliteWriteQueryExt;
pub(crate) use busy_retry::retry_on_busy;
use connection::JournalModePolicy;
use connection::connect_once;
use validation::SqliteQuickCheckManager;
const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(5);
const LOGS_DB_FILENAME: &str = "logs_2.sqlite";
const GOALS_DB_FILENAME: &str = "goals_1.sqlite";
const MEMORIES_DB_FILENAME: &str = "memories_1.sqlite";
const QUEUE_DB_FILENAME: &str = "queue_1.sqlite";
const STATE_DB_FILENAME: &str = "state_5.sqlite";
const THREAD_HISTORY_DB_FILENAME: &str = "thread_history_1.sqlite";
#[derive(Clone, Copy, Eq, PartialEq)]
enum RecoveryMode {
BackupAndRebuild,
Unavailable,
}
#[derive(Clone, Copy)]
struct RuntimeDbSpec {
label: &'static str,
filename: &'static str,
kind: DbKind,
open_phase: &'static str,
migrate_phase: &'static str,
/// Opt in only after auditing writers for deferred read-to-write upgrades:
/// an intervening reclamation commit can make those fail with SQLITE_BUSY_SNAPSHOT.
background_reclamation: bool,
recovery: RecoveryMode,
}
impl RuntimeDbSpec {
fn path(self, sqlite: &SqliteConfig) -> PathBuf {
let home = if matches!(self.kind, DbKind::Logs) {
sqlite.logs_home()
} else {
sqlite.home()
};
home.join(self.filename)
}
}
const STATE_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "state DB",
filename: STATE_DB_FILENAME,
kind: DbKind::State,
open_phase: "open_state",
migrate_phase: "migrate_state",
background_reclamation: false,
recovery: RecoveryMode::BackupAndRebuild,
};
const LOGS_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "log DB",
filename: LOGS_DB_FILENAME,
kind: DbKind::Logs,
open_phase: "open_logs",
migrate_phase: "migrate_logs",
// Log transactions write before reading, so they already hold the writer lock.
background_reclamation: true,
recovery: RecoveryMode::BackupAndRebuild,
};
const GOALS_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "goals DB",
filename: GOALS_DB_FILENAME,
kind: DbKind::Goals,
open_phase: "open_goals",
migrate_phase: "migrate_goals",
background_reclamation: false,
recovery: RecoveryMode::BackupAndRebuild,
};
const MEMORIES_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "memories DB",
filename: MEMORIES_DB_FILENAME,
kind: DbKind::Memories,
open_phase: "open_memories",
migrate_phase: "migrate_memories",
background_reclamation: false,
recovery: RecoveryMode::BackupAndRebuild,
};
const MEMORIES_V2_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "memories v2 DB",
filename: "memories_v2_1.sqlite",
background_reclamation: false,
..MEMORIES_DB
};
const QUEUE_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "queue DB",
filename: QUEUE_DB_FILENAME,
kind: DbKind::Queue,
open_phase: "open_queue",
migrate_phase: "migrate_queue",
background_reclamation: false,
recovery: RecoveryMode::BackupAndRebuild,
};
const THREAD_HISTORY_DB: RuntimeDbSpec = RuntimeDbSpec {
label: "thread history DB",
filename: THREAD_HISTORY_DB_FILENAME,
kind: DbKind::ThreadHistory,
open_phase: "open_thread_history",
migrate_phase: "migrate_thread_history",
background_reclamation: false,
recovery: RecoveryMode::Unavailable,
};
const RUNTIME_DBS: [RuntimeDbSpec; 7] = [
STATE_DB,
LOGS_DB,
GOALS_DB,
MEMORIES_DB,
MEMORIES_V2_DB,
QUEUE_DB,
THREAD_HISTORY_DB,
];
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeDbPath {
pub label: &'static str,
pub path: PathBuf,
pub(crate) background_reclamation: bool,
}
/// Resolved configuration shared by all Codex SQLite connections.
/// Clones share directory locks, filesystem probes, and quick-check attempts.
#[derive(Clone, Debug)]
pub struct SqliteConfig {
sqlite_home: AbsolutePathBuf,
local_logs_dir: Option<LocalLogsDir>,
is_nfs: Arc<OnceCell<bool>>,
logs_is_nfs: Arc<OnceCell<bool>>,
enforce_delete_on_nfs: bool,
quick_check_manager: SqliteQuickCheckManager,
}
// Directory locks, cached filesystem information, and validation history are operational state,
// not part of configuration equality.
impl PartialEq for SqliteConfig {
fn eq(&self, other: &Self) -> bool {
self.sqlite_home == other.sqlite_home
&& self.enforce_delete_on_nfs == other.enforce_delete_on_nfs
&& self.local_logs_dir.as_ref().map(LocalLogsDir::path)
== other.local_logs_dir.as_ref().map(LocalLogsDir::path)
}
}
impl Eq for SqliteConfig {}
impl SqliteConfig {
#[deprecated(
note = "Use SqliteConfig::from_sqlite_home_with_nfs_enforcement with the managed unsafe_enforce_sqlite_journal_mode requirement, or SqliteConfig::new_for_testing in tests"
)]
pub fn from_sqlite_home(sqlite_home: AbsolutePathBuf) -> Self {
Self::from_sqlite_home_with_nfs_enforcement(
sqlite_home,
/*enforce_delete_on_nfs*/ false,
)
}
/// Construct the configuration with the resolved `unsafe_enforce_sqlite_journal_mode` requirement.
pub fn from_sqlite_home_with_nfs_enforcement(
sqlite_home: AbsolutePathBuf,
enforce_delete_on_nfs: bool,
) -> Self {
Self {
sqlite_home,
local_logs_dir: None,
is_nfs: Arc::new(OnceCell::new()),
logs_is_nfs: Arc::new(OnceCell::new()),
enforce_delete_on_nfs,
quick_check_manager: SqliteQuickCheckManager::new(),
}
}
/// When enforcement is enabled, migrate existing WAL databases on NFS before opening them.
/// Other clients on all hosts must remain stopped during migration.
pub fn enable_delete_mode_on_nfs(mut self, enabled: bool) -> Self {
self.enforce_delete_on_nfs = enabled;
self
}
pub fn new_for_testing(sqlite_home: AbsolutePathBuf) -> Self {
Self::from_sqlite_home_with_nfs_enforcement(
sqlite_home,
/*enforce_delete_on_nfs*/ false,
)
}
pub fn home(&self) -> &Path {
self.sqlite_home.as_path()
}
/// Select the logs directory without accessing it until its database is opened.
pub fn with_local_logs_home(mut self, home: PathBuf) -> Self {
self.local_logs_dir = Some(LocalLogsDir::new(home));
self.logs_is_nfs = Arc::new(OnceCell::new());
self
}
pub(crate) fn logs_home(&self) -> &Path {
self.local_logs_dir
.as_ref()
.map_or(self.home(), LocalLogsDir::path)
}
/// Detects if the sqlite_home directory is under the NFS mount (once per the lifetime)
pub async fn is_nfs(&self) -> anyhow::Result<bool> {
probe_nfs(self.home(), &self.is_nfs).await
}
pub(crate) async fn logs_are_on_nfs(&self) -> anyhow::Result<bool> {
probe_nfs(self.logs_home(), &self.logs_is_nfs).await
}
/// Return the path to the primary state database.
pub fn state_db_path(&self) -> PathBuf {
STATE_DB.path(self)
}
/// Return the path to the logs database.
pub fn logs_db_path(&self) -> PathBuf {
LOGS_DB.path(self)
}
pub(crate) fn legacy_logs_db_path(&self) -> Option<PathBuf> {
let path = self.home().join(LOGS_DB_FILENAME);
(path != self.logs_db_path()).then_some(path)
}
/// Return the path to the goals database.
pub fn goals_db_path(&self) -> PathBuf {
GOALS_DB.path(self)
}
/// Return the path to the memories database.
pub fn memories_db_path(&self) -> PathBuf {
MEMORIES_DB.path(self)
}
pub(crate) fn memories_v2_db_path(&self) -> PathBuf {
MEMORIES_V2_DB.path(self)
}
pub(crate) async fn open_memories_v2_db(&self) -> anyhow::Result<SqlitePool> {
self.open_runtime_db(
MEMORIES_V2_DB,
&crate::migrations::runtime_memories_migrator(),
/*telemetry_override*/ None,
)
.await
}
/// Return the path to the durable user-message queue database.
pub fn queue_db_path(&self) -> PathBuf {
QUEUE_DB.path(self)
}
/// Return the path to the paginated thread-history database.
pub fn thread_history_db_path(&self) -> PathBuf {
THREAD_HISTORY_DB.path(self)
}
/// Return the paths to every database managed by the state runtime.
pub fn runtime_db_paths(&self) -> Vec<RuntimeDbPath> {
RUNTIME_DBS
.iter()
.map(|spec| RuntimeDbPath {
label: spec.label,
path: spec.path(self),
background_reclamation: spec.background_reclamation,
})
.collect()
}
pub(crate) fn reclamation_db_paths(&self) -> Vec<RuntimeDbPath> {
self.runtime_db_paths()
.into_iter()
.filter(|db| db.background_reclamation)
.chain(self.legacy_logs_db_path().map(|path| RuntimeDbPath {
label: "legacy log DB",
path,
background_reclamation: true,
}))
.collect()
}
pub(super) async fn open_state_db(
&self,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
// New state DBs should use incremental auto-vacuum, but retrofitting an
// existing DB requires a full VACUUM. Do not attempt that during process
// startup: it is maintenance work that can contend with foreground writers.
self.open_runtime_db(STATE_DB, migrator, telemetry_override)
.await
}
pub(super) async fn open_logs_db(
&self,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
self.open_runtime_db(LOGS_DB, migrator, telemetry_override)
.await
}
pub(super) async fn open_goals_db(
&self,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
self.open_runtime_db(GOALS_DB, migrator, telemetry_override)
.await
}
pub(super) async fn open_memories_db(
&self,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
self.open_runtime_db(MEMORIES_DB, migrator, telemetry_override)
.await
}
pub(super) async fn open_queue_db(
&self,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
self.open_runtime_db(QUEUE_DB, migrator, telemetry_override)
.await
}
pub(super) async fn open_thread_history_db(
&self,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
self.open_runtime_db(THREAD_HISTORY_DB, migrator, telemetry_override)
.await
}
async fn open_runtime_db(
&self,
spec: RuntimeDbSpec,
migrator: &Migrator,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
let path = spec.path(self);
let started = Instant::now();
let pool_result = self
.open_read_write_pool_with_spec(path.as_path(), Some(spec), telemetry_override)
.await;
telemetry::record_init_result(
telemetry_override,
spec.kind,
spec.open_phase,
started.elapsed(),
&pool_result,
);
let pool = pool_result.map_err(|source| {
RuntimeDbInitError::new(spec.label, "open", path.as_path(), source)
})?;
let started = Instant::now();
let migrate_result = async {
if matches!(spec.kind, DbKind::State) {
repair_legacy_recency_migration_version(&pool, migrator).await?;
}
// SQLx's SQLite migration lock is a no-op. Keep version checks and changes in
// one transaction, retrying from a fresh snapshot after a concurrent migration.
// A current schema needs only a read lock, including when opened on NFS.
retry_on_busy(|| async {
let mut transaction = pool.begin().await?;
if let Err(error) = migrator
.run_direct(/*target*/ None, &mut *transaction, /*skip*/ false)
.await
{
transaction.rollback().await?;
return Err(error.into());
}
transaction.commit().await.map_err(anyhow::Error::from)
})
.await
}
.await;
telemetry::record_init_result(
telemetry_override,
spec.kind,
spec.migrate_phase,
started.elapsed(),
&migrate_result,
);
if let Err(source) = migrate_result {
pool.close().await;
return Err(
RuntimeDbInitError::new(spec.label, "migrate", path.as_path(), source).into(),
);
}
Ok(pool)
}
/// Open a writable Codex SQLite database, creating it if necessary.
/// Keep this configuration alive to retain the cleanup lock for local logs.
pub async fn open_read_write_pool(&self, path: &Path) -> anyhow::Result<SqlitePool> {
self.open_read_write_pool_with_spec(
path, /*recover_spec*/ None, /*telemetry_override*/ None,
)
.await
}
async fn open_read_write_pool_with_spec(
&self,
path: &Path,
recover_spec: Option<RuntimeDbSpec>,
telemetry_override: Option<&dyn DbTelemetry>,
) -> anyhow::Result<SqlitePool> {
self.prepare_logs_directory(path).await?;
let directory = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let is_nfs = if self.local_logs_dir.is_some() && directory == self.logs_home() {
self.logs_are_on_nfs().await?
} else if directory == self.home() {
self.is_nfs().await?
} else {
probe_nfs(directory, &OnceCell::new()).await?
};
// Keep the migration lock through pool initialization so another managed startup
// cannot open the old inode or initialize a database during cutover.
let migration = if self.enforce_delete_on_nfs && is_nfs {
Some(nfs::prepare_database(self, path).await?)
} else {
None
};
let journal_mode_policy = if migration.is_some() {
JournalModePolicy::RequireDelete
} else if is_nfs {
JournalModePolicy::InitializeDelete
} else {
JournalModePolicy::InitializeWal
};
let recovery = recover_spec.map_or(RecoveryMode::Unavailable, |spec| spec.recovery);
let options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
.synchronous(SqliteSynchronous::Normal)
.busy_timeout(DEFAULT_BUSY_TIMEOUT)
.log_statements(LevelFilter::Off);
// Each failed attempt closes its pool before initialization is retried.
let connect = || async {
connect_once(&options, journal_mode_policy)
.await
.map_err(anyhow::Error::from)
};
let pool = retry_on_busy(connect).await?;
let validation_result = self
.quick_check_manager
.quick_check_once(
&pool,
path,
// Limit startup validation to 100 ms.
Duration::from_millis(/*millis*/ 100),
)
.await;
let Ok(result) = validation_result else {
pool.close().await;
return validation_result.map(|_| pool);
};
if result == validation::QuickCheckOutcome::CorruptedNeedsFixed {
tracing::error!(database = %path.display(), "SQLite quick check detected corruption");
telemetry::record_corruption(telemetry_override, recover_spec.map(|spec| spec.kind));
if recovery == RecoveryMode::BackupAndRebuild {
pool.close().await;
let backups = crate::backup_runtime_db_for_fresh_start(path).await?;
for backup in backups {
tracing::warn!(
database = %backup.original_path.display(),
backup = %backup.backup_path.display(),
"Preserved corrupt SQLite database before rebuilding"
);
}
return retry_on_busy(connect).await;
}
}
Ok(pool)
}
/// Open an existing Codex SQLite database without creating or modifying it.
/// Keep this configuration alive to retain the cleanup lock for local logs.
pub async fn open_read_only_pool(
&self,
path: &Path,
busy_timeout: Option<Duration>,
) -> Result<SqlitePool, Error> {
self.prepare_logs_directory(path).await.map_err(Error::Io)?;
let mut options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(false)
.read_only(true)
.log_statements(LevelFilter::Off);
if let Some(busy_timeout) = busy_timeout {
options = options.busy_timeout(busy_timeout);
}
SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
}
/// Open old logs for cleanup without creating, migrating, or rebuilding the database.
/// Skip legacy NFS logs when managed DELETE enforcement is active.
pub(crate) async fn open_legacy_logs_for_cleanup(&self) -> anyhow::Result<Option<SqlitePool>> {
let Some(path) = self.legacy_logs_db_path() else {
return Ok(None);
};
if !tokio::fs::try_exists(&path).await? {
return Ok(None);
}
if self.enforce_delete_on_nfs && self.is_nfs().await? {
return Ok(None);
}
let options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(false)
.busy_timeout(Duration::ZERO)
.log_statements(LevelFilter::Off);
SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.map(Some)
.map_err(anyhow::Error::from)
}
async fn prepare_logs_directory(&self, path: &Path) -> std::io::Result<()> {
// Login, login status, and logout load configuration without opening SQLite.
// Create and lock the logs directory only when opening its database.
// An unavailable log_dir must not prevent those commands from loading configuration.
if let Some(directory) = &self.local_logs_dir
&& path == self.logs_db_path()
{
directory.initialize().await?;
}
Ok(())
}
}
async fn probe_nfs(home: &Path, probe: &OnceCell<bool>) -> anyhow::Result<bool> {
probe
.get_or_try_init(|| async {
let home = home.to_path_buf();
Ok(tokio::task::spawn_blocking(move || codex_file_system::is_nfs(&home)).await??)
})
.await
.copied()
}
#[cfg(test)]
#[path = "sqlite_tests.rs"]
mod tests;

View File

@@ -0,0 +1,191 @@
//! Bounded retries for SQLite operations that can safely restart on external contention.
//! Callers must complete one atomic transaction (or only open a connection) per attempt.
//! Never retry cancellation: a commit whose result was not received may have succeeded.
use std::error::Error as StdError;
use std::future::Future;
use std::time::Duration;
use sqlx::Execute;
use sqlx::Executor;
use sqlx::FromRow;
use sqlx::Sqlite;
use sqlx::SqlitePool;
use sqlx::Transaction;
use sqlx::error::DatabaseError;
use sqlx::query::Query;
use sqlx::query::QueryAs;
use sqlx::sqlite::SqliteArguments;
use sqlx::sqlite::SqliteError;
use sqlx::sqlite::SqliteQueryResult;
use sqlx::sqlite::SqliteRow;
/// SQLite writer admission for pools shared by the state and thread stores.
/// Implementations must acquire the writer slot before any read snapshot and
/// retry only admission, never an already-started transaction or external effects.
pub trait SqlitePoolWriteExt {
fn begin_immediate(
&self,
) -> impl Future<Output = Result<Transaction<'static, Sqlite>, sqlx::Error>> + Send;
}
impl SqlitePoolWriteExt for SqlitePool {
async fn begin_immediate(&self) -> Result<Transaction<'static, Sqlite>, sqlx::Error> {
retry_when(
|| self.begin_with("BEGIN IMMEDIATE"),
|error| is_busy(error),
)
.await
}
}
/// Safe retry boundaries for single prepared SQLite writes, including RETURNING.
/// Implementations decode their row before committing, just as SQLx does in an
/// explicit transaction. Never use this for multiple statements or existing
/// transactions; those must keep using their transaction's connection.
pub(crate) trait SqliteWriteQueryExt<'q>: Execute<'q, Sqlite> + 'q {
type Output: Send;
fn decode_returning_row(row: SqliteRow) -> Result<Self::Output, sqlx::Error>;
/// Retry a standalone autocommit write with exactly the same bound inputs.
fn execute_with_busy_retry<'e>(
mut self,
pool: &'e SqlitePool,
) -> impl Future<Output = Result<SqliteQueryResult, sqlx::Error>> + Send + 'e
where
'q: 'e,
{
async move {
let persistent = Execute::persistent(&self);
let arguments = self
.take_arguments()
.map_err(sqlx::Error::Encode)?
.unwrap_or_default();
let sql = self.sql();
retry_when(
|| {
sqlx::query_with(sql.clone(), arguments.clone())
.persistent(persistent)
.execute(pool)
},
|error| is_busy(error),
)
.await
}
}
/// Reserve the writer slot for a RETURNING write; expose its row only after commit.
fn fetch_one_write<'e>(
self,
pool: &'e SqlitePool,
) -> impl Future<Output = Result<Self::Output, sqlx::Error>> + Send + 'e
where
'q: 'e,
{
async move {
let mut tx = pool.begin_immediate().await?;
let row = (&mut *tx).fetch_one(self).await?;
let output = Self::decode_returning_row(row)?;
tx.commit().await?;
Ok(output)
}
}
/// As with fetch_one_write, but commit a write that returns no row too.
fn fetch_optional_write<'e>(
self,
pool: &'e SqlitePool,
) -> impl Future<Output = Result<Option<Self::Output>, sqlx::Error>> + Send + 'e
where
'q: 'e,
{
async move {
let mut tx = pool.begin_immediate().await?;
let row = (&mut *tx).fetch_optional(self).await?;
let output = row.map(Self::decode_returning_row).transpose()?;
tx.commit().await?;
Ok(output)
}
}
}
impl<'q> SqliteWriteQueryExt<'q> for Query<'q, Sqlite, SqliteArguments> {
type Output = SqliteRow;
fn decode_returning_row(row: SqliteRow) -> Result<Self::Output, sqlx::Error> {
Ok(row)
}
}
impl<'q, O> SqliteWriteQueryExt<'q> for QueryAs<'q, Sqlite, O, SqliteArguments>
where
O: Send + Unpin + for<'r> FromRow<'r, SqliteRow> + 'q,
{
type Output = O;
fn decode_returning_row(row: SqliteRow) -> Result<Self::Output, sqlx::Error> {
O::from_row(&row)
}
}
/// Retries only received SQLite BUSY errors. Each operation must drop or roll back
/// its transaction before returning an error so even BUSY_SNAPSHOT starts fresh.
/// SQLite already waits up to five seconds per lock; allow two more attempts.
pub(crate) async fn retry_on_busy<T, F, Fut>(operation: F) -> anyhow::Result<T>
where
F: FnMut() -> Fut,
Fut: Future<Output = anyhow::Result<T>>,
{
retry_when(operation, |error| error.chain().any(is_busy)).await
}
async fn retry_when<T, E, F, Fut>(
mut operation: F,
is_retryable: impl Fn(&E) -> bool,
) -> Result<T, E>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<T, E>>,
{
let mut delays = [Duration::from_millis(100), Duration::from_millis(200)].into_iter();
loop {
match operation().await {
Ok(value) => return Ok(value),
Err(error) => {
if is_retryable(&error)
&& let Some(delay) = delays.next()
{
tokio::time::sleep(delay).await;
continue;
}
return Err(error);
}
}
}
}
fn is_busy(source: &(dyn StdError + 'static)) -> bool {
let Some(sqlite_error) = source
.downcast_ref::<sqlx::Error>()
.and_then(sqlx::Error::as_database_error)
.and_then(|database_error| database_error.try_downcast_ref::<SqliteError>())
else {
return false;
};
matches!(
sqlite_error
.code()
.and_then(|code| code.parse::<i32>().ok()),
Some(
libsqlite3_sys::SQLITE_BUSY
| libsqlite3_sys::SQLITE_BUSY_RECOVERY
| libsqlite3_sys::SQLITE_BUSY_SNAPSHOT
| libsqlite3_sys::SQLITE_BUSY_TIMEOUT
)
)
}
#[cfg(test)]
#[path = "retry_tests.rs"]
mod tests;

View File

@@ -0,0 +1,122 @@
//! Initializes writable connections while preserving existing database settings.
//! Only empty databases adopt the requested journal mode; DELETE connections use EXTRA sync.
//! Managed DELETE requirements also reject other modes on every connection.
#![expect(
clippy::disallowed_methods,
reason = "centralized SQLite connection initialization"
)]
use sqlx::Error;
use sqlx::SqlitePool;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::sqlite::SqlitePoolOptions;
#[derive(Clone, Copy, Eq, PartialEq)]
pub(super) enum JournalModePolicy {
InitializeWal,
InitializeDelete,
RequireDelete,
}
pub(super) async fn connect_once(
options: &SqliteConnectOptions,
journal_mode_policy: JournalModePolicy,
) -> Result<SqlitePool, Error> {
// SQLx retries after_connect errors, eventually replacing them with PoolTimedOut.
// Return the first initialization error directly while opening this pool.
let (init_error_tx, mut init_error_rx) = tokio::sync::mpsc::channel(/*buffer*/ 1);
let pool_options =
SqlitePoolOptions::new()
.max_connections(5)
.after_connect(move |connection, _metadata| {
let init_error_tx = init_error_tx.clone();
Box::pin(async move {
let result = async {
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&mut *connection)
.await?;
if journal_mode_policy == JournalModePolicy::RequireDelete
&& journal != "delete"
{
return Err(Error::Protocol(format!(
"NFS database requires DELETE journaling, found {journal}"
)));
}
if journal == "delete" {
// If the filesystem honors sync requests, EXTRA syncs the directory
// after SQLite deletes a rollback journal.
sqlx::query("PRAGMA synchronous = EXTRA")
.execute(connection)
.await?;
}
Ok(())
}
.await;
result.map_err(|error| match init_error_tx.try_send(error) {
// The opener owns the original error and cancels connection retries.
Ok(()) => Error::PoolClosed,
// After opening, lazy connections retain SQLx's normal error handling.
Err(error) => error.into_inner(),
})
})
});
let pool = tokio::select! {
biased;
Some(error) = init_error_rx.recv() => Err(error),
result = pool_options.connect_with(options.clone()) => result,
}?;
// Database settings persist on disk.
// Initialize these settings once before callers can use the pool.
// Connections that open later need only settings that apply to each connection.
let initialized: Result<(), Error> = async {
let mut connection = pool.acquire().await?;
// Auto-vacuum alone can write a header to disk.
// If creation stops before the schema exists, startup must initialize the file.
let empty =
sqlx::query_scalar::<_, bool>("SELECT NOT EXISTS (SELECT 1 FROM sqlite_schema)")
.fetch_one(&mut *connection)
.await?;
if empty {
let mode: i64 = sqlx::query_scalar("PRAGMA auto_vacuum")
.fetch_one(&mut *connection)
.await?;
if mode == 0 {
sqlx::query("PRAGMA auto_vacuum = INCREMENTAL")
.execute(&mut *connection)
.await?;
}
let pragma = match journal_mode_policy {
JournalModePolicy::InitializeWal => "PRAGMA journal_mode = WAL",
JournalModePolicy::InitializeDelete | JournalModePolicy::RequireDelete => {
"PRAGMA journal_mode = DELETE"
}
};
sqlx::query(pragma).execute(&mut *connection).await?;
}
// Initialization or another process can change the journal mode after after_connect.
// Match this connection's synchronization setting to the resulting journal mode.
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&mut *connection)
.await?;
if journal == "wal" {
sqlx::query("PRAGMA synchronous = NORMAL")
.execute(&mut *connection)
.await?;
} else if journal == "delete" {
sqlx::query("PRAGMA synchronous = EXTRA")
.execute(&mut *connection)
.await?;
}
// Wait for the connection to return to the pool before startup requests it again.
// An asynchronous drop can otherwise cause the pool to open a second connection.
connection.return_to_pool().await;
Ok(())
}
.await;
if let Err(error) = initialized {
pool.close().await;
return Err(error);
}
Ok(pool)
}

View File

@@ -0,0 +1,66 @@
//! Migrates databases after the caller checks the managed policy and detects NFS.
//! Migration errors must not trigger corruption recovery that would discard a WAL backup.
use super::SqliteConfig;
use crate::NfsDbMigration;
use crate::NfsDbMigrationOutcome;
use anyhow::Context;
use std::fs::TryLockError;
use std::path::Path;
use std::time::Duration;
use tokio::time::Instant;
pub(super) async fn prepare_database(
sqlite: &SqliteConfig,
path: &Path,
) -> anyhow::Result<NfsDbMigration> {
// Replacement syncs the source directory, which must not be an empty relative parent.
let absolute_path = std::path::absolute(path)?;
let path = absolute_path.as_path();
let home = path
.parent()
.context("database path has no parent directory")?;
// Concurrent managed startups can briefly hold this lock even after migration is complete.
let deadline = Instant::now() + super::DEFAULT_BUSY_TIMEOUT;
let mut migration = loop {
match NfsDbMigration::lock(home) {
Ok(migration) => break migration,
Err(error)
if matches!(
error.downcast_ref::<TryLockError>(),
Some(TryLockError::WouldBlock)
) && Instant::now() < deadline =>
{
tokio::time::sleep(Duration::from_millis(/*millis*/ 100)).await;
}
Err(error) => return Err(error),
}
};
// The primary runtime opens state first. Include lazy databases so startup also
// resumes interrupted migrations whose source path has not been reinstalled yet.
// A separate logs directory is checked and locked when its own database opens.
let paths = if path == sqlite.state_db_path() {
sqlite
.runtime_db_paths()
.into_iter()
.map(|db| db.path)
.filter(|path| path.parent() == Some(home))
.collect()
} else {
vec![path.to_path_buf()]
};
for path in paths {
let outcome = migration.migrate(&path, &std::env::temp_dir()).await.map_err(|error| {
// Do not expose a SQLite corruption error to automatic backup-and-rebuild recovery:
// an interrupted cutover must be resumed by the migration implementation itself.
anyhow::anyhow!(
"required NFS database migration failed for {}: {error:#}. Stop Codex instances on all hosts and rerun codex migrate-nfs-db",
path.display()
)
})?;
if let NfsDbMigrationOutcome::Migrated { backup_directory } = outcome {
tracing::info!(database = %path.display(), backup = %backup_directory.display(), "Migrated NFS database to DELETE journaling");
}
}
Ok(migration)
}

View File

@@ -0,0 +1,267 @@
//! Tests safe retries against real SQLite writer contention.
use super::retry_on_busy;
use crate::SqliteConfig;
use crate::SqliteQueueStore;
use crate::migrations::runtime_logs_migrator;
use crate::migrations::runtime_queue_migrator;
use crate::runtime::test_support::unique_temp_dir;
use anyhow::Context;
use codex_protocol::ThreadId;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::sqlite::SqlitePoolOptions;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
#[tokio::test]
#[expect(
clippy::await_holding_invalid_type,
reason = "Only this sequential retry closure owns these connections. The guards keep the real competing SQLite lock alive across attempts; no other task takes either guard."
)]
async fn retries_after_a_competing_writer_releases_its_lock() -> anyhow::Result<()> {
let sqlite_home = unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let pool = sqlite
.open_logs_db(&runtime_logs_migrator(), /*telemetry_override*/ None)
.await?;
let mut competing_writer = pool.acquire().await?;
let mut writer = pool.acquire().await?;
sqlx::query("PRAGMA busy_timeout=0")
.execute(&mut *writer)
.await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *competing_writer)
.await?;
let competing_writer = Mutex::new(competing_writer);
let writer = Mutex::new(writer);
retry_on_busy(|| async {
let mut writer = writer.lock().await;
let result = sqlx::query(
"INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body) \
VALUES (1, 0, 'INFO', 'retry-test', 'saved once')",
)
.execute(&mut **writer)
.await;
// Release the competing transaction only after SQLite actually rejected
// the write. This cannot pass by racing the first attempt's busy wait.
if result.is_err() {
let mut competing_writer = competing_writer.lock().await;
sqlx::query("ROLLBACK")
.execute(&mut **competing_writer)
.await?;
}
result.map_err(anyhow::Error::from)
})
.await?;
let rows = sqlx::query_scalar::<_, String>("SELECT feedback_log_body FROM logs ORDER BY id")
.fetch_all(&pool)
.await?;
assert_eq!(rows, vec!["saved once".to_string()]);
drop(writer);
drop(competing_writer);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn queue_enqueue_survives_received_busy_without_duplicating_the_message() -> anyhow::Result<()>
{
let sqlite_home = unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let pool = sqlite
.open_queue_db(&runtime_queue_migrator(), /*telemetry_override*/ None)
.await?;
let (attempt_finished, mut finished) = mpsc::unbounded_channel();
// No connection is opened or released until enqueue's first attempt.
// SQLite must have returned BUSY before after_release can run: the other
// writer is still holding the lock, and this connection never waits for it.
let writer_pool = SqlitePoolOptions::new()
.max_connections(/*max*/ 1)
.after_release(move |_, _| {
let _ = attempt_finished.send(());
Box::pin(async { Ok(true) })
})
.connect_lazy_with(
(*pool.connect_options())
.clone()
.busy_timeout(Duration::ZERO),
);
let queue = SqliteQueueStore::new(Arc::new(writer_pool));
let observer = SqliteQueueStore::new(Arc::new(pool.clone()));
let thread_id = ThreadId::new();
let mut competing_writer = pool.acquire().await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *competing_writer)
.await?;
let (item, ()) = tokio::try_join!(
queue.enqueue(thread_id, r#"{"text":"save this bound value"}"#),
async {
finished
.recv()
.await
.context("no completed writer attempt")?;
sqlx::query("ROLLBACK")
.execute(&mut *competing_writer)
.await?;
Ok::<(), anyhow::Error>(())
}
)?;
assert_eq!(
(thread_id, r#"{"text":"save this bound value"}"#),
(item.thread_id, item.payload.as_str())
);
assert_eq!(
vec![item],
observer
.list_page(thread_id, /*offset*/ 0, /*limit*/ 10)
.await?
);
drop(competing_writer);
queue.close().await;
pool.close().await;
Ok(())
}
#[tokio::test]
async fn queue_update_survives_received_busy_and_commits_once() -> anyhow::Result<()> {
let sqlite_home = unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let pool = sqlite
.open_queue_db(&runtime_queue_migrator(), /*telemetry_override*/ None)
.await?;
let observer = SqliteQueueStore::new(Arc::new(pool.clone()));
let thread_id = ThreadId::new();
let mut expected = observer
.enqueue(thread_id, r#"{"text":"original"}"#)
.await?;
let revision_before = observer.changes_since(/*revision*/ 0, &[thread_id]).await?[0].1;
expected.payload = r#"{"text":"edited bound value"}"#.to_string();
let (attempt_finished, mut finished) = mpsc::unbounded_channel();
let writer_pool = SqlitePoolOptions::new()
.max_connections(/*max*/ 1)
.after_release(move |_, _| {
let _ = attempt_finished.send(());
Box::pin(async { Ok(true) })
})
.connect_lazy_with(
(*pool.connect_options())
.clone()
.busy_timeout(Duration::ZERO),
);
let queue = SqliteQueueStore::new(Arc::new(writer_pool));
let mut competing_writer = pool.acquire().await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *competing_writer)
.await?;
let (updated, ()) = tokio::try_join!(
queue.update(thread_id, &expected.id, &expected.payload),
async {
// Release only after update actually failed admission, not while
// SQLite's busy handler could still turn the first attempt into success.
finished
.recv()
.await
.context("no completed writer attempt")?;
sqlx::query("ROLLBACK")
.execute(&mut *competing_writer)
.await?;
Ok::<(), anyhow::Error>(())
}
)?;
assert_eq!(Some(expected.clone()), updated);
assert_eq!(
(vec![expected], vec![(thread_id, revision_before + 1)]),
(
observer
.list_page(thread_id, /*offset*/ 0, /*limit*/ 10)
.await?,
observer
.changes_since(revision_before, &[thread_id])
.await?
)
);
drop(competing_writer);
queue.close().await;
pool.close().await;
Ok(())
}
#[tokio::test]
async fn queue_delete_survives_received_busy_and_preserves_other_messages() -> anyhow::Result<()> {
let sqlite_home = unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let pool = sqlite
.open_queue_db(&runtime_queue_migrator(), /*telemetry_override*/ None)
.await?;
let observer = SqliteQueueStore::new(Arc::new(pool.clone()));
let thread_id = ThreadId::new();
let target = observer.enqueue(thread_id, r#"{"text":"remove"}"#).await?;
let survivor = observer.enqueue(thread_id, r#"{"text":"keep"}"#).await?;
let revision_before = observer.changes_since(/*revision*/ 0, &[thread_id]).await?[0].1;
let (attempt_finished, mut finished) = mpsc::unbounded_channel();
let writer_pool = SqlitePoolOptions::new()
.max_connections(/*max*/ 1)
.after_release(move |_, _| {
let _ = attempt_finished.send(());
Box::pin(async { Ok(true) })
})
.connect_lazy_with(
(*pool.connect_options())
.clone()
.busy_timeout(Duration::ZERO),
);
let queue = SqliteQueueStore::new(Arc::new(writer_pool));
let mut competing_writer = pool.acquire().await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *competing_writer)
.await?;
let (deleted, ()) = tokio::try_join!(queue.delete(thread_id, &target.id), async {
// The first autocommit DELETE has returned BUSY and released its
// connection. Its bound thread and item IDs must survive the retry.
finished
.recv()
.await
.context("no completed writer attempt")?;
sqlx::query("ROLLBACK")
.execute(&mut *competing_writer)
.await?;
Ok::<(), anyhow::Error>(())
})?;
assert!(deleted);
assert_eq!(
(vec![survivor], vec![(thread_id, revision_before + 1)]),
(
observer
.list_page(thread_id, /*offset*/ 0, /*limit*/ 10)
.await?,
observer
.changes_since(revision_before, &[thread_id])
.await?
)
);
drop(competing_writer);
queue.close().await;
pool.close().await;
Ok(())
}

View File

@@ -0,0 +1,80 @@
//! Budgeted integrity checks that report confirmed corruption to database owners.
//!
//! Each file identity is checked at most once per shared SQLite configuration.
//! Attempts are recorded before validation, including failed or cancelled checks.
use file_id::FileId;
use sqlx::SqlitePool;
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tokio::sync::Mutex;
#[derive(Debug, Eq, PartialEq)]
pub(super) enum QuickCheckOutcome {
Complete,
Incomplete,
CorruptedNeedsFixed,
Skipped,
}
/// Keeps track of what databases were verified with quick_check() already
#[derive(Clone, Debug, Default)]
pub(super) struct SqliteQuickCheckManager(Arc<Mutex<HashSet<FileId>>>);
impl SqliteQuickCheckManager {
pub fn new() -> Self {
Self::default()
}
/// Returns this attempt's outcome, or `Skipped` if validation was already attempted.
pub async fn quick_check_once(
&self,
pool: &SqlitePool,
path: &Path,
budget: Duration,
) -> anyhow::Result<QuickCheckOutcome> {
let id = file_id::get_file_id(path)?;
if !self.0.lock().await.insert(id) {
// Only check each file once for this owner.
return Ok(QuickCheckOutcome::Skipped);
}
quick_check(pool, Instant::now() + budget).await
}
}
pub(super) async fn quick_check(
pool: &SqlitePool,
deadline: Instant,
) -> anyhow::Result<QuickCheckOutcome> {
let mut connection = pool.acquire().await?;
connection
.lock_handle()
.await?
.set_progress_handler(/*num_ops*/ 1_000, move || Instant::now() < deadline);
// quick_check(1) returns either "ok" or the first corruption finding
let result = sqlx::query_scalar::<_, String>("PRAGMA quick_check(1)")
.fetch_one(&mut *connection)
.await;
connection.lock_handle().await?.remove_progress_handler();
connection.return_to_pool().await;
match result.map_err(anyhow::Error::from) {
Ok(result) if result == "ok" => Ok(QuickCheckOutcome::Complete),
Ok(_) => Ok(QuickCheckOutcome::CorruptedNeedsFixed),
Err(error) if crate::is_sqlite_corruption_error(&error) => {
Ok(QuickCheckOutcome::CorruptedNeedsFixed)
}
// timeouts or other unhandled errors
Err(_) => Ok(QuickCheckOutcome::Incomplete),
}
}
#[cfg(test)]
#[path = "validation_tests.rs"]
mod tests;

View File

@@ -0,0 +1,586 @@
//! Exercises startup validation, per-file caching, and report-only lazy databases.
use super::QuickCheckOutcome;
use super::SqliteQuickCheckManager;
use super::quick_check;
use crate::SqliteConfig;
use crate::StateRuntime;
use crate::runtime::test_support::unique_temp_dir;
use anyhow::Context;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::sync::Mutex;
use std::time::Duration;
use std::time::Instant;
#[derive(Debug, Eq, PartialEq)]
struct CorruptionEvent {
count: i64,
tags: BTreeMap<String, String>,
}
#[derive(Default)]
struct CorruptionTelemetry(Mutex<Vec<CorruptionEvent>>);
impl crate::DbTelemetry for CorruptionTelemetry {
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
if name == crate::DB_CORRUPTION_METRIC {
self.0
.lock()
.expect("telemetry lock")
.push(CorruptionEvent {
count: inc,
tags: tags
.iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect(),
});
}
}
fn histogram(&self, _name: &str, _value: i64, _tags: &[(&str, &str)]) {}
fn record_duration(&self, _name: &str, _duration: Duration, _tags: &[(&str, &str)]) {}
}
#[tokio::test]
async fn runtime_opens_recover_or_report_corruption_by_database_policy() -> anyhow::Result<()> {
let root = unique_temp_dir();
let _cleanup = scopeguard::guard(root.clone(), |root| {
let _ = std::fs::remove_dir_all(root);
});
for spec in super::super::RUNTIME_DBS {
let home = root.join(spec.label);
tokio::fs::create_dir_all(&home).await?;
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let path = spec.path(&sqlite);
let fixture = path.with_extension("fixture");
let pool = sqlx::SqlitePool::connect_with(
sqlx::sqlite::SqliteConnectOptions::new()
.filename(&fixture)
.create_if_missing(true),
)
.await?;
sqlx::raw_sql(
"CREATE TABLE sample(value INTEGER);
INSERT INTO sample VALUES (NULL);
PRAGMA writable_schema=ON;
UPDATE sqlite_schema SET sql='CREATE TABLE sample(value INTEGER NOT NULL)' WHERE name='sample';
PRAGMA writable_schema=OFF;",
)
.execute(&pool)
.await?;
pool.close().await;
tokio::fs::rename(&fixture, &path).await?;
if path == sqlite.thread_history_db_path() {
let telemetry = CorruptionTelemetry::default();
// Unrelated corruption must not disable lazy history reads when the
// caller has no recovery path. Exercise both migration and reopening.
for _ in 0..2 {
let pool = sqlite
.open_thread_history_db(
&crate::migrations::runtime_thread_history_migrator(),
Some(&telemetry),
)
.await?;
assert_eq!(
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM thread_turns")
.fetch_one(&pool)
.await?,
0
);
assert_eq!(
quick_check(&pool, Instant::now() + Duration::from_secs(/*secs*/ 5)).await?,
QuickCheckOutcome::CorruptedNeedsFixed
);
pool.close().await;
}
assert_eq!(
*telemetry.0.lock().expect("telemetry lock"),
vec![CorruptionEvent {
count: 1,
tags: BTreeMap::from([("db".to_string(), "thread_history".to_string())]),
}]
);
continue;
}
// Recovery happens inside the database opener, without a CLI or app server.
for _ in 0..2 {
let runtime = StateRuntime::init(sqlite.clone(), "openai".to_string()).await?;
runtime.close().await;
}
let backups = std::fs::read_dir(home.join("db-backups"))
.with_context(|| format!("{} corruption did not create a backup", spec.label))?
.collect::<std::io::Result<Vec<_>>>()?;
assert_eq!(backups.len(), 1);
let backup_path = backups[0]
.path()
.join(path.file_name().expect("database filename"));
let pool = sqlite
.open_read_only_pool(&backup_path, /*busy_timeout*/ None)
.await?;
assert_eq!(
sqlx::query_scalar::<_, String>("PRAGMA quick_check(1)")
.fetch_one(&pool)
.await?,
"NULL value in sample.value"
);
assert_eq!(
sqlx::query_scalar::<_, String>("SELECT name FROM sqlite_schema WHERE type = 'table'")
.fetch_all(&pool)
.await?,
vec!["sample".to_string()]
);
pool.close().await;
}
Ok(())
}
#[tokio::test]
async fn quick_check_failure_is_recovered_before_runtime_init_returns() -> anyhow::Result<()> {
let home = unique_temp_dir();
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let telemetry = CorruptionTelemetry::default();
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let runtime = StateRuntime::init_with_telemetry_for_tests(
sqlite.clone(),
"openai".to_string(),
&telemetry,
)
.await?;
runtime.close().await;
let state_pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?;
sqlx::query("CREATE TABLE preserved(value); INSERT INTO preserved VALUES ('keep me')")
.execute(&state_pool)
.await?;
state_pool.close().await;
let logs_path = sqlite.logs_db_path();
sqlite
.open_logs_db(
&crate::migrations::runtime_logs_migrator(),
/*telemetry_override*/ None,
)
.await?
.close()
.await;
let fixture = logs_path.with_extension("fixture");
let pool = sqlx::SqlitePool::connect_with(
sqlx::sqlite::SqliteConnectOptions::new()
.filename(&fixture)
.create_if_missing(true),
)
.await?;
sqlx::raw_sql(
"CREATE TABLE sample(value INTEGER);
INSERT INTO sample VALUES (NULL);
PRAGMA writable_schema=ON;
UPDATE sqlite_schema SET sql='CREATE TABLE sample(value INTEGER NOT NULL)' WHERE name='sample';
PRAGMA writable_schema=OFF;",
)
.execute(&pool)
.await?;
pool.close().await;
// Replacing an already-validated file must trigger a new check at the same path.
tokio::fs::remove_file(&logs_path).await?;
tokio::fs::rename(&fixture, &logs_path).await?;
let runtime = StateRuntime::init_with_telemetry_for_tests(
sqlite.clone(),
"openai".to_string(),
&telemetry,
)
.await?;
runtime.close().await;
let runtime = StateRuntime::init_with_telemetry_for_tests(
sqlite.clone(),
"openai".to_string(),
&telemetry,
)
.await?;
runtime.close().await;
assert_eq!(
*telemetry.0.lock().expect("telemetry lock"),
vec![CorruptionEvent {
count: 1,
tags: BTreeMap::from([("db".to_string(), "logs".to_string())]),
}]
);
let backups =
std::fs::read_dir(home.join("db-backups"))?.collect::<std::io::Result<Vec<_>>>()?;
assert_eq!(backups.len(), 1);
let backup_path = backups[0]
.path()
.join(logs_path.file_name().expect("logs filename"));
let backup_pool = sqlite
.open_read_only_pool(&backup_path, /*busy_timeout*/ None)
.await?;
assert_eq!(
sqlx::query_scalar::<_, Option<i64>>("SELECT value FROM sample")
.fetch_all(&backup_pool)
.await?,
vec![None],
);
backup_pool.close().await;
let pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?;
assert_eq!(
sqlx::query_scalar::<_, String>("SELECT value FROM preserved")
.fetch_all(&pool)
.await?,
vec!["keep me".to_string()]
);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn repeated_pool_opens_share_completed_and_incomplete_attempts() -> anyhow::Result<()> {
for budget in [Duration::from_secs(/*secs*/ 5), Duration::ZERO] {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await?;
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let fixture = home.join("fixture.sqlite");
let pool = sqlx::SqlitePool::connect_with(
sqlx::sqlite::SqliteConnectOptions::new()
.filename(&fixture)
.create_if_missing(true),
)
.await?;
sqlx::raw_sql(
"CREATE TABLE sample(value INTEGER);
WITH RECURSIVE rows(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM rows WHERE id < 2048)
INSERT INTO sample SELECT id FROM rows;",
)
.execute(&pool)
.await?;
pool.close().await;
let path = sqlite.logs_db_path();
tokio::fs::rename(&fixture, &path).await?;
let pool = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
sqlite
.quick_check_manager
.quick_check_once(&pool, &path, budget)
.await?;
pool.close().await;
let migrator = crate::migrations::runtime_logs_migrator();
let pool = sqlite
.open_logs_db(&migrator, /*telemetry_override*/ None)
.await?;
sqlx::raw_sql(
"UPDATE sample SET value=NULL WHERE value=1;
PRAGMA writable_schema=ON;
UPDATE sqlite_schema SET sql='CREATE TABLE sample(value INTEGER NOT NULL)' WHERE name='sample';
PRAGMA writable_schema=OFF;",
)
.execute(&pool)
.await?;
pool.close().await;
// Corruption introduced after the first attempt exposes any repeated scan.
let cloned_sqlite = sqlite.clone();
let (first, second) = tokio::join!(
sqlite.open_logs_db(&migrator, /*telemetry_override*/ None),
cloned_sqlite.open_logs_db(&migrator, /*telemetry_override*/ None),
);
let first = first?;
let second = second?;
assert_eq!(
quick_check(&first, Instant::now() + Duration::from_secs(/*secs*/ 5)).await?,
QuickCheckOutcome::CorruptedNeedsFixed,
"an uncached check must still see the corruption"
);
first.close().await;
second.close().await;
// A separately constructed configuration must check and recover the file.
let independent_sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let repaired = independent_sqlite
.open_logs_db(&migrator, /*telemetry_override*/ None)
.await?;
assert_eq!(
quick_check(&repaired, Instant::now() + Duration::from_secs(/*secs*/ 5)).await?,
QuickCheckOutcome::Complete
);
assert!(home.join("db-backups").is_dir());
repaired.close().await;
}
Ok(())
}
#[tokio::test]
async fn concurrent_first_checks_share_an_in_flight_attempt() -> anyhow::Result<()> {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await?;
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let validation = SqliteQuickCheckManager::new();
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let path = sqlite.logs_db_path();
sqlx::SqlitePool::connect_with(
sqlx::sqlite::SqliteConnectOptions::new()
.filename(&path)
.create_if_missing(true),
)
.await?
.close()
.await;
let path = tokio::fs::canonicalize(path).await?;
let first = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
let second = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
// A second scan would fail on this pool instead of silently passing twice.
second.close().await;
let mut connection = first.acquire().await?;
let id = file_id::get_file_id(&path)?;
let check = tokio::spawn({
let validation = validation.clone();
let pool = first.clone();
let path = path.clone();
async move {
validation
.quick_check_once(&pool, &path, Duration::from_secs(/*secs*/ 5))
.await
}
});
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
while !validation.0.lock().await.contains(&id) {
tokio::task::yield_now().await;
}
})
.await?;
// The concurrent caller skips immediately, while the first check is blocked.
assert_eq!(
validation
.quick_check_once(&second, &path, Duration::from_secs(/*secs*/ 5))
.await?,
QuickCheckOutcome::Skipped
);
connection.return_to_pool().await;
assert_eq!(check.await??, QuickCheckOutcome::Complete);
first.close().await;
Ok(())
}
#[tokio::test]
async fn cancelled_check_counts_as_an_attempt() -> anyhow::Result<()> {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await?;
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let validation = SqliteQuickCheckManager::new();
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let path = sqlite.logs_db_path();
sqlx::SqlitePool::connect_with(
sqlx::sqlite::SqliteConnectOptions::new()
.filename(&path)
.create_if_missing(true),
)
.await?
.close()
.await;
let id = file_id::get_file_id(&path)?;
let pool = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
// Occupy the sole connection so cancellation happens during initialization.
let mut connection = pool.acquire().await?;
let check = tokio::spawn({
let validation = validation.clone();
let pool = pool.clone();
let path = path.clone();
async move {
validation
.quick_check_once(&pool, &path, Duration::from_secs(/*secs*/ 5))
.await
}
});
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
loop {
if validation.0.lock().await.contains(&id) {
break;
}
tokio::task::yield_now().await;
}
})
.await?;
check.abort();
assert!(
check
.await
.expect_err("check should be cancelled")
.is_cancelled()
);
connection.return_to_pool().await;
assert_eq!(
tokio::time::timeout(
Duration::from_secs(/*secs*/ 5),
validation.quick_check_once(&pool, &path, Duration::from_secs(/*secs*/ 5)),
)
.await??,
QuickCheckOutcome::Skipped
);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn corruption_attempts_are_cached_per_owner() -> anyhow::Result<()> {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await?;
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let validation = SqliteQuickCheckManager::new();
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let path = sqlite.logs_db_path();
let pool = sqlx::SqlitePool::connect_with(
sqlx::sqlite::SqliteConnectOptions::new()
.filename(&path)
.create_if_missing(true),
)
.await?;
let mut connection = pool.acquire().await?;
sqlx::raw_sql(
"CREATE TABLE sample(value INTEGER);
PRAGMA writable_schema=ON;
UPDATE sqlite_schema SET rootpage=2147483647 WHERE name='sample';
PRAGMA writable_schema=OFF;
PRAGMA schema_version=99;",
)
.execute(&mut *connection)
.await?;
connection.return_to_pool().await;
assert_eq!(
validation
.quick_check_once(&pool, &path, Duration::from_secs(/*secs*/ 5))
.await?,
QuickCheckOutcome::CorruptedNeedsFixed
);
// Another owner must check the same file independently.
let independent_validation = SqliteQuickCheckManager::new();
assert_eq!(
independent_validation
.quick_check_once(&pool, &path, Duration::from_secs(/*secs*/ 5))
.await?,
QuickCheckOutcome::CorruptedNeedsFixed
);
pool.close().await;
// A closed pool proves the completed attempt is skipped without another query.
assert_eq!(
validation
.quick_check_once(&pool, &path, Duration::from_secs(/*secs*/ 5))
.await?,
QuickCheckOutcome::Skipped
);
Ok(())
}
#[tokio::test]
async fn interrupted_check_leaves_connection_usable() -> anyhow::Result<()> {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await?;
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let path = sqlite.logs_db_path();
let pool = sqlite.open_read_write_pool(&path).await?;
sqlx::raw_sql(
"CREATE TABLE sample(value INTEGER);
WITH RECURSIVE rows(id) AS (SELECT 1 UNION ALL SELECT id + 1 FROM rows WHERE id < 2048)
INSERT INTO sample SELECT id FROM rows;",
)
.execute(&pool)
.await?;
pool.close().await;
// One connection ensures every assertion exercises the connection that was interrupted.
let pool = sqlite
.open_read_only_pool(&path, Some(Duration::from_secs(/*secs*/ 5)))
.await?;
assert_eq!(
quick_check(&pool, Instant::now()).await?,
QuickCheckOutcome::Incomplete
);
assert_eq!(
sqlx::query_scalar::<_, i64>("SELECT sum(value) FROM sample")
.fetch_one(&pool)
.await?,
2_098_176
);
assert_eq!(
quick_check(&pool, Instant::now() + Duration::from_secs(/*secs*/ 5)).await?,
QuickCheckOutcome::Complete
);
pool.close().await;
let pool = sqlite.open_read_write_pool(&path).await?;
sqlx::raw_sql(
"UPDATE sample SET value=NULL WHERE value=1;
PRAGMA writable_schema=ON;
UPDATE sqlite_schema SET sql='CREATE TABLE sample(value INTEGER NOT NULL)' WHERE name='sample';
PRAGMA writable_schema=OFF;",
)
.execute(&pool)
.await?;
pool.close().await;
let pool = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
assert_eq!(
quick_check(&pool, Instant::now()).await?,
QuickCheckOutcome::CorruptedNeedsFixed,
"retain a finding even if a later scan step exceeds the budget"
);
pool.close().await;
Ok(())
}
#[tokio::test]
async fn locked_database_does_not_count_as_corruption() -> anyhow::Result<()> {
let home = unique_temp_dir();
tokio::fs::create_dir_all(&home).await?;
let _cleanup = scopeguard::guard(home.clone(), |home| {
let _ = std::fs::remove_dir_all(home);
});
let sqlite = SqliteConfig::new_for_testing(home.as_path().abs());
let path = sqlite.logs_db_path();
let writer_pool = sqlite.open_read_write_pool(&path).await?;
let mut writer = writer_pool.acquire().await?;
sqlx::query("PRAGMA journal_mode=DELETE")
.execute(&mut *writer)
.await?;
let reader_pool = sqlite
.open_read_only_pool(&path, Some(Duration::from_millis(/*millis*/ 50)))
.await?;
sqlx::query("BEGIN EXCLUSIVE").execute(&mut *writer).await?;
let started = Instant::now();
let result = quick_check(&reader_pool, started + Duration::from_millis(/*millis*/ 50)).await;
sqlx::query("ROLLBACK").execute(&mut *writer).await?;
drop(writer);
writer_pool.close().await;
assert_eq!(result?, QuickCheckOutcome::Incomplete);
assert_eq!(
quick_check(
&reader_pool,
Instant::now() + Duration::from_secs(/*secs*/ 5)
)
.await?,
QuickCheckOutcome::Complete
);
reader_pool.close().await;
Ok(())
}

View File

@@ -0,0 +1,663 @@
//! Regression coverage for SQLite initialization, cached filesystem detection, and competing locks.
use super::SqliteConfig;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use sqlx::sqlite::SqliteAutoVacuum;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::sqlite::SqliteJournalMode;
use sqlx::sqlite::SqlitePoolOptions;
#[tokio::test]
async fn current_schema_opens_while_another_connection_has_writer_reservation() -> anyhow::Result<()>
{
let home = tempfile::TempDir::new()?;
let sqlite = SqliteConfig::new_for_testing(home.path().abs());
sqlite.is_nfs.set(/*value*/ true)?;
let migrator = crate::migrations::runtime_thread_history_migrator();
let pool = sqlite
.open_thread_history_db(&migrator, /*telemetry_override*/ None)
.await?;
let transaction = pool.begin_with("BEGIN IMMEDIATE").await?;
let reopened = sqlite
.open_thread_history_db(&migrator, /*telemetry_override*/ None)
.await?;
let check: String = sqlx::query_scalar("PRAGMA integrity_check")
.fetch_one(&reopened)
.await?;
assert_eq!(check, "ok");
transaction.rollback().await?;
reopened.close().await;
pool.close().await;
Ok(())
}
#[tokio::test]
async fn concurrent_openers_apply_schema_migrations_once() -> anyhow::Result<()> {
let home = tempfile::TempDir::new()?;
let sqlite = SqliteConfig::new_for_testing(home.path().abs());
sqlite.is_nfs.set(/*value*/ true)?;
let migrator = crate::migrations::runtime_thread_history_migrator();
let mut openers = tokio::task::JoinSet::new();
for _ in 0..8 {
let sqlite = sqlite.clone();
openers.spawn(async move {
sqlite
.open_thread_history_db(
&crate::migrations::runtime_thread_history_migrator(),
/*telemetry_override*/ None,
)
.await
});
}
while let Some(result) = openers.join_next().await {
let pool = result??;
let versions =
sqlx::query_scalar::<_, i64>("SELECT version FROM _sqlx_migrations ORDER BY version")
.fetch_all(&pool)
.await?;
assert_eq!(
versions,
migrator
.iter()
.map(|migration| migration.version)
.collect::<Vec<_>>()
);
pool.close().await;
}
Ok(())
}
#[tokio::test]
async fn configured_log_directory_is_initialized_on_use_and_retries_after_failure()
-> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let logs_home = sqlite_home.join("logs");
tokio::fs::write(&logs_home, "not a directory").await?;
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
sqlite.is_nfs.set(/*value*/ true)?;
let fallback_logs_path = sqlite.logs_db_path();
let sqlite = sqlite.with_local_logs_home(logs_home.clone());
sqlite.logs_is_nfs.set(/*value*/ false)?;
// Opening unrelated state must not require the configured logs directory.
let pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?;
pool.close().await;
assert!(
crate::StateRuntime::init(sqlite.clone(), "openai".to_string())
.await
.is_err()
);
assert!(!fallback_logs_path.exists());
// A failed initialization must remain retryable without replacing the config.
tokio::fs::remove_file(&logs_home).await?;
let runtime = crate::StateRuntime::init(sqlite.clone(), "openai".to_string()).await?;
assert!(sqlite.logs_db_path().is_file());
assert!(!fallback_logs_path.exists());
runtime.close().await;
// The configured logs directory has its own filesystem, independent of the NFS state home.
let mut modes = Vec::new();
for path in [sqlite.state_db_path(), sqlite.logs_db_path()] {
let pool = sqlite
.open_read_only_pool(&path, /*busy_timeout*/ None)
.await?;
modes.push(
sqlx::query_scalar::<_, String>("PRAGMA journal_mode")
.fetch_one(&pool)
.await?,
);
pool.close().await;
}
assert_eq!(modes, vec!["delete".to_string(), "wal".to_string()]);
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn configured_log_directory_lock_is_shared_by_reader_and_writer_config_clones()
-> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
let logs_home = sqlite_home.join("logs");
tokio::fs::create_dir_all(&logs_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let initial = SqliteConfig::new_for_testing(logs_home.as_path().abs());
let logs_path = initial.logs_db_path();
initial
.open_read_write_pool(&logs_path)
.await?
.close()
.await;
for read_only in [false, true] {
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs())
.with_local_logs_home(logs_home.clone());
let clone = sqlite.clone();
let cleanup_lock = std::fs::File::open(&logs_home)?;
cleanup_lock.try_lock()?;
cleanup_lock.unlock()?;
let pool = if read_only {
sqlite
.open_read_only_pool(&logs_path, /*busy_timeout*/ None)
.await?
} else {
sqlite.open_read_write_pool(&logs_path).await?
};
assert!(matches!(
cleanup_lock.try_lock(),
Err(std::fs::TryLockError::WouldBlock)
));
drop(sqlite);
assert!(matches!(
cleanup_lock.try_lock(),
Err(std::fs::TryLockError::WouldBlock)
));
pool.close().await;
drop(clone);
cleanup_lock.try_lock()?;
}
Ok(())
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn sqlite_home_filesystem_probe_is_shared_by_clones_until_config_replacement()
-> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let clone = sqlite.clone();
let is_nfs = sqlite.is_nfs().await?;
tokio::fs::remove_dir(&sqlite_home).await?;
// This clone has never queried the home. It must reuse the original's probe,
// because a fresh filesystem lookup would fail now that the home is absent.
assert_eq!(clone.is_nfs().await?, is_nfs);
let fresh = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
assert_eq!(
fresh
.is_nfs()
.await
.unwrap_err()
.downcast_ref::<std::io::Error>()
.unwrap()
.kind(),
std::io::ErrorKind::NotFound
);
Ok(())
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn failed_sqlite_home_filesystem_probe_recovers_after_home_creation() -> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
assert_eq!(
sqlite
.is_nfs()
.await
.unwrap_err()
.downcast_ref::<std::io::Error>()
.unwrap()
.kind(),
std::io::ErrorKind::NotFound
);
tokio::fs::create_dir_all(&sqlite_home).await?;
sqlite.is_nfs().await?;
Ok(())
}
#[tokio::test]
async fn open_read_write_pool_initializes_fresh_database_settings() -> anyhow::Result<()> {
for (enforced, nfs, partial_journal) in [
(false, false, None),
(false, false, Some(SqliteJournalMode::Delete)),
(false, true, None),
(false, true, Some(SqliteJournalMode::Delete)),
(false, true, Some(SqliteJournalMode::Wal)),
(true, false, None),
(true, false, Some(SqliteJournalMode::Delete)),
(true, cfg!(unix), None),
(true, cfg!(unix), Some(SqliteJournalMode::Delete)),
] {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::from_sqlite_home_with_nfs_enforcement(
sqlite_home.as_path().abs(),
enforced,
);
sqlite.is_nfs.set(nfs)?;
let path = sqlite.logs_db_path();
if let Some(journal_mode) = partial_journal {
// Startup must finish initialization when settings were written before the schema.
let partial = SqlitePoolOptions::new()
.max_connections(/*max*/ 1)
.connect_with(
SqliteConnectOptions::new()
.filename(&path)
.create_if_missing(/*create*/ true)
.auto_vacuum(SqliteAutoVacuum::Incremental)
.journal_mode(journal_mode),
)
.await?;
partial.close().await;
assert!(tokio::fs::metadata(&path).await?.len() > 0);
}
let pool = sqlite.open_read_write_pool(&path).await?;
// Hold connections open so the assertions cover lazy pool connections too.
let mut connections = Vec::new();
let mut settings = Vec::new();
for _ in 0..5 {
let mut connection = pool.acquire().await?;
let current: (String, i64, i64) = sqlx::query_as(
"SELECT journal_mode, auto_vacuum, synchronous
FROM pragma_journal_mode, pragma_auto_vacuum, pragma_synchronous",
)
.fetch_one(&mut *connection)
.await?;
settings.push(current);
connections.push(connection);
}
assert_eq!(
settings,
vec![
(
if nfs { "delete" } else { "wal" }.to_string(),
SqliteAutoVacuum::Incremental as i64,
if nfs { 3 } else { 1 },
);
5
]
);
drop(connections);
pool.close().await;
}
Ok(())
}
#[tokio::test]
async fn open_read_write_pool_uses_database_directory_for_filesystem_probe() -> anyhow::Result<()> {
let directory = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&directory).await?;
let _cleanup = scopeguard::guard(directory.clone(), |directory| {
let _ = std::fs::remove_dir_all(directory);
});
let nfs = codex_file_system::is_nfs(&directory)?;
let missing_home = directory.join("absent");
for (index, cached_home_nfs) in [None, Some(!nfs)].into_iter().enumerate() {
let sqlite = SqliteConfig::new_for_testing(missing_home.as_path().abs());
if let Some(nfs) = cached_home_nfs {
sqlite.is_nfs.set(nfs)?;
}
// An unrelated missing home or its cached filesystem must not affect this database.
let path = directory.join(format!("database-{index}.sqlite"));
let pool = sqlite.open_read_write_pool(&path).await?;
let settings: (String, i64) = sqlx::query_as(
"SELECT journal_mode, synchronous FROM pragma_journal_mode, pragma_synchronous",
)
.fetch_one(&pool)
.await?;
assert_eq!(
settings,
(
if nfs { "delete" } else { "wal" }.to_string(),
if nfs { 3 } else { 1 },
)
);
pool.close().await;
}
Ok(())
}
#[tokio::test]
async fn open_read_write_pool_preserves_existing_settings_under_write_lock() -> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
sqlite.is_nfs.set(/*value*/ true)?;
let database_path = sqlite.logs_db_path();
let existing_pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(
SqliteConnectOptions::new()
.filename(&database_path)
.create_if_missing(true)
.auto_vacuum(SqliteAutoVacuum::Full)
.journal_mode(SqliteJournalMode::Wal),
)
.await?;
sqlx::query("CREATE TABLE existing (id INTEGER PRIMARY KEY)")
.execute(&existing_pool)
.await?;
let mut lock_holder = existing_pool.acquire().await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *lock_holder)
.await?;
let pool = sqlite.open_read_write_pool(&database_path).await?;
let settings: (String, i64, i64) = sqlx::query_as(
"SELECT journal_mode, auto_vacuum, synchronous
FROM pragma_journal_mode, pragma_auto_vacuum, pragma_synchronous",
)
.fetch_one(&pool)
.await?;
assert_eq!(settings, ("wal".into(), SqliteAutoVacuum::Full as i64, 1));
sqlx::query("ROLLBACK").execute(&mut *lock_holder).await?;
drop(lock_holder);
pool.close().await;
existing_pool.close().await;
Ok(())
}
#[tokio::test]
async fn open_read_write_pool_preserves_delete_under_write_lock() -> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs())
.enable_delete_mode_on_nfs(/*enabled*/ true);
sqlite.is_nfs.set(cfg!(unix))?;
let database_path = sqlite.logs_db_path();
let existing_pool = SqlitePoolOptions::new()
.max_connections(1)
.connect_with(
SqliteConnectOptions::new()
.filename(&database_path)
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Delete),
)
.await?;
sqlx::query("CREATE TABLE existing (id INTEGER PRIMARY KEY)")
.execute(&existing_pool)
.await?;
let mut lock_holder = existing_pool.acquire().await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *lock_holder)
.await?;
let pool = sqlite.open_read_write_pool(&database_path).await?;
// Keep each acquired connection open to test connections that the pool initializes later.
let mut connections = Vec::new();
let mut settings = Vec::new();
for _ in 0..5 {
let mut connection = pool.acquire().await?;
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&mut *connection)
.await?;
let synchronous: i64 = sqlx::query_scalar("PRAGMA synchronous")
.fetch_one(&mut *connection)
.await?;
settings.push((journal, synchronous));
connections.push(connection);
}
assert_eq!(settings, vec![("delete".to_string(), 3); 5]);
drop(connections);
sqlx::query("ROLLBACK").execute(&mut *lock_holder).await?;
drop(lock_holder);
existing_pool.close().await;
sqlx::query("INSERT INTO existing VALUES(42)")
.execute(&pool)
.await?;
pool.close().await;
let reopened = sqlite.open_read_write_pool(&database_path).await?;
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&reopened)
.await?;
let rows: Vec<i64> = sqlx::query_scalar("SELECT id FROM existing")
.fetch_all(&reopened)
.await?;
assert_eq!((journal, rows), ("delete".into(), vec![42]));
reopened.close().await;
Ok(())
}
#[tokio::test]
async fn open_read_write_pool_preserves_empty_database_lock_error() -> anyhow::Result<()> {
let sqlite_home = crate::runtime::test_support::unique_temp_dir();
tokio::fs::create_dir_all(&sqlite_home).await?;
let _cleanup = scopeguard::guard(sqlite_home.clone(), |sqlite_home| {
let _ = std::fs::remove_dir_all(sqlite_home);
});
let sqlite = SqliteConfig::new_for_testing(sqlite_home.as_path().abs());
let database_path = sqlite.logs_db_path();
let existing_pool = SqlitePoolOptions::new()
.max_connections(/*max*/ 1)
.connect_with(
SqliteConnectOptions::new()
.filename(&database_path)
.create_if_missing(/*create*/ true)
.auto_vacuum(SqliteAutoVacuum::Incremental)
.journal_mode(SqliteJournalMode::Delete),
)
.await?;
// Leave the schema empty so startup must initialize WAL.
let mut lock_holder = existing_pool.acquire().await?;
sqlx::query("BEGIN IMMEDIATE")
.execute(&mut *lock_holder)
.await?;
let error = sqlite
.open_read_write_pool(&database_path)
.await
.expect_err("WAL setup must fail while another connection holds the writer lock");
assert_eq!(
error
.downcast_ref::<sqlx::Error>()
.and_then(sqlx::Error::as_database_error)
.and_then(sqlx::error::DatabaseError::code),
Some("5".into())
);
assert!(crate::sqlite_error_detail_is_lock(&error.to_string()));
sqlx::query("ROLLBACK").execute(&mut *lock_holder).await?;
// A failed opener must release its locks before another writer can proceed.
sqlx::query("BEGIN EXCLUSIVE")
.execute(&mut *lock_holder)
.await?;
sqlx::query("ROLLBACK").execute(&mut *lock_holder).await?;
drop(lock_holder);
existing_pool.close().await;
let pool = sqlite.open_read_write_pool(&database_path).await?;
sqlx::query("CREATE TABLE initialized (id INTEGER PRIMARY KEY)")
.execute(&pool)
.await?;
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&pool)
.await?;
assert_eq!(journal, "wal");
pool.close().await;
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn required_nfs_migration_preserves_runtime_data_and_backups_after_restart()
-> anyhow::Result<()> {
use std::os::unix::fs::PermissionsExt;
let home = tempfile::tempdir()?;
let original = SqliteConfig::new_for_testing(home.path().abs());
let runtime = crate::StateRuntime::init(original.clone(), "test-provider".into()).await?;
runtime.checkpoint_backfill("before-migration").await?;
let before = runtime.get_backfill_state().await?;
runtime.close().await;
original.open_memories_v2_db().await?.close().await;
crate::open_thread_history_db(&original)
.await?
.close()
.await;
let state_path = original.state_db_path();
assert!(crate::NfsDbMigration::needs_migration(&state_path).await?);
let bytes = std::fs::read(&state_path)?;
std::fs::set_permissions(&state_path, std::fs::Permissions::from_mode(/*mode*/ 0o060))?;
let staging = tempfile::tempdir()?;
let result = crate::NfsDbMigration::lock(home.path())?
.migrate(&state_path, staging.path())
.await;
std::fs::set_permissions(&state_path, std::fs::Permissions::from_mode(/*mode*/ 0o600))?;
assert!(result.is_err());
assert_eq!(std::fs::read(&state_path)?, bytes);
let mut backups = Vec::new();
for db in original
.runtime_db_paths()
.into_iter()
.filter(|db| db.path.exists())
{
std::fs::set_permissions(&db.path, std::fs::Permissions::from_mode(/*mode*/ 0o644))?;
let name = db.path.file_name().unwrap().to_str().unwrap();
backups.push((
home.path()
.join(format!("{name}_wal_migration_backup"))
.join(name),
std::fs::read(&db.path)?,
));
}
let sqlite = SqliteConfig::from_sqlite_home_with_nfs_enforcement(
home.path().abs(),
/*enforce_delete_on_nfs*/ true,
);
sqlite.is_nfs.set(/*value*/ true)?;
assert!(crate::NfsDbMigration::needs_permission_confirmation(
&sqlite.state_db_path()
)?);
let migrated = crate::StateRuntime::init(sqlite.clone(), "test-provider".into()).await?;
assert_eq!(migrated.get_backfill_state().await?, before);
migrated.checkpoint_backfill("after-migration").await?;
let after = migrated.get_backfill_state().await?;
migrated.close().await;
assert!(!crate::NfsDbMigration::needs_migration(&state_path).await?);
// Simulate a crash after moving the original but before reinstalling a lazy database.
let lazy = sqlite.memories_v2_db_path();
let name = lazy.file_name().unwrap().to_str().unwrap();
std::fs::rename(
&lazy,
home.path()
.join(format!("{name}_wal_migration_backup/delete.sqlite")),
)?;
assert!(crate::NfsDbMigration::needs_permission_confirmation(&lazy)?);
assert!(crate::NfsDbMigration::needs_migration(&lazy).await?);
let restarted = crate::StateRuntime::init(sqlite.clone(), "test-provider".into()).await?;
assert_eq!(restarted.get_backfill_state().await?, after);
restarted.close().await;
// Include lazily created databases: they must also start in DELETE mode.
for db in sqlite.runtime_db_paths() {
let pool = sqlite.open_read_write_pool(&db.path).await?;
let settings: (String, i64) = sqlx::query_as(
"SELECT journal_mode, synchronous FROM pragma_journal_mode, pragma_synchronous",
)
.fetch_one(&pool)
.await?;
assert_eq!(settings, ("delete".into(), 3));
pool.close().await;
if backups
.iter()
.any(|(backup, _)| backup.file_name() == db.path.file_name())
{
assert_eq!(
std::fs::metadata(&db.path)?.permissions().mode() & 0o777,
0o644
);
}
}
for (path, bytes) in backups {
assert_eq!(std::fs::read(path)?, bytes);
}
Ok(())
}
#[cfg(unix)]
#[tokio::test]
async fn required_nfs_migration_refuses_active_wal_and_retries_after_close() -> anyhow::Result<()> {
use std::future::Future;
use std::os::unix::fs::PermissionsExt;
use std::task::Poll;
let home = tempfile::tempdir()?;
let logs_home = home.path().join("local-logs");
let sqlite =
SqliteConfig::new_for_testing(home.path().abs()).with_local_logs_home(logs_home.clone());
let logs = sqlite.open_read_write_pool(&sqlite.logs_db_path()).await?;
sqlx::query("CREATE TABLE existing_logs (id INTEGER PRIMARY KEY)")
.execute(&logs)
.await?;
let path = sqlite.state_db_path();
let pool = sqlite.open_read_write_pool(&path).await?;
sqlx::raw_sql("CREATE TABLE entries(id); INSERT INTO entries VALUES(42);")
.execute(&pool)
.await?;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(/*mode*/ 0o600))?;
let required = SqliteConfig::new_for_testing(home.path().abs())
.with_local_logs_home(logs_home)
.enable_delete_mode_on_nfs(/*enabled*/ true);
required.is_nfs.set(/*value*/ true)?;
required.logs_is_nfs.set(/*value*/ false)?;
assert!(crate::NfsDbMigration::needs_migration(&path).await?);
let error = required.open_read_write_pool(&path).await.unwrap_err();
assert!(
error
.to_string()
.contains("required NFS database migration failed"),
"{error:#}"
);
assert!(!crate::is_sqlite_corruption_error(&error));
pool.close().await;
let migration_lock = crate::NfsDbMigration::lock(home.path())?;
let mut opening = Box::pin(required.open_read_write_pool(&path));
std::future::poll_fn(|cx| {
assert!(opening.as_mut().poll(cx).is_pending());
Poll::Ready(())
})
.await;
drop(migration_lock);
let migrated = opening.await?;
let rows: Vec<i64> = sqlx::query_scalar("SELECT id FROM entries")
.fetch_all(&migrated)
.await?;
assert_eq!(rows, vec![42]);
migrated.close().await;
// An active local logs database must remain in WAL while the NFS state database migrates.
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&logs)
.await?;
assert_eq!(journal, "wal");
logs.close().await;
// Old versions may create legacy WAL logs after startup. Managed cleanup must not write them.
let legacy = sqlite
.open_read_write_pool(&sqlite.legacy_logs_db_path().unwrap())
.await?;
assert!(required.open_legacy_logs_for_cleanup().await?.is_none());
let journal: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(&legacy)
.await?;
assert_eq!(journal, "wal");
legacy.close().await;
Ok(())
}

View File

@@ -0,0 +1,291 @@
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::Duration;
use crate::DB_CORRUPTION_METRIC;
use crate::DB_FALLBACK_METRIC;
use crate::DB_INIT_DURATION_METRIC;
use crate::DB_INIT_METRIC;
use crate::LOG_QUEUE_DROPPED_METRIC;
use crate::LOG_WRITE_BYTES_METRIC;
use crate::LOG_WRITE_DURATION_METRIC;
use crate::LOG_WRITE_ENTRIES_METRIC;
use crate::LOG_WRITE_MAX_ENTRY_BYTES_METRIC;
use crate::LOG_WRITE_METRIC;
use crate::LogEntry;
use crate::runtime::reclamation::ReclamationPass;
use tracing::debug;
/// Low-cardinality sink for SQLite startup, corruption, fallback, log-write, and reclamation telemetry.
///
/// Implementations should absorb delivery failures locally. Database behavior
/// must not depend on whether telemetry export succeeds.
pub trait DbTelemetry: Send + Sync + 'static {
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]);
fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]);
fn record_duration(&self, name: &str, duration: Duration, tags: &[(&str, &str)]);
}
pub type DbTelemetryHandle = Arc<dyn DbTelemetry>;
static PROCESS_DB_TELEMETRY: OnceLock<DbTelemetryHandle> = OnceLock::new();
/// Install the process-wide SQLite telemetry sink.
///
/// Startup owners should call this once after OTEL initialization. Low-level
/// database paths will use the registered sink unless an explicit sink is
/// provided. Subsequent installs are ignored and keep the first installed sink.
pub fn install_process_db_telemetry(telemetry: DbTelemetryHandle) -> bool {
if PROCESS_DB_TELEMETRY.set(telemetry).is_ok() {
true
} else {
debug!("process SQLite telemetry sink already installed; ignoring duplicate install");
false
}
}
#[derive(Clone, Copy)]
pub(crate) enum DbKind {
State,
Logs,
Goals,
Memories,
Queue,
ThreadHistory,
}
impl DbKind {
fn as_str(self) -> &'static str {
match self {
Self::State => "state",
Self::Logs => "logs",
Self::Goals => "goals",
Self::Memories => "memories",
Self::Queue => "queue",
Self::ThreadHistory => "thread_history",
}
}
}
pub(crate) fn record_corruption(telemetry: Option<&dyn DbTelemetry>, db: Option<DbKind>) {
record_counter(
telemetry,
DB_CORRUPTION_METRIC,
&[("db", db.map_or("other", DbKind::as_str))],
);
}
pub(crate) fn record_init_result<T>(
telemetry: Option<&dyn DbTelemetry>,
db: DbKind,
phase: &'static str,
duration: Duration,
result: &anyhow::Result<T>,
) {
let outcome = DbOutcomeTags::from_result(result);
let tags = [
("status", outcome.status),
("phase", phase),
("db", db.as_str()),
("error", outcome.error),
];
record_counter(telemetry, DB_INIT_METRIC, &tags);
record_duration(telemetry, DB_INIT_DURATION_METRIC, duration, &tags);
}
pub fn record_backfill_gate(
telemetry: Option<&dyn DbTelemetry>,
duration: Duration,
result: &anyhow::Result<()>,
) {
record_init_result(telemetry, DbKind::State, "backfill_gate", duration, result);
}
pub fn record_fallback(
caller: &'static str,
reason: &'static str,
telemetry_override: Option<&dyn DbTelemetry>,
) {
record_counter(
telemetry_override,
DB_FALLBACK_METRIC,
&[("caller", caller), ("reason", reason)],
);
}
pub(crate) fn record_log_write(
telemetry: Option<&dyn DbTelemetry>,
duration: Duration,
entries: &[LogEntry],
result: &anyhow::Result<()>,
) {
let Some(telemetry) = resolve_telemetry(telemetry) else {
return;
};
let outcome = DbOutcomeTags::from_result(result);
let tags = [("status", outcome.status), ("error", outcome.error)];
let mut batch_bytes = 0_i64;
let mut max_entry_bytes = 0_i64;
for entry in entries {
let entry_bytes = entry.estimated_bytes();
batch_bytes = batch_bytes.saturating_add(entry_bytes);
max_entry_bytes = max_entry_bytes.max(entry_bytes);
}
let entry_count = i64::try_from(entries.len()).unwrap_or(i64::MAX);
telemetry.counter(LOG_WRITE_METRIC, /*inc*/ 1, &tags);
telemetry.record_duration(LOG_WRITE_DURATION_METRIC, duration, &tags);
telemetry.histogram(LOG_WRITE_BYTES_METRIC, batch_bytes, &tags);
telemetry.histogram(LOG_WRITE_ENTRIES_METRIC, entry_count, &tags);
telemetry.histogram(LOG_WRITE_MAX_ENTRY_BYTES_METRIC, max_entry_bytes, &tags);
}
pub(crate) fn record_log_queue_drop(reason: &'static str, telemetry: Option<&dyn DbTelemetry>) {
record_counter(telemetry, LOG_QUEUE_DROPPED_METRIC, &[("reason", reason)]);
}
pub(crate) fn record_reclamation(
db: &'static str,
duration: Duration,
result: &anyhow::Result<ReclamationPass>,
) {
let Some(telemetry) = resolve_telemetry(/*telemetry*/ None) else {
return;
};
let outcome = DbOutcomeTags::from_result(result);
let tags = [
("db", db),
("status", outcome.status),
("error", outcome.error),
];
telemetry.counter("codex.sqlite.reclamation.count", /*inc*/ 1, &tags);
telemetry.record_duration("codex.sqlite.reclamation.duration_ms", duration, &tags);
if let Ok(pass) = result {
telemetry.histogram(
"codex.sqlite.reclamation.pages",
i64::from(pass.pages),
&tags,
);
}
}
fn record_counter(telemetry: Option<&dyn DbTelemetry>, name: &str, tags: &[(&str, &str)]) {
if let Some(telemetry) = resolve_telemetry(telemetry) {
telemetry.counter(name, /*inc*/ 1, tags);
}
}
fn record_duration(
telemetry: Option<&dyn DbTelemetry>,
name: &str,
duration: Duration,
tags: &[(&str, &str)],
) {
if let Some(telemetry) = resolve_telemetry(telemetry) {
telemetry.record_duration(name, duration, tags);
}
}
fn resolve_telemetry(telemetry: Option<&dyn DbTelemetry>) -> Option<&dyn DbTelemetry> {
telemetry.or_else(|| PROCESS_DB_TELEMETRY.get().map(AsRef::as_ref))
}
struct DbOutcomeTags {
status: &'static str,
error: &'static str,
}
impl DbOutcomeTags {
fn from_result<T>(result: &anyhow::Result<T>) -> Self {
match result {
Ok(_) => Self {
status: "success",
error: "none",
},
Err(err) => Self {
status: "failed",
error: classify_error(err),
},
}
}
}
pub(crate) fn classify_error(err: &anyhow::Error) -> &'static str {
for cause in err.chain() {
if let Some(sqlx_err) = cause.downcast_ref::<sqlx::Error>() {
return classify_sqlx_error(sqlx_err);
}
if cause
.downcast_ref::<sqlx::migrate::MigrateError>()
.is_some()
{
return "migration";
}
if cause.downcast_ref::<serde_json::Error>().is_some() {
return "serde";
}
if cause.downcast_ref::<std::io::Error>().is_some() {
return "io";
}
}
if crate::is_sqlite_corruption_error(err) {
"corrupt"
} else {
"unknown"
}
}
fn classify_sqlx_error(err: &sqlx::Error) -> &'static str {
match err {
sqlx::Error::Database(database_error) => {
let code = database_error
.code()
.unwrap_or(Cow::Borrowed("none"))
.to_string();
classify_sqlite_code(code.as_str())
}
sqlx::Error::PoolTimedOut => "pool_timeout",
sqlx::Error::Io(_) => "io",
sqlx::Error::ColumnDecode { source, .. } if source.is::<serde_json::Error>() => "serde",
sqlx::Error::Decode(source) if source.is::<serde_json::Error>() => "serde",
_ => "unknown",
}
}
fn classify_sqlite_code(code: &str) -> &'static str {
// SQLite result codes are documented at https://www.sqlite.org/rescode.html.
// Extended codes preserve the primary code in the low byte.
let primary_code = code.parse::<i32>().ok().map(|code| code & 0xff);
match primary_code {
Some(5) => "busy",
Some(6) => "locked",
Some(8) => "readonly",
Some(10) => "io",
Some(11) => "corrupt",
Some(13) => "full",
Some(14) => "cantopen",
Some(17) => "schema",
Some(19) => "constraint",
_ => "unknown",
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn classifies_extended_sqlite_codes() {
assert_eq!(classify_sqlite_code("5"), "busy");
assert_eq!(classify_sqlite_code("6"), "locked");
assert_eq!(classify_sqlite_code("2067"), "constraint");
}
}
#[cfg(test)]
#[path = "log_write_telemetry_tests.rs"]
mod log_write_telemetry_tests;