Skip to main content

adk_kernel/conformance/
process_store.rs

1//! Conformance cases for [`ProcessStore`] backends (spec 3.2 §11, §13 Q8).
2//!
3//! | Case | Contract |
4//! |------|----------|
5//! | [`put_get_round_trip`] | A row reads back exactly as put, every field and every [`Wake`], [`ProcessKind`] and [`Suspension`] variant included; ids with `:`, `/` and non-ASCII characters survive |
6//! | [`put_replaces`] | A second put with the same `pid` replaces the row, and `list` finds it only under its new partition, queue and parent |
7//! | [`list_filters_and_orders`] | `list` applies partition, queue, parent and limit, orders by `pid` in byte order, and ignores `states` |
8//! | [`set_wake_and_queue`] | `set_wake` sets and clears the wake set, `set_queue` the queue, leaving every other field |
9//! | [`unknown_pid`] | `get` of an unknown `pid` is `None`; `set_wake` and `set_queue` fail with `kernel.not_found` and create no row; `delete` answers `false` |
10//! | [`delete`] | `delete` removes the row and its `list` entries and answers `true`, then `false` |
11//! | [`records_survive_a_restart`] | Rows read back through a new handle (durable backends only) |
12//! | [`concurrent_writers`] | Concurrent puts and updates from two handles over distinct pids lose no row, and concurrent updates of different fields of one row lose neither |
13//! | [`sustained_writes`] | A sustained stream of puts, updates and deletes from two handles, read concurrently, stays consistent and readable (SQLite's write lock and WAL included) |
14//! | [`suspend_request_round_trips`] | `set_suspend_requested` sets and clears the flag leaving every other field, `put` writes it, `list` filters on it, and an unknown `pid` fails with `kernel.not_found` |
15//! | [`spend_sums_by_day_and_scope`] | `spend` sums `add_spend` over an inclusive day range per process or per partition; concurrent additions from two handles all count; deleting a process keeps its spend |
16//! | [`usage_sums_counters_by_day_and_scope`] | `usage` sums the cost, model calls, total tokens and every unit `add_spend` recorded, per process or per partition over an inclusive day range, through a second handle; concurrent additions all count; deleting a process keeps its usage |
17//!
18//! Every case writes under fresh process ids in fresh partitions and deletes its rows at
19//! the end, so a harness may point every case at one shared database. Spend totals have no
20//! delete, so the spend case leaves its totals, under ids no other case uses.
21
22use std::collections::BTreeMap;
23use std::sync::Arc;
24use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
25use std::time::Duration;
26
27use adk_core::MissedFirePolicy;
28use async_trait::async_trait;
29use chrono::{DateTime, NaiveDate, TimeZone, Utc};
30
31use crate::bus::SpendDelta;
32use crate::error::{KernelError, NOT_FOUND_CODE};
33use crate::partition::PartitionId;
34use crate::process::{ProcessKind, ProcessMeta, Suspension};
35use crate::sched::QueueClass;
36use crate::stores::{ProcessFilter, ProcessStore, SpendScope, UsageTotals};
37use crate::wake::{ExpiryAction, Wake, WakeSet};
38
39/// Opens a [`ProcessStore`] backend for the conformance suite.
40///
41/// # Example
42///
43/// ```rust
44/// use std::sync::Arc;
45/// use adk_kernel::conformance::ProcessStoreHarness;
46/// use adk_kernel::{InMemoryProcessStore, ProcessStore};
47///
48/// struct InMemory;
49///
50/// #[async_trait::async_trait]
51/// impl ProcessStoreHarness for InMemory {
52///     async fn open(&self) -> Arc<dyn ProcessStore> {
53///         Arc::new(InMemoryProcessStore::new())
54///     }
55///
56///     fn is_durable(&self) -> bool {
57///         false
58///     }
59/// }
60/// ```
61#[async_trait]
62pub trait ProcessStoreHarness: Send + Sync {
63    /// Opens a store. For a durable backend every call returns a new handle over the same
64    /// stored data. Panics when the backend cannot be opened.
65    async fn open(&self) -> Arc<dyn ProcessStore>;
66
67    /// Whether data written through one handle is visible through the next. `false` skips
68    /// the restart case and runs the concurrency case on a single handle.
69    fn is_durable(&self) -> bool {
70        true
71    }
72}
73
74/// A fresh identifier with the characters a backend must escape: `:`, `/`, non-ASCII.
75fn unique(prefix: &str) -> String {
76    format!("conformance:{prefix}/ü-日本/{}", uuid::Uuid::new_v4())
77}
78
79/// A fresh partition, so `list` in one case never sees another case's rows.
80fn partition() -> PartitionId {
81    PartitionId::new(unique("partition"))
82}
83
84/// An instant with nanoseconds, so a backend that rounds timestamps is caught.
85fn instant(seconds: i64) -> DateTime<Utc> {
86    Utc.timestamp_opt(1_800_000_000 + seconds, 123_456_789).single().expect("valid instant")
87}
88
89/// A wake set holding every [`Wake`] variant, with an expiry that runs the process.
90fn every_wake(partition: &PartitionId) -> WakeSet {
91    WakeSet::any_of([
92        Wake::At(instant(60)),
93        Wake::Cron { expr: "0 9 * * 1-5".into(), missed: MissedFirePolicy::CatchUp(3) },
94        Wake::FileChange {
95            root: "/srv/ü repo/日本".into(),
96            glob: "**/{Cargo.lock,*.rs}".into(),
97            debounce: Duration::from_millis(750),
98        },
99        Wake::Webhook { hook: unique("hook") },
100        Wake::Queue { source: unique("queue-source") },
101        Wake::Approval { fingerprint: unique("fingerprint") },
102        Wake::RunFinished { pid: unique("run") },
103        Wake::BudgetReplenished { partition: partition.clone() },
104        Wake::Manual,
105    ])
106    .with_expiry(instant(3_600), ExpiryAction::Run)
107}
108
109/// A row with every field set.
110fn full_meta(pid: &str, partition: &PartitionId) -> ProcessMeta {
111    ProcessMeta::new(pid, QueueClass::Background, ProcessKind::Triggered { source: unique("src") })
112        .with_parent(unique("parent"))
113        .with_partition(partition.clone())
114        .with_wake(every_wake(partition))
115        .with_suspension(Suspension::Preempted { by: unique("run") })
116        .with_agenda_item(unique("agenda"))
117        .with_label("repo", "adk-rust")
118        .with_label("ü-日本", "line one\nline \"two\"")
119}
120
121async fn list_pids(store: &dyn ProcessStore, filter: &ProcessFilter) -> Vec<String> {
122    store.list(filter).await.expect("list").into_iter().map(|meta| meta.pid).collect()
123}
124
125async fn cleanup(store: &dyn ProcessStore, pids: &[String]) {
126    for pid in pids {
127        store.delete(pid).await.expect("delete");
128    }
129}
130
131/// A row reads back exactly as put: every field, every [`Wake`], [`ProcessKind`] and
132/// [`Suspension`] variant, named queues, unicode labels, and ids with `:`, `/` and
133/// non-ASCII characters.
134pub async fn put_get_round_trip(harness: &dyn ProcessStoreHarness) {
135    let store = harness.open().await;
136    let partition = partition();
137    let kinds = [
138        ProcessKind::Interactive,
139        ProcessKind::Goal,
140        ProcessKind::Scheduled,
141        ProcessKind::Triggered { source: unique("source") },
142        ProcessKind::Proposed,
143        ProcessKind::Maintenance,
144    ];
145    let suspensions = [
146        None,
147        Some(Suspension::Manual),
148        Some(Suspension::Preempted { by: unique("run") }),
149        Some(Suspension::Freeze),
150        Some(Suspension::Drain),
151    ];
152    let queues = [
153        QueueClass::Interactive,
154        QueueClass::Background,
155        QueueClass::Maintenance,
156        QueueClass::Named(unique("queue")),
157    ];
158    let mut rows = Vec::new();
159    for (index, kind) in kinds.into_iter().enumerate() {
160        let mut meta = ProcessMeta::new(unique("pid"), queues[index % queues.len()].clone(), kind)
161            .with_partition(partition.clone());
162        if let Some(suspension) = suspensions[index % suspensions.len()].clone() {
163            meta = meta.with_suspension(suspension);
164        }
165        if index % 2 == 0 {
166            meta = meta.with_wake(every_wake(&partition)).with_parent(unique("parent"));
167        }
168        rows.push(meta);
169    }
170    rows.push(full_meta(&unique("pid"), &partition));
171    rows.push(
172        ProcessMeta::new(unique("pid"), QueueClass::Background, ProcessKind::Goal)
173            .with_partition(partition.clone())
174            .with_wake(WakeSet::any_of([Wake::Manual])),
175    );
176    // The default partition, as a phase-1 process has.
177    rows.push(ProcessMeta::new(unique("pid"), QueueClass::Interactive, ProcessKind::Interactive));
178
179    for meta in &rows {
180        store.put(meta.clone()).await.expect("put");
181    }
182    for meta in &rows {
183        assert_eq!(store.get(&meta.pid).await.expect("get").as_ref(), Some(meta), "{}", meta.pid);
184    }
185    let pids: Vec<String> = rows.iter().map(|meta| meta.pid.clone()).collect();
186    cleanup(&*store, &pids).await;
187}
188
189/// A second put with the same `pid` replaces the whole row; `list` then finds it under its
190/// new partition, queue and parent only.
191pub async fn put_replaces(harness: &dyn ProcessStoreHarness) {
192    let store = harness.open().await;
193    let (before, after) = (partition(), partition());
194    let pid = unique("pid");
195    let first = full_meta(&pid, &before);
196    store.put(first.clone()).await.expect("put");
197    let old_parent = first.parent.clone().expect("parent");
198
199    let second = ProcessMeta::new(&pid, QueueClass::Interactive, ProcessKind::Interactive)
200        .with_partition(after.clone());
201    store.put(second.clone()).await.expect("second put");
202    assert_eq!(store.get(&pid).await.expect("get"), Some(second.clone()));
203
204    let empty: Vec<String> = Vec::new();
205    assert_eq!(
206        list_pids(&*store, &ProcessFilter::default().partition(before.clone())).await,
207        empty
208    );
209    assert_eq!(list_pids(&*store, &ProcessFilter::default().parent(old_parent)).await, empty);
210    assert_eq!(
211        list_pids(
212            &*store,
213            &ProcessFilter::default().partition(before).queue(QueueClass::Background)
214        )
215        .await,
216        empty
217    );
218    assert_eq!(
219        store.list(&ProcessFilter::default().partition(after.clone())).await.expect("list"),
220        std::slice::from_ref(&second)
221    );
222    assert_eq!(
223        list_pids(
224            &*store,
225            &ProcessFilter::default().partition(after).queue(QueueClass::Interactive)
226        )
227        .await,
228        std::slice::from_ref(&pid)
229    );
230    cleanup(&*store, &[pid]).await;
231}
232
233/// `list` applies partition, queue, parent and limit together, orders by `pid` in byte
234/// order (so `B` < `Z` < `a` < `ä` < `日`), and ignores `states`, which the process table
235/// applies after joining the run store.
236pub async fn list_filters_and_orders(harness: &dyn ProcessStoreHarness) {
237    let store = harness.open().await;
238    let (here, there) = (partition(), partition());
239    let prefix = unique("pid");
240    let parent = unique("parent");
241    let named = QueueClass::Named(unique("queue"));
242    let pid = |suffix: &str| format!("{prefix}/{suffix}");
243    // Put out of order; `with_parent` marks the rows `parent` caused.
244    let rows = [
245        ProcessMeta::new(pid("日"), QueueClass::Background, ProcessKind::Goal)
246            .with_partition(here.clone())
247            .with_parent(parent.clone()),
248        ProcessMeta::new(pid("a"), QueueClass::Interactive, ProcessKind::Interactive)
249            .with_partition(here.clone()),
250        ProcessMeta::new(pid("Z"), QueueClass::Background, ProcessKind::Scheduled)
251            .with_partition(here.clone())
252            .with_parent(parent.clone()),
253        ProcessMeta::new(pid("ä"), QueueClass::Interactive, ProcessKind::Proposed)
254            .with_partition(here.clone()),
255        ProcessMeta::new(pid("B"), named.clone(), ProcessKind::Maintenance)
256            .with_partition(here.clone()),
257        ProcessMeta::new(pid("c"), QueueClass::Background, ProcessKind::Goal)
258            .with_partition(there.clone())
259            .with_parent(parent.clone()),
260        ProcessMeta::new(pid("A"), QueueClass::Interactive, ProcessKind::Goal)
261            .with_partition(there.clone()),
262    ];
263    for meta in &rows {
264        store.put(meta.clone()).await.expect("put");
265    }
266    let ours: Vec<String> = rows.iter().map(|meta| meta.pid.clone()).collect();
267    let pids = |suffixes: &[&str]| suffixes.iter().map(|suffix| pid(suffix)).collect::<Vec<_>>();
268
269    let in_here = ProcessFilter::default().partition(here.clone());
270    assert_eq!(list_pids(&*store, &in_here).await, pids(&["B", "Z", "a", "ä", "日"]));
271    let full: Vec<ProcessMeta> = store.list(&in_here).await.expect("list");
272    let mut expected: Vec<ProcessMeta> =
273        rows.iter().filter(|meta| meta.partition == here).cloned().collect();
274    expected.sort_by(|a, b| a.pid.cmp(&b.pid));
275    assert_eq!(full, expected, "list returns whole rows");
276    assert_eq!(
277        list_pids(&*store, &in_here.clone().queue(QueueClass::Interactive)).await,
278        pids(&["a", "ä"])
279    );
280    assert_eq!(
281        list_pids(&*store, &in_here.clone().queue(QueueClass::Background)).await,
282        pids(&["Z", "日"])
283    );
284    assert_eq!(list_pids(&*store, &ProcessFilter::default().queue(named)).await, pids(&["B"]));
285    assert_eq!(
286        list_pids(&*store, &ProcessFilter::default().parent(parent.clone())).await,
287        pids(&["Z", "c", "日"])
288    );
289    assert_eq!(
290        list_pids(&*store, &in_here.clone().parent(parent.clone())).await,
291        pids(&["Z", "日"])
292    );
293    assert_eq!(
294        list_pids(
295            &*store,
296            &ProcessFilter::default().partition(there.clone()).parent(parent.clone())
297        )
298        .await,
299        pids(&["c"])
300    );
301    assert_eq!(
302        list_pids(&*store, &in_here.clone().parent(parent).queue(QueueClass::Interactive)).await,
303        Vec::<String>::new()
304    );
305    assert_eq!(list_pids(&*store, &in_here.clone().limit(2)).await, pids(&["B", "Z"]));
306    assert_eq!(
307        list_pids(&*store, &in_here.clone().queue(QueueClass::Background).limit(1)).await,
308        pids(&["Z"])
309    );
310    assert_eq!(list_pids(&*store, &in_here.clone().limit(0)).await, Vec::<String>::new());
311    assert_eq!(
312        list_pids(
313            &*store,
314            &in_here.clone().states([adk_core::RunState::Completed, adk_core::RunState::Failed])
315        )
316        .await,
317        pids(&["B", "Z", "a", "ä", "日"]),
318        "states is not a side-table field"
319    );
320
321    let everything = list_pids(&*store, &ProcessFilter::default()).await;
322    assert!(everything.windows(2).all(|pair| pair[0] < pair[1]), "list orders by pid");
323    let found: Vec<String> = everything.into_iter().filter(|pid| ours.contains(pid)).collect();
324    let mut sorted = ours.clone();
325    sorted.sort();
326    assert_eq!(found, sorted, "an unfiltered list holds every row");
327    cleanup(&*store, &ours).await;
328}
329
330/// `set_wake` sets and clears the wake set and `set_queue` sets the queue, each leaving
331/// every other field as it was; `list` finds the row under its new queue.
332pub async fn set_wake_and_queue(harness: &dyn ProcessStoreHarness) {
333    let store = harness.open().await;
334    let partition = partition();
335    let pid = unique("pid");
336    let meta = full_meta(&pid, &partition);
337    store.put(meta.clone()).await.expect("put");
338
339    let replacement = WakeSet::any_of([Wake::RunFinished { pid: unique("run") }]);
340    store.set_wake(&pid, Some(replacement.clone())).await.expect("set wake");
341    let mut expected = meta.clone();
342    expected.wake = Some(replacement);
343    assert_eq!(store.get(&pid).await.expect("get"), Some(expected.clone()));
344
345    store.set_wake(&pid, None).await.expect("clear wake");
346    expected.wake = None;
347    assert_eq!(store.get(&pid).await.expect("get"), Some(expected.clone()));
348    store.set_wake(&pid, None).await.expect("clearing twice is not an error");
349
350    store.set_queue(&pid, QueueClass::Interactive).await.expect("set queue");
351    expected.queue = QueueClass::Interactive;
352    assert_eq!(store.get(&pid).await.expect("get"), Some(expected.clone()));
353    let in_partition = ProcessFilter::default().partition(partition.clone());
354    assert_eq!(
355        list_pids(&*store, &in_partition.clone().queue(QueueClass::Interactive)).await,
356        std::slice::from_ref(&pid)
357    );
358    assert_eq!(
359        list_pids(&*store, &in_partition.clone().queue(QueueClass::Background)).await,
360        Vec::<String>::new()
361    );
362
363    let named = QueueClass::Named(unique("queue"));
364    store.set_queue(&pid, named.clone()).await.expect("set a named queue");
365    store.set_queue(&pid, named.clone()).await.expect("setting the same queue again");
366    expected.queue = named.clone();
367    assert_eq!(store.get(&pid).await.expect("get"), Some(expected.clone()));
368    assert_eq!(list_pids(&*store, &in_partition.queue(named)).await, std::slice::from_ref(&pid));
369    assert!(
370        !list_pids(
371            &*store,
372            &ProcessFilter::default().queue(QueueClass::Interactive).limit(usize::MAX)
373        )
374        .await
375        .contains(&pid),
376        "the old queue's entry is gone"
377    );
378    cleanup(&*store, &[pid]).await;
379}
380
381/// An unknown `pid` reads as `None`; `set_wake` and `set_queue` fail with
382/// `kernel.not_found` naming it and create no row; `delete` answers `false`.
383pub async fn unknown_pid(harness: &dyn ProcessStoreHarness) {
384    let store = harness.open().await;
385    let pid = unique("missing");
386    assert_eq!(store.get(&pid).await.expect("get"), None);
387
388    let not_found = |result: crate::Result<()>, call: &str| {
389        let error = result.expect_err(call);
390        assert_eq!(error.code(), NOT_FOUND_CODE, "{call}: {error}");
391        assert!(
392            matches!(&error, KernelError::NotFound { pid: named } if *named == pid),
393            "{call}: {error}"
394        );
395    };
396    not_found(
397        store.set_wake(&pid, Some(WakeSet::any_of([Wake::Manual]))).await,
398        "set_wake of an unknown pid",
399    );
400    not_found(store.set_wake(&pid, None).await, "clearing the wake set of an unknown pid");
401    not_found(store.set_queue(&pid, QueueClass::Interactive).await, "set_queue of an unknown pid");
402    assert!(!store.delete(&pid).await.expect("delete"), "nothing to delete");
403    assert_eq!(store.get(&pid).await.expect("get"), None, "a failed update creates no row");
404    assert!(!list_pids(&*store, &ProcessFilter::default()).await.contains(&pid));
405}
406
407/// `delete` removes the row and its `list` entries and answers `true`, then `false`; the
408/// pid can be put again.
409pub async fn delete(harness: &dyn ProcessStoreHarness) {
410    let store = harness.open().await;
411    let partition = partition();
412    let pid = unique("pid");
413    let meta = full_meta(&pid, &partition);
414    let parent = meta.parent.clone().expect("parent");
415    store.put(meta.clone()).await.expect("put");
416
417    assert!(store.delete(&pid).await.expect("delete"), "the row existed");
418    assert_eq!(store.get(&pid).await.expect("get"), None);
419    assert!(!store.delete(&pid).await.expect("second delete"), "the row is gone");
420    let empty: Vec<String> = Vec::new();
421    assert_eq!(
422        list_pids(&*store, &ProcessFilter::default().partition(partition.clone())).await,
423        empty
424    );
425    assert_eq!(list_pids(&*store, &ProcessFilter::default().parent(parent)).await, empty);
426    assert!(!list_pids(&*store, &ProcessFilter::default()).await.contains(&pid));
427
428    store.put(meta.clone()).await.expect("put again");
429    assert_eq!(store.get(&pid).await.expect("get"), Some(meta));
430    cleanup(&*store, &[pid]).await;
431}
432
433/// Rows, with their updates, read back through a new handle as a restarted kernel opens
434/// one. Skipped for a backend that is not durable.
435pub async fn records_survive_a_restart(harness: &dyn ProcessStoreHarness) {
436    if !harness.is_durable() {
437        return;
438    }
439    let partition = partition();
440    let rows: Vec<ProcessMeta> = (0..3).map(|_| full_meta(&unique("pid"), &partition)).collect();
441    let mut expected = rows.clone();
442    {
443        let before = harness.open().await;
444        for meta in &rows {
445            before.put(meta.clone()).await.expect("put");
446        }
447        before.set_wake(&rows[0].pid, None).await.expect("set wake");
448        expected[0].wake = None;
449        before.set_queue(&rows[1].pid, QueueClass::Maintenance).await.expect("set queue");
450        expected[1].queue = QueueClass::Maintenance;
451    }
452    expected.sort_by(|a, b| a.pid.cmp(&b.pid));
453
454    let after = harness.open().await;
455    for meta in &expected {
456        assert_eq!(after.get(&meta.pid).await.expect("get").as_ref(), Some(meta));
457    }
458    assert_eq!(
459        after.list(&ProcessFilter::default().partition(partition)).await.expect("list"),
460        expected
461    );
462    let pids: Vec<String> = expected.iter().map(|meta| meta.pid.clone()).collect();
463    cleanup(&*after, &pids).await;
464}
465
466/// Sixteen writers over two handles put and update distinct pids at once and lose no row;
467/// two writers updating different fields of one row lose neither update.
468pub async fn concurrent_writers(harness: &dyn ProcessStoreHarness) {
469    let first = harness.open().await;
470    let second = if harness.is_durable() { harness.open().await } else { first.clone() };
471    let partition = partition();
472    let prefix = unique("pid");
473    let wake = WakeSet::any_of([Wake::Manual]);
474
475    let writers: Vec<_> = (0..16)
476        .map(|writer| {
477            let store = if writer % 2 == 0 { first.clone() } else { second.clone() };
478            let (partition, prefix, wake) = (partition.clone(), prefix.clone(), wake.clone());
479            tokio::spawn(async move {
480                for row in 0..8 {
481                    let pid = format!("{prefix}/{writer:02}-{row}");
482                    let meta = ProcessMeta::new(&pid, QueueClass::Background, ProcessKind::Goal)
483                        .with_partition(partition.clone());
484                    store.put(meta).await.expect("put");
485                    store.set_wake(&pid, Some(wake.clone())).await.expect("set wake");
486                    if row % 2 == 0 {
487                        store.set_queue(&pid, QueueClass::Interactive).await.expect("set queue");
488                    }
489                }
490            })
491        })
492        .collect();
493    for writer in writers {
494        writer.await.expect("writer completes");
495    }
496    let rows =
497        first.list(&ProcessFilter::default().partition(partition.clone())).await.expect("list");
498    assert_eq!(rows.len(), 128, "no row is lost");
499    for meta in &rows {
500        let row: u32 = meta.pid.rsplit('-').next().and_then(|row| row.parse().ok()).expect("row");
501        let queue =
502            if row.is_multiple_of(2) { QueueClass::Interactive } else { QueueClass::Background };
503        let expected = ProcessMeta::new(&meta.pid, queue, ProcessKind::Goal)
504            .with_partition(partition.clone())
505            .with_wake(wake.clone());
506        assert_eq!(meta, &expected);
507    }
508
509    // Different fields of one row, from two handles at once.
510    let pid = unique("shared");
511    let meta = ProcessMeta::new(&pid, QueueClass::Background, ProcessKind::Goal)
512        .with_partition(partition.clone());
513    first.put(meta.clone()).await.expect("put");
514    let last_wake = WakeSet::any_of([Wake::Webhook { hook: unique("hook") }]);
515    let wakes = {
516        let (store, pid, last_wake) = (first.clone(), pid.clone(), last_wake.clone());
517        tokio::spawn(async move {
518            for round in 0..20 {
519                let wake = WakeSet::any_of([Wake::At(instant(round))]);
520                store.set_wake(&pid, Some(wake)).await.expect("set wake");
521            }
522            store.set_wake(&pid, Some(last_wake)).await.expect("set wake");
523        })
524    };
525    let queues = {
526        let (store, pid) = (second.clone(), pid.clone());
527        tokio::spawn(async move {
528            for round in 0..20 {
529                let queue =
530                    if round % 2 == 0 { QueueClass::Maintenance } else { QueueClass::Background };
531                store.set_queue(&pid, queue).await.expect("set queue");
532            }
533            store.set_queue(&pid, QueueClass::Interactive).await.expect("set queue");
534        })
535    };
536    wakes.await.expect("wake writer completes");
537    queues.await.expect("queue writer completes");
538    let mut expected = meta;
539    expected.wake = Some(last_wake);
540    expected.queue = QueueClass::Interactive;
541    assert_eq!(first.get(&pid).await.expect("get"), Some(expected));
542
543    let mut pids: Vec<String> = rows.into_iter().map(|meta| meta.pid).collect();
544    pids.push(pid);
545    cleanup(&*first, &pids).await;
546}
547
548/// Four writers over two handles each run 150 rounds of put, set_wake and set_queue, and
549/// delete every third row, while two readers list and get without pause. No call fails,
550/// every read decodes to a state some write produced, and the final table holds exactly
551/// the rows not deleted, each with its last update.
552pub async fn sustained_writes(harness: &dyn ProcessStoreHarness) {
553    const WRITERS: usize = 4;
554    const ROUNDS: usize = 150;
555    let first = harness.open().await;
556    let second = if harness.is_durable() { harness.open().await } else { first.clone() };
557    let partition = partition();
558    let prefix = unique("pid");
559    let wake = WakeSet::any_of([Wake::Queue { source: unique("source") }]);
560    let writing = Arc::new(AtomicBool::new(true));
561    let reads = Arc::new(AtomicUsize::new(0));
562
563    let readers: Vec<_> = (0..2)
564        .map(|reader| {
565            let store = if reader == 0 { first.clone() } else { second.clone() };
566            let (partition, prefix, wake) = (partition.clone(), prefix.clone(), wake.clone());
567            let (writing, reads) = (writing.clone(), reads.clone());
568            tokio::spawn(async move {
569                let filter = ProcessFilter::default().partition(partition.clone());
570                while writing.load(Ordering::Acquire) {
571                    for meta in store.list(&filter).await.expect("list while writing") {
572                        assert!(meta.pid.starts_with(&prefix), "{}", meta.pid);
573                        assert!(
574                            matches!(meta.queue, QueueClass::Background | QueueClass::Interactive),
575                            "{:?}",
576                            meta.queue
577                        );
578                        assert!(meta.wake.is_none() || meta.wake.as_ref() == Some(&wake));
579                    }
580                    let probe = format!("{prefix}/{reader}-0");
581                    store.get(&probe).await.expect("get while writing");
582                    reads.fetch_add(1, Ordering::Relaxed);
583                    tokio::task::yield_now().await;
584                }
585            })
586        })
587        .collect();
588
589    let writers: Vec<_> = (0..WRITERS)
590        .map(|writer| {
591            let store = if writer % 2 == 0 { first.clone() } else { second.clone() };
592            let (partition, prefix, wake) = (partition.clone(), prefix.clone(), wake.clone());
593            tokio::spawn(async move {
594                for round in 0..ROUNDS {
595                    let pid = format!("{prefix}/{writer}-{round}");
596                    let meta = ProcessMeta::new(&pid, QueueClass::Background, ProcessKind::Goal)
597                        .with_partition(partition.clone());
598                    store.put(meta).await.expect("put");
599                    store.set_wake(&pid, Some(wake.clone())).await.expect("set wake");
600                    store.set_queue(&pid, QueueClass::Interactive).await.expect("set queue");
601                    if round % 3 == 0 {
602                        assert!(store.delete(&pid).await.expect("delete"), "{pid}");
603                    }
604                }
605            })
606        })
607        .collect();
608    for writer in writers {
609        writer.await.expect("writer completes");
610    }
611    writing.store(false, Ordering::Release);
612    for reader in readers {
613        reader.await.expect("reader completes");
614    }
615    assert!(reads.load(Ordering::Relaxed) > 0, "the readers read while the writers wrote");
616
617    let rows =
618        first.list(&ProcessFilter::default().partition(partition.clone())).await.expect("list");
619    let mut expected: BTreeMap<String, ProcessMeta> = BTreeMap::new();
620    for writer in 0..WRITERS {
621        for round in (0..ROUNDS).filter(|round| round % 3 != 0) {
622            let pid = format!("{prefix}/{writer}-{round}");
623            let meta = ProcessMeta::new(&pid, QueueClass::Interactive, ProcessKind::Goal)
624                .with_partition(partition.clone())
625                .with_wake(wake.clone());
626            expected.insert(pid, meta);
627        }
628    }
629    assert_eq!(rows, expected.into_values().collect::<Vec<_>>());
630    let pids: Vec<String> = rows.into_iter().map(|meta| meta.pid).collect();
631    cleanup(&*first, &pids).await;
632}
633
634/// `set_suspend_requested` sets and clears the pending suspension request, leaving every
635/// other field; `put` writes the flag and a second put replaces it; `list` filters on it,
636/// alone and with the other fields; `delete` drops a requested row from the filter; an
637/// unknown `pid` fails with `kernel.not_found` and creates no row.
638pub async fn suspend_request_round_trips(harness: &dyn ProcessStoreHarness) {
639    let store = harness.open().await;
640    let partition = partition();
641    let pid = unique("pid");
642    let meta = full_meta(&pid, &partition);
643    let other = ProcessMeta::new(unique("pid"), QueueClass::Interactive, ProcessKind::Goal)
644        .with_partition(partition.clone());
645    store.put(meta.clone()).await.expect("put");
646    store.put(other.clone()).await.expect("put");
647    assert_eq!(store.get(&pid).await.expect("get"), Some(meta.clone()), "not requested by default");
648
649    store.set_suspend_requested(&pid, true).await.expect("request");
650    let mut requested = meta.clone();
651    requested.suspend_requested = true;
652    assert_eq!(store.get(&pid).await.expect("get"), Some(requested.clone()));
653    store.set_suspend_requested(&pid, true).await.expect("requesting twice is not an error");
654
655    let in_partition = ProcessFilter::default().partition(partition.clone());
656    assert_eq!(
657        store.list(&in_partition.clone().suspend_requested(true)).await.expect("list"),
658        std::slice::from_ref(&requested)
659    );
660    assert_eq!(
661        list_pids(&*store, &in_partition.clone().suspend_requested(false)).await,
662        std::slice::from_ref(&other.pid)
663    );
664    assert_eq!(
665        list_pids(
666            &*store,
667            &in_partition.clone().suspend_requested(true).queue(QueueClass::Background)
668        )
669        .await,
670        std::slice::from_ref(&pid)
671    );
672    assert_eq!(
673        list_pids(
674            &*store,
675            &in_partition.clone().suspend_requested(true).queue(QueueClass::Interactive)
676        )
677        .await,
678        Vec::<String>::new()
679    );
680    let everywhere = store
681        .list(&ProcessFilter::default().suspend_requested(true))
682        .await
683        .expect("list every requested process");
684    assert!(everywhere.iter().all(|meta| meta.suspend_requested));
685    assert!(everywhere.iter().any(|meta| meta.pid == pid));
686
687    store.set_suspend_requested(&pid, false).await.expect("clear");
688    assert_eq!(store.get(&pid).await.expect("get"), Some(meta.clone()));
689    assert_eq!(
690        list_pids(&*store, &in_partition.clone().suspend_requested(true)).await,
691        Vec::<String>::new()
692    );
693    assert_eq!(list_pids(&*store, &in_partition.clone().suspend_requested(false)).await, {
694        let mut both = vec![pid.clone(), other.pid.clone()];
695        both.sort();
696        both
697    });
698
699    // `put` writes the flag, and a second put replaces it.
700    let mut flagged = other.clone();
701    flagged.suspend_requested = true;
702    store.put(flagged.clone()).await.expect("put a requested row");
703    assert_eq!(store.get(&other.pid).await.expect("get"), Some(flagged));
704    assert_eq!(
705        list_pids(&*store, &in_partition.clone().suspend_requested(true)).await,
706        std::slice::from_ref(&other.pid)
707    );
708    store.put(other.clone()).await.expect("put again");
709    assert_eq!(store.get(&other.pid).await.expect("get"), Some(other.clone()));
710    assert_eq!(
711        list_pids(&*store, &in_partition.clone().suspend_requested(true)).await,
712        Vec::<String>::new()
713    );
714
715    // A deleted row leaves the filter.
716    store.set_suspend_requested(&pid, true).await.expect("request");
717    assert!(store.delete(&pid).await.expect("delete"));
718    assert!(
719        !list_pids(&*store, &ProcessFilter::default().suspend_requested(true)).await.contains(&pid)
720    );
721
722    let missing = unique("missing");
723    let error = store.set_suspend_requested(&missing, true).await.expect_err("unknown pid");
724    assert_eq!(error.code(), NOT_FOUND_CODE, "{error}");
725    assert!(matches!(&error, KernelError::NotFound { pid } if *pid == missing), "{error}");
726    assert_eq!(store.get(&missing).await.expect("get"), None, "a failed update creates no row");
727    cleanup(&*store, &[other.pid]).await;
728}
729
730/// `spend` sums what `add_spend` recorded over an inclusive range of UTC days, per process
731/// or per partition: additions to one day accumulate, ranges cross month and year
732/// boundaries and reach back to the first century, an empty or reversed range is 0, and a
733/// process charged in two partitions counts in each. Forty concurrent additions from two
734/// handles all count, and deleting a process's row keeps its spend.
735pub async fn spend_sums_by_day_and_scope(harness: &dyn ProcessStoreHarness) {
736    let first = harness.open().await;
737    let second = if harness.is_durable() { harness.open().await } else { first.clone() };
738    let (here, there) = (partition(), partition());
739    let (a, b, c) = (unique("pid"), unique("pid"), unique("pid"));
740    let day = |year, month, day| NaiveDate::from_ymd_opt(year, month, day).expect("valid day");
741    let (ancient, d1, d2, d3) = (day(1, 1, 1), day(2026, 12, 31), day(2027, 1, 1), day(2027, 1, 7));
742    let add = |store: Arc<dyn ProcessStore>,
743               pid: String,
744               partition: PartitionId,
745               day,
746               micro_usd| async move {
747        store
748            .add_spend(&pid, &partition, day, SpendDelta::new(micro_usd))
749            .await
750            .expect("add spend");
751    };
752    add(first.clone(), a.clone(), here.clone(), d1, 100).await;
753    add(second.clone(), a.clone(), here.clone(), d1, 50).await;
754    add(first.clone(), a.clone(), here.clone(), d2, 7).await;
755    add(first.clone(), a.clone(), here.clone(), d3, 1).await;
756    add(first.clone(), a.clone(), here.clone(), ancient, 5).await;
757    add(first.clone(), b.clone(), here.clone(), d1, 1_000).await;
758    add(first.clone(), c.clone(), there.clone(), d1, 3).await;
759    add(first.clone(), c.clone(), here.clone(), d1, 10).await;
760    add(first.clone(), c.clone(), there.clone(), d1, 1 << 40).await;
761
762    let spend = |scope: SpendScope, from, to| {
763        let store = second.clone();
764        async move { store.spend(&scope, from, to).await.expect("spend") }
765    };
766    let process = |pid: &String| SpendScope::Process(pid.clone());
767    let partition_of = |partition: &PartitionId| SpendScope::Partition(partition.clone());
768    assert_eq!(spend(process(&a), d1, d1).await, 150, "one day accumulates");
769    assert_eq!(spend(process(&a), d1, d2).await, 157, "a range crosses the year");
770    assert_eq!(spend(process(&a), d2, d3).await, 8);
771    assert_eq!(spend(process(&a), ancient, d3).await, 163);
772    assert_eq!(spend(process(&a), ancient, ancient).await, 5);
773    assert_eq!(
774        spend(process(&a), d1.pred_opt().expect("day"), d1.pred_opt().expect("day")).await,
775        0
776    );
777    assert_eq!(spend(process(&a), d3, d1).await, 0, "a reversed range is empty");
778    assert_eq!(spend(process(&c), d1, d1).await, (1 << 40) + 13, "both partitions count");
779    assert_eq!(spend(process(&unique("pid")), ancient, d3).await, 0);
780    assert_eq!(spend(partition_of(&here), d1, d1).await, 100 + 50 + 1_000 + 10);
781    assert_eq!(spend(partition_of(&here), ancient, d3).await, 163 + 1_000 + 10);
782    assert_eq!(spend(partition_of(&there), d1, d3).await, (1 << 40) + 3);
783    assert_eq!(spend(partition_of(&partition()), ancient, d3).await, 0);
784
785    let adders: Vec<_> = (1..=40_u64)
786        .map(|micro_usd| {
787            let store = if micro_usd % 2 == 0 { first.clone() } else { second.clone() };
788            tokio::spawn(add(store, b.clone(), here.clone(), d2, micro_usd))
789        })
790        .collect();
791    for adder in adders {
792        adder.await.expect("adder completes");
793    }
794    assert_eq!(spend(process(&b), d2, d2).await, 820, "concurrent additions all count");
795    assert_eq!(spend(partition_of(&here), d2, d2).await, 7 + 820);
796
797    first
798        .put(
799            ProcessMeta::new(&b, QueueClass::Background, ProcessKind::Goal)
800                .with_partition(here.clone()),
801        )
802        .await
803        .expect("put");
804    assert!(first.delete(&b).await.expect("delete"));
805    assert_eq!(spend(process(&b), d1, d2).await, 1_000 + 820, "deleting the row keeps the spend");
806    assert_eq!(spend(partition_of(&here), d1, d1).await, 100 + 50 + 1_000 + 10);
807}
808
809/// `usage` sums what `add_spend` recorded — cost, model calls, total tokens and each unit —
810/// over an inclusive range of UTC days, per process or per partition, read through a second
811/// handle: a delta with units and no cost counts, a unit no delta named stays absent, twenty
812/// concurrent additions from two handles all count, and deleting a process's row keeps its
813/// usage. `spend` agrees with the cost `usage` reports.
814pub async fn usage_sums_counters_by_day_and_scope(harness: &dyn ProcessStoreHarness) {
815    use adk_core::{UsageUnit, UsageVector};
816
817    let first = harness.open().await;
818    let second = if harness.is_durable() { harness.open().await } else { first.clone() };
819    let (here, there) = (partition(), partition());
820    let (a, b) = (unique("pid"), unique("pid"));
821    let day = |year, month, day| NaiveDate::from_ymd_opt(year, month, day).expect("valid day");
822    let (d1, d2, d3) = (day(2026, 12, 31), day(2027, 1, 1), day(2027, 1, 7));
823    let images = |count| UsageVector::new().with(UsageUnit::Images, count);
824    let add = |store: Arc<dyn ProcessStore>, pid: String, partition: PartitionId, day, delta| async move {
825        store.add_spend(&pid, &partition, day, delta).await.expect("add spend");
826    };
827    add(first.clone(), a.clone(), here.clone(), d1, SpendDelta::new(10_000).with_units(images(1)))
828        .await;
829    add(
830        second.clone(),
831        a.clone(),
832        here.clone(),
833        d1,
834        SpendDelta::new(400).with_model_calls(2).with_total_tokens(1_500).with_units(
835            UsageVector::new()
836                .with(UsageUnit::InputTokens, 1_200)
837                .with(UsageUnit::OutputTokens, 300)
838                .with(UsageUnit::AudioMillis, 90_400),
839        ),
840    )
841    .await;
842    // Units without cost: a local model's usage still counts.
843    add(first.clone(), a.clone(), here.clone(), d2, SpendDelta::default().with_units(images(2)))
844        .await;
845    add(first.clone(), a.clone(), here.clone(), d3, SpendDelta::new(1).with_model_calls(1)).await;
846    add(first.clone(), b.clone(), here.clone(), d1, SpendDelta::new(5).with_units(images(4))).await;
847    add(
848        first.clone(),
849        b.clone(),
850        there.clone(),
851        d1,
852        SpendDelta::new(7).with_units(images(1 << 40)),
853    )
854    .await;
855
856    let usage = |scope: SpendScope, from, to| {
857        let store = second.clone();
858        async move { store.usage(&scope, from, to).await.expect("usage") }
859    };
860    let process = |pid: &String| SpendScope::Process(pid.clone());
861    let partition_of = |partition: &PartitionId| SpendScope::Partition(partition.clone());
862    let totals = |micro_usd, model_calls, total_tokens, units| UsageTotals {
863        micro_usd,
864        model_calls,
865        total_tokens,
866        units,
867    };
868    assert_eq!(
869        usage(process(&a), d1, d1).await,
870        totals(
871            10_400,
872            2,
873            1_500,
874            UsageVector::new()
875                .with(UsageUnit::Images, 1)
876                .with(UsageUnit::InputTokens, 1_200)
877                .with(UsageUnit::OutputTokens, 300)
878                .with(UsageUnit::AudioMillis, 90_400)
879        ),
880        "one day accumulates every counter"
881    );
882    assert_eq!(usage(process(&a), d2, d2).await, totals(0, 0, 0, images(2)), "units alone count");
883    assert_eq!(usage(process(&a), d2, d3).await, totals(1, 1, 0, images(2)));
884    assert_eq!(
885        usage(process(&a), d3, d1).await,
886        UsageTotals::default(),
887        "a reversed range is empty"
888    );
889    assert_eq!(usage(process(&unique("pid")), d1, d3).await, UsageTotals::default());
890    assert_eq!(usage(partition_of(&here), d1, d1).await.units.get(UsageUnit::Images), 1 + 4);
891    assert_eq!(usage(partition_of(&here), d1, d3).await.units.get(UsageUnit::Images), 1 + 2 + 4);
892    assert_eq!(usage(partition_of(&here), d1, d3).await.micro_usd, 10_400 + 1 + 5);
893    assert_eq!(usage(partition_of(&there), d1, d3).await, totals(7, 0, 0, images(1 << 40)));
894    assert_eq!(usage(process(&b), d1, d1).await.units.get(UsageUnit::Images), 4 + (1 << 40));
895    for scope in [process(&a), partition_of(&here)] {
896        let spend = second.spend(&scope, d1, d3).await.expect("spend");
897        assert_eq!(spend, usage(scope, d1, d3).await.micro_usd, "spend agrees with usage");
898    }
899
900    let adders: Vec<_> = (1..=20_u64)
901        .map(|count| {
902            let store = if count % 2 == 0 { first.clone() } else { second.clone() };
903            let delta = SpendDelta::new(count).with_model_calls(1).with_units(images(count));
904            tokio::spawn(add(store, b.clone(), here.clone(), d2, delta))
905        })
906        .collect();
907    for adder in adders {
908        adder.await.expect("adder completes");
909    }
910    assert_eq!(
911        usage(process(&b), d2, d2).await,
912        totals(210, 20, 0, images(210)),
913        "concurrent additions all count"
914    );
915
916    first
917        .put(
918            ProcessMeta::new(&b, QueueClass::Background, ProcessKind::Goal)
919                .with_partition(here.clone()),
920        )
921        .await
922        .expect("put");
923    assert!(first.delete(&b).await.expect("delete"));
924    assert_eq!(
925        usage(process(&b), d2, d2).await,
926        totals(210, 20, 0, images(210)),
927        "deleting the row keeps the usage"
928    );
929}