Skip to main content

rinne_core/
state.rs

1//! Machine state in SQLite (`CONTEXT.md` §12, §14).
2//!
3//! `state.db` holds everything needed to reconstruct a run: node statuses,
4//! iteration counts, the budget ledger, and quota buckets. Workers are amnesiac,
5//! so a killed run resumes entirely from here (`CONTEXT.md` §12 persistence).
6
7use std::path::Path;
8use std::time::Duration;
9
10use rusqlite::Connection;
11
12use crate::worker::Usage;
13use crate::{Result, RinneError};
14
15/// Turn a single-row query result into an `Option`, treating "no rows" as the
16/// legitimate `None` while propagating every other error (a locked, busy, or
17/// corrupt database). Reads that swallow these into a default silently feed the
18/// scheduler and budget checks wrong state — worse than failing loudly.
19fn optional<T>(r: rusqlite::Result<T>) -> Result<Option<T>> {
20    match r {
21        Ok(v) => Ok(Some(v)),
22        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
23        Err(e) => Err(sql_err(e)),
24    }
25}
26
27// The node lifecycle status now lives in `rinne-types` (the Blackboard seam);
28// re-export it so existing `rinne_core::state::NodeStatus` paths keep working.
29pub use rinne_types::NodeStatus;
30
31/// One recorded worker invocation, for `rinne logs`.
32#[derive(Debug, Clone)]
33pub struct UsageRow {
34    pub node_id: String,
35    pub worker: String,
36    pub prompt_tokens: u64,
37    pub completion_tokens: u64,
38    pub wall_ms: u64,
39    pub ts: u64,
40}
41
42/// A handle to the run's SQLite state.
43pub struct State {
44    conn: Connection,
45}
46
47impl State {
48    /// Open (creating if needed) the state database at `path`, ensuring schema.
49    pub fn open(path: &Path) -> Result<Self> {
50        let conn = Connection::open(path).map_err(sql_err)?;
51        // WAL gives durable, concurrent-friendly writes and clean recovery.
52        conn.pragma_update(None, "journal_mode", "WAL")
53            .map_err(sql_err)?;
54        conn.pragma_update(None, "synchronous", "NORMAL")
55            .map_err(sql_err)?;
56        // Wait briefly on a write lock instead of failing instantly, so a
57        // concurrent `rinne status`/`logs` reader doesn't error the engine.
58        conn.busy_timeout(Duration::from_secs(5)).map_err(sql_err)?;
59        let state = State { conn };
60        state.init_schema()?;
61        Ok(state)
62    }
63
64    /// Open an in-memory database (for tests).
65    pub fn open_in_memory() -> Result<Self> {
66        let conn = Connection::open_in_memory().map_err(sql_err)?;
67        let state = State { conn };
68        state.init_schema()?;
69        Ok(state)
70    }
71
72    /// Clear all run state in place (node statuses, iterations, ledger, meta),
73    /// keeping the connection and schema. Used by `Blackboard::reset_run` so a
74    /// fresh goal starts clean without deleting the db file out from under an
75    /// open connection.
76    pub fn reset(&self) -> Result<()> {
77        self.conn
78            .execute_batch(
79                "DELETE FROM nodes; DELETE FROM usage_ledger; \
80                 DELETE FROM quota_buckets; DELETE FROM run_meta;",
81            )
82            .map_err(sql_err)?;
83        Ok(())
84    }
85
86    fn init_schema(&self) -> Result<()> {
87        self.conn
88            .execute_batch(
89                r#"
90                CREATE TABLE IF NOT EXISTS nodes (
91                    node_id    TEXT PRIMARY KEY,
92                    status     TEXT NOT NULL DEFAULT 'pending',
93                    iterations INTEGER NOT NULL DEFAULT 0,
94                    worker     TEXT,
95                    updated_at INTEGER NOT NULL DEFAULT 0
96                );
97
98                CREATE TABLE IF NOT EXISTS usage_ledger (
99                    id                INTEGER PRIMARY KEY AUTOINCREMENT,
100                    node_id           TEXT NOT NULL,
101                    worker            TEXT,
102                    prompt_tokens     INTEGER NOT NULL,
103                    completion_tokens INTEGER NOT NULL,
104                    wall_ms           INTEGER NOT NULL,
105                    ts                INTEGER NOT NULL DEFAULT 0
106                );
107
108                CREATE TABLE IF NOT EXISTS quota_buckets (
109                    worker     TEXT PRIMARY KEY,
110                    tokens     REAL NOT NULL,
111                    updated_at INTEGER NOT NULL DEFAULT 0
112                );
113
114                CREATE TABLE IF NOT EXISTS run_meta (
115                    key   TEXT PRIMARY KEY,
116                    value TEXT NOT NULL
117                );
118                "#,
119            )
120            .map_err(sql_err)?;
121        Ok(())
122    }
123
124    /// Ensure a node row exists, without disturbing an existing one (so resume
125    /// preserves prior status). Call once per node when a plan is loaded.
126    pub fn ensure_node(&self, node_id: &str) -> Result<()> {
127        self.conn
128            .execute(
129                "INSERT OR IGNORE INTO nodes (node_id, status, iterations, updated_at)
130                 VALUES (?1, 'pending', 0, ?2)",
131                rusqlite::params![node_id, now()],
132            )
133            .map_err(sql_err)?;
134        Ok(())
135    }
136
137    pub fn set_status(&self, node_id: &str, status: NodeStatus) -> Result<()> {
138        self.conn
139            .execute(
140                "UPDATE nodes SET status = ?2, updated_at = ?3 WHERE node_id = ?1",
141                rusqlite::params![node_id, status.as_str(), now()],
142            )
143            .map_err(sql_err)?;
144        Ok(())
145    }
146
147    pub fn set_worker(&self, node_id: &str, worker: &str) -> Result<()> {
148        self.conn
149            .execute(
150                "UPDATE nodes SET worker = ?2, updated_at = ?3 WHERE node_id = ?1",
151                rusqlite::params![node_id, worker, now()],
152            )
153            .map_err(sql_err)?;
154        Ok(())
155    }
156
157    pub fn status(&self, node_id: &str) -> Result<NodeStatus> {
158        let s: Option<String> = optional(self.conn.query_row(
159            "SELECT status FROM nodes WHERE node_id = ?1",
160            [node_id],
161            |r| r.get(0),
162        ))?;
163        Ok(s.map(|s| NodeStatus::from_str(&s))
164            .unwrap_or(NodeStatus::Pending))
165    }
166
167    /// The worker last assigned to a node, if any.
168    pub fn worker(&self, node_id: &str) -> Result<Option<String>> {
169        Ok(optional(self.conn.query_row(
170            "SELECT worker FROM nodes WHERE node_id = ?1",
171            [node_id],
172            |r| r.get::<_, Option<String>>(0),
173        ))?
174        .flatten())
175    }
176
177    /// Increment a node's iteration counter and return the new value.
178    pub fn incr_iteration(&self, node_id: &str) -> Result<u32> {
179        self.conn
180            .execute(
181                "UPDATE nodes SET iterations = iterations + 1, updated_at = ?2 WHERE node_id = ?1",
182                rusqlite::params![node_id, now()],
183            )
184            .map_err(sql_err)?;
185        self.iterations(node_id)
186    }
187
188    pub fn iterations(&self, node_id: &str) -> Result<u32> {
189        let n: Option<i64> = optional(self.conn.query_row(
190            "SELECT iterations FROM nodes WHERE node_id = ?1",
191            [node_id],
192            |r| r.get(0),
193        ))?;
194        Ok(n.unwrap_or(0).clamp(0, u32::MAX as i64) as u32)
195    }
196
197    /// Record token/time usage for a node invocation.
198    pub fn record_usage(&self, node_id: &str, worker: &str, usage: &Usage) -> Result<()> {
199        self.conn
200            .execute(
201                "INSERT INTO usage_ledger
202                   (node_id, worker, prompt_tokens, completion_tokens, wall_ms, ts)
203                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
204                rusqlite::params![
205                    node_id,
206                    worker,
207                    usage.prompt_tokens as i64,
208                    usage.completion_tokens as i64,
209                    usage.wall_ms as i64,
210                    now()
211                ],
212            )
213            .map_err(sql_err)?;
214        Ok(())
215    }
216
217    /// Total iterations recorded across all nodes (the run-level loop count).
218    pub fn total_iterations(&self) -> Result<u32> {
219        // COALESCE(SUM(...)) always returns exactly one row, so any error here is
220        // a real DB failure — propagate it rather than reading "0 iterations",
221        // which would silently bypass the global iteration cap.
222        let n: i64 = self
223            .conn
224            .query_row("SELECT COALESCE(SUM(iterations), 0) FROM nodes", [], |r| {
225                r.get(0)
226            })
227            .map_err(sql_err)?;
228        Ok(n.clamp(0, u32::MAX as i64) as u32)
229    }
230
231    /// Aggregate token usage across the run.
232    pub fn total_usage(&self) -> Result<Usage> {
233        let (p, c, w): (i64, i64, i64) = self
234            .conn
235            .query_row(
236                "SELECT COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0), \
237                        COALESCE(SUM(wall_ms),0) FROM usage_ledger",
238                [],
239                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
240            )
241            .map_err(sql_err)?;
242        Ok(Usage {
243            prompt_tokens: p.max(0) as u64,
244            completion_tokens: c.max(0) as u64,
245            wall_ms: w.max(0) as u64,
246        })
247    }
248
249    /// Per-invocation usage rows for trajectory inspection (`rinne logs`).
250    pub fn usage_rows(&self) -> Result<Vec<UsageRow>> {
251        let mut stmt = self
252            .conn
253            .prepare(
254                "SELECT node_id, worker, prompt_tokens, completion_tokens, wall_ms, ts \
255                 FROM usage_ledger ORDER BY id ASC",
256            )
257            .map_err(sql_err)?;
258        let rows = stmt
259            .query_map([], |r| {
260                Ok(UsageRow {
261                    node_id: r.get(0)?,
262                    worker: r.get::<_, Option<String>>(1)?.unwrap_or_default(),
263                    prompt_tokens: r.get::<_, i64>(2)? as u64,
264                    completion_tokens: r.get::<_, i64>(3)? as u64,
265                    wall_ms: r.get::<_, i64>(4)? as u64,
266                    ts: r.get::<_, i64>(5)? as u64,
267                })
268            })
269            .map_err(sql_err)?;
270        let mut out = Vec::new();
271        for row in rows {
272            out.push(row.map_err(sql_err)?);
273        }
274        Ok(out)
275    }
276
277    /// Store/read a run-level scalar (e.g. the start timestamp).
278    pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {
279        self.conn
280            .execute(
281                "INSERT INTO run_meta (key, value) VALUES (?1, ?2)
282                 ON CONFLICT(key) DO UPDATE SET value = ?2",
283                rusqlite::params![key, value],
284            )
285            .map_err(sql_err)?;
286        Ok(())
287    }
288
289    pub fn meta(&self, key: &str) -> Result<Option<String>> {
290        optional(
291            self.conn
292                .query_row("SELECT value FROM run_meta WHERE key = ?1", [key], |r| {
293                    r.get(0)
294                }),
295        )
296    }
297}
298
299fn sql_err(e: rusqlite::Error) -> RinneError {
300    RinneError::Blackboard(format!("sqlite: {e}"))
301}
302
303fn now() -> i64 {
304    std::time::SystemTime::now()
305        .duration_since(std::time::SystemTime::UNIX_EPOCH)
306        .map(|d| d.as_secs() as i64)
307        .unwrap_or(0)
308}