summaryrefslogtreecommitdiffstats
path: root/tests/pipeline.rs
blob: 6dd1df5f87f9e05e5db90053e37b9bef9397c851 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
mod common;

use aur_build::db::{self, builds, model::*};
use aur_build::pipeline::{self, publish};
use aur_build::review::{approve, candidates, diff};
use common::*;

/// subscribe -> detect -> render the review -> approve.
fn approve_fixture(env: &Env, name: &str) -> CandidateRow {
    aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
    let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
    let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
    approve::approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap();
    candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap()
}

/// Re-detect and approve whatever is pending now (a later version).
fn approve_pending(env: &Env, name: &str) -> CandidateRow {
    approve_fixture(env, name)
}

fn run_for(env: &Env, c: &CandidateRow) -> pipeline::Outcome {
    let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, c).unwrap();
    pipeline::run(&env.cfg, &env.db, &id).unwrap()
}

fn in_index(env: &Env) -> Vec<(String, String)> {
    env.db
        .read(|c| {
            let mut st =
                c.prepare("SELECT name, version FROM package WHERE state='in_index' ORDER BY name")?;
            let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
            let mut v = Vec::new();
            for r in rows {
                v.push(r?);
            }
            Ok(v)
        })
        .unwrap()
}

fn step_rows(env: &Env) -> Vec<(String, String)> {
    env.db
        .read(|c| {
            let mut st = c.prepare("SELECT step, status FROM build_step ORDER BY rowid")?;
            let rows = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
            let mut v = Vec::new();
            for r in rows {
                v.push(r?);
            }
            Ok(v)
        })
        .unwrap()
}

#[test]
fn end_to_end_publishes_a_signed_index() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    let out = run_for(&env, &c);
    assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}");

    let rel = db::accepted_release(&env.db, "plain-make").unwrap().unwrap();
    assert_eq!(rel.state, ReleaseState::Published);
    assert_eq!(rel.pkgver, "1.0");
    assert_eq!(rel.version(), "1.0-1");

    // Both the packages and the database are signed (§9).
    let arch = env.cfg.repo_arch_dir();
    assert!(arch.join("plain-make-1.0-1-x86_64.pkg.tar.zst").exists());
    assert!(arch.join("plain-make-1.0-1-x86_64.pkg.tar.zst.sig").exists());
    assert!(arch.join("aur-build.db.tar.gz").exists());
    assert!(arch.join("aur-build.db.tar.gz.sig").exists());

    // One checkpoint row per step, all green (§8.1).
    let all = step_rows(&env);
    assert_eq!(all.len(), BUILD_STEPS.len(), "one row per step: {all:?}");
    assert!(
        all.iter().all(|(_, s)| s == "succeeded" || s == "skipped"),
        "{all:?}"
    );
}

#[test]
fn the_build_never_signs_ingest_does() {
    // Signing moved hub-side: the build command carries no `-si` and the signature
    // over each artifact is made at ingest by the hub's own gpg. Worst the sandbox
    // ever returns is unsigned bytes.
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. }));

    let shimlog = env.cfg.hooks.shim_dir.clone().unwrap();
    assert_eq!(
        aur_build::shims::called_with(&shimlog, "makechrootpkg", "-si"),
        0,
        "the build step must not hand a signing key to the sandbox"
    );

    let (digest, sig_path): (String, Option<String>) = env
        .db
        .read(|c| {
            Ok(c.prepare("SELECT digest, signature_path FROM artifact LIMIT 1")?
                .query_row([], |r| Ok((r.get(0)?, r.get(1)?)))?)
        })
        .unwrap();
    assert!(sig_path.is_some(), "ingest must record a signature for the artifact");
    assert!(std::path::Path::new(sig_path.as_ref().unwrap()).exists());
    assert!(
        aur_build::shims::called_with(&shimlog, "gpg", &digest) > 0,
        "the signature ingest recorded was made over the stored artifact's bytes"
    );
}

