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 #[cfg(test)]
105 pub(crate) fail_job_state_writes: Arc<AtomicU32>,
106}
107
108impl Debug for TaskStore {
109 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
110 f.debug_struct("TaskStore").finish_non_exhaustive()
111 }
112}
113
114impl TaskStore {
115 pub async fn open(db_path: &Path) -> anyhow::Result<Self> {
119 let options = SqliteConnectOptions::new()
120 .filename(db_path)
121 .journal_mode(SqliteJournalMode::Wal)
122 .create_if_missing(true)
123 .busy_timeout(Duration::from_secs(5))
124 .pragma("foreign_keys", "ON");
125
126 let pool = SqlitePoolOptions::new()
127 .max_connections(5)
128 .connect_with(options)
129 .await
130 .with_context(|| format!("opening task store: {}", db_path.display()))?;
131
132 let store = Self::from_pool(pool);
133 store.migrate().await?;
134 Ok(store)
135 }
136
137 pub async fn open_single(db_path: &Path) -> anyhow::Result<Self> {
143 let options = SqliteConnectOptions::new()
144 .filename(db_path)
145 .journal_mode(SqliteJournalMode::Wal)
146 .create_if_missing(true)
147 .busy_timeout(Duration::from_secs(5))
148 .pragma("foreign_keys", "ON");
149
150 let pool = SqlitePoolOptions::new()
151 .max_connections(1)
152 .connect_with(options)
153 .await
154 .with_context(|| format!("opening task store (single): {}", db_path.display()))?;
155
156 let store = Self::from_pool(pool);
157 store.migrate().await?;
158 Ok(store)
159 }
160
161 #[cfg(test)]
163 pub async fn open_memory() -> anyhow::Result<Self> {
164 let options = SqliteConnectOptions::new()
165 .filename(":memory:")
166 .pragma("foreign_keys", "ON");
167 let pool = SqlitePoolOptions::new()
168 .max_connections(1)
169 .connect_with(options)
170 .await?;
171
172 let store = Self::from_pool(pool);
173 store.migrate().await?;
174 Ok(store)
175 }
176
177 fn from_pool(pool: SqlitePool) -> Self {
178 Self {
179 pool,
180 raft: Arc::default(),
181 daemon: Arc::default(),
182 #[cfg(test)]
183 fail_status_writes: Arc::new(AtomicU32::new(0)),
184 #[cfg(test)]
185 fail_job_state_writes: Arc::new(AtomicU32::new(0)),
186 }
187 }
188
189 async fn migrate(&self) -> anyhow::Result<()> {
191 sqlx::migrate!("./migrations")
192 .run(&self.pool)
193 .await
194 .context("running task store migrations")?;
195 Ok(())
196 }
197
198 pub fn attach_node(&self, node: Node) {
199 if self.raft.set(node).is_err() {
200 tracing::warn!("raft already attached to the task store");
201 }
202 }
203
204 pub fn is_leader(&self) -> bool {
207 self.raft.get().is_none_or(cluster::Node::is_leader)
208 }
209
210 pub(crate) fn replicates(&self) -> bool {
212 self.raft.get().is_some() || self.daemon.get().is_some()
213 }
214
215 pub fn node(&self) -> Option<&Node> {
216 self.raft.get()
217 }
218
219 pub fn attach_daemon(&self, endpoint: Endpoint) {
220 let _ = self.daemon.set(endpoint);
221 }
222
223 pub(crate) async fn write(&self, cmd: Command) -> anyhow::Result<Reply> {
225 let Some(node) = self.raft.get() else {
226 if let Some(endpoint) = self.daemon.get() {
227 match local::send(endpoint, &cmd).await {
228 Ok(reply) => return reply_result(reply),
229 Err(e) if e.is_connect() => {
231 tracing::debug!(err = %e, "daemon not listening, writing directly");
232 }
233 Err(e) => return Err(e.into()),
234 }
235 }
236
237 return self.apply_direct(cmd).await;
238 };
239 let req = Request {
240 now: now_stamp(),
241 cmd,
242 };
243 reply_result(node.write(req).await?)
244 }
245
246 pub(crate) async fn write_int(&self, cmd: Command) -> anyhow::Result<i64> {
247 match self.write(cmd).await? {
248 Reply::Int(n) => Ok(n),
249 other => anyhow::bail!("expected an integer reply, got {other:?}"),
250 }
251 }
252
253 pub(crate) async fn write_bool(&self, cmd: Command) -> anyhow::Result<bool> {
254 match self.write(cmd).await? {
255 Reply::Bool(b) => Ok(b),
256 other => anyhow::bail!("expected a boolean reply, got {other:?}"),
257 }
258 }
259
260 pub(crate) async fn apply_direct(&self, cmd: Command) -> anyhow::Result<Reply> {
262 let mut attempt = 0;
263 loop {
264 match self.apply_once(cmd.clone()).await {
265 Err(e) if attempt < WRITE_LOCK_RETRIES && is_write_lock_error(&e) => {
267 attempt += 1;
268 tracing::warn!(attempt, err = %e, "database is locked, retrying the write");
269 time::sleep(Duration::from_millis(100 << (attempt - 1))).await;
270 }
271 result => return result,
272 }
273 }
274 }
275
276 async fn apply_once(&self, cmd: Command) -> anyhow::Result<Reply> {
277 let mut tx = self.begin_write().await?;
278 let reply = cluster::apply::run(cmd, &mut tx, &now_stamp(), false).await?;
279 tx.commit().await?;
280 Ok(reply)
281 }
282
283 pub(crate) async fn begin_write(
289 &self,
290 ) -> sqlx::Result<sqlx::Transaction<'static, sqlx::Sqlite>> {
291 self.pool.begin_with("BEGIN IMMEDIATE").await
292 }
293
294 pub fn pool(&self) -> &SqlitePool {
296 &self.pool
297 }
298}
299
300const WRITE_LOCK_RETRIES: u32 = 4;
302
303fn is_write_lock_error(err: &anyhow::Error) -> bool {
305 err.chain().any(|cause| {
306 cause
307 .downcast_ref::<sqlx::Error>()
308 .and_then(|e| e.as_database_error())
309 .and_then(DatabaseError::code)
310 .is_some_and(|code| code == "5" || code == "517")
311 })
312}
313
314fn reply_result(reply: Reply) -> anyhow::Result<Reply> {
315 match reply {
316 Reply::Err(e) => Err(anyhow::anyhow!(e)),
317 other => Ok(other),
318 }
319}
320
321impl TaskStore {
322 pub(crate) async fn snapshot_rows(
324 &self,
325 ) -> anyhow::Result<(
326 BTreeMap<String, Vec<serde_json::Value>>,
327 Vec<serde_json::Value>,
328 Vec<kv::Row>,
329 )> {
330 let mut tables = BTreeMap::new();
331 for table in replica::TABLES {
332 tables.insert(
333 table.to_string(),
334 replica::table_rows(&self.pool, table).await?,
335 );
336 }
337 let tasks = tasks::replicated_rows(&self.pool).await?;
338 let kv = kv::replicated_rows(&self.pool).await?;
339 Ok((tables, tasks, kv))
340 }
341}
342
343type Updates = Vec<(String, serde_json::Value)>;
344
345#[derive(Serialize, Deserialize, Clone, Debug)]
347pub struct Request {
348 pub now: String,
349 pub cmd: Command,
350}
351
352#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
353#[serde(tag = "op", rename_all = "snake_case")]
354pub enum Command {
355 KvSet {
356 key: String,
357 value: String,
358 },
359 KvIncrement {
360 key: String,
361 },
362 KvInsertIfAbsent {
363 key: String,
364 value: String,
365 },
366 KvDelete {
367 key: String,
368 },
369 TaskCreate {
370 new: NewTask,
371 internal: bool,
372 },
373 TaskUpsertExternal(UpsertExternalCmd),
374 TaskUpdateStatusAndFields {
375 id: i64,
376 status: TaskStatus,
377 updates: Updates,
378 },
379 TaskUpdateStatus {
380 id: i64,
381 status: TaskStatus,
382 expected: Option<TaskStatus>,
383 },
384 TaskUpdateExternalId {
385 id: i64,
386 external_id: String,
387 },
388 TaskTouch {
389 id: i64,
390 },
391 TaskResetToNew {
392 id: i64,
393 #[serde(default)]
394 keep_branch: bool,
395 },
396 TaskSetFields {
397 id: i64,
398 updates: Updates,
399 silent: bool,
400 },
401 TaskIncrement {
402 id: i64,
403 field: String,
404 },
405 TaskResetCounters {
406 id: i64,
407 failure_only: bool,
408 },
409 TaskStoreRoute(StoreRouteCmd),
410 TaskSetEstimateIfZero {
411 id: i64,
412 estimate: u8,
413 },
414 TaskAppendMemory {
415 id: i64,
416 entry: MemoryEntry,
417 },
418 TaskMarkCleaned {
419 id: i64,
420 },
421 MoveRepo {
422 old: String,
423 new: String,
424 },
425 DepReplace {
426 task_id: i64,
427 rows: Vec<NewDependency>,
428 },
429 DepLinkKnown {
430 task_id: i64,
431 repo: String,
432 number: i64,
433 },
434 DepBlockClaim {
435 task_id: i64,
436 },
437 JobStateUpsert(JobState),
438 ChannelSubscribe {
439 channel: String,
440 thread_id: String,
441 repo: String,
442 topic_id: String,
443 },
444 ChannelUnsubscribe {
445 channel: String,
446 thread_id: String,
447 repo: String,
448 },
449}
450
451#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
453pub enum Reply {
454 Done,
455 Bool(bool),
456 Int(i64),
457 Count(u64),
458 Value(String),
459 Unmet(Option<Vec<String>>),
460 Err(String),
461}
462
463impl Command {
464 pub(crate) fn check_replicable(&self) -> anyhow::Result<()> {
467 let key = match self {
468 Command::KvSet { key, .. }
469 | Command::KvIncrement { key }
470 | Command::KvInsertIfAbsent { key, .. }
471 | Command::KvDelete { key } => Some(key),
472 _ => None,
473 };
474 if let Some(key) = key {
475 anyhow::ensure!(
476 !kv::is_local(key),
477 "{key} is local to each node, never replicated"
478 );
479 }
480
481 let updates = match self {
482 Command::TaskSetFields { updates, .. }
483 | Command::TaskUpdateStatusAndFields { updates, .. } => &updates[..],
484 _ => &[],
485 };
486 if let Some((col, _)) = updates.iter().find(|(col, _)| tasks::is_local_column(col)) {
487 anyhow::bail!("{col} is local to each node, never replicated");
488 }
489
490 Ok(())
491 }
492}
493
494pub fn now_stamp() -> String {
496 chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
497}
498
499pub type KvRow = kv::Row;
501
502pub(crate) async fn put_kv(
504 conn: &mut SqliteConnection,
505 now: &str,
506 key: &str,
507 value: &str,
508) -> anyhow::Result<()> {
509 kv::set(conn, now, key, value).await
510}
511
512pub(crate) async fn replace_snapshot_rows(
514 conn: &mut SqliteConnection,
515 tables: &BTreeMap<String, Vec<serde_json::Value>>,
516 task_rows: &[serde_json::Value],
517 kv_rows: &[KvRow],
518) -> anyhow::Result<()> {
519 tasks::replace_replicated(conn, task_rows).await?;
520 for table in replica::TABLES {
521 let rows = tables.get(table).map(Vec::as_slice).unwrap_or_default();
522 replica::replace_table(conn, table, rows).await?;
523 }
524 kv::replace_replicated(conn, kv_rows).await
525}