@noetaris/harness-store-postgres
v0.6.1
Published
PostgreSQL session store for @noetaris/harness
Readme
@noetaris/harness-store-postgres
PostgreSQL session store for @noetaris/harness. Provides PostgresSessionStore — a fully-featured database-backed implementation with optimistic locking, full session history, branching, and distributed claim/lease support.
Overview
@noetaris/harness-store-postgres implements session persistence for the Harness agent framework using PostgreSQL.
Key characteristics:
- Optimistic locking —
save()checks the version in a transaction withFOR UPDATE; throwsConcurrentModificationErroron version mismatch - Full history —
loadHistory()returns all runs in chronological order - Branching —
branch()creates a new session from any historical run - Distributed claim/lease —
claim()/release()/extendClaim()backed by asession_claimstable;claimExpiresIn()tells a refused caller how long the claim still lives
A run that stands on an error is saved with it: finalState.$error (also in checkpoint rows) holds the error as @noetaris/harness copied it, with its name, message, stack trace, cause and the error's own fields. They are written to the session_runs table. Keep secrets off error objects.
Installation
pnpm add @noetaris/harness-store-postgresPeer dependencies — install these alongside the package:
pnpm add @noetaris/harness pgQuick Start
The store goes into the harness with .store({ session: store }). Runs that get the same sessionId then share one session.
import pg from 'pg'
import { createAgent, createHarness, field } from '@noetaris/harness'
import { PostgresSessionStore } from '@noetaris/harness-store-postgres'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const store = new PostgresSessionStore({ pool })
// Create the tables if they are missing. Call it at every start, from every instance.
await store.migrate()
// A harness with one step. The store goes in under the reserved `session` key.
const h = createHarness()({
count: field<number>({ default: () => 0 }),
})
.store({ session: store })
.loop((l) =>
l.start()
.step('add', {
run: async (state) => ({ count: state.count + 1 }),
route: () => 'done',
})
.on('done').end(),
)
const agent = createAgent('counter', h, {})
// Runs with the same sessionId share one session: the second run starts from the stored state.
const first = await agent.run({}, { sessionId: 'session-1' })
const second = await agent.run({}, { sessionId: 'session-1' })
console.log(first.state.count, second.state.count) // 1 2
// The store does not own the pool. Close it when you are done.
await pool.end()Running the tests
pnpm test runs the Postgres tests against a real database:
- with
PG_URLset, against that database (the tests truncatesession_runsandsession_claims); - otherwise against a throwaway
postgres:16-alpinecontainer started with Testcontainers, which needs Docker; - without either, the Postgres tests are skipped.
Database Schema
migrate() creates two tables if they do not already exist. Call it at every start, from every instance: it is idempotent, and instances that start at the same moment do not disturb each other (see migrate()).
session_runs
Stores every StoredRun for every session, one row per run.
| Column | Type | Description |
|--------|------|-------------|
| agent_id | TEXT | Agent identifier |
| session_id | TEXT | Session identifier |
| run_id | TEXT | Unique run identifier |
| version | INTEGER | Monotonically increasing version (starts at 0) |
| run | TEXT | JSON-serialized StoredRun |
| request_id | TEXT | The run's requestId, or NULL for a keyless run |
Primary key: (agent_id, session_id, version)
Index: session_runs_request_id_idx on (agent_id, session_id, request_id), used by findRequest.
Upgrading from an earlier version. migrate() also adds the request_id column and its index to a
session_runs table created by an earlier version. Adding the column is instant; building the index
blocks reads and writes of session_runs once, while it is built (both statements run in the one
transaction of migrate()). Rows saved before the upgrade keep
request_id NULL and are never returned by findRequest (there is no backfill).
session_claims
Tracks active distributed leases, one row per active claim.
| Column | Type | Description |
|--------|------|-------------|
| agent_id | TEXT | Agent identifier |
| session_id | TEXT | Session identifier |
| nonce | TEXT | UUID generated at claim time; guards release and extend |
| instance_id | TEXT | The instanceId of the agent that holds the claim (createAgent(…, { instanceId })); NULL when the claim was made without one |
| expires_at | BIGINT | Expiry as Unix milliseconds |
Primary key: (agent_id, session_id)
API Reference
PostgresSessionStore
new PostgresSessionStore(options: PostgresSessionStoreOptions)| Option | Type | Description |
|--------|------|-------------|
| pool | Pool | A pre-constructed pg Pool instance. The store does not manage the pool lifecycle — create the pool before use and call pool.end() after. The store attaches no listener to it: add your own pool.on('error', …), see Lost connections. |
An id with a lone surrogate (such as '\ud800') is rejected with a TypeError before anything is written or read: agentId and sessionId in every method that takes them, requestId in findRequest, runId in branch, and run.runId and run.requestId in save. PostgreSQL gets such a string as U+FFFD, so two different ids would name the same rows.
migrate(): Promise<void>
Creates session_runs and session_claims tables if they do not exist, and adds the request_id column and its index to a session_runs table from an earlier version. Must be called once before the store is used — save() writes request_id.
Safe to call at every start and from every instance, also when several instances start at the same moment:
- One transaction, one lock.
migrate()takes one connection from the pool, opens a transaction, takes a transaction-level advisory lock (pg_advisory_xact_lock(4540306354163545750)), reads the catalog and then creates only what is missing: the two tables, therequest_idcolumn, the index. Calls that arrive together run one after the other; the later ones find everything in place and change nothing. The lock ends with the transaction, on commit and on rollback. - All or nothing. When a statement fails, the transaction is rolled back, no table, column or index of this call stays behind, and
migrate()rejects with the database error. Calling it again is safe. - The lock key.
4540306354163545750is the first eight bytes of SHA-256(@noetaris/harness-store-postgres:migrate) as a signed 64-bit integer. It is fixed, so every version and every instance uses the same key. Advisory locks are per database: do not use this key for a lock of your own. Keys in the two-integer form (pg_advisory_lock(int, int)) never meet it. - Schemas. The tables are created in the first existing schema of the connection's
search_path, and only that schema is checked for them. The lock key is the same for every schema, so two calls for different schemas of one database also run one after the other. Each takes a few milliseconds. - PgBouncer. The lock is taken and released inside one transaction, so
migrate()works behind PgBouncer in transaction pooling mode (a session-level advisory lock would not). - Your own transactions.
migrate()always uses a connection of its own from the pool. It never runs inside a transaction you have open on another connection, and it needs one free connection in the pool. - No table lock on a migrated database. When the tables, the column and the index are all there,
migrate()only reads the catalog. It does not wait for transactions that usesession_runsorsession_claims(apg_dump, an idle transaction), andloadandsaveof running instances do not wait for it. - Table lock on an upgrade. When
request_idis missing,ADD COLUMNtakes anACCESS EXCLUSIVElock onsession_runsand holds it until the commit, so through the index build.migrate()first waits for every open transaction that uses the table, and everyloadandsavewaits behindmigrate(). Upgrade when no long transaction is open on the table. - Timeouts.
migrate()leavesstatement_timeoutandlock_timeoutof the connection as they are. With one of them set, a call can fail with57014or55P03, for example while it waits for the advisory lock during another instance's index build. Nothing is half-done then; callmigrate()again, or start the instance again. - Older versions. Versions before 0.5.0 take no lock. On an empty database, a first start of old and new instances at the same moment can still fail in the old instance with
23505.
load(agentId, sessionId): Promise<StoredRun | null>
Returns the latest run for the session (highest version), or null if none exists.
save(agentId, sessionId, run, options?): Promise<void>
Writes the run inside a transaction with FOR UPDATE row locking. Throws ConcurrentModificationError if run.version does not equal storedVersion + 1.
Two saves of the same version that arrive at the same moment, a first save of a new session included, end the same way: one is stored, the other throws ConcurrentModificationError. The row lock alone does not decide this (both can read the same latest row, or no row), so the insert is INSERT … ON CONFLICT (agent_id, session_id, version) DO NOTHING: the later save waits for the earlier one's commit, inserts nothing, and reports the version it then finds as storedVersion.
Isolation. The store opens its transactions (save() and migrate()) with BEGIN ISOLATION LEVEL READ COMMITTED. This holds even when the server, the role or the connection has REPEATABLE READ or SERIALIZABLE as its default (default_transaction_isolation). save() needs it: after a lost insert, it reads the version the winner committed. Under a stricter level, the loser would get the database error 40001 instead of ConcurrentModificationError.
save() takes one connection from the pool for its transaction. When that connection drops during the call, save() rejects with the connection error; see Lost connections.
With options.lease (@noetaris/harness passes it on every save a run makes while it holds a claim), the save is fenced: in the same transaction, before the version check, it locks the session's session_claims row (FOR UPDATE) and compares its nonce with the lease's. If there is no claim row, or it holds another nonce, nothing is written and save throws LeaseLostError, whatever the version. Only the nonce is compared: a claim that expired but that no other instance has taken yet still accepts its owner's save. Without options.lease, only the version is checked.
loadHistory(agentId, sessionId): Promise<StoredRun[]>
Returns all runs for the session in chronological order (version ascending). Returns an empty array if no runs exist.
findRequest(agentId, sessionId, requestId): Promise<StoredRun | null>
Returns the newest run (highest version) of the session saved with that requestId, or null. @noetaris/harness calls it when agent.run() gets a requestId that the session's latest run does not carry, so a late retry of an earlier request returns that request's outcome instead of running it again.
branch(agentId, sessionId, runId): Promise<string>
Creates a new session by forking from a specific run. The new session is initialised with the source run's finalState. Returns the new session UUID.
The new session's first record is a seed with phase: 'paused' and no step, so the next agent.run() on it runs. Its branchedFrom records the source — { sessionId, runId, carrier? } — which the first run sees as RunContext.branchedFrom. Branching a seed points at the run that seed came from. When a run id has more than one record (a paused run and the copy saved when its interrupt is answered, or the checkpoints of a run with checkpoint: 'step'), the one with the highest version is used.
Upgrading from 0.1.x: seeds written by 0.1.x have
phase: 'completed'. A session branched then still returns the stored state without running. Branch again from the source run to get a session that runs.
try {
const newSessionId = await store.branch('my-agent', 'session-original', 'run-abc123')
console.log(`Branched to: ${newSessionId}`)
} catch (err) {
if (err instanceof BranchNotFoundError) {
console.error('Run not found in session history')
}
}claim(agentId, sessionId, options): Promise<Lease | null>
Acquires a distributed lease using an INSERT … ON CONFLICT DO NOTHING pattern. Automatically evicts stale (expired) claims before retrying. Returns null if another instance holds an active claim.
options.instanceId says which instance claims. @noetaris/harness sets it on every claim of an agent created with instanceId, and leaves it out otherwise. The store writes it into session_claims.instance_id (NULL when absent) and returns it as lease.instanceId. A claim that takes over an expired one records the new holder, or no holder when the new claimer has none. A refused claim (null) does not change the row. Other fields of options are ignored.
When options.instanceId is given but is not a non-empty string, claim() rejects with a TypeError and does not touch the database. @noetaris/harness never passes such a value; this guards direct callers.
To see who holds a session:
SELECT instance_id, expires_at FROM session_claims WHERE agent_id = $1 AND session_id = $2;A row whose expires_at (Unix milliseconds) is in the past is an expired claim that nobody has taken over yet.
claimExpiresIn(agentId, sessionId): Promise<number | null>
The milliseconds until the session's claim ends, or null when no claim holds the session: there is no row, or the row has expired. It only reads the row; an expired row stays until the next claim() replaces it.
@noetaris/harness calls it once after a refused claim() and puts the answer into SessionBusyError.retryAfter. When the claim ended between the two calls, the answer is null and retryAfter is undefined.
The value is expires_at minus the clock of the process that asks. expires_at was written with the clock of the process that claimed, so a clock difference between the two instances shifts the value by that much.
release(lease): Promise<void>
Releases the lease using a nonce-guarded DELETE. Never throws — safe to call from finally blocks. The claim is found by the nonce in lease.token; lease.instanceId is not read.
extendClaim(lease, options): Promise<Lease>
Extends the lease by updating expires_at in session_claims, verified by nonce. Throws LeaseNotFoundError if the row is absent or the nonce does not match.
Only expires_at changes: instance_id stays as claim() wrote it, and the returned lease keeps the instanceId of the lease passed in.
@noetaris/harness calls it before every step but the first of a run that holds a claim, from ctx.keepAlive(), and from a debug session while it holds the run at a stop.
Error Handling
ConcurrentModificationError
Thrown by save() when the stored version does not match the expected version: run.version is not storedVersion + 1. This includes a save that lost against another save of the same version made at the same moment; storedVersion then equals attemptedVersion (or is higher, when more saves followed). No database error (23505) reaches the caller for this.
@noetaris/harness recognises the error by its name.
import { ConcurrentModificationError } from '@noetaris/harness-store-postgres'
try {
await store.save('my-agent', 'session-123', run)
} catch (err) {
if (err instanceof ConcurrentModificationError) {
// err.sessionId — the session that conflicted
// err.attemptedVersion — the version the caller tried to write
// err.storedVersion — the version currently in the store
console.error(`Concurrent write: ${err.message}`)
}
}Lost connections
migrate() and save() (also the save inside branch()) each take one connection from the pool and run a transaction on it. When that connection drops during the call (server restart, network cut, a session timeout of the server):
- The call rejects with the error
pggives for the lost connection, as it is: for exampleConnection terminated unexpectedly, or the server's last message such asterminating connection due to administrator command(code57P01). The store does not wrap it and has no error class of its own for it. - Nothing is raised outside the promise: no
uncaughtException, nounhandledRejection. The store listens to the connection'serrorevent while it holds the connection. - The connection is discarded, not put back into the pool. The next call gets another one.
- Nothing was written. The one exception is a connection that drops while the
COMMITis on its way: the run may or may not be stored then.load()tells; saving the same version again givesConcurrentModificationErrorwhen it was stored. - Rarely, the server ends the connection at the moment it answers the last statement of a
save()that fails withLeaseLostErrororConcurrentModificationError. The call then rejects with the connection error instead. Nothing was written, and a retry gives the right error.
The other methods run their statements through pool.query() and reject with the error pg gives in the same way.
Listen to the pool's error event. A connection that drops while it sits idle in the pool is reported by pg on the pool: pool.emit('error', err, client). The pool then removes that connection by itself, and the next call opens a new one. Without a listener, Node treats the event as an uncaught exception and ends the process. The pool is yours, so the store does not attach a listener to it; add one where you create the pool:
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
pool.on('error', (err) => {
console.error('idle PostgreSQL connection lost:', err.message)
})Set timeouts on the pool. The store sets no timeout of its own. A connection can be half dead: the server or the network is gone, but the socket is not closed. A call on it then waits until the operating system gives up on TCP, which can take many minutes. The pool is yours, so set the timeouts there:
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
query_timeout: 15_000, // pg rejects a call whose answer does not come in time
statement_timeout: 10_000, // the server ends a statement that runs or waits on a lock too long
idle_in_transaction_session_timeout: 30_000, // the server ends a session left idle inside a transaction
})query_timeout is checked by pg in your process, so it also covers a half-dead connection. The two server settings free locks that a stuck or vanished client holds, so other instances' saves do not wait behind it. Pick values well above your slowest normal call. They also apply to migrate(), see its notes on timeouts.
BranchNotFoundError
Thrown by branch() when the specified runId is not found in the session's history.
import { BranchNotFoundError } from '@noetaris/harness-store-postgres'
try {
await store.branch('my-agent', 'session-123', 'nonexistent-run')
} catch (err) {
if (err instanceof BranchNotFoundError) {
console.error(`Branch failed: ${err.message}`)
}
}LeaseLostError
Thrown by save() with options.lease when the session's claim is no longer that lease: the claim row is gone, or another instance claimed the session since. Nothing was written.
import { LeaseLostError } from '@noetaris/harness-store-postgres'
try {
await store.save('my-agent', 'session-123', run, { lease })
} catch (err) {
if (err instanceof LeaseLostError) {
// err.sessionId — the session whose claim this lease no longer holds
}
}@noetaris/harness handles it for you: the run stops and settles $error with LeaseExpiredError, whose cause is this error. state.$error holds both as plain objects, so test name and cause.name there, not instanceof. It recognises the error by name, so the class does not have to be the one exported here.
LeaseNotFoundError
Thrown by extendClaim() when the claim row is absent or the nonce does not match.
import { LeaseNotFoundError } from '@noetaris/harness-store-postgres'
try {
const newLease = await store.extendClaim(lease, { ttlMs: 10_000 })
} catch (err) {
if (err instanceof LeaseNotFoundError) {
// err.sessionId — the session whose claim was not found
console.error(`Lease gone: ${err.message}`)
}
}@noetaris/harness recognises the error by name, so the class does not have to be the one exported here. What it does depends on who called extendClaim():
- At a step boundary (before every step but the first of a run that holds a claim): the run stops there and settles
$errorwithLeaseExpiredError, whosecauseis this error.state.$errorholds both as plain objects, so testnameandcause.namethere, notinstanceof. No further step runs and nothing is saved. await ctx.keepAlive()in a step: the promise rejects with this error. Uncaught, it fails the step like any other error the step throws.ctx.keepAlive({ every })(background renewal): the error is ignored, and the run stops at the next step boundary.- A debug session (
agent.debug()): while it holds the run at a stop, it renews the claim every third of the claim TTL. The error is ignored there too. When the run goes on, it stops at the next step boundary.
Distributed Concurrency
PostgresSessionStore implements the two-layer hybrid concurrency model:
- Layer 1 — Optimistic locking (mandatory):
save()uses a transaction withSELECT … FOR UPDATE, a version check, and an insert that the primary key(agent_id, session_id, version)guards. Concurrent writes are detected and rejected withConcurrentModificationError, also two saves of the same version at the same moment and two first saves of a new session. - Layer 2 — Claim/lease (optional):
claim()usesINSERT … ON CONFLICT DO NOTHINGplus stale-claim eviction;release()andextendClaim()use nonce-guarded queries. A random UUID nonce is generated at claim time — stale leases cannot release or extend a new holder's lock. - Fencing:
save()with a lease checks the claim's nonce inside its transaction, before the version check, so an instance that lost its claim cannot overwrite the new holder's runs (LeaseLostError).
How @noetaris/harness uses claims and fencing during a run is described in its README: Keeping the claim and Fencing.
When to Use PostgresSessionStore
Good for:
- Production systems requiring durable, queryable session history
- Multi-process and multi-machine deployments
- Workloads needing session branching (e.g. experiments, replays, forks)
- Teams already running PostgreSQL who want a single storage backend
Not suitable for:
- Single-process development (use
InMemorySessionStoreorLocalFileSessionStorefrom@noetaris/harness-storeinstead) - Ultra-high-throughput workloads where database round-trips per step are a bottleneck (consider
@noetaris/harness-store-redis)
License
MIT
