Durable Stores

Three stores keep safe actions safe across restarts and across processes, and a fourth keeps the signed audit log. Other durable stores lists the run, schedule, kernel and harness stores.

StoreTraitKeepsSet on
Spend ledgerSpendLedgerBudget holds and committed spendRunConfig::spend_ledger, Runner::builder().spend_ledger(...)
Action ledgerActionLedgerOne record per non-idempotent tool callRunConfig::action_ledger, Runner::builder().action_ledger(...)
Approval storeApprovalStoreCalls held for confirmation and the decisions for them; the requests and delegations of the approval serviceRunConfig::approval_store, Runner::builder().approval_store(...), RunConfig::approval_service
Audit log storeadk_core::audit_log::AuditLogStoreAudit records, Merkle subtree hashes, and signed checkpointsadk_auth::signed_audit::AuditLog::builder(...) — see Audit Log

Every backend implements the same trait and passes the same conformance suite, so choosing a backend changes one constructor and nothing else.

Other durable stores

The runtime, the agent kernel and the harness keep their own state in further stores, each with its own backend matrix and conformance suite on the page that documents it:

StoreTraitKeepsBackendsPage
Durable runsDurableRunStoreThe run queue: input, state, attempts, lease, checkpoint, outcomeIn memory, SQLite, PostgreSQL, Redis, MongoDB, Neo4j, FirestoreDurable Runtime
SchedulesScheduleStoreCron, one-shot and interval schedules with their next fire timeAs durable runsDurable Runtime
Leases and governance stateLeaseStore, GovernanceStateStoreFenced ownership of runs; the freeze per organisation, tenant and agentAs durable runsDurable Runtime
Kernel processesProcessStoreThe kernel's metadata per run: parent, partition, queue, kind, wake set and suspensionIn memory, SQLite, PostgreSQL, Redis, MongoDB, Firestore, Neo4jKernel Store Backends
Cron watermarksCronWatermarkStoreThe cursor per cron source, which never moves back, so a restart knows which occurrences it missedAs kernel processesKernel Store Backends
The kernel's other storesAgendaStore, DriverStore, LedgerStore, PartitionStoreFollow-ups, supervised drivers, the activity ledger, partitionsAs kernel processes; KernelStores::open(url) opens every kernel store on one backendKernel Store Backends
Harness modesModeStoreThe mode of each sessionIn memory, file, SQLite, PostgreSQL, RedisHarness Durability
Standing rulesStandingRuleStoreRules a person granted, per user or per session; the policy reads them on every evaluationIn memory, file, SQLite, PostgreSQL, RedisHarness Durability
Harness goalsGoalStoreEach session's goal record; only the harness writes itIn memory, SQLitePlans and Goals

Backend matrix

BackendFeatureSpendLedgerActionLedgerApprovalStoreConformance run
In memoryadk-coreInMemorySpendLedgerInMemoryActionLedgerInMemoryApprovalStoreEvery PR (adk-core); restart cases are not applicable
SQLitesqliteSqliteSpendLedgerSqliteActionLedgerSqliteApprovalStoreEvery PR (adk-session)
PostgreSQLpostgresPostgresSpendLedgerPostgresActionLedgerPostgresApprovalStoreEvery PR (postgres job) and nightly, live server
RedisredisRedisSpendLedgerRedisActionLedgerRedisApprovalStoreNightly, live server
MongoDBmongodbMongoSpendLedgerMongoActionLedgerMongoApprovalStoreNightly, live server
Neo4jneo4jNeo4jSpendLedgerNeo4jActionLedgerNeo4jApprovalStoreNightly, live server
FirestorefirestoreFirestoreSpendLedgerFirestoreActionLedgerFirestoreApprovalStoreNightly, emulator
BackendFeatureAuditLogStoreConformance run
In memoryadk-coreInMemoryAuditLogStoreEvery PR (adk-core)
SQLitesqliteSqliteAuditLogStoreEvery PR (adk-session)
PostgreSQLpostgresPostgresAuditLogStoreEvery PR (postgres job) and nightly, live server
RedisredisRedisAuditLogStoreNightly, live server
MongoDBmongodbMongoAuditLogStoreNightly, live server
Neo4jneo4jNeo4jAuditLogStoreNightly, live server
FirestorefirestoreFirestoreAuditLogStoreNightly, emulator

