feat(lifecycle): scans interrupted by an agent restart start again
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 / Check (pull_request) Successful in 8m18s
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 / Check (pull_request) Successful in 8m18s
A redeploy or restart closes the scans it cut off as `interrupted` (#65), and nothing started them again: on prod the reconciler's redeploy interrupted two customer scans that then waited for the nightly run. After recover_orphaned_runs, resume_interrupted_scans starts those scans again in the background, for every tenant the scheduler runs for (so a suspended tenant is not), through the normal scan path (scan gate, concurrency), as a scheduled scan. It finds them by the completed_at this startup gave them. A target that is archived or gone is skipped, and so is one whose scan was already interrupted within the last day: the scan itself may be what stops the agent, and restarting it would loop. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
1 parent
96da28dd3f
commit
c05326e15f
3 files changed
+192
-4
No files matched your search
@@ -3,7 +3,8 @@
|
||||
//! 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. [`run_werkbank_sweeper`] returns Werkbank jobs whose
|
||||
//! 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
|
||||
@@ -136,6 +137,123 @@ async fn close_open_runs(db: &Database, now: DateTime<Utc>) -> Result<u64, Agent
|
||||
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 in targets {
|
||||
tracing::info!(
|
||||
tenant_id,
|
||||
target_id,
|
||||
"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,
|
||||
compliance_core::models::ScanTrigger::Scheduled,
|
||||
)
|
||||
.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>, 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()) {
|
||||
let interruptions = db
|
||||
.scan_runs()
|
||||
.count_documents(doc! {
|
||||
"repo_id": id,
|
||||
"status": "interrupted",
|
||||
"completed_at": { "$gte": window },
|
||||
})
|
||||
.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 {
|
||||
out.push(id.to_string());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Sweep expired Werkbank leases in every tenant (see
|
||||
/// [`JobQueue::sweep_expired`]). A tenant whose sweep fails is logged and
|
||||
/// skipped.
|
||||
@@ -209,6 +327,67 @@ mod tests {
|
||||
.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, ScanTrigger, 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.
|
||||
for id in [&resumes, &looping, &archived] {
|
||||
db.scan_runs()
|
||||
.insert_one(ScanRun::new(id.clone(), ScanTrigger::Scheduled))
|
||||
.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.
|
||||
assert_eq!(resumed, [resumes]);
|
||||
|
||||
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
|
||||
|
||||
@@ -30,9 +30,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
// Before anything can start a new run, close the runs the previous agent
|
||||
// process left open when it stopped.
|
||||
match lifecycle::recover_orphaned_runs(&agent.db_pool, chrono::Utc::now()).await {
|
||||
let started_at = chrono::Utc::now();
|
||||
match lifecycle::recover_orphaned_runs(&agent.db_pool, started_at).await {
|
||||
Ok(0) => {}
|
||||
Ok(closed) => tracing::warn!(closed, "closed runs left open by the previous agent"),
|
||||
Ok(closed) => {
|
||||
tracing::warn!(closed, "closed runs left open by the previous agent");
|
||||
// The code scans among them start again, in the background.
|
||||
let resume_agent = agent.clone();
|
||||
tokio::spawn(async move {
|
||||
let resumed = lifecycle::resume_interrupted_scans(&resume_agent, started_at).await;
|
||||
tracing::info!(resumed, "scans interrupted by the restart started again");
|
||||
});
|
||||
}
|
||||
Err(e) => tracing::error!("closing runs left open by the previous agent failed: {e}"),
|
||||
}
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ pub async fn start_scheduler(agent: &ComplianceAgent) -> Result<(), AgentError>
|
||||
///
|
||||
/// We never panic out of this function — the scheduler must keep
|
||||
/// firing even if the registry is offline.
|
||||
async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
|
||||
pub(crate) async fn scheduler_tenants(agent: &ComplianceAgent) -> Vec<String> {
|
||||
if let Some(registry) = agent.registry.as_ref() {
|
||||
match registry.list_tenants().await {
|
||||
Ok(rows) => {
|
||||
|
||||
Reference in new issue
Block a user