From 5e0e6b33de44609d96491ba226fe2aa03657abb0 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:37:14 +0100 Subject: [PATCH 1/3] test(scan): a person's follow-up waits behind every scheduled scan (t84) Reproduces t84: a scan requested while the target's scheduled scan still waits for a slot is coalesced as its follow-up, but the follow-up only queues for a slot after that scan finished, behind every other scheduled scan of the tick. Fails until person-started scans go first. Co-Authored-By: Claude Opus 5.5 --- compliance-agent/src/scan_gate.rs | 65 +++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/compliance-agent/src/scan_gate.rs b/compliance-agent/src/scan_gate.rs index af12658..f1ef939 100644 --- a/compliance-agent/src/scan_gate.rs +++ b/compliance-agent/src/scan_gate.rs @@ -274,6 +274,71 @@ mod tests { assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced); } + /// What `ComplianceAgent::run_target_scan` does once admitted: take a + /// slot, scan (here: log), and run the pending follow-up, if any. + async fn hold_and_scan( + gate: std::sync::Arc, + key: String, + mut trigger: ScanTrigger, + log: std::sync::Arc>>, + ) { + loop { + { + let _slot = gate.slot().await.unwrap(); + log.lock().unwrap().push((key.clone(), trigger.clone())); + } + match gate.finish(&key) { + Some(next) => trigger = next, + None => break, + } + } + } + + #[tokio::test] + async fn a_persons_follow_up_runs_before_scheduled_scans_still_waiting() { + let gate = std::sync::Arc::new(ScanGate::new(1)); + let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + // Another tenant's scan has the only slot. + let busy = gate.slot().await.unwrap(); + + // A scheduler tick admits three targets; all wait for the slot. + let mut tasks = Vec::new(); + for target in ["t1", "t2", "t3"] { + let key = ScanGate::key("acme", target); + assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run); + tasks.push(tokio::spawn(hold_and_scan( + gate.clone(), + key, + ScanTrigger::Scheduled, + log.clone(), + ))); + // Let it queue for the slot before the next one does. + tokio::task::yield_now().await; + } + + // A person asks for t1 while its scheduled scan still waits. + let t1 = ScanGate::key("acme", "t1"); + assert_eq!(gate.admit(&t1, ScanTrigger::Manual), Admission::Coalesced); + + drop(busy); + for task in tasks { + task.await.unwrap(); + } + let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone(); + let manual = order + .iter() + .position(|(k, t)| *k == t1 && *t == ScanTrigger::Manual) + .expect("the person's scan runs"); + let last_scheduled = order + .iter() + .rposition(|(_, t)| *t == ScanTrigger::Scheduled) + .expect("the scheduled scans run"); + assert!( + manual < last_scheduled, + "the person's follow-up waited behind every scheduled scan: {order:?}" + ); + } + #[tokio::test] async fn slots_bound_how_many_scans_run_at_once() { let gate = ScanGate::new(2); -- 2.54.1 From eac393613f75b006379254a5dd8cb555ab79a0f3 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:54:17 +0100 Subject: [PATCH 2/3] fix(scan): a person's scan gets the next slot and shows as queued (t84) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A scan a person asked for waited behind every scheduled scan of every tenant: the scan gate's slots were one FIFO semaphore, and a request for a target whose scheduled scan still waited became a follow-up behind it. On stage a click waited about 3 hours with nothing to show for it. - Scan gate: two queues for the slots. Manual and support scans go first, FIFO within each class; after 3 person scans in a row a waiting background scan gets the slot, so clicks never starve the scheduler. - A person's request takes over a waiting scan that was not a person's, at person priority; on a running target it is the follow-up and re-queues at person priority once the running scan ends. - Each request is recorded at once as a run with status `queued` ("Wartet auf einen Platz"), follow-ups included; the scan starts on that run. Requests that will not run have theirs removed; one whose scan ends before it starts is closed as failed. - A restart closes queued runs as interrupted and resumes the target; a queued run does not count toward the restart-loop guard, and a person's trigger wins. - Evidence and the platform's last_scan_at ignore queued runs. Metering is unchanged: a counted Prüfung is admitted and charged when it runs. Co-Authored-By: Claude Opus 5.5 --- compliance-agent/src/agent.rs | 130 +++- compliance-agent/src/api/handlers/evidence.rs | 7 +- .../src/api/handlers/onboarding.rs | 13 +- compliance-agent/src/api/handlers/platform.rs | 2 +- compliance-agent/src/lifecycle.rs | 53 +- compliance-agent/src/pipeline/orchestrator.rs | 73 +- compliance-agent/src/scan_gate.rs | 729 +++++++++++++++--- compliance-agent/tests/scan_queue.rs | 167 ++++ compliance-core/src/models/scan.rs | 34 + .../src/components/scan_runs.rs | 40 +- compliance-dashboard/src/i18n/texts.rs | 13 + .../src/infrastructure/onboarding.rs | 16 +- 12 files changed, 1087 insertions(+), 190 deletions(-) create mode 100644 compliance-agent/tests/scan_queue.rs diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index aed8b3e..247733d 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -10,7 +10,7 @@ use crate::database::DatabasePool; use crate::llm::LlmClient; use crate::pipeline::orchestrator::PipelineOrchestrator; use crate::registry::RegistryClient; -use crate::scan_gate::{Admission, HeldTarget, ScanGate}; +use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate}; use crate::secrets::SecretBox; /// A target whose billing changed, with its new billing (t72). @@ -262,11 +262,16 @@ impl ComplianceAgent { } /// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans - /// run at once, and a request for a target that is already being scanned is - /// coalesced — it becomes the one pending follow-up that this task runs next, - /// or it is dropped if a follow-up is already pending. A scheduled scan - /// first waits a random [`crate::scan_gate::start_delay`]. Every trigger - /// (click, webhook, scheduler, demo seed) comes through here. + /// run at once, a person's before scheduled and webhook ones, and a request + /// for a target that is already queued or being scanned is coalesced — it + /// becomes the one pending follow-up that this task runs next, it takes over + /// a queued scan that was not a person's, or it is dropped as covered. A + /// scheduled scan first waits a random [`crate::scan_gate::start_delay`]. + /// Every trigger (click, webhook, scheduler, demo seed) comes through here. + /// + /// Each request is recorded at once as a `queued` run, which shows that it + /// waits for a slot (t84); a request that will not run has its queued run + /// removed again. /// /// # Errors /// @@ -288,15 +293,22 @@ impl ComplianceAgent { ); tokio::time::sleep(delay).await; } + let db = self.db_pool.for_tenant_id(tenant_id).await?; + let run_id = queue_run(&db, target_id, &trigger).await; let key = ScanGate::key(tenant_id, target_id); - match self.scan_gate.admit(&key, trigger.clone()) { + match self + .scan_gate + .admit(&key, Job::new(trigger, run_id.clone())) + { Admission::Run => {} - Admission::Coalesced => { + Admission::Coalesced { replaced } => { tracing::info!( tenant_id, target_id, + took_over = replaced.is_some(), "scan already running; follow-up queued" ); + discard_queued_run(&db, replaced.as_deref()).await; return Ok(()); } Admission::Dropped => { @@ -305,40 +317,45 @@ impl ComplianceAgent { target_id, "scan and follow-up already queued; dropped" ); + discard_queued_run(&db, run_id.as_deref()).await; return Ok(()); } } // Released on panic or cancellation; a normal finish disarms it. let held = HeldTarget::new(&self.scan_gate, key.clone()); - let mut trigger = trigger; let result = loop { - let outcome = { - let _slot = self - .scan_gate - .slot() - .await - .map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?; - self.run_one_target_scan(tenant_id, target_id, trigger.clone()) - .await - }; + // The scan to run is the one current when the slot is granted: a + // person's request may have taken it over while it waited. + let (slot, job) = self + .scan_gate + .start(&key) + .await + .map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?; + let job_run = job.run_id; + let outcome = self + .run_one_target_scan(tenant_id, target_id, job.trigger, job_run.as_deref()) + .await; + drop(slot); if let Err(e) = &outcome { tracing::error!(tenant_id, target_id, "scan failed: {e}"); + fail_queued_run(&db, job_run.as_deref(), e).await; } - match self.scan_gate.finish(&key) { - Some(next) => trigger = next, - None => break outcome, + if !self.scan_gate.finish(&key) { + break outcome; } }; held.disarm(); result } - /// One scan of a target, with no gating: the pipeline plus its usage event. + /// One scan of a target, with no gating: the pipeline plus its usage event, + /// recorded on the run `queued` that waited for it. async fn run_one_target_scan( &self, tenant_id: &str, target_id: &str, trigger: compliance_core::models::ScanTrigger, + queued: Option<&str>, ) -> Result<(), crate::error::AgentError> { let db = self.db_pool.for_tenant_id(tenant_id).await?; // Whether this target is included or extra decides whether its scan @@ -355,7 +372,9 @@ impl ComplianceAgent { .with_advisory_index(self.advisory_index.clone()) .with_plan_limits(plan.map(|p| p.limits)); let started = chrono::Utc::now(); - let outcome = orchestrator.run_target(target_id, trigger.clone()).await?; + let outcome = orchestrator + .run_target(target_id, trigger.clone(), queued) + .await?; // Support's scans are ours, not the customer's usage; a scheduled scan // skipped because nothing changed scanned nothing (#465). if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support { @@ -424,7 +443,7 @@ impl ComplianceAgent { // slot too. Each PR is distinct work, so it is not coalesced. let _slot = self .scan_gate - .slot() + .slot(Priority::Background) .await .map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?; let db = self.db_pool.for_tenant_id(tenant_id).await?; @@ -500,6 +519,69 @@ impl ComplianceAgent { } } +/// Record a scan request for `target_id` as a run waiting for a slot (t84), +/// so it shows at once. Returns its id, or `None` when it could not be +/// written: the scan then runs on a run of its own when it starts. +async fn queue_run( + db: &crate::database::Database, + target_id: &str, + trigger: &compliance_core::models::ScanTrigger, +) -> Option { + let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone()); + match db.scan_runs().insert_one(&run).await { + Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()), + Err(e) => { + tracing::warn!(target_id, "queued scan run not recorded: {e}"); + None + } + } +} + +/// Remove the queued run `run_id` of a request that will not run, because +/// another queued scan covers it or took it over. A run that has started +/// meanwhile is kept. +async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) { + let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else { + return; + }; + if let Err(e) = db + .scan_runs() + .delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" }) + .await + { + tracing::warn!(run_id = %oid, "queued scan run not removed: {e}"); + } +} + +/// Close the queued run `run_id` as failed when its scan ended with `error` +/// before it started (an unknown target, an unreachable database), so it does +/// not stay queued. A run the scan started records its own outcome. +async fn fail_queued_run( + db: &crate::database::Database, + run_id: Option<&str>, + error: &crate::error::AgentError, +) { + let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else { + return; + }; + let (code, message) = error.run_failure(); + if let Err(e) = db + .scan_runs() + .update_one( + mongodb::bson::doc! { "_id": oid, "status": "queued" }, + mongodb::bson::doc! { "$set": { + "status": "failed", + "error_message": message, + "error_code": mongodb::bson::to_bson(&code).unwrap_or_default(), + "completed_at": mongodb::bson::DateTime::now(), + } }, + ) + .await + { + tracing::warn!(run_id = %oid, "queued scan run not closed: {e}"); + } +} + /// Findings of `target_id` first stored since `since`, by severity; `None` /// when there are none. async fn new_findings_summary( diff --git a/compliance-agent/src/api/handlers/evidence.rs b/compliance-agent/src/api/handlers/evidence.rs index b12f092..87ae16c 100644 --- a/compliance-agent/src/api/handlers/evidence.rs +++ b/compliance-agent/src/api/handlers/evidence.rs @@ -79,9 +79,14 @@ async fn load_inputs( .map_err(load_err)?, ) .await, + // A run still waiting for a slot has examined nothing yet (t84). last_run: db .scan_runs() - .find_one(by_target) + .find_one({ + let mut started = by_target; + started.insert("status", doc! { "$ne": "queued" }); + started + }) .sort(doc! { "started_at": -1 }) .await .map_err(load_err)?, diff --git a/compliance-agent/src/api/handlers/onboarding.rs b/compliance-agent/src/api/handlers/onboarding.rs index 722b456..82b4832 100644 --- a/compliance-agent/src/api/handlers/onboarding.rs +++ b/compliance-agent/src/api/handlers/onboarding.rs @@ -114,7 +114,7 @@ pub async fn list_targets( // `join!` borrows its futures' arguments, so the collections need names. let (runs, findings) = (db.scan_runs(), db.findings()); let (mut last_scans, counts) = tokio::join!( - latest_scan_runs(&runs, ids.clone()), + latest_scan_runs(&runs, ids.clone(), true), findings_counts(&findings, ids), ); let data = targets @@ -179,10 +179,13 @@ impl TargetFilter { } } -/// The newest scan run of each target in `target_ids`, in one query. +/// The newest scan run of each target in `target_ids`, in one query; with +/// `with_queued`, also a run still waiting for a slot (t84), which the +/// dashboard shows but which has scanned nothing yet. pub(crate) async fn latest_scan_runs( runs: &mongodb::Collection, target_ids: Vec, + with_queued: bool, ) -> HashMap { use futures_util::StreamExt; @@ -190,8 +193,12 @@ pub(crate) async fn latest_scan_runs( return HashMap::new(); } // Runs store their target's id as `repo_id`. + let mut matching = doc! { "repo_id": { "$in": target_ids } }; + if !with_queued { + matching.insert("status", doc! { "$ne": "queued" }); + } let pipeline = vec![ - doc! { "$match": { "repo_id": { "$in": target_ids } } }, + doc! { "$match": matching }, doc! { "$sort": { "started_at": -1 } }, doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } }, ]; diff --git a/compliance-agent/src/api/handlers/platform.rs b/compliance-agent/src/api/handlers/platform.rs index fceda1f..702d6a0 100644 --- a/compliance-agent/src/api/handlers/platform.rs +++ b/compliance-agent/src/api/handlers/platform.rs @@ -560,7 +560,7 @@ pub async fn list_targets( .collect(); let runs = db.scan_runs(); let (mut last_scans, open, vulns) = tokio::join!( - super::onboarding::latest_scan_runs(&runs, ids.clone()), + super::onboarding::latest_scan_runs(&runs, ids.clone(), false), open_findings_counts(&db, ids.clone()), open_vulnerabilities_counts(&db, ids), ); diff --git a/compliance-agent/src/lifecycle.rs b/compliance-agent/src/lifecycle.rs index d901848..750c2d6 100644 --- a/compliance-agent/src/lifecycle.rs +++ b/compliance-agent/src/lifecycle.rs @@ -43,14 +43,15 @@ struct OrphanRule { } /// Code scans are what customers see, so they get their own `interrupted` -/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and +/// status, also those still waiting for a slot: the queue lives in the agent's +/// memory and is gone after a restart (t84). The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and /// pentest are off in production, and graph and embedding builds are steps of /// a scan. A paused pentest session can only be resumed through in-memory /// state, so after a restart it is as dead as a running one. const ORPHAN_RULES: [OrphanRule; 5] = [ OrphanRule { collection: "scan_runs", - open: &["running"], + open: &["queued", "running"], closed_as: "interrupted", }, OrphanRule { @@ -218,12 +219,16 @@ async fn targets_to_resume( .await?; let mut out = Vec::new(); for id in ids.iter().filter_map(|v| v.as_str()) { + // Only scans that had started count: one interrupted while it still + // waited for a slot cannot be what stopped the agent. It never got a + // start time of its own, so it still starts when it was requested. let interruptions = db .scan_runs() .count_documents(doc! { "repo_id": id, "status": "interrupted", "completed_at": { "$gte": window }, + "$expr": { "$ne": ["$started_at", "$queued_at"] }, }) .await?; if interruptions > MAX_RECENT_INTERRUPTIONS { @@ -243,12 +248,25 @@ async fn targets_to_resume( .await?; if active > 0 { // Resumed as it was started: a scan a person started runs even when - // nothing changed since the last completed one (#465). - let trigger = db + // nothing changed since the last completed one (#465). Of a running + // scan and its queued follow-up, a person's wins. + let triggers = db .scan_runs() - .find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed }) - .await? - .map_or(ScanTrigger::Scheduled, |run| run.trigger); + .distinct( + "trigger", + doc! { "repo_id": id, "status": "interrupted", "completed_at": closed }, + ) + .await?; + let triggers: Vec = triggers + .into_iter() + .filter_map(|t| mongodb::bson::from_bson(t).ok()) + .collect(); + let trigger = triggers + .iter() + .find(|t| t.started_by_person()) + .or_else(|| triggers.first()) + .cloned() + .unwrap_or(ScanTrigger::Scheduled); out.push((id.to_string(), trigger)); } } @@ -365,10 +383,11 @@ mod tests { let archived = insert(archived_target).await; let earlier_only = insert(target("earlier-only")).await; - // Arrange: runs left open, plus one interrupted an hour ago. - // The scan to resume was started by a person. + // Arrange: runs left open, plus one interrupted an hour ago. The + // target to resume has a scheduled scan running and a person's + // follow-up queued (t84): one interruption, resumed as the person's. for (id, trigger) in [ - (&resumes, ScanTrigger::Manual), + (&resumes, ScanTrigger::Scheduled), (&looping, ScanTrigger::Scheduled), (&archived, ScanTrigger::Scheduled), ] { @@ -377,6 +396,10 @@ mod tests { .await .unwrap(); } + db.scan_runs() + .insert_one(ScanRun::queued(resumes.clone(), ScanTrigger::Manual)) + .await + .unwrap(); for id in [&looping, &earlier_only] { let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled); run.status = compliance_core::models::ScanRunStatus::Interrupted; @@ -423,6 +446,16 @@ mod tests { } } + #[test] + fn queued_code_scans_are_closed_at_startup_too() { + let scan_rule = ORPHAN_RULES + .iter() + .find(|r| r.collection == "scan_runs") + .expect("scan_runs rule"); + assert!(scan_rule.open.contains(&"queued")); + assert!(scan_rule.open.contains(&"running")); + } + #[test] fn code_scans_are_interrupted_not_failed() { let scan_rule = ORPHAN_RULES diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 847e801..4d79039 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -1159,7 +1159,9 @@ impl PipelineOrchestrator { /// `OnboardedTarget`. Mirrors [`Self::run`] but sources the target from /// `onboarded_targets` and dispatches by the scan plan. #[tracing::instrument(skip_all, fields(target_id = %target_id, trigger = ?trigger))] - /// Run one scan of the target `target_id`. + /// Run one scan of the target `target_id`, recorded on the run `queued` + /// that waited for this scan's slot (t84), or on a new run when there is + /// none. /// /// # Returns /// @@ -1174,6 +1176,7 @@ impl PipelineOrchestrator { &self, target_id: &str, trigger: ScanTrigger, + queued: Option<&str>, ) -> Result { let oid = mongodb::bson::oid::ObjectId::parse_str(target_id) .map_err(|e| AgentError::Other(e.to_string()))?; @@ -1191,12 +1194,9 @@ impl PipelineOrchestrator { scan_run.attribution = Some(attribution); scan_run.chargeable = attribution.chargeable(target.billing); } - let insert = self.db.scan_runs().insert_one(&scan_run).await?; - let scan_run_id = insert - .inserted_id - .as_object_id() - .map(|id| id.to_hex()) - .unwrap_or_default(); + let run_oid = self.start_run(&scan_run, queued).await?; + let scan_run_id = run_oid.to_hex(); + let run_id = mongodb::bson::Bson::ObjectId(run_oid); // A counted Prüfung a person started is checked against the plan // before anything runs (t72). @@ -1230,10 +1230,7 @@ impl PipelineOrchestrator { } self.db .scan_runs() - .update_one( - doc! { "_id": &insert.inserted_id }, - doc! { "$set": completed }, - ) + .update_one(doc! { "_id": &run_id }, doc! { "$set": completed }) .await?; // Refresh the target's cached findings count. The shared pipeline // (Stage 7) increments `repositories`, which the unified path does @@ -1270,7 +1267,7 @@ impl PipelineOrchestrator { self.db .scan_runs() .update_one( - doc! { "_id": &insert.inserted_id }, + doc! { "_id": &run_id }, doc! { "$set": { "status": "completed", "current_phase": "completed", @@ -1285,7 +1282,7 @@ impl PipelineOrchestrator { self.db .scan_runs() .update_one( - doc! { "_id": &insert.inserted_id }, + doc! { "_id": &run_id }, doc! { "$set": { "status": "failed", "error_message": message, @@ -1305,7 +1302,7 @@ impl PipelineOrchestrator { let run = self .db .scan_runs() - .find_one(doc! { "_id": &insert.inserted_id }) + .find_one(doc! { "_id": &run_id }) .await .ok() .flatten(); @@ -1319,7 +1316,7 @@ impl PipelineOrchestrator { // A counted Prüfung is charged when it completed, or when it failed on // the customer's input; a failure of ours never is (t72). let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) { - self.charge_run(&insert.inserted_id, target_id).await + self.charge_run(&run_id, target_id).await } else { None }; @@ -1334,6 +1331,52 @@ impl PipelineOrchestrator { }) } + /// Record that `run` starts now: on the run `queued` that waited for the + /// slot, which moves from `queued` to `running`, or as a new run when + /// there is none or it is gone. Returns the run's id. + /// + /// # Errors + /// + /// The run could not be written. + async fn start_run( + &self, + run: &ScanRun, + queued: Option<&str>, + ) -> Result { + if let Some(oid) = queued.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) { + let mut started = doc! { + "status": "running", + "trigger": mongodb::bson::to_bson(&run.trigger) + .map_err(|e| AgentError::Other(e.to_string()))?, + "started_at": mongodb::bson::DateTime::from_chrono(run.started_at), + "chargeable": run.chargeable, + }; + if let Some(attribution) = run.attribution { + started.insert( + "attribution", + mongodb::bson::to_bson(&attribution) + .map_err(|e| AgentError::Other(e.to_string()))?, + ); + } + let updated = self + .db + .scan_runs() + .update_one( + doc! { "_id": oid, "status": "queued" }, + doc! { "$set": started }, + ) + .await?; + if updated.matched_count == 1 { + return Ok(oid); + } + } + let insert = self.db.scan_runs().insert_one(run).await?; + insert + .inserted_id + .as_object_id() + .ok_or_else(|| AgentError::Other("the scan run got no id".into())) + } + /// Check a counted Prüfung against the plan before it scans (t72): /// the quota, today's Prüftag on the target, the customer's cap. It runs /// when the plan's limits or the usage are not known. diff --git a/compliance-agent/src/scan_gate.rs b/compliance-agent/src/scan_gate.rs index f1ef939..0cb74be 100644 --- a/compliance-agent/src/scan_gate.rs +++ b/compliance-agent/src/scan_gate.rs @@ -1,37 +1,55 @@ -//! How many scans run at once, and what happens to a scan requested while the -//! same target is already being scanned. +//! How many scans run at once, in which order they get a slot, and what +//! happens to a scan requested while the same target is already queued or +//! being scanned. //! //! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes, //! a scheduler tick and a few clicks could start any number of scans side by //! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two //! scans of the same target shared one checkout directory and corrupted each -//! other. Two rules now apply to every trigger (click, webhook, scheduler): +//! other. These rules now apply to every trigger (click, webhook, scheduler): //! //! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait //! for a slot. -//! * **Per target — coalesce:** one scan runs and at most one more is pending. -//! A request that arrives while one is pending is dropped, because the pending -//! scan will pick up the latest code anyway. Ten pushes during a long scan -//! therefore cost two scans, not ten. Dropped requests are never billed: only -//! a scan that actually ran emits usage. +//! * **Order:** a scan a person started ([`Priority::Person`]) gets a free slot +//! before scheduled, webhook and new-content scans ([`Priority::Background`]); +//! within a class the first to ask is the first served. So that a stream of +//! clicks never starves the scheduler, a waiting background scan gets the +//! slot after [`PERSON_GRANTS_IN_A_ROW`] person scans in a row (t84). +//! * **Per target — coalesce:** one scan of a target waits or runs, and while +//! it runs at most one more is pending. A request while the scan still waits +//! for its slot is covered by it (it reads the latest code once it starts); +//! a request while one is pending is covered by that one. Ten pushes during +//! a long scan therefore cost two scans, not ten. A person's request takes +//! over a waiting or pending scan that was not a person's, so it runs at +//! person priority and always scans. Requests that do not run are never +//! billed: only a scan that actually ran emits usage. +//! +//! Each admitted request carries the id of the run recorded for it while it +//! waits (status `queued`); the gate tells the caller which of those runs will +//! not happen, so no queued run is left behind. //! //! A scheduled scan also starts after a random delay of up to //! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often //! all on one git host) do not start in the same second. -use std::sync::Arc; +use std::collections::VecDeque; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use dashmap::mapref::entry::Entry; use dashmap::DashMap; use rand::Rng; -use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tokio::sync::oneshot; use compliance_core::models::ScanTrigger; /// The longest a scheduled scan waits before it starts. pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30); +/// How many slots in a row go to person-started scans while a background scan +/// waits; the next one goes to the background scan. +pub const PERSON_GRANTS_IN_A_ROW: u32 = 3; + /// How long a scan with `trigger` waits before it starts: a random delay of /// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a /// webhook or a person started. @@ -45,33 +63,101 @@ pub fn start_delay(trigger: &ScanTrigger) -> Duration { } } +/// Which queue a scan waits in for a slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Priority { + /// Started by a person (the customer or support): served first. + Person, + /// Scheduled, webhook and new-content scans, and PR reviews. + Background, +} + +impl Priority { + /// The queue a scan with `trigger` waits in. + pub fn of(trigger: &ScanTrigger) -> Self { + if trigger.started_by_person() { + Self::Person + } else { + Self::Background + } + } +} + +/// One scan to run: what started it and the run recorded for it while it +/// waits (`None` when that record could not be written). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Job { + pub trigger: ScanTrigger, + pub run_id: Option, +} + +impl Job { + /// A scan started by `trigger`, recorded as the run `run_id`. + pub fn new(trigger: ScanTrigger, run_id: Option) -> Self { + Self { trigger, run_id } + } + + fn priority(&self) -> Priority { + Priority::of(&self.trigger) + } +} + /// What happened to a scan request. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Admission { - /// Nothing was running for this target: the caller runs the scan now. + /// Nothing was queued or running for this target: the caller now holds + /// it and runs its scans through [`ScanGate::start`]. Run, - /// A scan is running; this request becomes the single pending follow-up, - /// run by the task that holds the target once it finishes. - Coalesced, - /// A scan is running and a follow-up is already pending: nothing to do. + /// The request will run: as the target's pending follow-up, or in place + /// of the target's waiting scan. `replaced` is the run of the request it + /// took over, which will not happen. + Coalesced { replaced: Option }, + /// A scan already queued for this target covers the request: its own run + /// will not happen. Dropped, } +/// The scan queue is gone, or the target is no longer held. +#[derive(Debug, thiserror::Error)] +pub enum GateError { + #[error("the scan queue was closed")] + Closed, + #[error("the target is not held")] + NotHeld, +} + /// Global scan slots plus the per-target coalescing state. #[derive(Debug)] pub struct ScanGate { - slots: Arc, - /// Present while a scan of the key is running; the value is the pending - /// follow-up's trigger, if one was requested meanwhile. - running: DashMap>, + slots: Arc, + /// Present while a scan of the key waits or runs. + targets: DashMap, +} + +/// The scans of one target that are queued or running. +#[derive(Debug)] +struct Held { + /// The scan that waits for a slot or runs now. + current: Job, + /// Whether `current` has its slot. + running: bool, + /// The follow-up requested while `current` runs. + pending: Option, } impl ScanGate { /// A gate allowing `concurrency` scans at once (at least one). pub fn new(concurrency: usize) -> Self { Self { - slots: Arc::new(Semaphore::new(concurrency.max(1))), - running: DashMap::new(), + slots: Arc::new(Slots { + queue: Mutex::new(Queue { + free: concurrency.max(1), + person: VecDeque::new(), + background: VecDeque::new(), + person_grants: 0, + }), + }), + targets: DashMap::new(), } } @@ -83,60 +169,248 @@ impl ScanGate { /// Decide what to do with a scan request for `key`. Atomic per key, so two /// simultaneous requests can never both be told to [`Admission::Run`]. - pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission { - match self.running.entry(key.to_string()) { + pub fn admit(&self, key: &str, job: Job) -> Admission { + // Lock order: a target's entry, then the slot queue (in `promote`). + // `start` keeps the same order and `Permit::drop` takes only the queue. + match self.targets.entry(key.to_string()) { Entry::Vacant(v) => { - v.insert(None); + v.insert(Held { + current: job, + running: false, + pending: None, + }); Admission::Run } - Entry::Occupied(mut o) if o.get().is_none() => { - o.insert(Some(trigger)); - Admission::Coalesced + Entry::Occupied(mut o) => { + let held = o.get_mut(); + let person = job.trigger.started_by_person(); + // A person's request takes over a queued scan that is not a + // person's: that one might skip as unchanged (#465), theirs + // always scans, e.g. right after they uploaded new files. + let takes_over = |queued: &Job| person && !queued.trigger.started_by_person(); + if !held.running { + // The waiting scan reads the latest code once it starts, + // so it covers the request, or the person's takes its + // place, at person priority. + if !takes_over(&held.current) { + return Admission::Dropped; + } + let replaced = std::mem::replace(&mut held.current, job).run_id; + self.slots.promote(key); + return Admission::Coalesced { replaced }; + } + match held.pending.as_ref().map(takes_over) { + None => { + held.pending = Some(job); + Admission::Coalesced { replaced: None } + } + Some(true) => { + let replaced = held.pending.replace(job).and_then(|p| p.run_id); + Admission::Coalesced { replaced } + } + Some(false) => Admission::Dropped, + } } - // A person's request takes over a pending scheduled or webhook - // follow-up: that one may skip as unchanged (#465), theirs always - // scans, e.g. right after they uploaded new files. - Entry::Occupied(mut o) - if trigger.started_by_person() - && o.get().as_ref().is_some_and(|p| !p.started_by_person()) => - { - o.insert(Some(trigger)); - Admission::Coalesced - } - Entry::Occupied(_) => Admission::Dropped, } } - /// Called by the task holding `key` after each scan. Returns the pending - /// follow-up to run next (the target stays held), or `None` once there is - /// nothing left, releasing the target. - pub fn finish(&self, key: &str) -> Option { - match self.running.entry(key.to_string()) { - Entry::Occupied(mut o) => match o.get_mut().take() { - Some(next) => Some(next), - None => { - o.remove(); - None + /// Wait for a slot for the held target `key`'s next scan, in the queue of + /// its priority, and return the slot with the scan to run. The scan is the + /// one current when the slot is granted: a person's request may have taken + /// it over meanwhile. + /// + /// # Errors + /// + /// [`GateError::NotHeld`] if `key` was released meanwhile, and + /// [`GateError::Closed`] if the queue is gone, which this gate never does. + pub async fn start(&self, key: &str) -> Result<(Permit, Job), GateError> { + let waiting = { + let held = self.targets.get(key).ok_or(GateError::NotHeld)?; + self.slots.enqueue(Some(key), held.current.priority()) + // The entry's guard is dropped here, before waiting. + }; + let permit = waiting.wait().await?; + let mut held = self.targets.get_mut(key).ok_or(GateError::NotHeld)?; + held.running = true; + Ok((permit, held.current.clone())) + } + + /// Called by the task holding `key` after each scan. Returns whether a + /// follow-up is pending, to run next through [`Self::start`] (the target + /// stays held), or `false` once there is nothing left, releasing it. + pub fn finish(&self, key: &str) -> bool { + match self.targets.entry(key.to_string()) { + Entry::Occupied(mut o) => { + let held = o.get_mut(); + match held.pending.take() { + Some(next) => { + held.current = next; + held.running = false; + true + } + None => { + o.remove(); + false + } } - }, - Entry::Vacant(_) => None, + } + Entry::Vacant(_) => false, } } /// Release `key` unconditionally, dropping any pending follow-up. Used when /// the holding task dies, so the target does not stay "running" forever. pub fn release(&self, key: &str) { - self.running.remove(key); + self.targets.remove(key); } - /// Wait for one of the global scan slots. The slot is freed when the - /// returned permit is dropped. + /// Wait for a slot for work that is not a target's scan (a PR review). + /// The slot is freed when the returned permit is dropped. /// /// # Errors /// - /// Only if the semaphore was closed, which this gate never does. - pub async fn slot(&self) -> Result { - self.slots.clone().acquire_owned().await + /// Only if the queue is gone, which this gate never does. + pub async fn slot(&self, priority: Priority) -> Result { + self.slots.enqueue(None, priority).wait().await + } +} + +/// The slots and the two queues waiting for them. +#[derive(Debug)] +struct Slots { + queue: Mutex, +} + +#[derive(Debug)] +struct Queue { + /// Slots nobody holds. Only above zero while nobody waits. + free: usize, + person: VecDeque, + background: VecDeque, + /// Person scans granted in a row while a background scan waited. + person_grants: u32, +} + +/// One request waiting for a slot; the slot is handed over through `grant`. +#[derive(Debug)] +struct Waiter { + /// The target it is for, so a person's request can move it forward. + key: Option, + grant: oneshot::Sender, +} + +/// A request in a queue, or a slot already granted. +enum Waiting { + Granted(Permit), + Queued(oneshot::Receiver), +} + +impl Waiting { + async fn wait(self) -> Result { + match self { + Self::Granted(permit) => Ok(permit), + // The sender only goes away unsent with the gate itself. + Self::Queued(grant) => grant.await.map_err(|_| GateError::Closed), + } + } +} + +impl Slots { + /// The queue, also after a thread panicked while holding it: every change + /// to it is a single push or pop, so it is never left half-changed. + fn lock(&self) -> MutexGuard<'_, Queue> { + self.queue.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Take a free slot, or join the queue of `priority`. + fn enqueue(self: &Arc, key: Option<&str>, priority: Priority) -> Waiting { + let mut queue = self.lock(); + if queue.free > 0 { + queue.free -= 1; + return Waiting::Granted(Permit::new(self)); + } + let (grant, granted) = oneshot::channel(); + let waiter = Waiter { + key: key.map(str::to_string), + grant, + }; + match priority { + Priority::Person => queue.person.push_back(waiter), + Priority::Background => queue.background.push_back(waiter), + } + Waiting::Queued(granted) + } + + /// Move the background request for `key`, if one waits, to the back of + /// the person queue. + fn promote(&self, key: &str) { + let mut queue = self.lock(); + let found = queue + .background + .iter() + .position(|w| w.key.as_deref() == Some(key)); + if let Some(waiter) = found.and_then(|i| queue.background.remove(i)) { + queue.person.push_back(waiter); + } + } + + /// Hand a freed slot to the next request, or keep it free. + fn release(self: &Arc) { + let mut queue = self.lock(); + while let Some(waiter) = queue.next() { + match waiter.grant.send(Permit::new(self)) { + Ok(()) => return, + // The request was given up (its task ended): the permit comes + // back unused, and the slot goes to the next one. + Err(mut unused) => unused.slots = None, + } + } + queue.free += 1; + } +} + +impl Queue { + /// The next request to serve: person scans first, except that a waiting + /// background scan gets the slot after [`PERSON_GRANTS_IN_A_ROW`] person + /// scans in a row. + fn next(&mut self) -> Option { + let background_due = self.person.is_empty() || self.person_grants >= PERSON_GRANTS_IN_A_ROW; + if background_due { + if let Some(waiter) = self.background.pop_front() { + self.person_grants = 0; + return Some(waiter); + } + } + let waiter = self.person.pop_front()?; + self.person_grants = if self.background.is_empty() { + 0 + } else { + self.person_grants + 1 + }; + Some(waiter) + } +} + +/// One scan slot; freed, and handed to the next request, when dropped. +#[derive(Debug)] +pub struct Permit { + /// `None` once the permit was given back unused. + slots: Option>, +} + +impl Permit { + fn new(slots: &Arc) -> Self { + Self { + slots: Some(Arc::clone(slots)), + } + } +} + +impl Drop for Permit { + fn drop(&mut self) { + if let Some(slots) = self.slots.take() { + slots.release(); + } } } @@ -175,10 +449,20 @@ impl Drop for HeldTarget<'_> { #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { - use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER}; + use super::{ + start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW, + SCHEDULED_SCAN_JITTER, + }; use compliance_core::models::ScanTrigger; + use std::sync::{Arc, Mutex}; use std::time::Duration; + type Log = Arc>>; + + fn job(trigger: ScanTrigger, run: &str) -> Job { + Job::new(trigger, Some(run.to_string())) + } + #[test] fn a_scheduled_scan_waits_within_the_jitter() { let delays: Vec = (0..1000) @@ -202,52 +486,117 @@ mod tests { } #[test] - fn a_burst_coalesces_into_one_run_and_one_follow_up() { + fn only_a_persons_scan_has_person_priority() { + assert_eq!(Priority::of(&ScanTrigger::Manual), Priority::Person); + assert_eq!(Priority::of(&ScanTrigger::Support), Priority::Person); + for trigger in [ + ScanTrigger::Scheduled, + ScanTrigger::Webhook, + ScanTrigger::NewContent, + ] { + assert_eq!(Priority::of(&trigger), Priority::Background); + } + } + + #[tokio::test] + async fn a_burst_coalesces_into_one_run_and_one_follow_up() { let gate = ScanGate::new(2); let key = ScanGate::key("acme", "t1"); - assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run); - assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced); - for _ in 0..8 { - assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r1")), + Admission::Run + ); + let (_slot, running) = gate.start(&key).await.unwrap(); + assert_eq!(running, job(ScanTrigger::Manual, "r1")); + + assert_eq!( + gate.admit(&key, job(ScanTrigger::Webhook, "r2")), + Admission::Coalesced { replaced: None } + ); + for i in 0..8 { + let run = format!("drop{i}"); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Webhook, &run)), + Admission::Dropped + ); } // The holder runs the one follow-up, then releases the target. - assert!(gate.finish(&key).is_some()); - assert!(gate.finish(&key).is_none()); - assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run); + assert!(gate.finish(&key)); + let (_next, follow_up) = gate.start(&key).await.unwrap(); + assert_eq!(follow_up, job(ScanTrigger::Webhook, "r2")); + assert!(!gate.finish(&key)); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r3")), + Admission::Run + ); } #[test] - fn a_persons_request_takes_over_a_pending_scheduled_follow_up() { + fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() { let gate = ScanGate::new(1); let key = ScanGate::key("acme", "t1"); - assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run); assert_eq!( - gate.admit(&key, ScanTrigger::Scheduled), - Admission::Coalesced + gate.admit(&key, job(ScanTrigger::Scheduled, "r1")), + Admission::Run + ); + // Not started yet, so it will read the push's code anyway. + assert_eq!( + gate.admit(&key, job(ScanTrigger::Webhook, "r2")), + Admission::Dropped + ); + } + + #[tokio::test] + async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() { + let gate = ScanGate::new(1); + let key = ScanGate::key("acme", "t1"); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Scheduled, "r1")), + Admission::Run + ); + let _slot = gate.start(&key).await.unwrap(); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Scheduled, "r2")), + Admission::Coalesced { replaced: None } ); - // Clicked after uploading new files: the follow-up scans in full. - assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced); - assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped); - assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped); + // Clicked after uploading new files: the follow-up scans in full, and + // the scheduled follow-up's queued run will not happen. + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r3")), + Admission::Coalesced { + replaced: Some("r2".into()) + } + ); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Webhook, "r4")), + Admission::Dropped + ); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Support, "r5")), + Admission::Dropped + ); - assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual)); + assert!(gate.finish(&key)); } #[test] fn targets_and_tenants_are_independent() { let gate = ScanGate::new(2); assert_eq!( - gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual), + gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")), Admission::Run ); assert_eq!( - gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual), + gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")), Admission::Run ); // Same target id in another tenant is another target. assert_eq!( - gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual), + gate.admit( + &ScanGate::key("globex", "t1"), + job(ScanTrigger::Manual, "c") + ), Admission::Run ); } @@ -256,99 +605,227 @@ mod tests { fn a_dead_holder_does_not_leave_the_target_locked() { let gate = ScanGate::new(1); let key = ScanGate::key("acme", "t1"); - assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r1")), + Admission::Run + ); { // The holding task ends without calling finish (panic / shutdown). let _held = HeldTarget::new(&gate, key.clone()); } - assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r2")), + Admission::Run + ); } - #[test] - fn a_disarmed_holder_leaves_the_state_to_finish() { + #[tokio::test] + async fn a_disarmed_holder_leaves_the_state_to_finish() { let gate = ScanGate::new(1); let key = ScanGate::key("acme", "t1"); - assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r1")), + Admission::Run + ); + let _slot = gate.start(&key).await.unwrap(); HeldTarget::new(&gate, key.clone()).disarm(); // Still held: disarm does not release, finish does. - assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Webhook, "r2")), + Admission::Coalesced { replaced: None } + ); } /// What `ComplianceAgent::run_target_scan` does once admitted: take a /// slot, scan (here: log), and run the pending follow-up, if any. - async fn hold_and_scan( - gate: std::sync::Arc, - key: String, - mut trigger: ScanTrigger, - log: std::sync::Arc>>, - ) { + async fn hold_and_scan(gate: Arc, key: String, log: Log) { loop { { - let _slot = gate.slot().await.unwrap(); - log.lock().unwrap().push((key.clone(), trigger.clone())); + let (_slot, job) = gate.start(&key).await.unwrap(); + log.lock().unwrap().push((key.clone(), job.trigger)); } - match gate.finish(&key) { - Some(next) => trigger = next, - None => break, + if !gate.finish(&key) { + break; } } } - #[tokio::test] - async fn a_persons_follow_up_runs_before_scheduled_scans_still_waiting() { - let gate = std::sync::Arc::new(ScanGate::new(1)); - let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - // Another tenant's scan has the only slot. - let busy = gate.slot().await.unwrap(); - - // A scheduler tick admits three targets; all wait for the slot. + /// Admit `trigger` for each of `targets` of tenant `acme`, each with a + /// task that scans it, queued in that order behind a slot held elsewhere. + async fn queue_targets( + gate: &Arc, + targets: &[&str], + trigger: ScanTrigger, + log: &Log, + ) -> Vec> { let mut tasks = Vec::new(); - for target in ["t1", "t2", "t3"] { + for target in targets { let key = ScanGate::key("acme", target); - assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run); - tasks.push(tokio::spawn(hold_and_scan( - gate.clone(), - key, - ScanTrigger::Scheduled, - log.clone(), - ))); + assert_eq!( + gate.admit(&key, job(trigger.clone(), target)), + Admission::Run + ); + tasks.push(tokio::spawn(hold_and_scan(gate.clone(), key, log.clone()))); // Let it queue for the slot before the next one does. tokio::task::yield_now().await; } + tasks + } - // A person asks for t1 while its scheduled scan still waits. - let t1 = ScanGate::key("acme", "t1"); - assert_eq!(gate.admit(&t1, ScanTrigger::Manual), Admission::Coalesced); + fn triggers(log: &Log) -> Vec { + log.lock().unwrap().iter().map(|(_, t)| t.clone()).collect() + } + + #[tokio::test] + async fn a_persons_scan_gets_the_next_slot_before_scheduled_scans() { + let gate = Arc::new(ScanGate::new(1)); + let log = Log::default(); + // Another tenant's scan has the only slot. + let busy = gate.slot(Priority::Background).await.unwrap(); + + let mut tasks = queue_targets(&gate, &["t1", "t2"], ScanTrigger::Scheduled, &log).await; + tasks.extend(queue_targets(&gate, &["t3"], ScanTrigger::Manual, &log).await); drop(busy); for task in tasks { task.await.unwrap(); } + assert_eq!( + triggers(&log), + [ + ScanTrigger::Manual, + ScanTrigger::Scheduled, + ScanTrigger::Scheduled + ] + ); + } + + #[tokio::test] + async fn a_persons_request_takes_over_a_scheduled_scan_still_waiting() { + let gate = Arc::new(ScanGate::new(1)); + let log = Log::default(); + // Another tenant's scan has the only slot. + let busy = gate.slot(Priority::Background).await.unwrap(); + + // A scheduler tick admits three targets; all wait for the slot. + let tasks = queue_targets(&gate, &["t1", "t2", "t3"], ScanTrigger::Scheduled, &log).await; + + // A person asks for t3 while its scheduled scan still waits, last. + let t3 = ScanGate::key("acme", "t3"); + assert_eq!( + gate.admit(&t3, job(ScanTrigger::Manual, "click")), + Admission::Coalesced { + replaced: Some("t3".into()) + } + ); + + drop(busy); + for task in tasks { + task.await.unwrap(); + } + // Their scan runs first, once, in place of the scheduled one. let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone(); - let manual = order + assert_eq!( + order, + [ + (t3, ScanTrigger::Manual), + (ScanGate::key("acme", "t1"), ScanTrigger::Scheduled), + (ScanGate::key("acme", "t2"), ScanTrigger::Scheduled), + ] + ); + } + + #[tokio::test] + async fn a_persons_follow_up_waits_only_for_the_running_scan() { + let gate = Arc::new(ScanGate::new(1)); + let log = Log::default(); + let t1 = ScanGate::key("acme", "t1"); + assert_eq!( + gate.admit(&t1, job(ScanTrigger::Scheduled, "t1")), + Admission::Run + ); + // t1's scheduled scan runs; two more targets queue behind it. + let (running, _) = gate.start(&t1).await.unwrap(); + let tasks = queue_targets(&gate, &["t2", "t3"], ScanTrigger::Scheduled, &log).await; + + assert_eq!( + gate.admit(&t1, job(ScanTrigger::Manual, "click")), + Admission::Coalesced { replaced: None } + ); + // t1's scan ends; its follow-up queues as a person's. + assert!(gate.finish(&t1)); + let follow_up = tokio::spawn(hold_and_scan(gate.clone(), t1.clone(), log.clone())); + tokio::task::yield_now().await; + drop(running); + follow_up.await.unwrap(); + for task in tasks { + task.await.unwrap(); + } + assert_eq!( + triggers(&log), + [ + ScanTrigger::Manual, + ScanTrigger::Scheduled, + ScanTrigger::Scheduled + ] + ); + } + + #[tokio::test] + async fn a_stream_of_clicks_does_not_starve_scheduled_scans() { + let gate = Arc::new(ScanGate::new(1)); + let log = Log::default(); + let busy = gate.slot(Priority::Background).await.unwrap(); + + let mut tasks = queue_targets(&gate, &["s1"], ScanTrigger::Scheduled, &log).await; + let clicks: Vec = (0..10).map(|i| format!("p{i}")).collect(); + let clicks: Vec<&str> = clicks.iter().map(String::as_str).collect(); + tasks.extend(queue_targets(&gate, &clicks, ScanTrigger::Manual, &log).await); + + drop(busy); + for task in tasks { + task.await.unwrap(); + } + let scheduled_at = triggers(&log) .iter() - .position(|(k, t)| *k == t1 && *t == ScanTrigger::Manual) - .expect("the person's scan runs"); - let last_scheduled = order - .iter() - .rposition(|(_, t)| *t == ScanTrigger::Scheduled) - .expect("the scheduled scans run"); + .position(|t| *t == ScanTrigger::Scheduled) + .unwrap(); + assert_eq!(scheduled_at, PERSON_GRANTS_IN_A_ROW as usize); + } + + #[tokio::test] + async fn a_given_up_request_passes_its_slot_on() { + let gate = Arc::new(ScanGate::new(1)); + let busy = gate.slot(Priority::Background).await.unwrap(); + // A request that waits and is then given up (its task ends). + let gone = tokio::spawn({ + let gate = gate.clone(); + async move { gate.slot(Priority::Person).await.map(drop) } + }); + tokio::task::yield_now().await; + gone.abort(); + let _ = gone.await; + + drop(busy); + let next = tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Background)); assert!( - manual < last_scheduled, - "the person's follow-up waited behind every scheduled scan: {order:?}" + next.await.is_ok(), + "the slot is not lost to the given-up request" ); } #[tokio::test] async fn slots_bound_how_many_scans_run_at_once() { let gate = ScanGate::new(2); - let a = gate.slot().await.unwrap(); - let _b = gate.slot().await.unwrap(); + let a = gate.slot(Priority::Background).await.unwrap(); + let _b = gate.slot(Priority::Background).await.unwrap(); // A third slot is not available until one is freed. - let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await; + let third = + tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await; assert!(third.is_err(), "a third concurrent scan must wait"); drop(a); - let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await; + let third = + tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await; assert!(third.is_ok(), "a freed slot is reused"); } } diff --git a/compliance-agent/tests/scan_queue.rs b/compliance-agent/tests/scan_queue.rs new file mode 100644 index 0000000..271ee16 --- /dev/null +++ b/compliance-agent/tests/scan_queue.rs @@ -0,0 +1,167 @@ +//! A scan request shows at once as a run waiting for a slot (t84): the run is +//! recorded `queued` before the scan gets one of the agent's slots, a person's +//! request takes over a waiting webhook scan without leaving its queued run +//! behind, a request covered by the waiting scan leaves none, and the run +//! leaves `queued` once its scan had its turn. Runs against a live Mongo +//! (`TEST_MONGODB_URI`) and skips cleanly without one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +mod common; + +use std::sync::Arc; +use std::time::Duration; + +use futures_util::TryStreamExt; +use mongodb::bson::doc; + +use compliance_agent::agent::ComplianceAgent; +use compliance_agent::database::Database; +use compliance_agent::scan_gate::Priority; +use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger}; + +use common::dev_config; + +const TENANT: &str = "scanqueue"; + +async fn runs(db: &Database, target_id: &str) -> Vec { + db.scan_runs() + .find(doc! { "repo_id": target_id }) + .await + .unwrap() + .try_collect() + .await + .unwrap() +} + +/// Wait until the runs of `target_id` satisfy `done`, and return them. +async fn until(db: &Database, target_id: &str, done: impl Fn(&[ScanRun]) -> bool) -> Vec { + for _ in 0..200 { + let found = runs(db, target_id).await; + if done(&found) { + return found; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!( + "runs never reached the expected state: {:?}", + runs(db, target_id).await + ); +} + +#[tokio::test] +async fn a_request_shows_as_queued_until_its_scan_has_a_slot() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); + let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id(TENANT).await.unwrap(); + let mut config = dev_config(uri, db_name); + config.scan_concurrency = 1; + let agent = Arc::new(ComplianceAgent::new(config, pool.clone())); + // No such target, so its scan ends at once when it gets the slot. + let target = mongodb::bson::oid::ObjectId::new().to_hex(); + + // Arrange: another scan has the only slot. + let busy = agent.scan_gate.slot(Priority::Background).await.unwrap(); + + // Act 1: a push asks for a scan; it waits, recorded as queued. + let holder = tokio::spawn({ + let (agent, target) = (agent.clone(), target.clone()); + async move { + agent + .run_target_scan(TENANT, &target, ScanTrigger::Webhook) + .await + } + }); + let queued = until(&db, &target, |r| r.len() == 1).await; + assert_eq!(queued[0].status, ScanRunStatus::Queued); + assert_eq!(queued[0].trigger, ScanTrigger::Webhook); + assert!(queued[0].queued_at.is_some()); + + // Act 2: a person asks while it waits: theirs takes its place, and only + // their queued run is left. Another push is covered and leaves none. + agent + .run_target_scan(TENANT, &target, ScanTrigger::Manual) + .await + .unwrap(); + agent + .run_target_scan(TENANT, &target, ScanTrigger::Webhook) + .await + .unwrap(); + let waiting = runs(&db, &target).await; + assert_eq!(waiting.len(), 1, "one queued run: {waiting:?}"); + assert_eq!(waiting[0].status, ScanRunStatus::Queued); + assert_eq!(waiting[0].trigger, ScanTrigger::Manual); + + // Act 3: the slot frees; the person's scan has its turn. + drop(busy); + assert!(holder.await.unwrap().is_err(), "the unknown target fails"); + + // Assert: the same run, no longer queued. + let done = runs(&db, &target).await; + assert_eq!(done.len(), 1); + assert_eq!(done[0].id, waiting[0].id); + assert_eq!(done[0].status, ScanRunStatus::Failed); + assert!(done[0].completed_at.is_some()); + + pool.drop_tenant(TENANT).await.ok(); +} + +#[tokio::test] +async fn the_scan_runs_on_the_run_that_waited() { + use compliance_core::models::{OnboardedTarget, TargetType}; + + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); + let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id(TENANT).await.unwrap(); + let mut config = dev_config(uri, db_name); + config.scan_concurrency = 1; + let agent = Arc::new(ComplianceAgent::new(config, pool.clone())); + // A target with nothing attached yet: its scan has nothing to read. + let target = db + .onboarded_targets() + .insert_one(OnboardedTarget::new( + "empty".into(), + TargetType::BackendService, + )) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap() + .to_hex(); + + let busy = agent.scan_gate.slot(Priority::Background).await.unwrap(); + let holder = tokio::spawn({ + let (agent, target) = (agent.clone(), target.clone()); + async move { + agent + .run_target_scan(TENANT, &target, ScanTrigger::Manual) + .await + } + }); + let queued = until(&db, &target, |r| r.len() == 1).await; + assert_eq!(queued[0].status, ScanRunStatus::Queued); + tokio::time::sleep(Duration::from_millis(20)).await; + + drop(busy); + holder.await.unwrap().ok(); + + // The scan used the queued run: one run, started after it was requested. + let done = runs(&db, &target).await; + assert_eq!(done.len(), 1, "{done:?}"); + assert_eq!(done[0].id, queued[0].id); + assert_ne!(done[0].status, ScanRunStatus::Queued); + assert!(done[0].started_at > done[0].queued_at.unwrap()); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 5ff9313..370045c 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -70,6 +70,9 @@ impl std::fmt::Display for ScanType { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ScanRunStatus { + /// Requested and waiting for one of the agent's scan slots (t84). Moves + /// to `running` when it gets one. + Queued, Running, Completed, /// The scan itself hit an error on the target (clone, tool, pipeline). @@ -80,6 +83,16 @@ pub enum ScanRunStatus { Interrupted, } +impl ScanRunStatus { + /// Whether the run has not ended yet: it waits for a slot or runs. + pub fn is_open(&self) -> bool { + match self { + Self::Queued | Self::Running => true, + Self::Completed | Self::Failed | Self::Interrupted => false, + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum ScanPhase { @@ -154,8 +167,18 @@ pub struct ScanRun { /// absent on runs recorded before it existed. #[serde(default)] pub error_code: Option, + /// When the run started; for a queued run, when it was requested, until + /// it starts. #[serde(with = "super::serde_helpers::bson_datetime")] pub started_at: DateTime, + /// When a run that waited for a slot was requested (t84); `None` for a + /// run that started at once, and in runs from before it was recorded. + #[serde( + default, + skip_serializing_if = "Option::is_none", + with = "super::serde_helpers::opt_bson_datetime" + )] + pub queued_at: Option>, #[serde(default, with = "super::serde_helpers::opt_bson_datetime")] pub completed_at: Option>, /// Stages the pipeline deliberately did not run (e.g. a deployment @@ -426,6 +449,7 @@ impl ScanRun { error_message: None, error_code: None, started_at: Utc::now(), + queued_at: None, completed_at: None, skipped_stages: Vec::new(), notes: Vec::new(), @@ -437,6 +461,16 @@ impl ScanRun { charge: None, } } + + /// A run requested by `trigger` that waits for a scan slot (t84). + pub fn queued(repo_id: String, trigger: ScanTrigger) -> Self { + let run = Self::new(repo_id, trigger); + Self { + status: ScanRunStatus::Queued, + queued_at: Some(run.started_at), + ..run + } + } } impl ScanRun { diff --git a/compliance-dashboard/src/components/scan_runs.rs b/compliance-dashboard/src/components/scan_runs.rs index 65103ba..0f4583b 100644 --- a/compliance-dashboard/src/components/scan_runs.rs +++ b/compliance-dashboard/src/components/scan_runs.rs @@ -108,9 +108,7 @@ pub fn ScanRunList( .peek() .as_ref() .and_then(|r| r.as_ref()) - .is_some_and(|list| { - list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running) - }); + .is_some_and(|list| list.is_empty() || list.iter().any(|r| r.status.is_open())); if waiting { runs.restart(); } @@ -161,7 +159,8 @@ fn run_transitions( let mut finished = Vec::new(); for run in runs { let id = run.id.map(|id| id.to_hex()).unwrap_or_default(); - if run.status == ScanRunStatus::Running { + // A queued run counts: it may finish before it is ever seen running. + if run.status.is_open() { running.push(id); } else if seen_running.contains(&id) && !finished_here.contains(&id) { finished.push(id); @@ -176,13 +175,20 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element { let started = format_time(&run.started_at, lang); let finished = run.completed_at.as_ref().map(|t| format_time(t, lang)); let running = run.status == ScanRunStatus::Running; + // A queued run's time is when it was asked for: it has not started. + let queued = run.status == ScanRunStatus::Queued; + let started_label = if queued { + scans::REQUESTED + } else { + scans::STARTED + }; rsx! { div { style: "border-left: 3px solid var(--border); padding: 6px 10px; margin: 6px 0;", div { style: "display: flex; gap: 12px; align-items: center; flex-wrap: wrap;", span { class: "{badge}", {status.get(lang)} } span { style: "font-size: 0.9em;", - {scans::STARTED.get(lang)} ": {started}" + {started_label.get(lang)} ": {started}" } if let Some(finished) = finished { span { style: "font-size: 0.9em;", @@ -213,6 +219,11 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element { run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(), } } + if queued { + div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;", + {scans::QUEUED_HINT.get(lang)} + } + } if run.status == ScanRunStatus::Interrupted { div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;", {scans::INTERRUPTED_HINT.get(lang)} @@ -450,6 +461,7 @@ fn RunReveal(target_id: String, run_id: String, count: u32) -> Element { /// The badge class and label for a run status. pub fn status_badge(status: &ScanRunStatus) -> (&'static str, Text) { match status { + ScanRunStatus::Queued => ("badge badge-neutral", scans::QUEUED), ScanRunStatus::Running => ("badge badge-info", scans::RUNNING), ScanRunStatus::Completed => ("badge badge-success", scans::COMPLETED), ScanRunStatus::Failed => ("badge badge-danger", scans::FAILED), @@ -542,6 +554,24 @@ mod tests { assert!(finished.is_empty()); } + #[test] + fn a_queued_run_reads_as_waiting_for_a_slot_and_is_followed_to_its_end() { + let mut run = ScanRun::queued("t".into(), compliance_core::models::ScanTrigger::Manual); + let (_, label) = status_badge(&run.status); + assert_eq!(label.get(Lang::De), "Wartet auf einen Platz"); + assert_eq!(label.get(Lang::En), "Waiting for a slot"); + + // Seen while it waits, so its end is revealed even if it is never + // seen running. + let none = HashSet::new(); + let (seen, _) = run_transitions(std::slice::from_ref(&run), &none, &none); + assert_eq!(seen, vec![String::new()]); + run.status = ScanRunStatus::Completed; + let seen = HashSet::from([String::new()]); + let (_, finished) = run_transitions(std::slice::from_ref(&run), &seen, &none); + assert_eq!(finished, vec![String::new()]); + } + #[test] fn the_stepper_marks_done_current_and_pending_phases() { let mut run = ScanRun::new("t".into(), compliance_core::models::ScanTrigger::Manual); diff --git a/compliance-dashboard/src/i18n/texts.rs b/compliance-dashboard/src/i18n/texts.rs index c0238aa..49c71a1 100644 --- a/compliance-dashboard/src/i18n/texts.rs +++ b/compliance-dashboard/src/i18n/texts.rs @@ -367,6 +367,19 @@ pub mod scans { de: "Noch nicht geprüft", en: "Not scanned yet", }; + pub const QUEUED: Text = Text { + de: "Wartet auf einen Platz", + en: "Waiting for a slot", + }; + pub const QUEUED_HINT: Text = Text { + de: "Alle Prüfplätze sind gerade belegt. Die Prüfung startet, sobald einer \ + frei wird.", + en: "All scan slots are busy right now. The scan starts as soon as one is free.", + }; + pub const REQUESTED: Text = Text { + de: "Angefordert", + en: "Requested", + }; pub const RUNNING: Text = Text { de: "Läuft", en: "Running", diff --git a/compliance-dashboard/src/infrastructure/onboarding.rs b/compliance-dashboard/src/infrastructure/onboarding.rs index f6f3bd9..1081d8f 100644 --- a/compliance-dashboard/src/infrastructure/onboarding.rs +++ b/compliance-dashboard/src/infrastructure/onboarding.rs @@ -113,11 +113,15 @@ pub async fn set_archive_password( } /// Whether any of `targets` (as the list endpoint returns them) has a scan -/// running, so a page showing them should keep refreshing. +/// running or waiting for a slot, so a page showing them should keep +/// refreshing. pub fn any_scan_running(targets: &[serde_json::Value]) -> bool { - targets - .iter() - .any(|t| t["last_scan"]["status"].as_str() == Some("running")) + targets.iter().any(|t| { + matches!( + t["last_scan"]["status"].as_str(), + Some("running" | "queued") + ) + }) } #[derive(Debug, Clone, Serialize, Deserialize, Default)] @@ -713,8 +717,10 @@ mod tests { let idle = serde_json::json!({ "last_scan": { "status": "completed" } }); let fresh = serde_json::json!({ "last_scan": null }); let busy = serde_json::json!({ "last_scan": { "status": "running" } }); + let queued = serde_json::json!({ "last_scan": { "status": "queued" } }); assert!(!any_scan_running(&[idle.clone(), fresh.clone()])); - assert!(any_scan_running(&[idle, fresh, busy])); + assert!(any_scan_running(&[idle.clone(), fresh, busy])); + assert!(any_scan_running(&[idle, queued])); } #[test] -- 2.54.1 From 9d79bac004c77c96ea005e84291851b4629835c8 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 7 Nov 2026 23:36:41 +0100 Subject: [PATCH 3/3] fix(scan): a taken-over waiting scan is charged as the scan it replaces (t84) When a person's request takes over a scheduled, webhook or new-content scan that still waits for a slot, the run keeps the person's priority and attribution (the history shows that a person asked), but it counts only as the scan it replaced would have: that scan would have run anyway, the customer only gets it sooner. Change detection decides, as for that trigger, so on an included target it is not charged. A person's follow-up after a running scan is a new run and is charged as their request, as before. The run records the trigger it is charged as in `charged_as`. Co-Authored-By: Claude Opus 5.5 --- compliance-agent/src/agent.rs | 18 ++-- compliance-agent/src/pipeline/orchestrator.rs | 99 ++++++++++++++++--- compliance-agent/src/scan_gate.rs | 65 +++++++++++- compliance-agent/tests/scan_queue.rs | 83 ++++++++++++++++ compliance-core/src/models/scan.rs | 7 ++ 5 files changed, 247 insertions(+), 25 deletions(-) diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 247733d..5fc8764 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -331,14 +331,11 @@ impl ComplianceAgent { .start(&key) .await .map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?; - let job_run = job.run_id; - let outcome = self - .run_one_target_scan(tenant_id, target_id, job.trigger, job_run.as_deref()) - .await; + let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await; drop(slot); if let Err(e) = &outcome { tracing::error!(tenant_id, target_id, "scan failed: {e}"); - fail_queued_run(&db, job_run.as_deref(), e).await; + fail_queued_run(&db, job.run_id.as_deref(), e).await; } if !self.scan_gate.finish(&key) { break outcome; @@ -349,14 +346,14 @@ impl ComplianceAgent { } /// One scan of a target, with no gating: the pipeline plus its usage event, - /// recorded on the run `queued` that waited for it. + /// recorded on the run that waited for it and charged as `job` says. async fn run_one_target_scan( &self, tenant_id: &str, target_id: &str, - trigger: compliance_core::models::ScanTrigger, - queued: Option<&str>, + job: &Job, ) -> Result<(), crate::error::AgentError> { + let trigger = job.trigger.clone(); let db = self.db_pool.for_tenant_id(tenant_id).await?; // Whether this target is included or extra decides whether its scan // counts, and the plan's limits whether a counted one may run (t72). @@ -370,10 +367,11 @@ impl ComplianceAgent { .with_nuget_license_cache(self.nuget_license_cache.clone()) .with_exploit_cache(self.exploit_cache.clone()) .with_advisory_index(self.advisory_index.clone()) - .with_plan_limits(plan.map(|p| p.limits)); + .with_plan_limits(plan.map(|p| p.limits)) + .with_charged_as(job.charged_as.clone()); let started = chrono::Utc::now(); let outcome = orchestrator - .run_target(target_id, trigger.clone(), queued) + .run_target(target_id, trigger.clone(), job.run_id.as_deref()) .await?; // Support's scans are ours, not the customer's usage; a scheduled scan // skipped because nothing changed scanned nothing (#465). diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 4d79039..7971e9b 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -82,6 +82,10 @@ pub struct PipelineOrchestrator { /// The tenant's plan limits for metering (t72); `None` when not known, /// and then counted Prüfungen are neither checked nor charged. pub(super) plan_limits: Option, + /// Set when this person's scan took over a waiting scheduled, webhook or + /// new-content scan (t84): the trigger it is charged as. Change detection + /// then decides whether it counts, as for that scan. + pub(super) charged_as: Option, } impl PipelineOrchestrator { @@ -99,9 +103,17 @@ impl PipelineOrchestrator { exploit_cache: None, advisory_index: None, plan_limits: None, + charged_as: None, } } + /// Charge this run as a scan started by `trigger` would be, when a + /// person's request took that waiting scan over (t84). + pub(crate) fn with_charged_as(mut self, trigger: Option) -> Self { + self.charged_as = trigger; + self + } + /// Check and charge counted Prüfungen against `limits` (t72). pub(crate) fn with_plan_limits(mut self, limits: Option) -> Self { self.plan_limits = limits; @@ -227,6 +239,16 @@ impl PipelineOrchestrator { repo.billing, ) .await?; + } else if let Some(original) = &self.charged_as { + let new_commits = + GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?; + self.charge_as_taken_over( + scan_run_id, + &repo_id, + ScanAttribution::detected(original, new_commits || repo.changed_besides_commits), + repo.billing, + ) + .await?; } // Submodules are part of what the product ships (a HAL, an RTOS). @@ -1192,8 +1214,12 @@ impl PipelineOrchestrator { // detection attributes the others (t72). if let Some(attribution) = ScanAttribution::of_person(&trigger) { scan_run.attribution = Some(attribution); - scan_run.chargeable = attribution.chargeable(target.billing); + // One that took over a waiting scan counts only as that scan + // would have; change detection decides below (t84). + scan_run.chargeable = + self.charged_as.is_none() && attribution.chargeable(target.billing); } + scan_run.charged_as = self.charged_as.clone(); let run_oid = self.start_run(&scan_run, queued).await?; let scan_run_id = run_oid.to_hex(); let run_id = mongodb::bson::Bson::ObjectId(run_oid); @@ -1351,6 +1377,13 @@ impl PipelineOrchestrator { "started_at": mongodb::bson::DateTime::from_chrono(run.started_at), "chargeable": run.chargeable, }; + if let Some(charged_as) = &run.charged_as { + started.insert( + "charged_as", + mongodb::bson::to_bson(charged_as) + .map_err(|e| AgentError::Other(e.to_string()))?, + ); + } if let Some(attribution) = run.attribution { started.insert( "attribution", @@ -1475,6 +1508,40 @@ impl PipelineOrchestrator { Ok(()) } + /// Count the run `scan_run_id`, a person's request that took over a + /// waiting scan, only when `detected` (that scan's attribution from change + /// detection) counts on a target billed as `billing`, and then check it + /// against the plan (t84). The run keeps the person's attribution, so its + /// history shows that a person asked. Several code artifacts: a change in + /// any of them counts it, as in [`Self::attribute_run`]. + /// + /// # Errors + /// + /// [`AgentError::NotAdmitted`] when the plan does not allow a counted + /// Prüfung now. + async fn charge_as_taken_over( + &self, + scan_run_id: &str, + target_id: &str, + detected: ScanAttribution, + billing: TargetBilling, + ) -> Result<(), AgentError> { + if !detected.chargeable(billing) { + return Ok(()); + } + if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) { + if let Err(e) = self + .db + .scan_runs() + .update_one(doc! { "_id": oid }, doc! { "$set": { "chargeable": true } }) + .await + { + tracing::warn!(scan_run_id, "scan run not marked as counted: {e}"); + } + } + self.admit_run(scan_run_id, target_id).await + } + /// Store `attribution` and `chargeable` on the run, unless it already /// reads as a change. async fn record_attribution( @@ -1549,17 +1616,25 @@ impl PipelineOrchestrator { return Ok(0); } // A git target is attributed where its commits are compared. - if !trigger.started_by_person() && !has_git { - self.attribute_run( - scan_run_id, - &target_id, - ScanAttribution::detected( - trigger, - crate::pipeline::change::content_changed(target), - ), - target.billing, - ) - .await?; + if !has_git { + let changed = crate::pipeline::change::content_changed(target); + if !trigger.started_by_person() { + self.attribute_run( + scan_run_id, + &target_id, + ScanAttribution::detected(trigger, changed), + target.billing, + ) + .await?; + } else if let Some(original) = &self.charged_as { + self.charge_as_taken_over( + scan_run_id, + &target_id, + ScanAttribution::detected(original, changed), + target.billing, + ) + .await?; + } } let plan = build_scan_plan(target); // An attached artifact nothing analyses is recorded, never passed over: diff --git a/compliance-agent/src/scan_gate.rs b/compliance-agent/src/scan_gate.rs index 0cb74be..36dc3d4 100644 --- a/compliance-agent/src/scan_gate.rs +++ b/compliance-agent/src/scan_gate.rs @@ -89,12 +89,19 @@ impl Priority { pub struct Job { pub trigger: ScanTrigger, pub run_id: Option, + /// Set when a person's request took over a waiting scan that was not a + /// person's: that scan's trigger, which the run is charged as (t84). + pub charged_as: Option, } impl Job { /// A scan started by `trigger`, recorded as the run `run_id`. pub fn new(trigger: ScanTrigger, run_id: Option) -> Self { - Self { trigger, run_id } + Self { + trigger, + run_id, + charged_as: None, + } } fn priority(&self) -> Priority { @@ -191,10 +198,15 @@ impl ScanGate { if !held.running { // The waiting scan reads the latest code once it starts, // so it covers the request, or the person's takes its - // place, at person priority. + // place, at person priority. It would have run anyway, + // so it is charged as the scan it replaces. if !takes_over(&held.current) { return Admission::Dropped; } + let job = Job { + charged_as: Some(held.current.trigger.clone()), + ..job + }; let replaced = std::mem::replace(&mut held.current, job).run_id; self.slots.promote(key); return Admission::Coalesced { replaced }; @@ -546,6 +558,52 @@ mod tests { ); } + #[tokio::test] + async fn a_waiting_scan_taken_over_is_charged_as_the_scan_it_replaces() { + let gate = ScanGate::new(1); + let key = ScanGate::key("acme", "t1"); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Webhook, "r1")), + Admission::Run + ); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r2")), + Admission::Coalesced { + replaced: Some("r1".into()) + } + ); + let (_slot, run) = gate.start(&key).await.unwrap(); + assert_eq!(run.trigger, ScanTrigger::Manual); + assert_eq!(run.charged_as, Some(ScanTrigger::Webhook)); + } + + #[tokio::test] + async fn a_persons_follow_up_after_a_running_scan_is_charged_as_theirs() { + let gate = ScanGate::new(1); + let key = ScanGate::key("acme", "t1"); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Scheduled, "r1")), + Admission::Run + ); + let (running, _) = gate.start(&key).await.unwrap(); + // Pending behind the running scan, replacing a scheduled follow-up. + assert_eq!( + gate.admit(&key, job(ScanTrigger::Scheduled, "r2")), + Admission::Coalesced { replaced: None } + ); + assert_eq!( + gate.admit(&key, job(ScanTrigger::Manual, "r3")), + Admission::Coalesced { + replaced: Some("r2".into()) + } + ); + drop(running); + assert!(gate.finish(&key)); + let (_slot, follow_up) = gate.start(&key).await.unwrap(); + assert_eq!(follow_up, job(ScanTrigger::Manual, "r3")); + assert_eq!(follow_up.charged_as, None); + } + #[tokio::test] async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() { let gate = ScanGate::new(1); @@ -723,7 +781,8 @@ mod tests { for task in tasks { task.await.unwrap(); } - // Their scan runs first, once, in place of the scheduled one. + // Their scan runs first, once, in place of the scheduled one, and + // is charged as the scheduled one (asserted on the job below). let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone(); assert_eq!( order, diff --git a/compliance-agent/tests/scan_queue.rs b/compliance-agent/tests/scan_queue.rs index 271ee16..882d60c 100644 --- a/compliance-agent/tests/scan_queue.rs +++ b/compliance-agent/tests/scan_queue.rs @@ -165,3 +165,86 @@ async fn the_scan_runs_on_the_run_that_waited() { pool.drop_tenant(TENANT).await.ok(); } + +/// The run of `target`'s scan by `trigger`, started while another scan has the +/// only slot; with `takes_over`, a webhook scan waits first and the person's +/// request takes it over. +async fn scan_with_slot_busy( + agent: &Arc, + db: &Database, + target: &str, + takes_over: bool, +) -> ScanRun { + let busy = agent.scan_gate.slot(Priority::Background).await.unwrap(); + let first = if takes_over { + ScanTrigger::Webhook + } else { + ScanTrigger::Manual + }; + let holder = tokio::spawn({ + let (agent, target) = (agent.clone(), target.to_string()); + async move { agent.run_target_scan(TENANT, &target, first).await } + }); + until(db, target, |r| r.len() == 1).await; + if takes_over { + agent + .run_target_scan(TENANT, target, ScanTrigger::Manual) + .await + .unwrap(); + } + drop(busy); + holder.await.unwrap().ok(); + let mut done = runs(db, target).await; + assert_eq!(done.len(), 1, "{done:?}"); + done.remove(0) +} + +#[tokio::test] +async fn a_taken_over_scan_is_charged_as_the_scan_it_replaces() { + use compliance_core::models::{OnboardedTarget, ScanAttribution, TargetType}; + + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]); + let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else { + eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id(TENANT).await.unwrap(); + let mut config = dev_config(uri, db_name); + config.scan_concurrency = 1; + let agent = Arc::new(ComplianceAgent::new(config, pool.clone())); + let new_target = || { + let db = db.clone(); + async move { + let target = OnboardedTarget::new("t".into(), TargetType::BackendService); + db.onboarded_targets() + .insert_one(target) + .await + .unwrap() + .inserted_id + .as_object_id() + .unwrap() + .to_hex() + } + }; + + // A person's request that took over a waiting webhook scan of an + // included target: their priority and attribution, but not counted, as + // the webhook scan would not have been. + let included = new_target().await; + let run = scan_with_slot_busy(&agent, &db, &included, true).await; + assert_eq!(run.trigger, ScanTrigger::Manual); + assert_eq!(run.attribution, Some(ScanAttribution::Request)); + assert_eq!(run.charged_as, Some(ScanTrigger::Webhook)); + assert!(!run.chargeable, "it would have run anyway: {run:?}"); + + // A person's own scan, not taking any over, counts as their request. + let asked = new_target().await; + let run = scan_with_slot_busy(&agent, &db, &asked, false).await; + assert_eq!(run.attribution, Some(ScanAttribution::Request)); + assert_eq!(run.charged_as, None); + assert!(run.chargeable); + + pool.drop_tenant(TENANT).await.ok(); +} diff --git a/compliance-core/src/models/scan.rs b/compliance-core/src/models/scan.rs index 370045c..4cc6de2 100644 --- a/compliance-core/src/models/scan.rs +++ b/compliance-core/src/models/scan.rs @@ -217,6 +217,12 @@ pub struct ScanRun { /// billing when it was attributed). #[serde(default)] pub chargeable: bool, + /// For a person's request that took over a scheduled, webhook or + /// new-content scan still waiting for a slot (t84): that scan's trigger. + /// The run has the person's priority and attribution, but it counts only + /// as that scan would have: it would have run anyway, just later. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub charged_as: Option, /// What the run was charged to once it counted; `None` while it runs, /// and for a run that did not count. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -458,6 +464,7 @@ impl ScanRun { sbom_quality: None, attribution: None, chargeable: false, + charged_as: None, charge: None, } } -- 2.54.1