diff options
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/invariants.rs | 396 |
1 files changed, 396 insertions, 0 deletions
diff --git a/tests/invariants.rs b/tests/invariants.rs new file mode 100644 index 0000000..c1a70ad --- /dev/null +++ b/tests/invariants.rs @@ -0,0 +1,396 @@ +//! The §2 invariant index. +//! +//! Every invariant in DESIGN.md §2 gets a named test here, asserted as a +//! **post-condition on a real end-to-end run** rather than as a unit test of the +//! function that happens to maintain it. If one of these ever fails, the +//! property the whole design rests on is broken, not just some helper. +//! +//! Invariants whose mechanism lands in a later phase are named at the bottom +//! with the test that covers them once it does. + +mod common; + +use aur_build::db::{self, model::*}; +use aur_build::pipeline::{self, publish}; +use aur_build::review::approve::approve as do_approve; +use aur_build::review::{candidates, diff}; +use common::*; + +/// subscribe → detect → render → approve → build → publish, in one call. +fn full_run(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(); + do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); + let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + let out = pipeline::run(&env.cfg, &env.db, &id).unwrap(); + assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}"); + c +} + +fn query_pairs(env: &Env, sql: &str) -> Vec<(String, String)> { + env.db + .read(move |c| { + let mut st = c.prepare(sql)?; + let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + Ok(rows.filter_map(|r| r.ok()).collect()) + }) + .unwrap() +} + +fn count(env: &Env, sql: &str) -> i64 { + env.db + .read(move |c| Ok(c.query_row(sql, [], |r| r.get::<_, i64>(0))?)) + .unwrap() +} + +/// **I1 — no artifact without an approval.** After a real publish, every entry +/// in the served index traces back through a release to an approval row. +#[test] +fn i1_every_index_entry_traces_back_to_an_approval() { + let (env, _fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + + // The §2 query, verbatim in spirit: index entry → release → approval. + assert_eq!( + count( + &env, + "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)" + ), + 0, + "I1: an index entry exists that no human approved" + ); + // And the reverse direction: nothing was approved and then quietly dropped. + assert_eq!( + count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"), + 1 + ); + assert_eq!(count(&env, "SELECT count(*) FROM release WHERE approval_id IS NULL"), 0); +} + +/// **I2 — the diff base is the last accepted version, never the last seen one.** +/// Many detections arrive while nobody is looking; the review still compares +/// against the accepted release, not against whatever was polled last. +#[test] +fn i2_base_is_the_last_accepted_version_after_many_detections() { + let (env, fx) = env_with_fixture("plain-make"); + let c = full_run(&env, "plain-make"); + let accepted = db::accepted_release(&env.db, "plain-make").unwrap().unwrap(); + assert_eq!(accepted.pkgver, "1.0"); + + // Five upstream moves with nobody reviewing. + for v in ["1.1", "1.2", "1.3", "1.4", "1.5"] { + fx.bump(&[("pkgver", v)]); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); + } + let open = candidates::pending_candidates(&env.db).unwrap(); + assert_eq!(open.len(), 1, "one open review, collapsed in place"); + assert_eq!(open[0].pkgver, "1.5", "it shows the newest state"); + assert_eq!( + open[0].base_release_id, + Some(accepted.id), + "I2: the diff base must be the accepted release ({}), not the last seen commit", + accepted.id + ); + // And the rendered diff really compares against it. + let panels = diff::panels(&env.cfg, &env.db, &open[0], Some(&accepted)).unwrap(); + let text = diff::render_text(&panels); + assert!(text.contains("1.0"), "diff should show the accepted version: {text}"); + assert!(text.contains("1.5"), "diff should show the candidate: {text}"); + let _ = c; +} + +/// **I4 — publishing is atomic.** Kill the process mid-publish: the consumer- +/// visible index is either entirely the old one or entirely the new one. +#[test] +fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() { + let (mut env, fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz"); + let old_bytes = std::fs::read(&db_file).unwrap(); + + fx.bump(&[("pkgver", "9.9")]); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + // Die after the new database is rendered to .tmp but before the rename. + env.set_publish_fault("before-rename"); + assert!(matches!( + pipeline::run(&env.cfg, &env.db, &id).unwrap(), + pipeline::Outcome::Failed { .. } + )); + + assert_eq!( + std::fs::read(&db_file).unwrap(), + old_bytes, + "I4: the served index was torn by a crash" + ); + assert_eq!( + query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"), + vec![("plain-make".to_string(), "1.0-1".to_string())] + ); + // Recovery re-materializes the index from the DB; it invents nothing. + assert!(publish::reconcile(&env.cfg, &env.db).unwrap() >= 1); + assert_eq!(std::fs::read(&db_file).unwrap(), old_bytes); +} + +/// **I5 — a build resumes at the next incomplete step.** A worker that dies +/// mid-pipeline does not repeat the expensive work or double-publish. +#[test] +fn i5_resume_after_a_crash_repeats_no_completed_step() { + let (mut env, fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + + fx.bump(&[("pkgver", "2.0")]); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + + env.set_publish_fault("before-rename"); + assert!(matches!( + pipeline::run(&env.cfg, &env.db, &id).unwrap(), + pipeline::Outcome::Failed { .. } + )); + let shim = env.cfg.shim_dir.clone().unwrap(); + let builds_before = aur_build::shims::called_with(&shim, "makechrootpkg", ""); + assert_eq!(builds_before, 2, "one build per attempted publish"); + + // "Restart" the worker on the same build row. + 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(&shim, "makechrootpkg", ""), + builds_before, + "I5: resuming re-ran the build step" + ); + // No duplicate side effects: one release row for the version, one artifact. + assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1); + // Artifacts are content-addressed and persist across builds; what must not + // happen is the same bytes recorded twice. + assert_eq!( + count(&env, "SELECT count(*) FROM artifact"), + count(&env, "SELECT count(DISTINCT digest) FROM artifact"), + "I5: the resume recorded a duplicate artifact" + ); + // Every step is checkpointed as succeeded or explicitly skipped. + let bad = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT count(*) FROM build_step WHERE status NOT IN ('succeeded','skipped')", + [], + |r| r.get::<_, i64>(0), + )?) + }) + .unwrap(); + assert_eq!(bad, 0, "every step reached a terminal state"); +} + +/// **I7 — at most one open review per pkgbase.** Enforced by the partial unique +/// index, not by application politeness. +#[test] +fn i7_the_schema_refuses_a_second_open_review() { + let (env, _fx) = env_with_fixture("plain-make"); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let pb = c.pkgbase_id; + let snap = c.snapshot_id; + let err = env + .db + .writer + .tx(move |tx| { + tx.execute( + "INSERT INTO candidate (pkgbase_id, kind, snapshot_id, epoch, pkgver, pkgrel, + upstream_pins_json, source_digests_json, identity_hash, + diff_digest, state, detected_at) + VALUES (?1,'new_version',?2,'0','9','1','[]','[]','other-hash','',?3,'now')", + rusqlite::params![pb, snap, candidate_state::PENDING], + )?; + Ok(()) + }) + .err(); + assert!(err.is_some(), "I7: a second pending review was accepted"); + assert_eq!(candidates::pending_candidates(&env.db).unwrap().len(), 1); +} + +/// **I8 — the served index is exactly the set of accepted pointers.** Not a +/// superset (nothing stale lingers) and not a subset (nothing published is +/// missing). Checked against the files on disk as well as the rows. +#[test] +fn i8_index_equals_the_accepted_pointers() { + let (env, fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + fx.bump(&[("pkgver", "2.0")]); + full_run(&env, "plain-make"); + + let pointers = query_pairs( + &env, + "SELECT p.name, + CASE WHEN r.epoch IN ('', '0') THEN '' ELSE r.epoch || ':' END + || r.pkgver || '-' || r.pkgrel + FROM pkgbase p + JOIN release r ON r.id = p.current_accepted_release_id", + ); + let index = query_pairs( + &env, + "SELECT name, version FROM package WHERE state='in_index'", + ); + assert!(!pointers.is_empty()); + assert_eq!(index, pointers, "I8: index and accepted pointers diverge"); + + // The superseded version is really gone, not merely hidden. + assert_eq!( + count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"), + 0 + ); + // And the database file on disk lists the same set. + let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz"); + let names = index_db_names(&db_file); + assert_eq!(names, vec!["plain-make".to_string()]); +} + +/// **I3 — the recipe is pinned to a commit.** Materializing anything other than +/// the approved tree fails closed before a build runs. +#[test] +fn i3_materialization_fails_closed_on_the_recipe_pin() { + let (env, _fx) = env_with_fixture("plain-make"); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); + env.exec( + "UPDATE snapshot SET recipe_hash='sha256:0000' WHERE id=?1", + ¶ms(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!("I3 requires a refusal, got {other:?}"), + } + assert_eq!(count(&env, "SELECT count(*) FROM release"), 0); +} + +/// **I6 — a rebuild never needs a new approval.** +#[test] +fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() { + let (env, _fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + let approvals = count(&env, "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 { .. } + )); + assert_eq!(count(&env, "SELECT count(*) FROM approval"), approvals, "I6: a rebuild demanded a new approval"); + assert_eq!( + query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"), + vec![("plain-make".to_string(), "1.0-1".to_string())] + ); +} + +/// **I10 — the audit log is append-only**, and every consequential action is in it. +#[test] +fn i10_audit_is_append_only_and_records_the_decisions() { + let (env, _fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + for sql in [ + "UPDATE audit SET action='x'", + "DELETE FROM audit", + "UPDATE approval SET note='x' WHERE id=1", + "DELETE FROM approval", + ] { + let db = env.db.clone(); + let s = sql.to_string(); + assert!( + db.writer + .tx(move |tx| { + tx.execute(&s, [])?; + Ok(()) + }) + .is_err(), + "{sql} should be refused" + ); + } + let actions = env + .db + .read(|c| { + let mut st = c.prepare("SELECT action FROM audit")?; + let rows = st.query_map([], |r| r.get::<_, String>(0))?; + Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>()) + }) + .unwrap(); + for want in ["approve", "publish", "build.start", "build.succeeded"] { + assert!(actions.iter().any(|a| a == want), "audit missing {want}: {actions:?}"); + } +} + +/// **I12 — every build records the world it was built against.** +#[test] +fn i12_every_build_records_a_world_snapshot() { + let (env, fx) = env_with_fixture("plain-make"); + full_run(&env, "plain-make"); + 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", "3.0")]); + full_run(&env, "plain-make"); + + assert_eq!( + count(&env, "SELECT count(*) FROM build WHERE world_snapshot_id IS NULL AND state='succeeded'"), + 0, + "I12: a succeeded build has no recorded world" + ); + let members = env + .db + .read(|c| { + let json: String = c.query_row( + "SELECT w.members_json FROM world_snapshot w + JOIN build b ON b.world_snapshot_id = w.id ORDER BY b.rowid DESC LIMIT 1", + [], + |r| r.get(0), + )?; + Ok(json) + }) + .unwrap(); + assert!(members.contains("plain-make"), "our own package belongs in the world"); + assert!(!members.contains("glibc"), "foreign packages must be filtered out (§10.1)"); +} + +// I9 (build isolation) is exercised by the chroot step and the real-chroot tier; +// I11 (non-publishable change becomes a notice, never a silent drop) is covered +// by `recipe_drift_under_a_static_version_is_a_notice_not_a_candidate` in +// tests/detect.rs and gets its full treatment with P1's upstream probes. + +/// Read the package names out of a pacman-style database file (gzipped tar). +fn index_db_names(path: &std::path::Path) -> Vec<String> { + let file = std::fs::File::open(path).unwrap(); + let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(file)); + let mut names: Vec<String> = ar + .entries() + .unwrap() + .filter_map(|e| e.ok()) + .filter_map(|e| { + let p = e.path().ok()?.to_string_lossy().into_owned(); + p.split('/').next().map(|s| s.to_string()) + }) + .collect(); + names.sort(); + names.dedup(); + names +} |
