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;
8
9use rusqlite::Connection;
10
11use crate::worker::Usage;
12use crate::{Result, RinneError};
13
14/// The lifecycle status of a node (`CONTEXT.md` §12 scheduler).
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum NodeStatus {
17    /// Not yet started.
18    Pending,
19    /// Dispatched and running (or interrupted mid-run).
20    Running,
21    /// Completed successfully.
22    Succeeded,
23    /// Ran and failed (terminal for Phase 3; P5 adds loop-back).
24    Failed,
25    /// Parked awaiting a human (checkpoint / stuck escalation — P5).
26    Parked,
27}
28
29impl NodeStatus {
30    fn as_str(self) -> &'static str {
31        match self {
32            NodeStatus::Pending => "pending",
33            NodeStatus::Running => "running",
34            NodeStatus::Succeeded => "succeeded",
35            NodeStatus::Failed => "failed",
36            NodeStatus::Parked => "parked",
37        }
38    }
39
40    fn from_str(s: &str) -> NodeStatus {
41        match s {
42            "running" => NodeStatus::Running,
43            "succeeded" => NodeStatus::Succeeded,
44            "failed" => NodeStatus::Failed,
45            "parked" => NodeStatus::Parked,
46            _ => NodeStatus::Pending,
47        }
48    }
49
50    pub fn label(self) -> &'static str {
51        self.as_str()
52    }
53
54    pub fn is_terminal_success(self) -> bool {
55        matches!(self, NodeStatus::Succeeded)
56    }
57}
58
59/// One recorded worker invocation, for `rinne logs`.
60#[derive(Debug, Clone)]
61pub struct UsageRow {
62    pub node_id: String,
63    pub worker: String,
64    pub prompt_tokens: u64,
65    pub completion_tokens: u64,
66    pub wall_ms: u64,
67    pub ts: u64,
68}
69
70/// A handle to the run's SQLite state.
71pub struct State {
72    conn: Connection,
73}
74
75impl State {
76    /// Open (creating if needed) the state database at `path`, ensuring schema.
77    pub fn open(path: &Path) -> Result<Self> {
78        let conn = Connection::open(path).map_err(sql_err)?;
79        // WAL gives durable, concurrent-friendly writes and clean recovery.
80        conn.pragma_update(None, "journal_mode", "WAL")
81            .map_err(sql_err)?;
82        conn.pragma_update(None, "synchronous", "NORMAL")
83            .map_err(sql_err)?;
84        let state = State { conn };
85        state.init_schema()?;
86        Ok(state)
87    }
88
89    /// Open an in-memory database (for tests).
90    pub fn open_in_memory() -> Result<Self> {
91        let conn = Connection::open_in_memory().map_err(sql_err)?;
92        let state = State { conn };
93        state.init_schema()?;
94        Ok(state)
95    }
96
97    fn init_schema(&self) -> Result<()> {
98        self.conn
99            .execute_batch(
100                r#"
101                CREATE TABLE IF NOT EXISTS nodes (
102                    node_id    TEXT PRIMARY KEY,
103                    status     TEXT NOT NULL DEFAULT 'pending',
104                    iterations INTEGER NOT NULL DEFAULT 0,
105                    worker     TEXT,
106                    updated_at INTEGER NOT NULL DEFAULT 0
107                );
108
109                CREATE TABLE IF NOT EXISTS usage_ledger (
110                    id                INTEGER PRIMARY KEY AUTOINCREMENT,
111                    node_id           TEXT NOT NULL,
112                    worker            TEXT,
113                    prompt_tokens     INTEGER NOT NULL,
114                    completion_tokens INTEGER NOT NULL,
115                    wall_ms           INTEGER NOT NULL,
116                    ts                INTEGER NOT NULL DEFAULT 0
117                );
118
119                CREATE TABLE IF NOT EXISTS quota_buckets (
120                    worker     TEXT PRIMARY KEY,
121                    tokens     REAL NOT NULL,
122                    updated_at INTEGER NOT NULL DEFAULT 0
123                );
124
125                CREATE TABLE IF NOT EXISTS run_meta (
126                    key   TEXT PRIMARY KEY,
127                    value TEXT NOT NULL
128                );
129                "#,
130            )
131            .map_err(sql_err)?;
132        Ok(())
133    }
134
135    /// Ensure a node row exists, without disturbing an existing one (so resume
136    /// preserves prior status). Call once per node when a plan is loaded.
137    pub fn ensure_node(&self, node_id: &str) -> Result<()> {
138        self.conn
139            .execute(
140                "INSERT OR IGNORE INTO nodes (node_id, status, iterations, updated_at)
141                 VALUES (?1, 'pending', 0, ?2)",
142                rusqlite::params![node_id, now()],
143            )
144            .map_err(sql_err)?;
145        Ok(())
146    }
147
148    pub fn set_status(&self, node_id: &str, status: NodeStatus) -> Result<()> {
149        self.conn
150            .execute(
151                "UPDATE nodes SET status = ?2, updated_at = ?3 WHERE node_id = ?1",
152                rusqlite::params![node_id, status.as_str(), now()],
153            )
154            .map_err(sql_err)?;
155        Ok(())
156    }
157
158    pub fn set_worker(&self, node_id: &str, worker: &str) -> Result<()> {
159        self.conn
160            .execute(
161                "UPDATE nodes SET worker = ?2, updated_at = ?3 WHERE node_id = ?1",
162                rusqlite::params![node_id, worker, now()],
163            )
164            .map_err(sql_err)?;
165        Ok(())
166    }
167
168    pub fn status(&self, node_id: &str) -> Result<NodeStatus> {
169        let s: Option<String> = self
170            .conn
171            .query_row(
172                "SELECT status FROM nodes WHERE node_id = ?1",
173                [node_id],
174                |r| r.get(0),
175            )
176            .ok();
177        Ok(s.map(|s| NodeStatus::from_str(&s)).unwrap_or(NodeStatus::Pending))
178    }
179
180    /// The worker last assigned to a node, if any.
181    pub fn worker(&self, node_id: &str) -> Result<Option<String>> {
182        Ok(self
183            .conn
184            .query_row(
185                "SELECT worker FROM nodes WHERE node_id = ?1",
186                [node_id],
187                |r| r.get::<_, Option<String>>(0),
188            )
189            .ok()
190            .flatten())
191    }
192
193    /// Increment a node's iteration counter and return the new value.
194    pub fn incr_iteration(&self, node_id: &str) -> Result<u32> {
195        self.conn
196            .execute(
197                "UPDATE nodes SET iterations = iterations + 1, updated_at = ?2 WHERE node_id = ?1",
198                rusqlite::params![node_id, now()],
199            )
200            .map_err(sql_err)?;
201        self.iterations(node_id)
202    }
203
204    pub fn iterations(&self, node_id: &str) -> Result<u32> {
205        let n: i64 = self
206            .conn
207            .query_row(
208                "SELECT iterations FROM nodes WHERE node_id = ?1",
209                [node_id],
210                |r| r.get(0),
211            )
212            .unwrap_or(0);
213        Ok(n as u32)
214    }
215
216    /// Record token/time usage for a node invocation.
217    pub fn record_usage(&self, node_id: &str, worker: &str, usage: &Usage) -> Result<()> {
218        self.conn
219            .execute(
220                "INSERT INTO usage_ledger
221                   (node_id, worker, prompt_tokens, completion_tokens, wall_ms, ts)
222                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
223                rusqlite::params![
224                    node_id,
225                    worker,
226                    usage.prompt_tokens as i64,
227                    usage.completion_tokens as i64,
228                    usage.wall_ms as i64,
229                    now()
230                ],
231            )
232            .map_err(sql_err)?;
233        Ok(())
234    }
235
236    /// Total iterations recorded across all nodes (the run-level loop count).
237    pub fn total_iterations(&self) -> Result<u32> {
238        let n: i64 = self
239            .conn
240            .query_row("SELECT COALESCE(SUM(iterations), 0) FROM nodes", [], |r| {
241                r.get(0)
242            })
243            .unwrap_or(0);
244        Ok(n as u32)
245    }
246
247    /// Aggregate token usage across the run.
248    pub fn total_usage(&self) -> Result<Usage> {
249        let (p, c, w): (i64, i64, i64) = self
250            .conn
251            .query_row(
252                "SELECT COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0), \
253                        COALESCE(SUM(wall_ms),0) FROM usage_ledger",
254                [],
255                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
256            )
257            .unwrap_or((0, 0, 0));
258        Ok(Usage {
259            prompt_tokens: p as u64,
260            completion_tokens: c as u64,
261            wall_ms: w as u64,
262        })
263    }
264
265    /// Per-invocation usage rows for trajectory inspection (`rinne logs`).
266    pub fn usage_rows(&self) -> Result<Vec<UsageRow>> {
267        let mut stmt = self
268            .conn
269            .prepare(
270                "SELECT node_id, worker, prompt_tokens, completion_tokens, wall_ms, ts \
271                 FROM usage_ledger ORDER BY id ASC",
272            )
273            .map_err(sql_err)?;
274        let rows = stmt
275            .query_map([], |r| {
276                Ok(UsageRow {
277                    node_id: r.get(0)?,
278                    worker: r.get::<_, Option<String>>(1)?.unwrap_or_default(),
279                    prompt_tokens: r.get::<_, i64>(2)? as u64,
280                    completion_tokens: r.get::<_, i64>(3)? as u64,
281                    wall_ms: r.get::<_, i64>(4)? as u64,
282                    ts: r.get::<_, i64>(5)? as u64,
283                })
284            })
285            .map_err(sql_err)?;
286        let mut out = Vec::new();
287        for row in rows {
288            out.push(row.map_err(sql_err)?);
289        }
290        Ok(out)
291    }
292
293    /// Store/read a run-level scalar (e.g. the start timestamp).
294    pub fn set_meta(&self, key: &str, value: &str) -> Result<()> {
295        self.conn
296            .execute(
297                "INSERT INTO run_meta (key, value) VALUES (?1, ?2)
298                 ON CONFLICT(key) DO UPDATE SET value = ?2",
299                rusqlite::params![key, value],
300            )
301            .map_err(sql_err)?;
302        Ok(())
303    }
304
305    pub fn meta(&self, key: &str) -> Result<Option<String>> {
306        Ok(self
307            .conn
308            .query_row("SELECT value FROM run_meta WHERE key = ?1", [key], |r| {
309                r.get(0)
310            })
311            .ok())
312    }
313}
314
315fn sql_err(e: rusqlite::Error) -> RinneError {
316    RinneError::Blackboard(format!("sqlite: {e}"))
317}
318
319fn now() -> i64 {
320    std::time::SystemTime::now()
321        .duration_since(std::time::SystemTime::UNIX_EPOCH)
322        .map(|d| d.as_secs() as i64)
323        .unwrap_or(0)
324}