adk-kernel 3.0.0

Agent kernel for ADK-Rust: a resident supervisor with a process model, wake sources, an event bus and a control plane over durable runs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! The kernel-owned stores and their backends (spec 3.2 §7.1, §7.3, §13 Q8).
//!
//! Phase 1 has one kernel-owned store, the [`ProcessStore`] side table, with the kernel's
//! daily spend totals per process (the phase-1 source of `ProcessView::spend_today` and
//! `spend_7d`). It runs on every
//! backend that holds the run, schedule and governance stores, with one conformance suite
//! (`process_store_conformance_tests!`, feature `conformance`):
//!
//! | Backend | Type | Feature | Opened from |
//! |---|---|---|---|
//! | In-memory | [`InMemoryProcessStore`] | — | — |
//! | SQLite | `SqliteProcessStore` | `sqlite` (default) | the pool of `harness.db`, with its own migration table |
//! | PostgreSQL | `PostgresProcessStore` | `postgres` | the URL of `adk-rust serve --store` |
//! | Redis | `RedisProcessStore` | `redis` | the URL of `adk-rust serve --store` |
//!
//! Phase 2 adds the [`AgendaStore`](crate::AgendaStore) on the same four backends
//! ([`InMemoryAgendaStore`], `SqliteAgendaStore`, `PostgresAgendaStore`, `RedisAgendaStore`,
//! suite `agenda_store_conformance_tests!`).
//!
//! The driver store (`drivers::DriverStore`, feature `drivers`) runs on
//! the same four backends: `InMemoryDriverStore`, `SqliteDriverStore`,
//! `PostgresDriverStore` and `RedisDriverStore` (spec 3.2 §7.7).
//!
//! The ledger store (`proc::LedgerStore`, feature `proc`) runs on the same four backends:
//! `InMemoryLedgerStore`, `SqliteLedgerStore`, `PostgresLedgerStore` and `RedisLedgerStore`
//! (spec 3.2 §7.10, suite `ledger_store_conformance_tests!`).
//!
//! The [`PartitionStore`](crate::PartitionStore) — the partition table and the crossing
//! ledger (§7.8) — runs on in-memory, SQLite, PostgreSQL and Redis
//! ([`InMemoryPartitionStore`], `SqlitePartitionStore`, `PostgresPartitionStore`,
//! `RedisPartitionStore`, suite `partition_store_conformance_tests!`).
//!
//! Phase 4 adds these stores on MongoDB, Firestore and Neo4j (§13 Q8), each checked by its
//! conformance suite against a live server in CI:
//!
//! | Store | MongoDB (`mongodb`) | Firestore (`firestore`) | Neo4j (`neo4j`) |
//! |---|---|---|---|
//! | [`ProcessStore`] | `MongoProcessStore` | `FirestoreProcessStore` | `Neo4jProcessStore` |
//! | [`AgendaStore`](crate::AgendaStore) | `MongoAgendaStore` | `FirestoreAgendaStore` | `Neo4jAgendaStore` |
//! | `drivers::DriverStore` (with `drivers`) | `MongoDriverStore` | `FirestoreDriverStore` | `Neo4jDriverStore` |
//! | `proc::LedgerStore` (with `proc`) | `MongoLedgerStore` | `FirestoreLedgerStore` | `Neo4jLedgerStore` |
//! | [`PartitionStore`](crate::PartitionStore) | `MongoPartitionStore` | `FirestorePartitionStore` | `Neo4jPartitionStore` |
//! | [`CronWatermarkStore`](crate::CronWatermarkStore) | `MongoCronWatermarkStore` | `FirestoreCronWatermarkStore` | `Neo4jCronWatermarkStore` |
//!
//! The [`CronWatermarkStore`](crate::CronWatermarkStore) — where each cron wake source left
//! off (§7.4) — runs on in-memory, SQLite, PostgreSQL and Redis
//! ([`InMemoryCronWatermarkStore`], `SqliteCronWatermarkStore`, `PostgresCronWatermarkStore`,
//! `RedisCronWatermarkStore`, suite `cron_watermark_store_conformance_tests!`), and on
//! MongoDB, Firestore and Neo4j.
//!
//! The [`AgentStore`](crate::agents::AgentStore) — the agents a person adds (spec 3.3 §5.7,
//! §10 K7) — runs on every backend: [`InMemoryAgentStore`], `SqliteAgentStore`,
//! `PostgresAgentStore`, `RedisAgentStore`, `MongoAgentStore`, `FirestoreAgentStore` and
//! `Neo4jAgentStore`, suite `agent_store_conformance_tests!`.
//!
//! There is no file backend and no Vertex AI backend (§13 Q8): no durable store on `main` is file-backed, and
//! Vertex AI holds sessions only.

