Implement this behavior to persist transactions and optional snapshot or logical-message deliveries. Replicant validates the required callbacks at startup for the configured delivery and checkpoint mode.
| Callback | Required when | Purpose |
|---|---|---|
handle_transaction/1 | Per-transaction delivery | Persist one committed transaction and return its LSN. |
checkpoint/0 | Sink owns the checkpoint | Report a durable resume point or nil if fresh. |
handle_batch/1 | :batch_delivery is enabled | Commit changes and the last LSN of a transaction batch. |
handle_snapshot/2 | Either snapshot mode is enabled | Apply snapshot rows and perform a redo-safe reset on first_for_table?. |
handle_snapshot_complete/1 | Point-in-time snapshot | Persist the snapshot handoff LSN. |
snapshot_progress/0 | Sink owns incremental snapshot progress | Report durable progress or the pending state. |
handle_message/2 | :messages is enabled | Persist a non-transactional logical message. |
handle_session_identity/2 | Optional | Accept the actual replication session before checkpoint lookup. |
handle_slot_origin/2 | Optional | Accept an append pipeline's origin before streaming. |
sink_kind/0 | Optional | Declare :state_mirror (default) or :append_log. |
handle_schema_change/2 | Optional | Admit or decline a destructive schema change. |
Summary
Callbacks
Last durably-persisted commit LSN, for resume AND as the dedup watermark.
Optional. Deliver a BATCH of committed transactions as ONE atomic unit. Enabled by
the top-level batch_delivery config (sink-owned mode only). transactions arrives in
ascending commit_lsn order; persist ALL of their rows AND checkpoint := the last (highest) commit_lsn in ONE atomic database transaction (or, at minimum, checkpoint-after-all-persist),
returning that LSN. Idempotency is unchanged: skip any commit_lsn <= checkpoint; upsert rows
by PK.
Deliver a non-transactional logical-decoding message when messages: true.
Delivery can repeat on reconnect. Deduplicate the durable effect on
context.lsn, which identifies the message's WAL record. An idempotency key
(for example ash_onetime's strategy :idempotency) accepts a valid retry.
A one-time nonce rejects it.
Optional. When a sink does not implement this, the Assembler (Task 13) applies
the default: an :additive change auto-applies; a :destructive change halts
the pipeline fail-closed. Implement it to accept (:ok) or decline ({:error, _})
a Replicant.SchemaChange.
Optional. Synchronously accept the PostgreSQL system/database identity read by
IDENTIFY_SYSTEM on the exact replication connection that will stream WAL.
Optional. Receive the replication slot's typed consistent-point origin — the LSN the
go-forward stream begins at — before START_REPLICATION, on every connect and reconnect.
Optional. Persist a batch of snapshot (backfill) rows for context.table — each a
%Replicant.Change{op: :snapshot} — upserting by table PK.
Optional. The snapshot handoff commit, called once after all batches. Durably persist
checkpoint := snapshot_lsn and return it. Until this succeeds the checkpoint stays
nil, so a crash before it re-runs the whole snapshot. A non-{:ok, _}
return (or a raise/throw/exit) halts the pipeline fail-closed.
Persist the whole transaction AND its checkpoint atomically; return the commit
LSN. Idempotency: skip if txn.commit_lsn <= checkpoint(); upsert rows by PK.
Optional (default :state_mirror). :append_log sinks receive appends.
Optional (REQUIRED for sink-owned incremental snapshot — Config gates on it).
Return the most recent context.progress token persisted atomically with a chunk.
nil means no backfill is active. :backfill_pending means the sink durably
armed a backfill but no chunk token has committed yet; on a reused slot Replicant
reads the live slot origin and restarts discovery instead of silently selecting
stream-only mode. Read at pipeline start and again when a contention/reconnect window
requires the reader to reload durable progress. A read fault halts fail-closed — the
resume decision is not dedup-recoverable (spec §6.1/§8).
Functions
Notify module's handle_slot_origin/2 of the slot origin (R04). A no-op :ok when the
sink does not implement the callback (so a sink without it is unaffected). Mirrors
accept_session_identity/3: :ok accepts; any other return, raise, throw, or exit is contained
as {:error, :slot_origin_rejected} — the value-bearing return/reason is NEVER surfaced
(Critical Rule 1). The caller halts the pipeline fail-closed on the error.
The sink's kind, defaulting to :state_mirror when sink_kind/0 is not
implemented. (Plan 2's start guard refuses a :state_mirror sink from an empty
checkpoint without go_forward_only: true.)
True when module implements handle_batch/1 — the config gate for batch_delivery
A batch_delivery config whose sink is missing this callback is rejected at
start (:batch_unsupported) rather than silently falling back to per-transaction delivery.
True when module implements handle_snapshot/2 AND snapshot_progress/0 — the
config gate for sink-owned snapshot: [mode: :incremental] (spec §6.1).
handle_snapshot_complete/1 is deliberately NOT required: incremental never calls
it. A partial sink is rejected at start (:snapshot_unsupported), fail-closed.
True when module implements handle_message/2 — the config gate for messages: true
(spec §6.3 / A2). A messages: true config whose sink is missing this callback is rejected
at start (:messages_unsupported) rather than silently dropping non-transactional messages.
True when module implements handle_slot_origin/2 — gates the connect-time slot-origin
exposure (R04). A sink without it keeps the prior connect behavior (no confirmed_flush_lsn
read, unchanged streaming).
True when module implements BOTH snapshot callbacks — the config gate for
snapshot: true. A partial implementation is rejected at start
(:snapshot_unsupported) rather than half-running a backfill.
Callbacks
@callback checkpoint() :: {:ok, Replicant.lsn() | nil} | {:error, term()}
Last durably-persisted commit LSN, for resume AND as the dedup watermark.
@callback handle_batch([Replicant.Transaction.t()]) :: {:ok, Replicant.lsn()} | {:error, term()}
Optional. Deliver a BATCH of committed transactions as ONE atomic unit. Enabled by
the top-level batch_delivery config (sink-owned mode only). transactions arrives in
ascending commit_lsn order; persist ALL of their rows AND checkpoint := the last (highest) commit_lsn in ONE atomic database transaction (or, at minimum, checkpoint-after-all-persist),
returning that LSN. Idempotency is unchanged: skip any commit_lsn <= checkpoint; upsert rows
by PK.
HARD OBLIGATION: the data + checkpoint write is atomic. The effect-once guarantee (dup = 0
across a mid-batch teardown) rests on it, exactly as handle_snapshot/2's redo-safety rests on
first_for_table?. A non-{:ok, _} return (or a raise/throw/exit) halts the pipeline
fail-closed; the batch is discarded un-acked and re-delivered on resume (deduped to zero net
effect by the idempotent sink).
The arity is frozen at 1 for 1.0: unlike handle_snapshot/2 / handle_message/2, NO context
arg is provided — the batch's high-water LSN is List.last(transactions).commit_lsn, and each
transaction carries its own commit_lsn. Adding a context arg later is a 2.0 callback change.
@callback handle_message(Replicant.Decoder.Messages.Message.t(), context) :: :ok | {:ok, term()} | {:error, term()} when context: %{lsn: Replicant.lsn()}
Deliver a non-transactional logical-decoding message when messages: true.
Delivery can repeat on reconnect. Deduplicate the durable effect on
context.lsn, which identifies the message's WAL record. An idempotency key
(for example ash_onetime's strategy :idempotency) accepts a valid retry.
A one-time nonce rejects it.
Return :ok or {:ok, term} to advance the checkpoint to the message LSN.
Any other result, raise, throw or exit halts the pipeline. Transactional
messages arrive in Replicant.Transaction with their enclosing transaction.
@callback handle_schema_change(Replicant.SchemaChange.t(), map()) :: :ok | {:error, term()}
Optional. When a sink does not implement this, the Assembler (Task 13) applies
the default: an :additive change auto-applies; a :destructive change halts
the pipeline fail-closed. Implement it to accept (:ok) or decline ({:error, _})
a Replicant.SchemaChange.
@callback handle_session_identity(Replicant.SessionIdentity.t(), context) :: :ok | {:error, term()} when context: %{slot_name: String.t(), publication: [String.t()]}
Optional. Synchronously accept the PostgreSQL system/database identity read by
IDENTIFY_SYSTEM on the exact replication connection that will stream WAL.
This callback runs on every connect and reconnect before checkpoint/0, any
checkpoint-store read, snapshot delivery, or START_REPLICATION. Return :ok
to accept. Any other return, raise, throw, or exit halts the pipeline
fail-closed with a fixed structural reason. context carries the configured
slot name and normalized publication list; it contains no row values.
A sink that binds checkpoints to their true source should implement this callback. A separate PostgreSQL connection is not an equivalent identity source because routing or failover can make it observe a different server.
@callback handle_slot_origin(Replicant.lsn(), context) :: :ok | {:error, term()} when context: %{slot_name: String.t(), reused?: boolean()}
Optional. Receive the replication slot's typed consistent-point origin — the LSN the
go-forward stream begins at — before START_REPLICATION, on every connect and reconnect.
This is the origin a go-forward append-log consumer needs to align its append log. It is
exposed for BOTH a freshly-created slot and a reused (already-present) slot, distinguished by
context.reused?:
reused?: false— a slot just created this session;originis theCREATE_REPLICATION_SLOTconsistent_point(per the PostgreSQL streaming-replication protocol, the earliest location from which the new slot can stream).reused?: true— an existing slot resumed this session;originis the effectiveSTART_REPLICATIONorigin: the greater of the requested durable checkpoint and the slot'spg_replication_slots.confirmed_flush_lsn. It advances across reconnects as the stream is acked, so a reconnect re-invokes this callback with the actual resume origin.
Return :ok to accept. Any other return, raise, throw, or exit halts the pipeline fail-closed
with a fixed structural reason — a consumer that detects an unacceptable origin (e.g. a
confirmed-flush that jumped past its last appended LSN, i.e. a gap) gets a veto instead of
silently skipping WAL. context carries the configured slot name and the boolean; it contains
no row values. Only sinks that implement this callback pay for it — a sink without it keeps the
exact prior connect behavior (no extra query, unchanged streaming). A missing, NULL, or malformed
logical-slot origin halts before the callback and START_REPLICATION with the structural reason
:slot_origin_unavailable; Replicant never fabricates origin 0.
@callback handle_snapshot([Replicant.Change.t()], context) :: :ok | {:error, term()} when context: %{ :snapshot_lsn => Replicant.lsn(), :table => String.t(), :first_for_table? => boolean(), optional(:progress) => binary() | nil, optional(:backfill_complete?) => boolean() }
Optional. Persist a batch of snapshot (backfill) rows for context.table — each a
%Replicant.Change{op: :snapshot} — upserting by table PK.
Records contain only published columns. An INSERT-only publication can omit its key; the sink must support that keyless shape. The reader never adds unpublished keys and uses a whole-table incremental window when any PK column is excluded.
This callback serves BOTH snapshot modes with mode-conditional obligations (spec §6.1 — normative):
| Obligation | v1 (snapshot: true) | incremental (snapshot: [mode: :incremental]) |
|---|---|---|
Non-:ok return / raise | aborts + re-runs the WHOLE snapshot | halts fail-closed; resume re-delivers from the last durable chunk |
first_for_table? | true on the first batch per table, EVERY attempt — clear the table's prior SNAPSHOT-ORIGIN mirror rows, and MUST NOT clear rows the live stream (handle_transaction/1) applied | true on a table's first chunk of a FRESH run AND on every PK-less-table redo attempt — same snapshot-origin-only clearing obligation |
| Checkpoint | never advance here | never advance here |
context.progress | absent | sink-owned mode MUST persist the token atomically with the chunk (effect-once); ignoring it degrades resume to restart-from-zero (safe, dup-only) |
context.backfill_complete? | absent | true ONLY on the dedicated final call (changes: []), delivered at-least-once until durable |
| Completion | handle_snapshot_complete/1 follows | handle_snapshot_complete/1 is NEVER called (it would REGRESS the stream-advanced checkpoint) |
In BOTH modes, the library guarantees at least one call per publication table (even a
zero-row table), so first_for_table? always fires and the redo-safety reset always
happens. A :state_mirror sink MUST distinguish snapshot-origin rows from stream-origin
rows for that reset: first_for_table? clears only the SNAPSHOT-loaded rows and must
PRESERVE rows the live stream (handle_transaction/1) applied — under frontier ordering
a stream update can land BEFORE the first chunk closes, and a blanket clear would lose it.
context.snapshot_lsn is the snapshot's consistent point.
@callback handle_snapshot_complete(snapshot_lsn :: Replicant.lsn()) :: {:ok, Replicant.lsn()} | {:error, term()}
Optional. The snapshot handoff commit, called once after all batches. Durably persist
checkpoint := snapshot_lsn and return it. Until this succeeds the checkpoint stays
nil, so a crash before it re-runs the whole snapshot. A non-{:ok, _}
return (or a raise/throw/exit) halts the pipeline fail-closed.
@callback handle_transaction(Replicant.Transaction.t()) :: {:ok, Replicant.lsn()} | {:error, term()}
Persist the whole transaction AND its checkpoint atomically; return the commit
LSN. Idempotency: skip if txn.commit_lsn <= checkpoint(); upsert rows by PK.
@callback sink_kind() :: :state_mirror | :append_log
Optional (default :state_mirror). :append_log sinks receive appends.
Optional (REQUIRED for sink-owned incremental snapshot — Config gates on it).
Return the most recent context.progress token persisted atomically with a chunk.
nil means no backfill is active. :backfill_pending means the sink durably
armed a backfill but no chunk token has committed yet; on a reused slot Replicant
reads the live slot origin and restarts discovery instead of silently selecting
stream-only mode. Read at pipeline start and again when a contention/reconnect window
requires the reader to reload durable progress. A read fault halts fail-closed — the
resume decision is not dedup-recoverable (spec §6.1/§8).
Functions
@spec notify_slot_origin(module(), Replicant.lsn(), map()) :: :ok | {:error, :slot_origin_rejected}
Notify module's handle_slot_origin/2 of the slot origin (R04). A no-op :ok when the
sink does not implement the callback (so a sink without it is unaffected). Mirrors
accept_session_identity/3: :ok accepts; any other return, raise, throw, or exit is contained
as {:error, :slot_origin_rejected} — the value-bearing return/reason is NEVER surfaced
(Critical Rule 1). The caller halts the pipeline fail-closed on the error.
@spec sink_kind(module()) :: :state_mirror | :append_log
The sink's kind, defaulting to :state_mirror when sink_kind/0 is not
implemented. (Plan 2's start guard refuses a :state_mirror sink from an empty
checkpoint without go_forward_only: true.)
True when module implements handle_batch/1 — the config gate for batch_delivery
A batch_delivery config whose sink is missing this callback is rejected at
start (:batch_unsupported) rather than silently falling back to per-transaction delivery.
True when module implements handle_snapshot/2 AND snapshot_progress/0 — the
config gate for sink-owned snapshot: [mode: :incremental] (spec §6.1).
handle_snapshot_complete/1 is deliberately NOT required: incremental never calls
it. A partial sink is rejected at start (:snapshot_unsupported), fail-closed.
True when module implements handle_message/2 — the config gate for messages: true
(spec §6.3 / A2). A messages: true config whose sink is missing this callback is rejected
at start (:messages_unsupported) rather than silently dropping non-transactional messages.
True when module implements handle_slot_origin/2 — gates the connect-time slot-origin
exposure (R04). A sink without it keeps the prior connect behavior (no confirmed_flush_lsn
read, unchanged streaming).
True when module implements BOTH snapshot callbacks — the config gate for
snapshot: true. A partial implementation is rejected at start
(:snapshot_unsupported) rather than half-running a backfill.