1use std::collections::BTreeMap;
7
8use jiff::Timestamp;
9use schedr_model::{
10 AttemptStatus, CleanupResult, DagId, RunKind, RunState, TaskId, TaskInstanceState,
11};
12
13use crate::database::{Database, DbError};
14use crate::query::{
15 db_time, from_json, from_name, on_pool, optional_time, parse_time, sql, to_json,
16};
17
18#[cfg(test)]
19mod tests;
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct StateCounts {
24 pub runs: Vec<(String, String, i64)>,
26 pub tasks: Vec<(String, i64)>,
28 pub workers: Vec<(String, i64)>,
30}
31
32pub const MAX_RUNS: u32 = 500;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RunRecord {
38 pub id: String,
40 pub dag_id: DagId,
42 pub kind: RunKind,
44 pub state: RunState,
46 pub planned_for: Timestamp,
48 pub since: Timestamp,
50 pub triggered_at: Timestamp,
52 pub triggered_by: String,
54 pub started_at: Option<Timestamp>,
56 pub ended_at: Option<Timestamp>,
58 pub late_failure: Option<String>,
60 pub parent_run_id: Option<String>,
63 pub backfill: Option<BackfillPlace>,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct BackfillPlace {
71 pub id: String,
73 pub index: u32,
75 pub total: u32,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct InstanceRecord {
82 pub task_id: TaskId,
84 pub map_index: i32,
87 pub reason: Option<String>,
89 pub state: TaskInstanceState,
91 pub outcome: Option<String>,
93 pub try_number: u32,
95 pub queued_reason: Option<String>,
97 pub cleanup_result: Option<CleanupResult>,
100 pub updated_at: Timestamp,
102}
103
104#[derive(Debug, Clone, PartialEq, Eq, Default)]
106pub struct CleanupRecord {
107 pub result: Option<CleanupResult>,
109 pub tries: Option<u32>,
111 pub duration_ms: Option<u64>,
113 pub error_kind: Option<String>,
115 pub error_summary: Option<String>,
117 pub moves: u32,
119 pub handles: Vec<String>,
121}
122
123impl CleanupRecord {
124 #[must_use]
126 pub fn is_empty(&self) -> bool {
127 *self == Self::default()
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct AttemptRecord {
134 pub id: String,
136 pub try_number: u32,
138 pub worker_id: Option<String>,
140 pub status: Option<AttemptStatus>,
142 pub exit_code: Option<i32>,
144 pub error_kind: Option<String>,
146 pub error_summary: Option<String>,
148 pub assigned_at: Timestamp,
150 pub started_at: Option<Timestamp>,
152 pub ended_at: Option<Timestamp>,
154 pub duration_ms: Option<u64>,
156 pub peak_memory_bytes: Option<u64>,
158 pub start_method: Option<String>,
160 pub usage: Option<schedr_model::runner::ProcessUsage>,
162 pub core_dumped: bool,
164 pub cleanup: CleanupRecord,
166 pub chained_run_id: Option<String>,
168}
169
170type RunRow = (
171 String,
172 String,
173 String,
174 String,
175 String,
176 String,
177 String,
178 String,
179 Option<String>,
180 Option<String>,
181 Option<String>,
182 Option<String>,
183 Option<String>,
184 i64,
185 i64,
186);
187
188type InstanceRow = (
189 String,
190 String,
191 Option<String>,
192 i32,
193 Option<String>,
194 String,
195 i32,
196 Option<String>,
197 Option<String>,
198);
199
200type CleanupRow = (
201 String,
202 Option<String>,
203 Option<i32>,
204 Option<i64>,
205 Option<String>,
206 Option<String>,
207 i32,
208);
209
210type AttemptRow = (
211 String,
212 i32,
213 Option<String>,
214 Option<String>,
215 Option<i32>,
216 Option<String>,
217 Option<String>,
218 String,
219 Option<String>,
220 Option<String>,
221 Option<i64>,
222 Option<i64>,
223 Option<String>,
224 Option<String>,
225 bool,
226 Option<String>,
227);
228
229const RUN_COLUMNS_ONE: &str = "SELECT id{text}, dag_id, kind, state, {ts<}planned_for{>ts}, \
230 {ts<}since{>ts}, {ts<}triggered_at{>ts}, triggered_by, {ts<}started_at{>ts}, \
231 {ts<}ended_at{>ts}, late_failure, parent_run_id{text}, backfill_id{text}, \
232 (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id \
233 AND (b.planned_for < runs.planned_for OR (b.planned_for = runs.planned_for AND b.id <= runs.id))), \
234 (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id) FROM runs WHERE id = $1{uuid}";
235
236const RUN_COLUMNS_OF_DAG: &str = "SELECT id{text}, dag_id, kind, state, {ts<}planned_for{>ts}, \
237 {ts<}since{>ts}, {ts<}triggered_at{>ts}, triggered_by, {ts<}started_at{>ts}, \
238 {ts<}ended_at{>ts}, late_failure, parent_run_id{text}, backfill_id{text}, \
239 (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id \
240 AND (b.planned_for < runs.planned_for OR (b.planned_for = runs.planned_for AND b.id <= runs.id))), \
241 (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id) FROM runs WHERE dag_id = $1 AND ($2{ts} IS NULL OR planned_for = $2{ts}) \
242 ORDER BY planned_for DESC, triggered_at DESC, id DESC LIMIT $3";
243
244macro_rules! runs_listed {
249 ($dag:literal) => {
250 concat!(
251 "SELECT id{text}, dag_id, kind, state, {ts<}planned_for{>ts}, \
252 {ts<}since{>ts}, {ts<}triggered_at{>ts}, triggered_by, {ts<}started_at{>ts}, \
253 {ts<}ended_at{>ts}, late_failure, parent_run_id{text}, backfill_id{text}, \
254 (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id \
255 AND (b.planned_for < runs.planned_for OR (b.planned_for = runs.planned_for AND b.id <= runs.id))), \
256 (SELECT COUNT(*) FROM runs b WHERE b.backfill_id = runs.backfill_id) FROM runs \
257 WHERE runs.id IN (SELECT id FROM runs WHERE ",
258 $dag,
259 " AND ($2 IS NULL OR state = $2) AND ($3{ts} IS NULL OR triggered_at < $3{ts} \
260 OR ($5{uuid} IS NOT NULL AND triggered_at = $3{ts} AND id < $5{uuid})) \
261 ORDER BY triggered_at DESC, id DESC LIMIT $4) \
262 ORDER BY triggered_at DESC, runs.id DESC"
263 )
264 };
265}
266
267const RUNS_FILTERED: &str = runs_listed!("($1 IS NULL OR dag_id = $1)");
268
269const DAGS_HOLDING: &str = "SELECT dag_id FROM dags WHERE LOWER(dag_id) LIKE $1 ESCAPE '\\'";
272
273const RUNS_OF_DAGS_SQLITE: &str =
278 runs_listed!("($1 IS NULL OR dag_id = $1) AND dag_id IN (SELECT value FROM json_each($6))");
279
280const RUNS_OF_DAGS_POSTGRES: &str =
284 runs_listed!("($1 IS NULL OR dag_id = $1) AND dag_id = ANY(string_to_array($6{text}, ','))");
285
286fn contains_pattern(part: &str) -> String {
289 let mut pattern = String::from("%");
290 for c in part.to_lowercase().chars() {
291 if matches!(c, '%' | '_' | '\\') {
292 pattern.push('\\');
293 }
294 pattern.push(c);
295 }
296 pattern.push('%');
297 pattern
298}
299
300#[derive(Debug, Clone, Default, PartialEq, Eq)]
302pub struct RunFilter {
303 pub dag_id: Option<DagId>,
305 pub dag_contains: Option<String>,
307 pub state: Option<RunState>,
309 pub before: Option<Timestamp>,
313 pub before_run: Option<String>,
315 pub limit: u32,
317}
318
319impl Database {
320 pub async fn runs(&self, filter: &RunFilter) -> Result<Vec<RunRecord>, DbError> {
326 let dags = match filter.dag_contains.as_deref() {
327 Some(part) => {
328 let dags: Vec<String> = on_pool!(self, |pool, backend| {
329 sqlx::query_scalar(sql(backend, DAGS_HOLDING))
330 .bind(contains_pattern(part))
331 .fetch_all(pool)
332 .await?
333 });
334 if dags.is_empty() {
335 return Ok(Vec::new());
336 }
337 Some(dags)
338 }
339 None => None,
340 };
341 let rows: Vec<RunRow> = on_pool!(self, |pool, backend| {
342 let postgres = matches!(backend, crate::backend::Backend::Postgres);
343 let query = sqlx::query_as(sql(
344 backend,
345 match (&dags, postgres) {
346 (None, _) => RUNS_FILTERED,
347 (Some(_), false) => RUNS_OF_DAGS_SQLITE,
348 (Some(_), true) => RUNS_OF_DAGS_POSTGRES,
349 },
350 ))
351 .bind(filter.dag_id.as_ref().map(DagId::as_str))
352 .bind(filter.state.map(|s| s.to_string()))
353 .bind(filter.before.map(db_time))
354 .bind(i64::from(filter.limit.min(MAX_RUNS)))
355 .bind(filter.before_run.as_deref());
356 match &dags {
357 Some(dags) => {
358 let list = if postgres {
359 dags.join(",")
360 } else {
361 to_json(dags)
362 };
363 query.bind(list).fetch_all(pool).await?
364 }
365 None => query.fetch_all(pool).await?,
366 }
367 });
368 rows.into_iter().map(run_record).collect()
369 }
370
371 pub async fn run_dag_json(&self, run_id: &str) -> Result<Option<serde_json::Value>, DbError> {
377 const DAG: &str = "SELECT v.dag_json{text} FROM runs r \
378 JOIN dag_versions v ON v.id = r.dag_version_id WHERE r.id = $1{uuid}";
379 let row: Option<(String,)> = on_pool!(self, |pool, backend| {
380 sqlx::query_as(sql(backend, DAG))
381 .bind(run_id)
382 .fetch_optional(pool)
383 .await?
384 });
385 row.map(|(json,)| from_json("dag_versions.dag_json", &json))
386 .transpose()
387 }
388
389 pub async fn run_dag(
396 &self,
397 run_id: &str,
398 ) -> Result<Option<std::sync::Arc<schedr_model::Dag>>, DbError> {
399 const VERSION: &str = "SELECT dag_version_id{text} FROM runs WHERE id = $1{uuid}";
400 let version: Option<String> = on_pool!(self, |pool, backend| {
401 sqlx::query_scalar(sql(backend, VERSION))
402 .bind(run_id)
403 .fetch_optional(pool)
404 .await?
405 });
406 match version {
407 Some(version) => Ok(Some(self.dag_version(&version).await?)),
408 None => Ok(None),
409 }
410 }
411
412 pub async fn run_dag_ids(&self, run_ids: &[&str]) -> Result<BTreeMap<String, String>, DbError> {
419 const DAGS: &str = "SELECT id{text}, dag_id FROM runs \
420 WHERE id IN (SELECT value{uuid} FROM {json_each}($1{json}))";
421 if run_ids.is_empty() {
422 return Ok(BTreeMap::new());
423 }
424 let list = to_json(&run_ids);
425 let rows: Vec<(String, String)> = on_pool!(self, |pool, backend| {
426 sqlx::query_as(sql(backend, DAGS))
427 .bind(&list)
428 .fetch_all(pool)
429 .await?
430 });
431 Ok(rows.into_iter().collect())
432 }
433
434 pub async fn mapped_instances(&self, run_id: &str, task_id: &TaskId) -> Result<usize, DbError> {
440 const COUNT: &str = "SELECT COUNT(*) FROM task_instances \
441 WHERE run_id = $1{uuid} AND task_id = $2 AND map_index >= 0";
442 let count: i64 = on_pool!(self, |pool, backend| {
443 sqlx::query_scalar(sql(backend, COUNT))
444 .bind(run_id)
445 .bind(task_id.as_str())
446 .fetch_one(pool)
447 .await?
448 });
449 Ok(usize::try_from(count).unwrap_or(0))
450 }
451
452 pub async fn run_task_output(
458 &self,
459 run_id: &str,
460 task_id: &TaskId,
461 ) -> Result<Option<(String, serde_json::Value)>, DbError> {
462 self.instance_output(run_id, task_id, -1).await
463 }
464
465 pub async fn instance_output(
472 &self,
473 run_id: &str,
474 task_id: &TaskId,
475 map_index: i32,
476 ) -> Result<Option<(String, serde_json::Value)>, DbError> {
477 const OUTPUT: &str = "SELECT o.outcome, o.value{text} FROM outputs o \
478 JOIN task_instances t ON t.id = o.task_instance_id \
479 WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3";
480 let row: Option<(String, String)> = on_pool!(self, |pool, backend| {
481 sqlx::query_as(sql(backend, OUTPUT))
482 .bind(run_id)
483 .bind(task_id.as_str())
484 .bind(map_index)
485 .fetch_optional(pool)
486 .await?
487 });
488 row.map(|(outcome, value)| Ok((outcome, from_json("outputs.value", &value)?)))
489 .transpose()
490 }
491
492 pub async fn outputs_deleted(&self, run_id: &str) -> Result<bool, DbError> {
498 const DELETED: &str = "SELECT 1 FROM runs WHERE id = $1{uuid} \
499 AND outputs_deleted_at IS NOT NULL";
500 let found: Option<i32> = on_pool!(self, |pool, backend| {
501 sqlx::query_scalar(sql(backend, DELETED))
502 .bind(run_id)
503 .fetch_optional(pool)
504 .await?
505 });
506 Ok(found.is_some())
507 }
508
509 pub async fn dag_runs(
516 &self,
517 dag_id: &DagId,
518 planned_for: Option<Timestamp>,
519 limit: u32,
520 ) -> Result<Vec<RunRecord>, DbError> {
521 let rows: Vec<RunRow> = on_pool!(self, |pool, backend| {
522 sqlx::query_as(sql(backend, RUN_COLUMNS_OF_DAG))
523 .bind(dag_id.as_str())
524 .bind(planned_for.map(db_time))
525 .bind(i64::from(limit.min(MAX_RUNS)))
526 .fetch_all(pool)
527 .await?
528 });
529 rows.into_iter().map(run_record).collect()
530 }
531
532 pub async fn run_record(&self, run_id: &str) -> Result<Option<RunRecord>, DbError> {
538 let row: Option<RunRow> = on_pool!(self, |pool, backend| {
539 sqlx::query_as(sql(backend, RUN_COLUMNS_ONE))
540 .bind(run_id)
541 .fetch_optional(pool)
542 .await?
543 });
544 row.map(run_record).transpose()
545 }
546
547 pub async fn run_instances(&self, run_id: &str) -> Result<Vec<InstanceRecord>, DbError> {
554 const INSTANCES: &str = "SELECT task_id, state, outcome, try_number, queued_reason, \
555 {ts<}updated_at{>ts}, map_index, reason, cleanup_result FROM task_instances \
556 WHERE run_id = $1{uuid} ORDER BY task_id, map_index";
557 let rows: Vec<InstanceRow> = on_pool!(self, |pool, backend| {
558 sqlx::query_as(sql(backend, INSTANCES))
559 .bind(run_id)
560 .fetch_all(pool)
561 .await?
562 });
563 rows.into_iter()
564 .map(
565 |(
566 task_id,
567 state,
568 outcome,
569 try_number,
570 queued_reason,
571 updated_at,
572 map_index,
573 reason,
574 cleanup_result,
575 )| {
576 Ok(InstanceRecord {
577 task_id: task_id_of(task_id)?,
578 map_index,
579 reason,
580 state: from_name("task_instances.state", state)?,
581 outcome,
582 try_number: u32::try_from(try_number).unwrap_or(0),
583 queued_reason,
584 cleanup_result: cleanup_result
585 .map(|name| from_name("task_instances.cleanup_result", name))
586 .transpose()?,
587 updated_at: parse_time("task_instances.updated_at", &updated_at)?,
588 })
589 },
590 )
591 .collect()
592 }
593
594 pub async fn run_code_hashes(&self, run_id: &str) -> Result<Vec<String>, DbError> {
601 const HASHES: &str = "SELECT a.code_hash FROM attempts a \
602 JOIN task_instances t ON t.id = a.task_instance_id \
603 WHERE t.run_id = $1{uuid} AND a.code_hash IS NOT NULL AND a.code_hash <> '' \
604 GROUP BY a.code_hash ORDER BY MIN(COALESCE(a.started_at, a.assigned_at)), a.code_hash";
605 let hashes = on_pool!(self, |pool, backend| {
606 sqlx::query_scalar(sql(backend, HASHES))
607 .bind(run_id)
608 .fetch_all(pool)
609 .await?
610 });
611 Ok(hashes)
612 }
613
614 pub async fn state_counts(&self) -> Result<StateCounts, DbError> {
621 const RUNS: &str =
622 "SELECT state, kind, COUNT(*) FROM runs GROUP BY state, kind ORDER BY state, kind";
623 const TASKS: &str = "SELECT t.state, COUNT(*) FROM task_instances t \
624 JOIN runs r ON r.id = t.run_id WHERE r.state IN ('queued', 'running') \
625 GROUP BY t.state ORDER BY t.state";
626 const WORKERS: &str = "SELECT state, COUNT(*) FROM workers GROUP BY state ORDER BY state";
627 let (runs, tasks, workers) = on_pool!(self, |pool, backend| {
628 (
629 sqlx::query_as(sql(backend, RUNS))
630 .fetch_all(&mut *pool)
631 .await?,
632 sqlx::query_as(sql(backend, TASKS))
633 .fetch_all(&mut *pool)
634 .await?,
635 sqlx::query_as(sql(backend, WORKERS))
636 .fetch_all(&mut *pool)
637 .await?,
638 )
639 });
640 Ok(StateCounts {
641 runs,
642 tasks,
643 workers,
644 })
645 }
646
647 pub async fn task_attempts(
653 &self,
654 run_id: &str,
655 task_id: &TaskId,
656 ) -> Result<Vec<AttemptRecord>, DbError> {
657 self.instance_attempts(run_id, task_id, -1).await
658 }
659
660 pub async fn instance_attempts(
666 &self,
667 run_id: &str,
668 task_id: &TaskId,
669 map_index: i32,
670 ) -> Result<Vec<AttemptRecord>, DbError> {
671 const ATTEMPTS: &str = "SELECT a.id{text}, a.try_number, a.worker_id, a.status, \
672 a.exit_code, a.error_kind, a.error_summary{text}, {ts<}a.assigned_at{>ts}, \
673 {ts<}a.started_at{>ts}, {ts<}a.ended_at{>ts}, a.duration_ms, a.peak_memory_bytes, \
674 a.start_method, a.usage{text}, a.core_dumped, a.chained_run_id{text} FROM attempts a \
675 JOIN task_instances t ON t.id = a.task_instance_id \
676 WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3 \
677 ORDER BY a.try_number";
678 const CLEANUPS: &str = "SELECT a.id{text}, a.cleanup_result, a.cleanup_tries, \
679 a.cleanup_duration_ms, a.cleanup_error_kind, a.cleanup_error_summary{text}, \
680 a.cleanup_moves FROM attempts a JOIN task_instances t ON t.id = a.task_instance_id \
681 WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3";
682 const HANDLES: &str = "SELECT h.attempt_id{text}, h.handle FROM cleanup_handles h \
683 JOIN attempts a ON a.id = h.attempt_id \
684 JOIN task_instances t ON t.id = a.task_instance_id \
685 WHERE t.run_id = $1{uuid} AND t.task_id = $2 AND t.map_index = $3 \
686 ORDER BY h.attempt_id, h.position";
687 let (rows, cleanups, handles): (Vec<AttemptRow>, Vec<CleanupRow>, Vec<(String, String)>) =
688 on_pool!(self, |pool, backend| {
689 (
690 sqlx::query_as(sql(backend, ATTEMPTS))
691 .bind(run_id)
692 .bind(task_id.as_str())
693 .bind(map_index)
694 .fetch_all(&mut *pool)
695 .await?,
696 sqlx::query_as(sql(backend, CLEANUPS))
697 .bind(run_id)
698 .bind(task_id.as_str())
699 .bind(map_index)
700 .fetch_all(&mut *pool)
701 .await?,
702 sqlx::query_as(sql(backend, HANDLES))
703 .bind(run_id)
704 .bind(task_id.as_str())
705 .bind(map_index)
706 .fetch_all(&mut *pool)
707 .await?,
708 )
709 });
710 let mut by_attempt: BTreeMap<String, CleanupRecord> = BTreeMap::new();
711 for (id, result, tries, duration_ms, error_kind, error_summary, moves) in cleanups {
712 by_attempt.insert(
713 id,
714 CleanupRecord {
715 result: result
716 .map(|name| from_name("attempts.cleanup_result", name))
717 .transpose()?,
718 tries: tries.and_then(|n| u32::try_from(n).ok()),
719 duration_ms: duration_ms.and_then(|ms| u64::try_from(ms).ok()),
720 error_kind,
721 error_summary,
722 moves: u32::try_from(moves).unwrap_or(0),
723 handles: Vec::new(),
724 },
725 );
726 }
727 for (id, handle) in handles {
728 by_attempt.entry(id).or_default().handles.push(handle);
729 }
730 rows.into_iter()
731 .map(|row| {
732 let mut record = attempt_record(row)?;
733 record.cleanup = by_attempt.remove(&record.id).unwrap_or_default();
734 Ok(record)
735 })
736 .collect()
737 }
738}
739
740fn task_id_of(text: String) -> Result<TaskId, DbError> {
741 TaskId::new(text).map_err(|e| DbError::InvalidData {
742 what: "task_instances.task_id",
743 reason: e.to_string(),
744 })
745}
746
747fn run_record(row: RunRow) -> Result<RunRecord, DbError> {
748 let (
749 id,
750 dag_id,
751 kind,
752 state,
753 planned_for,
754 since,
755 triggered_at,
756 triggered_by,
757 started,
758 ended,
759 late_failure,
760 parent_run_id,
761 backfill_id,
762 backfill_index,
763 backfill_total,
764 ) = row;
765 Ok(RunRecord {
766 id,
767 dag_id: DagId::new(dag_id).map_err(|e| DbError::InvalidData {
768 what: "runs.dag_id",
769 reason: e.to_string(),
770 })?,
771 kind: from_name("runs.kind", kind)?,
772 state: from_name("runs.state", state)?,
773 planned_for: parse_time("runs.planned_for", &planned_for)?,
774 since: parse_time("runs.since", &since)?,
775 triggered_at: parse_time("runs.triggered_at", &triggered_at)?,
776 triggered_by,
777 started_at: optional_time("runs.started_at", started)?,
778 ended_at: optional_time("runs.ended_at", ended)?,
779 late_failure,
780 parent_run_id,
781 backfill: backfill_id.map(|id| BackfillPlace {
782 id,
783 index: u32::try_from(backfill_index).unwrap_or(0),
784 total: u32::try_from(backfill_total).unwrap_or(0),
785 }),
786 })
787}
788
789fn attempt_record(row: AttemptRow) -> Result<AttemptRecord, DbError> {
790 let (
791 id,
792 try_number,
793 worker_id,
794 status,
795 exit_code,
796 error_kind,
797 error_summary,
798 assigned,
799 started,
800 ended,
801 duration_ms,
802 peak_memory,
803 start_method,
804 usage,
805 core_dumped,
806 chained_run_id,
807 ) = row;
808 Ok(AttemptRecord {
809 id,
810 try_number: u32::try_from(try_number).unwrap_or(0),
811 worker_id,
812 status: status
813 .map(|s| from_name("attempts.status", s))
814 .transpose()?,
815 exit_code,
816 error_kind,
817 error_summary,
818 assigned_at: parse_time("attempts.assigned_at", &assigned)?,
819 started_at: optional_time("attempts.started_at", started)?,
820 ended_at: optional_time("attempts.ended_at", ended)?,
821 duration_ms: duration_ms.and_then(|ms| u64::try_from(ms).ok()),
822 peak_memory_bytes: peak_memory.and_then(|bytes| u64::try_from(bytes).ok()),
823 start_method,
824 usage: usage
825 .map(|json| from_json("attempts.usage", &json))
826 .transpose()?,
827 core_dumped,
828 cleanup: CleanupRecord::default(),
829 chained_run_id,
830 })
831}