use async_trait::async_trait;
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};

use adk_core::{RunState, UsageVector};

use crate::bus::SpendDelta;
use crate::error::Result;
use crate::partition::PartitionId;
use crate::process::ProcessMeta;
use crate::sched::QueueClass;
use crate::wake::WakeSet;

#[cfg(feature = "firestore")]
mod agenda_firestore;
mod agenda_memory;
#[cfg(feature = "mongodb")]
mod agenda_mongodb;
#[cfg(feature = "neo4j")]
mod agenda_neo4j;
#[cfg(feature = "redis")]
mod agenda_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod agenda_sql;
#[cfg(feature = "firestore")]
mod agent_firestore;
mod agent_memory;
#[cfg(feature = "mongodb")]
mod agent_mongodb;
#[cfg(feature = "neo4j")]
mod agent_neo4j;
#[cfg(feature = "redis")]
mod agent_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod agent_sql;
mod bundle;
#[cfg(feature = "charter")]
pub(crate) mod charter_memory;
#[cfg(all(feature = "charter", feature = "redis"))]
pub(crate) mod charter_redis;
#[cfg(all(feature = "charter", any(feature = "sqlite", feature = "postgres")))]
pub(crate) mod charter_sql;
#[cfg(all(feature = "drivers", feature = "firestore"))]
mod driver_firestore;
#[cfg(feature = "drivers")]
mod driver_memory;
#[cfg(all(feature = "drivers", feature = "mongodb"))]
mod driver_mongodb;
#[cfg(all(feature = "drivers", feature = "neo4j"))]
mod driver_neo4j;
#[cfg(all(feature = "drivers", feature = "postgres"))]
mod driver_postgres;
#[cfg(all(feature = "drivers", feature = "redis"))]
mod driver_redis;
#[cfg(all(feature = "drivers", any(feature = "sqlite", feature = "postgres")))]
mod driver_sql;
#[cfg(all(feature = "drivers", feature = "sqlite"))]
mod driver_sqlite;
#[cfg(feature = "firestore")]
mod firestore;
#[cfg(all(feature = "proc", feature = "firestore"))]
mod ledger_firestore;
#[cfg(feature = "proc")]
mod ledger_memory;
#[cfg(all(feature = "proc", feature = "mongodb"))]
mod ledger_mongodb;
#[cfg(all(feature = "proc", feature = "neo4j"))]
mod ledger_neo4j;
#[cfg(all(feature = "proc", feature = "redis"))]
mod ledger_redis;
#[cfg(all(feature = "proc", any(feature = "sqlite", feature = "postgres")))]
pub(crate) mod ledger_sql;
mod memory;
#[cfg(feature = "mongodb")]
mod mongodb;
#[cfg(feature = "neo4j")]
mod neo4j;
#[cfg(feature = "firestore")]
mod partition_firestore;
mod partition_memory;
#[cfg(feature = "mongodb")]
mod partition_mongodb;
#[cfg(feature = "neo4j")]
mod partition_neo4j;
#[cfg(feature = "redis")]
mod partition_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod partition_sql;
#[cfg(feature = "postgres")]
mod postgres;
#[cfg(feature = "redis")]
mod redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
mod sql;
#[cfg(feature = "sqlite")]
mod sqlite;
#[cfg(feature = "firestore")]
mod watermark_firestore;
mod watermark_memory;
#[cfg(feature = "mongodb")]
mod watermark_mongodb;
#[cfg(feature = "neo4j")]
mod watermark_neo4j;
#[cfg(feature = "redis")]
mod watermark_redis;
#[cfg(any(feature = "sqlite", feature = "postgres"))]
pub(crate) mod watermark_sql;

