1pub(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
87pub async fn default_db_path() -> anyhow::Result<PathBuf> {
89 home::db_path().await
90}
91
92#[derive(Clone)]
94pub struct TaskStore {
95 pool: SqlitePool,
96 raft: Arc<OnceLock<Node>>,
98 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 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 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 #[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 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 pub fn is_leader(&self) -> bool {
201 self.raft.get().is_none_or(super::cluster::Node::is_leader)
202 }
203
204 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 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 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 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 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 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 pub fn pool(&self) -> &SqlitePool {
290 &self.pool
291 }
292}
293
294const WRITE_LOCK_RETRIES: u32 = 4;
296
297fn 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 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}