Files
pruefwerk/compliance-agent/src/lifecycle.rs
T
sharangandClaude Opus 5.5 d3c8eee393
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m47s
CI / Deploy Dashboard (push) Successful in 6m1s
CI / Deploy Agent (push) Successful in 8m15s
fix(scan): a person's scan gets the next slot and shows as queued (t84) (#940)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 07:52:24 +00:00

471 lines
17 KiB
Rust

//! Keeps work from staying stuck across an agent restart (#65).
//!
//! A redeploy, crash or out-of-memory kill ends every scan the agent was
//! running without anything recording it, so the run stays `running` forever.
//! [`recover_orphaned_runs`] closes those records once at startup, before
//! anything new can start; [`resume_interrupted_scans`] then starts those
//! code scans again. [`run_werkbank_sweeper`] returns Werkbank jobs whose
//! runner stopped heartbeating to the queue.
//!
//! Both assume one agent per environment, which is how every Orca deployment
//! runs today. With two replicas, one agent's startup would close runs the
//! other is still working on.
use std::time::Duration;
use chrono::{DateTime, Utc};
use mongodb::bson::{doc, DateTime as BsonDateTime};
use tokio::time::MissedTickBehavior;
use compliance_core::models::{RunErrorCode, ScanTrigger};
use compliance_core::shutdown::Shutdown;
use crate::database::{Database, DatabasePool};
use crate::error::AgentError;
use crate::werkbank::{JobQueue, SweepOutcome};
/// Recorded as `error_message` on every run closed at startup.
pub const INTERRUPTED_MESSAGE: &str = "interrupted by agent restart";
/// How often expired Werkbank leases are swept.
pub const WERKBANK_SWEEP_INTERVAL: Duration = Duration::from_secs(60);
/// A job whose lease has expired this many times is marked `expired` instead
/// of being queued again, so a job that keeps killing its runner stops.
pub const WERKBANK_MAX_ATTEMPTS: u32 = 3;
/// A kind of run record a stopped agent can leave open, and how it is closed.
struct OrphanRule {
collection: &'static str,
/// Statuses that only a live agent process ever moves on from.
open: &'static [&'static str],
closed_as: &'static str,
}
/// Code scans are what customers see, so they get their own `interrupted`
/// 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: &["queued", "running"],
closed_as: "interrupted",
},
OrphanRule {
collection: "graph_builds",
open: &["running"],
closed_as: "failed",
},
OrphanRule {
collection: "embedding_builds",
open: &["running"],
closed_as: "failed",
},
OrphanRule {
collection: "dast_scan_runs",
open: &["running"],
closed_as: "failed",
},
OrphanRule {
collection: "pentest_sessions",
open: &["running", "paused"],
closed_as: "failed",
},
];
/// Close every run a previous agent process left open, in every tenant.
///
/// Call once at startup, before the scheduler and servers start, so no run
/// this process creates can be caught. A tenant whose update fails is logged
/// and skipped, so one bad database cannot leave the others' runs open.
///
/// # Returns
///
/// How many records were closed across all tenants.
///
/// # Errors
///
/// Returns an error only if the tenant databases cannot be listed.
pub async fn recover_orphaned_runs(
pool: &DatabasePool,
now: DateTime<Utc>,
) -> Result<u64, AgentError> {
let mut closed = 0;
for db in pool.existing_tenant_dbs().await? {
match close_open_runs(&db, now).await {
Ok(count) => closed += count,
Err(e) => tracing::error!(
database = db.inner().name(),
"closing runs left open by the previous agent failed: {e}"
),
}
}
Ok(closed)
}
/// Apply every [`ORPHAN_RULES`] entry to one tenant database.
async fn close_open_runs(db: &Database, now: DateTime<Utc>) -> Result<u64, AgentError> {
let completed_at = BsonDateTime::from_chrono(now);
let mut closed = 0;
for rule in &ORPHAN_RULES {
let result = db
.raw_collection(rule.collection)
.update_many(
doc! { "status": { "$in": rule.open.to_vec() } },
doc! { "$set": {
"status": rule.closed_as,
"error_message": INTERRUPTED_MESSAGE,
"error_code": mongodb::bson::to_bson(&RunErrorCode::Interrupted)
.unwrap_or_default(),
"completed_at": completed_at,
} },
)
.await?;
if result.modified_count > 0 {
tracing::warn!(
database = db.inner().name(),
collection = rule.collection,
count = result.modified_count,
status = rule.closed_as,
"closed runs left open by the previous agent process"
);
}
closed += result.modified_count;
}
Ok(closed)
}
/// A target whose scan was interrupted this many times within
/// [`RESUME_WINDOW_HOURS`] is not started again: the scan itself may be what
/// stops the agent (out of memory, a crash), and restarting it would loop.
const MAX_RECENT_INTERRUPTIONS: u64 = 1;
/// The window [`MAX_RECENT_INTERRUPTIONS`] counts in.
const RESUME_WINDOW_HOURS: i64 = 24;
/// Start again the code scans [`recover_orphaned_runs`] closed at `closed_at`
/// (this startup), in every tenant the scheduler runs for, through the normal
/// scan path (scan gate, concurrency). A target that is archived or gone, or
/// whose scans were already interrupted before within the last day, is left
/// for the next scheduled run.
///
/// # Arguments
///
/// * `agent` - the agent, cloned for the background scans
/// * `closed_at` - the time `recover_orphaned_runs` was given
///
/// # Returns
///
/// How many scans were started again.
pub async fn resume_interrupted_scans(
agent: &crate::agent::ComplianceAgent,
closed_at: DateTime<Utc>,
) -> usize {
let mut resumed = 0;
for tenant_id in crate::scheduler::scheduler_tenants(agent).await {
let db = match agent.db_pool.for_tenant_id(&tenant_id).await {
Ok(db) => db,
Err(e) => {
tracing::warn!(tenant_id, "resume: cannot open tenant database: {e}");
continue;
}
};
let targets = match targets_to_resume(&db, closed_at).await {
Ok(targets) => targets,
Err(e) => {
tracing::warn!(tenant_id, "resume: cannot read interrupted scans: {e}");
continue;
}
};
for (target_id, trigger) in targets {
tracing::info!(
tenant_id,
target_id,
?trigger,
"starting a scan interrupted by the restart again"
);
let agent = agent.clone();
let tenant = tenant_id.clone();
tokio::spawn(async move {
if let Err(e) = agent.run_target_scan(&tenant, &target_id, trigger).await {
tracing::warn!(tenant_id = tenant, target_id, "resumed scan failed: {e}");
}
});
resumed += 1;
}
}
resumed
}
/// The targets in `db` whose scan was closed as interrupted at `closed_at`,
/// still active, and not interrupted more than [`MAX_RECENT_INTERRUPTIONS`]
/// times within [`RESUME_WINDOW_HOURS`].
async fn targets_to_resume(
db: &Database,
closed_at: DateTime<Utc>,
) -> Result<Vec<(String, ScanTrigger)>, AgentError> {
let closed = BsonDateTime::from_chrono(closed_at);
let window =
BsonDateTime::from_chrono(closed_at - chrono::Duration::hours(RESUME_WINDOW_HOURS));
let ids = db
.scan_runs()
.distinct(
"repo_id",
doc! { "status": "interrupted", "completed_at": closed },
)
.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 {
tracing::warn!(
target_id = id,
interruptions,
"not resuming a scan interrupted again within a day; the next scheduled run tries"
);
continue;
}
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(id) else {
continue;
};
let active = db
.onboarded_targets()
.count_documents(doc! { "_id": oid, "archived_at": { "$exists": false } })
.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). Of a running
// scan and its queued follow-up, a person's wins.
let triggers = db
.scan_runs()
.distinct(
"trigger",
doc! { "repo_id": id, "status": "interrupted", "completed_at": closed },
)
.await?;
let triggers: Vec<ScanTrigger> = 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));
}
}
Ok(out)
}
/// Sweep expired Werkbank leases in every tenant (see
/// [`JobQueue::sweep_expired`]). A tenant whose sweep fails is logged and
/// skipped.
///
/// # Errors
///
/// Returns an error only if the tenant databases cannot be listed.
pub async fn sweep_werkbank_leases(
pool: &DatabasePool,
now: DateTime<Utc>,
max_attempts: u32,
) -> Result<SweepOutcome, AgentError> {
let mut total = SweepOutcome::default();
for db in pool.existing_tenant_dbs().await? {
match JobQueue::new(&db).sweep_expired(now, max_attempts).await {
Ok(outcome) => {
total.requeued += outcome.requeued;
total.expired += outcome.expired;
}
Err(e) => tracing::error!(
database = db.inner().name(),
"Werkbank lease sweep failed: {e}"
),
}
}
Ok(total)
}
/// Sweep expired Werkbank leases every [`WERKBANK_SWEEP_INTERVAL`] until
/// `shutdown` fires. The first sweep runs immediately, which also picks up
/// leases that expired while the agent was down.
pub async fn run_werkbank_sweeper(pool: DatabasePool, shutdown: Shutdown) {
let mut ticks = tokio::time::interval(WERKBANK_SWEEP_INTERVAL);
// After a stall, wait a full interval rather than sweeping in a burst.
ticks.set_missed_tick_behavior(MissedTickBehavior::Delay);
let stop = shutdown.wait();
// `select!` polls this one future again on every loop turn, which Rust
// only allows once the future is pinned (fixed at one memory address).
tokio::pin!(stop);
loop {
tokio::select! {
() = &mut stop => return,
_ = ticks.tick() => {}
}
match sweep_werkbank_leases(&pool, Utc::now(), WERKBANK_MAX_ATTEMPTS).await {
Ok(outcome) if outcome != SweepOutcome::default() => tracing::info!(
requeued = outcome.requeued,
expired = outcome.expired,
"swept expired Werkbank leases"
),
Ok(_) => {}
Err(e) => tracing::error!("Werkbank lease sweep failed: {e}"),
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
use compliance_core::models::dast::DastScanStatus;
use compliance_core::models::embedding::EmbeddingBuildStatus;
use compliance_core::models::graph::GraphBuildStatus;
use compliance_core::models::pentest::PentestStatus;
use compliance_core::models::ScanRunStatus;
/// Parse a status literal the way Mongo documents are read back.
fn parse<T: serde::de::DeserializeOwned>(status: &str) -> T {
serde_json::from_value(serde_json::Value::String(status.to_string()))
.expect("status literal matches the enum's serde name")
}
#[tokio::test]
async fn only_scans_this_start_interrupted_are_resumed_once() {
use compliance_core::models::{OnboardedTarget, ScanRun, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"resume_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP resume: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id("resume").await.unwrap();
let now = Utc::now();
let target = |name: &str| OnboardedTarget::new(name.into(), TargetType::BackendService);
let insert = |t: OnboardedTarget| {
let db = db.clone();
async move {
db.onboarded_targets()
.insert_one(t)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex()
}
};
let resumes = insert(target("resumes")).await;
let looping = insert(target("looping")).await;
let mut archived_target = target("archived");
archived_target.archived_at = Some(now);
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
// 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::Scheduled),
(&looping, ScanTrigger::Scheduled),
(&archived, ScanTrigger::Scheduled),
] {
db.scan_runs()
.insert_one(ScanRun::new(id.clone(), trigger))
.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;
run.completed_at = Some(now - chrono::Duration::hours(1));
db.scan_runs().insert_one(run).await.unwrap();
}
// Act: this start closes the open runs.
close_open_runs(&db, now).await.unwrap();
let resumed = targets_to_resume(&db, now).await.unwrap();
// Assert: only the target interrupted once, by this start, and active,
// resumed as a person's scan, so it runs even if nothing changed.
assert_eq!(resumed, [(resumes, ScanTrigger::Manual)]);
pool.drop_tenant("resume").await.ok();
}
#[test]
fn rule_statuses_match_the_model_enums() {
// The rules use literals so they can be a `const`; this keeps them in
// step with the serde names of the enums the models read back.
for rule in &ORPHAN_RULES {
for status in rule.open.iter().chain([&rule.closed_as]) {
match rule.collection {
"scan_runs" => {
parse::<ScanRunStatus>(status);
}
"graph_builds" => {
parse::<GraphBuildStatus>(status);
}
"embedding_builds" => {
parse::<EmbeddingBuildStatus>(status);
}
"dast_scan_runs" => {
parse::<DastScanStatus>(status);
}
"pentest_sessions" => {
parse::<PentestStatus>(status);
}
other => panic!("no status enum registered for {other}"),
}
}
}
}
#[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
.iter()
.find(|r| r.collection == "scan_runs")
.expect("scan_runs rule");
assert_eq!(
parse::<ScanRunStatus>(scan_rule.closed_as),
ScanRunStatus::Interrupted
);
}
}