summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-20 21:03:58 +0000
committeraur-build <aur-build@localhost>2026-11-20 21:03:58 +0000
commit2210c934d4a25602318f094e0eca72f42862d44a (patch)
tree9bc80f269b05121e28f2465d3e9d1cd6d4457dfd
parent289560d196b65b0b257b59a92c956f088eb29fad (diff)
downloadaur-build-2210c934d4a25602318f094e0eca72f42862d44a.tar.gz
aur-build-2210c934d4a25602318f094e0eca72f42862d44a.zip
db, sandbox: apply the dispositions the table decided
Six db items are now gated behind `test-support`, each with a comment saying what it is for and why production never calls it: builds::claim production leases a batch; `claim_batch` is what the dispatcher runs settings::set_setting the readers are used, the setter is not Writer::shutdown the server runs until the process ends snapshots::snapshot_by_commit world::world_members production writes world snapshots, never reads one back member by member invariants::unapproved_index_entries gated, not relocated: reading it needs this module's private helpers, and widening those to let a test out would be the wrong trade Gating them exposed three things they were the only user of, and each is gated with them rather than left compiling into a binary that cannot reach it: `Msg::Shutdown` and its loop arm, and `model::json_or`. `arch-census.py --write-budget` also stopped erasing the `test_surface` section — two writers of one file must not delete each other's axis, or the ratchet quietly stops checking it. `steps::touch` is deleted, not narrowed. Nothing called it — not production, not a test. The census had credited it to `tests/shims.rs`, where the word appears inside a string. In sandbox, two tests moved into `src/sandbox/kata.rs`: the container record a lease provisions, and the TTL expiry of a sandbox that never dials in. Neither builds a fixture. `KataBackend::shared_for`, `provision_request`, `sandbox_cr` and `K8sSandboxProvisioner::for_config` are `pub(crate)` as a result. `KataBackend::reclaim` is deleted — same story as `touch`. It forwarded to `self.provisioner.reclaim`, which the reaping site already calls itself, and the TTL test the census credited it for implements the *trait's* `reclaim` on a null provisioner. Same word, different function. Two honest costs, both recorded rather than smoothed over: - `Provisioner` and `ProvisionRequest` are now named by nobody outside `sandbox`, yet cannot be narrowed: `LocalAgentProvisioner` is `pub` because two fixture tests construct it, and Rust forbids a public type implementing a private trait or taking a private parameter type. `sandbox.deadonly` therefore rises 0 → 2, with the reason here as the ratchet demands. - `agent_sandbox_config()` now exists in both `tests/kata.rs` and `src/sandbox/kata.rs`. Three of that file's remaining tests still need it, and a test helper cannot be shared across the crate boundary without making it public again. sandbox: 27 pub / 15 dead -> 22 pub / 10 dead. Suite: 284 passed, 0 failed, 0 ignored. Clippy clean.
-rw-r--r--src/db/builds/mod.rs10
-rw-r--r--src/db/builds/steps.rs9
-rw-r--r--src/db/invariants.rs8
-rw-r--r--src/db/mod.rs28
-rw-r--r--src/db/model/mod.rs3
-rw-r--r--src/db/settings.rs6
-rw-r--r--src/db/snapshots.rs5
-rw-r--r--src/db/world.rs5
-rw-r--r--src/sandbox/kata.rs117
-rw-r--r--tests/architecture-budget.json52
-rw-r--r--tests/kata.rs113
-rwxr-xr-xtools/arch-census.py14
-rw-r--r--tools/test-surface.md57
-rw-r--r--tools/test-surface.py22
14 files changed, 286 insertions, 163 deletions
diff --git a/src/db/builds/mod.rs b/src/db/builds/mod.rs
index 2035cfd..fc84335 100644
--- a/src/db/builds/mod.rs
+++ b/src/db/builds/mod.rs
@@ -127,6 +127,14 @@ pub fn queued(db: &Db, limit: i64) -> Result<Vec<String>> {
})
}
+/// Lease one named build to a worker.
+///
+/// Test-tier only. Production leases a *batch* — `claim_batch` is what the
+/// dispatcher runs — and nothing in the crate calls this single-build form.
+/// It stays because three test files lease one build at a time on purpose,
+/// and a test that wants to reason about one lease should not have to
+/// arrange for the batch form to hand back exactly one.
+#[cfg(feature = "test-support")]
pub fn claim(db: &Db, owner: &str, id: &str, lease_secs: i64) -> Result<bool> {
let (owner, id) = (owner.to_string(), id.to_string());
let exp = time::secs_ahead(lease_secs);
@@ -291,5 +299,5 @@ pub use steps::{
begin_step, blocked_builds, cancel_superseded, claim_batch,
finish_step, in_flight, queue_depth, requeue_transient,
retry, set_blocked_on, set_release_in, set_world,
- step_status, steps, touch,
+ step_status, steps,
};
diff --git a/src/db/builds/steps.rs b/src/db/builds/steps.rs
index 01d7c40..4ffff36 100644
--- a/src/db/builds/steps.rs
+++ b/src/db/builds/steps.rs
@@ -149,15 +149,6 @@ pub fn blocked_builds(db: &Db) -> Result<Vec<(String, String, Vec<String>)>> {
Ok(out)
})
}
-
-pub fn touch(db: &Db, id: &str) -> Result<()> {
- let id = id.to_string();
- db.writer.tx(move |tx| {
- tx.execute("UPDATE build SET updated_at=?1 WHERE id=?2", params![time::now(), id])?;
- Ok(())
- })
-}
-
pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64) -> Result<()> {
tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?;
Ok(())
diff --git a/src/db/invariants.rs b/src/db/invariants.rs
index 9853003..e2648fa 100644
--- a/src/db/invariants.rs
+++ b/src/db/invariants.rs
@@ -4,6 +4,14 @@ use crate::error::Result;
// ------------------------------------------------------- invariant helpers --
+/// Repo entries whose candidate was never approved.
+///
+/// Test-tier only, and deliberately so: this is an invariant the schema does
+/// not enforce and production does not check, so the only thing that keeps it
+/// true is that a test asserts it on every run. It is gated rather than moved
+/// to `tests/common` because reading it needs this module's private helpers,
+/// and widening those to let a test out would be the wrong trade.
+#[cfg(feature = "test-support")]
pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> {
db.read(|c| {
let mut stmt = c.prepare(
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 5ac55c9..e42bae4 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -26,6 +26,8 @@ mod world;
pub use migrations::MIGRATIONS;
pub(crate) use model::StateEnum;
+/// Its only caller is the test-tier `world_members`, so it is gated with it.
+#[cfg(feature = "test-support")]
pub(crate) use model::json_or;
pub use model::{
@@ -36,7 +38,9 @@ pub use model::{
notice_kind,
};
pub use audit::{AuditEntry, audit, audit_in, audit_system, list_audit};
-pub use invariants::{approved_but_unbuilt, unapproved_index_entries};
+pub use invariants::approved_but_unbuilt;
+#[cfg(feature = "test-support")]
+pub use invariants::unapproved_index_entries;
pub use metrics::{
artifact_bytes_served, build_state_counts, count_index_packages, count_pending_reviews,
count_published_releases, count_subscriptions, count_unacknowledged_notices, last_gc_age_secs,
@@ -63,8 +67,12 @@ pub use retention::{
mark_release_purged, pkgbase_release_pointers, published_release_ids, record_gc_run,
release_artifact_paths, serving_release_ids,
};
-pub use settings::{all_settings, set_setting, setting, setting_i64};
-pub use snapshots::{SnapshotRow, put_snapshot, snapshot_by_commit, snapshot_by_id};
+pub use settings::{all_settings, setting, setting_i64};
+#[cfg(feature = "test-support")]
+pub use settings::set_setting;
+pub use snapshots::{SnapshotRow, put_snapshot, snapshot_by_id};
+#[cfg(feature = "test-support")]
+pub use snapshots::snapshot_by_commit;
pub use stage_b::{stage_b_cache_get, stage_b_cache_put, stage_b_recent};
pub use staleness::{
NewArtifact, approval_note, candidate_snapshot_id, index_recipes,
@@ -75,7 +83,9 @@ pub use subscriptions::{
due_subscriptions, get_subscription, list_subscriptions, note_check,
set_subscription_state, subscribe,
};
-pub use world::{put_world_snapshot, world_members};
+pub use world::put_world_snapshot;
+#[cfg(feature = "test-support")]
+pub use world::world_members;
pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> {
T::parse(text).ok_or_else(|| {
@@ -160,6 +170,9 @@ type BoxedCall = Box<dyn FnOnce(&mut Connection) + Send>;
enum Msg {
Call(BoxedCall),
+ /// Only `Writer::shutdown` constructs this, and only the test tier calls
+ /// that; the server runs until the process ends.
+ #[cfg(feature = "test-support")]
Shutdown,
}
@@ -184,6 +197,7 @@ impl Writer {
for msg in rx.iter() {
match msg {
Msg::Call(f) => f(&mut conn),
+ #[cfg(feature = "test-support")]
Msg::Shutdown => break,
}
}
@@ -241,6 +255,12 @@ impl Writer {
.map_err(|_| Error::db("writer actor gone"))
}
+ /// Stop the writer actor.
+ ///
+ /// Test-tier only: the server runs until the process ends and never
+ /// quiesces the writer deliberately. Tests use it to prove a worker
+ /// that dies mid-write leaves the database consistent.
+#[cfg(feature = "test-support")]
pub fn shutdown(&self) {
let _ = self.tx.send(Msg::Shutdown);
}
diff --git a/src/db/model/mod.rs b/src/db/model/mod.rs
index 7c1fbf5..827ce5e 100644
--- a/src/db/model/mod.rs
+++ b/src/db/model/mod.rs
@@ -193,6 +193,9 @@ impl CandidateRow {
}
}
+/// Test-tier only: the one reader that needed it is `db::world_members`, which
+/// is itself gated because nothing in production reads a world snapshot back.
+#[cfg(feature = "test-support")]
pub(crate) fn json_or<T: serde::de::DeserializeOwned>(s: &str, fallback: T) -> T {
serde_json::from_str(s).unwrap_or(fallback)
}
diff --git a/src/db/settings.rs b/src/db/settings.rs
index ebd2c06..d42bb52 100644
--- a/src/db/settings.rs
+++ b/src/db/settings.rs
@@ -35,6 +35,12 @@ pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 {
}
}
+/// Write one settings row.
+///
+/// Test-tier only: the readers are used in production, the setter is not —
+/// settings are written by migration and by the operators' own hands, and no
+/// code path in the crate writes one at runtime.
+#[cfg(feature = "test-support")]
pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> {
let v = value.to_string();
let k = key.to_string();
diff --git a/src/db/snapshots.rs b/src/db/snapshots.rs
index 754d7b7..e227eca 100644
--- a/src/db/snapshots.rs
+++ b/src/db/snapshots.rs
@@ -47,6 +47,11 @@ pub struct SnapshotRow {
pub files_json: String,
}
+/// Find a snapshot by the commit it was taken at.
+///
+/// Test-tier only: detection looks snapshots up by id, and nothing in the
+/// crate performs a lookup by commit.
+#[cfg(feature = "test-support")]
pub fn snapshot_by_commit(db: &Db, pkgbase_id: i64, commit: &str) -> Result<Option<SnapshotRow>> {
db.read(|c| {
c.query_row(
diff --git a/src/db/world.rs b/src/db/world.rs
index 49779b9..73e327f 100644
--- a/src/db/world.rs
+++ b/src/db/world.rs
@@ -24,6 +24,11 @@ pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i6
})
}
+/// Read the members of a world snapshot.
+///
+/// Test-tier only: production writes world snapshots and never reads one back
+/// member by member; the index is served from the release rows.
+#[cfg(feature = "test-support")]
pub fn world_members(db: &Db, id: i64) -> Result<Vec<WorldMember>> {
db.read(|c| {
let s: String = c.query_row(
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs
index 26e4ba3..66f7cba 100644
--- a/src/sandbox/kata.rs
+++ b/src/sandbox/kata.rs
@@ -36,7 +36,7 @@ pub trait Provisioner: Send + Sync {
/// TTL even if the hub dies. The token rides in args for v1; a production
/// deployment should mount it from a Secret, and this comment is the honest
/// place that says so.
-pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
+pub(crate) fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
serde_json::json!({
"apiVersion": "agents.x-k8s.io/v1alpha1",
"kind": "Sandbox",
@@ -71,7 +71,7 @@ pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value {
}
impl K8sSandboxProvisioner {
- pub fn for_config(cfg: &Config) -> Option<Self> {
+ pub(crate) fn for_config(cfg: &Config) -> Option<Self> {
match &cfg.sandbox {
crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self {
api: api.clone(),
@@ -174,7 +174,7 @@ pub struct KataBackend {
}
impl KataBackend {
- pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> {
+ pub(crate) fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> {
let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } =
&cfg.sandbox
else {
@@ -199,7 +199,7 @@ impl KataBackend {
Ok(backend)
}
- pub fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest {
+ pub(crate) fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest {
ProvisionRequest {
sandbox_id: id.to_string(),
profile: spec.profile.clone(),
@@ -238,10 +238,15 @@ impl KataBackend {
})
}
- pub fn reclaim(&self, sandbox_id: &str) -> Result<()> {
- self.provisioner.reclaim(sandbox_id)
- }
-
+ /// NOTE: `KataBackend::reclaim` used to sit here and called nothing but
+ /// `self.provisioner.reclaim`, which the pool already calls itself at the
+ /// reaping site. Nothing — not a test — ever called the wrapper, so it is
+ /// gone rather than gated. The census had credited it to `tests/kata.rs`,
+ /// where the TTL test implements the *trait's* `reclaim` on a null
+ /// provisioner: same word, different function.
+ /// Test-tier in practice — `tests/remote_agent.rs` drives a real agent
+ /// through it — but it is a plain accessor on a public type, so it is
+ /// left public rather than gated behind a feature.
pub fn local_addr(&self) -> &str {
&self.addr
}
@@ -346,4 +351,100 @@ mod tests {
assert!(args.windows(2).any(|w| w[0] == "--hub" && w[1] == "10.0.0.5:9443"));
assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken"));
}
+
+ // ------------------------------------------------------------------
+ // Moved verbatim from tests/kata.rs. Neither test builds a fixture or
+ // touches a database: one asserts the shape of the container record a
+ // lease provisions, the other that a sandbox which never dials in expires
+ // by TTL rather than hanging. Both are about this module's own machinery,
+ // which is what let `KataBackend`, `sandbox_cr`, `provision_request`,
+ // `shared_for` and `for_config` stop being part of the crate's interface.
+ //
+ // `Provisioner` and `ProvisionRequest` stayed public, and not by
+ // oversight: a `pub` implementor cannot implement a `pub(crate)` trait,
+ // and a `pub` trait method cannot take a `pub(crate)` parameter. Narrowing
+ // them would force `LocalAgentProvisioner` private, and the two tests that
+ // construct it drive a real sandbox agent through a fixture.
+ // ------------------------------------------------------------------
+
+ fn agent_sandbox_config() -> Config {
+ let tmp = tempfile::tempdir().unwrap();
+ std::fs::write(
+ tmp.path().join("config.json"),
+ r#"{
+ "sandbox": {
+ "kind": "agent-sandbox",
+ "api": "https://k8s.test:6443",
+ "namespace": "builds",
+ "bearer": "kube-bearer",
+ "image": "aur-build-sandbox:test",
+ "listen": "127.0.0.1:0",
+ "token": "kata-cfg-token",
+ "shared_workspace": true
+ }
+}"#,
+ )
+ .unwrap();
+ let cfg = Config::load(tmp.path()).unwrap();
+ cfg.validate().expect("the config must survive the startup guard");
+ cfg
+ }
+
+ #[test]
+ fn an_agent_sandbox_config_provisions_a_kata_vm_per_lease() {
+ let cfg = agent_sandbox_config();
+ let backend = KataBackend::shared_for(&cfg).unwrap();
+ let spec = SandboxSpec::new("extra-x86_64", "build-9", Duration::from_secs(77));
+ let cr = sandbox_cr(&backend.provision_request(&spec, "sbx-nonce-9"));
+
+ assert_eq!(cr["spec"]["runtimeClass"], "kata", "the VM boundary is the point");
+ assert_eq!(
+ cr["spec"]["activeDeadlineSeconds"], 77,
+ "the orchestrator enforces the lease TTL even if the hub dies"
+ );
+ assert_eq!(
+ cr["metadata"]["name"], "sbx-nonce-9",
+ "the nonce names the box, so a stray sandbox cannot be leased to the wrong build"
+ );
+ assert_eq!(cr["spec"]["template"]["spec"]["containers"][0]["image"], "aur-build-sandbox:test");
+ let args: Vec<String> = cr["spec"]["template"]["spec"]["containers"][0]["args"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_str().unwrap().to_string())
+ .collect();
+ assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-nonce-9"));
+ assert!(args.windows(2).any(|w| w[0] == "--ttl" && w[1] == "77"));
+
+ let prov = K8sSandboxProvisioner::for_config(&cfg).unwrap();
+ assert_eq!(prov.api, "https://k8s.test:6443");
+ assert_eq!(prov.namespace, "builds");
+ assert_eq!(prov.bearer, "kube-bearer");
+ }
+
+ #[test]
+ fn a_sandbox_that_never_dials_in_is_a_ttl_expiry_not_a_hang() {
+ struct NullProvisioner;
+ impl Provisioner for NullProvisioner {
+ fn provision(&self, _req: &ProvisionRequest) -> Result<()> {
+ Ok(())
+ }
+ fn reclaim(&self, _id: &str) -> Result<()> {
+ Ok(())
+ }
+ fn name(&self) -> &str {
+ "null"
+ }
+ }
+ let cfg = Config::default();
+ let backend =
+ KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap();
+ let started = std::time::Instant::now();
+ let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) {
+ Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"),
+ Err(e) => e,
+ };
+ assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL");
+ assert!(err.to_string().contains("never dialed in"), "{err}");
+ }
}
diff --git a/tests/architecture-budget.json b/tests/architecture-budget.json
index d85d015..0e9fd0a 100644
--- a/tests/architecture-budget.json
+++ b/tests/architecture-budget.json
@@ -78,7 +78,7 @@
"test": 0
},
"config": {
- "dead": 3,
+ "dead": 2,
"deadonly": 0,
"glob": 0,
"largest": 667,
@@ -86,18 +86,18 @@
"lines": 667,
"priv": 0,
"pub": 29,
- "test": 3
+ "test": 2
},
"db": {
- "dead": 20,
+ "dead": 19,
"deadonly": 9,
"glob": 0,
"largest": 364,
"largest_file": "src/db/candidates.rs",
- "lines": 3859,
+ "lines": 3905,
"priv": 10,
- "pub": 201,
- "test": 11
+ "pub": 200,
+ "test": 10
},
"error": {
"dead": 0,
@@ -243,15 +243,15 @@
"test": 4
},
"sandbox": {
- "dead": 15,
- "deadonly": 0,
+ "dead": 10,
+ "deadonly": 2,
"glob": 0,
- "largest": 350,
+ "largest": 451,
"largest_file": "src/sandbox/kata.rs",
- "lines": 1178,
- "priv": 11,
- "pub": 27,
- "test": 15
+ "lines": 1279,
+ "priv": 15,
+ "pub": 22,
+ "test": 8
},
"shims": {
"dead": 12,
@@ -310,23 +310,25 @@
}
},
"test_surface": {
- "already-gated": 3,
- "gate": 9,
- "gate_pending": 9,
- "move-test": 9,
- "narrow": 6,
- "residue": 34
+ "already-gated": 9,
+ "gate": 3,
+ "gate_pending": 3,
+ "move-test": 3,
+ "narrow": 5,
+ "residue": 32,
+ "total": 52,
+ "ungated": 43
},
"totals": {
- "dead": 97,
- "deadonly": 34,
+ "dead": 90,
+ "deadonly": 36,
"edges": 87,
"glob": 0,
"largest": 667,
"largest_file": "src/config.rs",
- "lines": 14927,
- "priv": 109,
- "pub": 496,
- "test": 63
+ "lines": 15074,
+ "priv": 113,
+ "pub": 490,
+ "test": 54
}
}
diff --git a/tests/kata.rs b/tests/kata.rs
index f923ea2..a0c61fa 100644
--- a/tests/kata.rs
+++ b/tests/kata.rs
@@ -2,14 +2,42 @@ mod common;
use std::path::Path;
use std::sync::Arc;
-use std::time::{Duration, Instant};
+use std::time::Duration;
use aur_build::config::Config;
-use aur_build::error::Result;
-use aur_build::sandbox::kata::{KataBackend, LocalAgentProvisioner, ProvisionRequest, Provisioner};
+use aur_build::sandbox::kata::{KataBackend, LocalAgentProvisioner};
use aur_build::sandbox::{Cmd, SandboxBackend, SandboxSpec};
use common::{env_with_fixture, shim_dir};
+// What remains drives a real sandbox agent or a real fixture build. The two
+// tests that only asserted this module's own machinery — the container record a
+// lease provisions, and the TTL expiry of a sandbox that never dials in — moved
+// into src/sandbox/kata.rs, where that machinery is declared.
+
+
+fn agent_sandbox_config() -> Config {
+ let tmp = tempfile::tempdir().unwrap();
+ std::fs::write(
+ tmp.path().join("config.json"),
+ r#"{
+ "sandbox": {
+ "kind": "agent-sandbox",
+ "api": "https://k8s.test:6443",
+ "namespace": "builds",
+ "bearer": "kube-bearer",
+ "image": "aur-build-sandbox:test",
+ "listen": "127.0.0.1:0",
+ "token": "kata-cfg-token",
+ "shared_workspace": true
+ }
+}"#,
+ )
+ .unwrap();
+ let cfg = Config::load(tmp.path()).unwrap();
+ cfg.validate().expect("the config must survive the startup guard");
+ cfg
+}
+
#[test]
fn a_provisioned_sandbox_rendezvous_and_runs_a_command() {
let cfg = Config::default();
@@ -27,31 +55,6 @@ fn a_provisioned_sandbox_rendezvous_and_runs_a_command() {
}
#[test]
-fn a_sandbox_that_never_dials_in_is_a_ttl_expiry_not_a_hang() {
- struct NullProvisioner;
- impl Provisioner for NullProvisioner {
- fn provision(&self, _req: &ProvisionRequest) -> Result<()> {
- Ok(())
- }
- fn reclaim(&self, _id: &str) -> Result<()> {
- Ok(())
- }
- fn name(&self) -> &str {
- "null"
- }
- }
- let cfg = Config::default();
- let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "tok", Arc::new(NullProvisioner)).unwrap();
- let started = Instant::now();
- let err = match backend.acquire(&SandboxSpec::new("extra-x86_64", "ghost", Duration::from_secs(1))) {
- Ok(_) => panic!("nobody provisioned anything; the lease must not succeed"),
- Err(e) => e,
- };
- assert!(started.elapsed() >= Duration::from_millis(900), "acquire gave up before the TTL");
- assert!(err.to_string().contains("never dialed in"), "{err}");
-}
-
-#[test]
fn the_live_kata_tier_is_recorded_not_silently_absent() {
if !Path::new("/dev/kvm").exists() {
println!("note: no /dev/kvm on this host; the live kata tier is skipped, not passed");
@@ -76,60 +79,7 @@ fn the_live_kata_tier_is_recorded_not_silently_absent() {
sbx.destroy().unwrap();
}
-fn agent_sandbox_config() -> Config {
- let tmp = tempfile::tempdir().unwrap();
- std::fs::write(
- tmp.path().join("config.json"),
- r#"{
- "sandbox": {
- "kind": "agent-sandbox",
- "api": "https://k8s.test:6443",
- "namespace": "builds",
- "bearer": "kube-bearer",
- "image": "aur-build-sandbox:test",
- "listen": "127.0.0.1:0",
- "token": "kata-cfg-token",
- "shared_workspace": true
- }
-}"#,
- )
- .unwrap();
- let cfg = Config::load(tmp.path()).unwrap();
- cfg.validate().expect("the config must survive the startup guard");
- cfg
-}
-#[test]
-fn an_agent_sandbox_config_provisions_a_kata_vm_per_lease() {
- let cfg = agent_sandbox_config();
- let backend = aur_build::sandbox::kata::KataBackend::shared_for(&cfg).unwrap();
- let spec = SandboxSpec::new("extra-x86_64", "build-9", Duration::from_secs(77));
- let cr = aur_build::sandbox::kata::sandbox_cr(&backend.provision_request(&spec, "sbx-nonce-9"));
-
- assert_eq!(cr["spec"]["runtimeClass"], "kata", "the VM boundary is the point");
- assert_eq!(
- cr["spec"]["activeDeadlineSeconds"], 77,
- "the orchestrator enforces the lease TTL even if the hub dies"
- );
- assert_eq!(
- cr["metadata"]["name"], "sbx-nonce-9",
- "the nonce names the box, so a stray sandbox cannot be leased to the wrong build"
- );
- assert_eq!(cr["spec"]["template"]["spec"]["containers"][0]["image"], "aur-build-sandbox:test");
- let args: Vec<String> = cr["spec"]["template"]["spec"]["containers"][0]["args"]
- .as_array()
- .unwrap()
- .iter()
- .map(|v| v.as_str().unwrap().to_string())
- .collect();
- assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-nonce-9"));
- assert!(args.windows(2).any(|w| w[0] == "--ttl" && w[1] == "77"));
-
- let prov = aur_build::sandbox::kata::K8sSandboxProvisioner::for_config(&cfg).unwrap();
- assert_eq!(prov.api, "https://k8s.test:6443");
- assert_eq!(prov.namespace, "builds");
- assert_eq!(prov.bearer, "kube-bearer");
-}
#[test]
fn agent_sandbox_is_a_backend_not_a_fallthrough_to_loopback() {
@@ -183,4 +133,3 @@ fn a_fixture_builds_and_publishes_through_the_kata_lease_path() {
let shimlog = env.cfg.hooks.shim_dir.clone().unwrap();
assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1);
}
-
diff --git a/tools/arch-census.py b/tools/arch-census.py
index b493ea8..09f4201 100755
--- a/tools/arch-census.py
+++ b/tools/arch-census.py
@@ -285,8 +285,20 @@ def main():
data = census()
if args.write_budget:
+ # Preserve any section another tool owns (for example `test_surface`,
+ # written by tools/test-surface.py). Two writers of one file must not
+ # erase each other, or the ratchet silently stops checking one axis.
+ existing = {}
+ if os.path.exists(args.write_budget):
+ try:
+ existing = json.load(open(args.write_budget))
+ except (ValueError, OSError):
+ existing = {}
+ out = dict(existing)
+ out["modules"] = data["modules"]
+ out["totals"] = data["totals"]
with open(args.write_budget, "w") as handle:
- json.dump({"modules": data["modules"], "totals": data["totals"]}, handle, indent=2,
+ json.dump(out, handle, indent=2,
sort_keys=True)
handle.write("\n")
print(f"wrote {args.write_budget}")
diff --git a/tools/test-surface.md b/tools/test-surface.md
index f632e80..19890a1 100644
--- a/tools/test-surface.md
+++ b/tools/test-surface.md
@@ -46,51 +46,37 @@ The `residue` count is ratcheted by `tests/architecture.rs`, so it can only
shrink.
-## Gate behind `test-support` — 9 items
+## Gate behind `test-support` — 3 items
| module | item | declared at | test files | why |
|---|---|---|---|---|
-| `db` | `claim` | `src/db/builds/mod.rs:130` | `common/mod.rs`, `state_machine.rs`, `time.rs` | production leases with `claim_batch`; `claim` is called only by tests, so the release build need not compile it. |
-| `db` | `set_setting` | `src/db/settings.rs:38` | `db.rs` | a settings writer with no production caller; `setting`/`setting_i64` readers are used, the setter is not. |
-| `db` | `shutdown` | `src/db/mod.rs:244` | `common/mod.rs`, `crash.rs`, `dispatch.rs` | `Writer::shutdown` is never called by the server; tests use it to quiesce the writer thread. |
-| `db` | `snapshot_by_commit` | `src/db/snapshots.rs:50` | `detect.rs` | a snapshot lookup nothing in production performs. |
-| `db` | `unapproved_index_entries` | `src/db/invariants.rs:7` | `db.rs`, `detect.rs`, `notices.rs`, `shims.rs` | an invariant query nothing runs; it needs `pub(crate)` diff internals to be useful, so it is gated rather than relocated. |
-| `db` | `world_members` | `src/db/world.rs:27` | `db.rs` | a world-snapshot reader nothing calls; `put_world_snapshot` is the half production uses. |
| `review` | `render_and_store` | `src/review/diff.rs:269` | `approve.rs`, `common/mod.rs`, `crash.rs`, `dispatch.rs` … | intake renders through `review::intake::record`; this wrapper has zero callers in src and 17 in tests. Gated, not relocated: it needs the module-private diff renderer. |
| `shims` | `called_with` | `src/shims/mod.rs:144` | `crash.rs`, `dispatch.rs`, `invariants.rs`, `kata.rs` … | reads the shim's invocation log, which only tests inspect. |
| `time` | `unpin` | `src/time.rs:47` | `time.rs` | the clock escape hatch; `pin`/`unpin` exist so a test can freeze time. Its only in-module mention is a unit test. |
-## Move the test into the module, then narrow — 9 items
+## Move the test into the module, then narrow — 3 items
| module | item | declared at | test files | why |
|---|---|---|---|---|
| `http` | `cookie` | `src/http/mod.rs:36` | `common/mod.rs`, `http.rs` | the auth cookie helper; the tests that use it build no fixture, so they move into the module and it narrows. |
| `http` | `login` | `src/http/routes/mod.rs:45` | `common/mod.rs`, `http.rs` | the login route handler; same — its tests are harness-free and move with it. |
-| `sandbox` | `ProvisionRequest` | `src/sandbox/kata.rs:19` | `kata.rs` | kata provisioning internals; the test that names them needs no fixture. |
-| `sandbox` | `Provisioner` | `src/sandbox/kata.rs:28` | `kata.rs` | kata provisioning internals; same test. |
-| `sandbox` | `for_config` | `src/sandbox/kata.rs:74` | `kata.rs` | kata backend constructor; same test. |
-| `sandbox` | `provision_request` | `src/sandbox/kata.rs:202` | `kata.rs` | kata request builder; same test. |
-| `sandbox` | `reclaim` | `src/sandbox/kata.rs:241` | `kata.rs` | kata reclaim path; the TTL test that names it needs no fixture. |
-| `sandbox` | `sandbox_cr` | `src/sandbox/kata.rs:39` | `kata.rs` | kata container-record shape; same test. |
-| `sandbox` | `shared_for` | `src/sandbox/kata.rs:177` | `kata.rs` | kata workspace helper; same test. |
+| `sandbox` | `K8sSandboxProvisioner` | `src/sandbox/kata.rs:86` | `kata.rs` | the kata provisioner impl; tests/kata.rs drives it directly. |
-## Narrow — no test actually calls it — 6 items
+## Narrow — no test actually calls it — 5 items
| module | item | declared at | test files | why |
|---|---|---|---|---|
-| `db` | `touch` | `src/db/builds/steps.rs:153` | `shims.rs` | census false positive: `touch` appears in tests/shims.rs only inside a string literal. Narrow on its merits, not for the test tier. |
| `http` | `Attention` | `src/http/render.rs:182` | `crash.rs` | census false positive: named in crash.rs only inside a string. |
| `http` | `html` | `src/http/mod.rs:51` | `http.rs` | census false positive: named in http.rs only inside a string. |
| `http` | `logout` | `src/http/routes/mod.rs:36` | `http.rs` | census false positive: named in http.rs only inside a string. |
| `http` | `redirect` | `src/http/mod.rs:67` | `http.rs` | census false positive: named in http.rs only inside a string. |
| `http` | `route` | `src/http/routes/mod.rs:65` | `http.rs` | census false positive: named in http.rs only inside a string. |
-## Residue — `pub` because Rust has no test-conditional visibility — 34 items
+## Residue — `pub` because Rust has no test-conditional visibility — 32 items
| module | item | declared at | test files | why |
|---|---|---|---|---|
| `config` | `TestHooks` | `src/config.rs:138` | `common/mod.rs`, `production_surface.rs` | the `hooks` field is already gated; the type and its impl are not, so they compile into a release build that can never read them. |
-| `config` | `shared_workspace` | `src/config.rs:93` | `config.rs`, `kata.rs`, `remote_agent.rs` | `Config::validate` calls it at config.rs:226; tests/kata.rs and tests/remote_agent.rs call it too and both need a fixture. |
| `config` | `store_dir` | `src/config.rs:351` | `invariants.rs` | the content-addressed store layout is used at config.rs:313 and :355; tests/invariants.rs pins it and needs a fixture. |
| `db` | `MIGRATIONS` | `src/db/migrations.rs:326` | `db.rs` | `db::migrate` iterates it at db/mod.rs:135; tests/db.rs asserts the list is ordered and complete. |
| `db` | `ReleaseState` | `src/db/model/state.rs:78` | `pipeline.rs` | a row type named by twenty sites inside db; tests/pipeline.rs names it while driving a real pipeline. |
@@ -109,13 +95,12 @@ shrink.
| `review` | `BulkRefusal` | `src/review/approve.rs:155` | `approve.rs` | the bulk-refusal payload, built and matched across approve.rs; tests/approve.rs asserts on it. |
| `review` | `LOW` | `src/review/risk.rs:6` | `notices.rs` | the risk floor, compared at risk.rs:94,189,195; tests/notices.rs pins where the floor bites. |
| `sandbox` | `Exit` | `src/sandbox/mod.rs:43` | `failure_modes.rs` | the sandbox exit record, named across the backends; tests/failure_modes.rs asserts on it. |
-| `sandbox` | `K8sSandboxProvisioner` | `src/sandbox/kata.rs:86` | `kata.rs` | the kata provisioner impl; tests/kata.rs drives it directly. |
| `sandbox` | `KataBackend` | `src/sandbox/kata.rs:167` | `kata.rs` | the kata backend; tests/kata.rs constructs it rather than going through `for_config`'s caller. |
| `sandbox` | `LocalAgentProvisioner` | `src/sandbox/kata.rs:124` | `kata.rs` | the local agent provisioner impl; tests/kata.rs drives it. |
| `sandbox` | `LoopbackBackend` | `src/sandbox/loopback.rs:10` | `failure_modes.rs` | the default backend; tests/failure_modes.rs constructs it to inject a fault. |
| `sandbox` | `RemoteBackend` | `src/sandbox/remote.rs:12` | `remote_agent.rs` | the remote backend; tests/remote_agent.rs constructs it against a real agent. |
| `sandbox` | `SandboxInfo` | `src/sandbox/mod.rs:70` | `failure_modes.rs` | the sandbox descriptor returned by the trait; tests/failure_modes.rs reads its fields. |
-| `sandbox` | `local_addr` | `src/sandbox/kata.rs:245` | `remote_agent.rs` | the agent's local address, read by the backend selection at mod.rs:120; tests/remote_agent.rs asserts on it. |
+| `sandbox` | `local_addr` | `src/sandbox/kata.rs:250` | `remote_agent.rs` | the agent's local address, read by the backend selection at mod.rs:120; tests/remote_agent.rs asserts on it. |
| `shims` | `invocations` | `src/shims/mod.rs:133` | `shims.rs` | reads the shim invocation log; the shim writes it in production (mod.rs:112) but nothing in src reads it back. |
| `shims` | `manifest` | `src/shims/mod.rs:88` | `common/mod.rs`, `invariants.rs`, `pipeline.rs`, `production_surface.rs` … | the shim manifest, read by `run` at mod.rs:161; seven test files read it to assert what a build did. |
| `shims` | `valid_db_arg` | `src/shims/mod.rs:479` | `shims.rs` | the shim's `--db` argument validator; production calls it at mod.rs:510, tests check its verdicts. |
@@ -124,11 +109,17 @@ shrink.
| `watch` | `probe` | `src/watch/upstream.rs:25` | `ops.rs`, `vcs.rs` | the upstream probe, called by detect.rs:95; tests/ops.rs and tests/vcs.rs both need a fixture. |
| `watch` | `sync_mirror` | `src/watch/mirror.rs:17` | `detect.rs` | the mirror sync, called by detect.rs:40; tests/detect.rs drives a real sync. |
-## Already gated — 3 items
+## Already gated — 9 items
| module | item | declared at | test files | why |
|---|---|---|---|---|
-| `db` | `tx_for_tests` | `src/db/mod.rs:251` | `approve.rs`, `common/mod.rs`, `db.rs`, `invariants.rs` … | already gated behind test-support — the pattern the rest of this table asks for. |
+| `db` | `claim` | `src/db/builds/mod.rs:138` | `common/mod.rs`, `state_machine.rs`, `time.rs` | production leases with `claim_batch`; `claim` is called only by tests, so the release build need not compile it. |
+| `db` | `set_setting` | `src/db/settings.rs:44` | `db.rs` | a settings writer with no production caller; `setting`/`setting_i64` readers are used, the setter is not. |
+| `db` | `shutdown` | `src/db/mod.rs:264` | `common/mod.rs`, `crash.rs`, `dispatch.rs` | `Writer::shutdown` is never called by the server; tests use it to quiesce the writer thread. |
+| `db` | `snapshot_by_commit` | `src/db/snapshots.rs:55` | `detect.rs` | a snapshot lookup nothing in production performs. |
+| `db` | `tx_for_tests` | `src/db/mod.rs:271` | `approve.rs`, `common/mod.rs`, `db.rs`, `invariants.rs` … | already gated behind test-support — the pattern the rest of this table asks for. |
+| `db` | `unapproved_index_entries` | `src/db/invariants.rs:15` | `db.rs`, `detect.rs`, `notices.rs`, `shims.rs` | an invariant query nothing runs; it needs `pub(crate)` diff internals to be useful, so it is gated rather than relocated. |
+| `db` | `world_members` | `src/db/world.rs:32` | `db.rs` | a world-snapshot reader nothing calls; `put_world_snapshot` is the half production uses. |
| `time` | `virtual_sleep` | `src/time.rs:168` | `production_surface.rs` | already gated behind test-support. |
| `time` | `virtualize` | `src/time.rs:119` | `crash.rs`, `dispatch.rs`, `production_surface.rs` | already gated behind test-support. |
@@ -136,14 +127,14 @@ shrink.
| disposition | count |
|---|---|
-| `gate` | 9 |
-| `move-test` | 9 |
-| `narrow` | 6 |
-| `residue` | 34 |
-| `already-gated` | 3 |
-| **total** | **61** |
-
-Of these, 58 are ungated today. Gating the `gate` rows and narrowing the
-`narrow` rows removes 15 items from the release build's public surface; the
-`move-test` rows remove 9 more and take their tests home with them.
+| `gate` | 3 |
+| `move-test` | 3 |
+| `narrow` | 5 |
+| `residue` | 32 |
+| `already-gated` | 9 |
+| **total** | **52** |
+
+Of these, 43 are ungated today. Gating the `gate` rows and narrowing the
+`narrow` rows removes 8 items from the release build's public surface; the
+`move-test` rows remove 3 more and take their tests home with them.
diff --git a/tools/test-surface.py b/tools/test-surface.py
index 40385ad..7a89069 100644
--- a/tools/test-surface.py
+++ b/tools/test-surface.py
@@ -279,12 +279,34 @@ if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--json", action="store_true")
ap.add_argument("--write", action="store_true")
+ ap.add_argument("--write-budget", metavar="FILE",
+ help="re-record the `test_surface` section of the budget file")
a = ap.parse_args()
rows = analyse()
if a.json:
counts = collections.Counter(r["disp"] for r in rows)
counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"])
+ counts["ungated"] = sum(1 for r in rows if not r["gated"])
+ counts["total"] = len(rows)
print(json.dumps({"rows": rows, "counts": counts}, indent=1))
+ elif a.write_budget:
+ rows = analyse()
+ counts = collections.Counter(r["disp"] for r in rows)
+ counts["gate_pending"] = sum(1 for r in rows if r["disp"] == "gate" and not r["gated"])
+ counts["ungated"] = sum(1 for r in rows if not r["gated"])
+ counts["total"] = len(rows)
+ path = a.write_budget
+ if not os.path.isabs(path):
+ path = os.path.join(ROOT, path)
+ budget = json.load(open(path))
+ budget["test_surface"] = {k: counts[k] for k in
+ ("gate", "gate_pending", "move-test", "narrow",
+ "residue", "already-gated", "total", "ungated")
+ if counts[k]}
+ with open(path, "w") as handle:
+ json.dump(budget, handle, indent=2, sort_keys=True)
+ handle.write("\n")
+ print("wrote", os.path.relpath(path, ROOT), json.dumps(budget["test_surface"], sort_keys=True))
elif a.write:
open(DOC, "w").write(render(rows))
print("wrote", os.path.relpath(DOC, ROOT))