Every durable type in adk-session follows one setup sequence:

  1. Construct it with new(...), or from the handle a session service already holds: from_pool (SQLite, PostgreSQL), from_client (Redis), from_database (MongoDB), from_graph (Neo4j), from_db (Firestore).
  2. Call migrate() once at startup. It creates tables, indexes, constraints, or loads scripts, and is safe to call from several processes at once.
  3. Spend ledgers only: set with_limits, with_reservation_ttl, and with_clock.
  4. Install it on the runner builder or the run config.
use std::sync::Arc;

use adk_core::{SpendKey, SpendLimits, SpendPeriod};
use adk_runner::Runner;
use adk_session::{
    PostgresActionLedger, PostgresApprovalStore, PostgresSessionService, PostgresSpendLedger,
};
use sqlx::postgres::PgPool;

let pool = PgPool::connect("postgres://localhost/app").await?;
let sessions = PostgresSessionService::from_pool(pool.clone());
sessions.migrate().await?;

let actions = PostgresActionLedger::from_pool(pool.clone());
let approvals = PostgresApprovalStore::from_pool(pool.clone());
let spend = PostgresSpendLedger::from_pool(pool).with_limits(
    SpendLimits::new().limit(SpendKey::org("payments").per(SpendPeriod::Day), 50_000_000),
);
actions.migrate().await?;
approvals.migrate().await?;
spend.migrate().await?;

let runner = Runner::builder()
    .app_name("payments")
    .agent(agent)
    .session_service(Arc::new(sessions))
    .action_ledger(Arc::new(actions))
    .approval_store(Arc::new(approvals))
    .spend_ledger(Arc::new(spend))
    .build()?;

Switching to Redis replaces the three constructors with RedisActionLedger::new(url), RedisApprovalStore::new(url), and RedisSpendLedger::new(url); the runner code does not change. A run that carries its own store in RunConfig keeps it; the runner fills only the stores the run leaves unset.

How each backend stays atomic

BackendReservation never overspendsBegin admits one callerA decision is taken once
In memoryOne mutexOne write lockOne write lock
SQLiteBEGIN IMMEDIATE before the limit checkINSERT ... ON CONFLICT DO NOTHINGDELETE ... RETURNING
PostgreSQLSELECT ... FOR UPDATE on the organization rowINSERT ... ON CONFLICT DO NOTHINGDELETE ... RETURNING
RedisOne Lua script per reservation, keys hash-tagged by organizationLua create-if-absentLua get-and-delete
MongoDBCompare-and-set on the organization document's sequence; no transactions, so standalone servers workinsert_one on the key as _idfind_one_and_delete
Neo4jA transaction writes the organization node first, taking its write lockUnique constraint on the keyA transaction writes the scope node first, then deletes the decision
FirestoreA transaction reads the organization document and its live holds; a conflicting reservation is retriedCreate-only write (exists = false)Transactional read and delete

Backend-specific limits:

BackendLimit
RedisDay buckets of committed spend expire 70 days after their last write, so only day and month windows read them; lifetime totals are kept forever. Sums are exact up to 2^53 micro-USD per window.
MongoDBA reservation retries its compare-and-set up to 200 times under contention, then fails with spend.ledger_unavailable.
PostgreSQLTimestamps are TIMESTAMPTZ, so action-record times round-trip at microsecond precision.

The no-duplicate guarantee

An ActionLedger makes a non-idempotent call execute at most once per idempotency key. A replay after a crash, a timeout, or a cancelled run is answered from the record, or as outcome_unknown when the call began and never completed. The guarantee holds only when every process that can replay a session reads the same durable ledger.

Session storeAction ledgerDuplicate execution after a restart
AnyInMemoryActionLedgerPossible: records die with the process
AnyA durable ledger on a store each process reaches separately (for example, one SQLite file per host)Possible when another host replays the session
SQLite (one host)SqliteActionLedger on the same database filePrevented
PostgreSQLPostgresActionLedger on the same databasePrevented
RedisRedisActionLedger on the same server or clusterPrevented; requires persistence (AOF or RDB) on the server
MongoDBMongoActionLedger on the same deploymentPrevented
Neo4jNeo4jActionLedger on the same databasePrevented
FirestoreFirestoreActionLedger on the same projectPrevented

