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 mod cluster;
27pub(crate) mod control;
28pub(crate) mod dependencies;
29mod helpers;
30pub(crate) mod jobs;
31pub(crate) mod kv;
32mod metrics;
33pub(crate) mod replica;
34pub(crate) mod tasks;
35
36#[cfg(test)]
37mod tests;
38mod usage;
39
40use anyhow::Context;
41use serde::{Deserialize, Serialize};
42use sqlx::SqliteConnection;
43use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions};
44use std::collections::BTreeMap;
45use std::fmt;
46use std::fmt::Debug;
47use std::fmt::Formatter;
48use std::path::Path;
49use std::path::PathBuf;
50use std::sync::{Arc, OnceLock};
51use std::time::Duration;
52use tasks::{StoreRouteCmd, UpsertExternalCmd};
53
54pub use control::{ChatCostSummary, ControlMessage, MemoryEntry, parse_since_duration};
55pub use dependencies::{
56    BlockerSnapshot, DepSource, NewDependency, ObservedPullRequest, TaskDependency,
57    WaitingOnDependency, blocker_failure_kind, blocker_is_satisfied, blocker_snapshot_key,
58    dep_label, worktree_refresh_key,
59};
60pub use helpers::{
61    StoreResult, get_recent_memory, get_recent_memory_result, get_reported_cost,
62    get_reported_cost_result, get_task_field, get_task_field_direct, get_token_usage,
63    get_token_usage_result, opt_store_get_task, opt_store_get_task_by_id, resolve_store_id,
64    store_increment, store_increment_by_id, store_log_activity, store_reset_counters,
65    store_reset_failure_counters, store_set, store_set_by_id, store_set_result,
66    store_set_result_by_id, store_touch_updated_at,
67};
68pub use jobs::JobState;
69pub use metrics::{
70    AgentStat, CostByGroup, CostPeriod, CostSummary, ErrorStat, HighReviewCycleTask,
71    InsertTaskMetric, MetricsSummary, SlowTaskInfo,
72};
73use sqlx::error::DatabaseError;
74pub use tasks::{
75    CliTaskRef, CliTaskSpec, CompleteRun, NewTask, RunTokenUsage, StartRun, StatsEvents,
76    StatusChange, StoreRoute, Task, TaskActivity, TaskRun, TaskStatus, UpsertExternal,
77    parse_cli_task_spec,
78};
79use tokio::time;
80pub use usage::TokenUsage;
81
82use crate::sys::home;
83use cluster::Node;
84use cluster::local;
85use cluster::local::Endpoint;
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(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: 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 = cluster::apply::run(cmd, &mut tx, &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}
336
337type Updates = Vec<(String, serde_json::Value)>;
338
339/// One replicated write. The proposer stamps `now`, so every node applies the same value
340#[derive(Serialize, Deserialize, Clone, Debug)]
341pub struct Request {
342    pub now: String,
343    pub cmd: Command,
344}
345
346#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
347#[serde(tag = "op", rename_all = "snake_case")]
348pub enum Command {
349    KvSet {
350        key: String,
351        value: String,
352    },
353    KvIncrement {
354        key: String,
355    },
356    KvInsertIfAbsent {
357        key: String,
358        value: String,
359    },
360    KvDelete {
361        key: String,
362    },
363    TaskCreate {
364        new: NewTask,
365        internal: bool,
366    },
367    TaskUpsertExternal(UpsertExternalCmd),
368    TaskUpdateStatusAndFields {
369        id: i64,
370        status: TaskStatus,
371        updates: Updates,
372    },
373    TaskUpdateStatus {
374        id: i64,
375        status: TaskStatus,
376        expected: Option<TaskStatus>,
377    },
378    TaskUpdateExternalId {
379        id: i64,
380        external_id: String,
381    },
382    TaskTouch {
383        id: i64,
384    },
385    TaskResetToNew {
386        id: i64,
387        #[serde(default)]
388        keep_branch: bool,
389    },
390    TaskSetFields {
391        id: i64,
392        updates: Updates,
393        silent: bool,
394    },
395    TaskIncrement {
396        id: i64,
397        field: String,
398    },
399    TaskResetCounters {
400        id: i64,
401        failure_only: bool,
402    },
403    TaskStoreRoute(StoreRouteCmd),
404    TaskSetEstimateIfZero {
405        id: i64,
406        estimate: u8,
407    },
408    TaskAppendMemory {
409        id: i64,
410        entry: MemoryEntry,
411    },
412    TaskMarkCleaned {
413        id: i64,
414    },
415    MoveRepo {
416        old: String,
417        new: String,
418    },
419    DepReplace {
420        task_id: i64,
421        rows: Vec<NewDependency>,
422    },
423    DepLinkKnown {
424        task_id: i64,
425        repo: String,
426        number: i64,
427    },
428    DepBlockClaim {
429        task_id: i64,
430    },
431    JobStateUpsert(JobState),
432    ChannelSubscribe {
433        channel: String,
434        thread_id: String,
435        repo: String,
436        topic_id: String,
437    },
438    ChannelUnsubscribe {
439        channel: String,
440        thread_id: String,
441        repo: String,
442    },
443}
444
445/// A failed command is `Err` on every node, so one bad command cannot stop the state machine
446#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
447pub enum Reply {
448    Done,
449    Bool(bool),
450    Int(i64),
451    Count(u64),
452    Value(String),
453    Unmet(Option<Vec<String>>),
454    Err(String),
455}
456
457impl Command {
458    /// A write through the log may not touch this node's own state: a local kv key, such as its
459    /// Raft position, or a local task column, such as the worktree path that cleanup removes
460    pub(crate) fn check_replicable(&self) -> anyhow::Result<()> {
461        let key = match self {
462            Command::KvSet { key, .. }
463            | Command::KvIncrement { key }
464            | Command::KvInsertIfAbsent { key, .. }
465            | Command::KvDelete { key } => Some(key),
466            _ => None,
467        };
468        if let Some(key) = key {
469            anyhow::ensure!(
470                !kv::is_local(key),
471                "{key} is local to each node, never replicated"
472            );
473        }
474
475        let updates = match self {
476            Command::TaskSetFields { updates, .. }
477            | Command::TaskUpdateStatusAndFields { updates, .. } => &updates[..],
478            _ => &[],
479        };
480        if let Some((col, _)) = updates.iter().find(|(col, _)| tasks::is_local_column(col)) {
481            anyhow::bail!("{col} is local to each node, never replicated");
482        }
483
484        Ok(())
485    }
486}
487
488/// The proposer's clock, in the format the store writes timestamps in
489pub fn now_stamp() -> String {
490    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
491}
492
493/// A kv row as a raft snapshot carries it
494pub type KvRow = kv::Row;
495
496/// Write a kv value inside a raft storage transaction
497pub(crate) async fn put_kv(
498    conn: &mut SqliteConnection,
499    now: &str,
500    key: &str,
501    value: &str,
502) -> anyhow::Result<()> {
503    kv::set(conn, now, key, value).await
504}
505
506/// Replace the replicated rows with a raft snapshot's
507pub(crate) async fn replace_snapshot_rows(
508    conn: &mut SqliteConnection,
509    tables: &BTreeMap<String, Vec<serde_json::Value>>,
510    task_rows: &[serde_json::Value],
511    kv_rows: &[KvRow],
512) -> anyhow::Result<()> {
513    tasks::replace_replicated(conn, task_rows).await?;
514    for table in replica::TABLES {
515        let rows = tables.get(table).map(Vec::as_slice).unwrap_or_default();
516        replica::replace_table(conn, table, rows).await?;
517    }
518    kv::replace_replicated(conn, kv_rows).await
519}