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_core::event::Usage;
7use troupekit_core::ids::RunId;
8use troupekit_core::message::Message;
9use troupekit_core::store::{BlobStore, Checkpoint, CheckpointStore, MemoryLog, UsageLedger};
10use troupekit_trace::{trace_span, Trace};
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!(
114            Trace::Store,
115            "checkpoint.save",
116            store = "sqlite",
117            run = run.as_str(),
118            step = actual,
119            bytes = bytes.len()
120        );
121        let result = span
122            .instrument(self.call(move |conn| {
123                let tx = immediate(conn)?;
124                let expected = match max_step(&tx, &run)? {
125                    None => 0,
126                    Some(m) => m
127                        .checked_add(1)
128                        .ok_or_else(|| corrupt("step at u64::MAX".into()))?,
129                };
130                if actual != expected {
131                    return Err(CoreError::Conflict { expected, actual });
132                }
133                let inserted = tx
134                    .execute(
135                        "INSERT INTO checkpoint (run_id, step, state_json) VALUES (?1, ?2, ?3)",
136                        params![run, step, bytes],
137                    )
138                    .map_err(db)?;
139                assert_eq!(inserted, 1);
140                assert_eq!(max_step(&tx, &run)?, Some(actual));
141                tx.commit().map_err(db)
142            }))
143            .await;
144        if let Err(e) = &result {
145            span.fail(e.to_string());
146        }
147        result
148    }
149
150    async fn latest(&self, run_id: RunId) -> Result<Option<Checkpoint>, CoreError> {
151        let run = run_id.to_string();
152        let mut span = trace_span!(
153            Trace::Store,
154            "checkpoint.latest",
155            store = "sqlite",
156            run = run.as_str()
157        );
158        let result = span
159            .instrument(self.call(move |conn| {
160                let row: Option<(i64, Vec<u8>)> = conn
161                    .query_row(
162                        "SELECT step, state_json FROM checkpoint WHERE run_id = ?1 \
163                     ORDER BY step DESC LIMIT 1",
164                        [&run],
165                        |row| Ok((row.get(0)?, row.get(1)?)),
166                    )
167                    .optional()
168                    .map_err(db)?;
169                row.map(|(step, bytes)| row_checkpoint(run_id, step, &bytes))
170                    .transpose()
171            }))
172            .await;
173        match &result {
174            Ok(Some(cp)) => span.record("found_step", cp.step),
175            Ok(None) => span.record("found", false),
176            Err(e) => span.fail(e.to_string()),
177        }
178        result
179    }
180
181    async fn history(&self, run_id: RunId) -> Result<Vec<Checkpoint>, CoreError> {
182        let run = run_id.to_string();
183        let max = self.limits().history_steps_max;
184        let max_bytes = self.limits().history_bytes_max;
185        self.call(move |conn| {
186            let tx = conn.transaction().map_err(db)?;
187            let count: i64 = tx
188                .query_row(
189                    "SELECT COUNT(*) FROM checkpoint WHERE run_id = ?1",
190                    [&run],
191                    |r| r.get(0),
192                )
193                .map_err(db)?;
194            let count = from_sql_int("count", count)?;
195            if count > max {
196                return Err(CoreError::Store(format!(
197                    "run has {count} kept steps, above max_history_steps {max}"
198                )));
199            }
200            let mut stmt = tx
201                .prepare_cached(
202                    "SELECT step, state_json FROM checkpoint WHERE run_id = ?1 ORDER BY step",
203                )
204                .map_err(db)?;
205            let rows = stmt
206                .query_map([&run], |row| {
207                    Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
208                })
209                .map_err(db)?;
210            let mut out = Vec::with_capacity(count as usize);
211            let mut total = 0u64;
212            for row in rows {
213                let (step, bytes) = row.map_err(db)?;
214                total = total.saturating_add(bytes.len() as u64);
215                if total > max_bytes {
216                    return Err(CoreError::Store(format!(
217                        "run history is above max_history_bytes {max_bytes}"
218                    )));
219                }
220                out.push(row_checkpoint(run_id, step, &bytes)?);
221            }
222            assert!(total <= max_bytes);
223            assert_eq!(out.len() as u64, count);
224            assert!(out.windows(2).all(|w| w[0].step < w[1].step));
225            Ok(out)
226        })
227        .await
228    }
229
230    async fn prune(&self, run_id: RunId, keep_last: u64) -> Result<u64, CoreError> {
231        if keep_last == 0 {
232            return Err(CoreError::Store(
233                "prune keep_last must be at least 1".into(),
234            ));
235        }
236        let run = run_id.to_string();
237        self.call(move |conn| {
238            let tx = immediate(conn)?;
239            let Some(max) = max_step(&tx, &run)? else {
240                return Ok(0);
241            };
242            let cutoff = (max + 1).saturating_sub(keep_last);
243            assert!(cutoff <= max, "prune never reaches the latest step");
244            let deleted = tx
245                .execute(
246                    "DELETE FROM checkpoint WHERE run_id = ?1 AND step < ?2",
247                    params![run, to_sql_int("step", cutoff)?],
248                )
249                .map_err(db)?;
250            assert_eq!(max_step(&tx, &run)?, Some(max));
251            tx.commit().map_err(db)?;
252            Ok(deleted as u64)
253        })
254        .await
255    }
256}
257
258/// Returns the length of `log` as its last index plus one, one primary
259/// key seek instead of a count over the whole log. `append` keeps the
260/// indexes gapless and `read` refuses a gap. Input: the transaction and
261/// the log name. Output: the length, 0 for an empty log.
262fn log_len(tx: &Transaction<'_>, log: &str) -> Result<u64, CoreError> {
263    let last: Option<i64> = tx
264        .query_row(
265            "SELECT MAX(idx) FROM memory_entry WHERE log = ?1",
266            [log],
267            |row| row.get(0),
268        )
269        .map_err(db)?;
270    match last {
271        None => Ok(0),
272        Some(idx) => from_sql_int("log index", idx)?
273            .checked_add(1)
274            .ok_or_else(|| corrupt("log index at u64::MAX".into())),
275    }
276}
277
278#[async_trait]
279impl MemoryLog for SqliteStore {
280    async fn append(
281        &self,
282        log: &str,
283        expected_len: u64,
284        entries: Vec<Message>,
285    ) -> Result<u64, CoreError> {
286        let mut encoded = Vec::with_capacity(entries.len());
287        for message in &entries {
288            let value = serde_json::to_value(message)
289                .map_err(|e| CoreError::Store(format!("cannot encode message: {e}")))?;
290            check_depth(&value, "message")?;
291            encoded.push(
292                serde_json::to_vec(message)
293                    .map_err(|e| CoreError::Store(format!("cannot encode message: {e}")))?,
294            );
295        }
296        let log = log.to_string();
297        self.call(move |conn| {
298            let tx = immediate(conn)?;
299            let actual = log_len(&tx, &log)?;
300            if actual != expected_len {
301                return Err(CoreError::Conflict {
302                    expected: expected_len,
303                    actual,
304                });
305            }
306            let added = encoded.len() as u64;
307            {
308                let mut insert = tx
309                    .prepare_cached(
310                        "INSERT INTO memory_entry (log, idx, message_json) VALUES (?1, ?2, ?3)",
311                    )
312                    .map_err(db)?;
313                for (offset, bytes) in encoded.iter().enumerate() {
314                    let idx = to_sql_int("log index", actual + offset as u64)?;
315                    let inserted = insert.execute(params![log, idx, bytes]).map_err(db)?;
316                    assert_eq!(inserted, 1);
317                }
318            }
319            let len = log_len(&tx, &log)?;
320            assert_eq!(len, actual + added);
321            tx.commit().map_err(db)?;
322            Ok(len)
323        })
324        .await
325    }
326
327    async fn read(&self, log: &str) -> Result<Vec<Message>, CoreError> {
328        let log = log.to_string();
329        self.call(move |conn| {
330            let mut stmt = conn
331                .prepare_cached(
332                    "SELECT idx, message_json FROM memory_entry WHERE log = ?1 ORDER BY idx",
333                )
334                .map_err(db)?;
335            let rows = stmt
336                .query_map([&log], |row| {
337                    Ok((row.get::<_, i64>(0)?, row.get::<_, Vec<u8>>(1)?))
338                })
339                .map_err(db)?;
340            let mut out = Vec::new();
341            for row in rows {
342                let (idx, bytes) = row.map_err(db)?;
343                if from_sql_int("log index", idx)? != out.len() as u64 {
344                    return Err(corrupt(format!("log has a gap at index {}", out.len())));
345                }
346                let message = serde_json::from_slice(&bytes)
347                    .map_err(|e| corrupt(format!("message is not valid: {e}")))?;
348                out.push(message);
349            }
350            Ok(out)
351        })
352        .await
353    }
354}
355
356#[async_trait]
357impl BlobStore for SqliteStore {
358    async fn put(&self, path: &str, bytes: Vec<u8>) -> Result<(), CoreError> {
359        let max = self.limits().blob_bytes_max;
360        if bytes.len() as u64 > max {
361            return Err(CoreError::Store(format!(
362                "blob is {} bytes, above max_blob_bytes {max}",
363                bytes.len()
364            )));
365        }
366        let path = path.to_string();
367        self.call(move |conn| {
368            let written = conn
369                .execute(
370                    "INSERT INTO blob_entry (path, bytes) VALUES (?1, ?2) \
371                     ON CONFLICT (path) DO UPDATE SET bytes = excluded.bytes",
372                    params![path, bytes],
373                )
374                .map_err(db)?;
375            assert_eq!(written, 1);
376            Ok(())
377        })
378        .await
379    }
380
381    async fn get(&self, path: &str) -> Result<Vec<u8>, CoreError> {
382        let path = path.to_string();
383        self.call(move |conn| {
384            let bytes: Option<Vec<u8>> = conn
385                .query_row(
386                    "SELECT bytes FROM blob_entry WHERE path = ?1",
387                    [&path],
388                    |row| row.get(0),
389                )
390                .optional()
391                .map_err(db)?;
392            bytes.ok_or(CoreError::NotFound(path))
393        })
394        .await
395    }
396}
397
398fn read_usage(conn: &Connection, key: &str) -> Result<Usage, CoreError> {
399    let row: Option<(i64, i64, i64)> = conn
400        .query_row(
401            "SELECT input_tokens, output_tokens, cost_usd_micros FROM usage_total \
402             WHERE ledger_key = ?1",
403            [key],
404            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
405        )
406        .optional()
407        .map_err(db)?;
408    let Some((input, output, cost)) = row else {
409        return Ok(Usage::default());
410    };
411    Ok(Usage {
412        input_tokens: from_sql_int("input_tokens", input)?,
413        output_tokens: from_sql_int("output_tokens", output)?,
414        cost_usd_micros: from_sql_int("cost_usd_micros", cost)?,
415    })
416}
417
418fn add_counter(name: &str, total: u64, more: u64) -> Result<i64, CoreError> {
419    let sum = total
420        .checked_add(more)
421        .ok_or_else(|| CoreError::Store(format!("{name} total would overflow")))?;
422    to_sql_int(name, sum)
423}
424
425#[async_trait]
426impl UsageLedger for SqliteStore {
427    async fn period_total(&self, key: &str) -> Result<u64, CoreError> {
428        let key = key.to_string();
429        self.call(move |conn| Ok(read_usage(conn, &key)?.cost_usd_micros))
430            .await
431    }
432
433    async fn record(&self, key: &str, usage: Usage) -> Result<(), CoreError> {
434        let key = key.to_string();
435        self.call(move |conn| {
436            let tx = immediate(conn)?;
437            let total = read_usage(&tx, &key)?;
438            let input = add_counter("input_tokens", total.input_tokens, usage.input_tokens)?;
439            let output = add_counter("output_tokens", total.output_tokens, usage.output_tokens)?;
440            let cost = add_counter(
441                "cost_usd_micros",
442                total.cost_usd_micros,
443                usage.cost_usd_micros,
444            )?;
445            let written = tx
446                .execute(
447                    "INSERT INTO usage_total \
448                     (ledger_key, input_tokens, output_tokens, cost_usd_micros) \
449                     VALUES (?1, ?2, ?3, ?4) ON CONFLICT (ledger_key) DO UPDATE SET \
450                     input_tokens = excluded.input_tokens, \
451                     output_tokens = excluded.output_tokens, \
452                     cost_usd_micros = excluded.cost_usd_micros",
453                    params![key, input, output, cost],
454                )
455                .map_err(db)?;
456            assert_eq!(written, 1);
457            assert_eq!(read_usage(&tx, &key)?, total + usage);
458            tx.commit().map_err(db)
459        })
460        .await
461    }
462}