Skip to main content

troupekit_core/
store.rs

1use crate::error::CoreError;
2use crate::event::Usage;
3use crate::ids::RunId;
4use crate::message::Message;
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::collections::BTreeMap;
9
10/// Saved state of a run after one step.
11/// Steps start at 0 and rise by one per saved checkpoint.
12/// `state` is the run's serialized state machine.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub struct Checkpoint {
15    pub run_id: RunId,
16    pub step: u64,
17    pub state: Value,
18}
19
20/// Durable run snapshots.
21/// `save` accepts only the next step and returns `CoreError::Conflict` otherwise,
22/// so two workers can never both advance the same run.
23#[async_trait]
24pub trait CheckpointStore: Send + Sync {
25    async fn save(&self, cp: Checkpoint) -> Result<(), CoreError>;
26    async fn latest(&self, run_id: RunId) -> Result<Option<Checkpoint>, CoreError>;
27
28    /// Returns the kept checkpoints of `run_id`, lowest step first.
29    /// The default lists `latest` as zero or one checkpoint, which is
30    /// exact for a store that keeps only the latest step.
31    async fn history(&self, run_id: RunId) -> Result<Vec<Checkpoint>, CoreError> {
32        Ok(self.latest(run_id).await?.into_iter().collect())
33    }
34
35    /// Deletes all but the `keep_last` highest steps of `run_id` and returns
36    /// how many it deleted. The latest step is never deleted, so `save` keeps
37    /// its next-step rule. `keep_last == 0` returns `CoreError::Store`.
38    /// The default deletes nothing.
39    async fn prune(&self, run_id: RunId, keep_last: u64) -> Result<u64, CoreError> {
40        let _ = run_id;
41        if keep_last == 0 {
42            return Err(CoreError::Store("prune keep_last must be at least 1".into()));
43        }
44        Ok(0)
45    }
46}
47
48/// Append-only message logs keyed by name.
49/// `append` succeeds only when the log still has `expected_len` entries and
50/// returns the new length; otherwise it returns `CoreError::Conflict`.
51#[async_trait]
52pub trait MemoryLog: Send + Sync {
53    async fn append(&self, log: &str, expected_len: u64, entries: Vec<Message>) -> Result<u64, CoreError>;
54    async fn read(&self, log: &str) -> Result<Vec<Message>, CoreError>;
55}
56
57/// One embedded chunk stored in a `VectorStore`.
58/// Holds the id, the embedding, the source text and string metadata
59/// used by `Filter`.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub struct VectorRecord {
62    pub id: String,
63    pub vector: Vec<f32>,
64    pub text: String,
65    pub meta: BTreeMap<String, String>,
66}
67
68/// A search hit from a `VectorStore`.
69/// Carries the record's id, text and metadata plus its cosine similarity
70/// to the query; higher scores are closer.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72pub struct Scored {
73    pub id: String,
74    pub score: f32,
75    pub text: String,
76    pub meta: BTreeMap<String, String>,
77}
78
79/// Equality filter on record metadata.
80/// Every key and value pair in the filter must match the record;
81/// an empty filter matches every record.
82#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
83pub struct Filter(pub BTreeMap<String, String>);
84
85impl Filter {
86    /// Checks the filter against a record's `meta`.
87    /// Returns true when every filter pair is present in `meta`
88    /// with the same value.
89    pub fn matches(&self, meta: &BTreeMap<String, String>) -> bool {
90        self.0.iter().all(|(k, v)| meta.get(k) == Some(v))
91    }
92}
93
94/// Object-safe vector index of a fixed dimension, so a store can be chosen
95/// at runtime. `upsert` and `search` return `CoreError::DimensionMismatch`
96/// for vectors whose length is not `dims`.
97#[async_trait]
98pub trait VectorStore: Send + Sync {
99    fn dims(&self) -> usize;
100    async fn upsert(&self, records: Vec<VectorRecord>) -> Result<(), CoreError>;
101    async fn search(&self, query: &[f32], k: usize, filter: &Filter) -> Result<Vec<Scored>, CoreError>;
102}
103
104/// Object-safe keyword search over stored text, so a store can be chosen
105/// at runtime. `search_text` ranks records by BM25, higher scores first,
106/// keeps only records whose meta matches `filter` and returns at most `k`
107/// hits. Query text is plain words, never a query language.
108#[async_trait]
109pub trait KeywordStore: Send + Sync {
110    async fn search_text(&self, query: &str, k: usize, filter: &Filter) -> Result<Vec<Scored>, CoreError>;
111}
112
113/// Byte storage by path, for attached files and media.
114/// `put` replaces any existing bytes at the path.
115/// `get` of an unknown path returns `CoreError::NotFound`.
116#[async_trait]
117pub trait BlobStore: Send + Sync {
118    async fn put(&self, path: &str, bytes: Vec<u8>) -> Result<(), CoreError>;
119    async fn get(&self, path: &str) -> Result<Vec<u8>, CoreError>;
120}
121
122/// Cosine similarity of vectors `a` and `b`, which must have equal length.
123/// Returns a value in -1.0..=1.0, or 0.0 when either vector is all zeros.
124/// Panics on unequal lengths; callers check dimensions first.
125pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
126    assert_eq!(a.len(), b.len(), "cosine of unequal lengths");
127    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
128    let na = a.iter().map(|x| x * x).sum::<f32>().sqrt();
129    let nb = b.iter().map(|x| x * x).sum::<f32>().sqrt();
130    if na == 0.0 || nb == 0.0 {
131        return 0.0;
132    }
133    dot / (na * nb)
134}
135
136/// A claimed job: the run to step, the lease token that proves the claim
137/// and how many times the job was claimed since it last completed or was
138/// rescheduled. A token from an expired, re-claimed lease is stale.
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct Lease {
141    pub run_id: RunId,
142    pub token: u64,
143    pub attempts: u32,
144}
145
146/// Where one run's job stands. `Pending` waits for `due_ms`; `Leased` is
147/// held until `until_ms`, with `next_due_ms` from an enqueue during the
148/// lease; `Done` and `Failed` end it until the next enqueue.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum JobState {
151    Pending {
152        due_ms: i64,
153    },
154    Leased {
155        token: u64,
156        until_ms: i64,
157        next_due_ms: Option<i64>,
158    },
159    Done,
160    Failed {
161        error: String,
162    },
163}
164
165/// Jobs keyed by run, at most one live job per run. `claim_due` leases due
166/// jobs and expired leases, earliest first; `complete`, `fail` and
167/// `reschedule` end a lease and return `CoreError::Conflict` for a stale one.
168#[async_trait]
169pub trait JobQueue: Send + Sync {
170    async fn enqueue(&self, run_id: RunId, due_ms: i64) -> Result<(), CoreError>;
171    async fn claim_due(&self, limit: usize, lease_ms: i64) -> Result<Vec<Lease>, CoreError>;
172    async fn complete(&self, lease: &Lease) -> Result<(), CoreError>;
173    async fn fail(&self, lease: &Lease, error: &str) -> Result<(), CoreError>;
174    async fn reschedule(&self, lease: &Lease, due_ms: i64) -> Result<(), CoreError>;
175}
176
177/// Spend totals per key for the current period, kept by the host (for
178/// example one row per goal and month). `period_total` returns millionths
179/// of a US dollar spent so far; `record` adds one call's usage.
180#[async_trait]
181pub trait UsageLedger: Send + Sync {
182    async fn period_total(&self, key: &str) -> Result<u64, CoreError>;
183    async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError>;
184}