ExAgent. Store behaviour
(ExAgent v3.0.0)
View Source
Behaviour for persisting agent/session snapshots and optional atomic records.
Stability — Stable.
ExAgent delegates persistence to the configured Store. ExAgent.Store.ETS
keeps snapshots in ETS for development and tests. ExAgent.Store.Postgres
uses the application's Repo and requires Store SQL migration 4 for
continuation writes and run pages, and migration 5 for keyed admission.
Atomic continuation operations are optional and data-only. They require a
trusted scoped/2 descriptor and explicit durability admission. Legacy
snapshot operations reject a continuation envelope; legacy lists omit it,
preventing an unintegrated runtime from executing its embedded snapshot.
Use the bundled ETS or PostgreSQL Store for atomic continuations. Their
journal schema, reducer and receipts are internal. For operator reads, use
ExAgent.Continuation.get/3 with diagnostics: true to include the journal
body or ExAgent.Server.continuation/2 for a live Server.
The contract (what a store must do)
save_agent_snapshot/2— persist a snapshot, keyed by itsagent_id.load_agent_snapshot/2— fetch a snapshot byagent_id.list_agent_snapshots/1— list all persisted agent snapshots.delete_agent_snapshot/2— remove a snapshot byagent_id.save_session_snapshot/2/load_session_snapshot/2— the session counterparts used byExAgent.Session.
Portability rule
Implement the snapshot callbacks for a custom Store. Configure it as
{MyStore, config}. Keep the supplied ID verbatim as the storage key, including
its namespace encoding. Round-trip snapshots through the public JSON codecs
ExAgent.Server.Snapshot.serialize/1 and ExAgent.Server.Snapshot.deserialize/1,
or ExAgent.Session.Snapshot.serialize/1 and ExAgent.Session.Snapshot.deserialize/1.
Use the matching ExAgent.Server.Snapshot.validate/2 or
ExAgent.Session.Snapshot.validate/2 to check a decoded snapshot against its
storage key. JSON preserves application strings, including secrets.
Use ExAgent.Store.ContractCase to check the snapshot contract in ExUnit.
The bundled ETS and Postgres adapters validate the serialized candidate
with their snapshot reader before replacing the stored revision.
Stores advertising snapshot_cas: true accept an absent key, the immediate
successor revision or an exact byte-for-byte retry. A stale or divergent
candidate returns {:error, :superseded}.
Save replaces one complete snapshot atomically. Save and delete return
:ok only after backend confirmation. After an error or timeout the change
may still take effect. Reconcile the stored state before repeating it and
keep one logical writer per key throughout recovery. This contract does not
provide distributed locking or replay of external effects. Adapter IO must
be bounded: a synchronous blocked adapter also blocks its runtime owner.
A store is referenced as {module, config} (for example, with an ETS table
name). normalize/1 resolves friendly forms and validates the bundled
PostgreSQL descriptor. Custom Store config is opaque. nil means "no store".
Summary
Types
An opaque position in a page query. Pass it back to the same Store and query.
Callbacks
Delete an agent snapshot by agent_id.
Delete a session snapshot by session_id.
Optional body-free read. Return at most count agent headers from the requested
namespace in ascending physical ID byte order, strictly after the supplied
physical ID (nil starts the scan). Include the physical ID in each header.
Use agent_key_in_namespace?/2 to match the callback's namespace against
an ID previously passed to the adapter. Omit continuations and internal
records. Return a tagged backend error on failure.
List all agent snapshots with their physical IDs. Verify each snapshot against
its storage key. Return {:ok, []} for a successful empty inventory and
{:error, reason} when a row or the backend cannot be read.
Load an agent snapshot by agent_id, or {:error, :not_found}.
Load a session snapshot by session_id.
Implement the candidate subject protocol for ExAgent.Retention.
:status reads the phase and fence token. :fence commits a closing tombstone
before replying with that token. It refuses new execution and admissions while
allowing already admitted work to finish. :inventory reads retained references.
A fence that deletes pending follow-ups returns their IDs in :follow_ups.
{:erase, fence, expiring?} checks the token and the journal, then removes
the snapshot, journal, segments and turn receipts atomically.
It returns the provider references it observed, and may return an opaque seal token
for {:arm, token, ttl_ms} to start the expiry after dependent stores confirm.
Active claims and unconfirmed effects keep their evidence. A sealed subject
allows only administrative reconciliation and closure.
Persist an agent snapshot, keyed by its agent_id.
Persist a session snapshot, keyed by session_id.
Functions
Match a physical agent snapshot ID against the requested namespace.
Optional atomic capability; unknown or malformed declarations fail closed.
Delete an agent snapshot via the resolved tuple.
Delete a session snapshot via the resolved tuple.
Advance the Store by one format level after all replica readers support it. ExAgent 3.0.0 supports level 1. This operation becomes available when a future release adds the next level.
Read the active write format level of a Store. The level applies to the entire backing table, including every namespace. Level 1 covers the 3.0.0 format. Readers support every format their binary knows, independently of the write level.
Page standalone agent snapshot IDs, revisions and store update times.
The page omits session snapshots and continuation records, including those
written by a Server configured with :continuation.
Use limit: 1..100 and after: cursor in a keyword list. The default limit
is 50. Pass the opaque cursor back to the same Store and namespace. Rows follow
physical key order. Changes between pages are visible.
List all agent snapshots in the requested namespace (or all unscoped snapshots
for a plain tuple). A successful empty inventory returns {:ok, []}.
An unreadable backend or snapshot returns {:error, reason}.
Load an agent snapshot via the resolved tuple.
Load a session snapshot via the resolved tuple.
Return the effective namespace of a Store scoped with a non-nil namespace
by scoped/2. An unscoped Store or nil raises FunctionClauseError.
Resolve a store option into a {module, config} tuple, or nil for "no store".
Persist an agent snapshot via the resolved {module, config} tuple.
Persist a session snapshot via the resolved tuple.
Scope snapshot operations to an application-supplied namespace (nonempty UTF-8 string). Nil preserves legacy keys. Use the same namespace on Server/Session and Event topic helpers; never obtain it from untrusted stored data.
Types
@type agent_header() :: %{ agent_id: String.t(), revision: non_neg_integer(), updated_at: DateTime.t() }
@type agent_snapshot() :: ExAgent.Server.Snapshot.t()
@opaque cursor()
An opaque position in a page query. Pass it back to the same Store and query.
@type header_page() :: page(agent_header())
@type page(item) :: %{items: [item], cursor: cursor() | nil}
@opaque scoped()
@type session_snapshot() :: ExAgent.Session.Snapshot.t()
Callbacks
Delete an agent snapshot by agent_id.
@callback delete_session_snapshot(config :: term(), session_id :: String.t()) :: :ok | {:error, term()}
Delete a session snapshot by session_id.
@callback list_agent_headers(term(), String.t() | nil, String.t() | nil, pos_integer()) :: {:ok, [agent_header()]} | {:error, term()}
Optional body-free read. Return at most count agent headers from the requested
namespace in ascending physical ID byte order, strictly after the supplied
physical ID (nil starts the scan). Include the physical ID in each header.
Use agent_key_in_namespace?/2 to match the callback's namespace against
an ID previously passed to the adapter. Omit continuations and internal
records. Return a tagged backend error on failure.
@callback list_agent_snapshots(config :: term()) :: {:ok, [agent_snapshot()]} | {:error, term()}
List all agent snapshots with their physical IDs. Verify each snapshot against
its storage key. Return {:ok, []} for a successful empty inventory and
{:error, reason} when a row or the backend cannot be read.
@callback load_agent_snapshot(config :: term(), agent_id :: String.t()) :: {:ok, agent_snapshot()} | {:error, :not_found | term()}
Load an agent snapshot by agent_id, or {:error, :not_found}.
@callback load_session_snapshot(config :: term(), session_id :: String.t()) :: {:ok, session_snapshot()} | {:error, :not_found | term()}
Load a session snapshot by session_id.
@callback retention_subject( term(), {String.t(), ExAgent.Retention.subject_kind(), String.t()}, :status | :fence | :inventory | {:erase, String.t() | nil, boolean()} | {:arm, String.t(), pos_integer()} ) :: {:ok, %{ :phase => :open | :closing | :sealed, :fence => String.t() | nil, optional(:follow_ups) => [String.t()] }} | {:ok, :sealed} | {:ok, [ExAgent.Retention.inventory_entry()]} | {:ok, %{ phase: :closing | :sealed, outcome: ExAgent.Retention.outcome(), provider_copies: [ExAgent.Retention.provider_copy()], seal: String.t() | nil }} | {:error, term()}
Implement the candidate subject protocol for ExAgent.Retention.
:status reads the phase and fence token. :fence commits a closing tombstone
before replying with that token. It refuses new execution and admissions while
allowing already admitted work to finish. :inventory reads retained references.
A fence that deletes pending follow-ups returns their IDs in :follow_ups.
{:erase, fence, expiring?} checks the token and the journal, then removes
the snapshot, journal, segments and turn receipts atomically.
It returns the provider references it observed, and may return an opaque seal token
for {:arm, token, ttl_ms} to start the expiry after dependent stores confirm.
Active claims and unconfirmed effects keep their evidence. A sealed subject
allows only administrative reconciliation and closure.
@callback save_agent_snapshot(config :: term(), snapshot :: agent_snapshot()) :: :ok | {:error, term()}
Persist an agent snapshot, keyed by its agent_id.
@callback save_session_snapshot(config :: term(), snapshot :: session_snapshot()) :: :ok | {:error, term()}
Persist a session snapshot, keyed by session_id.
Functions
Match a physical agent snapshot ID against the requested namespace.
Pass the ID supplied to the snapshot callbacks, before adding any
adapter-specific key prefix. Pass nil to match unscoped IDs.
Optional atomic capability; unknown or malformed declarations fail closed.
Delete an agent snapshot via the resolved tuple.
Delete a session snapshot via the resolved tuple.
Advance the Store by one format level after all replica readers support it. ExAgent 3.0.0 supports level 1. This operation becomes available when a future release adds the next level.
The Store compares the expected level and atomically records the new level
and an audit receipt with :from, :to, :actor and the Store's UTC
millisecond timestamp :at. A concurrent or repeated finalization returns
{:error, {:format_level_conflict, current_level}}.
The host supplies the authorized operator or deployment identity. PostgreSQL
requires enrollment through ExAgent.Migration. Finalization has no inverse.
@spec format_level(t()) :: {:ok, pos_integer()} | {:error, term()}
Read the active write format level of a Store. The level applies to the entire backing table, including every namespace. Level 1 covers the 3.0.0 format. Readers support every format their binary knows, independently of the write level.
@spec list_agent_headers(t(), keyword()) :: {:ok, header_page()} | {:error, term()}
Page standalone agent snapshot IDs, revisions and store update times.
The page omits session snapshots and continuation records, including those
written by a Server configured with :continuation.
Use limit: 1..100 and after: cursor in a keyword list. The default limit
is 50. Pass the opaque cursor back to the same Store and namespace. Rows follow
physical key order. Changes between pages are visible.
Returns {:ok, %{items: headers, cursor: cursor_or_nil}} or {:error, reason}.
Invalid options raise ArgumentError. A malformed cursor or a cursor from
a different query returns {:error, :invalid_scan}.
A store without this optional read returns :unsupported_store_capability.
Use list_agent_snapshots/1 for a full integrity check.
@spec list_agent_snapshots(t()) :: {:ok, [ExAgent.Server.Snapshot.t()]} | {:error, term()}
List all agent snapshots in the requested namespace (or all unscoped snapshots
for a plain tuple). A successful empty inventory returns {:ok, []}.
An unreadable backend or snapshot returns {:error, reason}.
@spec load_agent_snapshot(t(), String.t()) :: {:ok, ExAgent.Server.Snapshot.t()} | {:error, term()}
Load an agent snapshot via the resolved tuple.
@spec load_session_snapshot(t(), String.t()) :: {:ok, ExAgent.Session.Snapshot.t()} | {:error, term()}
Load a session snapshot via the resolved tuple.
Return the effective namespace of a Store scoped with a non-nil namespace
by scoped/2. An unscoped Store or nil raises FunctionClauseError.
Resolve a store option into a {module, config} tuple, or nil for "no store".
nil→nil(no persistence — default).:ets→{ExAgent.Store.ETS, ExAgent.Store.ETS}(default table).{mod, cfg}→ as-is. PostgreSQL checks Repo shape, table name and options before any IO. An invalid descriptor raisesArgumentError.mod→{mod, []}.
@spec save_agent_snapshot(t(), ExAgent.Server.Snapshot.t()) :: :ok | {:error, term()}
Persist an agent snapshot via the resolved {module, config} tuple.
@spec save_session_snapshot(t(), ExAgent.Session.Snapshot.t()) :: :ok | {:error, term()}
Persist a session snapshot via the resolved tuple.
Scope snapshot operations to an application-supplied namespace (nonempty UTF-8 string). Nil preserves legacy keys. Use the same namespace on Server/Session and Event topic helpers; never obtain it from untrusted stored data.
Existing snapshot callbacks receive versioned encoded IDs. Loads verify the exact stored ID before restoring its logical value; no legacy fallback occurs. Lists omit other namespaces and report unreadable snapshots in scope. Direct backend calls bypass this dispatch boundary. This provides neither distributed claims nor access control against the application itself.