Skip to main content

gemini_memory_rs/ingestion/
ledger.rs

1//! The session candidate ledger.
2//!
3//! Observations accumulate here before anything becomes canonical. The ledger
4//! is what makes a crash survivable, what turns three mentions of the same
5//! thing into one candidate with three pieces of evidence, and what
6//! consolidation reads at the end of a session.
7
8use async_trait::async_trait;
9use chrono::{DateTime, Datelike, Utc};
10use parking_lot::RwLock;
11use serde::{Deserialize, Serialize};
12use std::collections::{BTreeMap, HashSet};
13
14use crate::core::{
15    AdmissionVerdict, DiscardReason, Explicitness, FactFingerprint, IngestionConfig, MemoryError,
16    MemoryKind, MemoryObservation, MemoryValue, MutationIntent, ObservationId, ProposedPersistence,
17    SensitivityClass, SessionId, TemporalScope, TurnId, admit_observation, aggregate_confidence,
18};
19
20/// Where a candidate stands within the session.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum SessionCandidateStatus {
24    /// Seen once; not yet trusted enough to answer with.
25    Observed,
26    /// Usable in this conversation.
27    ActiveSessionFact,
28    /// Will be offered to post-session reconciliation.
29    StagedForReconciliation,
30    /// Contradicted by something the user said later in the session.
31    Suppressed,
32    /// Refused by policy.
33    Rejected,
34    /// An explicit command awaiting durable commit.
35    PendingExplicitCommit,
36}
37
38impl SessionCandidateStatus {
39    /// Whether a candidate in this state may be retrieved during the session.
40    pub fn is_usable(self) -> bool {
41        matches!(
42            self,
43            Self::ActiveSessionFact | Self::StagedForReconciliation | Self::PendingExplicitCommit
44        )
45    }
46}
47
48/// One piece of evidence behind a candidate.
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50pub struct ObservationEvidence {
51    /// Which observation.
52    pub observation_id: ObservationId,
53    /// Which turn it came from.
54    pub turn_id: TurnId,
55    /// How directly it was stated.
56    pub explicitness: Explicitness,
57    /// Extractor confidence.
58    pub confidence: f32,
59    /// The utterance behind it.
60    pub utterance: String,
61    /// When it was observed.
62    pub observed_at: DateTime<Utc>,
63}
64
65/// A proposed memory accumulating evidence within a session.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct SessionCandidate {
68    /// Deduplication key.
69    pub fingerprint: FactFingerprint,
70    /// Subject of the fact.
71    pub subject: crate::core::EntityRef,
72    /// Canonical predicate.
73    pub predicate: crate::core::CanonicalPredicate,
74    /// Value side.
75    pub value: MemoryValue,
76    /// Natural-language rendering.
77    pub canonical_statement: String,
78    /// Proposed kind.
79    pub kind: MemoryKind,
80    /// Expected persistence.
81    pub temporal_scope: TemporalScope,
82    /// Supporting evidence.
83    pub evidence: Vec<ObservationEvidence>,
84    /// Distinct turns that produced evidence.
85    pub distinct_turns: usize,
86    /// First turn the candidate appeared on.
87    pub first_seen_turn: TurnId,
88    /// Most recent turn the candidate appeared on.
89    pub last_seen_turn: TurnId,
90    /// Aggregated confidence.
91    pub confidence: f32,
92    /// Strongest explicitness across the evidence.
93    pub explicitness: Explicitness,
94    /// Retention policy assigned at admission.
95    pub proposed_persistence: ProposedPersistence,
96    /// Lifecycle state.
97    pub status: SessionCandidateStatus,
98    /// Explicit command carried by the evidence, if any.
99    pub mutation_intent: Option<MutationIntent>,
100    /// Terms this fact may later be searched by, merged across its evidence.
101    pub search_terms: Vec<String>,
102    /// Privacy classification, carried from the observation.
103    ///
104    /// Dropping this here would let an explicit health or religious statement
105    /// reach the corpus with ordinary privacy metadata, silently bypassing
106    /// every sensitivity-dependent rule downstream.
107    pub sensitivity: SensitivityClass,
108    /// When the fact stops holding, for episodic candidates.
109    pub expected_expiry: Option<DateTime<Utc>>,
110}
111
112impl SessionCandidate {
113    fn from_observation(
114        observation: &MemoryObservation,
115        persistence: ProposedPersistence,
116        now: DateTime<Utc>,
117    ) -> Self {
118        let evidence = ObservationEvidence {
119            observation_id: observation.observation_id.clone(),
120            turn_id: observation.turn_id,
121            explicitness: observation.explicitness,
122            confidence: observation.confidence,
123            utterance: observation.transcript_evidence.utterance.clone(),
124            observed_at: now,
125        };
126        let status = status_for(persistence, observation);
127        Self {
128            fingerprint: observation.fingerprint(),
129            subject: observation.subject.clone(),
130            predicate: observation.predicate.clone(),
131            value: observation.value.clone(),
132            canonical_statement: observation.canonical_statement.clone(),
133            kind: observation.kind,
134            temporal_scope: observation.temporal_scope,
135            evidence: vec![evidence],
136            distinct_turns: 1,
137            first_seen_turn: observation.turn_id,
138            last_seen_turn: observation.turn_id,
139            confidence: observation.confidence,
140            explicitness: observation.explicitness,
141            proposed_persistence: persistence,
142            status,
143            mutation_intent: observation.mutation_intent,
144            search_terms: observation.search_terms.clone(),
145            sensitivity: observation.sensitivity,
146            expected_expiry: observation.expected_expiry,
147        }
148    }
149
150    fn absorb(&mut self, observation: &MemoryObservation, now: DateTime<Utc>) {
151        if self
152            .evidence
153            .iter()
154            .any(|e| e.observation_id == observation.observation_id)
155        {
156            return;
157        }
158        let new_turn = observation.turn_id != self.last_seen_turn;
159        self.evidence.push(ObservationEvidence {
160            observation_id: observation.observation_id.clone(),
161            turn_id: observation.turn_id,
162            explicitness: observation.explicitness,
163            confidence: observation.confidence,
164            utterance: observation.transcript_evidence.utterance.clone(),
165            observed_at: now,
166        });
167        if new_turn {
168            self.distinct_turns += 1;
169        }
170        self.last_seen_turn = observation.turn_id;
171        self.explicitness = self.explicitness.max(observation.explicitness);
172        self.confidence = aggregate_confidence(
173            &self
174                .evidence
175                .iter()
176                .map(|e| (e.confidence, e.explicitness))
177                .collect::<Vec<_>>(),
178        );
179        if observation.mutation_intent.is_some() {
180            self.mutation_intent = observation.mutation_intent;
181        }
182        // The most restrictive classification any evidence carried wins.
183        self.sensitivity = self.sensitivity.max(observation.sensitivity);
184        // Search terms accumulate: each restatement may add the vocabulary of
185        // a different language or a different way of asking.
186        for term in &observation.search_terms {
187            if !self
188                .search_terms
189                .iter()
190                .any(|t| t.eq_ignore_ascii_case(term))
191            {
192                self.search_terms.push(term.clone());
193            }
194        }
195        if self.status == SessionCandidateStatus::Observed && self.explicitness.is_explicit() {
196            self.status = SessionCandidateStatus::ActiveSessionFact;
197        }
198    }
199
200    /// Distinct calendar days the evidence spans.
201    pub fn distinct_days(&self) -> u32 {
202        self.evidence
203            .iter()
204            .map(|e| (e.observed_at.year(), e.observed_at.ordinal()))
205            .collect::<HashSet<_>>()
206            .len() as u32
207    }
208
209    /// The `subject|predicate` window used to find contradictions.
210    pub fn subject_predicate(&self) -> &str {
211        self.fingerprint.subject_predicate()
212    }
213}
214
215fn status_for(
216    persistence: ProposedPersistence,
217    observation: &MemoryObservation,
218) -> SessionCandidateStatus {
219    if observation.mutation_intent.is_some() {
220        return SessionCandidateStatus::PendingExplicitCommit;
221    }
222    match persistence {
223        ProposedPersistence::Durable | ProposedPersistence::Episodic => {
224            SessionCandidateStatus::ActiveSessionFact
225        }
226        ProposedPersistence::SessionOnly => SessionCandidateStatus::ActiveSessionFact,
227        ProposedPersistence::Staged => SessionCandidateStatus::Observed,
228        ProposedPersistence::Discard => SessionCandidateStatus::Rejected,
229    }
230}
231
232/// What happened when an observation was offered to the ledger.
233#[derive(Debug, Clone, PartialEq)]
234pub enum LedgerOutcome {
235    /// A new candidate was created.
236    Created(FactFingerprint),
237    /// Evidence was added to an existing candidate.
238    Reinforced {
239        /// The candidate reinforced.
240        fingerprint: FactFingerprint,
241        /// Evidence count after the merge.
242        evidence_count: usize,
243    },
244    /// The observation was refused by policy.
245    Rejected(DiscardReason),
246}
247
248/// A ledger sealed against further writes.
249#[derive(Debug, Clone)]
250pub struct SealedSessionLedger {
251    /// The session it belongs to.
252    pub session_id: SessionId,
253    /// Candidates carried into consolidation.
254    pub candidates: Vec<SessionCandidate>,
255    /// When it was sealed.
256    pub sealed_at: DateTime<Utc>,
257}
258
259/// A snapshot of the ledger mid-session.
260#[derive(Debug, Clone)]
261pub struct SessionLedgerSnapshot {
262    /// The session it belongs to.
263    pub session_id: SessionId,
264    /// Every candidate, in fingerprint order.
265    pub candidates: Vec<SessionCandidate>,
266    /// Ledger revision.
267    pub revision: u64,
268}
269
270/// Accumulates observations for a logical session.
271#[async_trait]
272pub trait SessionLedger: Send + Sync {
273    /// Offer an observation to the ledger.
274    async fn append_observation(
275        &self,
276        observation: MemoryObservation,
277    ) -> Result<LedgerOutcome, MemoryError>;
278
279    /// Read the current candidate set.
280    async fn snapshot(&self) -> Result<SessionLedgerSnapshot, MemoryError>;
281
282    /// Close the ledger and hand its candidates to consolidation.
283    async fn seal(&self) -> Result<SealedSessionLedger, MemoryError>;
284}
285
286/// The in-process ledger.
287#[derive(Debug)]
288pub struct InMemorySessionLedger {
289    session_id: SessionId,
290    config: IngestionConfig,
291    inner: RwLock<LedgerState>,
292}
293
294#[derive(Debug, Default)]
295struct LedgerState {
296    candidates: BTreeMap<FactFingerprint, SessionCandidate>,
297    revision: u64,
298    sealed: bool,
299}
300
301impl InMemorySessionLedger {
302    /// A ledger for one session.
303    pub fn new(session_id: SessionId, config: IngestionConfig) -> Self {
304        Self {
305            session_id,
306            config,
307            inner: RwLock::new(LedgerState::default()),
308        }
309    }
310
311    /// The session this ledger belongs to.
312    pub fn session_id(&self) -> &SessionId {
313        &self.session_id
314    }
315
316    /// The ledger revision, bumped on every accepted observation.
317    pub fn revision(&self) -> u64 {
318        self.inner.read().revision
319    }
320
321    /// How many candidates are held.
322    pub fn len(&self) -> usize {
323        self.inner.read().candidates.len()
324    }
325
326    /// Whether the ledger holds no candidates.
327    pub fn is_empty(&self) -> bool {
328        self.inner.read().candidates.is_empty()
329    }
330
331    /// Candidates usable for retrieval right now.
332    pub fn usable_candidates(&self) -> Vec<SessionCandidate> {
333        self.inner
334            .read()
335            .candidates
336            .values()
337            .filter(|c| c.status.is_usable())
338            .cloned()
339            .collect()
340    }
341
342    /// Merge duplicates, resolve in-session contradictions, and re-evaluate
343    /// statuses (§18).
344    ///
345    /// Runs on a cadence during the session. Deliberately local: it compares
346    /// candidates against each other, never against the durable corpus.
347    pub fn micro_reconcile(&self) -> MicroReconciliationReport {
348        let mut state = self.inner.write();
349        let mut report = MicroReconciliationReport::default();
350
351        // Within one `subject|predicate` window, the newest explicit statement
352        // wins and older competing values are suppressed. A user who says
353        // "actually, pescatarian" has not left two beliefs behind.
354        //
355        // Only where the window is single-valued, though. `dietary_identity`
356        // holds one answer, so a second value contradicts the first; `routine`
357        // and `preference` are the buckets an extractor uses when it could not
358        // say *which* attribute a fact is about, so two values there are
359        // usually two facts. Collapsing those lost data mid-conversation: "I've
360        // started a pottery class on Thursdays" and "I always take the metro to
361        // work" both land on `user|routine`, and the second silently deleted
362        // the first — measured, recallable on turn 1 and gone by turn 2.
363        //
364        // The residual case is "I prefer window seats" followed by "actually,
365        // aisle": a real correction inside an unclassified window, which now
366        // leaves both. That is a symptom of the coarse vocabulary rather than
367        // of this rule — a model-backed extractor writes `seat_preference` and
368        // the window is single-valued again — and leaving two facts is the
369        // better failure, because the alternative deletes one the user never
370        // retracted.
371        let mut by_window: BTreeMap<String, Vec<FactFingerprint>> = BTreeMap::new();
372        for (fingerprint, candidate) in state.candidates.iter() {
373            if candidate.status == SessionCandidateStatus::Rejected
374                || matches!(
375                    candidate.mutation_intent,
376                    Some(
377                        crate::core::MutationIntent::Forget
378                            | crate::core::MutationIntent::Delete
379                            | crate::core::MutationIntent::List
380                    )
381                )
382            {
383                continue;
384            }
385            by_window
386                .entry(candidate.subject_predicate().to_string())
387                .or_default()
388                .push(fingerprint.clone());
389        }
390
391        for (_, fingerprints) in by_window {
392            if fingerprints.len() < 2 {
393                continue;
394            }
395            // An explicit correction collapses its window whatever the
396            // predicate is named: the user said outright that one replaces the
397            // other.
398            let corrected = fingerprints.iter().any(|f| {
399                state.candidates[f].mutation_intent == Some(crate::core::MutationIntent::Correct)
400            });
401            let single_valued = fingerprints
402                .iter()
403                .any(|f| is_single_valued(state.candidates[f].predicate.as_str()));
404            if !corrected && !single_valued {
405                continue;
406            }
407            let Some(winner) = fingerprints
408                .iter()
409                .max_by(|a, b| {
410                    let ca = &state.candidates[*a];
411                    let cb = &state.candidates[*b];
412                    ca.explicitness
413                        .cmp(&cb.explicitness)
414                        .then_with(|| ca.last_seen_turn.cmp(&cb.last_seen_turn))
415                })
416                .cloned()
417            else {
418                // An empty window has no winner (windows here hold two or more).
419                continue;
420            };
421
422            for fingerprint in fingerprints {
423                if fingerprint == winner {
424                    continue;
425                }
426                if let Some(candidate) = state.candidates.get_mut(&fingerprint)
427                    && candidate.status != SessionCandidateStatus::Suppressed
428                {
429                    candidate.status = SessionCandidateStatus::Suppressed;
430                    report.suppressed += 1;
431                }
432            }
433        }
434
435        // Promote observations that have earned in-session trust.
436        for candidate in state.candidates.values_mut() {
437            if candidate.status == SessionCandidateStatus::Observed
438                && (candidate.distinct_turns >= 2
439                    || candidate.confidence >= self.config.minimum_observation_confidence * 2.0)
440            {
441                candidate.status = SessionCandidateStatus::StagedForReconciliation;
442                report.staged += 1;
443            }
444        }
445
446        report.candidates = state.candidates.len();
447        state.revision += 1;
448        report
449    }
450}
451
452/// What one micro-reconciliation pass did.
453#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
454pub struct MicroReconciliationReport {
455    /// Candidates suppressed by a later contradiction.
456    pub suppressed: usize,
457    /// Candidates promoted to staging.
458    pub staged: usize,
459    /// Total candidates after the pass.
460    pub candidates: usize,
461}
462
463#[async_trait]
464impl SessionLedger for InMemorySessionLedger {
465    async fn append_observation(
466        &self,
467        observation: MemoryObservation,
468    ) -> Result<LedgerOutcome, MemoryError> {
469        if self.inner.read().sealed {
470            return Err(MemoryError::PolicyRefused(
471                "session ledger is sealed".to_string(),
472            ));
473        }
474
475        let persistence = match admit_observation(&observation, &self.config) {
476            AdmissionVerdict::Accept(persistence) => persistence,
477            AdmissionVerdict::Reject(reason) => return Ok(LedgerOutcome::Rejected(reason)),
478        };
479
480        let now = Utc::now();
481        let fingerprint = observation.fingerprint();
482        let mut state = self.inner.write();
483        state.revision += 1;
484
485        match state.candidates.get_mut(&fingerprint) {
486            Some(existing) => {
487                existing.absorb(&observation, now);
488                Ok(LedgerOutcome::Reinforced {
489                    fingerprint,
490                    evidence_count: existing.evidence.len(),
491                })
492            }
493            None => {
494                state.candidates.insert(
495                    fingerprint.clone(),
496                    SessionCandidate::from_observation(&observation, persistence, now),
497                );
498                Ok(LedgerOutcome::Created(fingerprint))
499            }
500        }
501    }
502
503    async fn snapshot(&self) -> Result<SessionLedgerSnapshot, MemoryError> {
504        let state = self.inner.read();
505        Ok(SessionLedgerSnapshot {
506            session_id: self.session_id.clone(),
507            candidates: state.candidates.values().cloned().collect(),
508            revision: state.revision,
509        })
510    }
511
512    async fn seal(&self) -> Result<SealedSessionLedger, MemoryError> {
513        let mut state = self.inner.write();
514        state.sealed = true;
515        Ok(SealedSessionLedger {
516            session_id: self.session_id.clone(),
517            candidates: state
518                .candidates
519                .values()
520                .filter(|c| {
521                    !matches!(
522                        c.status,
523                        SessionCandidateStatus::Rejected | SessionCandidateStatus::Suppressed
524                    )
525                })
526                .cloned()
527                .collect(),
528            sealed_at: Utc::now(),
529        })
530    }
531}
532
533/// The predicates that are not really predicates: an extractor's "something
534/// about the user, unclassified" buckets.
535///
536/// A second value in a named window — `dietary_identity`, `residence`,
537/// `employer` — contradicts the first. A second value in one of these is
538/// usually just a second fact.
539fn is_single_valued(predicate: &str) -> bool {
540    !matches!(predicate, "preference" | "routine")
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546    use crate::core::{CanonicalPredicate, EntityRef, SpeakerAttribution, TranscriptEvidence};
547
548    fn observation(
549        predicate: &str,
550        value: &str,
551        turn: u64,
552        explicitness: Explicitness,
553    ) -> MemoryObservation {
554        MemoryObservation {
555            observation_id: ObservationId::generate(),
556            session_id: SessionId::new("ses_1"),
557            turn_id: TurnId(turn),
558            subject: EntityRef::user(),
559            predicate: CanonicalPredicate::new(predicate),
560            value: MemoryValue::Text(value.to_string()),
561            canonical_statement: format!("The user is {value}."),
562            kind: MemoryKind::Preference,
563            explicitness,
564            confidence: 0.9,
565            persistence: ProposedPersistence::Durable,
566            temporal_scope: TemporalScope::Persistent,
567            valid_from: None,
568            expected_expiry: None,
569            transcript_evidence: TranscriptEvidence::new(format!("I am {value}")),
570            speaker_attribution: SpeakerAttribution::User,
571            sensitivity: SensitivityClass::Normal,
572            mutation_intent: None,
573            search_terms: Vec::new(),
574        }
575    }
576
577    fn ledger() -> InMemorySessionLedger {
578        InMemorySessionLedger::new(SessionId::new("ses_1"), IngestionConfig::default())
579    }
580
581    #[tokio::test]
582    async fn the_same_fact_stated_twice_becomes_one_candidate_with_two_evidences() {
583        let ledger = ledger();
584        let first = ledger
585            .append_observation(observation(
586                "dietary_identity",
587                "pescatarian",
588                1,
589                Explicitness::ExplicitStatement,
590            ))
591            .await
592            .unwrap();
593        assert!(matches!(first, LedgerOutcome::Created(_)));
594
595        let second = ledger
596            .append_observation(observation(
597                "dietary_identity",
598                "pescatarian",
599                4,
600                Explicitness::ExplicitStatement,
601            ))
602            .await
603            .unwrap();
604        assert!(matches!(
605            second,
606            LedgerOutcome::Reinforced {
607                evidence_count: 2,
608                ..
609            }
610        ));
611        assert_eq!(ledger.len(), 1);
612        assert_eq!(ledger.usable_candidates()[0].distinct_turns, 2);
613    }
614
615    #[tokio::test]
616    async fn refused_observations_never_enter_the_ledger() {
617        let ledger = ledger();
618        let mut bystander = observation(
619            "dietary_identity",
620            "vegan",
621            1,
622            Explicitness::ExplicitStatement,
623        );
624        bystander.speaker_attribution = SpeakerAttribution::Bystander;
625
626        let outcome = ledger.append_observation(bystander).await.unwrap();
627        assert_eq!(
628            outcome,
629            LedgerOutcome::Rejected(DiscardReason::SpeakerNotUser)
630        );
631        assert!(ledger.is_empty());
632    }
633
634    #[tokio::test]
635    async fn a_later_contradiction_suppresses_the_earlier_candidate() {
636        let ledger = ledger();
637        ledger
638            .append_observation(observation(
639                "dietary_identity",
640                "vegetarian",
641                1,
642                Explicitness::ExplicitStatement,
643            ))
644            .await
645            .unwrap();
646        ledger
647            .append_observation(observation(
648                "dietary_identity",
649                "pescatarian",
650                5,
651                Explicitness::ExplicitStatement,
652            ))
653            .await
654            .unwrap();
655
656        let report = ledger.micro_reconcile();
657        assert_eq!(report.suppressed, 1);
658
659        let usable = ledger.usable_candidates();
660        assert_eq!(usable.len(), 1);
661        assert_eq!(usable[0].canonical_statement, "The user is pescatarian.");
662    }
663
664    #[tokio::test]
665    async fn an_explicit_correction_beats_a_more_recent_inference() {
666        let ledger = ledger();
667        ledger
668            .append_observation(observation(
669                "dietary_identity",
670                "pescatarian",
671                1,
672                Explicitness::ExplicitStatement,
673            ))
674            .await
675            .unwrap();
676        // A later *inference* must not displace what the user actually said.
677        ledger
678            .append_observation(observation(
679                "dietary_identity",
680                "vegan",
681                6,
682                Explicitness::WeakInference,
683            ))
684            .await
685            .unwrap();
686
687        ledger.micro_reconcile();
688        let usable = ledger.usable_candidates();
689        assert_eq!(usable.len(), 1);
690        assert_eq!(usable[0].canonical_statement, "The user is pescatarian.");
691    }
692
693    #[tokio::test]
694    async fn repeated_inference_earns_staging_but_not_more() {
695        let ledger = ledger();
696        for turn in 1..=2 {
697            ledger
698                .append_observation(observation(
699                    "exercise_routine",
700                    "morning gym",
701                    turn,
702                    Explicitness::StrongImplication,
703                ))
704                .await
705                .unwrap();
706        }
707        let report = ledger.micro_reconcile();
708        assert_eq!(report.staged, 1);
709        assert_eq!(
710            ledger.usable_candidates()[0].status,
711            SessionCandidateStatus::StagedForReconciliation
712        );
713    }
714
715    #[tokio::test]
716    async fn sealing_drops_suppressed_and_rejected_candidates_and_stops_writes() {
717        let ledger = ledger();
718        ledger
719            .append_observation(observation(
720                "dietary_identity",
721                "vegetarian",
722                1,
723                Explicitness::ExplicitStatement,
724            ))
725            .await
726            .unwrap();
727        ledger
728            .append_observation(observation(
729                "dietary_identity",
730                "pescatarian",
731                5,
732                Explicitness::ExplicitStatement,
733            ))
734            .await
735            .unwrap();
736        ledger.micro_reconcile();
737
738        let sealed = ledger.seal().await.unwrap();
739        assert_eq!(sealed.candidates.len(), 1);
740
741        let err = ledger
742            .append_observation(observation(
743                "dietary_identity",
744                "vegan",
745                9,
746                Explicitness::ExplicitStatement,
747            ))
748            .await
749            .unwrap_err();
750        assert!(matches!(err, MemoryError::PolicyRefused(_)));
751    }
752
753    #[tokio::test]
754    async fn confidence_aggregates_rather_than_accumulates() {
755        let ledger = ledger();
756        for turn in 1..=4 {
757            ledger
758                .append_observation(observation(
759                    "beverage_preference",
760                    "flat white",
761                    turn,
762                    Explicitness::ExplicitStatement,
763                ))
764                .await
765                .unwrap();
766        }
767        let candidate = &ledger.usable_candidates()[0];
768        assert!(candidate.confidence <= 0.95);
769        assert!(candidate.confidence >= 0.9);
770    }
771}