#[cfg(feature = "firestore")]
pub use agenda_firestore::FirestoreAgendaStore;
pub use agenda_memory::InMemoryAgendaStore;
#[cfg(feature = "mongodb")]
pub use agenda_mongodb::MongoAgendaStore;
#[cfg(feature = "neo4j")]
pub use agenda_neo4j::Neo4jAgendaStore;
#[cfg(feature = "redis")]
pub use agenda_redis::RedisAgendaStore;
#[cfg(feature = "postgres")]
pub use agenda_sql::PostgresAgendaStore;
#[cfg(feature = "sqlite")]
pub use agenda_sql::SqliteAgendaStore;
#[cfg(feature = "firestore")]
pub use agent_firestore::FirestoreAgentStore;
pub use agent_memory::InMemoryAgentStore;
#[cfg(feature = "mongodb")]
pub use agent_mongodb::MongoAgentStore;
#[cfg(feature = "neo4j")]
pub use agent_neo4j::Neo4jAgentStore;
#[cfg(feature = "redis")]
pub use agent_redis::RedisAgentStore;
#[cfg(feature = "postgres")]
pub use agent_sql::PostgresAgentStore;
#[cfg(feature = "sqlite")]
pub use agent_sql::SqliteAgentStore;
pub use bundle::{KernelStores, StoreOrigin, StoreUse};
#[cfg(all(feature = "drivers", feature = "firestore"))]
pub use driver_firestore::FirestoreDriverStore;
#[cfg(feature = "drivers")]
pub use driver_memory::InMemoryDriverStore;
#[cfg(all(feature = "drivers", feature = "mongodb"))]
pub use driver_mongodb::MongoDriverStore;
#[cfg(all(feature = "drivers", feature = "neo4j"))]
pub use driver_neo4j::Neo4jDriverStore;
#[cfg(all(feature = "drivers", feature = "postgres"))]
pub use driver_postgres::PostgresDriverStore;
#[cfg(all(feature = "drivers", feature = "redis"))]
pub use driver_redis::RedisDriverStore;
#[cfg(all(feature = "drivers", feature = "sqlite"))]
pub use driver_sqlite::SqliteDriverStore;
#[cfg(feature = "firestore")]
pub use firestore::FirestoreProcessStore;
#[cfg(all(feature = "proc", feature = "firestore"))]
pub use ledger_firestore::FirestoreLedgerStore;
#[cfg(feature = "proc")]
pub use ledger_memory::InMemoryLedgerStore;
#[cfg(all(feature = "proc", feature = "mongodb"))]
pub use ledger_mongodb::MongoLedgerStore;
#[cfg(all(feature = "proc", feature = "neo4j"))]
pub use ledger_neo4j::Neo4jLedgerStore;
#[cfg(all(feature = "proc", feature = "redis"))]
pub use ledger_redis::RedisLedgerStore;
#[cfg(all(feature = "proc", feature = "postgres"))]
pub use ledger_sql::PostgresLedgerStore;
#[cfg(all(feature = "proc", feature = "sqlite"))]
pub use ledger_sql::SqliteLedgerStore;
pub use memory::InMemoryProcessStore;
#[cfg(feature = "mongodb")]
pub use mongodb::MongoProcessStore;
#[cfg(feature = "neo4j")]
pub use neo4j::Neo4jProcessStore;
#[cfg(feature = "firestore")]
pub use partition_firestore::FirestorePartitionStore;
pub use partition_memory::InMemoryPartitionStore;
#[cfg(feature = "mongodb")]
pub use partition_mongodb::MongoPartitionStore;
#[cfg(feature = "neo4j")]
pub use partition_neo4j::Neo4jPartitionStore;
#[cfg(feature = "redis")]
pub use partition_redis::RedisPartitionStore;
#[cfg(feature = "postgres")]
pub use partition_sql::PostgresPartitionStore;
#[cfg(feature = "sqlite")]
pub use partition_sql::SqlitePartitionStore;
#[cfg(feature = "postgres")]
pub use postgres::PostgresProcessStore;
#[cfg(feature = "redis")]
pub use redis::RedisProcessStore;
#[cfg(feature = "sqlite")]
pub use sqlite::SqliteProcessStore;
#[cfg(feature = "firestore")]
pub use watermark_firestore::FirestoreCronWatermarkStore;
pub use watermark_memory::InMemoryCronWatermarkStore;
#[cfg(feature = "mongodb")]
pub use watermark_mongodb::MongoCronWatermarkStore;
#[cfg(feature = "neo4j")]
pub use watermark_neo4j::Neo4jCronWatermarkStore;
#[cfg(feature = "redis")]
pub use watermark_redis::RedisCronWatermarkStore;
#[cfg(feature = "postgres")]
pub use watermark_sql::PostgresCronWatermarkStore;
#[cfg(feature = "sqlite")]
pub use watermark_sql::SqliteCronWatermarkStore;