#[test]
fn a_tampered_store_artifact_fails_the_lease_closed() {
    // Corrupt the store bytes after publication: provisioning re-hashes everything
    // it stages and must refuse, not build against bytes the index never approved.
    let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client");
    let c = approve_fixture(&env, "plain-make");
    assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. }));

    let c2 = approve_fixture(&env, "dep-client");
    let id2 = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();

    let (digest, path): (String, String) = env
        .db
        .read(|c| {
            Ok(c.query_row("SELECT digest, path FROM artifact LIMIT 1", [], |r| {
                Ok((r.get(0)?, r.get(1)?))
            })?)
        })
        .unwrap();
    let original = std::fs::read(&path).unwrap();
    let mut tampered = original.clone();
    tampered[16] ^= 0xFF;
    std::fs::write(&path, &tampered).unwrap();

    match pipeline::run(&env.cfg, &env.db, &id2).unwrap() {
        pipeline::Outcome::Failed { step, error, transient } => {
            assert_eq!(step, "chroot", "provisioning is where the lie gets caught");
            assert!(error.contains("hash") && error.contains(&digest), "{error}");
            assert!(!transient, "a corrupt store is not a network hiccup");
        }
        other => panic!("{other:?}"),
    }

    // Restore the bytes and resume: the lease verifies, the sandbox's `pacman -Q`
    // confirms the pinned world landed, and the build completes.
    std::fs::write(&path, &original).unwrap();
    assert!(
        matches!(pipeline::run(&env.cfg, &env.db, &id2).unwrap(), pipeline::Outcome::Succeeded { .. }),
        "the resumed build failed"
    );
    assert!(in_index(&env).iter().any(|(n, _)| n == "dep-client"));
    let shimlog = env.cfg.hooks.shim_dir.clone().unwrap();
    assert!(
        aur_build::shims::called_with(&shimlog, "pacman", "-U") > 0,
        "the dependency arrived as a pinned blob through pacman -U, not a live mirror"
    );
}

#[test]
fn i1_no_index_entry_without_an_approval() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);
    let orphans: i64 = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT count(*) FROM package p
                 LEFT JOIN release r ON r.id = p.release_id
                 WHERE p.state='in_index' AND (r.id IS NULL OR r.approval_id IS NULL)",
                [],
                |r| r.get(0),
            )?)
        })
        .unwrap();
    assert_eq!(orphans, 0, "I1: index entry with no approval behind it");
}

#[test]
fn i8_served_index_holds_exactly_the_accepted_pointers() {
    let (env, fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);

    fx.bump(&[("pkgver", "1.0.1")]);
    let c2 = approve_pending(&env, "plain-make");
    run_for(&env, &c2);

    // The old version is gone from the index, not merely superseded in place.
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]);
    let rel = db::accepted_release(&env.db, "plain-make").unwrap().unwrap();
    assert_eq!(rel.pkgver, "1.0.1");
    let old: i64 = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'",
                [],
                |r| r.get(0),
            )?)
        })
        .unwrap();
    assert_eq!(old, 0, "the previous release must leave the index");
}

#[test]
fn step0_fails_closed_when_the_recipe_hash_drifts() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    // The mirror no longer matches what was approved. There is no path from
    // "AUR moved since the review" to "we built it anyway" (I3).
    env.exec(
        "UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1",
        &params(vec![c.snapshot_id]),
    );
    let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
        pipeline::Outcome::Failed { step, error, .. } => {
            assert_eq!(step, "materialize");
            assert!(error.contains("recipe_hash mismatch"), "{error}");
        }
        other => panic!("expected a fail-closed failure, got {other:?}"),
    }
    assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none());
    assert!(in_index(&env).is_empty());
}

#[test]
fn step4_fails_closed_when_pkgver_no_longer_matches() {
    let (env, fx) = env_with_fixture("git-sourced");
    let c = approve_fixture(&env, "git-sourced");
    assert_eq!(c.pkgver, "r1.0");
    // Upstream moves after approval: the tool now resolves a different pkgver.
    // The build must refuse rather than silently ship the newer one (§8.1).
    let mut m = fx.manifest_json();
    m["vercheck"] = serde_json::json!("r9.9-1");
    std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap();

    match run_for(&env, &c) {
        pipeline::Outcome::Failed { step, error, .. } => {
            assert_eq!(step, "pkgver");
            assert!(error.contains("r9.9") && error.contains("r1.0"), "{error}");
        }
        other => panic!("expected a fail-closed pkgver failure, got {other:?}"),
    }
    assert!(in_index(&env).is_empty());
}

#[test]
fn step4_passes_when_the_vcs_pkgver_still_matches() {
    let (env, _fx) = env_with_fixture("git-sourced");
    let c = approve_fixture(&env, "git-sourced");
    assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. }));
    assert_eq!(in_index(&env), vec![("git-sourced".into(), "r1.0-1".into())]);
}

#[test]
fn i4_kill_mid_publish_leaves_the_old_index_intact() {
    let (mut env, fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);
    let v1 = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz");
    let before = std::fs::read(&v1).unwrap();

    fx.bump(&[("pkgver", "1.0.1")]);
    let c2 = approve_pending(&env, "plain-make");
    env.set_publish_fault("before-rename");
    let out = run_for(&env, &c2);
    assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}");

    // The served database is byte-for-byte the old one, and the DB never recorded
    // the new release: consumers saw either the old world or the new one (I4).
    assert_eq!(std::fs::read(&v1).unwrap(), before);
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
    assert_eq!(
        env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
        Some(0)
    );
}

