1pub 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;
50#[cfg(test)]
51use std::sync::atomic::AtomicU32;
52use std::sync::{Arc, OnceLock};
53use std::time::Duration;
54use tasks::{StoreRouteCmd, UpsertExternalCmd};
55
56pub use control::{ChatCostSummary, ControlMessage, MemoryEntry, parse_since_duration};
57pub use dependencies::{
58 BlockerSnapshot, DepSource, NewDependency, ObservedPullRequest, TaskDependency,
59 WaitingOnDependency, blocker_failure_kind, blocker_is_satisfied, blocker_snapshot_key,
60 dep_label, worktree_refresh_key,
61};
62pub use helpers::{
63 StoreResult, get_recent_memory, get_recent_memory_result, get_reported_cost,
64 get_reported_cost_result, get_task_field, get_task_field_direct, get_token_usage,
65 get_token_usage_result, opt_store_get_task, opt_store_get_task_by_id, resolve_store_id,
66 store_increment, store_increment_by_id, store_log_activity, store_reset_counters,
67 store_reset_failure_counters, store_set, store_set_by_id, store_set_result,
68 store_set_result_by_id, store_touch_updated_at,
69};
70pub use jobs::JobState;
71pub use metrics::{
72 AgentStat, CostByGroup, CostPeriod, CostSummary, ErrorStat, HighReviewCycleTask,
73 InsertTaskMetric, MetricsSummary, SlowTaskInfo,
74};
75use sqlx::error::DatabaseError;
76pub use tasks::{
77 CliTaskRef, CliTaskSpec, CompleteRun, NewTask, RunTokenUsage, StartRun, StatsEvents,
78 StatusChange, StoreRoute, Task, TaskActivity, TaskRun, TaskStatus, UpsertExternal,
79 parse_cli_task_spec,
80};
81use tokio::time;
82pub use usage::TokenUsage;
83
84use crate::sys::home;
85use cluster::Node;
86use cluster::local;
87use cluster::local::Endpoint;
88
89pub async fn default_db_path() -> anyhow::Result<PathBuf> {
91 home::db_path().await
92}
93
94#[derive(Clone)]
96pub struct TaskStore {
97 pool: SqlitePool,
98 raft: Arc<OnceLock<Node>>,
100 daemon: Arc<OnceLock<Endpoint>>,
102 #[cfg(test)]
103 pub(crate) fail_status_writes: Arc<AtomicU32>,
104}
105
106impl Debug for TaskStore {
107 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
108 f.debug_struct("TaskStore").finish_non_exhaustive()
109 }
110}
111
112impl TaskStore {
113 pub async fn open(db_path: &Path) -> anyhow::Result<Self> {
117 let options = SqliteConnectOptions::new()
118 .filename(db_path)
119 .journal_mode(SqliteJournalMode::Wal)
120 .create_if_missing(true)
121 .busy_timeout(Duration::from_secs(5))
122 .pragma("foreign_keys", "ON");
123
124 let pool = SqlitePoolOptions::new()
125 .max_connections(5)
126 .connect_with(options)
127 .await
128 .with_context(|| format!("opening task store: {}", db_path.display()))?;
129
130 let store = Self::from_pool(pool);
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::from_pool(pool);
155 store.migrate().await?;
156 Ok(store)
157 }
158
159 #[cfg(test)]
161 pub async fn open_memory() -> anyhow::Result<Self> {
162 let options = SqliteConnectOptions::new()
163 .filename(":memory:")
164 .pragma("foreign_keys", "ON");
165 let pool = SqlitePoolOptions::new()
166 .max_connections(1)
167 .connect_with(options)
168 .await?;
169
170 let store = Self::from_pool(pool);
171 store.migrate().await?;
172 Ok(store)
173 }
174
175 fn from_pool(pool: SqlitePool) -> Self {
176 Self {
177 pool,
178 raft: Arc::default(),
179 daemon: Arc::default(),
180 #[cfg(test)]
181 fail_status_writes: Arc::new(AtomicU32::new(0)),
182 }
183 }
184
185 async fn migrate(&self) -> anyhow::Result<()> {
187 sqlx::migrate!("./migrations")
188 .run(&self.pool)
189 .await
190 .context("running task store migrations")?;
191 Ok(())
192 }
193
194 pub fn attach_node(&self, node: Node) {
195 if self.raft.set(node).is_err() {
196 tracing::warn!("raft already attached to the task store");
197 }
198 }
199
200 pub fn is_leader(&self) -> bool {
203 self.raft.get().is_none_or(cluster::Node::is_leader)
204 }
205
206 pub(crate) fn replicates(&self) -> bool {
208 self.raft.get().is_some() || self.daemon.get().is_some()
209 }
210
211 pub fn node(&self) -> Option<&Node> {
212 self.raft.get()
213 }
214
215 pub fn attach_daemon(&self, endpoint: Endpoint) {
216 let _ = self.daemon.set(endpoint);
217 }
218
219 pub(crate) async fn write(&self, cmd: Command) -> anyhow::Result<Reply> {
221 let Some(node) = self.raft.get() else {
222 if let Some(endpoint) = self.daemon.get() {
223 match local::send(endpoint, &cmd).await {
224 Ok(reply) => return reply_result(reply),
225 Err(e) if e.is_connect() => {
227 tracing::debug!(err = %e, "daemon not listening, writing directly");
228 }
229 Err(e) => return Err(e.into()),
230 }
231 }
232
233 return self.apply_direct(cmd).await;
234 };
235 let req = Request {
236 now: now_stamp(),
237 cmd,
238 };
239 reply_result(node.write(req).await?)
240 }
241
242 pub(crate) async fn write_int(&self, cmd: Command) -> anyhow::Result<i64> {
243 match self.write(cmd).await? {
244 Reply::Int(n) => Ok(n),
245 other => anyhow::bail!("expected an integer reply, got {other:?}"),
246 }
247 }
248
249 pub(crate) async fn write_bool(&self, cmd: Command) -> anyhow::Result<bool> {
250 match self.write(cmd).await? {
251 Reply::Bool(b) => Ok(b),
252 other => anyhow::bail!("expected a boolean reply, got {other:?}"),
253 }
254 }
255
256 pub(crate) async fn apply_direct(&self, cmd: Command) -> anyhow::Result<Reply> {
258 let mut attempt = 0;
259 loop {
260 match self.apply_once(cmd.clone()).await {
261 Err(e) if attempt < WRITE_LOCK_RETRIES && is_write_lock_error(&e) => {
263 attempt += 1;
264 tracing::warn!(attempt, err = %e, "database is locked, retrying the write");
265 time::sleep(Duration::from_millis(100 << (attempt - 1))).await;
266 }
267 result => return result,
268 }
269 }
270 }
271
272 async fn apply_once(&self, cmd: Command) -> anyhow::Result<Reply> {
273 let mut tx = self.begin_write().await?;
274 let reply = cluster::apply::run(cmd, &mut tx, &now_stamp(), false).await?;
275 tx.commit().await?;
276 Ok(reply)
277 }
278
279 pub(crate) async fn begin_write(
285 &self,
286 ) -> sqlx::Result<sqlx::Transaction<'static, sqlx::Sqlite>> {
287 self.pool.begin_with("BEGIN IMMEDIATE").await
288 }
289
290 pub fn pool(&self) -> &SqlitePool {
292 &self.pool
293 }
294}
295
296const WRITE_LOCK_RETRIES: u32 = 4;
298
299fn is_write_lock_error(err: &anyhow::Error) -> bool {
301 err.chain().any(|cause| {
302 cause
303 .downcast_ref::<sqlx::Error>()
304 .and_then(|e| e.as_database_error())
305 .and_then(DatabaseError::code)
306 .is_some_and(|code| code == "5" || code == "517")
307 })
308}
309
310fn reply_result(reply: Reply) -> anyhow::Result<Reply> {
311 match reply {
312 Reply::Err(e) => Err(anyhow::anyhow!(e)),
313 other => Ok(other),
314 }
315}
316
317impl TaskStore {
318 pub(crate) async fn snapshot_rows(
320 &self,
321 ) -> anyhow::Result<(
322 BTreeMap<String, Vec<serde_json::Value>>,
323 Vec<serde_json::Value>,
324 Vec<kv::Row>,
325 )> {
326 let mut tables = BTreeMap::new();
327 for table in replica::TABLES {
328 tables.insert(
329 table.to_string(),
330 replica::table_rows(&self.pool, table).await?,
331 );
332 }
333 let tasks = tasks::replicated_rows(&self.pool).await?;
334 let kv = kv::replicated_rows(&self.pool).await?;
335 Ok((tables, tasks, kv))
336 }
337}
338
339type Updates = Vec<(String, serde_json::Value)>;
340
341#[derive(Serialize, Deserialize, Clone, Debug)]
343pub struct Request {
344 pub now: String,
345 pub cmd: Command,
346}
347
348#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
349#[serde(tag = "op", rename_all = "snake_case")]
350pub enum Command {
351 KvSet {
352 key: String,
353 value: String,
354 },
355 KvIncrement {
356 key: String,
357 },
358 KvInsertIfAbsent {
359 key: String,
360 value: String,
361 },
362 KvDelete {
363 key: String,
364 },
365 TaskCreate {
366 new: NewTask,
367 internal: bool,
368 },
369 TaskUpsertExternal(UpsertExternalCmd),
370 TaskUpdateStatusAndFields {
371 id: i64,
372 status: TaskStatus,
373 updates: Updates,
374 },
375 TaskUpdateStatus {
376 id: i64,
377 status: TaskStatus,
378 expected: Option<TaskStatus>,
379 },
380 TaskUpdateExternalId {
381 id: i64,
382 external_id: String,
383 },
384 TaskTouch {
385 id: i64,
386 },
387 TaskResetToNew {
388 id: i64,
389 #[serde(default)]
390 keep_branch: bool,
391 },
392 TaskSetFields {
393 id: i64,
394 updates: Updates,
395 silent: bool,
396 },
397 TaskIncrement {
398 id: i64,
399 field: String,
400 },
401 TaskResetCounters {
402 id: i64,
403 failure_only: bool,
404 },
405 TaskStoreRoute(StoreRouteCmd),
406 TaskSetEstimateIfZero {
407 id: i64,
408 estimate: u8,
409 },
410 TaskAppendMemory {
411 id: i64,
412 entry: MemoryEntry,
413 },
414 TaskMarkCleaned {
415 id: i64,
416 },
417 MoveRepo {
418 old: String,
419 new: String,
420 },
421 DepReplace {
422 task_id: i64,
423 rows: Vec<NewDependency>,
424 },
425 DepLinkKnown {
426 task_id: i64,
427 repo: String,
428 number: i64,
429 },
430 DepBlockClaim {
431 task_id: i64,
432 },
433 JobStateUpsert(JobState),
434 ChannelSubscribe {
435 channel: String,
436 thread_id: String,
437 repo: String,
438 topic_id: String,
439 },
440 ChannelUnsubscribe {
441 channel: String,
442 thread_id: String,
443 repo: String,
444 },
445}
446
447#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
449pub enum Reply {
450 Done,
451 Bool(bool),
452 Int(i64),
453 Count(u64),
454 Value(String),
455 Unmet(Option<Vec<String>>),
456 Err(String),
457}
458
459impl Command {
460 pub(crate) fn check_replicable(&self) -> anyhow::Result<()> {
463 let key = match self {
464 Command::KvSet { key, .. }
465 | Command::KvIncrement { key }
466 | Command::KvInsertIfAbsent { key, .. }
467 | Command::KvDelete { key } => Some(key),
468 _ => None,
469 };
470 if let Some(key) = key {
471 anyhow::ensure!(
472 !kv::is_local(key),
473 "{key} is local to each node, never replicated"
474 );
475 }
476
477 let updates = match self {
478 Command::TaskSetFields { updates, .. }
479 | Command::TaskUpdateStatusAndFields { updates, .. } => &updates[..],
480 _ => &[],
481 };
482 if let Some((col, _)) = updates.iter().find(|(col, _)| tasks::is_local_column(col)) {
483 anyhow::bail!("{col} is local to each node, never replicated");
484 }
485
486 Ok(())
487 }
488}
489
490pub fn now_stamp() -> String {
492 chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
493}
494
495pub type KvRow = kv::Row;
497
498pub(crate) async fn put_kv(
500 conn: &mut SqliteConnection,
501 now: &str,
502 key: &str,
503 value: &str,
504) -> anyhow::Result<()> {
505 kv::set(conn, now, key, value).await
506}
507
508pub(crate) async fn replace_snapshot_rows(
510 conn: &mut SqliteConnection,
511 tables: &BTreeMap<String, Vec<serde_json::Value>>,
512 task_rows: &[serde_json::Value],
513 kv_rows: &[KvRow],
514) -> anyhow::Result<()> {
515 tasks::replace_replicated(conn, task_rows).await?;
516 for table in replica::TABLES {
517 let rows = tables.get(table).map(Vec::as_slice).unwrap_or_default();
518 replica::replace_table(conn, table, rows).await?;
519 }
520 kv::replace_replicated(conn, kv_rows).await
521}