OXYGENHUB
# ced6d3afc5cf oxygenhub / crates / hub / src / db / flow.rs
19.4 KiB · Rust · last changed Runners are offered only jobs whose image they hold (closes #73) 1 month ago source blame history raw
1
//! OxygenFlow runs, jobs and logs (hub spec §13.2).
2
3
use super::{now_ms, Pool};
4
use sqlx::FromRow;
5
6
#[derive(Clone, Debug, FromRow)]
7
pub struct Run {
8
    pub id: i64,
9
    pub repo_id: i64,
10
    /// The run's number within its repository, from 1 (migration 0019).
11
    #[sqlx(default)]
12
    pub number: i64,
13
    /// `push`, `manual` or `rerun:N` (migration 0020).
14
    #[sqlx(default)]
15
    pub trigger: String,
16
    pub bookmark: String,
17
    pub state: String,
18
    pub heads: String,
19
    pub pipeline_hash: String,
20
    pub status: String,
21
    pub error: String,
22
    pub actor: String,
23
    pub created_ms: i64,
24
    pub finished_ms: Option<i64>,
25
}
26
27
impl Run {
28
    /// How the run page says what started it.
29
    pub fn started_by(&self) -> String {
30
        match self.trigger.as_str() {
31
            "manual" => format!("started by {}", self.actor),
32
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", &t[6..], self.actor),
33
            _ => format!("pushed by {}", self.actor),
34
        }
35
    }
36
37
    pub fn head_list(&self) -> Vec<&str> {
38
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
39
    }
40
41
    pub fn live(&self) -> bool {
42
        matches!(self.status.as_str(), "queued" | "running")
43
    }
44
}
45
46
#[derive(Clone, Debug, FromRow)]
47
pub struct Job {
48
    pub id: i64,
49
    pub run_id: i64,
50
    pub name: String,
51
    pub depth: i64,
52
    pub depends: String,
53
    pub spec: String,
54
    pub sandbox: String,
55
    pub runtime: String,
56
    pub status: String,
57
    pub runner: String,
58
    pub token_hash: String,
59
    pub started_ms: Option<i64>,
60
    pub finished_ms: Option<i64>,
61
    pub exit_code: Option<i64>,
62
    pub error: String,
63
    pub receipt: String,
64
    pub receipt_hash: String,
65
    pub log_count: i64,
66
    /// Comma-separated ids of other repositories the job token may read.
67
    pub also_read: String,
68
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
69
    pub receipt_attest: String,
70
    /// Who signed it: the runner's identity name.
71
    pub receipt_signer: String,
72
    /// Why a signed receipt was not kept.
73
    pub receipt_note: String,
74
}
75
76
impl Job {
77
    pub fn depends_on(&self) -> Vec<String> {
78
        serde_json::from_str(&self.depends).unwrap_or_default()
79
    }
80
81
    pub fn done(&self) -> bool {
82
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error")
83
    }
84
}
85
86
#[derive(Clone, Debug, FromRow)]
87
pub struct LogLine {
88
    pub seq: i64,
89
    pub t: i64,
90
    pub stream: String,
91
    pub text: String,
92
}
93
94
/// A job as the trigger creates it.
95
pub struct NewJob {
96
    pub name: String,
97
    pub depth: i64,
98
    pub depends: Vec<String>,
99
    pub spec: String,
100
    pub sandbox: String,
101
    pub runtime: String,
102
}
103
104
pub struct NewRun<'a> {
105
    pub repo_id: i64,
106
    pub bookmark: &'a str,
107
    pub state: &'a str,
108
    pub heads: &'a str,
109
    pub pipeline_hash: &'a str,
110
    pub actor: &'a str,
111
    /// `push`, `manual` or `rerun:N`.
112
    pub trigger: &'a str,
113
    /// Problems when the pipeline is invalid: the run is recorded in error.
114
    pub error: Option<&'a str>,
115
}
116
117
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
118
    let mut tx = super::begin_write(pool).await?;
119
    let now = now_ms();
120
    let status = if r.error.is_some() { "error" } else { "queued" };
