Skip to main content

orch/store/tasks/
fields.rs

1//! Task field, counter and route writes
2
3#[cfg(test)]
4use super::{ALLOWED_FIELDS, TASK_COLS, Task, sql_value_for_task_field};
5use super::{
6    INCREMENTABLE_FIELDS, StoreRoute, StoreRouteCmd, apply, is_local_column, owned_updates,
7};
8use crate::store::Command;
9use crate::store::TaskStore;
10use crate::store::now_stamp;
11use sqlx::Row;
12use std::collections::HashSet;
13
14impl TaskStore {
15    /// Aggregate cost and token data for a repo.
16    /// Returns (total_input_tokens, total_output_tokens, total_cost_usd).
17    pub async fn set_fields(
18        &self,
19        id: i64,
20        updates: &[(&str, serde_json::Value)],
21    ) -> anyhow::Result<()> {
22        self.set_fields_split(id, updates, false).await
23    }
24
25    /// Like `set_fields` but does NOT touch `updated_at`.
26    ///
27    /// Use this for internal bookkeeping writes (probe timestamps, counters) that
28    /// must not make a stale task appear recently-modified to triage queries.
29    pub async fn set_fields_silent(
30        &self,
31        id: i64,
32        updates: &[(&str, serde_json::Value)],
33    ) -> anyhow::Result<()> {
34        self.set_fields_split(id, updates, true).await
35    }
36
37    /// Local columns are written on this node only, the rest go through the log
38    async fn set_fields_split(
39        &self,
40        id: i64,
41        updates: &[(&str, serde_json::Value)],
42        silent: bool,
43    ) -> anyhow::Result<()> {
44        let all = owned_updates(updates)?;
45        // On one machine nothing is replicated, so the whole update stays one statement
46        if !self.replicates() {
47            let mut tx = self.begin_write().await?;
48            apply::set_fields(&mut tx, &now_stamp(), id, &all, silent).await?;
49            tx.commit().await?;
50            return Ok(());
51        }
52
53        let (local, replicated): (Vec<_>, Vec<_>) =
54            all.into_iter().partition(|(col, _)| is_local_column(col));
55        if !local.is_empty() {
56            let mut tx = self.begin_write().await?;
57            apply::set_fields(&mut tx, &now_stamp(), id, &local, silent).await?;
58            tx.commit().await?;
59        }
60
61        if replicated.is_empty() {
62            return Ok(());
63        }
64
65        self.write(Command::TaskSetFields {
66            id,
67            updates: replicated,
68            silent,
69        })
70        .await
71        .map(|_| ())
72    }
73
74    /// Increment an integer field by 1, returning the new value.
75    pub async fn increment(&self, id: i64, field: &str) -> anyhow::Result<i32> {
76        anyhow::ensure!(
77            INCREMENTABLE_FIELDS.contains(&field),
78            "field {field} is not incrementable"
79        );
80        let n = self
81            .write_int(Command::TaskIncrement {
82                id,
83                field: field.to_string(),
84            })
85            .await?;
86        Ok(i32::try_from(n)?)
87    }
88
89    /// Reset all failure/retry counters to zero.
90    pub async fn reset_counters(&self, id: i64) -> anyhow::Result<()> {
91        self.write(Command::TaskResetCounters {
92            id,
93            failure_only: false,
94        })
95        .await
96        .map(|_| ())
97    }
98
99    /// Reset transient failure/retry counters to zero, preserving
100    /// `review_cycles`, `ci_merge_failures`, and `merge_conflict_retries`.
101    ///
102    /// Use this after `RequestChanges` to clear per-attempt noise without
103    /// undoing the review-cycle count that `handle_review_changes` just set.
104    /// `ci_merge_failures` and `merge_conflict_retries` are preserved here because
105    /// they must accumulate across attempts to enforce their circuit breakers,
106    /// just like `review_cycles`.
107    ///
108    /// NOTE: `attempts` and `review_invocations` are intentionally NOT reset here.
109    /// Both must increase monotonically across the task's lifetime so that
110    /// `(task_id, attempt, run_type)` keys in `task_runs` remain unique. Resetting
111    /// either causes subsequent retries to overwrite earlier audit trail records via
112    /// the ON CONFLICT UPSERT in `start_run()`.
113    pub async fn reset_failure_counters(&self, id: i64) -> anyhow::Result<()> {
114        self.write(Command::TaskResetCounters {
115            id,
116            failure_only: true,
117        })
118        .await
119        .map(|_| ())
120    }
121
122    /// Store routing results for a task.
123    pub async fn store_route(&self, route: &StoreRoute<'_>) -> anyhow::Result<()> {
124        self.write(Command::TaskStoreRoute(StoreRouteCmd {
125            id: route.id,
126            agent: route.agent.to_string(),
127            model: route.model.map(str::to_string),
128            complexity: route.complexity.to_string(),
129            estimate: route.estimate,
130            reason: route.reason.to_string(),
131            profile: route.profile.to_string(),
132        }))
133        .await
134        .map(|_| ())
135    }
136
137    /// Return `(external_id, estimate)` for all non-internal tasks that have a
138    /// positive Fibonacci estimate stored in the database.
139    ///
140    /// Used by startup estimate reconciliation to push orch-stored estimates to
141    /// the GitHub Projects board for tasks that were routed before the estimate
142    /// sync feature was available or before `project_estimate_field_id` was
143    /// configured.
144    pub async fn list_external_tasks_with_estimates(&self) -> anyhow::Result<Vec<(String, u8)>> {
145        let rows = sqlx::query(
146            "SELECT external_id, estimate FROM tasks \
147             WHERE estimate > 0 AND external_id NOT LIKE 'internal:%' \
148             AND status NOT IN ('done', 'blocked')",
149        )
150        .fetch_all(&self.pool)
151        .await?;
152
153        let mut result = Vec::new();
154        for row in &rows {
155            let external_id: String = row.try_get("external_id")?;
156            let estimate_raw: i64 = row.try_get("estimate")?;
157            if let Ok(estimate @ 1..) = u8::try_from(estimate_raw) {
158                result.push((external_id, estimate));
159            }
160        }
161        Ok(result)
162    }
163
164    /// Set the Fibonacci estimate for a task (only if currently 0).
165    ///
166    /// Used during ingestion to populate `tasks.estimate` from GitHub Projects
167    /// when the orch estimate is still 0. This avoids overwriting estimates
168    /// already set by the router.
169    pub async fn set_estimate_if_zero(&self, id: i64, estimate: u8) -> anyhow::Result<bool> {
170        self.write_bool(Command::TaskSetEstimateIfZero { id, estimate })
171            .await
172    }
173
174    /// Mark a task's worktree as cleaned.
175    pub async fn mark_cleaned(&self, id: i64) -> anyhow::Result<()> {
176        self.write(Command::TaskMarkCleaned { id })
177            .await
178            .map(|_| ())
179    }
180
181    /// Batch-update fields for multiple tasks in a single transaction.
182    ///
183    /// Each entry is `(id, updates)` where `updates` is a slice of `(column, value)` pairs.
184    /// Skips entries with empty update slices.
185    /// Test-only helper / bulk operations used by admin paths and tests.
186    #[cfg(test)]
187    pub async fn batch_set_fields(
188        &self,
189        updates: &[(i64, &[(&str, serde_json::Value)])],
190    ) -> anyhow::Result<()> {
191        if updates.is_empty() {
192            return Ok(());
193        }
194
195        for (_, entry_updates) in updates {
196            for (col, _) in *entry_updates {
197                anyhow::ensure!(
198                    ALLOWED_FIELDS.contains(col),
199                    "column {col} is not in the update allowlist"
200                );
201            }
202        }
203
204        let mut tx = self.begin_write().await?;
205        for (id, entry_updates) in updates {
206            if entry_updates.is_empty() {
207                continue;
208            }
209            let mut set_parts = Vec::new();
210            let mut values: Vec<Option<String>> = Vec::new();
211            for (col, val) in *entry_updates {
212                set_parts.push(format!("{col} = ?"));
213                values.push(sql_value_for_task_field(col, val)?);
214            }
215            set_parts.push("updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')".to_string());
216            let sql = format!("UPDATE tasks SET {} WHERE id = ?", set_parts.join(", "));
217            let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
218            for v in &values {
219                query = query.bind(v.as_deref());
220            }
221            query = query.bind(*id);
222            query.execute(&mut *tx).await?;
223        }
224        tx.commit().await?;
225        Ok(())
226    }
227
228    /// Batch-increment a field for multiple tasks in a single transaction.
229    ///
230    /// Each entry is `(id, field)`. All fields must be in the incrementable allowlist.
231    /// Test-only helper for bulk increments used by tests.
232    #[cfg(test)]
233    pub async fn batch_increment(&self, entries: &[(i64, &str)]) -> anyhow::Result<()> {
234        if entries.is_empty() {
235            return Ok(());
236        }
237
238        for (_, field) in entries {
239            anyhow::ensure!(
240                INCREMENTABLE_FIELDS.contains(field),
241                "field {field} is not incrementable"
242            );
243        }
244
245        let mut tx = self.begin_write().await?;
246        for (id, field) in entries {
247            let sql = format!(
248                "UPDATE tasks SET {field} = {field} + 1, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?"
249            );
250            sqlx::query(sqlx::AssertSqlSafe(sql.as_str()))
251                .bind(*id)
252                .execute(&mut *tx)
253                .await?;
254        }
255        tx.commit().await?;
256        Ok(())
257    }
258
259    /// Reset transient failure/retry counters for multiple tasks in a single transaction.
260    ///
261    /// Preserves `review_cycles`, `ci_merge_failures`, and
262    /// `merge_conflict_retries` (same semantics as
263    /// [`reset_failure_counters`]).
264    /// Test-only helper for bulk counter resets used by tests.
265    #[cfg(test)]
266    pub async fn batch_reset_failure_counters(&self, ids: &[i64]) -> anyhow::Result<()> {
267        // SQLite has a hard limit on host parameters (commonly 999). Chunk the
268        // IN-list into smaller batches to avoid exceeding the limit.
269        const CHUNK_SIZE: usize = 500;
270        if ids.is_empty() {
271            return Ok(());
272        }
273
274        let mut tx = self.begin_write().await?;
275
276        for chunk in ids.chunks(CHUNK_SIZE) {
277            // Build WHERE id IN (?, ?, ...) placeholders for this chunk
278            let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
279            let sql = format!(
280                "UPDATE tasks SET
281            route_attempts = 0,
282            review_agent_failures = 0,
283            review_resets = 0,
284            review_invocations = 0,
285            pr_create_failures = 0,
286            push_failures = 0,
287            network_retries = 0,
288            timeout_retries = 0,
289            auto_unblock_count = 0,
290            auto_unblock_last_at = '',
291            auto_unblock_last_reason = '',
292            ci_recovery_count = 0,
293            no_code_reroutes = 0,
294            needs_review_refires = 0,
295            updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
296         WHERE id IN ({placeholders})",
297            );
298            let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
299            for id in chunk {
300                query = query.bind(*id);
301            }
302            query.execute(&mut *tx).await?;
303        }
304
305        tx.commit().await?;
306        Ok(())
307    }
308
309    /// Mark multiple tasks' worktrees as cleaned in a single transaction.
310    ///
311    /// Appends a `branch_delete` activity event for each task.
312    /// Test-only helper for bulk cleaning used by tests.
313    #[cfg(test)]
314    pub async fn batch_mark_cleaned(&self, ids: &[i64]) -> anyhow::Result<()> {
315        // Chunk updates to avoid exceeding SQLite's parameter limit.
316        const CHUNK_SIZE: usize = 500;
317        if ids.is_empty() {
318            return Ok(());
319        }
320
321        let mut tx = self.begin_write().await?;
322
323        for chunk in ids.chunks(CHUNK_SIZE) {
324            let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
325            let sql = format!(
326                "UPDATE tasks SET worktree_cleaned = 1, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id IN ({placeholders})",
327            );
328            let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
329            for id in chunk {
330                query = query.bind(*id);
331            }
332            query.execute(&mut *tx).await?;
333        }
334
335        // Append activity for each task (must be done individually — activity is per-task JSON)
336        // Insert using the same transaction to avoid connection pool exhaustion
337        // / deadlocks in tests.
338        let details = serde_json::json!({ "worktree_cleaned": true });
339        let details_json = serde_json::to_string(&details)?;
340        for id in ids {
341            sqlx::query(
342                "INSERT INTO task_activity (task_id, event_type, from_status, to_status, agent, model, details) VALUES (?, ?, ?, ?, ?, ?, ?)",
343            )
344            .bind(*id)
345            .bind("branch_delete")
346            .bind(None::<&str>)
347            .bind(None::<&str>)
348            .bind(None::<&str>)
349            .bind(None::<&str>)
350            .bind(details_json.as_str())
351            .execute(&mut *tx)
352            .await?;
353        }
354
355        tx.commit().await?;
356        Ok(())
357    }
358
359    /// List tasks that are done/blocked with worktrees that haven't been cleaned.
360    /// Test-only helper and used by cleanup tests.
361    #[cfg(test)]
362    pub async fn list_cleanable(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
363        let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
364            "SELECT {TASK_COLS} FROM tasks
365         WHERE repo = ?
366           AND worktree != ''
367           AND worktree_cleaned = 0
368           AND status IN ('done', 'blocked')
369         ORDER BY updated_at ASC"
370        )))
371        .bind(repo)
372        .fetch_all(&self.pool)
373        .await?;
374
375        rows.iter().map(Self::row_to_task).collect()
376    }
377
378    /// Return external IDs of tasks whose worktrees have already been cleaned.
379    ///
380    /// Used by `cleanup_done_worktrees` to skip already-cleaned tasks without
381    /// issuing one `resolve_task_id + get` per task (N+1 elimination).
382    pub async fn cleaned_external_ids(&self, repo: &str) -> anyhow::Result<HashSet<String>> {
383        let rows: Vec<(String,)> =
384            sqlx::query_as("SELECT external_id FROM tasks WHERE repo = ? AND worktree_cleaned = 1 AND external_id IS NOT NULL")
385                .bind(repo)
386                .fetch_all(&self.pool)
387                .await?;
388
389        Ok(rows.into_iter().map(|(id,)| id).collect())
390    }
391}