Keep the session store and the action ledger in the same database: one backup then restores both to the same point, and a restored session never replays calls its ledger has forgotten. The session event append and the ledger record are separate writes, so a crash between them is reported as outcome_unknown, never as a second execution.

Conformance suite

The suites live in adk-core behind the conformance feature. A third-party backend runs them by implementing a harness and invoking one macro per store:

[dev-dependencies]
adk-core = { version = "3.0.0", features = ["conformance"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use std::sync::Arc;

use adk_core::conformance::ActionLedgerHarness;
use adk_core::{ActionLedger, async_trait};

struct MyHarness;

#[async_trait]
impl ActionLedgerHarness for MyHarness {
    async fn open(&self) -> Arc<dyn ActionLedger> {
        // A new handle over the same data on every call, as a restart would create.
        let ledger = MyActionLedger::connect(&std::env::var("MY_URL").unwrap()).await.unwrap();
        Arc::new(ledger)
    }
}

adk_core::action_ledger_conformance_tests! {
    #[ignore = "requires a server at MY_URL"]
    harness = MyHarness,
}
SuiteCases
spend_ledger_conformance_tests!reserve/commit/release accounting; each reservation settles once; per-key limits; day and month rollover at UTC boundaries (driven by a ManualClock); expired holds; 40 concurrent reservations across two handles; holds and settlements across a restart
action_ledger_conformance_tests!begin/complete round trip; a recorded call answered without executing; a begun call read as outcome_unknown after a restart; 32 concurrent begins with one winner; write-once outcomes with one concurrent winner
approval_store_conformance_tests!pending kept once, oldest first, per scope; has_decision does not consume and take_decision consumes once; a later decision replaces an earlier one; expiry; scope isolation; 16 concurrent takes with one winner; records across a restart; decisions carry edited arguments and messages; requests created once; 16 concurrent replace_request calls across two handles with one winner; listing by state, openness, application, and cursor; listing by session (application, user and session ID), paged inside it; delegations stored, replaced, listed, and deleted; requests and delegations across a restart
approval_service_conformance_tests!the StoreApprovalService over the store: expiry denies once; quorum of two stays pending after one approval; self-approval refused, also through a delegation; delegation only within its window; 12 concurrent decisions across two handles with one winner; edits restart the quorum and carry their arguments; escalation fires once; inbox by name, group, and delegation with paging; inbox by session with paging; one open request per held call; cancel and reject deny; a partly approved request across a restart
audit_log_store_conformance_tests!contiguous appends read back unchanged; a gap or overlap is audit_log.seq_conflict; malformed batches are audit_log.invalid_batch; concurrent appends at one position across two handles have one winner; logs are independent; leaf and subtree hashes; reads past the end fail; checkpoints never exceed the log or fork, and a re-signed note replaces the old one; pruning keeps hashes; data across a restart

Run the suites for the workspace backends:

BackendCommand
In memorycargo nextest run -p adk-core --test store_conformance
SQLitecargo nextest run -p adk-session --features sqlite --test store_conformance_sqlite
PostgreSQLDATABASE_URL=postgres://postgres@localhost:5432/postgres cargo nextest run -p adk-session --features postgres --run-ignored only --test store_conformance_postgres
RedisREDIS_URL=redis://localhost:6379 cargo nextest run -p adk-session --features redis --run-ignored only --test store_conformance_redis
MongoDBMONGODB_URL=mongodb://localhost:27017 cargo nextest run -p adk-session --features mongodb --run-ignored only --test store_conformance_mongodb
Neo4jNEO4J_URI=bolt://localhost:7687 NEO4J_USER=neo4j NEO4J_PASSWORD=<password> cargo nextest run -p adk-session --features neo4j --run-ignored only --test store_conformance_neo4j
FirestoreFIRESTORE_EMULATOR_HOST=localhost:8080 cargo nextest run -p adk-session --features firestore --run-ignored only --test store_conformance_firestore

The durable-stores job in the nightly workflow starts PostgreSQL, Redis, MongoDB, Neo4j, and the Firestore emulator and runs every live suite.