SqliteCheckpointer

org.llm4s.agent.graph.sqlite.SqliteCheckpointer
See theSqliteCheckpointer companion object
final class SqliteCheckpointer extends Checkpointer, AutoCloseable

A durable org.llm4s.agent.graph.Checkpointer in one SQLite database file: threads, their checkpoint histories, pending writes, event logs and run claims survive a restart, and several runtimes - in this process or in others on the same host - can share the file, each through a store of its own.

Open it with SqliteCheckpointer.open and close it with close. It meets the Checkpointer contract (and passes CheckpointerContract from llm4s-agent-testkit):

  • '''Atomic, fenced commits.''' Every call that writes is one BEGIN IMMEDIATE transaction: a Commit's checkpoint, pending writes and events land together or not at all, and the claim's token and the thread's version are checked inside the same transaction, so two stores over one file cannot both pass the checks; so is a Commit.fence's claim on another thread.
  • '''Claims expire by clock''', the clock this store was opened with: the clock of the process that grants or renews a claim decides when it lapses. Stores in processes on different hosts sharing one file therefore judge expiry by different clocks, and skew between them changes a claim's effective ttl (see docs/guide/agents/durable-checkpointers.md); fencing keeps writes safe regardless.
  • '''History and retention.''' Every checkpoint a commit supersedes stays in the file, readable with history (newest first, paged through the (thread, position) primary key) and checkpoint, until prune, a commit's retractTurn or deleteThread removes it; each of those is one write transaction too.
  • '''Fencing tokens''' come from one counter for the whole file, stored in it, so they keep increasing across restarts and deleteThread, and are never issued twice.
  • '''Fenced deletes, numbered incarnations.''' deleteThread checks the deleter's token in its own write transaction, as a commit does. It keeps the thread's next event number in the file, so a new thread of the same id numbers its events past the deleted one's, in this process and every other, and a read from inside the deleted log is refused with GraphError.ThreadDeleted - also once a sweep has reclaimed the tombstone, through the file's reclamation mark (design 4.53, sweep).
  • '''Data only.''' Checkpoints, pending writes and events are stored as JSON - the checkpoint through Checkpoint.toJson, which records its format version - and decoded on read, so nothing executable is stored.
  • '''Change notification by polling.''' SQLite cannot tell a connection that another has committed, so this store keeps Checkpointer.awaitEventsAfter's default: a subscription watching it reads the event log once per WatchPolicy.pollInterval, and sees commits made through other stores on the file that long after they land.

The database runs in WAL mode with synchronous = FULL: readers never block the writer, and a commit that returned survives a crash or a power loss. SQLite admits one writer at a time per file; a write that finds another connection writing waits up to SqliteCheckpointerConfig.busyTimeout, then fails with a ProcessingError, changing nothing. WAL needs shared memory between the processes that open the file, so keep the file on a local disk - not on a network file system.