#[test]
fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() {
    let (mut env, fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);

    fx.bump(&[("pkgver", "1.0.1")]);
    let c2 = approve_pending(&env, "plain-make");
    let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();
    env.set_publish_fault("before-rename");
    assert!(matches!(
        pipeline::run(&env.cfg, &env.db, &id).unwrap(),
        pipeline::Outcome::Failed { .. }
    ));
    let builds_after_crash =
        aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", "");
    assert_eq!(builds_after_crash, 2, "one real build before the crash");

    // "Restart": same build row, no fault. Only publish re-runs; the expensive
    // steps are checkpointed.
    env.clear_publish_fault();
    match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
        pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0),
        other => panic!("{other:?}"),
    }
    assert_eq!(
        aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""),
        builds_after_crash,
        "I5: resuming must not rebuild"
    );
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]);
    // Exactly one release row per version: no duplicates from the resume.
    assert_eq!(
        env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
        Some(1)
    );
}

#[test]
fn split_pkgbase_is_one_approval_and_many_index_rows() {
    let (env, _fx) = env_with_fixture("split-pkgbase");
    let c = approve_fixture(&env, "split-pkgbase");
    assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. }));
    let names: Vec<String> = in_index(&env).into_iter().map(|(n, _)| n).collect();
    assert!(names.contains(&"split-pkgbase".to_string()), "{names:?}");
    assert!(names.contains(&"split-pkgbase-docs".to_string()), "{names:?}");
    // One approval, one release, N packages — the §3 split-pkgbase rule.
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1));
    assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1));
}

#[test]
fn a_failed_build_leaves_the_previous_version_serving() {
    let (mut env, fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);

    fx.bump(&[("pkgver", "1.0.1")]);
    let c2 = approve_pending(&env, "plain-make");
    // The build itself fails this time.
    env.set_shim_fail("makepkg");
    let out = run_for(&env, &c2);
    match out {
        pipeline::Outcome::Failed { step, .. } => assert_eq!(step, "build"),
        other => panic!("{other:?}"),
    }
    // §8.4: the old version keeps serving and the candidate stays approved.
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
    assert_eq!(
        candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state,
        CandidateState::Approved
    );
    assert_eq!(
        env.query_i64("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0.1-1'", &[]),
        Some(0)
    );
}

#[test]
fn an_unresolvable_dependency_blocks_instead_of_failing() {
    let (env, _fx) = env_with_fixture("missing-dep");
    // We subscribe to `dep-partner` but have never published it: "unresolvable" in
    // §10.4 means wait, not fail.
    env.subscribe("dep-partner");
    let c = approve_fixture(&env, "missing-dep");
    let out = run_for(&env, &c);
    match out {
        pipeline::Outcome::Blocked { on } => {
            assert!(on.contains(&"dep-partner".to_string()), "{on:?}");
        }
        other => panic!("expected a blocked build, got {other:?}"),
    }
    let (bid, _name, blocked_on) = builds::blocked_builds(&env.db).unwrap().remove(0);
    assert_eq!(blocked_on, vec!["dep-partner".to_string()]);
    assert_eq!(builds::get(&env.db, &bid).unwrap().unwrap().state, BuildState::BlockedMissingDep);
    assert!(in_index(&env).is_empty(), "a blocked build publishes nothing");
}

#[test]
fn a_blocked_build_waits_until_its_dependency_actually_arrives() {
    let (env, _fx) = env_with_fixture("missing-dep");
    env.subscribe("dep-partner");
    let c = approve_fixture(&env, "missing-dep");
    assert!(matches!(run_for(&env, &c), pipeline::Outcome::Blocked { .. }));
    assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1);
    // The dispatcher sweeps blocked builds every pass. Requeueing one whose blocker
    // is still missing would block again immediately, so it must stay put.
    let _ = publish::reconcile(&env.cfg, &env.db);
    assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked");
    assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1);
}

#[test]
fn re_enqueueing_the_same_intent_is_a_noop() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    let a = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    let b = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    assert_eq!(a, b, "build ids are deterministic (§8.2)");
    assert_eq!(env.query_i64("SELECT count(*) FROM build", &[]), Some(1));
}

#[test]
fn i6_manual_rebuild_reuses_the_approved_identity() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);
    let before = env.query_i64("SELECT count(*) FROM approval", &[]);

    let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
    assert!(matches!(
        pipeline::run(&env.cfg, &env.db, &id).unwrap(),
        pipeline::Outcome::Succeeded { .. }
    ));
    // Same version, new release row, and crucially: no new approval (§2 I6).
    assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), before);
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
    assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(2));
}