121
    let id: i64 = sqlx::query_scalar(
122
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
123
         VALUES (?, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
124
    )
125
    .bind(r.repo_id)
126
    .bind(r.repo_id)
127
    .bind(r.bookmark)
128
    .bind(r.state)
129
    .bind(r.heads)
130
    .bind(r.pipeline_hash)
131
    .bind(status)
132
    .bind(r.error.unwrap_or(""))
133
    .bind(r.actor)
134
    .bind(r.trigger)
135
    .bind(now)
136
    .bind(r.error.map(|_| now))
137
    .fetch_one(&mut *tx)
138
    .await?;
139
    for j in jobs {
140
        sqlx::query(
141
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued')",
142
        )
143
        .bind(id)
144
        .bind(&j.name)
145
        .bind(j.depth)
146
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
147
        .bind(&j.spec)
148
        .bind(&j.sandbox)
149
        .bind(&j.runtime)
150
        .execute(&mut *tx)
151
        .await?;
152
    }
153
    tx.commit().await?;
154
    Ok(id)
155
}
156
157
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
158
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
159
    let mut out: Vec<String> = [spec, sandbox]
160
        .iter()
161
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
162
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
163
        .filter_map(|l| l.as_str().map(String::from))
164
        .collect();
165
    out.sort();
166
    out.dedup();
167
    out
168
}
169
170
impl Job {
171
    /// The runner labels this job needs.
172
    pub fn needs(&self) -> Vec<String> {
173
        labels_in(&self.spec, &self.sandbox)
174
    }
175
}
176
177
/// A job waiting for or held by a runner, with where it comes from.
178
#[derive(Clone, Debug, FromRow)]
179
pub struct QueueEntry {
180
    pub job_id: i64,
181
    pub run_id: i64,
182
    pub repo_id: i64,
183
    pub owner: String,
184
    pub name: String,
185
    pub visibility: String,
186
    pub run_number: i64,
187
    pub job: String,
188
    pub status: String,
189
    /// The runner holding it, when running.
190
    pub runner: String,
191
    pub spec: String,
192
    pub sandbox: String,
193
}
194
195
impl QueueEntry {
196
    /// The runner labels the job needs.
197
    pub fn needs(&self) -> Vec<String> {
198
        labels_in(&self.spec, &self.sandbox)
199
    }
200
}
201
202
/// Every job of a live run that is running or queued: running ones first,
203
/// then queued ones in the order runners claim them (hub spec §13.2).
204
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
205
    sqlx::query_as(
206
        "SELECT j.id AS job_id, j.run_id, r.repo_id, p.owner, p.name, p.visibility, r.number AS run_number, j.name AS job, j.status, j.runner, j.spec, j.sandbox \
207
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
208
         WHERE j.status IN ('queued', 'running') AND r.status IN ('queued', 'running') \
209
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.run_id, j.depth, j.id",
210
    )
211
    .fetch_all(pool)
212
    .await
213
}
214
215
/// A repository's runs, newest first, numbered below `before`.
216
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
217
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
218
        .bind(repo_id)
219
        .bind(before.unwrap_or(i64::MAX))
220
        .bind(limit)
221
        .fetch_all(pool)
222
        .await
223
}
224
225
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
226
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
227
        .bind(repo_id)
228
        .bind(before.unwrap_or(i64::MAX))
229
        .bind(limit)
230
        .fetch_all(pool)
231
        .await
232
}
233
234
/// A repository's run by its number there.
235
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
236
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
237
}
238
239
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
240
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
241
}
242
243
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
244
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
245
}
246
247
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
248
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
249
}
250
251
/// The running job a job token belongs to, while it may still be used.
252
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
253
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
254
        .bind(token_hash)
255
        .bind(now_ms() - max_age_ms)
256
        .fetch_optional(pool)
257
        .await
258
}
259
260
/// Take the oldest queued job whose dependencies all passed and whose tier
261
/// the runner offers, and mark it running for `runner` with a token.
262
/// Let a job's token also read these repositories (its pinned subrepos).
263
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
264
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
265
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
266
    Ok(())