/// The kernel's side table of process metadata, keyed by run id (spec 3.2 §7.3, §6 D-2).
///
/// `RunRecord` has no metadata field, so the kernel keeps what the run store does not here
/// instead of changing the run store's schema across six backends. Rows of runs the run
/// store has pruned are deleted with [`delete`](Self::delete).
///
/// # Example
///
/// ```rust
/// use adk_kernel::{InMemoryProcessStore, ProcessKind, ProcessMeta, ProcessStore, QueueClass};
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> adk_kernel::Result<()> {
/// let store = InMemoryProcessStore::new();
/// store.put(ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal)).await?;
/// store.set_queue("run-1", QueueClass::Interactive).await?;
/// assert_eq!(store.get("run-1").await?.unwrap().queue, QueueClass::Interactive);
/// # Ok(())
/// # }
/// ```
#[async_trait]
pub trait ProcessStore: Send + Sync {
    /// Inserts `meta`, or replaces the row with the same `pid`.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn put(&self, meta: ProcessMeta) -> Result<()>;

    /// The row of `pid`, or `None`.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>>;

    /// The rows `filter` selects by partition, queue, parent and pending suspension request,
    /// ordered by `pid`, at most
    /// `filter.limit`. `filter.states` is a run-store field and is applied by
    /// [`ProcessTable::ps`](crate::ProcessTable::ps), not here.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>>;

    /// Sets or clears the wake set of `pid`.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::NotFound`](crate::KernelError::NotFound) when no row has
    /// `pid`, or [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()>;

    /// Sets the queue class of `pid`.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::NotFound`](crate::KernelError::NotFound) when no row has
    /// `pid`, or [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()>;

    /// Deletes the row of `pid`; `false` when there was none.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn delete(&self, pid: &str) -> Result<bool>;

    /// Sets or clears the pending suspension request of `pid`
    /// ([`ProcessMeta::suspend_requested`]).
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::NotFound`](crate::KernelError::NotFound) when no row has
    /// `pid`, or [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()>;

    /// Adds `delta` — its cost, model calls, total tokens and units — to the totals of `pid`
    /// in `partition` on the UTC day `day`. Additions from concurrent writers all count.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn add_spend(
        &self,
        pid: &str,
        partition: &PartitionId,
        day: NaiveDate,
        delta: SpendDelta,
    ) -> Result<()>;

    /// The spend `scope` recorded from `from` through `to_inclusive`, in micro-USD; 0 when
    /// none was.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn spend(
        &self,
        scope: &SpendScope,
        from: NaiveDate,
        to_inclusive: NaiveDate,
    ) -> Result<u64>;

    /// What `scope` used from `from` through `to_inclusive`: the cost, model calls, total
    /// tokens and units [`add_spend`](Self::add_spend) recorded; zero when none was.
    ///
    /// # Errors
    ///
    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
    async fn usage(
        &self,
        scope: &SpendScope,
        from: NaiveDate,
        to_inclusive: NaiveDate,
    ) -> Result<UsageTotals>;
}

/// What a process or a partition used over a span of UTC days ([`ProcessStore::usage`]).
///
/// # Example
///
/// ```rust
/// use adk_core::{UsageUnit, UsageVector};
/// use adk_kernel::SpendDelta;
/// use adk_kernel::stores::UsageTotals;
///
/// let mut totals = UsageTotals::default();
/// totals.add(&SpendDelta::new(10_000).with_units(UsageVector::new().with(UsageUnit::Images, 1)));
/// totals.add(&SpendDelta::new(500).with_model_calls(1).with_total_tokens(900));
/// assert_eq!(totals.micro_usd, 10_500);
/// assert_eq!((totals.model_calls, totals.total_tokens), (1, 900));
/// assert_eq!(totals.units.get(UsageUnit::Images), 1);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct UsageTotals {
    /// Cost, in micro-USD.
    pub micro_usd: u64,
    /// Model calls.
    pub model_calls: u64,
    /// Input plus output tokens.
    pub total_tokens: u64,
    /// Usage per unit.
    pub units: UsageVector,
}

impl UsageTotals {
    /// Adds `delta`, saturating.
    pub fn add(&mut self, delta: &SpendDelta) {
        self.micro_usd = self.micro_usd.saturating_add(delta.micro_usd);
        self.model_calls = self.model_calls.saturating_add(delta.model_calls);
        self.total_tokens = self.total_tokens.saturating_add(delta.total_tokens);
        self.units.merge(&delta.units);
    }

    /// Adds every total of `other`, saturating.
    pub fn merge(&mut self, other: &UsageTotals) {
        self.micro_usd = self.micro_usd.saturating_add(other.micro_usd);
        self.model_calls = self.model_calls.saturating_add(other.model_calls);
        self.total_tokens = self.total_tokens.saturating_add(other.total_tokens);
        self.units.merge(&other.units);
    }

    /// Adds `amount` to the counter a durable backend stores as `name` ([`counters`]); an
    /// unknown name, written by a later version, is skipped.
    #[cfg(any(
        feature = "sqlite",
        feature = "postgres",
        feature = "redis",
        feature = "mongodb",
        feature = "firestore",
        feature = "neo4j"
    ))]
    pub(crate) fn add_counter(&mut self, name: &str, amount: u64) {
        match name {
            MODEL_CALLS_COUNTER => self.model_calls = self.model_calls.saturating_add(amount),
            TOTAL_TOKENS_COUNTER => self.total_tokens = self.total_tokens.saturating_add(amount),
            unit => {
                if let Some(unit) =
                    adk_core::UsageUnit::ALL.into_iter().find(|known| known.as_str() == unit)
                {
                    self.units.add(unit, amount);
                }
            }
        }
    }
}