#[test]
fn i12_world_snapshot_is_recorded_at_ingest() {
    let (env, fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);

    // Now a second build whose chroot had our own published package installed:
    // that is the pair staleness tracking is computed from (§10.1).
    let mut m = fx.manifest_json();
    m["installed"] = serde_json::json!([
        {"name": "plain-make", "version": "1.0-1", "arch": "x86_64"},
        {"name": "glibc", "version": "2.39-1", "arch": "x86_64"}
    ]);
    std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap();
    fx.bump(&[("pkgver", "1.0.1")]);
    let c2 = approve_pending(&env, "plain-make");
    run_for(&env, &c2);

    let wid = env
        .db
        .read(|c| {
            Ok(c.query_row(
                "SELECT world_snapshot_id FROM build WHERE world_snapshot_id IS NOT NULL
                 ORDER BY rowid DESC LIMIT 1",
                [],
                |r| r.get::<_, i64>(0),
            )?)
        })
        .unwrap();
    let json: String = env
        .db
        .read(|c| {
            Ok(c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", rusqlite::params![wid], |r| r.get(0))?)
        })
        .unwrap();
    let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
    let members: Vec<(String, String)> = parsed
        .iter()
        .map(|v| {
            (
                v["pkgbase"].as_str().unwrap_or_default().to_string(),
                v["version"].as_str().unwrap_or_default().to_string(),
            )
        })
        .collect();
    // The snapshot is the installed set INTERSECTED with our own packages:
    // unfiltered, Arch moving would make every package permanently stale.
    assert!(members.iter().any(|(n, v)| n == "plain-make" && v == "1.0-1"), "{members:?}");
    assert!(!members.iter().any(|(n, _)| n == "glibc"), "{members:?}");
}

#[test]
fn publish_refuses_without_an_approval_behind_it() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);
    // Approval rows are immutable (I10 / §7.2), so the bad state is built from the
    // other side: a release with nothing behind it.
    let rid = db::accepted_release(&env.db, "plain-make").unwrap().unwrap().id;
    env.exec("UPDATE release SET approval_id=NULL WHERE id=?1", &params(vec![rid]));
    let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap();
    match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
        pipeline::Outcome::Failed { step, error, .. } => {
            assert_eq!(step, "publish");
            assert!(error.contains("no approval"), "{error}");
        }
        other => panic!("I1 requires a refusal, got {other:?}"),
    }
    // The index still holds exactly the one entry that does have an approval.
    assert_eq!(in_index(&env).len(), 1);
}

#[test]
fn a_stale_accepted_pointer_refuses_to_publish() {
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    // The approval was taken against "nothing accepted yet". Move the pointer
    // out from under the build and the compare-and-swap must refuse.
    env.exec(
        "UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'",
        &[],
    );
    match pipeline::run(&env.cfg, &env.db, &id).unwrap() {
        pipeline::Outcome::Failed { step, error, .. } => {
            assert_eq!(step, "publish");
            assert!(error.contains("accepted pointer moved"), "{error}");
        }
        other => panic!("expected a CAS refusal, got {other:?}"),
    }
    assert!(in_index(&env).is_empty());
}

// ------------------------------------------------------- withdrawal and cleanup --

#[test]
fn withdrawing_a_release_twice_is_refused_the_second_time() {
    // m-10: the second withdraw used to report success while rewriting nothing.
    let (env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    run_for(&env, &c);
    let rid = db::accepted_release(&env.db, "plain-make").unwrap().unwrap().id;
    approve::withdraw(&env.db, "tester", rid, "upstream pulled the tarball").unwrap();
    let err = approve::withdraw(&env.db, "tester", rid, "again").unwrap_err();
    assert!(err.to_string().contains("not published"), "{err}");
    let err = approve::withdraw(&env.db, "tester", rid + 999, "x").unwrap_err();
    assert!(err.to_string().contains("no release"), "{err}");
    // The first withdrawal stands: the index no longer serves it.
    assert!(in_index(&env).is_empty(), "the withdrawn release is still in the index");
}

#[test]
fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() {
    // m-16: the artifacts are copied into the served tree before the DB commit,
    // and when the commit refused those bytes used to stay.
    let (mut env, _fx) = env_with_fixture("plain-make");
    let c = approve_fixture(&env, "plain-make");
    env.set_publish_fault("before-rename");
    let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
    assert!(matches!(
        pipeline::run(&env.cfg, &env.db, &id).unwrap(),
        pipeline::Outcome::Failed { .. }
    ));
    let stray: Vec<String> = std::fs::read_dir(env.cfg.repo_arch_dir())
        .expect("arch dir")
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().to_string())
        .filter(|n| n.ends_with(".pkg.tar.zst") || n.ends_with(".sig"))
        .collect();
    assert!(stray.is_empty(), "a publish that did not land left files behind: {stray:?}");

    // And the retry still works: the artifacts come from the collect dir, not the
    // served tree.
    env.clear_publish_fault();
    assert!(
        matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }),
        "the retry after cleanup failed"
    );
    assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]);
}