1use super::{CompleteRun, RunTokenUsage, StartRun, TASK_RUN_COLS, TaskRun};
4use crate::security;
5use crate::store::Command;
6use crate::store::{MemoryEntry, TaskStore};
7use sqlx::Row;
8use sqlx::sqlite::SqliteRow;
9use std::collections::HashMap;
10
11impl TaskStore {
12 pub async fn append_memory(&self, id: i64, entry: &MemoryEntry) -> anyhow::Result<()> {
17 self.write(Command::TaskAppendMemory {
18 id,
19 entry: entry.clone(),
20 })
21 .await
22 .map(|_| ())
23 }
24
25 pub async fn recent_memory(&self, id: i64, max: usize) -> anyhow::Result<Vec<MemoryEntry>> {
27 let row = sqlx::query("SELECT memory FROM tasks WHERE id = ?")
28 .bind(id)
29 .fetch_one(&self.pool)
30 .await?;
31
32 let memory_opt: Option<String> = row
33 .try_get::<Option<String>, _>("memory")
34 .map_err(|e| anyhow::anyhow!("failed to read memory column for task {id}: {e}"))?;
35 let memory_str = memory_opt.unwrap_or_default();
36
37 let mut memory: Vec<MemoryEntry> = if memory_str.trim().is_empty() {
38 Vec::new()
39 } else {
40 serde_json::from_str(&memory_str)
41 .map_err(|e| anyhow::anyhow!("failed to parse memory JSON for task {id}: {e}"))?
42 };
43
44 memory.sort_by_key(|m| m.attempt);
45 if memory.len() > max {
46 memory = memory.split_off(memory.len() - max);
47 }
48 Ok(memory)
49 }
50
51 pub async fn store_tokens(
53 &self,
54 id: i64,
55 input: u64,
56 output: u64,
57 cost_usd: Option<f64>,
58 ) -> anyhow::Result<()> {
59 sqlx::query(
60 "UPDATE tasks SET
61 input_tokens = COALESCE(input_tokens, 0) + ?,
62 output_tokens = COALESCE(output_tokens, 0) + ?,
63 total_cost_usd = COALESCE(total_cost_usd, 0.0) + COALESCE(?, 0.0),
64 updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
65 WHERE id = ?",
66 )
67 .bind(i64::try_from(input).unwrap_or_else(|_| {
68 tracing::warn!(input, "input_tokens overflows i64, clamping to MAX");
69 i64::MAX
70 }))
71 .bind(i64::try_from(output).unwrap_or_else(|_| {
72 tracing::warn!(output, "output_tokens overflows i64, clamping to MAX");
73 i64::MAX
74 }))
75 .bind(cost_usd)
76 .bind(id)
77 .execute(&self.pool)
78 .await?;
79
80 Ok(())
81 }
82
83 pub async fn start_run(&self, run: &StartRun<'_>) -> anyhow::Result<i64> {
85 let orphaned: Vec<(i64,)> = sqlx::query_as(
97 "SELECT id FROM task_runs
98 WHERE task_id = ? AND run_type = ? AND attempt != ?
99 AND outcome IS NULL AND completed_at IS NULL",
100 )
101 .bind(run.task_id)
102 .bind(run.run_type)
103 .bind(run.attempt)
104 .fetch_all(&self.pool)
105 .await?;
106
107 for (run_id,) in orphaned {
108 self.complete_run(&CompleteRun {
109 run_id,
110 exit_code: Some(-1),
111 stdout: "",
112 stderr: "",
113 parsed: "",
114 outcome: "aborted",
115 error: "superseded by a new run start before this one completed",
116 tokens: RunTokenUsage::default(),
117 })
118 .await?;
119 }
120
121 let row = sqlx::query(
122 "INSERT INTO task_runs (task_id, attempt, run_type, agent, model, command, prompt, outcome)
123 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
124 ON CONFLICT(task_id, attempt, run_type) DO UPDATE SET
125 agent = excluded.agent, model = excluded.model,
126 command = excluded.command, prompt = excluded.prompt,
127 outcome = NULL,
128 started_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now'),
129 completed_at = NULL, error = NULL, exit_code = NULL,
130 stdout = NULL, stderr = NULL, parsed_response = NULL,
131 duration_secs = NULL, input_tokens = NULL, output_tokens = NULL,
132 total_cost_usd = NULL
133 RETURNING id",
134 )
135 .bind(run.task_id)
136 .bind(run.attempt)
137 .bind(run.run_type)
138 .bind(run.agent)
139 .bind(run.model)
140 .bind(run.command)
141 .bind(run.prompt)
142 .fetch_one(&self.pool)
143 .await?;
144
145 let run_id: i64 = row
146 .try_get("id")
147 .map_err(|e| anyhow::anyhow!("INSERT RETURNING id returned NULL or invalid: {e}"))?;
148 let event_type = match run.run_type {
149 "review" => "review_start",
150 _ => "dispatch",
151 };
152 let details = serde_json::json!({
153 "run_type": run.run_type,
154 "attempt": run.attempt,
155 "command": run.command,
156 });
157 self.append_activity(
158 run.task_id,
159 event_type,
160 None,
161 None,
162 Some(run.agent),
163 Some(run.model),
164 Some(&details),
165 )
166 .await?;
167
168 Ok(run_id)
169 }
170
171 pub async fn complete_run(&self, run: &CompleteRun<'_>) -> anyhow::Result<()> {
173 let run_ctx =
174 sqlx::query("SELECT task_id, run_type, agent, model FROM task_runs WHERE id = ?")
175 .bind(run.run_id)
176 .fetch_optional(&self.pool)
177 .await?;
178 let updated = sqlx::query(
179 "UPDATE task_runs SET
180 exit_code = ?, stdout = ?, stderr = ?, parsed_response = ?,
181 outcome = ?, error = NULLIF(?, ''),
182 input_tokens = ?, output_tokens = ?, total_cost_usd = ?,
183 duration_secs = CASE WHEN ? > 0 THEN ?
184 ELSE MAX(0, (julianday('now') - julianday(started_at)) * 86400.0) END,
185 completed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
186 WHERE id = ? AND outcome IS NULL",
187 )
188 .bind(run.exit_code)
189 .bind(run.stdout)
190 .bind(security::redact(run.stderr))
191 .bind(run.parsed)
192 .bind(run.outcome)
193 .bind(security::redact(run.error))
194 .bind(i64::try_from(run.tokens.input_tokens).unwrap_or_else(|_| {
195 tracing::warn!(
196 run.tokens.input_tokens,
197 "input_tokens overflows i64, clamping to MAX"
198 );
199 i64::MAX
200 }))
201 .bind(i64::try_from(run.tokens.output_tokens).unwrap_or_else(|_| {
202 tracing::warn!(
203 run.tokens.output_tokens,
204 "output_tokens overflows i64, clamping to MAX"
205 );
206 i64::MAX
207 }))
208 .bind(run.tokens.total_cost_usd)
209 .bind(run.tokens.duration_secs)
210 .bind(run.tokens.duration_secs)
211 .bind(run.run_id)
212 .execute(&self.pool)
213 .await?;
214 if updated.rows_affected() == 0 && run_ctx.is_some() {
215 tracing::debug!(
217 run_id = run.run_id,
218 "run already closed, keeping its outcome"
219 );
220 return Ok(());
221 }
222 if let Some(run_ctx) = run_ctx {
223 let task_id: i64 = run_ctx.try_get("task_id").map_err(|e| {
224 anyhow::anyhow!("failed to decode task_id from run_id {}: {e}", run.run_id)
225 })?;
226 let run_type: String = run_ctx.try_get("run_type").map_err(|e| {
227 anyhow::anyhow!("failed to decode run_type from run_id {}: {e}", run.run_id)
228 })?;
229 let agent: String = run_ctx.try_get("agent").map_err(|e| {
230 anyhow::anyhow!("failed to decode agent from run_id {}: {e}", run.run_id)
231 })?;
232 let model: String = run_ctx.try_get("model").map_err(|e| {
233 anyhow::anyhow!("failed to decode model from run_id {}: {e}", run.run_id)
234 })?;
235 if run.outcome == "timeout" {
236 self.append_activity(
237 task_id,
238 "timeout",
239 None,
240 None,
241 Some(&agent),
242 Some(&model),
243 Some(&serde_json::json!({
244 "run_type": run_type,
245 "error": run.error,
246 "stderr": run.stderr,
247 })),
248 )
249 .await?;
250 } else if run.outcome != "success" {
251 self.append_activity(
252 task_id,
253 "error",
254 None,
255 None,
256 Some(&agent),
257 Some(&model),
258 Some(&serde_json::json!({
259 "run_type": run_type,
260 "outcome": run.outcome,
261 "error": run.error,
262 })),
263 )
264 .await?;
265 }
266 } else if run.outcome != "success" {
267 tracing::warn!(
268 run_id = run.run_id,
269 outcome = run.outcome,
270 "run_id not found in task_runs; skipping timeout/error activity log"
271 );
272 }
273 Ok(())
274 }
275
276 pub async fn finalize_incomplete_runs(
281 &self,
282 task_id: i64,
283 outcome: &str,
284 error: &str,
285 ) -> anyhow::Result<u64> {
286 let rows: Vec<(i64,)> = sqlx::query_as(
287 "SELECT id FROM task_runs
288 WHERE task_id = ?
289 AND outcome IS NULL
290 AND completed_at IS NULL
291 ORDER BY id ASC",
292 )
293 .bind(task_id)
294 .fetch_all(&self.pool)
295 .await?;
296
297 for (run_id,) in &rows {
298 self.complete_run(&CompleteRun {
299 run_id: *run_id,
300 exit_code: Some(-1),
301 stdout: "",
302 stderr: "",
303 parsed: "",
304 outcome,
305 error,
306 tokens: RunTokenUsage::default(),
307 })
308 .await?;
309 }
310
311 Ok(rows.len() as u64)
312 }
313
314 pub async fn get_runs(&self, task_id: i64) -> anyhow::Result<Vec<TaskRun>> {
316 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
317 "SELECT {TASK_RUN_COLS} FROM task_runs WHERE task_id = ? ORDER BY attempt ASC, run_type ASC"
318 )))
319 .bind(task_id)
320 .fetch_all(&self.pool)
321 .await?;
322
323 rows.iter().map(Self::row_to_run).collect()
324 }
325
326 pub async fn get_runs_batch(
329 &self,
330 task_ids: &[i64],
331 ) -> anyhow::Result<HashMap<i64, Vec<TaskRun>>> {
332 const CHUNK_SIZE: usize = 500;
335 if task_ids.is_empty() {
336 return Ok(HashMap::new());
337 }
338
339 let mut result: HashMap<i64, Vec<TaskRun>> = HashMap::new();
340
341 for chunk in task_ids.chunks(CHUNK_SIZE) {
342 let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
343 let sql = format!(
344 "SELECT {TASK_RUN_COLS} FROM task_runs WHERE task_id IN ({placeholders}) ORDER BY task_id ASC, attempt ASC, run_type ASC"
345 );
346 let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
347 for id in chunk {
348 query = query.bind(*id);
349 }
350 let rows = query.fetch_all(&self.pool).await?;
351 for row in &rows {
352 let run = Self::row_to_run(row)?;
353 result.entry(run.task_id).or_default().push(run);
354 }
355 }
356 Ok(result)
357 }
358
359 #[cfg(test)]
362 pub async fn get_last_run(
363 &self,
364 task_id: i64,
365 run_type: &str,
366 ) -> anyhow::Result<Option<TaskRun>> {
367 let row = sqlx::query(sqlx::AssertSqlSafe(format!(
368 "SELECT {TASK_RUN_COLS} FROM task_runs WHERE task_id = ? AND run_type = ? ORDER BY attempt DESC LIMIT 1"
369 )))
370 .bind(task_id)
371 .bind(run_type)
372 .fetch_optional(&self.pool)
373 .await?;
374
375 match row {
376 Some(r) => Ok(Some(Self::row_to_run(&r)?)),
377 None => Ok(None),
378 }
379 }
380
381 pub async fn previous_review_agents(&self, task_id: i64) -> anyhow::Result<Vec<String>> {
385 let rows: Vec<(String,)> = sqlx::query_as(
386 "SELECT DISTINCT agent FROM task_runs \
387 WHERE task_id = ? AND run_type = 'review' \
388 ORDER BY agent",
389 )
390 .bind(task_id)
391 .fetch_all(&self.pool)
392 .await?;
393 Ok(rows.into_iter().map(|(a,)| a).collect())
394 }
395
396 pub async fn prune_old_runs(&self, days: i32) -> anyhow::Result<u64> {
399 let result = sqlx::query(
400 "UPDATE task_runs
401 SET stdout = '', stderr = '', prompt = '', parsed_response = ''
402 WHERE (stdout != '' OR stderr != '' OR prompt != '' OR parsed_response != '')
403 AND task_id IN (
404 SELECT t.id FROM tasks t
405 WHERE t.status = 'done'
406 AND (SELECT MAX(a.timestamp) FROM task_activity a
407 WHERE a.task_id = t.id
408 AND a.event_type = 'status_change'
409 AND a.to_status = 'done')
410 < strftime('%Y-%m-%dT%H:%M:%SZ', 'now', ? || ' days')
411 )",
412 )
413 .bind(format!("-{days}"))
414 .execute(&self.pool)
415 .await?;
416
417 if result.rows_affected() > 0 {
418 sqlx::query("PRAGMA incremental_vacuum")
419 .execute(&self.pool)
420 .await?;
421 }
422
423 Ok(result.rows_affected())
424 }
425
426 pub(super) fn row_to_run(row: &SqliteRow) -> anyhow::Result<TaskRun> {
427 Ok(TaskRun {
428 id: row
429 .try_get("id")
430 .map_err(|e| anyhow::anyhow!("run row decode error for id: {e}"))?,
431 task_id: row
432 .try_get("task_id")
433 .map_err(|e| anyhow::anyhow!("run row decode error for task_id: {e}"))?,
434 attempt: row
435 .try_get("attempt")
436 .map_err(|e| anyhow::anyhow!("run row decode error for attempt: {e}"))?,
437 run_type: row
438 .try_get("run_type")
439 .map_err(|e| anyhow::anyhow!("run row decode error for run_type: {e}"))?,
440 agent: row
441 .try_get("agent")
442 .map_err(|e| anyhow::anyhow!("run row decode error for agent: {e}"))?,
443 model: row
444 .try_get("model")
445 .map_err(|e| anyhow::anyhow!("run row decode error for model: {e}"))?,
446 command: row
447 .try_get("command")
448 .map_err(|e| anyhow::anyhow!("run row decode error for command: {e}"))?,
449 prompt: row
450 .try_get("prompt")
451 .map_err(|e| anyhow::anyhow!("run row decode error for prompt: {e}"))?,
452 env_vars: row
453 .try_get("env_vars")
454 .map_err(|e| anyhow::anyhow!("run row decode error for env_vars: {e}"))?,
455 exit_code: row
456 .try_get("exit_code")
457 .map_err(|e| anyhow::anyhow!("run row decode error for exit_code: {e}"))?,
458 stdout: row
459 .try_get("stdout")
460 .map_err(|e| anyhow::anyhow!("run row decode error for stdout: {e}"))?,
461 stderr: row
462 .try_get("stderr")
463 .map_err(|e| anyhow::anyhow!("run row decode error for stderr: {e}"))?,
464 parsed_response: row
465 .try_get("parsed_response")
466 .map_err(|e| anyhow::anyhow!("run row decode error for parsed_response: {e}"))?,
467 outcome: row
468 .try_get("outcome")
469 .map_err(|e| anyhow::anyhow!("run row decode error for outcome: {e}"))?,
470 error: row
471 .try_get("error")
472 .map_err(|e| anyhow::anyhow!("run row decode error for error: {e}"))?,
473 input_tokens: row
474 .try_get("input_tokens")
475 .map_err(|e| anyhow::anyhow!("run row decode error for input_tokens: {e}"))?,
476 output_tokens: row
477 .try_get("output_tokens")
478 .map_err(|e| anyhow::anyhow!("run row decode error for output_tokens: {e}"))?,
479 total_cost_usd: row
480 .try_get("total_cost_usd")
481 .map_err(|e| anyhow::anyhow!("run row decode error for total_cost_usd: {e}"))?,
482 duration_secs: row
483 .try_get("duration_secs")
484 .map_err(|e| anyhow::anyhow!("run row decode error for duration_secs: {e}"))?,
485 started_at: row
486 .try_get("started_at")
487 .map_err(|e| anyhow::anyhow!("run row decode error for started_at: {e}"))?,
488 completed_at: row.try_get("completed_at").unwrap_or(None),
489 })
490 }
491}