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