aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

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 akode_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 akode_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 akode_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 akode_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 akode_protocol::MemoryVersion;
use akode_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 akode_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 akode_protocol::ThreadId;
use akode_protocol::protocol::SessionSource;
use akode_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 akode_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 akode_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 akode_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 akode_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,84 @@
#[cfg(test)]
use chrono::DateTime;
#[cfg(test)]
use chrono::Utc;
#[cfg(test)]
use akode_protocol::ThreadId;
#[cfg(test)]
use akode_protocol::openai_models::ReasoningEffort;
#[cfg(test)]
use akode_protocol::protocol::AskForApproval;
#[cfg(test)]
use akode_protocol::protocol::SandboxPolicy;
#[cfg(test)]
use akode_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,
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 akode_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 akode_protocol::ThreadId;
use akode_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 akode_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 akode_protocol::ThreadId;
use akode_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 akode_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 akode_protocol::ThreadId;
use akode_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 akode_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 akode_protocol::ThreadId;
use akode_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 akode_protocol::ThreadId;
use akode_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