adk_kernel/review.rs
1//! The review the maintenance tick makes of what may have drifted (spec 3.2 §7.4, §9.1
2//! permission drift).
3//!
4//! At most once per partition and UTC day, the kernel lists what is older than the
5//! partition's [`ProactivityPolicy::review_period`](crate::ProactivityPolicy::review_period):
6//!
7//! | List | What |
8//! |---|---|
9//! | `rules` | Standing rules with no `expires_at`, granted longer ago than the period, each with a renewal ask |
10//! | `sleepers` | `Waiting` processes asleep or suspended for longer than the period |
11//! | `frozen` | Processes a freeze parked longer ago than the period |
12//! | `crossings` | Crossings out of the partition that recur, at least [`ReviewReport::CROSSING_THRESHOLD`] times in [`ReviewReport::CROSSING_WINDOW`] by source, target, resource and name (spec 3.2 §7.8), each with partition membership as the remedy |
13//!
14//! A report is published as a [`KernelEvent::Review`](crate::KernelEvent::Review) and written as
15//! one `kernel.review` audit record — ids, ages, resource names and counts, no content. The
16//! review never revokes, suspends or kills anything, and never waives a crossing.
17//!
18//! `adk-kernel` reads no harness type (§6 D-1), so it reads standing rules through a
19//! [`StandingRuleSource`] the harness implements over its rule store.
20
21use std::time::Duration;
22
23use async_trait::async_trait;
24use chrono::{DateTime, Utc};
25use serde::{Deserialize, Serialize};
26
27use crate::error::Result;
28use crate::partition::{PartitionId, RecurringCrossing};
29
30/// When a standing rule was granted and whether it expires, as the review reads it (spec
31/// 3.2 §9.1).
32///
33/// # Example
34///
35/// ```rust
36/// use adk_kernel::RuleAge;
37///
38/// let rule = RuleAge::new("rule-1", "alice", chrono::Utc::now());
39/// assert!(rule.expires_at.is_none());
40/// ```
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct RuleAge {
45 /// The rule's id.
46 pub id: String,
47 /// The user the rule belongs to.
48 pub user: String,
49 /// When it was granted.
50 pub created_at: DateTime<Utc>,
51 /// When it expires; `None` never.
52 #[serde(default, skip_serializing_if = "Option::is_none")]
53 pub expires_at: Option<DateTime<Utc>>,
54}
55
56impl RuleAge {
57 /// A rule of `user` granted at `created_at` that never expires.
58 pub fn new(id: impl Into<String>, user: impl Into<String>, created_at: DateTime<Utc>) -> Self {
59 Self { id: id.into(), user: user.into(), created_at, expires_at: None }
60 }
61
62 /// Sets the expiry.
63 #[must_use]
64 pub fn with_expiry(mut self, at: DateTime<Utc>) -> Self {
65 self.expires_at = Some(at);
66 self
67 }
68}
69
70/// Reads the standing rules the review checks (spec 3.2 §9.1): the harness implements it
71/// over its rule store and `Harness::kernel` registers it
72/// ([`KernelBuilder::standing_rules`](crate::KernelBuilder::standing_rules)).
73///
74/// # Example
75///
76/// ```rust
77/// use adk_kernel::{RuleAge, StandingRuleSource};
78/// use async_trait::async_trait;
79///
80/// struct Fixed(Vec<RuleAge>);
81///
82/// #[async_trait]
83/// impl StandingRuleSource for Fixed {
84/// async fn rules(&self, _app: &str, user: &str) -> adk_kernel::Result<Vec<RuleAge>> {
85/// Ok(self.0.iter().filter(|rule| rule.user == user).cloned().collect())
86/// }
87/// }
88/// ```
89#[async_trait]
90pub trait StandingRuleSource: Send + Sync {
91 /// Every standing rule of `user` in `app`.
92 ///
93 /// # Errors
94 ///
95 /// Returns the rule store's error; the review then lists no rules.
96 async fn rules(&self, app: &str, user: &str) -> Result<Vec<RuleAge>>;
97}
98
99/// A standing rule the review asks to renew (spec 3.2 §9.1).
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101#[serde(rename_all = "camelCase")]
102#[non_exhaustive]
103pub struct StaleRule {
104 /// The rule's id.
105 pub id: String,
106 /// The user it belongs to.
107 pub user: String,
108 /// How long ago it was granted.
109 #[serde(rename = "ageMs", with = "crate::serde_util::millis")]
110 pub age: Duration,
111}
112
113/// A process the review reports (spec 3.2 §7.4).
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub struct AgedProcess {
118 /// The process.
119 pub pid: String,
120 /// How long it has waited.
121 #[serde(rename = "ageMs", with = "crate::serde_util::millis")]
122 pub age: Duration,
123}
124
125/// One partition's review (spec 3.2 §7.4, §9.1): what is older than its review period.
126///
127/// # Example
128///
129/// ```rust
130/// use adk_kernel::ReviewReport;
131///
132/// let report: ReviewReport = serde_json::from_value(serde_json::json!({
133/// "partition": "default", "reviewPeriodMs": 7_776_000_000u64, "at": "2026-10-23T09:00:00Z",
134/// "rules": [{ "id": "rule-1", "user": "alice", "ageMs": 9_000_000_000u64 }],
135/// "sleepers": [], "frozen": [],
136/// "crossings": [{ "from": "default", "to": "work", "resource": "driver",
137/// "name": "calendar", "count": 9 }]
138/// })).unwrap();
139/// assert!(report.renewal_ask().unwrap().contains("rule-1"));
140/// assert!(report.crossing_remedies()[0].contains("move calendar into default"));
141/// ```
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143#[serde(rename_all = "camelCase")]
144#[non_exhaustive]
145pub struct ReviewReport {
146 /// The partition reviewed.
147 pub partition: PartitionId,
148 /// Its review period.
149 #[serde(rename = "reviewPeriodMs", with = "crate::serde_util::millis")]
150 pub review_period: Duration,
151 /// When the review ran.
152 pub at: DateTime<Utc>,
153 /// Standing rules without an expiry granted longer ago than the period.
154 #[serde(default)]
155 pub rules: Vec<StaleRule>,
156 /// `Waiting` processes asleep or suspended longer than the period.
157 #[serde(default)]
158 pub sleepers: Vec<AgedProcess>,
159 /// Processes a freeze parked longer ago than the period.
160 #[serde(default)]
161 pub frozen: Vec<AgedProcess>,
162 /// Crossings out of the partition that recur (spec 3.2 §7.8), most frequent first.
163 #[serde(default)]
164 pub crossings: Vec<RecurringCrossing>,
165}
166
167impl ReviewReport {
168 /// How far back the review counts crossings.
169 pub const CROSSING_WINDOW: Duration = Duration::from_secs(7 * 86_400);
170
171 /// How many crossings of one resource in the window the review reports.
172 pub const CROSSING_THRESHOLD: usize = 5;
173
174 /// Whether nothing is older than the period and no crossing recurs.
175 pub fn is_empty(&self) -> bool {
176 self.rules.is_empty()
177 && self.sleepers.is_empty()
178 && self.frozen.is_empty()
179 && self.crossings.is_empty()
180 }
181
182 /// One line per recurring crossing, with partition membership as the remedy.
183 pub fn crossing_remedies(&self) -> Vec<String> {
184 self.crossings.iter().map(RecurringCrossing::remedy).collect()
185 }
186
187 /// The renewal ask for the stale rules, `None` without any.
188 pub fn renewal_ask(&self) -> Option<String> {
189 if self.rules.is_empty() {
190 return None;
191 }
192 let ids: Vec<&str> = self.rules.iter().map(|rule| rule.id.as_str()).collect();
193 Some(format!(
194 "{} standing rule(s) have no expiry and were granted more than {} day(s) ago: {}. \
195 Renew each with an expiry, or revoke it.",
196 ids.len(),
197 self.review_period.as_secs() / 86_400,
198 ids.join(", ")
199 ))
200 }
201}