Skip to main content

orch/store/
mod.rs

1//! Unified task store — SQLite as single source of truth.
2//!
3//! `TaskStore` replaces the legacy `internal_tasks` table and GitHub labels as the
4//! authoritative task state. External backends (GitHub, Linear) become sync adapters
5//! that mirror state changes outward.
6//!
7//! Uses sqlx for async SQLite access with file-based migrations.
8//!
9//! All task state, metrics, KV, and rate limits flow through this module.
10//!
11//! # Safety Warning: Never Use `SELECT *`
12//!
13//! Using `SELECT *` with `sqlx-sqlite`'s prepared statement cache can cause **OOB
14//! (out-of-bounds) panics** when the schema changes (e.g., new migration adds a column).
15//!
16//! The issue occurs because:
17//! 1. SQLite caches prepared statements with column metadata at prepare time
18//! 2. When a migration adds a new column, `sqlite3_column_count()` returns the updated count
19//! 3. The cached statement's column metadata vector was built with the old count
20//! 4. Accessing column index N when only N columns exist (0..N-1) causes a panic
21//!
22//! **Solution:** Always use explicit column lists via constants like `TASK_COLS`,
23//! `CONTROL_MESSAGE_COLS`, `JOB_STATE_COLS`, etc. See `tasks.rs` and `control.rs`
24//! for examples. CI will fail if `SELECT *` is detected in store files.
25
26pub(crate) mod control;
27pub(crate) mod dependencies;
28mod helpers;
29pub(crate) mod jobs;
30pub(crate) mod kv;
31mod metrics;
32pub(crate) mod replica;
33pub(crate) mod tasks;
34
35#[cfg(test)]
36mod tests;
37mod usage;
38
39use anyhow::Context;
40use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions};
41use std::collections::BTreeMap;
42use std::fmt;
43use std::fmt::Debug;
44use std::fmt::Formatter;
45use std::path::Path;
46use std::path::PathBuf;
47use std::sync::{Arc, OnceLock};
48use std::time::Duration;
49
50pub use control::{ChatCostSummary, ControlMessage, MemoryEntry, parse_since_duration};
51pub use dependencies::{
52    BlockerSnapshot, DepSource, NewDependency, ObservedPullRequest, TaskDependency,
53    WaitingOnDependency, blocker_failure_kind, blocker_is_satisfied, blocker_snapshot_key,
54    dep_label, worktree_refresh_key,
55};
56pub use helpers::{
57    StoreResult, get_recent_memory, get_recent_memory_result, get_reported_cost,
58    get_reported_cost_result, get_task_field, get_task_field_direct, get_token_usage,
59    get_token_usage_result, opt_store_get_task, opt_store_get_task_by_id, resolve_store_id,
60    store_increment, store_increment_by_id, store_log_activity, store_reset_counters,
61    store_reset_failure_counters, store_set, store_set_by_id, store_set_result,
62    store_set_result_by_id, store_touch_updated_at,
63};
64pub use jobs::JobState;
65pub use metrics::{
66    AgentStat, CostByGroup, CostPeriod, CostSummary, ErrorStat, HighReviewCycleTask,
67    InsertTaskMetric, MetricsSummary, SlowTaskInfo,
68};
69use sqlx::error::DatabaseError;
70pub use tasks::{
71    CliTaskRef, CliTaskSpec, CompleteRun, NewTask, RunTokenUsage, StartRun, StatsEvents,
72    StatusChange, StoreRoute, Task, TaskActivity, TaskRun, TaskStatus, UpsertExternal,
73    parse_cli_task_spec,
74};
75use tokio::time;
76pub use usage::TokenUsage;
77
78use crate::cluster;
79use crate::cluster::Command;
80use crate::cluster::Node;
81use crate::cluster::Reply;
82use crate::cluster::Request;
83use crate::cluster::local;
84use crate::cluster::local::Endpoint;
85use crate::home;
86
87/// Default database path: `~/.orch/orch.db`
88pub async fn default_db_path() -> anyhow::Result<PathBuf> {
89    home::db_path().await
90}
91
92/// The unified task store backed by SQLite (via sqlx).
93#[derive(Clone)]
94pub struct TaskStore {
95    pool: SqlitePool,
96    /// Set once on the daemon. Without it, replicated writes apply directly, as in tests and the CLI
97    raft: Arc<OnceLock<Node>>,
98    /// Set on the CLI when a daemon runs, so its writes go through the daemon's log
99    daemon: Arc<OnceLock<Endpoint>>,
100}
101
102impl Debug for TaskStore {
103    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
104        f.debug_struct("TaskStore").finish_non_exhaustive()
105    }
106}
107
108impl TaskStore {
109    /// Open (or create) the store at the given database path.
110    ///
111    /// Runs file-based migrations from the `migrations/` directory.
112    pub async fn open(db_path: &Path) -> anyhow::Result<Self> {
113        let options = SqliteConnectOptions::new()
114            .filename(db_path)
115            .journal_mode(SqliteJournalMode::Wal)
116            .create_if_missing(true)
117            .busy_timeout(Duration::from_secs(5))
118            .pragma("foreign_keys", "ON");
119
120        let pool = SqlitePoolOptions::new()
121            .max_connections(5)
122            .connect_with(options)
123            .await
124            .with_context(|| format!("opening task store: {}", db_path.display()))?;
125
126        let store = Self {
127            pool,
128            raft: Arc::default(),
129            daemon: Arc::default(),
130        };
131        store.migrate().await?;
132        Ok(store)
133    }
134
135    /// Open a store with a single connection.
136    ///
137    /// Uses `max_connections(1)` to avoid WAL visibility issues where a write
138    /// on one pooled connection isn't visible to a read on another. Used by
139    /// integration tests that need read-your-own-writes consistency.
140    pub async fn open_single(db_path: &Path) -> anyhow::Result<Self> {
141        let options = SqliteConnectOptions::new()
142            .filename(db_path)
143            .journal_mode(SqliteJournalMode::Wal)
144            .create_if_missing(true)
145            .busy_timeout(Duration::from_secs(5))
146            .pragma("foreign_keys", "ON");
147
148        let pool = SqlitePoolOptions::new()
149            .max_connections(1)
150            .connect_with(options)
151            .await
152            .with_context(|| format!("opening task store (single): {}", db_path.display()))?;
153
154        let store = Self {
155            pool,
156            raft: Arc::default(),
157            daemon: Arc::default(),
158        };
159        store.migrate().await?;
160        Ok(store)
161    }
162
163    /// Open an in-memory store (for testing).
164    #[cfg(test)]
165    pub async fn open_memory() -> anyhow::Result<Self> {
166        let options = SqliteConnectOptions::new()
167            .filename(":memory:")
168            .pragma("foreign_keys", "ON");
169        let pool = SqlitePoolOptions::new()
170            .max_connections(1)
171            .connect_with(options)
172            .await?;
173
174        let store = Self {
175            pool,
176            raft: Arc::default(),
177            daemon: Arc::default(),
178        };
179        store.migrate().await?;
180        Ok(store)
181    }
182
183    /// Run migrations.
184    async fn migrate(&self) -> anyhow::Result<()> {
185        sqlx::migrate!("./migrations")
186            .run(&self.pool)
187            .await
188            .context("running task store migrations")?;
189        Ok(())
190    }
191
192    pub fn attach_node(&self, node: Node) {
193        if self.raft.set(node).is_err() {
194            tracing::warn!("raft already attached to the task store");
195        }
196    }
197
198    /// True on the node that decides: the Raft leader, or a store with no Raft, as in the CLI and tests.
199    /// A single node always leads, so one machine runs every phase as before
200    pub fn is_leader(&self) -> bool {
201        self.raft.get().is_none_or(super::cluster::Node::is_leader)
202    }
203
204    /// Writes go through Raft or a daemon that runs it, so they reach the other machines
205    pub(crate) fn replicates(&self) -> bool {
206        self.raft.get().is_some() || self.daemon.get().is_some()
207    }
208
209    pub fn node(&self) -> Option<&Node> {
210        self.raft.get()
211    }
212
213    pub fn attach_daemon(&self, endpoint: Endpoint) {
214        let _ = self.daemon.set(endpoint);
215    }
216
217    /// Propose a replicated write through Raft, or apply it directly when no Raft is attached
218    pub(crate) async fn write(&self, cmd: Command) -> anyhow::Result<Reply> {
219        let Some(node) = self.raft.get() else {
220            if let Some(endpoint) = self.daemon.get() {
221                match local::send(endpoint, &cmd).await {
222                    Ok(reply) => return reply_result(reply),
223                    // Nothing was sent, so applying here cannot apply the command twice
224                    Err(e) if e.is_connect() => {
225                        tracing::debug!(err = %e, "daemon not listening, writing directly");
226                    }
227                    Err(e) => return Err(e.into()),
228                }
229            }
230
231            return self.apply_direct(cmd).await;
232        };
233        let req = Request {
234            now: cluster::now_stamp(),
235            cmd,
236        };
237        reply_result(node.write(req).await?)
238    }
239
240    pub(crate) async fn write_int(&self, cmd: Command) -> anyhow::Result<i64> {
241        match self.write(cmd).await? {
242            Reply::Int(n) => Ok(n),
243            other => anyhow::bail!("expected an integer reply, got {other:?}"),
244        }
245    }
246
247    pub(crate) async fn write_bool(&self, cmd: Command) -> anyhow::Result<bool> {
248        match self.write(cmd).await? {
249            Reply::Bool(b) => Ok(b),
250            other => anyhow::bail!("expected a boolean reply, got {other:?}"),
251        }
252    }
253
254    /// The same SQL apply runs, in one transaction on this node only
255    pub(crate) async fn apply_direct(&self, cmd: Command) -> anyhow::Result<Reply> {
256        let mut attempt = 0;
257        loop {
258            match self.apply_once(cmd.clone()).await {
259                // A dropped transaction rolls back, so running the command again is safe
260                Err(e) if attempt < WRITE_LOCK_RETRIES && is_write_lock_error(&e) => {
261                    attempt += 1;
262                    tracing::warn!(attempt, err = %e, "database is locked, retrying the write");
263                    time::sleep(Duration::from_millis(100 << (attempt - 1))).await;
264                }
265                result => return result,
266            }
267        }
268    }
269
270    async fn apply_once(&self, cmd: Command) -> anyhow::Result<Reply> {
271        let mut tx = self.begin_write().await?;
272        let reply = cmd.apply(&mut tx, &cluster::now_stamp(), false).await?;
273        tx.commit().await?;
274        Ok(reply)
275    }
276
277    /// Start a transaction that holds the write lock from its first statement.
278    ///
279    /// A deferred `BEGIN` that reads and then writes fails at once with `database is locked` when
280    /// another connection commits in between, and `busy_timeout` cannot wait that out. `BEGIN
281    /// IMMEDIATE` waits for the lock up front, where `busy_timeout` applies
282    pub(crate) async fn begin_write(
283        &self,
284    ) -> sqlx::Result<sqlx::Transaction<'static, sqlx::Sqlite>> {
285        self.pool.begin_with("BEGIN IMMEDIATE").await
286    }
287
288    /// Get a reference to the underlying pool (for advanced queries).
289    pub fn pool(&self) -> &SqlitePool {
290        &self.pool
291    }
292}
293
294/// Retries for a write that still finds the database locked after `busy_timeout`
295const WRITE_LOCK_RETRIES: u32 = 4;
296
297/// `SQLITE_BUSY` (5) or `SQLITE_BUSY_SNAPSHOT` (517) anywhere in the error chain
298fn is_write_lock_error(err: &anyhow::Error) -> bool {
299    err.chain().any(|cause| {
300        cause
301            .downcast_ref::<sqlx::Error>()
302            .and_then(|e| e.as_database_error())
303            .and_then(DatabaseError::code)
304            .is_some_and(|code| code == "5" || code == "517")
305    })
306}
307
308fn reply_result(reply: Reply) -> anyhow::Result<Reply> {
309    match reply {
310        Reply::Err(e) => Err(anyhow::anyhow!(e)),
311        other => Ok(other),
312    }
313}
314
315impl TaskStore {
316    /// The replicated tables, task rows and kv rows a raft snapshot carries
317    pub(crate) async fn snapshot_rows(
318        &self,
319    ) -> anyhow::Result<(
320        BTreeMap<String, Vec<serde_json::Value>>,
321        Vec<serde_json::Value>,
322        Vec<kv::Row>,
323    )> {
324        let mut tables = BTreeMap::new();
325        for table in replica::TABLES {
326            tables.insert(
327                table.to_string(),
328                replica::table_rows(&self.pool, table).await?,
329            );
330        }
331        let tasks = tasks::replicated_rows(&self.pool).await?;
332        let kv = kv::replicated_rows(&self.pool).await?;
333        Ok((tables, tasks, kv))
334    }
335}