fix(scan): a taken-over waiting scan is charged as the scan it replaces (t84)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m58s
CI / Check (pull_request) Successful in 19m58s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 5m58s
CI / Check (pull_request) Successful in 19m58s
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
eac393613f
commit
9d79bac004
5 files changed
+247
-25
No files matched your search
@@ -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).
|
||||
|
||||
@@ -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<PlanLimits>,
|
||||
/// 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<ScanTrigger>,
|
||||
}
|
||||
|
||||
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<ScanTrigger>) -> 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<PlanLimits>) -> 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:
|
||||
|
||||
@@ -89,12 +89,19 @@ impl Priority {
|
||||
pub struct Job {
|
||||
pub trigger: ScanTrigger,
|
||||
pub run_id: Option<String>,
|
||||
/// 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<ScanTrigger>,
|
||||
}
|
||||
|
||||
impl Job {
|
||||
/// A scan started by `trigger`, recorded as the run `run_id`.
|
||||
pub fn new(trigger: ScanTrigger, run_id: Option<String>) -> 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,
|
||||
|
||||
@@ -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<ComplianceAgent>,
|
||||
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();
|
||||
}
|
||||
@@ -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<ScanTrigger>,
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user