'''Fair writes within a process.''' SQLite does not queue a waiting writer: it sleeps and tries again, and wins only if it wakes while no other connection is writing, so a store beside one that writes back to back can wait out its whole busy timeout although every write is short (#1951). The stores in one JVM that opened the same path therefore take turns through a fair, first-come-first-served lock for the file before they begin a write (and an opener before its migration): each waits for the writes queued ahead of it, up to the busy timeout, and only then for SQLite's lock, which another process may hold - up to the busy timeout again. Between processes SQLite's polling still decides the order, so a process writing steadily can starve another's write; raise busyTimeout there.

One store is one connection, and its calls are serialised: it is safe to call from any number of threads. Every failure of the database itself is a ProcessingError, and so is any call after close.

'''Every call returns within twice the busy timeout''', plus the time its own SQL takes, as the Checkpointer contract requires (#1919). A call waits for this store's earlier calls, and a write then for its turn at the file, at most busyTimeout from the call's start; a write then waits for SQLite's own lock, which another process may hold, at most busyTimeout again. A call that reaches either limit fails with a ProcessingError, changing nothing. A read never waits for a writer in WAL mode, so it waits only for this store's earlier calls. awaitEventsAfter polls, so it returns within its timeout plus that bound. What no limit here covers is the SQL itself once it holds the connection: sqlite-jdbc's native calls cannot be timed out or interrupted, so a disk that stalls inside a write - synchronous = FULL waits for the disk to sync every commit - holds that call, and the store's later calls fail once they have waited busyTimeout for it. Keep the bound well inside ClaimPolicy.ttl - ClaimPolicy.renewEvery: with the default 5 second busy timeout and 30 second ttl, it is.

Attributes

Companion
object
Graph
Supertypes
trait AutoCloseable
trait Checkpointer
class Object
trait Matchable
class Any

Members list

Value members

Concrete methods

def checkpoint(threadId: ThreadId, checkpointId: String): Result[Option[Checkpoint]]

Checkpoint checkpointId of the thread's history, latest included; None if it is not there.

Checkpoint checkpointId of the thread's history, latest included; None if it is not there.

Attributes

def children(parent: ThreadId, after: Option[ThreadId], limit: Int): Result[Vector[ChildThread]]

Up to limit of parent's direct children (design 4.41), oldest first: every thread whose latest checkpoint's Checkpoint.origin names parent, in the order each first committed a checkpoint with that origin, starting after child after when it is given, so a caller pages through them by passing the last id of each page. A thread deleteThread removed is not listed, nor is a thread whose latest checkpoint names another parent or none. An after the store does not know as a child of parent is Left(ValidationError); a child deleted since it was listed keeps its place as long as its tombstone does (deleteThread), so a page boundary survives retention deleting it. A thread with no children has none; limit below 1 reads none. Needs no claim, and reads no tenant: the runtime checks the parent's tenant (GraphRuntime.children).

Up to limit of parent's direct children (design 4.41), oldest first: every thread whose latest checkpoint's Checkpoint.origin names parent, in the order each first committed a checkpoint with that origin, starting after child after when it is given, so a caller pages through them by passing the last id of each page. A thread deleteThread removed is not listed, nor is a thread whose latest checkpoint names another parent or none. An after the store does not know as a child of parent is Left(ValidationError); a child deleted since it was listed keeps its place as long as its tombstone does (deleteThread), so a page boundary survives retention deleting it. A thread with no children has none; limit below 1 reads none. Needs no claim, and reads no tenant: the runtime checks the parent's tenant (GraphRuntime.children).

Attributes

def claim(threadId: ThreadId, request: ClaimRequest): Result[RunClaim]

Claims threadId for request.holder, recording request.tenantId with the claim, until request.ttl from now, by the store's clock, if no other claim on it is live, and returns the claim with a new FencingToken. A live claim - whoever holds it, the same holder included - is Left(GraphError.ThreadBusy(threadId, latest, holder)) with the thread's latest checkpoint id and nothing changed. holder is GraphError.BusyHolder.Run(holder) only when the live claim's tenant is request.tenantId (None and Some differ), and GraphError.BusyHolder.Unnamed otherwise - also for a claim that recorded no tenant, such as one persisted before claims carried one - so that a refusal never reveals another tenant's RunId; a store never returns GraphError.BusyHolder.Lapsed. A thread need not have a checkpoint to be claimed. A claim that replaces an expired one nobody released names that claim's holder as RunClaim.takenOverFrom, under the same rule: only if it was of request.tenantId, and None otherwise.

Claims threadId for request.holder, recording request.tenantId with the claim, until request.ttl from now, by the store's clock, if no other claim on it is live, and returns the claim with a new FencingToken. A live claim - whoever holds it, the same holder included - is Left(GraphError.ThreadBusy(threadId, latest, holder)) with the thread's latest checkpoint id and nothing changed. holder is GraphError.BusyHolder.Run(holder) only when the live claim's tenant is request.tenantId (None and Some differ), and GraphError.BusyHolder.Unnamed otherwise - also for a claim that recorded no tenant, such as one persisted before claims carried one - so that a refusal never reveals another tenant's RunId; a store never returns GraphError.BusyHolder.Lapsed. A thread need not have a checkpoint to be claimed. A claim that replaces an expired one nobody released names that claim's holder as RunClaim.takenOverFrom, under the same rule: only if it was of request.tenantId, and None otherwise.

Attributes

def close(): Unit

Closes the connection. Later calls return a ProcessingError; closing again does nothing. A claim this store granted stays in the file until it is released through another store or expires.

Closes the connection. Later calls return a ProcessingError; closing again does nothing. A claim this store granted stays in the file until it is released through another store or expires.

Attributes

def commit(threadId: ThreadId, commit: Commit): Result[Vector[EventRecord]]

Applies commit atomically, fenced by its token, and returns its events with their sequence numbers, each recording that token. A Commit.fence of (other, otherToken) fences it by other's claim too, checked in the same transaction or under the same lock as the write, after the thread's own claim: otherwise Left(GraphError.StaleClaim(other, otherToken, otherCurrent)) with nothing written.

Applies commit atomically, fenced by its token, and returns its events with their sequence numbers, each recording that token. A Commit.fence of (other, otherToken) fences it by other's claim too, checked in the same transaction or under the same lock as the write, after the thread's own claim: otherwise Left(GraphError.StaleClaim(other, otherToken, otherCurrent)) with nothing written.

Attributes

def compactEvents(threadId: ThreadId, beforeSeq: Long): Result[Unit]

Drops events with seq < beforeSeq; replay can then start no earlier than beforeSeq.

Drops events with seq < beforeSeq; replay can then start no earlier than beforeSeq.

Attributes

def deleteThread(threadId: ThreadId, token: FencingToken, fence: Option[(ThreadId, FencingToken)]): Result[Unit]

Deletes the thread in one write transaction, which first checks that token is the thread's current claim - so the check and the delete see one state of the file, whatever other stores on it are doing. The thread's row stays, emptied, as a tombstone (see SqliteSchema) once it has numbered an event, so that a new thread of the id numbers on past it. A fence thread's claim is checked in the same transaction, after the thread's own.

Deletes the thread in one write transaction, which first checks that token is the thread's current claim - so the check and the delete see one state of the file, whatever other stores on it are doing. The thread's row stays, emptied, as a tombstone (see SqliteSchema) once it has numbered an event, so that a new thread of the id numbers on past it. A fence thread's claim is checked in the same transaction, after the thread's own.

Attributes

def effect(threadId: ThreadId, key: EffectKey): Result[Option[EffectRecord]]

The thread's effect record under key (ReplayGuard, design §4.24); None if it has none, or the thread is unknown. Needs no claim.

The thread's effect record under key (ReplayGuard, design §4.24); None if it has none, or the thread is unknown. Needs no claim.

Attributes

def eventsAfter(threadId: ThreadId, afterSeq: Long, limit: Int): Result[Vector[EventRecord]]

Up to limit events with seq > afterSeq, ascending. afterSeq 0 reads from the thread's first event, as does the number just before it; one behind the replay floor is GraphError.ReplayUnavailable, and one inside the log of a deleted thread of the id (Checkpointer.deleted) is GraphError.ThreadDeleted.

Up to limit events with seq > afterSeq, ascending. afterSeq 0 reads from the thread's first event, as does the number just before it; one behind the replay floor is GraphError.ReplayUnavailable, and one inside the log of a deleted thread of the id (Checkpointer.deleted) is GraphError.ThreadDeleted.

Attributes

def history(threadId: ThreadId, before: Option[String], limit: Int): Result[Vector[Checkpoint]]

Up to limit of the thread's checkpoints, newest first - the latest is the first of the first page - starting after checkpoint before when it is given, so a caller pages through the history by passing the last id of each page. A before that is not in the history is Left(GraphError.CheckpointNotFound); a thread with no checkpoint has an empty history.

Up to limit of the thread's checkpoints, newest first - the latest is the first of the first page - starting after checkpoint before when it is given, so a caller pages through the history by passing the last id of each page. A before that is not in the history is Left(GraphError.CheckpointNotFound); a thread with no checkpoint has an empty history.

Attributes

def incompleteThreads(tenantId: Option[TenantId], after: Option[ThreadCursor], limit: Int): Result[ThreadPage]

The incomplete root threads of tenantId (design 4.52): those whose latest checkpoint is incomplete (CheckpointStatus.Running) and that no live claim holds, by the store's clock - ThreadStatus.Idle - oldest first by ThreadSummary.updatedAt (ties by thread id, ascending), starting after after, at most limit (1 to ThreadQuery.MaxLimit, ValidationError otherwise), with the next page's cursor when more match. A thread whose claim expired without a release is listed; one whose cascade delete has begun is not (ThreadStatus.Deleted).

The incomplete root threads of tenantId (design 4.52): those whose latest checkpoint is incomplete (CheckpointStatus.Running) and that no live claim holds, by the store's clock - ThreadStatus.Idle - oldest first by ThreadSummary.updatedAt (ties by thread id, ascending), starting after after, at most limit (1 to ThreadQuery.MaxLimit, ValidationError otherwise), with the next page's cursor when more match. A thread whose claim expired without a release is listed; one whose cascade delete has begun is not (ThreadStatus.Deleted).

It is for operators, not a worker's recovery query: a cancelled run, a drained one and a crashed one all look alike here, and only a run queue's entry says which should run again (Stage 5, rule 4). Tenant-scoped and bounded as threads is.

Attributes

def isClosed: Boolean

Whether close has been called.

Whether close has been called.

Attributes

def latest(threadId: ThreadId): Result[Option[StoredCheckpoint]]

The thread's latest checkpoint and its pending writes; None for a new thread.

The thread's latest checkpoint and its pending writes; None for a new thread.

Attributes

def latestOfRuns(threadId: ThreadId, runIds: Set[RunId]): Result[Option[Checkpoint]]

The run-id lookup (Stage 5 rule 4, design 4.55): the newest checkpoint in threadId's history whose Checkpoint.runId is one of runIds, or None if none of them committed one that is still kept - none of them was admitted, or the thread was deleted since. A run queue's attempt asks it with the RunIds its entry recorded, before it touches the thread, to learn whether the entry's input was admitted, whatever ran on the thread since: the thread's latest checkpoint alone cannot say, because a direct run after the attempt died would have replaced it. Newest is by place in the history, not by createdAt.

The run-id lookup (Stage 5 rule 4, design 4.55): the newest checkpoint in threadId's history whose Checkpoint.runId is one of runIds, or None if none of them committed one that is still kept - none of them was admitted, or the thread was deleted since. A run queue's attempt asks it with the RunIds its entry recorded, before it touches the thread, to learn whether the entry's input was admitted, whatever ran on the thread since: the thread's latest checkpoint alone cannot say, because a direct run after the attempt died would have replaced it. Newest is by place in the history, not by createdAt.

A store answers it by an index on the thread and run, within its bound, however long the history; an empty runIds is Right(None). While an open entry of the store's run queue names a run, prune keeps the newest checkpoint that run committed, so the lookup never loses the evidence an open entry depends on. Needs no claim.

Attributes

def prune(threadId: ThreadId, policy: RetentionPolicy): Result[Unit]

Removes what policy does not keep, in one write transaction, so it sees and changes one state of the thread whatever other stores on the file are doing; it takes no claim, as the contract says.

Removes what policy does not keep, in one write transaction, so it sees and changes one state of the thread whatever other stores on the file are doing; it takes no claim, as the contract says.

Attributes

def release(threadId: ThreadId, token: FencingToken): Result[Unit]

Ends the claim whose token is token, so the thread can be claimed again at once. A token that is not the thread's current claim changes nothing and is Right(()): a run that lost its claim must never release its successor's.

Ends the claim whose token is token, so the thread can be claimed again at once. A token that is not the thread's current claim changes nothing and is Right(()): a run that lost its claim must never release its successor's.

Attributes

def renew(threadId: ThreadId, token: FencingToken, ttl: FiniteDuration): Result[RunClaim]

Extends the claim whose token is token to ttl from now, by the store's clock, and returns it. Left(GraphError.StaleClaim) if token is not the thread's current claim (another run took it over, it was released, or the thread was deleted). An expired claim nobody replaced is renewed.

Extends the claim whose token is token to ttl from now, by the store's clock, and returns it. Left(GraphError.StaleClaim) if token is not the thread's current claim (another run took it over, it was released, or the thread was deleted). An expired claim nobody replaced is renewed.

Attributes

def sweep(policy: SweepPolicy, after: Option[ThreadId], guard: SweepGuard): Result[SweepPage]

One page of the sweep (design 4.53): the page's thread ids read in one read transaction by the primary key, the guard asked outside any transaction, then the page pruned and its old tombstones reclaimed in one write transaction, so the call is bounded as every write is. A tombstone is reclaimed only if, inside that transaction, its row still holds nothing but where its numbering ended - no checkpoint, event, effect, metadata or claim newer than the cutoff - so a thread created again over it meanwhile is kept.

One page of the sweep (design 4.53): the page's thread ids read in one read transaction by the primary key, the guard asked outside any transaction, then the page pruned and its old tombstones reclaimed in one write transaction, so the call is bounded as every write is. A tombstone is reclaimed only if, inside that transaction, its row still holds nothing but where its numbering ended - no checkpoint, event, effect, metadata or claim newer than the cutoff - so a thread created again over it meanwhile is kept.

Attributes

The thread registry (design 4.52): a page of the root threads of query.tenantId that pass every filter of query (ThreadQuery.matches), newest first by ThreadSummary.updatedAt - when the store last committed a checkpoint or metadata to the thread, by its clock - ties broken by thread id, descending; starting after query.after, at most query.limit of them, with the cursor of the next page when more match (ThreadPage.of). Each thread's ThreadStatus is judged from its latest checkpoint and whether a live claim holds it, by the store's clock, when it is read.

The thread registry (design 4.52): a page of the root threads of query.tenantId that pass every filter of query (ThreadQuery.matches), newest first by ThreadSummary.updatedAt - when the store last committed a checkpoint or metadata to the thread, by its clock - ties broken by thread id, descending; starting after query.after, at most query.limit of them, with the cursor of the next page when more match (ThreadPage.of). Each thread's ThreadStatus is judged from its latest checkpoint and whether a live claim holds it, by the store's clock, when it is read.

Listed are only threads with a checkpoint whose latest checkpoint's tenant is query.tenantId (None and Some differ) and whose latest checkpoint names no parent (Checkpoint.origin): a child thread is read through children, and a thread deleteThread removed is never listed. Paging is by position: a thread changed while a caller pages moves to the front, so a later page of that pass does not list it again, and a pass from the start, or with updatedSince, finds it. Needs no claim, and reads no other tenant's thread: the tenant is the query's. A store answers it within its bound however many threads it holds, by an index.

Attributes

Inherited methods

def awaitEventsAfter(threadId: ThreadId, afterSeq: Long, limit: Int, timeout: FiniteDuration): Result[Vector[EventRecord]]

eventsAfter, waiting for a commit when there is nothing to return yet: up to limit events with seq > afterSeq, ascending, at once if the log holds any; otherwise those of a commit that lands within timeout, or an empty Vector once it has passed. It is how a subscription learns of commits made through another GraphRuntime or process sharing the store (see WatchPolicy): each subscription calls it in a loop, from the last event it has queued.

eventsAfter, waiting for a commit when there is nothing to return yet: up to limit events with seq > afterSeq, ascending, at once if the log holds any; otherwise those of a commit that lands within timeout, or an empty Vector once it has passed. It is how a subscription learns of commits made through another GraphRuntime or process sharing the store (see WatchPolicy): each subscription calls it in a loop, from the last event it has queued.

The default polls. It reads once and, finding nothing, waits timeout and returns empty, so the caller's next call reads again: a commit is seen up to timeout after it lands, at the cost of one eventsAfter per timeout per subscription. A store that can be told of commits overrides it to return as soon as one lands, without reading meanwhile - InMemoryCheckpointer wakes on its own commits, and a database store can use its notification channel (PostgreSQL's LISTEN/NOTIFY). Such a store must wake for commits made through every store over the same storage, not only its own, and still return within about timeout when none lands.

Errors are eventsAfter's - GraphError.ReplayUnavailable when afterSeq is behind the replay floor. Interrupting the waiting thread ends the wait with Left(CancelledError), the thread's interrupt flag set again.

'''The reading thread may be interrupted at any point.''' A subscription's watch calls this on a thread of its own, and Subscription.cancel - or the subscription's end - interrupts that thread whether it is waiting or in the middle of a read, so the interrupt can land inside the store's own I/O (eventsAfter included). A store must take that as the end of this one call, never as damage to itself: release what the call held (a pooled connection, a lock), and stay usable by other threads and later calls. Beware drivers whose I/O goes through a java.nio.channels.InterruptibleChannel (a FileChannel or SocketChannel): an interrupt during a read or write closes the channel, with ClosedByInterruptException, so a store that shares one channel - one connection - between threads would lose it for all of them. Such a store reads on a connection of its own for the waiting call, or discards and replaces a connection an interrupt has closed.

Attributes

Inherited from:
Checkpointer

Concrete fields

val path: Path
lazy val runQueue: RunQueue

The store's run queue (design 4.55), in the same file and over the same connection as its checkpoints: its open entries learn of their thread's deletion in deleteThread's own transaction, and prune keeps the newest checkpoint of every run an open entry recorded. Closing the store closes it.

The store's run queue (design 4.55), in the same file and over the same connection as its checkpoints: its open entries learn of their thread's deletion in deleteThread's own transaction, and prune keeps the newest checkpoint of every run an open entry recorded. Closing the store closes it.

Attributes