From 6076d498d3773adef0b0f0bf3563fe91c17666ef Mon Sep 17 00:00:00 2001 From: "Angel L. Pinzon" Date: Thu, 3 Dec 2026 20:57:22 -0500 Subject: [PATCH] Prevent cooldown overflow and fail closed on future timestamps --- crates/operator/src/policy.rs | 40 ++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/operator/src/policy.rs b/crates/operator/src/policy.rs index 32f89a2..31ac789 100644 --- a/crates/operator/src/policy.rs +++ b/crates/operator/src/policy.rs @@ -55,7 +55,7 @@ impl PolicyEngine { // 1. Cooldown check if let Some(last_ts) = ctx.last_correction_at { let elapsed = (Utc::now() - last_ts).num_seconds(); - if elapsed < ctx.cooldown_secs as i64 { + if elapsed < 0 || (elapsed as u64) < ctx.cooldown_secs { return PolicyDecision::Skip { reason: format!( "Cooldown active ({}s < {}s), skipping correction", @@ -215,4 +215,42 @@ mod tests { PolicyDecision::Skip { .. } )); } + + #[test] + fn extreme_cooldown_does_not_wrap_and_allow_correction() { + let ctx = PolicyContext { + plc_name: "test-plc".into(), + register_name: "reg1".into(), + desired_value: 100, + current_value: 120, + strategy: RemediationStrategy::Auto, + last_correction_at: Some(Utc::now() - Duration::seconds(60)), + corrections_last_hour: 0, + max_corrections_per_hour: 5, + cooldown_secs: u64::MAX, + }; + assert!(matches!( + PolicyEngine::evaluate(&ctx), + PolicyDecision::Skip { .. } + )); + } + + #[test] + fn future_correction_timestamp_fails_closed() { + let ctx = PolicyContext { + plc_name: "test-plc".into(), + register_name: "reg1".into(), + desired_value: 100, + current_value: 120, + strategy: RemediationStrategy::Auto, + last_correction_at: Some(Utc::now() + Duration::hours(1)), + corrections_last_hour: 0, + max_corrections_per_hour: 5, + cooldown_secs: 0, + }; + assert!(matches!( + PolicyEngine::evaluate(&ctx), + PolicyDecision::Skip { .. } + )); + } }