From 9579bf44d517471fd51e4637fc178f33e5f1c6ee Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:11:34 +0200 Subject: [PATCH 1/2] fix(scheduler): scheduled scans are spread out and at most two clones run per git host A scheduled scan now starts after a random delay of up to 30 s (SCHEDULED_SCAN_JITTER), applied in run_target_scan before the target and a scan slot are taken; webhook, manual and support scans start at once. Every clone or fetch takes one of two slots of its git host (pipeline/clone_limit.rs, process-wide), held only around clone_or_fetch, so a tenant's scans no longer all hit one self-hosted Gitea together, while another host's clones go ahead. The global scan semaphore stays. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/agent.rs | 14 +- compliance-agent/src/pipeline/clone_limit.rs | 141 +++++++++++++++++++ compliance-agent/src/pipeline/git.rs | 5 + compliance-agent/src/pipeline/mod.rs | 1 + compliance-agent/src/scan_gate.rs | 43 +++++- 5 files changed, 202 insertions(+), 2 deletions(-) create mode 100644 compliance-agent/src/pipeline/clone_limit.rs diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index ef674c2..97eed9c 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -146,7 +146,8 @@ 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. Every trigger + /// 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. /// /// # Errors @@ -158,6 +159,17 @@ impl ComplianceAgent { target_id: &str, trigger: compliance_core::models::ScanTrigger, ) -> Result<(), crate::error::AgentError> { + // Scheduled scans spread out before they take a slot or the target. + let delay = crate::scan_gate::start_delay(&trigger); + if !delay.is_zero() { + tracing::debug!( + tenant_id, + target_id, + delay_ms = delay.as_millis(), + "scheduled scan waits" + ); + tokio::time::sleep(delay).await; + } let key = ScanGate::key(tenant_id, target_id); match self.scan_gate.admit(&key, trigger.clone()) { Admission::Run => {} diff --git a/compliance-agent/src/pipeline/clone_limit.rs b/compliance-agent/src/pipeline/clone_limit.rs new file mode 100644 index 0000000..263402a --- /dev/null +++ b/compliance-agent/src/pipeline/clone_limit.rs @@ -0,0 +1,141 @@ +//! At most two clones or fetches against one git host at a time. +//! +//! Every target of a tenant usually lives on the same git host. When scans of +//! several of them start together (a git sync creating targets, scans resumed +//! after a restart), they would all clone from that host at once; a small +//! self-hosted Gitea answers that with an OOM kill and `502`s. The limit is +//! held only around the clone or fetch itself, not the rest of the scan, and +//! another host's clones go ahead meanwhile. + +use std::collections::HashMap; +use std::sync::{Arc, Condvar, LazyLock, Mutex, PoisonError}; + +/// How many clones or fetches may run against one git host at once. +pub const CLONES_PER_HOST: usize = 2; + +/// The limiter every clone and fetch of this process goes through. +pub static CLONE_SLOTS: LazyLock = LazyLock::new(|| HostLimiter::new(CLONES_PER_HOST)); + +/// A counting semaphore per git host, for blocking (non-async) callers. +#[derive(Debug)] +pub struct HostLimiter { + per_host: usize, + hosts: Mutex>>, +} + +/// The slots of one host: how many are taken, and a wake-up for waiters. +#[derive(Debug, Default)] +struct HostSlots { + taken: Mutex, + freed: Condvar, +} + +/// One taken slot of a host; dropping it frees the slot. +#[derive(Debug)] +pub struct HostPermit { + slots: Arc, +} + +impl HostLimiter { + /// A limiter allowing `per_host` operations per host at once (at least one). + pub fn new(per_host: usize) -> Self { + Self { + per_host: per_host.max(1), + hosts: Mutex::new(HashMap::new()), + } + } + + /// Wait until `host` has a free slot and take it. + /// + /// Blocks the calling thread. On the async runtime's worker threads it + /// hands the worker's other tasks to another worker first. + pub fn acquire(&self, host: &str) -> HostPermit { + // The map lock is held only for the lookup, never while waiting. + let slots = { + let mut hosts = self.hosts.lock().unwrap_or_else(PoisonError::into_inner); + Arc::clone(hosts.entry(host.to_ascii_lowercase()).or_default()) + }; + let taken = slots.taken.lock().unwrap_or_else(PoisonError::into_inner); + let mut taken = if *taken < self.per_host { + taken + } else { + tracing::info!(host, "waiting for a free clone slot on this git host"); + off_the_runtime(|| { + slots + .freed + .wait_while(taken, |taken| *taken >= self.per_host) + .unwrap_or_else(PoisonError::into_inner) + }) + }; + *taken += 1; + drop(taken); + HostPermit { slots } + } +} + +impl Drop for HostPermit { + fn drop(&mut self) { + let mut taken = self + .slots + .taken + .lock() + .unwrap_or_else(PoisonError::into_inner); + *taken = taken.saturating_sub(1); + self.slots.freed.notify_one(); + } +} + +/// Run blocking `work` without stalling the async runtime: on a multi-thread +/// runtime's worker, `block_in_place` moves the worker's other tasks first. +fn off_the_runtime(work: impl FnOnce() -> R) -> R { + let on_multi_thread_runtime = tokio::runtime::Handle::try_current() + .is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread); + if on_multi_thread_runtime { + tokio::task::block_in_place(work) + } else { + work() + } +} + +#[cfg(test)] +#[allow(clippy::expect_used, clippy::unwrap_used)] +mod tests { + use super::HostLimiter; + use std::sync::{mpsc, Arc}; + use std::time::Duration; + + #[test] + fn a_host_runs_at_most_two_while_another_host_proceeds() { + let limiter = Arc::new(HostLimiter::new(2)); + let first = limiter.acquire("git.example.com"); + let _second = limiter.acquire("git.example.com"); + + // A third clone from the same host waits. + let (sent, received) = mpsc::channel(); + let waiting = Arc::clone(&limiter); + let third = std::thread::spawn(move || { + let permit = waiting.acquire("GIT.example.com"); + sent.send(()).expect("send"); + drop(permit); + }); + assert!(received.recv_timeout(Duration::from_millis(100)).is_err()); + + // Another host is not held up by the full one. + let _other = limiter.acquire("gitlab.example.org"); + + // A freed slot lets the waiting clone go ahead. + drop(first); + received + .recv_timeout(Duration::from_secs(5)) + .expect("the third clone runs once a slot is free"); + third.join().expect("join"); + } + + #[test] + fn a_dropped_permit_frees_its_slot() { + let limiter = HostLimiter::new(1); + drop(limiter.acquire("git.example.com")); + // Would block forever if the slot had not been freed. + let _again = limiter.acquire("git.example.com"); + } +} diff --git a/compliance-agent/src/pipeline/git.rs b/compliance-agent/src/pipeline/git.rs index 0cfb22b..805ec52 100644 --- a/compliance-agent/src/pipeline/git.rs +++ b/compliance-agent/src/pipeline/git.rs @@ -298,6 +298,11 @@ impl GitOps { #[tracing::instrument(skip_all, fields(tenant = %self.tenant_id, repo_name = %repo_name))] pub fn clone_or_fetch(&self, git_url: &str, repo_name: &str) -> Result { reject_ssh_url(git_url)?; + // At most two clones or fetches per git host, held to the end of this + // one; a refused remote has no host and fails below anyway. + let _host_slot = self + .remote_host(git_url) + .map(|host| crate::pipeline::clone_limit::CLONE_SLOTS.acquire(&host)); // Per tenant: two tenants with the same target name get two checkouts. let repo_path = self.clone_path(repo_name); diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 7bd5f6a..7362532 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -3,6 +3,7 @@ pub mod binary_depth; pub mod build_lifecycle; pub mod change; pub mod clamav; +pub mod clone_limit; pub mod code_review; pub mod cppcheck; pub(crate) mod csaf_feed; diff --git a/compliance-agent/src/scan_gate.rs b/compliance-agent/src/scan_gate.rs index 3de8b15..6f44692 100644 --- a/compliance-agent/src/scan_gate.rs +++ b/compliance-agent/src/scan_gate.rs @@ -14,15 +14,34 @@ //! 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. +//! +//! 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::time::Duration; use dashmap::mapref::entry::Entry; use dashmap::DashMap; +use rand::Rng; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; 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 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. +pub fn start_delay(trigger: &ScanTrigger) -> Duration { + match trigger { + ScanTrigger::Scheduled => rand::rng().random_range(Duration::ZERO..=SCHEDULED_SCAN_JITTER), + ScanTrigger::Webhook | ScanTrigger::Manual | ScanTrigger::Support => Duration::ZERO, + } +} + /// What happened to a scan request. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Admission { @@ -153,8 +172,30 @@ impl Drop for HeldTarget<'_> { #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { - use super::{Admission, HeldTarget, ScanGate}; + use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER}; use compliance_core::models::ScanTrigger; + use std::time::Duration; + + #[test] + fn a_scheduled_scan_waits_within_the_jitter() { + let delays: Vec = (0..1000) + .map(|_| start_delay(&ScanTrigger::Scheduled)) + .collect(); + assert!(delays.iter().all(|d| *d <= SCHEDULED_SCAN_JITTER)); + // Spread out, not one fixed delay. + assert!(delays.iter().any(|d| *d != delays[0])); + } + + #[test] + fn webhook_manual_and_support_scans_start_at_once() { + for trigger in [ + ScanTrigger::Webhook, + ScanTrigger::Manual, + ScanTrigger::Support, + ] { + assert_eq!(start_delay(&trigger), Duration::ZERO); + } + } #[test] fn a_burst_coalesces_into_one_run_and_one_follow_up() { -- 2.54.1 From a5720f9fa3694d43298a9d56a06836aa878b1665 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:25:11 +0200 Subject: [PATCH 2/2] refactor(git): the retry wait and the clone limit share one off-the-runtime wrapper Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/pipeline/clone_limit.rs | 2 +- compliance-agent/src/pipeline/git_retry.rs | 16 ++++------------ 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/compliance-agent/src/pipeline/clone_limit.rs b/compliance-agent/src/pipeline/clone_limit.rs index 263402a..9f9c201 100644 --- a/compliance-agent/src/pipeline/clone_limit.rs +++ b/compliance-agent/src/pipeline/clone_limit.rs @@ -87,7 +87,7 @@ impl Drop for HostPermit { /// Run blocking `work` without stalling the async runtime: on a multi-thread /// runtime's worker, `block_in_place` moves the worker's other tasks first. -fn off_the_runtime(work: impl FnOnce() -> R) -> R { +pub(crate) fn off_the_runtime(work: impl FnOnce() -> R) -> R { let on_multi_thread_runtime = tokio::runtime::Handle::try_current() .is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread); if on_multi_thread_runtime { diff --git a/compliance-agent/src/pipeline/git_retry.rs b/compliance-agent/src/pipeline/git_retry.rs index c5a23b2..81472a6 100644 --- a/compliance-agent/src/pipeline/git_retry.rs +++ b/compliance-agent/src/pipeline/git_retry.rs @@ -108,19 +108,11 @@ pub fn is_transient(error: &git2::Error) -> bool { } } -/// Wait `duration` on this thread. Clones run on the async runtime's worker -/// threads; `block_in_place` hands this worker's other tasks to another -/// worker first, so a waiting retry does not stall them. +/// Wait `duration` on this thread, without stalling the async runtime's +/// other tasks (clones run on its worker threads). fn sleep(duration: Duration) { - if duration.is_zero() { - return; - } - let on_multi_thread_runtime = tokio::runtime::Handle::try_current() - .is_ok_and(|h| h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread); - if on_multi_thread_runtime { - tokio::task::block_in_place(|| std::thread::sleep(duration)); - } else { - std::thread::sleep(duration); + if !duration.is_zero() { + crate::pipeline::clone_limit::off_the_runtime(|| std::thread::sleep(duration)); } } -- 2.54.1