Skip to main content

troupekit_store_sqlite/
stores.rs

1use crate::{db, SqliteStore};
2use async_trait::async_trait;
3use rusqlite::{params, Connection, OptionalExtension, Transaction, TransactionBehavior};
4use serde_json::Value;
5use troupekit_core::error::CoreError;
6use troupekit_trace::{trace_span, Trace};
7use troupekit_core::event::Usage;
8use troupekit_core::ids::RunId;
9use troupekit_core::message::Message;
10use troupekit_core::store::{BlobStore, Checkpoint, CheckpointStore, MemoryLog, UsageLedger};
11
12/// Starts the write transaction every check-then-write uses. `IMMEDIATE`
13/// takes the write lock at once, so two handles never both pass a check.
14/// Input: the connection. Output: the transaction guard.
15pub(crate) fn immediate(conn: &mut Connection) -> Result<Transaction<'_>, CoreError> {
16    conn.transaction_with_behavior(TransactionBehavior::Immediate)
17        .map_err(db)
18}
19
20/// Converts a caller's `u64` to a SQLite integer.
21/// Input: the value and its name for the message.
22/// Output: the `i64`, or `CoreError::Store` when it does not fit.
23pub(crate) fn to_sql_int(name: &str, value: u64) -> Result<i64, CoreError> {
24    i64::try_from(value).map_err(|_| CoreError::Store(format!("{name} {value} is above i64::MAX")))
25}
26
27/// Converts a stored SQLite integer back to `u64`.
28/// Input: the value and its name. Output: the `u64`, or
29/// `CoreError::Store("corrupt store: ...")` for a negative value.
30pub(crate) fn from_sql_int(name: &str, value: i64) -> Result<u64, CoreError> {
31    u64::try_from(value).map_err(|_| corrupt(format!("negative {name} {value}")))
32}
33
34/// Builds the error for a value read from the file that cannot be right.
35/// Input: what was wrong. Output: `CoreError::Store("corrupt store: ...")`.
36pub(crate) fn corrupt(what: String) -> CoreError {
37    CoreError::Store(format!("corrupt store: {what}"))
38}
39
40const STATE_DEPTH_MAX: usize = 127;
41
42/// Tells whether `value` nests arrays and objects at most `levels_left`
43/// deep. Recursion stops one level past the limit, so it is bounded.
44/// Input: the value and the levels it may still use. Output: true when
45/// the value fits, which is what `decode_state` can read back.
46fn fits_depth(value: &Value, levels_left: usize) -> bool {
47    assert!(
48        levels_left <= STATE_DEPTH_MAX,
49        "depth budget above the limit"
50    );
51    match value {
52        Value::Array(items) => {
53            levels_left > 0 && items.iter().all(|v| fits_depth(v, levels_left - 1))
54        }
55        Value::Object(map) => {
56            levels_left > 0 && map.values().all(|v| fits_depth(v, levels_left - 1))
57        }
58        _ => true,
59    }
60}
61
62/// Refuses JSON the read path could not decode because it nests too
63/// deep. Input: the value and what it is, for the message. Output: `Ok`
64/// when it fits, `CoreError::Store` naming the limit otherwise.
65fn check_depth(value: &Value, what: &str) -> Result<(), CoreError> {
66    if fits_depth(value, STATE_DEPTH_MAX) {
67        return Ok(());
68    }
69    Err(CoreError::Store(format!(
70        "{what} nests deeper than {STATE_DEPTH_MAX} levels"
71    )))
72}
73
74fn decode_state(bytes: &[u8]) -> Result<Value, CoreError> {
75    serde_json::from_slice(bytes).map_err(|e| corrupt(format!("checkpoint state is not JSON: {e}")))
76}
77
78fn max_step(tx: &Transaction<'_>, run: &str) -> Result<Option<u64>, CoreError> {
79    let max: Option<i64> = tx
80        .query_row(
81            "SELECT MAX(step) FROM checkpoint WHERE run_id = ?1",
82            [run],
83            |row| row.get(0),
84        )
85        .map_err(db)?;
86    max.map(|m| from_sql_int("step", m)).transpose()
87}
88
89fn row_checkpoint(run_id: RunId, step: i64, bytes: &[u8]) -> Result<Checkpoint, CoreError> {
90    Ok(Checkpoint {
91        run_id,
92        step: from_sql_int("step", step)?,
93        state: decode_state(bytes)?,
94    })
95}
96
97#[async_trait]
98impl CheckpointStore for SqliteStore {
99    async fn save(&self, cp: Checkpoint) -> Result<(), CoreError> {
100        let step = to_sql_int("step", cp.step)?;
101        check_depth(&cp.state, "checkpoint state")?;
102        let bytes = serde_json::to_vec(&cp.state)
103            .map_err(|e| CoreError::Store(format!("cannot encode checkpoint state: {e}")))?;
104        let max = self.limits().state_bytes_max;
105        if bytes.len() as u64 > max {
106            return Err(CoreError::Store(format!(
107                "checkpoint state is {} bytes, above max_state_bytes {max}",
108                bytes.len()
109            )));
110        }
111        let run = cp.run_id.to_string();
112        let actual = cp.step;
113        let mut span = trace_span!(Trace::Store, "checkpoint.save", store = "sqlite", run = run.as_str(), step = actual, bytes = bytes.len());
114        let result = span.instrument(self.call(move |conn| {
115            let tx = immediate(conn)?;
116            let expected = match max_step(&tx, &run)? {
117                None => 0,
118                Some(m) => m
119                    .checked_add(1)
120                    .ok_or_else(|| corrupt("step at u64::MAX".into()))?,
121            };
122            if actual != expected {
123                return Err(CoreError::Conflict { expected, actual });
124            }
125            let inserted = tx
126                .execute(
127                    "INSERT INTO checkpoint (run_id, step, state_json) VALUES (?1, ?2, ?3)",
128                    params![run, step, bytes],
129                )
130                .map_err(db)?;
131            assert_eq!(inserted, 1);
132            assert_eq!(max_step(&tx, &run)?, Some(actual));
133            tx.commit().map_err(db)
134        }))
135        .await;
136        if let Err(e) = &result {
137            span.fail(e.to_string());
138        }
139        result
140    }
141
142    async fn latest(&self, run_id: RunId) -> Result<Option<Checkpoint>, CoreError> {
143        let run = run_id.to_string();
144        let mut span = trace_span!(Trace::Store, "checkpoint.latest", store = "sqlite", run = run.as_str());
145        let result = span.instrument(self.call(move |conn| {
146            let row: Option<(i64, Vec<u8>)> = conn
147                .query_row(
148                    "SELECT step, state_json FROM checkpoint WHERE run_id = ?1 \
149                     ORDER BY step DESC LIMIT 1",
150                    [&run],
151                    |row| Ok((row.get(0)?, row.get(1)?)),
152                )
153                .optional()
154                .map_err(db)?;
155            row.map(|(step, bytes)| row_checkpoint(run_id, step, &bytes))
156                .transpose()
157        }))
158        .await;
159        match &result {
160            Ok(Some(cp)) => span.record("found_step", cp.step),
161            Ok(None) => span.record("found", false),
162            Err(e) => span.fail(e.to_string()),
163        }
164        result
165    }
166
167    async fn history(&self, run_id: RunId) -> Result<Vec<Checkpoint>, CoreError> {
168        let run = run_id.to_string();
169        let max = self.limits().history_steps_max;
170        self.call(move |conn| {
171            let tx = conn.transaction().map_err(db)?;
172            let count: i64 = tx
173                .query_row(
174                    "SELECT COUNT(*) FROM checkpoint WHERE run_id = ?1",
175                    [&run],
176                    |r| r.get(0),
177                )
178                .map_err(db)?;
179            let count = from_sql_int("count", count)?;
180            if count > max {
181                return Err(CoreError::Store(format!(
182                    "run has {count} kept steps, above max_history_steps {max}"
183                )));
184            }
185            let mut stmt = tx
186                .prepare_cached(
187                    "SELECT step, state_json FROM checkpoint WHERE run_id = ?1 ORDER BY step",
188                )
189                .map_err(db)?;
190            let rows = stmt
191                .query_map([&run], |row| {
192                    Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
193                })
194                .map_err(db)?;
195            let mut out = Vec::with_capacity(count as usize);
196            for row in rows {
197                let (step, bytes) = row.map_err(db)?;
198                out.push(row_checkpoint(run_id, step, &bytes)?);
199            }
200            assert_eq!(out.len() as u64, count);
201            assert!(out.windows(2).all(|w| w[0].step < w[1].step));
202            Ok(out)
203        })
204        .await
205    }
206
207    async fn prune(&self, run_id: RunId, keep_last: u64) -> Result<u64, CoreError> {
208        if keep_last == 0 {
209            return Err(CoreError::Store(
210                "prune keep_last must be at least 1".into(),
211            ));
212        }
213        let run = run_id.to_string();
214        self.call(move |conn| {
215            let tx = immediate(conn)?;
216            let Some(max) = max_step(&tx, &run)? else {
217                return Ok(0);
218            };
219            let cutoff = (max + 1).saturating_sub(keep_last);
220            assert!(cutoff <= max, "prune never reaches the latest step");
221            let deleted = tx
222                .execute(
223                    "DELETE FROM checkpoint WHERE run_id = ?1 AND step < ?2",
224                    params![run, to_sql_int("step", cutoff)?],
225                )
226                .map_err(db)?;
227            assert_eq!(max_step(&tx, &run)?, Some(max));
228            tx.commit().map_err(db)?;
229            Ok(deleted as u64)
230        })
231        .await
232    }
233}
234
235fn log_len(tx: &Transaction<'_>, log: &str) -> Result<u64, CoreError> {
236    let count: i64 = tx
237        .query_row(
238            "SELECT COUNT(*) FROM memory_entry WHERE log = ?1",
239            [log],
240            |row| row.get(0),
241        )
242        .map_err(db)?;
243    from_sql_int("log length", count)
244}
245
246#[async_trait]
247impl MemoryLog for SqliteStore {
248    async fn append(
249        &self,
250        log: &str,
251        expected_len: u64,
252        entries: Vec<Message>,
253    ) -> Result<u64, CoreError> {
254        let mut encoded = Vec::with_capacity(entries.len());
255        for message in &entries {
256            let value = serde_json::to_value(message)
257                .map_err(|e| CoreError::Store(format!("cannot encode message: {e}")))?;
258            check_depth(&value, "message")?;
259            encoded.push(
260                serde_json::to_vec(message)
261                    .map_err(|e| CoreError::Store(format!("cannot encode message: {e}")))?,
262            );
263        }
264        let log = log.to_string();
265        self.call(move |conn| {
266            let tx = immediate(conn)?;
267            let actual = log_len(&tx, &log)?;
268            if actual != expected_len {
269                return Err(CoreError::Conflict {
270                    expected: expected_len,
271                    actual,
272                });
273            }
274            let added = encoded.len() as u64;
275            {
276                let mut insert = tx
277                    .prepare_cached(
278                        "INSERT INTO memory_entry (log, idx, message_json) VALUES (?1, ?2, ?3)",
279                    )
280                    .map_err(db)?;
281                for (offset, bytes) in encoded.iter().enumerate() {
282                    let idx = to_sql_int("log index", actual + offset as u64)?;
283                    let inserted = insert.execute(params![log, idx, bytes]).map_err(db)?;
284                    assert_eq!(inserted, 1);
285                }
286            }
287            let len = log_len(&tx, &log)?;
288            assert_eq!(len, actual + added);
289            tx.commit().map_err(db)?;
290            Ok(len)
291        })
292        .await
293    }
294
295    async fn read(&self, log: &str) -> Result<Vec<Message>, CoreError> {
296        let log = log.to_string();
297        self.call(move |conn| {
298            let mut stmt = conn
299                .prepare_cached(
300                    "SELECT idx, message_json FROM memory_entry WHERE log = ?1 ORDER BY idx",
301                )
302                .map_err(db)?;
303            let rows = stmt
304                .query_map([&log], |row| {
305                    Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
306                })
307                .map_err(db)?;
308            let mut out = Vec::new();
309            for row in rows {
310                let (idx, bytes) = row.map_err(db)?;
311                if from_sql_int("log index", idx)? != out.len() as u64 {
312                    return Err(corrupt(format!("log has a gap at index {}", out.len())));
313                }
314                let message = serde_json::from_slice(&bytes)
315                    .map_err(|e| corrupt(format!("message is not valid: {e}")))?;
316                out.push(message);
317            }
318            Ok(out)
319        })
320        .await
321    }
322}
323
324#[async_trait]
325impl BlobStore for SqliteStore {
326    async fn put(&self, path: &str, bytes: Vec<u8>) -> Result<(), CoreError> {
327        let max = self.limits().blob_bytes_max;
328        if bytes.len() as u64 > max {
329            return Err(CoreError::Store(format!(
330                "blob is {} bytes, above max_blob_bytes {max}",
331                bytes.len()
332            )));
333        }
334        let path = path.to_string();
335        self.call(move |conn| {
336            let written = conn
337                .execute(
338                    "INSERT INTO blob_entry (path, bytes) VALUES (?1, ?2) \
339                     ON CONFLICT (path) DO UPDATE SET bytes = excluded.bytes",
340                    params![path, bytes],
341                )
342                .map_err(db)?;
343            assert_eq!(written, 1);
344            Ok(())
345        })
346        .await
347    }
348
349    async fn get(&self, path: &str) -> Result<Vec<u8>, CoreError> {
350        let path = path.to_string();
351        self.call(move |conn| {
352            let bytes: Option<Vec<u8>> = conn
353                .query_row(
354                    "SELECT bytes FROM blob_entry WHERE path = ?1",
355                    [&path],
356                    |row| row.get(0),
357                )
358                .optional()
359                .map_err(db)?;
360            bytes.ok_or(CoreError::NotFound(path))
361        })
362        .await
363    }
364}
365
366fn read_usage(conn: &Connection, key: &str) -> Result<Usage, CoreError> {
367    let row: Option<(i64, i64, i64)> = conn
368        .query_row(
369            "SELECT input_tokens, output_tokens, cost_usd_micros FROM usage_total \
370             WHERE ledger_key = ?1",
371            [key],
372            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
373        )
374        .optional()
375        .map_err(db)?;
376    let Some((input, output, cost)) = row else {
377        return Ok(Usage::default());
378    };
379    Ok(Usage {
380        input_tokens: from_sql_int("input_tokens", input)?,
381        output_tokens: from_sql_int("output_tokens", output)?,
382        cost_usd_micros: from_sql_int("cost_usd_micros", cost)?,
383    })
384}
385
386fn add_counter(name: &str, total: u64, more: u64) -> Result<i64, CoreError> {
387    let sum = total
388        .checked_add(more)
389        .ok_or_else(|| CoreError::Store(format!("{name} total would overflow")))?;
390    to_sql_int(name, sum)
391}
392
393#[async_trait]
394impl UsageLedger for SqliteStore {
395    async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
396        let key = key.to_string();
397        self.call(move |conn| Ok(read_usage(conn, &key)?.cost_usd_micros))
398            .await
399    }
400
401    async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
402        let key = key.to_string();
403        self.call(move |conn| {
404            let tx = immediate(conn)?;
405            let total = read_usage(&tx, &key)?;
406            let input = add_counter("input_tokens", total.input_tokens, usage.input_tokens)?;
407            let output = add_counter("output_tokens", total.output_tokens, usage.output_tokens)?;
408            let cost = add_counter(
409                "cost_usd_micros",
410                total.cost_usd_micros,
411                usage.cost_usd_micros,
412            )?;
413            let written = tx
414                .execute(
415                    "INSERT INTO usage_total \
416                     (ledger_key, input_tokens, output_tokens, cost_usd_micros) \
417                     VALUES (?1, ?2, ?3, ?4) ON CONFLICT (ledger_key) DO UPDATE SET \
418                     input_tokens = excluded.input_tokens, \
419                     output_tokens = excluded.output_tokens, \
420                     cost_usd_micros = excluded.cost_usd_micros",
421                    params![key, input, output, cost],
422                )
423                .map_err(db)?;
424            assert_eq!(written, 1);
425            assert_eq!(read_usage(&tx, &key)?, total + usage);
426            tx.commit().map_err(db)
427        })
428        .await
429    }
430}