//! Reconcile summary aggregation, config inventory publication, and metric emission. use std::any::Any; use std::collections::HashSet; use std::time::Instant; use pplx_space_cluster_pool::{AutoscaleRun, InvalidPoolConfigRow, PoolConfig, PoolSlotCounts}; use uuid::Uuid; use super::pass::AutoscaleOutcome; use super::{ReconcileSummary, WarmPoolError, target_open_slots}; use crate::metrics::warm_pool::SlotDeleteReason; impl ReconcileSummary { pub(super) fn completed_required_operations(&self) -> bool { self.failed_required_operations == 0 } /// Single source of truth mapping delete-counter fields to their /// [`SlotDeleteReason`]: both the `deleted_slots` log field and the /// per-reason metric emission consume this. The exhaustive destructure /// forces a decision here when a `ReconcileSummary` field is added, and /// the fixed array length forces the new delete reason into every /// consumer at once. pub(super) fn delete_counts(&self) -> [(SlotDeleteReason, usize); 10] { let Self { enabled_pool_configs: _, template_write_annotations: _, created_slots: _, marked_ready_slots: _, deleted_missing_pods, deleted_unready_pods, deleted_excess_slots, deleted_mismatched_slots, deleted_stale_claimed_slots, deleted_dead_claimed_slots, deleted_orphaned_receipts, deleted_cleanup_pending_slots, deleted_cordoned_slots, deleted_unhealthy_node_slots, reconciled_slot_counts: _, failed_required_operations: _, } = *self; [ (SlotDeleteReason::MissingPod, deleted_missing_pods), (SlotDeleteReason::UnreadyPod, deleted_unready_pods), (SlotDeleteReason::Excess, deleted_excess_slots), (SlotDeleteReason::Mismatched, deleted_mismatched_slots), (SlotDeleteReason::StaleClaimed, deleted_stale_claimed_slots), (SlotDeleteReason::DeadClaimed, deleted_dead_claimed_slots), (SlotDeleteReason::OrphanedReceipt, deleted_orphaned_receipts), ( SlotDeleteReason::CleanupPending, deleted_cleanup_pending_slots, ), (SlotDeleteReason::Cordoned, deleted_cordoned_slots), ( SlotDeleteReason::UnhealthyNode, deleted_unhealthy_node_slots, ), ] } pub(super) fn deleted_slots(&self) -> usize { self.delete_counts().iter().map(|(_, count)| count).sum() } pub(super) fn emit_metrics(&self) { crate::metrics::warm_pool::reconcile_summary(self.created_slots, self.marked_ready_slots); for (reason, count) in self.delete_counts() { crate::metrics::warm_pool::slots_deleted(reason, count); } crate::metrics::warm_pool::slots_evicted_cordoned(self.deleted_cordoned_slots); crate::metrics::warm_pool::dead_claimed_slots_drained(self.deleted_dead_claimed_slots); } } impl std::ops::AddAssign for ReconcileSummary { fn add_assign(&mut self, rhs: Self) { self.enabled_pool_configs += rhs.enabled_pool_configs; self.template_write_annotations += rhs.template_write_annotations; self.created_slots += rhs.created_slots; self.marked_ready_slots += rhs.marked_ready_slots; self.deleted_missing_pods += rhs.deleted_missing_pods; self.deleted_unready_pods += rhs.deleted_unready_pods; self.deleted_excess_slots += rhs.deleted_excess_slots; self.deleted_mismatched_slots += rhs.deleted_mismatched_slots; self.deleted_stale_claimed_slots += rhs.deleted_stale_claimed_slots; self.deleted_dead_claimed_slots += rhs.deleted_dead_claimed_slots; self.deleted_orphaned_receipts += rhs.deleted_orphaned_receipts; self.deleted_cleanup_pending_slots += rhs.deleted_cleanup_pending_slots; self.deleted_cordoned_slots += rhs.deleted_cordoned_slots; self.deleted_unhealthy_node_slots += rhs.deleted_unhealthy_node_slots; self.reconciled_slot_counts = rhs.reconciled_slot_counts.or(self.reconciled_slot_counts); self.failed_required_operations += rhs.failed_required_operations; } } pub(super) struct ConfigReconcileResult { pub(super) config: PoolConfig, pub(super) result: Result, } impl ConfigReconcileResult { pub(super) fn succeeded(&self) -> bool { self.result .as_ref() .is_ok_and(ReconcileSummary::completed_required_operations) } pub(super) fn is_shutdown(&self) -> bool { self.result.as_ref().is_err_and(WarmPoolError::is_shutdown) } pub(super) fn slot_counts(&self) -> Option { self.result .as_ref() .ok() .and_then(|summary| summary.reconciled_slot_counts) } pub(super) fn into_parts(self) -> (PoolConfig, Result) { (self.config, self.result) } } #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct ConfigInventoryState { template_release_id: Uuid, template_name: String, content_hash: String, vcpu: u32, memory_mib: u64, target_ready_slots: i32, refill_per_tick: i32, max_warming_slots: i32, namespace: String, enabled: bool, managed_by: pplx_space_cluster_pool::PoolConfigOwner, } impl ConfigInventoryState { pub(super) fn from_config(config: &PoolConfig) -> Self { Self { template_release_id: config.template_release_id, template_name: config.template_name.to_string(), content_hash: config.content_hash.to_string(), vcpu: config.vcpu.get().get(), memory_mib: config.memory.as_mib_floor(), target_ready_slots: config.target_ready_slots, refill_per_tick: config.refill_per_tick, max_warming_slots: config.max_warming_slots, namespace: config.namespace.clone(), enabled: config.enabled, managed_by: config.managed_by, } } } pub(super) struct ConfigInventoryPublication { pub(super) config: ConfigInventoryState, pub(super) succeeded: bool, pub(super) emitted_at: Instant, } pub(super) fn panic_payload_message(payload: &(dyn Any + Send)) -> String { payload .downcast_ref::<&str>() .map(|message| (*message).to_string()) .or_else(|| payload.downcast_ref::().cloned()) .unwrap_or_else(|| "unknown panic payload".to_string()) } #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct ReconcileConfigState { active: bool, succeeded: bool, } fn reconcile_config_state(config: &PoolConfig, succeeded: bool) -> ReconcileConfigState { ReconcileConfigState { active: config.enabled, succeeded: config.enabled && succeeded, } } pub(super) fn emit_reconcile_config_states(config: &PoolConfig, succeeded: bool) { let template = config.template_name.as_str(); let content_hash = config.content_hash.to_string(); let vcpu = config.vcpu.get().get(); let memory_mib = config.memory.as_mib_floor(); let state = reconcile_config_state(config, succeeded); crate::metrics::warm_pool::reconcile_config_state( template, &content_hash, vcpu, memory_mib, config.managed_by.as_str(), "active", state.active, ); crate::metrics::warm_pool::reconcile_config_state( template, &content_hash, vcpu, memory_mib, config.managed_by.as_str(), "succeeded", state.succeeded, ); } /// Log each row and candidate the autoscale step skipped, and classify the /// step for the pass report. pub(super) fn report_autoscale_run(run: &AutoscaleRun) -> AutoscaleOutcome { for row in &run.invalid_rows { tracing::error!( read = %row.read, template_release_id = %row.template_release_id, error = %row.error, "warm pool: autoscale row is not valid; skipping it" ); } for candidate in &run.failed_candidates { tracing::warn!( template_release_id = %candidate.template_release_id, vcpu = candidate.vcpu.get().get(), memory_mib = candidate.memory.as_mib_floor(), error = %candidate.error, "warm pool: could not write an autoscale config; leaving its stored config as it is" ); } let held = run.held_release_ids(); if !held.is_empty() { tracing::warn!( held_releases = held.len(), "warm pool: autoscale skipped rows or candidates, so stale configs of their releases stay enabled" ); } if run.invalid_rows.is_empty() && run.failed_candidates.is_empty() { AutoscaleOutcome::Ok } else { AutoscaleOutcome::Partial } } /// Log and count each invalid config row that a read did not return as a config. pub(super) fn report_invalid_config_rows(read: &'static str, rows: &[InvalidPoolConfigRow]) { for row in rows { tracing::error!( read, config_id = %row.id, template_release_id = %row.template_release_id, template = %row.template_name, content_hash = %row.content_hash, error = %row.error, "warm pool: config row is not valid; skipping it and continuing with remaining configs" ); crate::metrics::warm_pool::config_decode_failed(read, &row.template_name); } } pub(super) fn retired_configs_to_emit( deleted_configs: Vec, recently_disabled_configs: Vec, reconcilable_config_ids: &HashSet, ) -> Vec { deleted_configs .into_iter() .chain( recently_disabled_configs .into_iter() .filter(|config| !reconcilable_config_ids.contains(&config.id)), ) .collect() } pub(super) fn emit_slot_gauges(config: &PoolConfig, counts: PoolSlotCounts) { let template = config.template_name.as_str(); let content_hash = config.content_hash.to_string(); let vcpu = config.vcpu.get().get(); let memory_mib = config.memory.as_mib_floor(); crate::metrics::warm_pool::slots( template, &content_hash, vcpu, memory_mib, config.managed_by.as_str(), "ready", counts.ready, ); crate::metrics::warm_pool::slots( template, &content_hash, vcpu, memory_mib, config.managed_by.as_str(), "warming", counts.warming, ); crate::metrics::warm_pool::slots( template, &content_hash, vcpu, memory_mib, config.managed_by.as_str(), "desired", // Reuse the reconciler's effective target so a config it refuses to // fill (disabled, encryptable) also reports zero desired capacity. target_open_slots(config), ); } pub(super) fn emit_config_inventory( config: &PoolConfig, counts: Option, succeeded: bool, ) { let (warming_slots, ready_slots) = counts .map(|counts| (Some(counts.warming), Some(counts.ready))) .unwrap_or((None, None)); tracing::info!( config_id = %config.id, template_release_id = %config.template_release_id, template = %config.template_name, content_hash = %config.content_hash, pool_vcpu = config.vcpu.get().get(), pool_memory_mib = config.memory.as_mib_floor(), target_ready_slots = config.target_ready_slots, desired_ready_slots = target_open_slots(config), refill_per_tick = config.refill_per_tick, max_warming_slots = config.max_warming_slots, namespace = %config.namespace, enabled = config.enabled, managed_by = %config.managed_by, warming_slots, ready_slots, config_created_at = ?config.created_at, config_updated_at = ?config.updated_at, reconcile_succeeded = succeeded, "warm pool: config inventory" ); }