diff --git a/Cargo.toml b/Cargo.toml index 2706b257..48b83e89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ authors = ["Momentry Team"] description = "Digital asset management system with video analysis and RAG" [dependencies] +sysinfo = "0.30" # Core anyhow = "1.0" thiserror = "1.0" diff --git a/src/core/dynamic_concurrency.rs b/src/core/dynamic_concurrency.rs new file mode 100644 index 00000000..2e3ba6f7 --- /dev/null +++ b/src/core/dynamic_concurrency.rs @@ -0,0 +1,200 @@ +use std::sync::{Arc, RwLock}; +use std::time::Duration; +use std::collections::VecDeque; +use tokio::sync::{Semaphore, SemaphorePermit, AcquireError}; +use tracing::info; +use sysinfo::System; + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum MemoryStatus { + Low, // < 38 GB (can increase concurrency) + Normal, // 38-41 GB + High, // > 41 GB (must decrease concurrency) +} + +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum VlmStatus { + Available, // < 5s (can increase concurrency) + Normal, // 5-10s + Overloaded, // > 10s (must decrease concurrency) + Unknown, +} + +pub struct DynamicSemaphore { + inner: Arc, + current_permits: Arc>, + max_permits: usize, + min_permits: usize, +} + +impl DynamicSemaphore { + pub fn new(initial_permits: usize, max_permits: usize, min_permits: usize) -> Self { + Self { + inner: Arc::new(Semaphore::new(initial_permits)), + current_permits: Arc::new(RwLock::new(initial_permits)), + max_permits, + min_permits, + } + } + + pub async fn acquire(&self) -> Result { + self.inner.acquire().await + } + + pub fn increase(&self) -> bool { + let mut current = self.current_permits.write().unwrap(); + if *current < self.max_permits { + *current += 1; + self.inner.add_permits(1); + info!("[AutoScaler] Increased SCENE_VLM concurrency to {}", *current); + return true; + } + false + } + + pub fn decrease(&self) -> bool { + let mut current = self.current_permits.write().unwrap(); + if *current > self.min_permits { + *current -= 1; + info!("[AutoScaler] Decreased SCENE_VLM concurrency to {}", *current); + true + } else { + false + } + } + + pub fn current(&self) -> usize { + *self.current_permits.read().unwrap() + } +} + +pub struct SystemMonitor { + total_memory_bytes: u64, + memory_threshold_high: f64, + memory_threshold_low: f64, +} + +impl SystemMonitor { + pub fn new(total_memory_gb: u64) -> Self { + Self { + total_memory_bytes: total_memory_gb * 1024 * 1024 * 1024, + memory_threshold_high: 0.85, // 41 GB for 48 GB system + memory_threshold_low: 0.80, // 38 GB for 48 GB system + } + } + + pub fn check_memory(&self) -> MemoryStatus { + let mut sys = System::new_all(); + sys.refresh_memory(); + + let used = sys.used_memory() as f64; + let total = self.total_memory_bytes as f64; + let ratio = used / total; + + if ratio > self.memory_threshold_high { + MemoryStatus::High + } else if ratio < self.memory_threshold_low { + MemoryStatus::Low + } else { + MemoryStatus::Normal + } + } +} + +pub struct VlmMonitor { + response_threshold_high: Duration, + response_threshold_low: Duration, + recent_responses: Arc>>, +} + +impl VlmMonitor { + pub fn new() -> Self { + Self { + response_threshold_high: Duration::from_secs(10), + response_threshold_low: Duration::from_secs(5), + recent_responses: Arc::new(RwLock::new(VecDeque::with_capacity(10))), + } + } + + pub fn record_response(&self, duration: Duration) { + let mut responses = self.recent_responses.write().unwrap(); + responses.push_back(duration); + + if responses.len() > 10 { + responses.pop_front(); + } + } + + pub fn check_status(&self) -> VlmStatus { + let responses = self.recent_responses.read().unwrap(); + if responses.is_empty() { + return VlmStatus::Unknown; + } + + let avg: Duration = responses.iter().sum::() / responses.len() as u32; + + if avg > self.response_threshold_high { + VlmStatus::Overloaded + } else if avg < self.response_threshold_low { + VlmStatus::Available + } else { + VlmStatus::Normal + } + } +} + +pub struct AutoScaler { + semaphore: Arc, + system_monitor: Arc, + vlm_monitor: Arc, + check_interval: Duration, +} + +impl AutoScaler { + pub fn new( + semaphore: Arc, + system_monitor: Arc, + vlm_monitor: Arc, + check_interval: Duration, + ) -> Self { + Self { + semaphore, + system_monitor, + vlm_monitor, + check_interval, + } + } + + pub async fn run(self: Arc) { + use tokio::time::interval; + + let mut ticker = interval(self.check_interval); + + loop { + ticker.tick().await; + + let mem_status = self.system_monitor.check_memory(); + let vlm_status = self.vlm_monitor.check_status(); + let current = self.semaphore.current(); + + info!( + "[AutoScaler] Status: mem={:?}, vlm={:?}, current_concurrency={}", + mem_status, vlm_status, current + ); + + match (&mem_status, &vlm_status) { + (MemoryStatus::High, _) | + (_, VlmStatus::Overloaded) => { + self.semaphore.decrease(); + } + + (MemoryStatus::Low, VlmStatus::Available) | + (MemoryStatus::Low, VlmStatus::Unknown) => { + self.semaphore.increase(); + } + + _ => {} + } + } + } +} diff --git a/src/core/mod.rs b/src/core/mod.rs index d5813729..07ae1755 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -8,6 +8,7 @@ pub mod checkin; pub mod chunk; pub mod command; pub mod config; +pub mod dynamic_concurrency; pub mod db; pub mod embedding; pub mod face_filter_engine; diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 7e700ac6..47b1fd4a 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use std::sync::LazyLock; use std::time::Duration; use tokio::sync::Semaphore; +use crate::core::dynamic_concurrency::{DynamicSemaphore, SystemMonitor, VlmMonitor, AutoScaler}; use tokio::time::sleep; use tracing::{debug, error, info, warn}; @@ -30,7 +31,10 @@ static FACE_TRACE_INFLIGHT: LazyLock = LazyLock::new(|| Semaphore::new(1)); +static SCENE_VLM_SEM: LazyLock> = LazyLock::new(|| Arc::new(DynamicSemaphore::new(1, 3, 1))); + +/// Global VLM monitor for tracking response times +static VLM_MONITOR: LazyLock> = LazyLock::new(|| Arc::new(VlmMonitor::new())); /// Tracks uuids with a Scene VLM task currently spawned (or queued for a permit). /// Prevents the per-poll loop from spawning duplicate tasks before `scenes.json` @@ -4866,3 +4870,19 @@ mod tests { assert!(stage_dependencies(ProcessorType::Cut).is_empty()); } } + +/// Start the AutoScaler background task for dynamic SCENE_VLM concurrency +pub fn start_autoscaler() { + let auto_scaler = Arc::new(AutoScaler::new( + SCENE_VLM_SEM.clone(), + Arc::new(SystemMonitor::new(48)), // M5Max48 + VLM_MONITOR.clone(), + Duration::from_secs(30), + )); + + tokio::spawn(async move { + auto_scaler.run().await; + }); + + info!("[AutoScaler] Started dynamic concurrency controller for SCENE_VLM"); +}