/// The counter name of [`SpendDelta::model_calls`] in the durable backends.
#[cfg(any(
    feature = "sqlite",
    feature = "postgres",
    feature = "redis",
    feature = "mongodb",
    feature = "firestore",
    feature = "neo4j"
))]
const MODEL_CALLS_COUNTER: &str = "modelCalls";

/// The counter name of [`SpendDelta::total_tokens`] in the durable backends.
#[cfg(any(
    feature = "sqlite",
    feature = "postgres",
    feature = "redis",
    feature = "mongodb",
    feature = "firestore",
    feature = "neo4j"
))]
const TOTAL_TOKENS_COUNTER: &str = "totalTokens";

/// A counter amount as a durable backend stores it, a signed 64-bit integer.
#[cfg(any(
    feature = "sqlite",
    feature = "postgres",
    feature = "redis",
    feature = "mongodb",
    feature = "firestore",
    feature = "neo4j"
))]
pub(crate) fn stored_amount(backend: &'static str, name: &str, amount: u64) -> Result<i64> {
    i64::try_from(amount).map_err(|_| crate::KernelError::Store {
        backend,
        reason: format!("a {name} delta of {amount} exceeds a signed 64-bit integer"),
    })
}

/// The named counters a durable backend stores beside a delta's micro-USD: model calls,
/// total tokens and each unit by its wire name, the zero ones left out.
#[cfg(any(
    feature = "sqlite",
    feature = "postgres",
    feature = "redis",
    feature = "mongodb",
    feature = "firestore",
    feature = "neo4j"
))]
pub(crate) fn counters(delta: &SpendDelta) -> Vec<(&'static str, u64)> {
    [(MODEL_CALLS_COUNTER, delta.model_calls), (TOTAL_TOKENS_COUNTER, delta.total_tokens)]
        .into_iter()
        .chain(delta.units.iter().map(|(unit, amount)| (unit.as_str(), amount)))
        .filter(|(_, amount)| *amount > 0)
        .collect()
}

/// Whose spend [`ProcessStore::spend`] sums (spec 3.2 §7.3, §7.10).
///
/// # Example
///
/// ```rust
/// use adk_kernel::stores::SpendScope;
///
/// let scope = SpendScope::Process("run-1".into());
/// assert_eq!(serde_json::to_value(&scope).unwrap()["process"], "run-1");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum SpendScope {
    /// One process.
    Process(String),
    /// Every process of a partition.
    Partition(PartitionId),
}

