1use std::collections::BTreeMap;
21use std::fmt;
22use std::sync::{Arc, Mutex};
23use std::time::Duration;
24
25use adk_core::principal::SubjectRef;
26use adk_core::{NewRun, OnConflict, RunBudget};
27use adk_server::background::{WorkflowExecutor, WorkflowRunContext, WorkflowState};
28use async_trait::async_trait;
29use chrono::{DateTime, Utc};
30use serde::{Deserialize, Serialize};
31use serde_json::{Value, json};
32use tokio_util::sync::CancellationToken;
33
34use crate::agenda::{AgendaHandle, AgendaItem, AgendaOrigin};
35use crate::bus::SpendDelta;
36use crate::error::Result;
37use crate::partition::{PartitionId, PartitionMode};
38use crate::process::{ProcessKind, ProcessSpec, ProcessTable};
39use crate::sched::{QueueClass, QuietHours};
40use crate::supervise::Supervision;
41use crate::wake::KERNEL_WAKE_TARGET;
42
43#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase", default)]
87#[non_exhaustive]
88pub struct ConsolidationTick {
89 pub min_new_sessions: usize,
91 pub min_new_facts: usize,
93 #[serde(rename = "minIntervalMs", with = "crate::serde_util::millis")]
95 pub min_interval: Duration,
96 #[serde(rename = "debounceMs", with = "crate::serde_util::millis")]
98 pub debounce: Duration,
99 #[serde(skip_serializing_if = "Option::is_none")]
101 pub schedule: Option<String>,
102 pub budget_share: f32,
104 pub max_tokens_per_tick: u64,
106 pub dedup_score: f32,
109 pub expire_confidence: f32,
111 #[serde(rename = "assumedTtlMs", with = "crate::serde_util::millis")]
113 pub assumed_ttl: Duration,
114 pub max_clusters_per_tick: usize,
116 pub max_loss_fraction: f32,
120}
121
122impl ConsolidationTick {
123 pub const DEFAULT_MAX_TOKENS_PER_TICK: u64 = 50_000;
125
126 pub fn new() -> Self {
128 Self::default()
129 }
130
131 #[must_use]
133 pub fn with_min_new_sessions(mut self, sessions: usize) -> Self {
134 self.min_new_sessions = sessions;
135 self
136 }
137
138 #[must_use]
140 pub fn with_min_new_facts(mut self, facts: usize) -> Self {
141 self.min_new_facts = facts;
142 self
143 }
144
145 #[must_use]
147 pub fn with_min_interval(mut self, interval: Duration) -> Self {
148 self.min_interval = interval;
149 self
150 }
151
152 #[must_use]
154 pub fn with_debounce(mut self, debounce: Duration) -> Self {
155 self.debounce = debounce;
156 self
157 }
158
159 #[must_use]
161 pub fn with_schedule(mut self, schedule: impl Into<String>) -> Self {
162 self.schedule = Some(schedule.into());
163 self
164 }
165
166 #[must_use]
168 pub fn with_budget_share(mut self, share: f32) -> Self {
169 self.budget_share = share;
170 self
171 }
172
173 #[must_use]
175 pub fn with_max_tokens_per_tick(mut self, tokens: u64) -> Self {
176 self.max_tokens_per_tick = tokens;
177 self
178 }
179
180 #[must_use]
182 pub fn with_dedup_score(mut self, score: f32) -> Self {
183 self.dedup_score = score;
184 self
185 }
186
187 #[must_use]
189 pub fn with_expire_confidence(mut self, confidence: f32) -> Self {
190 self.expire_confidence = confidence;
191 self
192 }
193
194 #[must_use]
196 pub fn with_assumed_ttl(mut self, ttl: Duration) -> Self {
197 self.assumed_ttl = ttl;
198 self
199 }
200
201 #[must_use]
203 pub fn with_max_clusters_per_tick(mut self, clusters: usize) -> Self {
204 self.max_clusters_per_tick = clusters;
205 self
206 }
207
208 #[must_use]
210 pub fn with_max_loss_fraction(mut self, fraction: f32) -> Self {
211 self.max_loss_fraction = fraction;
212 self
213 }
214}
215
216impl Default for ConsolidationTick {
217 fn default() -> Self {
218 Self {
219 min_new_sessions: 3,
220 min_new_facts: 25,
221 min_interval: Duration::from_secs(6 * 60 * 60),
222 debounce: Duration::from_secs(30 * 60),
223 schedule: None,
224 budget_share: 0.10,
225 max_tokens_per_tick: Self::DEFAULT_MAX_TOKENS_PER_TICK,
226 dedup_score: 0.92,
227 expire_confidence: 0.5,
228 assumed_ttl: Duration::from_secs(90 * 24 * 60 * 60),
229 max_clusters_per_tick: 20,
230 max_loss_fraction: 0.25,
231 }
232 }
233}
234
235pub const CONSOLIDATION_TARGET: &str = "kernel.consolidation";
244
245pub const CONSOLIDATION_LABEL: &str = "kernel.tick";
253
254const EVALUATE_EVERY: chrono::Duration = chrono::Duration::seconds(60);
256
257#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "camelCase")]
268#[non_exhaustive]
269pub struct TickSpend {
270 pub cost_micro_usd: u64,
272 pub total_tokens: u64,
274 pub model_calls: u64,
276}
277
278impl TickSpend {
279 pub fn new(cost_micro_usd: u64, total_tokens: u64, model_calls: u64) -> Self {
281 Self { cost_micro_usd, total_tokens, model_calls }
282 }
283}
284
285#[derive(Debug, Clone, PartialEq)]
297#[non_exhaustive]
298pub struct TickMaterial {
299 pub user: String,
301 pub mode: PartitionMode,
303 pub last_tick: Option<DateTime<Utc>>,
305 pub new_sessions: usize,
307 pub new_facts: usize,
309 pub last_activity: Option<DateTime<Utc>>,
311 pub sessions: Vec<String>,
313 pub spent_today: TickSpend,
315}
316
317impl TickMaterial {
318 pub fn new(user: impl Into<String>, mode: PartitionMode) -> Self {
320 Self {
321 user: user.into(),
322 mode,
323 last_tick: None,
324 new_sessions: 0,
325 new_facts: 0,
326 last_activity: None,
327 sessions: Vec::new(),
328 spent_today: TickSpend::default(),
329 }
330 }
331
332 #[must_use]
334 pub fn with_last_tick(mut self, at: DateTime<Utc>) -> Self {
335 self.last_tick = Some(at);
336 self
337 }
338
339 #[must_use]
341 pub fn with_new_material(mut self, sessions: usize, facts: usize) -> Self {
342 self.new_sessions = sessions;
343 self.new_facts = facts;
344 self
345 }
346
347 #[must_use]
349 pub fn with_last_activity(mut self, at: DateTime<Utc>) -> Self {
350 self.last_activity = Some(at);
351 self
352 }
353
354 #[must_use]
356 pub fn with_sessions(mut self, sessions: impl IntoIterator<Item = impl Into<String>>) -> Self {
357 self.sessions = sessions.into_iter().map(Into::into).collect();
358 self
359 }
360
361 #[must_use]
363 pub fn with_spent_today(mut self, spend: TickSpend) -> Self {
364 self.spent_today = spend;
365 self
366 }
367}
368
369#[derive(Debug, Clone, PartialEq)]
380#[non_exhaustive]
381pub struct TickRun {
382 pub tick_id: String,
384 pub partition: PartitionId,
386 pub user: String,
388 pub sessions: Vec<String>,
390 pub tick: ConsolidationTick,
392 pub budget: RunBudget,
395 pub at: DateTime<Utc>,
397}
398
399impl TickRun {
400 pub fn new(
403 tick_id: impl Into<String>,
404 partition: impl Into<PartitionId>,
405 user: impl Into<String>,
406 tick: ConsolidationTick,
407 at: DateTime<Utc>,
408 ) -> Self {
409 Self {
410 tick_id: tick_id.into(),
411 partition: partition.into(),
412 user: user.into(),
413 sessions: Vec::new(),
414 tick,
415 budget: RunBudget::new(),
416 at,
417 }
418 }
419
420 #[must_use]
422 pub fn with_sessions(mut self, sessions: Vec<String>) -> Self {
423 self.sessions = sessions;
424 self
425 }
426
427 #[must_use]
429 pub fn with_budget(mut self, budget: RunBudget) -> Self {
430 self.budget = budget;
431 self
432 }
433}
434
435#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445#[serde(rename_all = "camelCase")]
446#[non_exhaustive]
447pub struct TickProposal {
448 pub title: String,
450 pub rationale: String,
452}
453
454impl TickProposal {
455 pub fn new(title: impl Into<String>, rationale: impl Into<String>) -> Self {
457 Self { title: title.into(), rationale: rationale.into() }
458 }
459}
460
461#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
470#[serde(rename_all = "camelCase")]
471#[non_exhaustive]
472pub struct TickOutcome {
473 pub tick_id: String,
475 pub superseded: usize,
477 pub forgotten: usize,
479 pub merged: usize,
481 pub distilled: usize,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
485 pub refused: Option<String>,
486 pub spend: TickSpend,
488 #[serde(default, skip_serializing_if = "Vec::is_empty")]
490 pub proposals: Vec<TickProposal>,
491}
492
493impl TickOutcome {
494 pub fn new(tick_id: impl Into<String>) -> Self {
496 Self { tick_id: tick_id.into(), ..Self::default() }
497 }
498
499 #[must_use]
501 pub fn with_counts(
502 mut self,
503 superseded: usize,
504 forgotten: usize,
505 merged: usize,
506 distilled: usize,
507 ) -> Self {
508 self.superseded = superseded;
509 self.forgotten = forgotten;
510 self.merged = merged;
511 self.distilled = distilled;
512 self
513 }
514
515 #[must_use]
517 pub fn with_refused(mut self, reason: impl Into<String>) -> Self {
518 self.refused = Some(reason.into());
519 self
520 }
521
522 #[must_use]
524 pub fn with_spend(mut self, spend: TickSpend) -> Self {
525 self.spend = spend;
526 self
527 }
528
529 #[must_use]
531 pub fn with_proposal(mut self, proposal: TickProposal) -> Self {
532 self.proposals.push(proposal);
533 self
534 }
535}
536
537#[async_trait]
560pub trait Consolidator: Send + Sync {
561 async fn material(&self, partition: &PartitionId, now: DateTime<Utc>) -> Result<TickMaterial>;
564
565 async fn consolidate(&self, run: TickRun) -> Result<TickOutcome>;
568}
569
570#[derive(Debug, Clone)]
582#[non_exhaustive]
583pub struct TickInputs {
584 pub now: DateTime<Utc>,
586 pub material: TickMaterial,
588 pub busy: bool,
590 pub quiet_hours: Vec<QuietHours>,
592 pub daily_budget: RunBudget,
594 pub proactive_spent: u64,
596 pub proactive_model_calls: u64,
598 pub proactive_tokens: u64,
600}
601
602impl TickInputs {
603 pub fn new(now: DateTime<Utc>, material: TickMaterial) -> Self {
606 Self {
607 now,
608 material,
609 busy: false,
610 quiet_hours: Vec::new(),
611 daily_budget: RunBudget::new(),
612 proactive_spent: 0,
613 proactive_model_calls: 0,
614 proactive_tokens: 0,
615 }
616 }
617
618 #[must_use]
620 pub fn with_busy(mut self, busy: bool) -> Self {
621 self.busy = busy;
622 self
623 }
624
625 #[must_use]
627 pub fn with_quiet_hours(mut self, windows: impl IntoIterator<Item = QuietHours>) -> Self {
628 self.quiet_hours = windows.into_iter().collect();
629 self
630 }
631
632 #[must_use]
635 pub fn with_daily_budget(mut self, budget: RunBudget, spent_micro_usd: u64) -> Self {
636 self.daily_budget = budget;
637 self.proactive_spent = spent_micro_usd;
638 self
639 }
640
641 #[must_use]
657 pub fn with_proactive_calls_and_tokens(mut self, model_calls: u64, tokens: u64) -> Self {
658 self.proactive_model_calls = model_calls;
659 self.proactive_tokens = tokens;
660 self
661 }
662}
663
664#[derive(Debug, Clone, PartialEq)]
672#[non_exhaustive]
673pub enum TickAdmission {
674 Admit {
676 budget: RunBudget,
678 },
679 Mode,
681 NoMaterial,
683 NotDue {
685 next: Option<DateTime<Utc>>,
687 },
688 Interval {
690 until: DateTime<Utc>,
692 },
693 Busy,
695 Debounce {
697 until: DateTime<Utc>,
699 },
700 QuietHours {
702 until: DateTime<Utc>,
704 },
705 Budget,
707 Share,
709}
710
711impl TickAdmission {
712 pub fn reason(&self) -> &'static str {
715 match self {
716 Self::Admit { .. } => "admit",
717 Self::Mode => "mode",
718 Self::NoMaterial => "no_material",
719 Self::NotDue { .. } => "not_due",
720 Self::Interval { .. } => "interval",
721 Self::Busy => "busy",
722 Self::Debounce { .. } => "debounce",
723 Self::QuietHours { .. } => "quiet_hours",
724 Self::Budget => "budget",
725 Self::Share => "share",
726 }
727 }
728}
729
730fn chrono_of(duration: Duration) -> chrono::Duration {
731 chrono::Duration::from_std(duration).unwrap_or(chrono::Duration::MAX)
732}
733
734fn share_of(cap: u64, share: f32) -> u64 {
736 (cap as f64 * f64::from(share.clamp(0.0, 1.0))).floor() as u64
737}
738
739fn next_fire(expr: &str, after: DateTime<Utc>) -> Option<DateTime<Utc>> {
741 adk_core::schedule::ScheduleSpec::Cron { expr: expr.to_string(), timezone: "UTC".into() }
742 .next_after(after)
743 .ok()
744 .flatten()
745}
746
747pub fn admit_tick(tick: &ConsolidationTick, inputs: &TickInputs) -> TickAdmission {
780 let now = inputs.now;
781 let material = &inputs.material;
782 if matches!(material.mode, PartitionMode::ReadOnly | PartitionMode::Plan) {
783 return TickAdmission::Mode;
784 }
785 let quiet: Vec<&QuietHours> =
786 inputs.quiet_hours.iter().filter(|window| window.contains(now)).collect();
787 if !quiet.is_empty() {
788 let mut until = now;
790 for _ in 0..=inputs.quiet_hours.len() {
791 let next = inputs
792 .quiet_hours
793 .iter()
794 .map(|window| window.release_at(until))
795 .max()
796 .unwrap_or(until);
797 if next == until {
798 break;
799 }
800 until = next;
801 }
802 return TickAdmission::QuietHours { until };
803 }
804 let daily = &inputs.daily_budget;
805 let spent = material.spent_today;
806 if daily.max_cost_micro_usd.is_some_and(|cap| inputs.proactive_spent >= cap)
807 || daily.max_model_calls.is_some_and(|cap| inputs.proactive_model_calls >= cap)
808 || daily.max_total_tokens.is_some_and(|cap| inputs.proactive_tokens >= cap)
809 {
810 return TickAdmission::Budget;
811 }
812 let remaining = |cap: Option<u64>, used: u64| {
813 cap.map(|cap| share_of(cap, tick.budget_share).saturating_sub(used))
814 };
815 let cost = remaining(daily.max_cost_micro_usd, spent.cost_micro_usd);
816 let tokens = remaining(daily.max_total_tokens, spent.total_tokens);
817 let calls = remaining(daily.max_model_calls, spent.model_calls);
818 if [cost, tokens, calls].contains(&Some(0)) {
819 return TickAdmission::Share;
820 }
821 match &tick.schedule {
822 Some(expr) => {
823 let anchor = material.last_tick.unwrap_or(now - chrono::Duration::days(1));
824 let next = next_fire(expr, anchor);
825 if next.is_none_or(|next| next > now) {
826 return TickAdmission::NotDue { next };
827 }
828 }
829 None => {
830 if material.new_sessions < tick.min_new_sessions
831 && material.new_facts < tick.min_new_facts
832 {
833 return TickAdmission::NoMaterial;
834 }
835 if let Some(last) = material.last_tick {
836 let until = last + chrono_of(tick.min_interval);
837 if now < until {
838 return TickAdmission::Interval { until };
839 }
840 }
841 if inputs.busy {
842 return TickAdmission::Busy;
843 }
844 if let Some(active) = material.last_activity {
845 let until = active + chrono_of(tick.debounce);
846 if now < until {
847 return TickAdmission::Debounce { until };
848 }
849 }
850 }
851 }
852 let day_left = |cap: Option<u64>, used: u64| cap.map(|cap| cap.saturating_sub(used));
854 let tokens_left = day_left(daily.max_total_tokens, inputs.proactive_tokens);
855 let mut budget = RunBudget::new().max_total_tokens(
856 [tokens, tokens_left].into_iter().flatten().fold(tick.max_tokens_per_tick, u64::min),
857 );
858 if let Some(cost) = cost {
859 let day_left =
860 daily.max_cost_micro_usd.map_or(cost, |cap| cap.saturating_sub(inputs.proactive_spent));
861 budget = budget.max_cost_micro_usd(cost.min(day_left));
862 }
863 if let Some(calls) = calls {
864 let day_left = day_left(daily.max_model_calls, inputs.proactive_model_calls);
865 budget = budget.max_model_calls(day_left.map_or(calls, |left| calls.min(left)));
866 }
867 if daily.allow_unpriced_models {
868 budget = budget.allow_unpriced_models();
869 }
870 TickAdmission::Admit { budget }
871}
872
873#[derive(Debug, Clone, Serialize, Deserialize)]
875#[serde(rename_all = "camelCase")]
876struct TickInput {
877 partition: PartitionId,
878 user: String,
879 mode: PartitionMode,
880 sessions: Vec<String>,
881 tick: ConsolidationTick,
882 #[serde(with = "crate::serde_util::run_budget")]
883 budget: RunBudget,
884}
885
886pub(crate) struct ConsolidationExecutor {
890 sup: Arc<Supervision>,
891 consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
892 agenda: AgendaHandle,
893 user: Option<Arc<dyn WorkflowExecutor>>,
894}
895
896impl fmt::Debug for ConsolidationExecutor {
897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
898 f.debug_struct("ConsolidationExecutor")
899 .field("partitions", &self.consolidators.keys().collect::<Vec<_>>())
900 .finish_non_exhaustive()
901 }
902}
903
904impl ConsolidationExecutor {
905 pub(crate) fn new(
906 sup: Arc<Supervision>,
907 consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
908 agenda: AgendaHandle,
909 user: Option<Arc<dyn WorkflowExecutor>>,
910 ) -> Self {
911 Self { sup, consolidators, agenda, user }
912 }
913
914 async fn run_tick(
915 &self,
916 run_id: &str,
917 input: WorkflowState,
918 ) -> std::result::Result<Value, String> {
919 let input: TickInput = serde_json::from_value(Value::Object(input.into_iter().collect()))
920 .map_err(|error| {
921 format!(
922 "a `{CONSOLIDATION_TARGET}` run's input is not a tick the kernel spawned: {error}"
923 )
924 })?;
925 let now = self.sup.clock.now();
926 if self.sup.quiet_release(&input.partition, now).await > now {
928 return Ok(json!({ "tickId": run_id, "skipped": "quiet_hours" }));
929 }
930 let consolidator = self.consolidators.get(&input.partition).ok_or_else(|| {
931 format!("no consolidator is registered for partition {}", input.partition)
932 })?;
933 let run = TickRun::new(run_id, input.partition.clone(), &input.user, input.tick, now)
934 .with_sessions(input.sessions)
935 .with_budget(input.budget);
936 let outcome = consolidator.consolidate(run).await.map_err(|error| error.to_string())?;
937 let spend = SpendDelta::new(outcome.spend.cost_micro_usd)
939 .with_model_calls(outcome.spend.model_calls)
940 .with_total_tokens(outcome.spend.total_tokens);
941 if !spend.is_empty()
942 && let Err(error) = self
943 .sup
944 .processes
945 .add_spend(run_id, &input.partition, now.date_naive(), spend)
946 .await
947 {
948 tracing::warn!(process.pid = run_id, error = %error, "could not record a consolidation tick's spend");
949 }
950 let mut proposed = Vec::new();
951 if let Some(agenda) = self.agenda.get() {
952 for proposal in &outcome.proposals {
953 let item = AgendaItem::new(
954 format!("consolidation-{}", uuid::Uuid::new_v4()),
955 SubjectRef::human(input.user.clone()),
956 proposal.title.clone(),
957 proposal.rationale.clone(),
958 AgendaOrigin::Consolidation,
959 now,
960 )
961 .with_partition(input.partition.clone());
962 let id = item.id.clone();
963 match agenda.propose(item, input.mode).await {
964 Ok(_) => proposed.push(id),
965 Err(error) => {
966 tracing::warn!(error = %error, "could not file a consolidation proposal")
967 }
968 }
969 }
970 }
971 tracing::info!(
972 process.pid = run_id,
973 memory.superseded = outcome.superseded,
974 memory.forgotten = outcome.forgotten,
975 memory.merged = outcome.merged,
976 memory.distilled = outcome.distilled,
977 agenda.proposed = proposed.len(),
978 "consolidation tick finished"
979 );
980 Ok(json!({ "outcome": outcome, "proposed": proposed }))
981 }
982}
983
984#[async_trait]
985impl WorkflowExecutor for ConsolidationExecutor {
986 fn has_workflow(&self, workflow_id: &str) -> bool {
987 workflow_id == CONSOLIDATION_TARGET
988 || self.user.as_ref().is_some_and(|user| user.has_workflow(workflow_id))
989 }
990
991 async fn execute(
992 &self,
993 workflow_id: &str,
994 input: WorkflowState,
995 cancel_token: CancellationToken,
996 ) -> std::result::Result<Value, String> {
997 match &self.user {
998 Some(user) if workflow_id != CONSOLIDATION_TARGET => {
999 user.execute(workflow_id, input, cancel_token).await
1000 }
1001 _ => Err(format!("`{CONSOLIDATION_TARGET}` runs only as a durable run")),
1002 }
1003 }
1004
1005 async fn execute_durable(
1006 &self,
1007 workflow_id: &str,
1008 input: WorkflowState,
1009 run: WorkflowRunContext,
1010 ) -> std::result::Result<Value, String> {
1011 if workflow_id != CONSOLIDATION_TARGET {
1012 return match &self.user {
1013 Some(user) => user.execute_durable(workflow_id, input, run).await,
1014 None => Err(format!("no workflow `{workflow_id}`")),
1015 };
1016 }
1017 tokio::select! {
1018 result = self.run_tick(&run.run_id, input) => result,
1019 () = run.cancel.cancelled() => Err("the consolidation tick was cancelled".to_string()),
1020 }
1021 }
1022}
1023
1024#[derive(Clone)]
1027pub(crate) struct ConsolidationTicker {
1028 sup: Arc<Supervision>,
1029 processes: ProcessTable,
1030 consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
1031 evaluated: Arc<Mutex<BTreeMap<PartitionId, DateTime<Utc>>>>,
1032}
1033
1034impl ConsolidationTicker {
1035 pub(crate) fn new(
1036 sup: Arc<Supervision>,
1037 processes: ProcessTable,
1038 consolidators: Arc<BTreeMap<PartitionId, Arc<dyn Consolidator>>>,
1039 ) -> Self {
1040 Self { sup, processes, consolidators, evaluated: Arc::default() }
1041 }
1042
1043 async fn busy(&self, partition: &PartitionId) -> bool {
1046 for run in self.sup.running().await {
1047 if run.target == KERNEL_WAKE_TARGET {
1048 continue;
1049 }
1050 let meta =
1051 self.sup.stored_meta(&run).await.unwrap_or_else(|| Supervision::infer_meta(&run));
1052 if meta.partition == *partition {
1053 return true;
1054 }
1055 }
1056 false
1057 }
1058
1059 pub(crate) async fn tick(&self) {
1061 let Some(tick) = self.sup.proactivity.consolidation.clone() else {
1062 return;
1063 };
1064 if self.sup.governance.is_frozen() {
1065 return;
1066 }
1067 let now = self.sup.clock.now();
1068 for (partition, consolidator) in self.consolidators.iter() {
1069 {
1070 let mut evaluated = self.evaluated.lock().unwrap_or_else(|e| e.into_inner());
1071 if evaluated.get(partition).is_some_and(|at| now - *at < EVALUATE_EVERY) {
1072 continue;
1073 }
1074 evaluated.insert(partition.clone(), now);
1075 }
1076 if let Err(error) = self.evaluate(&tick, partition, consolidator.as_ref(), now).await {
1077 tracing::debug!(partition = %partition, error = %error, "consolidation tick not spawned");
1078 }
1079 }
1080 }
1081
1082 async fn evaluate(
1083 &self,
1084 tick: &ConsolidationTick,
1085 partition: &PartitionId,
1086 consolidator: &dyn Consolidator,
1087 now: DateTime<Utc>,
1088 ) -> Result<()> {
1089 let mut material = consolidator.material(partition, now).await?;
1090 material.mode = self.sup.area_mode(partition, material.mode).await;
1092 let daily = self.sup.proactivity.daily_budget.clone();
1093 let used = if daily.max_cost_micro_usd.is_some()
1094 || daily.max_model_calls.is_some()
1095 || daily.max_total_tokens.is_some()
1096 {
1097 self.sup.proactive_usage(partition).await
1098 } else {
1099 crate::stores::UsageTotals::default()
1100 };
1101 let quiet = self.sup.quiet_windows(partition).await;
1102 let inputs = TickInputs::new(now, material.clone())
1103 .with_busy(self.busy(partition).await)
1104 .with_quiet_hours(quiet)
1105 .with_daily_budget(daily, used.micro_usd)
1106 .with_proactive_calls_and_tokens(used.model_calls, used.total_tokens);
1107 let budget = match admit_tick(tick, &inputs) {
1108 TickAdmission::Admit { budget } => budget,
1109 held => {
1110 tracing::debug!(partition = %partition, admission = held.reason(), "consolidation tick held");
1111 return Ok(());
1112 }
1113 };
1114 let input = TickInput {
1115 partition: partition.clone(),
1116 user: material.user.clone(),
1117 mode: material.mode,
1118 sessions: material.sessions.clone(),
1119 tick: tick.clone(),
1120 budget,
1121 };
1122 let window = now.timestamp() / EVALUATE_EVERY.num_seconds().max(1);
1125 let last = material.last_tick.map_or(0, |at| at.timestamp_millis());
1126 let run = NewRun::new(
1127 QueueClass::MAINTENANCE,
1128 &self.sup.app_name,
1129 &material.user,
1130 CONSOLIDATION_TARGET,
1131 serde_json::to_value(&input)?,
1132 )
1133 .with_idempotency_key(format!("consolidation:{partition}:{last}:{window}"))
1134 .with_concurrency_key(format!("consolidation:{partition}"), OnConflict::Reject)
1135 .with_max_attempts(1)
1136 .with_service_subject();
1137 let spec = ProcessSpec::new(ProcessKind::Maintenance)
1138 .with_partition(partition.clone())
1139 .with_label(CONSOLIDATION_LABEL, "consolidation");
1140 let process = self.processes.spawn(run, spec).await?;
1141 self.sup.nudge();
1142 tracing::info!(partition = %partition, process.pid = %process.meta.pid, "consolidation tick spawned");
1143 Ok(())
1144 }
1145}
1146
1147#[cfg(test)]
1148mod tests {
1149 use chrono::TimeZone;
1150
1151 use super::*;
1152
1153 fn noon() -> DateTime<Utc> {
1154 Utc.with_ymd_and_hms(2026, 10, 23, 12, 0, 0).unwrap()
1155 }
1156
1157 fn minutes(n: i64) -> chrono::Duration {
1158 chrono::Duration::minutes(n)
1159 }
1160
1161 fn ready() -> TickMaterial {
1164 TickMaterial::new("alice", PartitionMode::Ask)
1165 .with_new_material(3, 0)
1166 .with_last_tick(noon() - minutes(7 * 60))
1167 .with_last_activity(noon() - minutes(60))
1168 }
1169
1170 fn decide(material: TickMaterial) -> TickAdmission {
1171 admit_tick(&ConsolidationTick::default(), &TickInputs::new(noon(), material))
1172 }
1173
1174 fn admitted(decision: &TickAdmission) -> bool {
1175 matches!(decision, TickAdmission::Admit { .. })
1176 }
1177
1178 #[test]
1179 fn the_admission_table() {
1180 let tick = ConsolidationTick::default();
1181 let six_hours = minutes(6 * 60);
1182 let cases: Vec<(&str, TickMaterial, TickAdmission)> = vec![
1183 (
1184 "new sessions at the threshold",
1185 ready(),
1186 TickAdmission::Admit {
1187 budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1188 },
1189 ),
1190 (
1191 "one session short, no facts",
1192 ready().with_new_material(2, 24),
1193 TickAdmission::NoMaterial,
1194 ),
1195 (
1196 "facts at the threshold",
1197 ready().with_new_material(0, 25),
1198 TickAdmission::Admit {
1199 budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1200 },
1201 ),
1202 (
1203 "interval one minute short",
1204 ready().with_last_tick(noon() - six_hours + minutes(1)),
1205 TickAdmission::Interval { until: noon() + minutes(1) },
1206 ),
1207 (
1208 "interval exactly passed",
1209 ready().with_last_tick(noon() - six_hours),
1210 TickAdmission::Admit {
1211 budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1212 },
1213 ),
1214 (
1215 "active 29 minutes ago",
1216 ready().with_last_activity(noon() - minutes(29)),
1217 TickAdmission::Debounce { until: noon() + minutes(1) },
1218 ),
1219 (
1220 "idle exactly 30 minutes",
1221 ready().with_last_activity(noon() - minutes(30)),
1222 TickAdmission::Admit {
1223 budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1224 },
1225 ),
1226 (
1227 "first tick ever",
1228 TickMaterial::new("alice", PartitionMode::Auto).with_new_material(3, 0),
1229 TickAdmission::Admit {
1230 budget: RunBudget::new().max_total_tokens(tick.max_tokens_per_tick),
1231 },
1232 ),
1233 (
1234 "read-only partition",
1235 TickMaterial { mode: PartitionMode::ReadOnly, ..ready() },
1236 TickAdmission::Mode,
1237 ),
1238 (
1239 "plan partition",
1240 TickMaterial { mode: PartitionMode::Plan, ..ready() },
1241 TickAdmission::Mode,
1242 ),
1243 ];
1244 for (name, material, expected) in cases {
1245 assert_eq!(decide(material), expected, "{name}");
1246 }
1247 let busy = admit_tick(&tick, &TickInputs::new(noon(), ready()).with_busy(true));
1248 assert_eq!(busy, TickAdmission::Busy, "a running process is activity");
1249 }
1250
1251 #[test]
1252 fn quiet_hours_hold_a_ready_tick_until_they_end() {
1253 let quiet: QuietHours = "11:00-13:00".parse().unwrap();
1254 let quiet = quiet.with_utc_offset_minutes(0);
1255 let inputs = TickInputs::new(noon(), ready()).with_quiet_hours([quiet]);
1256 assert_eq!(
1257 admit_tick(&ConsolidationTick::default(), &inputs),
1258 TickAdmission::QuietHours { until: noon() + minutes(60) }
1259 );
1260 let after = TickInputs::new(noon() + minutes(60), ready()).with_quiet_hours([quiet]);
1261 assert!(admitted(&admit_tick(&ConsolidationTick::default(), &after)));
1262 }
1263
1264 #[test]
1265 fn the_budget_share_bounds_the_tick() {
1266 let tick = ConsolidationTick::default().with_max_tokens_per_tick(50_000);
1267 let daily = RunBudget::new().max_cost_micro_usd(1_000_000).max_total_tokens(200_000);
1268 let spent = TickSpend::new(30_000, 5_000, 2);
1270 let inputs = TickInputs::new(noon(), ready().with_spent_today(spent))
1271 .with_daily_budget(daily.clone(), 400_000);
1272 assert_eq!(
1273 admit_tick(&tick, &inputs),
1274 TickAdmission::Admit {
1275 budget: RunBudget::new().max_total_tokens(15_000).max_cost_micro_usd(70_000)
1276 }
1277 );
1278 let tight = TickInputs::new(noon(), ready()).with_daily_budget(daily.clone(), 960_000);
1280 assert_eq!(
1281 admit_tick(&tick, &tight),
1282 TickAdmission::Admit {
1283 budget: RunBudget::new().max_total_tokens(20_000).max_cost_micro_usd(40_000)
1284 }
1285 );
1286 let spent_day =
1287 TickInputs::new(noon(), ready()).with_daily_budget(daily.clone(), 1_000_000);
1288 assert_eq!(admit_tick(&tick, &spent_day), TickAdmission::Budget);
1289 let share_spent =
1290 TickInputs::new(noon(), ready().with_spent_today(TickSpend::new(100_000, 0, 0)))
1291 .with_daily_budget(daily, 100_000);
1292 assert_eq!(admit_tick(&tick, &share_spent), TickAdmission::Share);
1293 let uncapped = TickInputs::new(noon(), ready());
1295 assert_eq!(
1296 admit_tick(&tick.with_max_tokens_per_tick(9_000), &uncapped),
1297 TickAdmission::Admit { budget: RunBudget::new().max_total_tokens(9_000) }
1298 );
1299 }
1300
1301 #[test]
1302 fn a_bare_schedule_replaces_material_interval_and_debounce() {
1303 let nightly = ConsolidationTick::default().with_schedule("0 3 * * *");
1304 let quiet = TickMaterial::new("alice", PartitionMode::Ask)
1305 .with_last_tick(Utc.with_ymd_and_hms(2026, 10, 22, 3, 0, 5).unwrap())
1306 .with_last_activity(noon() - minutes(1));
1307 assert_eq!(
1310 admit_tick(&nightly, &TickInputs::new(noon(), quiet.clone())),
1311 TickAdmission::Admit {
1312 budget: RunBudget::new().max_total_tokens(nightly.max_tokens_per_tick)
1313 },
1314 "today's 03:00 passed since yesterday's tick"
1315 );
1316 let ticked_today =
1317 quiet.with_last_tick(Utc.with_ymd_and_hms(2026, 10, 23, 3, 0, 5).unwrap());
1318 assert_eq!(
1319 admit_tick(&nightly, &TickInputs::new(noon(), ticked_today)),
1320 TickAdmission::NotDue {
1321 next: Some(Utc.with_ymd_and_hms(2026, 10, 24, 3, 0, 0).unwrap())
1322 }
1323 );
1324 let broken = ConsolidationTick::default().with_schedule("not cron");
1325 assert_eq!(
1326 admit_tick(&broken, &TickInputs::new(noon(), ready())),
1327 TickAdmission::NotDue { next: None }
1328 );
1329 }
1330}