1use std::collections::{BTreeMap, BTreeSet};
9use std::sync::Arc;
10
11use jiff::Timestamp;
12use schedr_model::{AttemptStatus, CleanupResult, Dag, DagId, RunKind, TaskId, TaskInstanceState};
13use uuid::Uuid;
14
15use crate::database::{Database, DbError};
16use crate::query::{db_time, from_json, from_name, in_tx, on_pool, parse_time, sql, sql_text};
17
18macro_rules! unstarted_any_time_from {
21 () => {
22 "FROM attempts a WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.started_at IS NULL"
23 };
24}
25pub(crate) use unstarted_any_time_from;
26
27macro_rules! unstarted_cleanups_any_time_from {
29 () => {
30 "FROM attempts a WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.moved_at IS NOT NULL"
31 };
32}
33pub(crate) use unstarted_cleanups_any_time_from;
34
35macro_rules! replaced_from {
37 () => {
38 "FROM attempts WHERE status IS NULL AND replaced_at IS NOT NULL"
39 };
40}
41pub(crate) use replaced_from;
42
43macro_rules! unschedulable_from {
45 () => {
46 "FROM task_instances t JOIN runs r ON r.id = t.run_id WHERE t.state = 'unschedulable' AND r.state = 'running'"
47 };
48}
49pub(crate) use unschedulable_from;
50
51macro_rules! chained_from {
53 () => {
54 "FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id JOIN runs r ON r.id = t.run_id LEFT JOIN runs c ON c.id = a.chained_run_id WHERE a.status IS NULL AND a.chained_run_id IS NOT NULL"
55 };
56}
57pub(crate) use chained_from;
58
59macro_rules! ready_from {
61 () => {
62 "FROM task_instances t JOIN runs r ON r.id = t.run_id JOIN dag_versions v ON v.id = r.dag_version_id JOIN parse_results p ON p.id = v.parse_result_id WHERE t.state = 'queued' AND t.ready_at <= $1{ts} AND (t.look_at IS NULL OR t.look_at <= $1{ts}) AND r.state = 'running' AND t.cancel_requested_at IS NULL"
63 };
64}
65pub(crate) use ready_from;
66
67macro_rules! waiting_cleanups_any_time_from {
69 () => {
70 "FROM attempts a WHERE a.status IS NULL AND a.worker_id IS NULL AND a.chained_run_id IS NULL"
71 };
72}
73pub(crate) use waiting_cleanups_any_time_from;
74
75const OUTPUTS_PER_QUERY: usize = 500;
77
78const CLAIMS_PER_STATEMENT: usize = 200;
80
81#[cfg(test)]
82mod tests;
83
84#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct Unschedulable {
87 pub run_id: String,
89 pub task_id: TaskId,
91 pub map_index: i32,
93 pub dag: Arc<Dag>,
95 pub since: Timestamp,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct ChainedAttempt {
102 pub id: String,
104 pub instance_id: String,
106 pub run_id: String,
108 pub task_id: TaskId,
110 pub map_index: i32,
112 pub started_at: Timestamp,
114 pub chained_run_id: String,
116 pub chained_state: Option<schedr_model::RunState>,
118 pub chained_ended_at: Option<Timestamp>,
120 pub dag: Arc<Dag>,
122 pub cancel_requested: bool,
124 pub run_kind: RunKind,
126 pub planned_for: Timestamp,
128 pub since: Timestamp,
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct ReadyInstance {
135 pub instance_id: String,
137 pub run_id: String,
139 pub task_id: TaskId,
141 pub try_number: u32,
143 pub run_kind: RunKind,
145 pub planned_for: Timestamp,
147 pub since: Timestamp,
149 pub dag: Arc<Dag>,
151 pub version_id: String,
153 pub content_hash: String,
156 pub queued_reason: Option<String>,
158 pub parse_version: String,
161 pub map_index: i32,
163}
164
165#[derive(Debug, Clone, PartialEq, Eq)]
167pub struct ActiveAttempt {
168 pub attempt_id: String,
170 pub dag_id: DagId,
172 pub run_id: String,
174 pub task_id: TaskId,
176}
177
178#[derive(Debug, Clone, PartialEq)]
180pub struct InstanceResult {
181 pub map_index: i32,
183 pub state: TaskInstanceState,
185 pub outcome: Option<String>,
187 pub output: Option<serde_json::Value>,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq)]
193pub struct StoredAttempt {
194 pub id: String,
196 pub instance_id: String,
198 pub run_id: String,
200 pub task_id: TaskId,
202 pub try_number: u32,
204 pub worker_id: String,
206 pub status: Option<AttemptStatus>,
208 pub started: bool,
210 pub map_index: i32,
212 pub result_kept: bool,
214 pub cleanup_moves: u32,
216 pub moving: bool,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
222pub struct AttemptEnd {
223 pub status: AttemptStatus,
225 pub exit_code: Option<i32>,
227 pub signal: Option<i32>,
229 pub peak_memory_bytes: Option<u64>,
231 pub usage: Option<schedr_model::runner::ProcessUsage>,
233 pub core_dumped: bool,
235 pub duration_ms: Option<u64>,
238 pub error_kind: Option<String>,
240 pub error_summary: Option<String>,
242 pub code_hash: Option<String>,
244 pub cleanup: Option<CleanupEnd>,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct CleanupEnd {
251 pub result: CleanupResult,
253 pub tries: u32,
255 pub duration_ms: u64,
257 pub error_kind: Option<String>,
259 pub error_summary: Option<String>,
261}
262
263impl AttemptEnd {
264 #[must_use]
266 pub const fn by_master(status: AttemptStatus) -> Self {
267 Self {
268 status,
269 exit_code: None,
270 signal: None,
271 peak_memory_bytes: None,
272 usage: None,
273 core_dumped: false,
274 duration_ms: None,
275 error_kind: None,
276 error_summary: None,
277 code_hash: None,
278 cleanup: None,
279 }
280 }
281}
282
283type ReadyRow = (
284 String,
285 String,
286 String,
287 i32,
288 String,
289 String,
290 String,
291 String,
292 String,
293 Option<String>,
294 String,
295 i32,
296 bool,
297);
298type AttemptRow = (
299 String,
300 String,
301 String,
302 String,
303 i32,
304 Option<String>,
305 Option<String>,
306 bool,
307 i32,
308 bool,
309 i32,
310 bool,
311);
312
313pub const ENDS_PER_STATEMENT: usize = 100;
317
318const ATTEMPT_BY_ID: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
319 t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
320 t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
321 a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
322 WHERE a.id = $1{uuid}";
323const OPEN_ATTEMPTS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
324 t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
325 t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
326 a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
327 WHERE a.status IS NULL AND a.chained_run_id IS NULL AND ($1 IS NULL OR a.worker_id = $1) \
328 ORDER BY a.assigned_at, a.id";
329const UNSTARTED_CLEANUPS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
330 t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
331 t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
332 a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
333 WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.moved_at < $1{ts} \
334 AND a.worker_id NOT IN (SELECT value FROM {json_each}($3{json})) \
335 ORDER BY a.moved_at LIMIT $2";
336const ACTIVE_ATTEMPTS: &str = "SELECT a.id{text}, r.dag_id, t.run_id{text}, t.task_id \
337 FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
338 JOIN runs r ON r.id = t.run_id WHERE a.status IS NULL AND a.chained_run_id IS NULL \
339 ORDER BY a.id";
340const UNSTARTED_ATTEMPTS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
341 t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
342 t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
343 a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
344 WHERE a.status IS NULL AND a.chained_run_id IS NULL AND a.started_at IS NULL \
345 AND a.assigned_at < $1{ts} \
346 AND a.worker_id NOT IN (SELECT value FROM {json_each}($3{json})) \
347 ORDER BY a.assigned_at, a.id LIMIT $2";
348
349impl Database {
350 pub async fn ready_instances(&self, now: Timestamp) -> Result<Vec<ReadyInstance>, DbError> {
357 const READY: &str = concat!(
358 "SELECT t.id{text}, r.id{text}, t.task_id, t.try_number, r.kind, \
359 {ts<}r.planned_for{>ts}, {ts<}r.since{>ts}, r.dag_version_id{text}, p.content_hash, \
360 t.queued_reason, p.schedr_version, t.map_index, r.cancel_requested_at IS NOT NULL ",
361 ready_from!(),
362 " ORDER BY t.ready_at, t.id"
363 );
364 if self.skipped_at(crate::probe::Check::Ready, now).await? {
365 return Ok(Vec::new());
366 }
367 let rows: Vec<ReadyRow> = on_pool!(self, |pool, backend| {
368 sqlx::query_as(sql(backend, READY))
369 .bind(db_time(now))
370 .fetch_all(pool)
371 .await?
372 });
373 let mut ready_list = Vec::with_capacity(rows.len());
376 for row in rows {
377 let run_cancelling = row.12;
378 let dag = self.dag_version(&row.7).await?;
379 let cleanup = dag
380 .resource_of_cleanup(&task_id_of(row.2.clone())?)
381 .is_some();
382 if run_cancelling && !cleanup {
384 continue;
385 }
386 ready_list.push((cleanup, ready(row, dag)?));
387 }
388 ready_list.sort_by_key(|(cleanup, _)| !*cleanup);
391 Ok(ready_list.into_iter().map(|(_, r)| r).collect())
392 }
393
394 pub async fn assign_attempt(
401 &self,
402 instance_id: &str,
403 worker_id: &str,
404 now: Timestamp,
405 ) -> Result<Option<(String, u32)>, DbError> {
406 const CLAIM: &str = "UPDATE task_instances SET state = 'running', \
407 try_number = try_number + 1, ready_at = NULL, queued_reason = NULL, updated_at = $1{ts} \
408 WHERE id = $2{uuid} AND state = 'queued'";
409 const TRY: &str = "SELECT try_number FROM task_instances WHERE id = $1{uuid}";
410 const INSERT: &str = "INSERT INTO attempts \
411 (id, task_instance_id, try_number, worker_id, assigned_at) \
412 VALUES ($1{uuid}, $2{uuid}, $3, $4, $5{ts})";
413 let id = Uuid::now_v7().to_string();
414 let now = db_time(now);
415 let try_number: Option<i32> = in_tx!(self, |tx, backend| {
416 let claimed = sqlx::query(sql(backend, CLAIM))
417 .bind(&now)
418 .bind(instance_id)
419 .execute(&mut *tx)
420 .await?
421 .rows_affected();
422 if claimed == 1 {
423 let try_number: i32 = sqlx::query_scalar(sql(backend, TRY))
424 .bind(instance_id)
425 .fetch_one(&mut *tx)
426 .await?;
427 sqlx::query(sql(backend, INSERT))
428 .bind(&id)
429 .bind(instance_id)
430 .bind(try_number)
431 .bind(worker_id)
432 .bind(&now)
433 .execute(&mut *tx)
434 .await?;
435 Some(try_number)
436 } else {
437 None
438 }
439 });
440 Ok(try_number.map(|n| (id, u32::try_from(n).unwrap_or(0))))
441 }
442
443 pub async fn claim_attempts(
452 &self,
453 claims: &[(&str, &str, &str)],
454 now: Timestamp,
455 ) -> Result<BTreeMap<String, u32>, DbError> {
456 Box::pin(self.atomically(self.claim_chunks(claims, now))).await
458 }
459
460 async fn claim_chunks(
461 &self,
462 claims: &[(&str, &str, &str)],
463 now: Timestamp,
464 ) -> Result<BTreeMap<String, u32>, DbError> {
465 let now = db_time(now);
466 let mut tries: BTreeMap<String, u32> = BTreeMap::new();
467 for chunk in claims.chunks(CLAIMS_PER_STATEMENT) {
468 let ids: Vec<String> = (2..chunk.len() + 2)
469 .map(|n| format!("${n}{{uuid}}"))
470 .collect();
471 let claim = format!(
472 "UPDATE task_instances SET state = 'running', try_number = try_number + 1, \
473 ready_at = NULL, queued_reason = NULL, updated_at = $1{{ts}} \
474 WHERE state = 'queued' AND id IN ({}) RETURNING id{{text}}, try_number",
475 ids.join(", ")
476 );
477 let claimed: BTreeMap<String, u32> = in_tx!(self, |tx, backend| {
479 let mut query =
480 sqlx::query_as::<_, (String, i32)>(sql_text(backend, &claim)).bind(&now);
481 for (instance, _, _) in chunk {
482 query = query.bind(*instance);
483 }
484 let claimed: BTreeMap<String, u32> = query
485 .fetch_all(&mut *tx)
486 .await?
487 .into_iter()
488 .map(|(id, n)| (id, u32::try_from(n).unwrap_or(0)))
489 .collect();
490 let rows: Vec<&(&str, &str, &str)> = chunk
491 .iter()
492 .filter(|(instance, _, _)| claimed.contains_key(*instance))
493 .collect();
494 if !rows.is_empty() {
495 let values: Vec<String> = (0..rows.len())
496 .map(|i| {
497 let n = i * 4 + 2;
498 format!(
499 "(${n}{{uuid}}, ${}{{uuid}}, ${}, ${}, $1{{ts}})",
500 n + 1,
501 n + 2,
502 n + 3
503 )
504 })
505 .collect();
506 let insert = format!(
507 "INSERT INTO attempts (id, task_instance_id, try_number, worker_id, \
508 assigned_at) VALUES {}",
509 values.join(", ")
510 );
511 let mut query = sqlx::query(sql_text(backend, &insert)).bind(&now);
512 for (instance, worker, attempt) in &rows {
513 let try_number = i32::try_from(claimed[*instance]).unwrap_or(i32::MAX);
514 query = query
515 .bind(*attempt)
516 .bind(*instance)
517 .bind(try_number)
518 .bind(*worker);
519 }
520 query.execute(&mut *tx).await?;
521 }
522 claimed
523 });
524 tries.extend(claimed);
525 }
526 Ok(tries)
527 }
528
529 pub async fn start_chained_attempt(
538 &self,
539 instance_id: &str,
540 chained_run_id: &str,
541 now: Timestamp,
542 ) -> Result<Option<(String, u32)>, DbError> {
543 const CLAIM: &str = "UPDATE task_instances SET state = 'running', \
544 try_number = try_number + 1, ready_at = NULL, queued_reason = NULL, updated_at = $1{ts} \
545 WHERE id = $2{uuid} AND state = 'queued'";
546 const TRY: &str = "SELECT try_number FROM task_instances WHERE id = $1{uuid}";
547 const INSERT: &str = "INSERT INTO attempts \
548 (id, task_instance_id, try_number, assigned_at, started_at, chained_run_id) \
549 VALUES ($1{uuid}, $2{uuid}, $3, $4{ts}, $4{ts}, $5{uuid})";
550 let id = Uuid::now_v7().to_string();
551 let now = db_time(now);
552 let try_number: Option<i32> = in_tx!(self, |tx, backend| {
553 let claimed = sqlx::query(sql(backend, CLAIM))
554 .bind(&now)
555 .bind(instance_id)
556 .execute(&mut *tx)
557 .await?
558 .rows_affected();
559 if claimed == 1 {
560 let try_number: i32 = sqlx::query_scalar(sql(backend, TRY))
561 .bind(instance_id)
562 .fetch_one(&mut *tx)
563 .await?;
564 sqlx::query(sql(backend, INSERT))
565 .bind(&id)
566 .bind(instance_id)
567 .bind(try_number)
568 .bind(&now)
569 .bind(chained_run_id)
570 .execute(&mut *tx)
571 .await?;
572 Some(try_number)
573 } else {
574 None
575 }
576 });
577 Ok(try_number.map(|n| (id, u32::try_from(n).unwrap_or(0))))
578 }
579
580 pub async fn chained_attempts(&self) -> Result<Vec<ChainedAttempt>, DbError> {
588 const OPEN: &str = concat!(
589 "SELECT a.id{text}, t.id{text}, t.run_id{text}, t.task_id, \
590 t.map_index, {ts<}a.assigned_at{>ts}, a.chained_run_id{text}, c.state, \
591 r.dag_version_id{text}, \
592 (r.cancel_requested_at IS NOT NULL OR t.cancel_requested_at IS NOT NULL), \
593 r.kind, {ts<}r.planned_for{>ts}, {ts<}r.since{>ts}, {ts<}c.ended_at{>ts} ",
594 chained_from!(),
595 " ORDER BY a.assigned_at, a.id"
596 );
597 type Row = (
598 String,
599 String,
600 String,
601 String,
602 i32,
603 String,
604 String,
605 Option<String>,
606 String,
607 bool,
608 String,
609 String,
610 String,
611 Option<String>,
612 );
613 if self.skipped(crate::probe::Check::ChainedAttempts).await? {
614 return Ok(Vec::new());
615 }
616 let rows: Vec<Row> = on_pool!(self, |pool, backend| {
617 sqlx::query_as(sql(backend, OPEN)).fetch_all(pool).await?
618 });
619 let mut found = Vec::with_capacity(rows.len());
620 for row in rows {
621 let (id, instance_id, run_id, task_id, map_index, at, chained, state, version, cancel) = (
622 row.0, row.1, row.2, row.3, row.4, row.5, row.6, row.7, row.8, row.9,
623 );
624 found.push(ChainedAttempt {
625 id,
626 instance_id,
627 run_id,
628 task_id: TaskId::new(&task_id).map_err(|e| DbError::InvalidData {
629 what: "task_instances.task_id",
630 reason: e.to_string(),
631 })?,
632 map_index,
633 started_at: parse_time("attempts.assigned_at", &at)?,
634 chained_run_id: chained,
635 chained_state: state.map(|s| from_name("runs.state", s)).transpose()?,
636 dag: self.dag_version(&version).await?,
637 cancel_requested: cancel,
638 run_kind: from_name("runs.kind", row.10)?,
639 planned_for: parse_time("runs.planned_for", &row.11)?,
640 since: parse_time("runs.since", &row.12)?,
641 chained_ended_at: row
642 .13
643 .map(|at| parse_time("runs.ended_at", &at))
644 .transpose()?,
645 });
646 }
647 Ok(found)
648 }
649
650 pub async fn undo_assignment(
658 &self,
659 attempt_id: &str,
660 state: TaskInstanceState,
661 ready_at: Option<Timestamp>,
662 reason: Option<&str>,
663 now: Timestamp,
664 ) -> Result<(), DbError> {
665 const RESET: &str = "UPDATE task_instances SET state = $1, ready_at = $2{ts}, \
666 queued_reason = $3, try_number = try_number - 1, updated_at = $4{ts} \
667 WHERE id = (SELECT task_instance_id FROM attempts WHERE id = $5{uuid}) \
668 AND state = 'running'";
669 const DELETE: &str = "DELETE FROM attempts WHERE id = $1{uuid} AND status IS NULL";
670 in_tx!(self, |tx, backend| {
671 sqlx::query(sql(backend, RESET))
672 .bind(state.to_string())
673 .bind(ready_at.map(db_time))
674 .bind(reason)
675 .bind(db_time(now))
676 .bind(attempt_id)
677 .execute(&mut *tx)
678 .await?;
679 sqlx::query(sql(backend, DELETE))
680 .bind(attempt_id)
681 .execute(&mut *tx)
682 .await?;
683 });
684 Ok(())
685 }
686
687 pub async fn first_start(&self, instance_id: &str) -> Result<Option<Timestamp>, DbError> {
699 const FIRST: &str = "SELECT {ts<}started_at{>ts} FROM attempts \
700 WHERE task_instance_id = $1{uuid} AND started_at IS NOT NULL \
701 ORDER BY started_at LIMIT 1";
702 let first: Option<String> = on_pool!(self, |pool, backend| {
703 sqlx::query_scalar(sql(backend, FIRST))
704 .bind(instance_id)
705 .fetch_optional(pool)
706 .await?
707 });
708 first
709 .map(|at| parse_time("attempts.started_at", &at))
710 .transpose()
711 }
712
713 pub async fn first_starts(
720 &self,
721 instance_ids: &[&str],
722 ) -> Result<BTreeMap<String, Timestamp>, DbError> {
723 let mut first = BTreeMap::new();
724 for chunk in instance_ids.chunks(OUTPUTS_PER_QUERY) {
725 let wanted: Vec<String> = (1..=chunk.len()).map(|n| format!("${n}{{uuid}}")).collect();
726 let text = format!(
727 "SELECT task_instance_id{{text}}, {{ts<}}MIN(started_at){{>ts}} FROM attempts \
728 WHERE started_at IS NOT NULL AND task_instance_id IN ({}) \
729 GROUP BY task_instance_id",
730 wanted.join(", ")
731 );
732 let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
733 let mut query = sqlx::query_as(sql_text(backend, &text));
734 for id in chunk {
735 query = query.bind(*id);
736 }
737 query.fetch_all(pool).await?
738 });
739 for (instance_id, at) in rows {
740 first.insert(instance_id, parse_time("attempts.started_at", &at)?);
741 }
742 }
743 Ok(first)
744 }
745
746 pub async fn attempt(&self, attempt_id: &str) -> Result<Option<StoredAttempt>, DbError> {
752 let query = ATTEMPT_BY_ID;
753 let row: Option<AttemptRow> = on_pool!(self, |pool, backend| {
754 sqlx::query_as(sql(backend, query))
755 .bind(attempt_id)
756 .fetch_optional(pool)
757 .await?
758 });
759 row.map(stored_attempt).transpose()
760 }
761
762 pub async fn open_attempts(
768 &self,
769 worker_id: Option<&str>,
770 ) -> Result<Vec<StoredAttempt>, DbError> {
771 let query = OPEN_ATTEMPTS;
772 let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
773 sqlx::query_as(sql(backend, query))
774 .bind(worker_id)
775 .fetch_all(pool)
776 .await?
777 });
778 rows.into_iter().map(stored_attempt).collect()
779 }
780
781 pub async fn mark_replaced(
788 &self,
789 attempt_ids: &[String],
790 now: Timestamp,
791 ) -> Result<(), DbError> {
792 const MARK: &str = "UPDATE attempts SET replaced_at = COALESCE(replaced_at, $1{ts}) \
793 WHERE id = $2{uuid} AND status IS NULL";
794 in_tx!(self, |tx, backend| {
795 for attempt_id in attempt_ids {
796 sqlx::query(sql(backend, MARK))
797 .bind(db_time(now))
798 .bind(attempt_id)
799 .execute(&mut *tx)
800 .await?;
801 }
802 });
803 Ok(())
804 }
805
806 pub async fn clear_replaced(&self, attempt_ids: &[String]) -> Result<(), DbError> {
813 const CLEAR: &str = "UPDATE attempts SET replaced_at = NULL \
814 WHERE id = $1{uuid} AND replaced_at IS NOT NULL";
815 in_tx!(self, |tx, backend| {
816 for attempt_id in attempt_ids {
817 sqlx::query(sql(backend, CLEAR))
818 .bind(attempt_id)
819 .execute(&mut *tx)
820 .await?;
821 }
822 });
823 Ok(())
824 }
825
826 pub async fn replaced_attempts(&self) -> Result<Vec<String>, DbError> {
832 const REPLACED: &str = concat!(
833 "SELECT id{text} ",
834 replaced_from!(),
835 " ORDER BY replaced_at, id"
836 );
837 if self.skipped(crate::probe::Check::ReplacedAttempts).await? {
838 return Ok(Vec::new());
839 }
840 Ok(on_pool!(self, |pool, backend| {
841 sqlx::query_scalar(sql(backend, REPLACED))
842 .fetch_all(pool)
843 .await?
844 }))
845 }
846
847 pub async fn set_task_result(&self, attempt_id: &str, result: &[u8]) -> Result<(), DbError> {
853 const SET: &str = "UPDATE attempts SET task_result = $1 \
855 WHERE id = $2{uuid} AND status IS NULL AND task_result IS NULL";
856 in_tx!(self, |tx, backend| {
857 sqlx::query(sql(backend, SET))
858 .bind(result)
859 .bind(attempt_id)
860 .execute(&mut *tx)
861 .await?;
862 });
863 Ok(())
864 }
865
866 pub async fn task_result(&self, attempt_id: &str) -> Result<Option<Vec<u8>>, DbError> {
872 const GET: &str = "SELECT task_result FROM attempts WHERE id = $1{uuid}";
873 let row: Option<(Option<Vec<u8>>,)> = on_pool!(self, |pool, backend| {
874 sqlx::query_as(sql(backend, GET))
875 .bind(attempt_id)
876 .fetch_optional(pool)
877 .await?
878 });
879 Ok(row.and_then(|(result,)| result))
880 }
881
882 pub async fn add_cleanup_handles(
890 &self,
891 attempt_id: &str,
892 first: u32,
893 handles: &[String],
894 limit: usize,
895 ) -> Result<bool, DbError> {
896 const STORED: &str = "SELECT position, CAST(OCTET_LENGTH(handle) AS BIGINT) \
897 FROM cleanup_handles WHERE attempt_id = $1{uuid}";
898 const ADD: &str = "INSERT INTO cleanup_handles (attempt_id, position, handle) \
899 VALUES ($1{uuid}, $2, $3) ON CONFLICT (attempt_id, position) DO NOTHING";
900 let fitted = in_tx!(self, |tx, backend| {
901 let stored: Vec<(i32, i64)> = sqlx::query_as(sql(backend, STORED))
902 .bind(attempt_id)
903 .fetch_all(&mut *tx)
904 .await?;
905 let mut size = stored.iter().fold(0_usize, |size, (_, bytes)| {
906 size.saturating_add(usize::try_from(*bytes).unwrap_or(usize::MAX))
907 });
908 let taken: BTreeSet<i32> = stored.into_iter().map(|(position, _)| position).collect();
909 let mut fitted = true;
910 for (index, handle) in handles.iter().enumerate() {
911 let index = u32::try_from(index).unwrap_or(u32::MAX);
913 let position = i32::try_from(first.saturating_add(index)).unwrap_or(i32::MAX);
914 if taken.contains(&position) {
916 continue;
917 }
918 size = size.saturating_add(handle.len());
919 if size > limit {
920 fitted = false;
921 break;
922 }
923 sqlx::query(sql(backend, ADD))
924 .bind(attempt_id)
925 .bind(position)
926 .bind(handle)
927 .execute(&mut *tx)
928 .await?;
929 }
930 fitted
931 });
932 Ok(fitted)
933 }
934
935 pub async fn cleanup_handles_unbroken(&self, attempt_id: &str) -> Result<u32, DbError> {
943 const POSITIONS: &str = "SELECT position FROM cleanup_handles \
944 WHERE attempt_id = $1{uuid} ORDER BY position";
945 let rows: Vec<(i32,)> = on_pool!(self, |pool, backend| {
946 sqlx::query_as(sql(backend, POSITIONS))
947 .bind(attempt_id)
948 .fetch_all(pool)
949 .await?
950 });
951 let unbroken = rows
952 .iter()
953 .zip(0_i32..)
954 .take_while(|((position,), expected)| position == expected)
955 .count();
956 Ok(u32::try_from(unbroken).unwrap_or(u32::MAX))
957 }
958
959 pub async fn cleanup_handles(&self, attempt_id: &str) -> Result<Vec<String>, DbError> {
965 const HANDLES: &str = "SELECT handle FROM cleanup_handles WHERE attempt_id = $1{uuid} \
966 ORDER BY position";
967 let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
968 sqlx::query_as(sql(backend, HANDLES))
969 .bind(attempt_id)
970 .fetch_all(pool)
971 .await?
972 });
973 Ok(rows.into_iter().map(|(handle,)| handle).collect())
974 }
975
976 pub async fn move_cleanup(
983 &self,
984 attempt_id: &str,
985 result: &[u8],
986 not_before: Timestamp,
987 ) -> Result<(), DbError> {
988 const MOVE: &str = "UPDATE attempts SET moved_from = worker_id, worker_id = NULL, \
989 cleanup_origin = COALESCE(cleanup_origin, worker_id), \
990 moved_at = NULL, cleanup_moves = cleanup_moves + 1, \
991 task_result = COALESCE(task_result, $1), \
992 cleanup_not_before = $2{ts} WHERE id = $3{uuid} AND status IS NULL";
993 in_tx!(self, |tx, backend| {
994 sqlx::query(sql(backend, MOVE))
995 .bind(result)
996 .bind(db_time(not_before))
997 .bind(attempt_id)
998 .execute(&mut *tx)
999 .await?;
1000 });
1001 Ok(())
1002 }
1003
1004 pub async fn take_back_cleanup(
1013 &self,
1014 attempt_id: &str,
1015 worker_id: &str,
1016 drop_result: bool,
1017 ) -> Result<bool, DbError> {
1018 const BACK: &str = "UPDATE attempts SET worker_id = $1, moved_from = NULL, \
1019 moved_at = NULL, cleanup_not_before = NULL, cleanup_moves = cleanup_moves - 1, \
1020 cleanup_origin = CASE WHEN cleanup_moves = 1 THEN NULL ELSE cleanup_origin END, \
1021 task_result = CASE WHEN $2 THEN NULL ELSE task_result END \
1022 WHERE id = $3{uuid} AND status IS NULL AND worker_id IS NULL AND moved_from = $1 \
1023 AND cleanup_moves > 0";
1024 let updated = in_tx!(self, |tx, backend| {
1025 sqlx::query(sql(backend, BACK))
1026 .bind(worker_id)
1027 .bind(drop_result)
1028 .bind(attempt_id)
1029 .execute(&mut *tx)
1030 .await?
1031 .rows_affected()
1032 });
1033 Ok(updated == 1)
1034 }
1035
1036 pub async fn rest_owed_by(&self, attempt_id: &str) -> Result<Option<String>, DbError> {
1044 const FROM: &str = "SELECT cleanup_origin FROM attempts \
1045 WHERE id = $1{uuid} AND NOT rest_cleaned";
1046 let row: Option<(Option<String>,)> = on_pool!(self, |pool, backend| {
1047 sqlx::query_as(sql(backend, FROM))
1048 .bind(attempt_id)
1049 .fetch_optional(pool)
1050 .await?
1051 });
1052 Ok(row.and_then(|(from,)| from))
1053 }
1054
1055 pub async fn cleanup_moved_from(&self, attempt_id: &str) -> Result<Option<String>, DbError> {
1062 const FROM: &str = "SELECT moved_from FROM attempts \
1063 WHERE id = $1{uuid} AND status IS NULL AND worker_id IS NULL";
1064 let row: Option<(Option<String>,)> = on_pool!(self, |pool, backend| {
1065 sqlx::query_as(sql(backend, FROM))
1066 .bind(attempt_id)
1067 .fetch_optional(pool)
1068 .await?
1069 });
1070 Ok(row.and_then(|(from,)| from))
1071 }
1072
1073 pub async fn assign_cleanup(
1079 &self,
1080 attempt_id: &str,
1081 worker_id: &str,
1082 now: Timestamp,
1083 ) -> Result<bool, DbError> {
1084 const ASSIGN: &str = "UPDATE attempts SET worker_id = $1, moved_at = $2{ts} \
1085 WHERE id = $3{uuid} AND status IS NULL AND worker_id IS NULL";
1086 const REASON: &str = "UPDATE task_instances SET queued_reason = NULL \
1087 WHERE id = (SELECT task_instance_id FROM attempts WHERE id = $1{uuid})";
1088 let updated = in_tx!(self, |tx, backend| {
1089 let updated = sqlx::query(sql(backend, ASSIGN))
1090 .bind(worker_id)
1091 .bind(db_time(now))
1092 .bind(attempt_id)
1093 .execute(&mut *tx)
1094 .await?
1095 .rows_affected();
1096 sqlx::query(sql(backend, REASON))
1097 .bind(attempt_id)
1098 .execute(&mut *tx)
1099 .await?;
1100 updated
1101 });
1102 Ok(updated == 1)
1103 }
1104
1105 pub async fn unassign_cleanup(&self, attempt_id: &str) -> Result<(), DbError> {
1112 const BACK: &str = "UPDATE attempts SET worker_id = NULL, moved_at = NULL, \
1114 replaced_at = NULL WHERE id = $1{uuid} AND status IS NULL";
1115 in_tx!(self, |tx, backend| {
1116 sqlx::query(sql(backend, BACK))
1117 .bind(attempt_id)
1118 .execute(&mut *tx)
1119 .await?;
1120 });
1121 Ok(())
1122 }
1123
1124 pub async fn unstarted_cleanups(
1131 &self,
1132 cutoff: Timestamp,
1133 except_workers: &[String],
1134 limit: u32,
1135 ) -> Result<Vec<StoredAttempt>, DbError> {
1136 if self.skipped(crate::probe::Check::UnstartedCleanups).await? {
1137 return Ok(Vec::new());
1138 }
1139 let except = serde_json::to_string(except_workers).unwrap_or_else(|_| "[]".to_owned());
1140 let query = UNSTARTED_CLEANUPS;
1141 let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
1142 sqlx::query_as(sql(backend, query))
1143 .bind(db_time(cutoff))
1144 .bind(i64::from(limit))
1145 .bind(&except)
1146 .fetch_all(pool)
1147 .await?
1148 });
1149 rows.into_iter().map(stored_attempt).collect()
1150 }
1151
1152 pub async fn waiting_cleanups(
1159 &self,
1160 now: Timestamp,
1161 ) -> Result<Vec<(String, ReadyInstance)>, DbError> {
1162 const WAITING: &str = "SELECT t.id{text}, r.id{text}, t.task_id, t.try_number, r.kind, \
1163 {ts<}r.planned_for{>ts}, {ts<}r.since{>ts}, r.dag_version_id{text}, p.content_hash, \
1164 t.queued_reason, p.schedr_version, t.map_index, r.cancel_requested_at IS NOT NULL \
1165 FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
1166 JOIN runs r ON r.id = t.run_id \
1167 JOIN dag_versions v ON v.id = r.dag_version_id \
1168 JOIN parse_results p ON p.id = v.parse_result_id \
1169 WHERE a.status IS NULL AND a.worker_id IS NULL AND a.chained_run_id IS NULL \
1170 AND a.cleanup_not_before <= $1{ts} \
1171 ORDER BY a.assigned_at, a.id";
1172 const IDS: &str = concat!(
1173 "SELECT a.id{text}, a.task_instance_id{text} ",
1174 waiting_cleanups_any_time_from!()
1175 );
1176 if self.skipped(crate::probe::Check::WaitingCleanups).await? {
1177 return Ok(Vec::new());
1178 }
1179 let rows: Vec<ReadyRow> = on_pool!(self, |pool, backend| {
1180 sqlx::query_as(sql(backend, WAITING))
1181 .bind(db_time(now))
1182 .fetch_all(pool)
1183 .await?
1184 });
1185 if rows.is_empty() {
1186 return Ok(Vec::new());
1187 }
1188 let ids: Vec<(String, String)> = on_pool!(self, |pool, backend| {
1189 sqlx::query_as(sql(backend, IDS)).fetch_all(pool).await?
1190 });
1191 let mut waiting = Vec::with_capacity(rows.len());
1192 for row in rows {
1193 let dag = self.dag_version(&row.7).await?;
1194 let instance = ready(row, dag)?;
1195 if let Some((attempt, _)) = ids.iter().find(|(_, i)| *i == instance.instance_id) {
1196 waiting.push((attempt.clone(), instance));
1197 }
1198 }
1199 Ok(waiting)
1200 }
1201
1202 pub async fn active_attempts(&self) -> Result<Vec<ActiveAttempt>, DbError> {
1209 let query = ACTIVE_ATTEMPTS;
1210 let rows: Vec<(String, String, String, String)> = on_pool!(self, |pool, backend| {
1211 sqlx::query_as(sql(backend, query)).fetch_all(pool).await?
1212 });
1213 rows.into_iter()
1214 .map(|(attempt_id, dag_id, run_id, task_id)| {
1215 Ok(ActiveAttempt {
1216 attempt_id,
1217 dag_id: DagId::new(dag_id).map_err(|e| DbError::InvalidData {
1218 what: "runs.dag_id",
1219 reason: e.to_string(),
1220 })?,
1221 run_id,
1222 task_id: task_id_of(task_id)?,
1223 })
1224 })
1225 .collect()
1226 }
1227
1228 pub async fn active_counts(
1235 &self,
1236 dag_id: &DagId,
1237 ) -> Result<Vec<(String, TaskId, u32)>, DbError> {
1238 const COUNTS: &str = "SELECT t.run_id{text}, t.task_id, COUNT(*) \
1239 FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
1240 JOIN runs r ON r.id = t.run_id WHERE a.status IS NULL AND a.chained_run_id IS NULL \
1241 AND r.dag_id = $1 \
1242 GROUP BY t.run_id, t.task_id ORDER BY t.run_id, t.task_id";
1243 let rows: Vec<(String, String, i64)> = on_pool!(self, |pool, backend| {
1244 sqlx::query_as(sql(backend, COUNTS))
1245 .bind(dag_id.as_str())
1246 .fetch_all(pool)
1247 .await?
1248 });
1249 rows.into_iter()
1250 .map(|(run, task, count)| {
1251 Ok((
1252 run,
1253 task_id_of(task)?,
1254 u32::try_from(count).unwrap_or(u32::MAX),
1255 ))
1256 })
1257 .collect()
1258 }
1259
1260 pub async fn unstarted_attempts(
1269 &self,
1270 cutoff: Timestamp,
1271 except_workers: &[String],
1272 limit: u32,
1273 ) -> Result<Vec<StoredAttempt>, DbError> {
1274 if self.skipped(crate::probe::Check::Unstarted).await? {
1275 return Ok(Vec::new());
1276 }
1277 let except = serde_json::to_string(except_workers).unwrap_or_else(|_| "[]".to_owned());
1278 let query = UNSTARTED_ATTEMPTS;
1279 let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
1280 sqlx::query_as(sql(backend, query))
1281 .bind(db_time(cutoff))
1282 .bind(i64::from(limit))
1283 .bind(&except)
1284 .fetch_all(pool)
1285 .await?
1286 });
1287 rows.into_iter().map(stored_attempt).collect()
1288 }
1289
1290 pub async fn mark_started(
1298 &self,
1299 attempt_id: &str,
1300 start_method: &str,
1301 at: Timestamp,
1302 ) -> Result<bool, DbError> {
1303 const START: &str = "UPDATE attempts SET started_at = COALESCE(started_at, \
1304 CASE WHEN $1{ts} < assigned_at THEN assigned_at ELSE $1{ts} END), \
1305 start_method = $2, moved_at = NULL WHERE id = $3{uuid} AND status IS NULL";
1306 let now = at;
1307 let updated = in_tx!(self, |tx, backend| {
1308 sqlx::query(sql(backend, START))
1309 .bind(db_time(now))
1310 .bind(start_method)
1311 .bind(attempt_id)
1312 .execute(&mut *tx)
1313 .await?
1314 .rows_affected()
1315 });
1316 Ok(updated == 1)
1317 }
1318
1319 pub async fn mark_started_many(
1327 &self,
1328 starts: &[(&str, Timestamp)],
1329 start_method: &str,
1330 ) -> Result<BTreeSet<String>, DbError> {
1331 const SQLITE: &str = "UPDATE attempts SET started_at = COALESCE(attempts.started_at, \
1333 CASE WHEN p.at < attempts.assigned_at THEN attempts.assigned_at ELSE p.at END), \
1334 start_method = $1, moved_at = NULL \
1335 FROM (SELECT json_extract(value, '$[0]') AS id, json_extract(value, '$[1]') AS at \
1336 FROM json_each($2)) p \
1337 WHERE attempts.id = p.id AND attempts.status IS NULL RETURNING attempts.id";
1338 const POSTGRES: &str = "UPDATE attempts a SET started_at = COALESCE(a.started_at, \
1339 CASE WHEN p.at < a.assigned_at THEN a.assigned_at ELSE p.at END), \
1340 start_method = $1, moved_at = NULL \
1341 FROM (SELECT (value->>0)::uuid AS id, (value->>1)::timestamptz AS at \
1342 FROM jsonb_array_elements($2::jsonb)) p \
1343 WHERE a.id = p.id AND a.status IS NULL RETURNING a.id::text";
1344 if starts.is_empty() {
1345 return Ok(BTreeSet::new());
1346 }
1347 let pairs: Vec<(&str, String)> =
1348 starts.iter().map(|(id, at)| (*id, db_time(*at))).collect();
1349 let list = crate::query::to_json(&pairs);
1350 let started: Vec<String> = in_tx!(self, |tx, backend| {
1351 let query = match backend {
1352 crate::backend::Backend::Sqlite => SQLITE,
1353 crate::backend::Backend::Postgres => POSTGRES,
1354 };
1355 sqlx::query_scalar(sql(backend, query))
1356 .bind(start_method)
1357 .bind(&list)
1358 .fetch_all(&mut *tx)
1359 .await?
1360 });
1361 Ok(started.into_iter().collect())
1362 }
1363
1364 pub async fn mark_adopted(&self, attempt_id: &str, now: Timestamp) -> Result<(), DbError> {
1372 const START: &str = "UPDATE attempts SET started_at = COALESCE(started_at, $1{ts}), \
1373 moved_at = NULL WHERE id = $2{uuid} AND status IS NULL";
1374 in_tx!(self, |tx, backend| {
1375 sqlx::query(sql(backend, START))
1376 .bind(db_time(now))
1377 .bind(attempt_id)
1378 .execute(&mut *tx)
1379 .await?
1380 .rows_affected()
1381 });
1382 Ok(())
1383 }
1384
1385 pub async fn attempts_by_ids(&self, ids: &[&str]) -> Result<Vec<StoredAttempt>, DbError> {
1392 const BY_IDS: &str = "SELECT a.id{text}, a.task_instance_id{text}, t.run_id{text}, \
1393 t.task_id, a.try_number, a.worker_id, a.status, a.started_at IS NOT NULL, \
1394 t.map_index, a.task_result IS NOT NULL, a.cleanup_moves, \
1395 a.moved_at IS NOT NULL FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
1396 WHERE a.id IN (SELECT value{uuid} FROM {json_each}($1{json}))";
1397 if ids.is_empty() {
1398 return Ok(Vec::new());
1399 }
1400 let list = crate::query::to_json(&ids);
1401 let rows: Vec<AttemptRow> = on_pool!(self, |pool, backend| {
1402 sqlx::query_as(sql(backend, BY_IDS))
1403 .bind(&list)
1404 .fetch_all(pool)
1405 .await?
1406 });
1407 rows.into_iter().map(stored_attempt).collect()
1408 }
1409
1410 pub async fn end_attempts(
1418 &self,
1419 ends: &[(&str, &AttemptEnd)],
1420 now: Timestamp,
1421 ) -> Result<BTreeSet<String>, DbError> {
1422 let now = db_time(now);
1423 let mut recorded = BTreeSet::new();
1424 in_tx!(self, |tx, backend| {
1425 for chunk in ends.chunks(ENDS_PER_STATEMENT) {
1426 let rows: Vec<String> = (0..chunk.len())
1427 .map(|i| {
1428 let n = 1 + i * 16;
1429 format!(
1430 "(${}{{uuid}}, ${}, ${}, ${}, ${}, ${}, ${}{{json}}, ${}, ${}, \
1431 ${}{{json}}, ${}, ${}, ${}, ${}, ${}, ${}{{json}})",
1432 n + 1,
1433 n + 2,
1434 n + 3,
1435 n + 4,
1436 n + 5,
1437 n + 6,
1438 n + 7,
1439 n + 8,
1440 n + 9,
1441 n + 10,
1442 n + 11,
1443 n + 12,
1444 n + 13,
1445 n + 14,
1446 n + 15,
1447 n + 16
1448 )
1449 })
1450 .collect();
1451 let text = format!(
1453 "UPDATE attempts AS t SET status = v.column2, exit_code = v.column3, \
1454 signal = v.column4, peak_memory_bytes = v.column5, error_kind = v.column6, \
1455 error_summary = v.column7, code_hash = v.column8, ended_at = $1{{ts}}, \
1456 duration_ms = v.column9, usage = v.column10, core_dumped = v.column11, \
1457 cleanup_result = CASE WHEN NOT t.rest_cleaned THEN v.column12 \
1458 WHEN t.cleanup_result IN ('failed', 'worker_lost') THEN t.cleanup_result \
1459 WHEN v.column12 IN ('failed', 'worker_lost') THEN v.column12 \
1460 WHEN t.cleanup_result = 'ok' OR v.column12 = 'ok' THEN 'ok' \
1461 ELSE COALESCE(v.column12, t.cleanup_result) END, \
1462 cleanup_tries = CASE WHEN NOT t.rest_cleaned THEN v.column13 \
1463 ELSE COALESCE(t.cleanup_tries, 0) + COALESCE(v.column13, 0) END, \
1464 cleanup_duration_ms = CASE WHEN NOT t.rest_cleaned THEN v.column14 \
1465 ELSE COALESCE(t.cleanup_duration_ms, 0) + COALESCE(v.column14, 0) END, \
1466 cleanup_error_kind = CASE WHEN NOT t.rest_cleaned THEN v.column15 \
1467 ELSE COALESCE(t.cleanup_error_kind, v.column15) END, \
1468 cleanup_error_summary = CASE WHEN NOT t.rest_cleaned THEN v.column16 \
1469 ELSE COALESCE(t.cleanup_error_summary, v.column16) END, \
1470 task_result = NULL \
1471 FROM (VALUES {}) AS v \
1472 WHERE t.id = v.column1 AND t.status IS NULL RETURNING id{{text}}",
1473 rows.join(", ")
1474 );
1475 let mut update =
1476 sqlx::query_scalar::<_, String>(sql_text(backend, &text)).bind(&now);
1477 for (attempt_id, end) in chunk {
1478 let cleanup = end.cleanup.as_ref();
1479 update = update
1480 .bind(*attempt_id)
1481 .bind(end.status.to_string())
1482 .bind(end.exit_code)
1483 .bind(end.signal)
1484 .bind(
1485 end.peak_memory_bytes
1486 .map(|b| i64::try_from(b).unwrap_or(i64::MAX)),
1487 )
1488 .bind(end.error_kind.as_deref())
1489 .bind(end.error_summary.clone().map(crate::query::storable_json))
1490 .bind(end.code_hash.as_deref())
1491 .bind(
1492 end.duration_ms
1493 .map(|ms| i64::try_from(ms).unwrap_or(i64::MAX)),
1494 )
1495 .bind(end.usage.as_ref().map(crate::query::to_json))
1496 .bind(end.core_dumped)
1497 .bind(cleanup.map(|c| c.result.to_string()))
1498 .bind(cleanup.map(|c| i64::from(c.tries)))
1499 .bind(cleanup.map(|c| i64::try_from(c.duration_ms).unwrap_or(i64::MAX)))
1500 .bind(cleanup.and_then(|c| c.error_kind.as_deref()))
1501 .bind(
1502 cleanup
1503 .and_then(|c| c.error_summary.clone())
1504 .map(crate::query::storable_json),
1505 );
1506 }
1507 recorded.extend(update.fetch_all(&mut *tx).await?);
1508 }
1509 });
1510 Ok(recorded)
1511 }
1512
1513 pub async fn end_attempt(
1521 &self,
1522 attempt_id: &str,
1523 end: &AttemptEnd,
1524 now: Timestamp,
1525 ) -> Result<bool, DbError> {
1526 const END: &str = "UPDATE attempts SET status = $1, exit_code = $2, signal = $3, \
1527 peak_memory_bytes = $4, error_kind = $5, error_summary = $6{json}, code_hash = $7, \
1528 ended_at = $8{ts}, duration_ms = $9, usage = $10{json}, core_dumped = $11, \
1529 cleanup_result = CASE WHEN NOT rest_cleaned THEN $12 \
1530 WHEN cleanup_result IN ('failed', 'worker_lost') THEN cleanup_result \
1531 WHEN $12 IN ('failed', 'worker_lost') THEN $12 \
1532 WHEN cleanup_result = 'ok' OR $12 = 'ok' THEN 'ok' \
1533 ELSE COALESCE($12, cleanup_result) END, \
1534 cleanup_tries = CASE WHEN NOT rest_cleaned THEN $13 \
1535 ELSE COALESCE(cleanup_tries, 0) + COALESCE($13, 0) END, \
1536 cleanup_duration_ms = CASE WHEN NOT rest_cleaned THEN $14 \
1537 ELSE COALESCE(cleanup_duration_ms, 0) + COALESCE($14, 0) END, \
1538 cleanup_error_kind = CASE WHEN NOT rest_cleaned THEN $15 \
1539 ELSE COALESCE(cleanup_error_kind, $15) END, \
1540 cleanup_error_summary = CASE WHEN NOT rest_cleaned THEN $16{json} \
1541 ELSE COALESCE(cleanup_error_summary, $16{json}) END, \
1542 task_result = NULL \
1543 WHERE id = $17{uuid} AND status IS NULL";
1544 let cleanup = end.cleanup.as_ref();
1545 let updated = in_tx!(self, |tx, backend| {
1546 sqlx::query(sql(backend, END))
1547 .bind(end.status.to_string())
1548 .bind(end.exit_code)
1549 .bind(end.signal)
1550 .bind(
1551 end.peak_memory_bytes
1552 .map(|b| i64::try_from(b).unwrap_or(i64::MAX)),
1553 )
1554 .bind(end.error_kind.as_deref())
1555 .bind(end.error_summary.clone().map(crate::query::storable_json))
1556 .bind(end.code_hash.as_deref())
1557 .bind(db_time(now))
1558 .bind(
1559 end.duration_ms
1560 .map(|ms| i64::try_from(ms).unwrap_or(i64::MAX)),
1561 )
1562 .bind(end.usage.as_ref().map(crate::query::to_json))
1563 .bind(end.core_dumped)
1564 .bind(cleanup.map(|c| c.result.to_string()))
1565 .bind(cleanup.map(|c| i64::from(c.tries)))
1566 .bind(cleanup.map(|c| i64::try_from(c.duration_ms).unwrap_or(i64::MAX)))
1567 .bind(cleanup.and_then(|c| c.error_kind.as_deref()))
1568 .bind(
1569 cleanup
1570 .and_then(|c| c.error_summary.clone())
1571 .map(crate::query::storable_json),
1572 )
1573 .bind(attempt_id)
1574 .bind(true)
1575 .execute(&mut *tx)
1576 .await?
1577 .rows_affected()
1578 });
1579 Ok(updated == 1)
1580 }
1581
1582 pub async fn add_rest_cleanup(
1592 &self,
1593 attempt_id: &str,
1594 rest: &CleanupEnd,
1595 ) -> Result<bool, DbError> {
1596 const ADD: &str = "UPDATE attempts SET \
1597 cleanup_result = CASE WHEN cleanup_result IN ('failed', 'worker_lost') \
1598 THEN cleanup_result \
1599 WHEN $1 IN ('failed', 'worker_lost') THEN $1 \
1600 WHEN cleanup_result = 'ok' OR $1 = 'ok' THEN 'ok' ELSE $1 END, \
1601 cleanup_tries = COALESCE(cleanup_tries, 0) + $2, \
1602 cleanup_duration_ms = COALESCE(cleanup_duration_ms, 0) + $3, \
1603 cleanup_error_kind = COALESCE($4, cleanup_error_kind), \
1604 cleanup_error_summary = COALESCE($5{json}, cleanup_error_summary), \
1605 rest_cleaned = $7 \
1606 WHERE id = $6{uuid} AND NOT rest_cleaned";
1607 let updated = in_tx!(self, |tx, backend| {
1608 sqlx::query(sql(backend, ADD))
1609 .bind(rest.result.to_string())
1610 .bind(i64::from(rest.tries))
1611 .bind(i64::try_from(rest.duration_ms).unwrap_or(i64::MAX))
1612 .bind(rest.error_kind.as_deref())
1613 .bind(rest.error_summary.clone().map(crate::query::storable_json))
1614 .bind(attempt_id)
1615 .bind(true)
1616 .execute(&mut *tx)
1617 .await?
1618 .rows_affected()
1619 });
1620 Ok(updated == 1)
1621 }
1622
1623 pub async fn run_outputs(
1629 &self,
1630 run_id: &str,
1631 ) -> Result<BTreeMap<TaskId, serde_json::Value>, DbError> {
1632 const OUTPUTS: &str = "SELECT t.task_id, o.value{text} FROM outputs o \
1633 JOIN task_instances t ON t.id = o.task_instance_id \
1634 WHERE t.run_id = $1{uuid} AND t.map_index = -1";
1635 let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
1636 sqlx::query_as(sql(backend, OUTPUTS))
1637 .bind(run_id)
1638 .fetch_all(pool)
1639 .await?
1640 });
1641 rows.into_iter()
1642 .map(|(task_id, value)| Ok((task_id_of(task_id)?, from_json("outputs.value", &value)?)))
1643 .collect()
1644 }
1645
1646 pub async fn upstream_outcomes(
1654 &self,
1655 run_id: &str,
1656 tasks: &[&TaskId],
1657 ) -> Result<BTreeMap<TaskId, Option<String>>, DbError> {
1658 let mut outcomes = BTreeMap::new();
1659 for chunk in tasks.chunks(OUTPUTS_PER_QUERY) {
1660 let wanted: Vec<String> = (2..chunk.len() + 2).map(|n| format!("${n}")).collect();
1661 let text = format!(
1662 "SELECT task_id, state, outcome FROM task_instances \
1663 WHERE run_id = $1{{uuid}} AND state IN ('success', 'skipped') \
1664 AND map_index = -1 AND task_id IN ({})",
1665 wanted.join(", ")
1666 );
1667 let rows: Vec<(String, String, Option<String>)> = on_pool!(self, |pool, backend| {
1668 let mut query = sqlx::query_as(sql_text(backend, &text)).bind(run_id);
1669 for task in chunk {
1670 query = query.bind(task.as_str());
1671 }
1672 query.fetch_all(pool).await?
1673 });
1674 for (task_id, state, outcome) in rows {
1675 let outcome = (state == "success")
1676 .then(|| outcome.unwrap_or_else(|| schedr_model::DEFAULT_OUTCOME.to_owned()));
1677 outcomes.insert(task_id_of(task_id)?, outcome);
1678 }
1679 }
1680 Ok(outcomes)
1681 }
1682
1683 pub async fn outputs_of(
1690 &self,
1691 run_id: &str,
1692 tasks: &[&TaskId],
1693 ) -> Result<BTreeMap<TaskId, serde_json::Value>, DbError> {
1694 let mut outputs = BTreeMap::new();
1695 for chunk in tasks.chunks(OUTPUTS_PER_QUERY) {
1696 let wanted: Vec<String> = (2..chunk.len() + 2).map(|n| format!("${n}")).collect();
1697 let text = format!(
1698 "SELECT t.task_id, o.value{{text}} FROM outputs o \
1699 JOIN task_instances t ON t.id = o.task_instance_id \
1700 WHERE t.run_id = $1{{uuid}} AND t.map_index = -1 AND t.task_id IN ({})",
1701 wanted.join(", ")
1702 );
1703 let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
1704 let mut query = sqlx::query_as(sql_text(backend, &text)).bind(run_id);
1705 for task in chunk {
1706 query = query.bind(task.as_str());
1707 }
1708 query.fetch_all(pool).await?
1709 });
1710 for (task_id, value) in rows {
1711 outputs.insert(task_id_of(task_id)?, from_json("outputs.value", &value)?);
1712 }
1713 }
1714 Ok(outputs)
1715 }
1716
1717 pub async fn ended_in_order(
1725 &self,
1726 run_id: &str,
1727 tasks: &[&TaskId],
1728 ) -> Result<Vec<TaskId>, DbError> {
1729 let mut ended: Vec<TaskId> = Vec::new();
1730 let wanted: Vec<String> = (2..tasks.len() + 2).map(|n| format!("${n}")).collect();
1733 let text = format!(
1734 "SELECT task_id FROM task_instances \
1735 WHERE run_id = $1{{uuid}} AND map_index = -1 AND state = 'success' \
1736 AND task_id IN ({}) ORDER BY ended_at, task_id",
1737 wanted.join(", ")
1738 );
1739 if tasks.is_empty() {
1740 return Ok(ended);
1741 }
1742 let rows: Vec<(String,)> = on_pool!(self, |pool, backend| {
1743 let mut query = sqlx::query_as(sql_text(backend, &text)).bind(run_id);
1744 for task in tasks {
1745 query = query.bind(task.as_str());
1746 }
1747 query.fetch_all(pool).await?
1748 });
1749 for (task_id,) in rows {
1750 ended.push(task_id_of(task_id)?);
1751 }
1752 Ok(ended)
1753 }
1754
1755 pub async fn instance_results(
1763 &self,
1764 run_id: &str,
1765 task: &TaskId,
1766 ) -> Result<Vec<InstanceResult>, DbError> {
1767 const RESULTS: &str = "SELECT t.map_index, t.state, t.outcome, o.value{text} \
1768 FROM task_instances t LEFT JOIN outputs o ON o.task_instance_id = t.id \
1769 WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index >= 0 \
1770 ORDER BY t.map_index";
1771 let rows: Vec<(i32, String, Option<String>, Option<String>)> =
1772 on_pool!(self, |pool, backend| {
1773 sqlx::query_as(sql(backend, RESULTS))
1774 .bind(run_id)
1775 .bind(task.as_str())
1776 .fetch_all(pool)
1777 .await?
1778 });
1779 rows.into_iter()
1780 .map(|(map_index, state, outcome, value)| {
1781 Ok(InstanceResult {
1782 map_index,
1783 state: from_name("task_instances.state", state)?,
1784 outcome,
1785 output: value.map(|v| from_json("outputs.value", &v)).transpose()?,
1786 })
1787 })
1788 .collect()
1789 }
1790
1791 pub async fn instance_result(
1798 &self,
1799 run_id: &str,
1800 task: &TaskId,
1801 map_index: i32,
1802 ) -> Result<Option<InstanceResult>, DbError> {
1803 const RESULT: &str = "SELECT t.state, t.outcome, o.value{text} \
1804 FROM task_instances t LEFT JOIN outputs o ON o.task_instance_id = t.id \
1805 WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3";
1806 let row: Option<(String, Option<String>, Option<String>)> =
1807 on_pool!(self, |pool, backend| {
1808 sqlx::query_as(sql(backend, RESULT))
1809 .bind(run_id)
1810 .bind(task.as_str())
1811 .bind(map_index)
1812 .fetch_optional(pool)
1813 .await?
1814 });
1815 row.map(|(state, outcome, value)| {
1816 Ok(InstanceResult {
1817 map_index,
1818 state: from_name("task_instances.state", state)?,
1819 outcome,
1820 output: value.map(|v| from_json("outputs.value", &v)).transpose()?,
1821 })
1822 })
1823 .transpose()
1824 }
1825
1826 pub async fn unschedulable_instances(&self) -> Result<Vec<Unschedulable>, DbError> {
1833 const WAITING: &str = concat!(
1834 "SELECT r.id{text}, t.task_id, t.map_index, \
1835 r.dag_version_id{text}, {ts<}t.updated_at{>ts} ",
1836 unschedulable_from!(),
1837 " ORDER BY t.updated_at"
1838 );
1839 if self.skipped(crate::probe::Check::Unschedulable).await? {
1840 return Ok(Vec::new());
1841 }
1842 let rows: Vec<(String, String, i32, String, String)> = on_pool!(self, |pool, backend| {
1843 sqlx::query_as(sql(backend, WAITING))
1844 .fetch_all(pool)
1845 .await?
1846 });
1847 let mut waiting = Vec::with_capacity(rows.len());
1848 for (run_id, task_id, map_index, version_id, since) in rows {
1849 waiting.push(Unschedulable {
1850 run_id,
1851 task_id: task_id_of(task_id)?,
1852 map_index,
1853 dag: self.dag_version(&version_id).await?,
1854 since: parse_time("task_instances.updated_at", &since)?,
1855 });
1856 }
1857 Ok(waiting)
1858 }
1859
1860 pub async fn requeue_unschedulable(&self, now: Timestamp) -> Result<u64, DbError> {
1867 const REQUEUE: &str = "UPDATE task_instances SET state = 'queued', ready_at = $1{ts}, \
1868 queued_reason = NULL, updated_at = $1{ts} WHERE state = 'unschedulable'";
1869 let updated = in_tx!(self, |tx, backend| {
1870 sqlx::query(sql(backend, REQUEUE))
1871 .bind(db_time(now))
1872 .execute(&mut *tx)
1873 .await?
1874 .rows_affected()
1875 });
1876 Ok(updated)
1877 }
1878}
1879
1880fn task_id_of(text: String) -> Result<TaskId, DbError> {
1881 TaskId::new(text).map_err(|e| DbError::InvalidData {
1882 what: "task_instances.task_id",
1883 reason: e.to_string(),
1884 })
1885}
1886
1887fn ready(row: ReadyRow, dag: Arc<Dag>) -> Result<ReadyInstance, DbError> {
1888 let (
1889 instance_id,
1890 run_id,
1891 task_id,
1892 try_number,
1893 kind,
1894 planned_for,
1895 since,
1896 version_id,
1897 content_hash,
1898 queued_reason,
1899 parse_version,
1900 map_index,
1901 _,
1902 ) = row;
1903 Ok(ReadyInstance {
1904 instance_id,
1905 run_id,
1906 task_id: task_id_of(task_id)?,
1907 try_number: u32::try_from(try_number).unwrap_or(0),
1908 run_kind: from_name("runs.kind", kind)?,
1909 planned_for: parse_time("runs.planned_for", &planned_for)?,
1910 since: parse_time("runs.since", &since)?,
1911 dag,
1912 version_id,
1913 content_hash,
1914 queued_reason,
1915 parse_version,
1916 map_index,
1917 })
1918}
1919
1920fn stored_attempt(row: AttemptRow) -> Result<StoredAttempt, DbError> {
1921 let (
1922 id,
1923 instance_id,
1924 run_id,
1925 task_id,
1926 try_number,
1927 worker_id,
1928 status,
1929 started,
1930 map_index,
1931 kept,
1932 moves,
1933 moving,
1934 ) = row;
1935 Ok(StoredAttempt {
1936 id,
1937 instance_id,
1938 run_id,
1939 task_id: task_id_of(task_id)?,
1940 try_number: u32::try_from(try_number).unwrap_or(0),
1941 worker_id: worker_id.unwrap_or_default(),
1942 status: status
1943 .map(|s| from_name("attempts.status", s))
1944 .transpose()?,
1945 started,
1946 map_index,
1947 result_kept: kept,
1948 cleanup_moves: u32::try_from(moves).unwrap_or(0),
1949 moving,
1950 })
1951}