/// Which processes `ps` lists (spec 3.2 §7.3, §8.1 `adk-rust ps [--partition P] [--state S]`).
///
/// An empty field matches everything.
///
/// # Example
///
/// ```rust
/// use adk_core::RunState;
/// use adk_kernel::{ProcessFilter, ProcessKind, ProcessMeta, QueueClass};
///
/// let filter = ProcessFilter::default().partition("default").states([RunState::Waiting]).limit(20);
/// let meta = ProcessMeta::new("run-1", QueueClass::Background, ProcessKind::Goal);
/// assert!(filter.matches(&meta));
/// assert!(!filter.clone().queue(QueueClass::Interactive).matches(&meta));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ProcessFilter {
    /// Only processes in this partition.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub partition: Option<PartitionId>,
    /// Only processes whose run is in one of these states.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub states: Vec<RunState>,
    /// Only processes in this queue class.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub queue: Option<QueueClass>,
    /// Only processes this run caused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
    /// Only processes whose [`ProcessMeta::suspend_requested`] is this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suspend_requested: Option<bool>,
    /// Only processes whose run's target is this: an agent's id (spec 3.3 §5.7).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// At most this many processes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
}

impl ProcessFilter {
    /// Only processes in `partition`.
    #[must_use]
    pub fn partition(mut self, partition: impl Into<PartitionId>) -> Self {
        self.partition = Some(partition.into());
        self
    }

    /// Only processes whose run is in one of `states`.
    #[must_use]
    pub fn states(mut self, states: impl IntoIterator<Item = RunState>) -> Self {
        self.states = states.into_iter().collect();
        self
    }

    /// Only processes in `queue`.
    #[must_use]
    pub fn queue(mut self, queue: QueueClass) -> Self {
        self.queue = Some(queue);
        self
    }

    /// Only processes `parent` caused.
    #[must_use]
    pub fn parent(mut self, parent: impl Into<String>) -> Self {
        self.parent = Some(parent.into());
        self
    }

    /// Only processes whose pending suspension request is `requested`.
    #[must_use]
    pub fn suspend_requested(mut self, requested: bool) -> Self {
        self.suspend_requested = Some(requested);
        self
    }

    /// Only processes whose run's target is `target`, such as an added agent's id (spec 3.3
    /// §5.7). Like `states`, it is a run-record field, applied by
    /// [`ProcessTable::ps`](crate::ProcessTable::ps) rather than by the store.
    #[must_use]
    pub fn target(mut self, target: impl Into<String>) -> Self {
        self.target = Some(target.into());
        self
    }

    /// At most `limit` processes.
    #[must_use]
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Whether `meta` passes the side-table fields: partition, queue, parent and the
    /// pending suspension request. `states`, `target` and `limit` are not checked here.
    pub fn matches(&self, meta: &ProcessMeta) -> bool {
        self.partition.as_ref().is_none_or(|partition| *partition == meta.partition)
            && self.queue.as_ref().is_none_or(|queue| *queue == meta.queue)
            && self.parent.as_ref().is_none_or(|parent| meta.parent.as_ref() == Some(parent))
            && self.suspend_requested.is_none_or(|requested| requested == meta.suspend_requested)
    }
}

/// The stored form of a UTC day in the document and graph backends: its number of days from
/// the common era, as the SQL backends store it, so a range compares as integers.
#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
pub(crate) fn day_number(day: NaiveDate) -> i64 {
    i64::from(chrono::Datelike::num_days_from_ce(&day))
}

/// A spend delta as the document and graph backends store it, a signed 64-bit integer.
#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
pub(crate) fn stored_micro_usd(backend: &'static str, delta: &SpendDelta) -> Result<i64> {
    i64::try_from(delta.micro_usd).map_err(|_| crate::KernelError::Store {
        backend,
        reason: format!(
            "a spend delta of {} micro-USD exceeds a signed 64-bit integer",
            delta.micro_usd
        ),
    })
}

/// A summed spend total as returned.
#[cfg(any(feature = "mongodb", feature = "firestore", feature = "neo4j"))]
pub(crate) fn stored_total(backend: &'static str, total: i64) -> Result<u64> {
    u64::try_from(total).map_err(|_| crate::KernelError::Store {
        backend,
        reason: format!("the stored spend total {total} is negative"),
    })
}