267
}
268
269
impl Job {
270
    pub fn also_read_ids(&self) -> Vec<i64> {
271
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
272
    }
273
}
274
275
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
276
/// limit, and the rootfs images it holds, `None` when it does not say.
277
#[derive(Clone, Debug, Default)]
278
pub struct Room {
279
    pub memory_mib: Option<u32>,
280
    pub cpus: Option<u32>,
281
    pub images: Option<std::collections::HashSet<String>>,
282
}
283
284
impl Room {
285
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
286
    /// and its rootfs image among the runner's (oxygenhub#73).
287
    pub fn fits(&self, sandbox_json: &str) -> bool {
288
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
289
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
290
        let rootfs = v["rootfs"].as_str().unwrap_or("");
291
        self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
292
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
293
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)))
294
    }
295
}
296
297
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
298
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
299
}
300
301
/// The oldest runnable job that fits in `room`.
302
/// The first queued job a runner with these tiers, this room and this
303
/// scope may take, now running under `runner`. A scoped runner never sees
304
/// another scope's jobs (oxygenhub#41).
305
pub async fn claim_within(
306
    pool: &Pool,
307
    runtimes: &[String],
308
    runner: &str,
309
    token_hash: &str,
310
    room: Room,
311
    scope: &super::runners::Scope,
312
    labels: &[String],
313
) -> sqlx::Result<Option<Job>> {
314
    let mut tx = super::begin_write(pool).await?;
315
    let queued: Vec<Job> = sqlx::query_as(
316
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
317
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') \
318
         AND (? = '' OR rep.owner = ?) AND (? IS NULL OR r.repo_id = ?) \
319
         ORDER BY j.run_id, j.depth, j.id LIMIT 200",
320
    )
321
    .bind(&scope.owner)
322
    .bind(&scope.owner)
323
    .bind(scope.repo_id)
324
    .bind(scope.repo_id)
325
    .fetch_all(&mut *tx)
326
    .await?;
327
    for j in queued {
328
        if !runtimes.iter().any(|r| r == &j.runtime) || !room.fits(&j.sandbox) {
329
            continue;
330
        }
331
        // Every label the job and its sandbox ask for (`runs-on`).
332
        if !j.needs().iter().all(|l| labels.contains(l)) {
333
            continue;
334
        }
335
        let deps = j.depends_on();
336
        if !deps.is_empty() {
337
            let mut passed = 0i64;
338
            for d in &deps {
339
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
340
                    .bind(j.run_id)
341
                    .bind(d)
342
                    .fetch_optional(&mut *tx)
343
                    .await?;
344
                if st.as_deref() == Some("passed") {
345
                    passed += 1;
346
                }
347
            }
348
            if passed != deps.len() as i64 {
349
                continue;
350
            }
351
        }
352
        let now = now_ms();
353
        let done = sqlx::query(
354
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
355
        )
356
        .bind(runner)
357
        .bind(token_hash)
358
        .bind(now)
359
        .bind(j.id)
360
        .execute(&mut *tx)
361
        .await?;
362
        if done.rows_affected() == 1 {
363
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
364
                .bind(j.run_id)
365
                .execute(&mut *tx)
366
                .await?;
367
            tx.commit().await?;
368
            return job(pool, j.id).await;
369
        }
370
    }
371
    tx.commit().await?;
372
    Ok(None)
373
}
374
375
/// Append records; returns how many were kept (the rest exceed the cap).
376
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
377
    let mut tx = super::begin_write(pool).await?;
378
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
379
    let room = (cap - count).max(0) as usize;
380
    let keep = &records[..records.len().min(room)];
381
    for (i, r) in keep.iter().enumerate() {
382
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
383
            .bind(job_id)
384
            .bind(count + i as i64 + 1)
385
            .bind(r.t as i64)
386
            .bind(&r.stream)
387
            .bind(&r.text)
388
            .execute(&mut *tx)
389
            .await?;
390
    }
391
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
392
        .bind(keep.len() as i64)
393
        .bind(job_id)
394
        .execute(&mut *tx)
395
        .await?;
396
    tx.commit().await?;
397
    Ok(keep.len())
398
}
399
400
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
401
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
402
        .bind(job_id)
403
        .bind(after)
404
        .bind(limit)
405
        .fetch_all(pool)
406
        .await
