1#[cfg(feature = "runner")]
18use std::collections::{HashMap, HashSet};
19use std::time::Duration;
20
21use adk_core::principal::SubjectRef;
22use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, RunBudget};
23use chrono::{DateTime, Utc};
24use serde::{Deserialize, Serialize};
25
26#[cfg(feature = "runner")]
27use super::index::cosine;
28use super::store::FactStore;
29#[cfg(feature = "runner")]
30use super::types::{FactKind, MemoryFact, fact_digest};
31use super::types::{FactScope, FactStatus};
32
33pub const CONSOLIDATION_CLUSTER_SCORE: f32 = 0.80;
42
43#[cfg(feature = "runner")]
45const CLUSTER_MAX_FACTS: usize = 8;
46
47#[derive(Clone, Debug, PartialEq)]
63pub struct ConsolidationConfig {
64 pub dedup_score: f32,
67 pub expire_confidence: f32,
69 pub assumed_ttl: Duration,
71 pub max_clusters_per_tick: usize,
73 pub max_loss_fraction: f32,
77 pub max_tokens_per_tick: u64,
79}
80
81impl Default for ConsolidationConfig {
82 fn default() -> Self {
83 Self {
84 dedup_score: 0.92,
85 expire_confidence: 0.5,
86 assumed_ttl: Duration::from_secs(90 * 24 * 60 * 60),
87 max_clusters_per_tick: 20,
88 max_loss_fraction: 0.25,
89 max_tokens_per_tick: 50_000,
90 }
91 }
92}
93
94#[derive(Clone, Debug, Default)]
110pub struct ConsolidationRequest {
111 pub tick_id: Option<String>,
113 pub partition: Option<String>,
115 pub sessions: Vec<String>,
117 pub config: ConsolidationConfig,
119 pub budget: Option<RunBudget>,
122 pub at: Option<DateTime<Utc>>,
124}
125
126impl ConsolidationRequest {
127 pub fn new() -> Self {
129 Self::default()
130 }
131
132 #[must_use]
134 pub fn with_tick_id(mut self, tick_id: impl Into<String>) -> Self {
135 self.tick_id = Some(tick_id.into());
136 self
137 }
138
139 #[must_use]
141 pub fn with_partition(mut self, partition: impl Into<String>) -> Self {
142 self.partition = Some(partition.into());
143 self
144 }
145
146 #[must_use]
148 pub fn with_sessions(mut self, sessions: impl IntoIterator<Item = impl Into<String>>) -> Self {
149 self.sessions = sessions.into_iter().map(Into::into).collect();
150 self
151 }
152
153 #[must_use]
155 pub fn with_config(mut self, config: ConsolidationConfig) -> Self {
156 self.config = config;
157 self
158 }
159
160 #[must_use]
162 pub fn with_budget(mut self, budget: RunBudget) -> Self {
163 self.budget = Some(budget);
164 self
165 }
166
167 #[must_use]
169 pub fn at(mut self, at: DateTime<Utc>) -> Self {
170 self.at = Some(at);
171 self
172 }
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum ChangeReason {
185 Duplicate,
187 Expired,
189 Merged,
191 Superseded,
193 Evicted,
195}
196
197impl ChangeReason {
198 pub fn as_str(self) -> &'static str {
200 match self {
201 Self::Duplicate => "duplicate",
202 Self::Expired => "expired",
203 Self::Merged => "merged",
204 Self::Superseded => "superseded",
205 Self::Evicted => "evicted",
206 }
207 }
208}
209
210#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
227#[serde(rename_all = "camelCase")]
228pub struct FactChange {
229 pub fact: String,
231 pub scope: FactScope,
233 pub to: FactStatus,
235 pub reason: ChangeReason,
237}
238
239#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(rename_all = "camelCase")]
250pub struct BesideKnown {
251 pub fact: String,
253 pub known: String,
255}
256
257#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
269#[serde(rename_all = "camelCase")]
270pub struct ConsolidationRecord {
271 pub tick_id: String,
273 pub app: String,
275 pub user: String,
277 pub partition: String,
279 pub at: DateTime<Utc>,
281 #[serde(default)]
283 pub scopes: Vec<FactScope>,
284 #[serde(default)]
286 pub sessions: Vec<String>,
287 #[serde(default)]
289 pub distilled: Vec<String>,
290 #[serde(default)]
292 pub merged: Vec<String>,
293 #[serde(default)]
295 pub changes: Vec<FactChange>,
296 #[serde(default)]
298 pub beside_known: Vec<BesideKnown>,
299 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub refused: Option<String>,
302 #[serde(default)]
304 pub model_calls: u64,
305 #[serde(default)]
307 pub total_tokens: u64,
308 #[serde(default)]
310 pub cost_micro_usd: u64,
311 #[serde(default, skip_serializing_if = "Option::is_none")]
314 pub finished_at: Option<DateTime<Utc>>,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
317 pub undone_at: Option<DateTime<Utc>>,
318}
319
320impl ConsolidationRecord {
321 pub fn new(
323 tick_id: impl Into<String>,
324 app: impl Into<String>,
325 user: impl Into<String>,
326 partition: impl Into<String>,
327 at: DateTime<Utc>,
328 ) -> Self {
329 Self {
330 tick_id: tick_id.into(),
331 app: app.into(),
332 user: user.into(),
333 partition: partition.into(),
334 at,
335 scopes: Vec::new(),
336 sessions: Vec::new(),
337 distilled: Vec::new(),
338 merged: Vec::new(),
339 changes: Vec::new(),
340 beside_known: Vec::new(),
341 refused: None,
342 model_calls: 0,
343 total_tokens: 0,
344 cost_micro_usd: 0,
345 finished_at: None,
346 undone_at: None,
347 }
348 }
349
350 pub fn superseded(&self) -> impl Iterator<Item = &FactChange> {
352 self.changes.iter().filter(|change| matches!(change.to, FactStatus::Superseded { .. }))
353 }
354
355 pub fn forgotten(&self) -> impl Iterator<Item = &FactChange> {
357 self.changes.iter().filter(|change| change.to == FactStatus::Forgotten)
358 }
359
360 pub fn written(&self) -> impl Iterator<Item = &String> {
362 self.distilled.iter().chain(&self.merged)
363 }
364}
365
366#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase")]
376pub struct ConsolidationUndo {
377 pub tick_id: String,
379 pub restored: Vec<String>,
381 pub forgotten: Vec<String>,
383 pub kept: Vec<String>,
385}
386
387fn invalid(code: &'static str, message: String) -> AdkError {
388 AdkError::new(ErrorComponent::Agent, ErrorCategory::InvalidInput, code, message)
389}
390
391pub async fn find_consolidation(
398 store: &dyn FactStore,
399 app: &str,
400 user: &str,
401 tick_id: &str,
402) -> Result<ConsolidationRecord> {
403 let wanted = tick_id.trim();
404 let records = store.consolidations(app, user).await?;
405 if let Some(record) = records.iter().find(|record| record.tick_id == wanted) {
406 return Ok(record.clone());
407 }
408 let upper = wanted.to_ascii_uppercase();
409 let mut matches = records.into_iter().filter(|record| {
410 !wanted.is_empty()
411 && (record.tick_id.starts_with(wanted) || record.tick_id.starts_with(&upper))
412 });
413 match (matches.next(), matches.next()) {
414 (Some(record), None) => Ok(record),
415 (None, _) => Err(AdkError::new(
416 ErrorComponent::Agent,
417 ErrorCategory::NotFound,
418 "harness.memory.tick_not_found",
419 format!(
420 "there is no consolidation tick '{wanted}'; `adk-rust memory list --source consolidation` lists them"
421 ),
422 )),
423 (Some(_), Some(_)) => Err(invalid(
424 "harness.memory.tick_not_found",
425 format!("'{wanted}' matches more than one consolidation tick; give more of the id"),
426 )),
427 }
428}
429
430pub async fn undo_consolidation(
452 store: &dyn FactStore,
453 app: &str,
454 user: &str,
455 tick_id: &str,
456 by: &SubjectRef,
457) -> Result<ConsolidationUndo> {
458 let mut record = find_consolidation(store, app, user, tick_id).await?;
459 if record.finished_at.is_none() {
460 return Err(AdkError::new(
461 ErrorComponent::Agent,
462 ErrorCategory::Conflict,
463 "harness.memory.tick_unfinished",
464 format!(
465 "consolidation tick '{}' has not finished; undo it once it has (a tick cut off \
466 is run again by its kernel)",
467 record.tick_id
468 ),
469 ));
470 }
471 if record.undone_at.is_some() {
472 return Err(AdkError::new(
473 ErrorComponent::Agent,
474 ErrorCategory::Conflict,
475 "harness.memory.tick_undone",
476 format!("consolidation tick '{}' was undone already", record.tick_id),
477 ));
478 }
479 let mut report = ConsolidationUndo { tick_id: record.tick_id.clone(), ..Default::default() };
480 for change in record.changes.iter().rev() {
482 let current = store.get(&change.fact).await?;
483 match current {
484 Some(fact) if fact.status == change.to => {
485 store.restore_assumed(&change.fact, by).await?;
486 report.restored.push(change.fact.clone());
487 }
488 _ => report.kept.push(change.fact.clone()),
489 }
490 }
491 for id in record.written() {
492 match store.get(id).await? {
493 Some(fact) if fact.status == FactStatus::Assumed => {
494 store.set_status(id, FactStatus::Forgotten, by).await?;
495 report.forgotten.push(id.clone());
496 }
497 _ => report.kept.push(id.clone()),
498 }
499 }
500 record.undone_at = Some(Utc::now());
501 store.put_consolidation(&record).await?;
502 Ok(report)
503}
504
505#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
517#[serde(rename_all = "camelCase")]
518pub struct SessionDistillation {
519 pub sessions: Vec<String>,
521 pub skipped: Vec<String>,
524 pub stored: Vec<String>,
526 pub rejected: usize,
528 pub changes: Vec<FactChange>,
531 pub beside_known: Vec<BesideKnown>,
533 pub model_calls: u64,
535 pub total_tokens: u64,
537 pub cost_micro_usd: u64,
539}
540
541#[cfg(feature = "runner")]
543#[derive(Clone, Debug, Default)]
544pub(crate) struct ScopeFacts {
545 pub(crate) live: Vec<MemoryFact>,
546 pub(crate) vectors: HashMap<String, Vec<f32>>,
547}
548
549#[cfg(feature = "runner")]
550impl ScopeFacts {
551 fn similarity(&self, a: &MemoryFact, b: &MemoryFact) -> Option<f32> {
552 cosine(self.vectors.get(&a.id)?, self.vectors.get(&b.id)?)
553 }
554}
555
556#[cfg(feature = "runner")]
558fn newest_first(facts: &mut [&MemoryFact]) {
559 facts.sort_by(|a, b| b.valid_from.cmp(&a.valid_from).then_with(|| b.id.cmp(&a.id)));
560}
561
562#[cfg(feature = "runner")]
566pub(crate) fn expires(fact: &MemoryFact, config: &ConsolidationConfig, now: DateTime<Utc>) -> bool {
567 let ttl = chrono::Duration::from_std(config.assumed_ttl).unwrap_or(chrono::Duration::MAX);
568 fact.status == FactStatus::Assumed
569 && fact.uses == 0
570 && fact.last_recalled.is_none()
571 && fact.confidence.is_some_and(|confidence| confidence < config.expire_confidence)
572 && now.signed_duration_since(fact.valid_from) > ttl
573}
574
575#[cfg(feature = "runner")]
580pub(crate) fn pass_one(
581 facts: &ScopeFacts,
582 config: &ConsolidationConfig,
583 now: DateTime<Utc>,
584) -> (Vec<FactChange>, Vec<MemoryFact>) {
585 let mut changes = Vec::new();
586 let mut assumed: Vec<&MemoryFact> =
587 facts.live.iter().filter(|fact| fact.status == FactStatus::Assumed).collect();
588 newest_first(&mut assumed);
589 let mut remaining = Vec::new();
590 for fact in assumed {
591 if expires(fact, config, now) {
592 changes.push(FactChange {
593 fact: fact.id.clone(),
594 scope: fact.scope.clone(),
595 to: FactStatus::Forgotten,
596 reason: ChangeReason::Expired,
597 });
598 } else {
599 remaining.push(fact);
600 }
601 }
602 let mut survivors: Vec<&MemoryFact> = Vec::new();
603 for fact in remaining {
604 let best = survivors
605 .iter()
606 .filter(|survivor| survivor.kind == fact.kind)
607 .filter_map(|survivor| Some((*survivor, facts.similarity(survivor, fact)?)))
608 .filter(|(_, score)| *score >= config.dedup_score)
609 .max_by(|a, b| a.1.total_cmp(&b.1));
610 match best {
611 Some((survivor, _)) => changes.push(FactChange {
612 fact: fact.id.clone(),
613 scope: fact.scope.clone(),
614 to: FactStatus::Superseded { by: survivor.id.clone() },
615 reason: ChangeReason::Duplicate,
616 }),
617 None => survivors.push(fact),
618 }
619 }
620 (changes, survivors.into_iter().cloned().collect())
621}
622
623#[cfg(feature = "runner")]
628pub(crate) fn clusters(
629 facts: &ScopeFacts,
630 survivors: &[MemoryFact],
631 config: &ConsolidationConfig,
632 limit: usize,
633) -> Vec<Vec<MemoryFact>> {
634 let mut ordered: Vec<&MemoryFact> = survivors.iter().collect();
635 newest_first(&mut ordered);
636 let mut taken = HashSet::new();
637 let mut out = Vec::new();
638 for (i, head) in ordered.iter().enumerate() {
639 if out.len() >= limit {
640 break;
641 }
642 if taken.contains(&head.id) {
643 continue;
644 }
645 let mut cluster = vec![(*head).clone()];
646 for other in &ordered[i + 1..] {
647 if cluster.len() >= CLUSTER_MAX_FACTS {
648 break;
649 }
650 if taken.contains(&other.id) || other.kind != head.kind {
651 continue;
652 }
653 let similar = facts.similarity(head, other).is_some_and(|score| {
654 (CONSOLIDATION_CLUSTER_SCORE..config.dedup_score).contains(&score)
655 });
656 if similar {
657 cluster.push((*other).clone());
658 }
659 }
660 if cluster.len() >= 2 {
661 taken.extend(cluster.iter().map(|fact| fact.id.clone()));
662 out.push(cluster);
663 }
664 }
665 out
666}
667
668#[cfg(feature = "runner")]
670#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
671pub(crate) struct MergeAnswer {
672 #[serde(default)]
673 pub(crate) merged_text: String,
674 #[serde(default)]
675 pub(crate) source_ids: Vec<String>,
676 #[serde(default)]
677 pub(crate) supersedes: Vec<String>,
678}
679
680#[cfg(feature = "runner")]
682#[derive(Clone, Debug, PartialEq)]
683pub(crate) enum PlannedMerge {
684 New {
686 kind: FactKind,
687 scope: FactScope,
688 text: String,
689 sources: Vec<MemoryFact>,
690 supersedes: Vec<String>,
691 },
692 Into { into: String, supersedes: Vec<String> },
694}
695
696#[cfg(feature = "runner")]
702pub(crate) fn plan_merge(
703 cluster: &[MemoryFact],
704 answer: &MergeAnswer,
705 text: Option<String>,
706 scope_live: &[MemoryFact],
707) -> Option<PlannedMerge> {
708 let text = text?;
709 let in_cluster = |id: &String| {
710 cluster.iter().any(|fact| fact.id == *id && fact.status == FactStatus::Assumed)
711 };
712 let mut sources: Vec<MemoryFact> = Vec::new();
713 for id in answer.source_ids.iter().filter(|id| in_cluster(id)) {
714 if !sources.iter().any(|fact| fact.id == *id) {
715 sources.extend(cluster.iter().find(|fact| fact.id == *id).cloned());
716 }
717 }
718 let mut supersedes: Vec<String> = Vec::new();
719 for id in &answer.supersedes {
720 if sources.iter().any(|fact| fact.id == *id) && !supersedes.contains(id) {
721 supersedes.push(id.clone());
722 }
723 }
724 let head = cluster.first()?;
725 let digest = fact_digest(&text);
726 if let Some(same) = sources.iter().find(|fact| fact.digest == digest) {
727 supersedes.retain(|id| *id != same.id);
728 return (!supersedes.is_empty())
729 .then(|| PlannedMerge::Into { into: same.id.clone(), supersedes });
730 }
731 if supersedes.is_empty() || scope_live.iter().any(|fact| fact.digest == digest) {
732 return None;
733 }
734 Some(PlannedMerge::New {
735 kind: head.kind,
736 scope: head.scope.clone(),
737 text,
738 sources,
739 supersedes,
740 })
741}
742
743#[cfg(feature = "runner")]
747pub(crate) fn loss_cap(live: usize, max_loss_fraction: f32) -> usize {
748 ((max_loss_fraction * live as f32).floor() as usize).max(1)
749}
750
751#[cfg(all(test, feature = "runner"))]
752mod tests {
753 use super::*;
754 use crate::facts::{FactSource, Provenance};
755
756 const DAY: i64 = 24 * 60 * 60;
757
758 fn fact(kind: FactKind, status: FactStatus, age_days: i64, now: DateTime<Utc>) -> MemoryFact {
759 let mut fact = MemoryFact::new(
760 FactScope::new("app", "alice", Some("p".into())),
761 kind,
762 format!("fact {}", uuid::Uuid::new_v4()),
763 status,
764 Provenance::new(FactSource::AgentInferred, "s", "i"),
765 );
766 fact.valid_from = now - chrono::Duration::days(age_days);
767 fact
768 }
769
770 fn pair(score: f32) -> (Vec<f32>, Vec<f32>) {
772 (vec![1.0, 0.0], vec![score, (1.0 - score * score).max(0.0).sqrt()])
773 }
774
775 fn scope(facts: Vec<(MemoryFact, Vec<f32>)>) -> ScopeFacts {
776 let mut out = ScopeFacts::default();
777 for (fact, vector) in facts {
778 out.vectors.insert(fact.id.clone(), vector);
779 out.live.push(fact);
780 }
781 out
782 }
783
784 #[test]
785 fn pass_one_supersedes_the_older_at_the_dedup_score_and_not_below() {
786 let now = Utc::now();
787 let config = ConsolidationConfig::default();
788 for (score, superseded) in [(0.92f32, true), (0.9199, false), (0.99, true)] {
789 let (a, b) = pair(score);
790 let older = fact(FactKind::ProjectFact, FactStatus::Assumed, 2, now);
791 let newer = fact(FactKind::ProjectFact, FactStatus::Assumed, 1, now);
792 let facts = scope(vec![(older.clone(), a), (newer.clone(), b)]);
793 let (changes, survivors) = pass_one(&facts, &config, now);
794 if superseded {
795 assert_eq!(
796 changes,
797 vec![FactChange {
798 fact: older.id.clone(),
799 scope: older.scope.clone(),
800 to: FactStatus::Superseded { by: newer.id.clone() },
801 reason: ChangeReason::Duplicate,
802 }],
803 "score {score}"
804 );
805 assert_eq!(survivors, vec![newer]);
806 } else {
807 assert!(changes.is_empty(), "score {score}: {changes:?}");
808 }
809 }
810 }
811
812 #[test]
813 fn pass_one_never_touches_known_facts_or_other_kinds() {
814 let now = Utc::now();
815 let (a, b) = pair(1.0);
816 let known = fact(FactKind::ProjectFact, FactStatus::Known, 400, now);
817 let twin = fact(FactKind::ProjectFact, FactStatus::Assumed, 1, now);
818 let other_kind = fact(FactKind::Decision, FactStatus::Assumed, 2, now);
819 let facts =
820 scope(vec![(known, a.clone()), (twin.clone(), b.clone()), (other_kind.clone(), a)]);
821 let (changes, survivors) = pass_one(&facts, &ConsolidationConfig::default(), now);
822 assert!(changes.is_empty(), "{changes:?}");
823 assert_eq!(survivors.len(), 2);
824 }
825
826 #[test]
827 fn expiry_holds_exactly_past_the_thresholds() {
828 let now = Utc::now();
829 let config = ConsolidationConfig::default();
830 let stale = |confidence: f32, age: chrono::Duration| {
831 let mut fact =
832 fact(FactKind::Outcome, FactStatus::Assumed, 0, now).with_confidence(confidence);
833 fact.valid_from = now - age;
834 fact
835 };
836 let ninety = chrono::Duration::seconds(90 * DAY);
837 let second = chrono::Duration::seconds(1);
838 assert!(expires(&stale(0.49, ninety + second), &config, now));
839 assert!(!expires(&stale(0.5, ninety + second), &config, now), "0.5 is not under 0.5");
840 assert!(!expires(&stale(0.49, ninety), &config, now), "90 days is not over 90 days");
841 let mut used = stale(0.1, ninety * 2);
842 used.uses = 1;
843 assert!(!expires(&used, &config, now));
844 let mut recalled = stale(0.1, ninety * 2);
845 recalled.last_recalled = Some(now);
846 assert!(!expires(&recalled, &config, now));
847 let mut unknown = stale(0.1, ninety * 2);
848 unknown.confidence = None;
849 assert!(!expires(&unknown, &config, now), "an unknown confidence is not a low one");
850 let mut known = stale(0.1, ninety * 2);
851 known.status = FactStatus::Known;
852 assert!(!expires(&known, &config, now));
853 }
854
855 #[test]
856 fn clusters_take_the_band_below_the_dedup_score() {
857 let now = Utc::now();
858 let config = ConsolidationConfig::default();
859 let head = fact(FactKind::Procedure, FactStatus::Assumed, 1, now);
860 let near = fact(FactKind::Procedure, FactStatus::Assumed, 2, now);
861 let far = fact(FactKind::Procedure, FactStatus::Assumed, 3, now);
862 let (a, b) = pair(0.85);
863 let (_, c) = pair(0.79);
864 let facts = scope(vec![(head.clone(), a), (near.clone(), b), (far, c)]);
865 let found = clusters(&facts, &facts.live, &config, 20);
866 assert_eq!(found, vec![vec![head, near]]);
867 assert!(clusters(&facts, &facts.live, &config, 0).is_empty());
868 }
869
870 #[test]
871 fn merges_stay_inside_their_cluster() {
872 let now = Utc::now();
873 let a = fact(FactKind::Procedure, FactStatus::Assumed, 1, now);
874 let b = fact(FactKind::Procedure, FactStatus::Assumed, 2, now);
875 let known = fact(FactKind::Procedure, FactStatus::Known, 3, now);
876 let cluster = vec![a.clone(), b.clone()];
877 let live = vec![a.clone(), b.clone(), known.clone()];
878 let answer = |supersedes: Vec<&str>| MergeAnswer {
879 merged_text: "merged".into(),
880 source_ids: vec![a.id.clone(), b.id.clone(), known.id.clone()],
881 supersedes: supersedes.into_iter().map(str::to_string).collect(),
882 };
883 let planned = plan_merge(
884 &cluster,
885 &answer(vec![&a.id, &b.id, &known.id]),
886 Some("merged".into()),
887 &live,
888 )
889 .unwrap();
890 let PlannedMerge::New { supersedes, .. } = planned else {
891 panic!("a new merged fact: {planned:?}");
892 };
893 assert_eq!(supersedes, [a.id.clone(), b.id.clone()], "never the known fact");
894 assert!(plan_merge(&cluster, &answer(vec![]), Some("merged".into()), &live).is_none());
895 assert!(plan_merge(&cluster, &answer(vec![&a.id]), None, &live).is_none(), "refused text");
896 let same = plan_merge(&cluster, &answer(vec![&a.id, &b.id]), Some(a.text.clone()), &live);
897 assert_eq!(
898 same,
899 Some(PlannedMerge::Into { into: a.id.clone(), supersedes: vec![b.id.clone()] })
900 );
901 assert!(
902 plan_merge(&cluster, &answer(vec![&a.id]), Some(known.text.clone()), &live).is_none(),
903 "a text a live fact already holds"
904 );
905 }
906
907 #[test]
908 fn the_loss_cap_is_a_share_of_live_facts_and_at_least_one() {
909 let caps: Vec<usize> =
910 [0, 2, 3, 4, 7, 8, 10, 100].into_iter().map(|live| loss_cap(live, 0.25)).collect();
911 assert_eq!(caps, vec![1, 1, 1, 1, 1, 2, 2, 25]);
912 assert_eq!((loss_cap(10, 0.7), loss_cap(10, 0.0), loss_cap(10, 1.0)), (7, 1, 10));
913 }
914}
915
916#[cfg(feature = "runner")]
917mod tick {
918 use std::sync::Arc;
919
920 use adk_core::audit_log::AuditActor;
921 use adk_core::{BudgetTracker, Result, RunBudget};
922 use chrono::{DateTime, Utc};
923 use serde_json::json;
924
925 use super::{
926 ChangeReason, ConsolidationRecord, ConsolidationRequest, FactChange, PlannedMerge,
927 ScopeFacts, SessionDistillation, clusters, loss_cap, pass_one, plan_merge,
928 };
929 use crate::audit::HarnessAudit;
930 use crate::facts::runtime::{FactsRuntime, harness_subject};
931 use crate::facts::types::{
932 FactFilter, FactScope, FactSource, FactStatus, MemoryFact, Provenance, new_fact_id,
933 };
934 use crate::facts::writer::TickWrites;
935
936 struct ScopePlan {
938 facts: ScopeFacts,
939 changes: Vec<FactChange>,
940 clusters: Vec<Vec<MemoryFact>>,
941 merges: Vec<PlannedMerge>,
942 }
943
944 fn not_live(error: &adk_core::AdkError) -> bool {
945 error.code == "harness.memory.fact_not_live"
946 }
947
948 impl FactsRuntime {
949 pub(crate) async fn distill_sessions(
951 &self,
952 app: &str,
953 user: &str,
954 sessions: &[String],
955 now: DateTime<Utc>,
956 budget: Option<RunBudget>,
957 ) -> Result<SessionDistillation> {
958 let _one_at_a_time = self.distilling.lock().await;
959 let parent = budget.map(|budget| Arc::new(BudgetTracker::new(budget)));
960 self.distill_unreached(app, user, sessions, now, &TickWrites::new(None), parent).await
961 }
962
963 async fn scope_facts(&self, scope: &FactScope) -> Result<ScopeFacts> {
967 let live = self
968 .store
969 .list(FactFilter { live_only: true, ..FactFilter::exactly(scope) })
970 .await?;
971 let stored = self.store.embeddings(scope).await?;
972 let id = match &self.embedder {
973 Some(embedder) => crate::facts::embedder_id(embedder.as_ref()),
974 None => {
975 let mut counts: std::collections::BTreeMap<&str, usize> =
976 std::collections::BTreeMap::new();
977 for (_, embedding) in &stored {
978 *counts.entry(embedding.embedder.as_str()).or_default() += 1;
979 }
980 let most = counts.iter().max_by_key(|(_, count)| **count);
981 most.map(|(id, _)| (*id).to_string()).unwrap_or_default()
982 }
983 };
984 let mut vectors: std::collections::HashMap<String, Vec<f32>> = stored
985 .into_iter()
986 .filter(|(_, embedding)| embedding.is_from(&id))
987 .map(|(fact, embedding)| (fact, embedding.vector))
988 .collect();
989 if let Some(embedder) = &self.embedder {
990 let dimensions = embedder.dimensions();
991 let missing: Vec<&MemoryFact> = live
992 .iter()
993 .filter(|fact| fact.status == FactStatus::Assumed)
994 .filter(|fact| {
995 vectors.get(&fact.id).is_none_or(|vector| {
996 vector.is_empty() || (dimensions > 0 && vector.len() != dimensions)
997 })
998 })
999 .collect();
1000 if !missing.is_empty() {
1001 let texts: Vec<String> = missing.iter().map(|fact| fact.text.clone()).collect();
1002 match embedder.embed(&texts).await {
1003 Ok(embedded) => {
1004 for (fact, vector) in missing.into_iter().zip(embedded) {
1005 let embedding =
1006 crate::facts::FactEmbedding::new(id.clone(), vector.clone());
1007 if let Err(error) =
1008 self.store.put_embedding(&fact.id, embedding).await
1009 {
1010 tracing::debug!(error = %error, "could not store a fact embedding");
1011 }
1012 vectors.insert(fact.id.clone(), vector);
1013 }
1014 }
1015 Err(error) => tracing::warn!(
1016 error = %error,
1017 "fact embedding failed; consolidation compares the stored vectors only"
1018 ),
1019 }
1020 }
1021 }
1022 Ok(ScopeFacts { live, vectors })
1023 }
1024
1025 fn tick_audit(&self, app: &str, user: &str, tick_id: &str) -> Option<HarnessAudit> {
1027 self.outside_trail().map(|trail| {
1028 HarnessAudit::new(
1029 trail,
1030 AuditActor::for_invocation(
1031 app,
1032 &format!("{}-consolidator", self.root_agent),
1033 user,
1034 tick_id,
1035 ),
1036 String::new(),
1037 )
1038 })
1039 }
1040
1041 pub(crate) async fn consolidate(
1047 &self,
1048 app: &str,
1049 user: &str,
1050 request: ConsolidationRequest,
1051 ) -> Result<ConsolidationRecord> {
1052 let config = request.config.clone();
1053 let now = request.at.unwrap_or_else(Utc::now);
1054 let tick_id = request
1055 .tick_id
1056 .clone()
1057 .filter(|id| !id.trim().is_empty())
1058 .unwrap_or_else(new_fact_id);
1059 let partition = request.partition.clone().unwrap_or_else(|| "default".to_string());
1060 let _one_at_a_time = self.distilling.lock().await;
1061 let mut record = ConsolidationRecord::new(&tick_id, app, user, &partition, now);
1062 let project = self.scope(app, user);
1063 record.scopes = if self.confined {
1065 vec![project.clone()]
1066 } else {
1067 vec![project.clone(), project.user_wide()]
1068 };
1069 self.store.put_consolidation(&record).await?;
1071
1072 let budget = request.budget.clone().unwrap_or_default();
1073 let tokens = budget
1074 .max_total_tokens
1075 .map_or(config.max_tokens_per_tick, |cap| cap.min(config.max_tokens_per_tick));
1076 let tracker = Arc::new(BudgetTracker::new(budget.max_total_tokens(tokens)));
1077
1078 let writes = TickWrites::new(Some(tick_id.clone()));
1080 let distilled = self
1081 .distill_unreached(
1082 app,
1083 user,
1084 &request.sessions,
1085 now,
1086 &writes,
1087 Some(tracker.clone()),
1088 )
1089 .await?;
1090 record.sessions = distilled.sessions;
1091 record.distilled = distilled.stored;
1092 record.changes = distilled.changes;
1093 record.beside_known = distilled.beside_known;
1094
1095 let mut plans = Vec::with_capacity(record.scopes.len());
1097 let mut cluster_room = config.max_clusters_per_tick;
1098 for scope in &record.scopes {
1099 let facts = self.scope_facts(scope).await?;
1100 let (changes, survivors) = pass_one(&facts, &config, now);
1101 let clusters = clusters(&facts, &survivors, &config, cluster_room);
1102 cluster_room = cluster_room.saturating_sub(clusters.len());
1103 plans.push(ScopePlan { facts, changes, clusters, merges: Vec::new() });
1104 }
1105
1106 'pass_two: for plan in &mut plans {
1108 for cluster in std::mem::take(&mut plan.clusters) {
1109 if tracker.check().is_err() {
1110 break 'pass_two;
1111 }
1112 match self.run_merge(user, &cluster, Some(tracker.clone())).await {
1113 Ok((answer, _)) => {
1114 let text = Some(answer.merged_text.trim())
1115 .filter(|text| !text.is_empty())
1116 .and_then(|text| {
1117 crate::facts::redact::redact_fact_text(
1118 text,
1119 self.config.max_fact_chars,
1120 )
1121 .ok()
1122 });
1123 plan.merges.extend(plan_merge(
1124 &cluster,
1125 &answer,
1126 text,
1127 &plan.facts.live,
1128 ));
1129 }
1130 Err(error) => {
1131 tracing::warn!(error = %error, "a consolidation merge failed; its facts stay as they are");
1132 if tracker.check().is_err() {
1133 break 'pass_two;
1134 }
1135 }
1136 }
1137 }
1138 }
1139
1140 for plan in &plans {
1144 let live = plan.facts.live.len();
1145 let lost = plan.changes.len()
1146 + plan
1147 .merges
1148 .iter()
1149 .map(|merge| match merge {
1150 PlannedMerge::New { supersedes, .. } => {
1151 supersedes.len().saturating_sub(1)
1152 }
1153 PlannedMerge::Into { supersedes, .. } => supersedes.len(),
1154 })
1155 .sum::<usize>();
1156 let cap = loss_cap(live, config.max_loss_fraction);
1157 if lost > cap {
1158 record.refused = Some(format!(
1159 "the passes would lose {lost} of the {live} live facts of one scope, \
1160 more than the {cap} max_loss_fraction {} allows",
1161 config.max_loss_fraction
1162 ));
1163 break;
1164 }
1165 }
1166
1167 let audit = self.tick_audit(app, user, &tick_id);
1168 if record.refused.is_none() {
1169 self.apply(&mut record, plans, audit.as_ref(), now).await?;
1170 }
1171 let usage = tracker.usage();
1172 record.model_calls = usage.model_calls;
1173 record.total_tokens = usage.total_tokens;
1174 record.cost_micro_usd = usage.cost_micro_usd;
1175 record.finished_at = Some(Utc::now());
1176 self.store.put_consolidation(&record).await?;
1177 if let Some(audit) = &audit {
1178 let ids = |changes: Vec<&FactChange>| {
1179 changes.into_iter().map(|change| change.fact.clone()).collect::<Vec<_>>()
1180 };
1181 let superseded = ids(record.superseded().collect());
1182 let forgotten = ids(record.forgotten().collect());
1183 audit
1184 .record(
1185 "harness.memory.consolidated",
1186 json!({
1187 "tickId": record.tick_id,
1188 "partition": record.partition,
1189 "scope": project.project,
1190 "superseded": superseded,
1191 "forgotten": forgotten,
1192 "merged": record.merged,
1193 "distilled": record.distilled,
1194 "besideKnown": record
1195 .beside_known
1196 .iter()
1197 .map(|beside| json!({ "fact": beside.fact, "known": beside.known }))
1198 .collect::<Vec<_>>(),
1199 "sessions": record.sessions.len(),
1200 "counts": {
1201 "superseded": superseded.len(),
1202 "forgotten": forgotten.len(),
1203 "merged": record.merged.len(),
1204 "distilled": record.distilled.len(),
1205 },
1206 "refused": record.refused.is_some(),
1207 "modelCalls": record.model_calls,
1208 "tokens": record.total_tokens,
1209 "cost": record.cost_micro_usd,
1210 }),
1211 )
1212 .await?;
1213 }
1214 tracing::info!(
1215 memory.tick = %record.tick_id,
1216 memory.superseded = record.superseded().count(),
1217 memory.forgotten = record.forgotten().count(),
1218 memory.merged = record.merged.len(),
1219 memory.distilled = record.distilled.len(),
1220 memory.refused = record.refused.is_some(),
1221 "memory consolidated"
1222 );
1223 Ok(record)
1224 }
1225
1226 async fn apply(
1229 &self,
1230 record: &mut ConsolidationRecord,
1231 plans: Vec<ScopePlan>,
1232 audit: Option<&HarnessAudit>,
1233 now: DateTime<Utc>,
1234 ) -> Result<()> {
1235 let tick_id = record.tick_id.clone();
1236 let mut pass_one: Vec<(MemoryFact, FactChange)> = Vec::new();
1237 let mut merges: Vec<(Option<MemoryFact>, String, Vec<MemoryFact>)> = Vec::new();
1239 for plan in plans {
1240 let live =
1241 |id: &String| plan.facts.live.iter().find(|fact| fact.id == *id).cloned();
1242 for change in plan.changes {
1243 pass_one.extend(live(&change.fact).map(|fact| (fact, change)));
1244 }
1245 for merge in plan.merges {
1246 match merge {
1247 PlannedMerge::New { kind, scope, text, sources, supersedes } => {
1248 let mut provenance =
1249 Provenance::new(FactSource::AgentInferred, "", tick_id.clone());
1250 provenance.at = now;
1251 provenance.source_ids =
1252 sources.iter().map(|source| source.id.clone()).collect();
1253 provenance.tick = Some(tick_id.clone());
1254 let mut fact =
1255 MemoryFact::new(scope, kind, text, FactStatus::Assumed, provenance);
1256 fact.confidence = sources
1257 .iter()
1258 .filter_map(|source| source.confidence)
1259 .reduce(f32::max);
1260 fact.uses = sources
1261 .iter()
1262 .fold(0u32, |uses, source| uses.saturating_add(source.uses));
1263 fact.last_recalled =
1264 sources.iter().filter_map(|source| source.last_recalled).max();
1265 let target = fact.id.clone();
1266 let superseded = supersedes.iter().filter_map(live).collect();
1267 merges.push((Some(fact), target, superseded));
1268 }
1269 PlannedMerge::Into { into, supersedes } => {
1270 merges.push((None, into, supersedes.iter().filter_map(live).collect()));
1271 }
1272 }
1273 }
1274 }
1275 let merged = |fact: &MemoryFact, target: &str| FactChange {
1276 fact: fact.id.clone(),
1277 scope: fact.scope.clone(),
1278 to: FactStatus::Superseded { by: target.to_string() },
1279 reason: ChangeReason::Merged,
1280 };
1281
1282 let mut planned = record.clone();
1284 planned.changes.extend(pass_one.iter().map(|(_, change)| change.clone()));
1285 for (new, target, superseded) in &merges {
1286 planned.merged.extend(new.as_ref().map(|fact| fact.id.clone()));
1287 planned.changes.extend(superseded.iter().map(|fact| merged(fact, target)));
1288 }
1289 self.store.put_consolidation(&planned).await?;
1290
1291 let by = harness_subject();
1292 let mut changes = pass_one;
1293 for (new, target, superseded) in merges {
1294 let target = match new {
1295 Some(fact) => {
1296 if let Some(audit) = audit {
1297 audit
1298 .record(
1299 "harness.memory.fact.stored",
1300 json!({
1301 "factId": fact.id,
1302 "kind": fact.kind.as_str(),
1303 "status": fact.status.label(),
1304 "source": fact.provenance.source.as_str(),
1305 "project": fact.scope.project,
1306 "digest": fact.digest,
1307 "sessionId": "",
1308 "tickId": tick_id,
1309 "sourceIds": fact.provenance.source_ids,
1310 }),
1311 )
1312 .await?;
1313 }
1314 let stored = self.store.put(fact).await?;
1315 if let Err(error) = self.index.upsert(&stored).await {
1316 tracing::warn!(error = %error, "could not index a fact; recall by search may miss it");
1317 }
1318 record.merged.push(stored.id.clone());
1319 stored.id
1320 }
1321 None => target,
1322 };
1323 changes.extend(superseded.into_iter().map(|fact| {
1324 let change = merged(&fact, &target);
1325 (fact, change)
1326 }));
1327 }
1328 for (fact, change) in changes {
1329 let reason = change.reason.as_str();
1330 match self
1331 .change_status_in(
1332 audit,
1333 &fact,
1334 change.to.clone(),
1335 &by,
1336 Some((&tick_id, reason)),
1337 )
1338 .await
1339 {
1340 Ok(()) => record.changes.push(change),
1341 Err(error) if not_live(&error) => {}
1342 Err(error) => return Err(error),
1343 }
1344 }
1345 Ok(())
1346 }
1347 }
1348}