1use chrono::{DateTime, Datelike as _, FixedOffset, NaiveDate};
17use serde_json::{Map, Value};
18
19use crate::error::{KernelError, Result};
20use crate::proc::{LedgerEntry, LedgerQuery, ObservationQuery};
21
22pub(crate) const REGISTRY_TABLE: &str = "_adk_kernel_ledger_migrations";
24
25#[cfg(feature = "sqlite")]
26pub(crate) const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
27 1,
28 "create kernel ledger, observation and pass state tables",
29 "\
30CREATE TABLE IF NOT EXISTS adk_kernel_ledger (\
31 seq INTEGER PRIMARY KEY AUTOINCREMENT, \
32 ts_ms BIGINT NOT NULL, \
33 offset_s INTEGER NOT NULL, \
34 partition_id TEXT NOT NULL, \
35 agent TEXT NOT NULL, \
36 kind TEXT NOT NULL, \
37 effect TEXT, \
38 duration_ms BIGINT, \
39 subject_hash TEXT, \
40 meta TEXT NOT NULL, \
41 trace_id TEXT\
42);\
43CREATE INDEX IF NOT EXISTS adk_kernel_ledger_ts ON adk_kernel_ledger (ts_ms);\
44CREATE INDEX IF NOT EXISTS adk_kernel_ledger_partition ON adk_kernel_ledger (partition_id, seq);\
45CREATE INDEX IF NOT EXISTS adk_kernel_ledger_kind ON adk_kernel_ledger (kind, seq);\
46CREATE TABLE IF NOT EXISTS adk_kernel_observations (\
47 id TEXT PRIMARY KEY, \
48 partition_id TEXT NOT NULL, \
49 as_of BIGINT NOT NULL, \
50 body TEXT NOT NULL\
51);\
52CREATE INDEX IF NOT EXISTS adk_kernel_observations_as_of ON adk_kernel_observations (as_of, id);\
53CREATE TABLE IF NOT EXISTS adk_kernel_proc_state (\
54 partition_id TEXT PRIMARY KEY, \
55 body TEXT NOT NULL\
56);",
57)];
58
59#[cfg(feature = "postgres")]
62pub(crate) const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
63 1,
64 "create kernel ledger, observation and pass state tables",
65 "\
66CREATE TABLE IF NOT EXISTS adk_kernel_ledger (\
67 seq BIGSERIAL PRIMARY KEY, \
68 ts_ms BIGINT NOT NULL, \
69 offset_s INTEGER NOT NULL, \
70 partition_id TEXT NOT NULL, \
71 agent TEXT NOT NULL, \
72 kind TEXT NOT NULL, \
73 effect TEXT, \
74 duration_ms BIGINT, \
75 subject_hash TEXT, \
76 meta TEXT NOT NULL, \
77 trace_id TEXT\
78);\
79CREATE INDEX IF NOT EXISTS adk_kernel_ledger_ts ON adk_kernel_ledger (ts_ms);\
80CREATE INDEX IF NOT EXISTS adk_kernel_ledger_partition ON adk_kernel_ledger (partition_id, seq);\
81CREATE INDEX IF NOT EXISTS adk_kernel_ledger_kind ON adk_kernel_ledger (kind, seq);\
82CREATE TABLE IF NOT EXISTS adk_kernel_observations (\
83 id TEXT COLLATE \"C\" PRIMARY KEY, \
84 partition_id TEXT NOT NULL, \
85 as_of BIGINT NOT NULL, \
86 body TEXT NOT NULL\
87);\
88CREATE INDEX IF NOT EXISTS adk_kernel_observations_as_of ON adk_kernel_observations (as_of, id);\
89CREATE TABLE IF NOT EXISTS adk_kernel_proc_state (\
90 partition_id TEXT COLLATE \"C\" PRIMARY KEY, \
91 body TEXT NOT NULL\
92);",
93)];
94
95pub(crate) const APPEND: &str = "\
96INSERT INTO adk_kernel_ledger \
97 (ts_ms, offset_s, partition_id, agent, kind, effect, duration_ms, subject_hash, meta, \
98 trace_id) \
99VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING seq";
100
101const COLUMNS: &str = "seq, ts_ms, offset_s, partition_id, agent, kind, effect, duration_ms, \
102 subject_hash, meta, trace_id";
103
104pub(crate) const PUT_OBSERVATION: &str = "\
105INSERT INTO adk_kernel_observations (id, partition_id, as_of, body) VALUES ($1, $2, $3, $4) \
106ON CONFLICT (id) DO UPDATE SET \
107 partition_id = excluded.partition_id, as_of = excluded.as_of, body = excluded.body";
108
109pub(crate) const PASS_STATE: &str =
110 "SELECT body FROM adk_kernel_proc_state WHERE partition_id = $1";
111
112pub(crate) const PASS_STATES: &str = "SELECT body FROM adk_kernel_proc_state ORDER BY partition_id";
113
114pub(crate) const PUT_PASS_STATE: &str = "\
115INSERT INTO adk_kernel_proc_state (partition_id, body) VALUES ($1, $2) \
116ON CONFLICT (partition_id) DO UPDATE SET body = excluded.body";
117
118pub(crate) type Row = (
120 i64,
121 i64,
122 i32,
123 String,
124 String,
125 String,
126 Option<String>,
127 Option<i64>,
128 Option<String>,
129 String,
130 Option<String>,
131);
132
133pub(crate) enum Bind {
135 Text(String),
136 Int(i64),
137}
138
139pub(crate) fn list(query: &LedgerQuery) -> (String, Vec<Bind>) {
141 let mut conditions = Vec::new();
142 let mut binds = Vec::new();
143 let bind = |binds: &mut Vec<Bind>, value: Bind| {
144 binds.push(value);
145 format!("${}", binds.len())
146 };
147 if let Some(partition) = &query.partition {
148 let n = bind(&mut binds, Bind::Text(partition.as_str().to_string()));
149 conditions.push(format!("partition_id = {n}"));
150 }
151 if !query.kinds.is_empty() {
152 let names: Vec<String> =
153 query.kinds.iter().map(|kind| bind(&mut binds, Bind::Text(kind.clone()))).collect();
154 conditions.push(format!("kind IN ({})", names.join(", ")));
155 }
156 if let Some(agent) = &query.agent {
157 let n = bind(&mut binds, Bind::Text(agent.clone()));
158 conditions.push(format!("agent = {n}"));
159 }
160 if let Some(from) = query.from {
161 let n = bind(&mut binds, Bind::Int(from.timestamp_millis()));
162 conditions.push(format!("ts_ms >= {n}"));
163 }
164 if let Some(to) = query.to {
165 let n = bind(&mut binds, Bind::Int(to.timestamp_millis()));
166 conditions.push(format!("ts_ms < {n}"));
167 }
168 if let Some(after) = query.after {
169 let n = bind(&mut binds, Bind::Int(i64::try_from(after).unwrap_or(i64::MAX)));
170 conditions.push(format!("seq > {n}"));
171 }
172 let mut sql = format!("SELECT {COLUMNS} FROM adk_kernel_ledger");
173 if !conditions.is_empty() {
174 sql.push_str(" WHERE ");
175 sql.push_str(&conditions.join(" AND "));
176 }
177 sql.push_str(" ORDER BY seq");
178 if let Some(limit) = query.limit {
179 let n = bind(&mut binds, Bind::Int(i64::try_from(limit).unwrap_or(i64::MAX)));
180 sql.push_str(&format!(" LIMIT {n}"));
181 }
182 (sql, binds)
183}
184
185pub(crate) fn observations(query: &ObservationQuery) -> (String, Vec<Bind>) {
187 let mut conditions = Vec::new();
188 let mut binds = Vec::new();
189 if let Some(partition) = &query.partition {
190 binds.push(Bind::Text(partition.as_str().to_string()));
191 conditions.push(format!("partition_id = ${}", binds.len()));
192 }
193 if let Some(since) = query.since {
194 binds.push(Bind::Int(day(since)));
195 conditions.push(format!("as_of >= ${}", binds.len()));
196 }
197 let mut sql = "SELECT body FROM adk_kernel_observations".to_string();
198 if !conditions.is_empty() {
199 sql.push_str(" WHERE ");
200 sql.push_str(&conditions.join(" AND "));
201 }
202 sql.push_str(" ORDER BY as_of DESC, id");
203 if let Some(limit) = query.limit {
204 binds.push(Bind::Int(i64::try_from(limit).unwrap_or(i64::MAX)));
205 sql.push_str(&format!(" LIMIT ${}", binds.len()));
206 }
207 (sql, binds)
208}
209
210pub(crate) fn day(day: NaiveDate) -> i64 {
212 i64::from(day.num_days_from_ce())
213}
214
215pub(crate) struct Encoded {
217 pub(crate) ts_ms: i64,
218 pub(crate) offset_s: i32,
219 pub(crate) duration_ms: Option<i64>,
220 pub(crate) meta: String,
221}
222
223impl Encoded {
224 pub(crate) fn new(entry: &LedgerEntry) -> Result<Self> {
225 Ok(Self {
226 ts_ms: entry.ts.timestamp_millis(),
227 offset_s: entry.ts.offset().local_minus_utc(),
228 duration_ms: entry.duration_ms.map(|ms| i64::try_from(ms).unwrap_or(i64::MAX)),
229 meta: serde_json::to_string(&entry.meta)?,
230 })
231 }
232}
233
234pub(crate) fn decode(backend: &'static str, row: Row) -> Result<LedgerEntry> {
236 let (
237 seq,
238 ts_ms,
239 offset_s,
240 partition,
241 agent,
242 kind,
243 effect,
244 duration_ms,
245 subject_hash,
246 meta,
247 trace_id,
248 ) = row;
249 let corrupt = |column: &str| KernelError::Store {
250 backend,
251 reason: format!("column `{column}` of ledger row {seq} is corrupt"),
252 };
253 let offset = FixedOffset::east_opt(offset_s).ok_or_else(|| corrupt("offset_s"))?;
254 let ts = DateTime::from_timestamp_millis(ts_ms).ok_or_else(|| corrupt("ts_ms"))?;
255 let meta: Map<String, Value> = serde_json::from_str(&meta).map_err(|_| corrupt("meta"))?;
256 Ok(LedgerEntry {
257 seq: u64::try_from(seq).map_err(|_| corrupt("seq"))?,
258 ts: ts.with_timezone(&offset),
259 partition: partition.into(),
260 agent,
261 kind,
262 effect,
263 duration_ms: duration_ms.map(|ms| u64::try_from(ms).unwrap_or(0)),
264 subject_hash,
265 meta,
266 trace_id,
267 })
268}
269
270pub(crate) fn body<T: serde::de::DeserializeOwned>(
272 backend: &'static str,
273 table: &str,
274 body: &str,
275) -> Result<T> {
276 serde_json::from_str(body).map_err(|error| KernelError::Store {
277 backend,
278 reason: format!("a row of `{table}` is corrupt: {error}"),
279 })
280}
281
282pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
284 KernelError::Store { backend, reason: format!("could not {action}: {error}") }
285}
286
287macro_rules! sql_ledger_store {
290 ($store:ty, $backend:literal) => {
291 #[async_trait::async_trait]
292 impl $crate::proc::LedgerStore for $store {
293 async fn append(
294 &self,
295 mut entry: $crate::proc::LedgerEntry,
296 ) -> $crate::error::Result<$crate::proc::LedgerEntry> {
297 let row = $crate::stores::ledger_sql::Encoded::new(&entry)?;
298 let (seq,): (i64,) = sqlx::query_as($crate::stores::ledger_sql::APPEND)
299 .bind(row.ts_ms)
300 .bind(row.offset_s)
301 .bind(entry.partition.as_str())
302 .bind(&entry.agent)
303 .bind(&entry.kind)
304 .bind(&entry.effect)
305 .bind(row.duration_ms)
306 .bind(&entry.subject_hash)
307 .bind(row.meta)
308 .bind(&entry.trace_id)
309 .fetch_one(&self.pool)
310 .await
311 .map_err(|e| {
312 $crate::stores::ledger_sql::db_error($backend, "append to the ledger", &e)
313 })?;
314 entry.seq = u64::try_from(seq).unwrap_or_default();
315 Ok(entry)
316 }
317
318 async fn list(
319 &self,
320 query: &$crate::proc::LedgerQuery,
321 ) -> $crate::error::Result<Vec<$crate::proc::LedgerEntry>> {
322 let (sql, binds) = $crate::stores::ledger_sql::list(query);
323 let mut statement =
324 sqlx::query_as::<_, $crate::stores::ledger_sql::Row>(sqlx::AssertSqlSafe(sql));
325 for bind in binds {
326 statement = match bind {
327 $crate::stores::ledger_sql::Bind::Text(text) => statement.bind(text),
328 $crate::stores::ledger_sql::Bind::Int(int) => statement.bind(int),
329 };
330 }
331 let rows = statement.fetch_all(&self.pool).await.map_err(|e| {
332 $crate::stores::ledger_sql::db_error($backend, "read the ledger", &e)
333 })?;
334 rows.into_iter()
335 .map(|row| $crate::stores::ledger_sql::decode($backend, row))
336 .collect()
337 }
338
339 async fn put_observation(
340 &self,
341 observation: $crate::proc::Observation,
342 ) -> $crate::error::Result<()> {
343 sqlx::query($crate::stores::ledger_sql::PUT_OBSERVATION)
344 .bind(&observation.id)
345 .bind(observation.partition.as_str())
346 .bind($crate::stores::ledger_sql::day(observation.as_of))
347 .bind(serde_json::to_string(&observation)?)
348 .execute(&self.pool)
349 .await
350 .map_err(|e| {
351 $crate::stores::ledger_sql::db_error($backend, "write an observation", &e)
352 })?;
353 Ok(())
354 }
355
356 async fn observations(
357 &self,
358 query: &$crate::proc::ObservationQuery,
359 ) -> $crate::error::Result<Vec<$crate::proc::Observation>> {
360 let (sql, binds) = $crate::stores::ledger_sql::observations(query);
361 let mut statement = sqlx::query_as::<_, (String,)>(sqlx::AssertSqlSafe(sql));
362 for bind in binds {
363 statement = match bind {
364 $crate::stores::ledger_sql::Bind::Text(text) => statement.bind(text),
365 $crate::stores::ledger_sql::Bind::Int(int) => statement.bind(int),
366 };
367 }
368 let rows = statement.fetch_all(&self.pool).await.map_err(|e| {
369 $crate::stores::ledger_sql::db_error($backend, "read the observations", &e)
370 })?;
371 rows.iter()
372 .map(|(body,)| {
373 $crate::stores::ledger_sql::body($backend, "adk_kernel_observations", body)
374 })
375 .collect()
376 }
377
378 async fn pass_state(
379 &self,
380 partition: &$crate::partition::PartitionId,
381 ) -> $crate::error::Result<Option<$crate::proc::PassState>> {
382 let row: Option<(String,)> = sqlx::query_as($crate::stores::ledger_sql::PASS_STATE)
383 .bind(partition.as_str())
384 .fetch_optional(&self.pool)
385 .await
386 .map_err(|e| {
387 $crate::stores::ledger_sql::db_error($backend, "read the pass state", &e)
388 })?;
389 row.map(|(body,)| {
390 $crate::stores::ledger_sql::body($backend, "adk_kernel_proc_state", &body)
391 })
392 .transpose()
393 }
394
395 async fn pass_states(&self) -> $crate::error::Result<Vec<$crate::proc::PassState>> {
396 let rows: Vec<(String,)> = sqlx::query_as($crate::stores::ledger_sql::PASS_STATES)
397 .fetch_all(&self.pool)
398 .await
399 .map_err(|e| {
400 $crate::stores::ledger_sql::db_error($backend, "read the pass states", &e)
401 })?;
402 rows.iter()
403 .map(|(body,)| {
404 $crate::stores::ledger_sql::body($backend, "adk_kernel_proc_state", body)
405 })
406 .collect()
407 }
408
409 async fn put_pass_state(
410 &self,
411 state: $crate::proc::PassState,
412 ) -> $crate::error::Result<()> {
413 sqlx::query($crate::stores::ledger_sql::PUT_PASS_STATE)
414 .bind(state.partition.as_str())
415 .bind(serde_json::to_string(&state)?)
416 .execute(&self.pool)
417 .await
418 .map_err(|e| {
419 $crate::stores::ledger_sql::db_error($backend, "write the pass state", &e)
420 })?;
421 Ok(())
422 }
423 }
424 };
425}
426
427#[cfg(feature = "sqlite")]
455#[derive(Debug, Clone)]
456pub struct SqliteLedgerStore {
457 pool: sqlx::SqlitePool,
458}
459
460#[cfg(feature = "sqlite")]
461impl SqliteLedgerStore {
462 pub fn new(pool: sqlx::SqlitePool) -> Self {
464 Self { pool }
465 }
466
467 pub fn pool(&self) -> &sqlx::SqlitePool {
469 &self.pool
470 }
471
472 pub async fn migrate(&self) -> Result<()> {
479 adk_session::migration::sqlite_runner::run_sql_migrations(
480 &self.pool,
481 REGISTRY_TABLE,
482 SQLITE_MIGRATIONS,
483 || async { Ok(false) },
484 )
485 .await
486 .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
487 }
488}
489
490#[cfg(feature = "sqlite")]
491sql_ledger_store!(SqliteLedgerStore, "sqlite");
492
493#[cfg(feature = "postgres")]
510#[derive(Debug, Clone)]
511pub struct PostgresLedgerStore {
512 pool: sqlx::PgPool,
513}
514
515#[cfg(feature = "postgres")]
516impl PostgresLedgerStore {
517 pub fn new(pool: sqlx::PgPool) -> Self {
519 Self { pool }
520 }
521
522 pub fn pool(&self) -> &sqlx::PgPool {
524 &self.pool
525 }
526
527 pub async fn connect(database_url: &str) -> Result<Self> {
533 let pool =
534 sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
535 backend: "postgres",
536 reason: format!("could not connect: {error}"),
537 })?;
538 Ok(Self::new(pool))
539 }
540
541 pub async fn migrate(&self) -> Result<()> {
549 super::postgres::migrate_locked(self.pool.clone(), REGISTRY_TABLE, POSTGRES_MIGRATIONS)
550 .await
551 }
552}
553
554#[cfg(feature = "postgres")]
555sql_ledger_store!(PostgresLedgerStore, "postgres");
556
557#[cfg(test)]
558mod tests {
559 use super::*;
560
561 #[test]
562 fn list_numbers_parameters_in_order() {
563 let query = LedgerQuery::default()
564 .partition("work")
565 .kind("tool_call")
566 .kind("intent")
567 .agent("harness")
568 .from(DateTime::from_timestamp_millis(1).unwrap())
569 .to(DateTime::from_timestamp_millis(2).unwrap())
570 .after(9)
571 .limit(5);
572 assert_eq!(
573 list(&query).0,
574 format!(
575 "SELECT {COLUMNS} FROM adk_kernel_ledger WHERE partition_id = $1 AND kind IN \
576 ($2, $3) AND agent = $4 AND ts_ms >= $5 AND ts_ms < $6 AND seq > $7 ORDER BY \
577 seq LIMIT $8"
578 )
579 );
580 assert_eq!(
581 list(&LedgerQuery::default()).0,
582 format!("SELECT {COLUMNS} FROM adk_kernel_ledger ORDER BY seq")
583 );
584 let observed = ObservationQuery::default()
585 .partition("work")
586 .since(NaiveDate::from_ymd_opt(2026, 10, 1).unwrap())
587 .limit(2);
588 assert_eq!(
589 observations(&observed).0,
590 "SELECT body FROM adk_kernel_observations WHERE partition_id = $1 AND as_of >= $2 \
591 ORDER BY as_of DESC, id LIMIT $3"
592 );
593 }
594}