use crate::error::ContextError;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;
use troupekit_core::error::CoreError;
use troupekit_core::message::{Message, Role};
use troupekit_core::store::MemoryLog;
const FACT_LOG_PREFIX: &str = "facts/";
const MAX_ATTEMPTS: usize = 3;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Fact {
pub key: String,
pub value: String,
pub source: String,
pub at_ms: i64,
pub confidence: f32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
enum FactEntry {
Set { fact: Fact },
Remove { key: String, at_ms: i64 },
}
impl FactEntry {
fn key_and_time(&self) -> (&str, i64) {
match self {
FactEntry::Set { fact } => (&fact.key, fact.at_ms),
FactEntry::Remove { key, at_ms } => (key, *at_ms),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FactCaps {
pub max_facts: usize,
pub max_log_entries: usize,
}
pub struct FactBook {
log: Arc<dyn MemoryLog>,
}
impl FactBook {
pub fn new(log: Arc<dyn MemoryLog>) -> Self {
Self { log }
}
pub async fn put(&self, subject: &str, fact: Fact) -> Result<(), ContextError> {
check_key(&fact.key)?;
if !(0.0..=1.0).contains(&fact.confidence) {
return Err(ContextError::Invalid("confidence must be within 0.0..=1.0".into()));
}
self.append(subject, FactEntry::Set { fact }, None).await
}
pub async fn put_capped(&self, subject: &str, fact: Fact, caps: FactCaps) -> Result<(), ContextError> {
check_key(&fact.key)?;
if !(0.0..=1.0).contains(&fact.confidence) {
return Err(ContextError::Invalid("confidence must be within 0.0..=1.0".into()));
}
self.append(subject, FactEntry::Set { fact }, Some(caps)).await
}
pub async fn remove(&self, subject: &str, key: &str, at_ms: i64) -> Result<(), ContextError> {
check_key(key)?;
self.append(subject, FactEntry::Remove { key: key.to_string(), at_ms }, None).await
}
pub async fn remove_capped(&self, subject: &str, key: &str, at_ms: i64, max_log_entries: usize) -> Result<(), ContextError> {
check_key(key)?;
let caps = FactCaps { max_facts: usize::MAX, max_log_entries };
self.append(subject, FactEntry::Remove { key: key.to_string(), at_ms }, Some(caps)).await
}
pub async fn list(&self, subject: &str) -> Result<Vec<Fact>, ContextError> {
let name = log_name(subject)?;
Ok(fold(&name, &self.log.read(&name).await?)?
.into_values()
.filter_map(|e| match e {
FactEntry::Set { fact } => Some(fact),
FactEntry::Remove { .. } => None,
})
.collect())
}
pub async fn entries(&self, subject: &str) -> Result<usize, ContextError> {
let name = log_name(subject)?;
Ok(self.log.read(&name).await?.len())
}
async fn append(&self, subject: &str, entry: FactEntry, caps: Option<FactCaps>) -> Result<(), ContextError> {
let name = log_name(subject)?;
let json = serde_json::to_string(&entry).expect("fact entry serializes");
for attempt in 1..=MAX_ATTEMPTS {
let entries = self.log.read(&name).await?;
if let Some(caps) = caps {
check_caps(&name, &entries, &entry, caps)?;
}
let len = entries.len() as u64;
match self.log.append(&name, len, vec![Message::text(Role::System, json.clone())]).await {
Ok(_) => return Ok(()),
Err(CoreError::Conflict { .. }) if attempt < MAX_ATTEMPTS => continue,
Err(e) => return Err(e.into()),
}
}
unreachable!("the last attempt always returns")
}
}
fn fold(name: &str, messages: &[Message]) -> Result<BTreeMap<String, FactEntry>, ContextError> {
let mut current: BTreeMap<String, FactEntry> = BTreeMap::new();
for message in messages {
let entry: FactEntry = serde_json::from_str(&message.text_content())
.map_err(|e| CoreError::Store(format!("corrupt fact entry in {name}: {e}")))?;
let (key, at_ms) = entry.key_and_time();
if current.get(key).is_none_or(|old| at_ms >= old.key_and_time().1) {
current.insert(key.to_string(), entry);
}
}
Ok(current)
}
fn check_caps(name: &str, entries: &[Message], entry: &FactEntry, caps: FactCaps) -> Result<(), ContextError> {
if entries.len() >= caps.max_log_entries {
return Err(ContextError::Invalid(format!(
"fact log holds max_fact_log_entries {} edits; no more fact writes for this subject",
caps.max_log_entries
)));
}
let FactEntry::Set { fact } = entry else {
return Ok(());
};
let current = fold(name, entries)?;
let live = current.values().filter(|e| matches!(e, FactEntry::Set { .. }));
let is_live = |key: &str| matches!(current.get(key), Some(FactEntry::Set { .. }));
if live.count() >= caps.max_facts && !is_live(&fact.key) {
return Err(ContextError::Invalid(format!(
"subject already has max_facts {} facts; forget one first",
caps.max_facts
)));
}
Ok(())
}
fn log_name(subject: &str) -> Result<String, ContextError> {
if subject.trim().is_empty() {
return Err(ContextError::Invalid("subject must not be empty".into()));
}
Ok(format!("{FACT_LOG_PREFIX}{subject}"))
}
fn check_key(key: &str) -> Result<(), ContextError> {
if key.trim().is_empty() {
return Err(ContextError::Invalid("fact key must not be empty".into()));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use async_trait::async_trait;
use std::sync::atomic::{AtomicUsize, Ordering};
use troupekit_core::inmem::InMemMemory;
use troupekit_core::message::Message;
fn fact(key: &str, value: &str, at_ms: i64) -> Fact {
Fact { key: key.into(), value: value.into(), source: "chat".into(), at_ms, confidence: 0.9 }
}
fn book() -> FactBook {
FactBook::new(Arc::new(InMemMemory::default()))
}
fn values(facts: &[Fact]) -> Vec<(&str, &str)> {
facts.iter().map(|f| (f.key.as_str(), f.value.as_str())).collect()
}
#[tokio::test]
async fn newest_wins_per_key() {
let b = book();
b.put("u1", fact("weight", "80", 10)).await.unwrap();
b.put("u1", fact("weight", "78", 20)).await.unwrap();
b.put("u1", fact("height", "180", 5)).await.unwrap();
assert_eq!(values(&b.list("u1").await.unwrap()), vec![("height", "180"), ("weight", "78")]);
}
#[tokio::test]
async fn older_edit_does_not_override() {
let b = book();
b.put("u1", fact("weight", "78", 20)).await.unwrap();
b.put("u1", fact("weight", "80", 10)).await.unwrap();
assert_eq!(values(&b.list("u1").await.unwrap()), vec![("weight", "78")]);
}
#[tokio::test]
async fn equal_time_later_write_wins() {
let b = book();
b.put("u1", fact("diet", "vegan", 10)).await.unwrap();
b.put("u1", fact("diet", "vegetarian", 10)).await.unwrap();
assert_eq!(values(&b.list("u1").await.unwrap()), vec![("diet", "vegetarian")]);
}
#[tokio::test]
async fn remove_hides_key_until_newer_put() {
let b = book();
b.put("u1", fact("diet", "vegan", 10)).await.unwrap();
b.remove("u1", "diet", 20).await.unwrap();
assert!(b.list("u1").await.unwrap().is_empty());
b.put("u1", fact("diet", "keto", 15)).await.unwrap();
assert!(b.list("u1").await.unwrap().is_empty());
b.put("u1", fact("diet", "keto", 30)).await.unwrap();
assert_eq!(values(&b.list("u1").await.unwrap()), vec![("diet", "keto")]);
}
#[tokio::test]
async fn subjects_are_separate() {
let b = book();
b.put("u1", fact("diet", "vegan", 10)).await.unwrap();
assert!(b.list("u2").await.unwrap().is_empty());
}
#[tokio::test]
async fn rejects_invalid() {
let b = book();
assert!(matches!(b.put("", fact("k", "v", 1)).await, Err(ContextError::Invalid(_))));
assert!(matches!(b.put("u1", fact(" ", "v", 1)).await, Err(ContextError::Invalid(_))));
for confidence in [-0.1, 1.5, f32::NAN] {
let f = Fact { confidence, ..fact("k", "v", 1) };
assert!(matches!(b.put("u1", f).await, Err(ContextError::Invalid(_))));
}
assert!(matches!(b.remove("u1", "", 1).await, Err(ContextError::Invalid(_))));
assert!(matches!(b.list("").await, Err(ContextError::Invalid(_))));
}
struct Flaky {
inner: InMemMemory,
conflicts: AtomicUsize,
}
#[async_trait]
impl MemoryLog for Flaky {
async fn append(&self, log: &str, expected_len: u64, entries: Vec<Message>) -> Result<u64, CoreError> {
if self.conflicts.load(Ordering::SeqCst) > 0 {
self.conflicts.fetch_sub(1, Ordering::SeqCst);
return Err(CoreError::Conflict { expected: expected_len, actual: expected_len + 1 });
}
self.inner.append(log, expected_len, entries).await
}
async fn read(&self, log: &str) -> Result<Vec<Message>, CoreError> {
self.inner.read(log).await
}
}
#[tokio::test]
async fn retries_on_conflict_then_gives_up() {
let b = FactBook::new(Arc::new(Flaky { inner: InMemMemory::default(), conflicts: AtomicUsize::new(2) }));
b.put("u1", fact("diet", "vegan", 10)).await.unwrap();
assert_eq!(b.list("u1").await.unwrap().len(), 1);
let b = FactBook::new(Arc::new(Flaky { inner: InMemMemory::default(), conflicts: AtomicUsize::new(9) }));
assert!(matches!(b.put("u1", fact("diet", "vegan", 10)).await, Err(ContextError::Core(CoreError::Conflict { .. }))));
}
}