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;
50use std::sync::{Arc, OnceLock};
51use std::time::Duration;
52use tasks::{StoreRouteCmd, UpsertExternalCmd, apply};
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::home;
83use cluster::Node;
84use cluster::local;
85use cluster::local::Endpoint;
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(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: 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, &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}
336
337type Updates = Vec<(String, serde_json::Value)>;
338
339#[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#[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 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 pub(crate) async fn apply(
490 self,
491 conn: &mut SqliteConnection,
492 now: &str,
493 replicated: bool,
494 ) -> anyhow::Result<Reply> {
495 if replicated {
496 self.check_replicable()?;
497 }
498
499 Ok(match self {
500 Command::KvSet { key, value } => {
501 kv::set(conn, now, &key, &value).await?;
502 Reply::Done
503 }
504 Command::KvIncrement { key } => Reply::Count(kv::increment(conn, now, &key).await?),
505 Command::KvInsertIfAbsent { key, value } => {
506 Reply::Value(kv::insert_if_absent(conn, now, &key, &value).await?)
507 }
508 Command::KvDelete { key } => {
509 kv::delete(conn, &key).await?;
510 Reply::Done
511 }
512 Command::TaskCreate { new, internal } => {
513 Reply::Int(apply::create(conn, now, &new, internal, replicated).await?)
514 }
515 Command::TaskUpsertExternal(ext) => {
516 Reply::Int(apply::upsert_external(conn, now, &ext, replicated).await?)
517 }
518 Command::TaskUpdateStatusAndFields {
519 id,
520 status,
521 updates,
522 } => {
523 apply::update_status_and_fields(conn, now, id, status, &updates).await?;
524 Reply::Done
525 }
526 Command::TaskUpdateStatus {
527 id,
528 status,
529 expected,
530 } => Reply::Bool(apply::update_status(conn, now, id, status, expected).await?),
531 Command::TaskUpdateExternalId { id, external_id } => {
532 apply::update_external_id(conn, now, id, &external_id).await?;
533 Reply::Done
534 }
535 Command::TaskTouch { id } => {
536 apply::touch(conn, now, id).await?;
537 Reply::Done
538 }
539 Command::TaskResetToNew { id, keep_branch } => {
540 apply::reset_to_new(conn, now, id, keep_branch).await?;
541 Reply::Done
542 }
543 Command::TaskSetFields {
544 id,
545 updates,
546 silent,
547 } => {
548 apply::set_fields(conn, now, id, &updates, silent).await?;
549 Reply::Done
550 }
551 Command::TaskIncrement { id, field } => {
552 Reply::Int(apply::increment(conn, now, id, &field).await?)
553 }
554 Command::TaskResetCounters { id, failure_only } => {
555 apply::reset_counters(conn, now, id, failure_only).await?;
556 Reply::Done
557 }
558 Command::TaskStoreRoute(route) => {
559 apply::store_route(conn, now, &route).await?;
560 Reply::Done
561 }
562 Command::TaskSetEstimateIfZero { id, estimate } => {
563 Reply::Bool(apply::set_estimate_if_zero(conn, now, id, estimate).await?)
564 }
565 Command::TaskAppendMemory { id, entry } => {
566 apply::append_memory(conn, now, id, &entry).await?;
567 Reply::Done
568 }
569 Command::TaskMarkCleaned { id } => {
570 apply::mark_cleaned(conn, now, id).await?;
571 Reply::Done
572 }
573 Command::MoveRepo { old, new } => {
574 let moved = dependencies::apply::move_repo(conn, &old, &new).await?;
575 Reply::Int(i64::try_from(moved)?)
576 }
577 Command::DepReplace { task_id, rows } => {
578 dependencies::apply::replace_dependencies(conn, task_id, &rows).await?;
579 Reply::Done
580 }
581 Command::DepLinkKnown {
582 task_id,
583 repo,
584 number,
585 } => {
586 dependencies::apply::link_known_task(conn, task_id, &repo, number).await?;
587 Reply::Done
588 }
589 Command::DepBlockClaim { task_id } => {
590 Reply::Unmet(dependencies::apply::block_claim(conn, now, task_id).await?)
591 }
592 Command::JobStateUpsert(state) => {
593 jobs::apply::upsert_job_state(conn, &state).await?;
594 Reply::Done
595 }
596 Command::ChannelSubscribe {
597 channel,
598 thread_id,
599 repo,
600 topic_id,
601 } => {
602 jobs::apply::subscribe(conn, &channel, &thread_id, &repo, &topic_id).await?;
603 Reply::Done
604 }
605 Command::ChannelUnsubscribe {
606 channel,
607 thread_id,
608 repo,
609 } => {
610 jobs::apply::unsubscribe(conn, &channel, &thread_id, &repo).await?;
611 Reply::Done
612 }
613 })
614 }
615}
616
617pub fn now_stamp() -> String {
619 chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
620}
621
622pub type KvRow = kv::Row;
624
625pub(crate) async fn put_kv(
627 conn: &mut SqliteConnection,
628 now: &str,
629 key: &str,
630 value: &str,
631) -> anyhow::Result<()> {
632 kv::set(conn, now, key, value).await
633}
634
635pub(crate) async fn replace_snapshot_rows(
637 conn: &mut SqliteConnection,
638 tables: &BTreeMap<String, Vec<serde_json::Value>>,
639 task_rows: &[serde_json::Value],
640 kv_rows: &[KvRow],
641) -> anyhow::Result<()> {
642 tasks::replace_replicated(conn, task_rows).await?;
643 for table in replica::TABLES {
644 let rows = tables.get(table).map(Vec::as_slice).unwrap_or_default();
645 replica::replace_table(conn, table, rows).await?;
646 }
647 kv::replace_replicated(conn, kv_rows).await
648}