407
}
408
409
/// Jobs running since before `ms` (the oldest first).
410
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
411
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < ? ORDER BY started_ms")
412
        .bind(ms)
413
        .fetch_all(pool)
414
        .await
415
}
416
417
pub struct Outcome<'a> {
418
    pub status: &'a str,
419
    pub exit_code: Option<i64>,
420
    pub error: &'a str,
421
    pub receipt: &'a str,
422
    pub receipt_hash: &'a str,
423
}
424
425
/// Record a job's end, skip the jobs that can no longer run, and settle the
426
/// run. Returns the jobs whose status changed (for their checks).
427
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
428
    let mut tx = super::begin_write(pool).await?;
429
    let now = now_ms();
430
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
431
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
432
        .bind(o.status)
433
        .bind(o.exit_code)
434
        .bind(o.error)
435
        .bind(o.receipt)
436
        .bind(o.receipt_hash)
437
        .bind(now)
438
        .bind(job_id)
439
        .execute(&mut *tx)
440
        .await?;
441
    let mut changed = vec![job_id];
442
    // Dependents of anything that did not pass are skipped, transitively.
443
    loop {
444
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
445
        let blocked: Vec<i64> = all
446
            .iter()
447
            .filter(|x| x.status == "queued")
448
            .filter(|x| {
449
                x.depends_on()
450
                    .iter()
451
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
452
            })
453
            .map(|x| x.id)
454
            .collect();
455
        if blocked.is_empty() {
456
            break;
457
        }
458
        for id in blocked {
459
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
460
                .bind(now)
461
                .bind(id)
462
                .execute(&mut *tx)
463
                .await?;
464
            changed.push(id);
465
        }
466
    }
467
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
468
    if all.iter().all(Job::done) {
469
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
470
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
471
            .bind(status)
472
            .bind(now)
473
            .bind(j.run_id)
474
            .execute(&mut *tx)
475
            .await?;
476
    }
477
    tx.commit().await?;
478
    let mut out = Vec::new();
479
    for id in changed {
480
        if let Some(x) = job(pool, id).await? {
481
            out.push(x);
482
        }
483
    }
484
    Ok(out)
485
}
486
487
/// The newest run of exactly this state (heads joined with `+`, sorted).
488
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
489
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
490
        .bind(repo_id)
491
        .bind(heads)
492
        .fetch_optional(pool)
493
        .await
494
}
495
496
/// Record what became of job `job_id`'s signed receipt.
497
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
498
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
499
        .bind(attest)
500
        .bind(signer)
501
        .bind(note)
502
        .bind(job_id)
503
        .execute(pool)
504
        .await?;
505
    Ok(())
506
}
507
508
/// A job's artifact, kept as a blob of the run's repository.
509
#[derive(Clone, Debug, FromRow)]
510
pub struct Artifact {
511
    pub job_id: i64,
512
    pub name: String,
513
    pub path: String,
514
    pub blob: String,
515
    pub size: i64,
516
    /// BLAKE3 of the bytes.
517
    pub content: String,
518
    pub created_ms: i64,
519
}
520
521
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
522
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
523
        .bind(a.job_id)
524
        .bind(&a.name)
525
        .bind(&a.path)
526
        .bind(&a.blob)
527
        .bind(a.size)
528
        .bind(&a.content)
529
        .bind(a.created_ms)
530
        .execute(pool)
531
        .await?;
532
    Ok(())
533
}
534
535
/// Job `job_id`'s artifacts, by name.
536
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
537
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
538
}
539
540
/// Where an artifact with given content came from: the run and job that
541
/// built it, and the job's signed receipt when one was kept.
542
#[derive(Clone, Debug, FromRow)]
543
pub struct Provenance {
544
    pub run_number: i64,
545
    pub job: String,
546
    pub name: String,
547
    pub receipt_attest: String,
548
    pub receipt_signer: String,
549
}
550
551
/// The build of the bytes whose BLAKE3 is `content` in repository
552
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
553
/// run first.
554
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
555
    sqlx::query_as(
556
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
557
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
558
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
559
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
560
    )
561
    .bind(repo_id)
562
    .bind(content)
563
    .fetch_optional(pool)
564
    .await
565
}