This is the multi-page printable view of this section.
pgEdge upstream manuals
- 1: Quick start
- 2: Spock
- 2.1: Installing and Configuring the Spock Extension
- 2.2: Creating a Spock Cluster: End-to-End Installation Guide
- 2.3: Using Spock to Create a Two-Node Cluster
- 2.4: Sizing Postgres Resources for Spock
- 2.5: Configuring Spock
- 2.6: Managing a Spock Installation
- 2.7: Adding a Node to a Replicating Cluster
- 2.8: Conflict Types
- 2.9: Conflict-Free Delta-Apply Columns (Conflict Avoidance)
- 2.10: Monitoring the Configuration and Health of Your Cluster
- 2.11: Spock Functions
- 2.11.1: Spock Functions
- 2.11.1.1: spock.cleanup_resolutions
- 2.11.1.2: spock.gen_slot_name()
- 2.11.1.3: spock.get_country()
- 2.11.1.4: spock.max_proto_version()
- 2.11.1.5: spock.min_proto_version()
- 2.11.1.6: spock.node_add_interface()
- 2.11.1.7: spock.node_alter()
- 2.11.1.8: spock.node_create()
- 2.11.1.9: spock.node_drop_interface()
- 2.11.1.10: spock.node_drop()
- 2.11.1.11: spock.node_info()
- 2.11.1.12: spock.node_refresh_info()
- 2.11.1.13: spock.replicate_ddl()
- 2.11.1.14: spock.repset_add_all_seqs()
- 2.11.1.15: spock.repset_add_all_tables()
- 2.11.1.16: spock.repset_add_partition()
- 2.11.1.17: spock.repset_add_seq()
- 2.11.1.18: spock.repset_add_table()
- 2.11.1.19: spock.repset_alter()
- 2.11.1.20: spock.repset_create()
- 2.11.1.21: spock.repset_drop()
- 2.11.1.22: spock.repset_remove_partition()
- 2.11.1.23: spock.repset_remove_seq()
- 2.11.1.24: spock.repset_remove_table()
- 2.11.1.25: spock.repset_show_table()
- 2.11.1.26: spock.sub_add_repset()
- 2.11.1.27: spock.sub_alter_interface()
- 2.11.1.28: spock.sub_alter_options()
- 2.11.1.29: spock.sub_alter_skiplsn()
- 2.11.1.30: spock.sub_alter_sync
- 2.11.1.31: spock.sub_create()
- 2.11.1.32: spock.sub_disable
- 2.11.1.33: spock.sub_drop()
- 2.11.1.34: spock.sub_enable
- 2.11.1.35: spock.sub_remove_repset
- 2.11.1.36: spock.sub_resync_table
- 2.11.1.37: spock.sub_show_status
- 2.11.1.38: spock.sub_show_table
- 2.11.1.39: spock.sub_wait_for_sync
- 2.11.1.40: spock.sync_event
- 2.11.1.41: spock.sync_seq
- 2.11.1.42: spock.table_wait_for_sync()
- 2.11.1.43: spock.version_num()
- 2.11.1.44: spock.version()
- 2.11.1.45: spock.wait_slot_confirm_lsn()
- 2.11.1.46: spock.xact_commit_timestamp_origin()
- 2.11.2: Management Functions
- 2.11.3: Node Management
- 2.11.4: Replication Set Management
- 2.11.5: Subscription Management Functions
- 2.11.1: Spock Functions
- 2.12: Upgrading the Spock Extension
- 2.13: Recovery
- 2.14: Logical Slot Failover
- 2.15: Limitations and Restrictions
- 2.16: Internals
- 2.16.1: Design proposals
- 2.16.2: Historical plans
- 2.16.3: Design decisions
- 2.16.4: spock Output Plugin
- 2.16.5: Spock Protocol
- 2.17: Troubleshooting Spock
- 2.18: Frequently Asked Questions
- 2.19: Spock Release Notes
- 2.20: pglogical to Spock function names
- 3: LOLOR
- 4: Snowflake
- 5: SafeSession
- 6: About this site
- 6.1: Sources and attribution
- 6.2: License texts
- 6.3: Maintenance and coverage
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Four extensions address concrete tasks in distributed PostgreSQL. Start with Spock replication, then add identifiers, large-object replication, and session protection as your application needs them.
- Spock — Multi-master replication and conflicts
- Snowflake — Distributed unique IDs
- LOLOR — Large object logical replication
- SafeSession — Read-only sessions by role
The English source set is Spock v6.0.0-beta.2, LOLOR 1.3.0 development, SafeSession v1.1, and Snowflake v2.6.1. All 118 English pages have Chinese counterparts. See sources and versions.
Start reading
1 - Quick start
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Read the installation prerequisites, then follow the complete two-node procedure. Spock requires PostgreSQL server patches, compatible table definitions, and authenticated connections between nodes.
2 - Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The English source is v6.0.0-beta.2 (pre-release), pinned at d05e2e2b6a82. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
The Spock extension provides multi-master (active-active) replication for pgEdge Distributed and Enterprise Postgres, versions 15, 16, 17, 18, and 19. The extension leverages the pgLogical open-source project as a solid foundation to build upon for this enterprise-class extension.
Continue reading
- Frequently Asked Questions
- Configuring Spock
- Conflict Types
- Conflict-Free Delta-Apply Columns (Conflict Avoidance)
- Creating a Spock Cluster: End-to-End Installation Guide
- Installing and Configuring the Spock Extension
- Limitations and Restrictions
- Logical Slot Failover
- pglogical to Spock function names
- Sizing Postgres Resources for Spock
- Spock Release Notes
- Troubleshooting Spock
- Using Spock to Create a Two-Node Cluster
- Upgrading the Spock Extension
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.1 - Installing and Configuring the Spock Extension
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension can be installed with pgEdge Postgres packages or built from source. pgEdge Postgres deployments provide a simplified upgrade path that allows you to take advantage of important new features quickly and easily.
Spock is open-source, with code available for review at GitHub.
Spock uses files stored in the spock schema to provide replication
functionality. Do not delete, create, or modify files in the spock
schema directly; use Spock functions and procedures to manage
replication.
For detailed information about using Spock to create a two-node cluster, see Creating a Two-Node Cluster.
Installing Spock with pgEdge Enterprise Postgres
The latest Spock extension is automatically installed with any pgEdge Enterprise Postgres installation. A pgEdge deployment provides quick and easy access to the following features:
- the latest minor version of your preferred Postgres version.
- Spock functions and procedures.
- ACE consistency monitoring.
- Snowflake sequences.
- pgBackRest for simplified backup and restore capabilities.
- LOLOR large object support.
- management tools for your active-active distributed cluster.
Building the Extension from Source
Spock is available as an open-source project
that you can build from source code distributed at the GitHub project page.
The Spock extension must be built on a version-specific build of Postgres
that is patched to provide hooks so spock can access the Postgres engine.
To patch the Postgres source code, download the source code from the
Postgres project, and move into
the source directory. Then, clone the spock directory:
Then, apply the .diff files from the spock/patches/version directory
that match your build version. To apply a patch, use the command:
After applying version-specific patches, you can configure, make, and
make install the Postgres server as described in the
Postgres documentation.
When the build completes, add the location of your pg_config file to your
PATH variable:
Before invoking make and make install, install the
jansson library to meet
Spock prerequisites.
Then, move into the spock directory, and use a build process much like
any other Postgres extension:
Configuring Postgres for Spock Replication
After installing Postgres on each node that will host a spock instance, use initdb to initialize a Postgres cluster. After initializing the cluster, you can connect with psql, and query the server for file locations and cluster details:
Then, use your choice of editor to update the postgresql.conf file, adding
required Postgres parameters to the end of the file:
The values above are a working starting point for a small cluster (two or
three nodes, one replicated database). They are not one-size-fits-all: Spock
launches a supervisor, a slot sync worker, one background worker per database
in the instance, and one per subscription; subscription counts scale with node count multiplied by the number of
replicated databases, and max_worker_processes is shared with parallel query
workers. See
Sizing Postgres Resources for Spock for the formulas and
per-cluster recommendations before going to production.
Set output_plugin_libraries only if your server has that parameter — it was
added by a 2026 security fix and, without spock_output listed there, logical
decoding fails with library "spock_output" may not be used as an output plugin. The check runs every time decoding starts, so it stops established
clusters after a minor-version upgrade too, and it applies to every node. On
older releases the parameter does not exist and setting it stops the server
from starting. See Configuring Spock for how to check.
Note on replication origin states:
- PostgreSQL 15-17: The
max_replication_slotsparameter controls both the number of replication slots and the number of replication origin states; when sizing this parameter, account for both slots and origins (one origin per subscription, and subscriptions are counted per replicated database). - PostgreSQL 18+: A new parameter
max_active_replication_originswas introduced to separately control the number of replication origin states; the default value is 10, which may be insufficient for clusters with many subscriptions; set this to at least the number of subscriptions this node applies -(nodes - 1) x replicated databasesin a full mesh - plus some headroom (similar sizing tomax_replication_slots).
After modifying the Postgres parameters, use your OS-specific command to restart the Postgres server:
Then, connect to the psql command line, and create the spock extension:
On each node that will host spock, modify the pg_hba.conf
file and
allow connections between n1 and n2. The following snippet is provided
as an example only, and is not recommended for a production system as it
will open your system for connection from any client:
Creating a Replication Scenario
After configuring the nodes, connect to the psql command line of the first
provider node, and use the spock.node_create command to create the
provider node:
Then, add the tables in the public schema to the default replication
set:
Once the provider node is configured, you can add subscribers. First, create the subscriber node:
Then, create the subscription which will start synchronization and replication on the subscriber node:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.2 - Creating a Spock Cluster: End-to-End Installation Guide
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This guide walks you through installing Spock and creating a two-node active-active replication cluster.
Before you begin, ensure you have met the following prerequisites:
- Each node must be a physical or virtual machine with network connectivity.
- You must have administrative access to both nodes.
- A basic familiarity with PostgreSQL and command-line operations is required.
The installation process follows these steps.
- Add the pgEdge repository and install pgEdge Postgres with Spock.
- Configure PostgreSQL parameters for logical replication.
- Create the Spock extension on both nodes.
- Set up node definitions and bidirectional subscriptions.
- Enable automatic DDL replication across the cluster.
- Test the cluster to verify bidirectional replication works correctly.
Install pgEdge Enterprise Postgres (Recommended Path)
This section describes how to install pgEdge Enterprise Postgres with Spock using the pgEdge repository.
First, on each node, add the pgEdge repository to your system.
For RHEL/Rocky Linux/AlmaLinux 10, first install EPEL:
On RHEL 10, also enable the CodeReady Builder repository:
On Rocky Linux 10 or AlmaLinux 10, enable the equivalent CRB repository instead:
Version-specific commands for RHEL, OEL, Alma, and Rocky are available in the pgEdge Enterprise Postgres documentation.
For Ubuntu/Debian:
Before configuring local access to the pgedge repository, you should ensure that your system does not contain any community Postgres packages. Then, install the platform-specific prerequisites for your system with the commands:
Then, create the repository with the commands:
For detailed information about using the pgEdge repository, see the pgEdge Enterprise Postgres documentation.
After creating the repository, install your preferred PostgreSQL version. The examples use PostgreSQL 18. If you switch to 15, 16, 17, or 19, update every versioned package, path, and service name in the snippets below.
For RHEL/Rocky Linux/AlmaLinux:
For Ubuntu/Debian:
On each node, initialize the PostgreSQL database cluster.
For RHEL/Rocky Linux/AlmaLinux:
For Ubuntu/Debian:
In the following example, the psql command connects to PostgreSQL to
verify the installation:
Once connected, confirm that you can see the configuration file locations.
In the following example, the SHOW commands display the PostgreSQL
configuration file locations:
The pgEdge Enterprise Postgres installation automatically includes the following components:
- The latest minor version of your chosen Postgres version.
- The Spock extension (pre-installed, ready to enable).
- Spock functions and procedures.
- ACE consistency monitoring.
- Snowflake sequences.
- pgBackRest for simplified backup and restore.
- LOLOR large object support.
- Management tools for active-active distributed clusters.
Install from Source (Alternative Path)
If you need to build Spock from source instead of using pgEdge Enterprise Postgres, follow these steps.
Download PostgreSQL source code from the Postgres project and navigate to the source directory.
Clone the Spock repository with the following command:
Apply the version-specific patches with the following command:
Configure, build, and install PostgreSQL as described in the Postgres documentation.
Add the
pg_configfile location to your PATH with this command:Install the jansson library (required for Spock).
Build and install Spock with the following commands:
Repeat the installation process on both nodes.
After building from source, use initdb to initialize a PostgreSQL cluster on each node.
Configure PostgreSQL for Spock Replication
On each node, edit the postgresql.conf file and add the required
parameters to the end of the file.
In the following example, the configuration parameters enable logical replication and load the Spock extension:
max_worker_processesThis parameter covers more than one worker per node: Spock runs a
supervisor, a slot sync worker (present on every node, primary or
standby), a manager for every connectable database in the instance
(including postgres and template1), an apply worker per subscription,
and a sync worker per subscription during table synchronization.
Subscriptions are created per database, so their count is the number of
other nodes multiplied by the number of replicated databases. The pool
is also shared with parallel query workers. See
Sizing Postgres Resources for Spock for the formulas.
Set output_plugin_libraries only if your server has that parameter — it
was added by a 2026 security fix and, without spock_output listed there,
logical decoding fails with library "spock_output" may not be used as an output plugin. The check runs every time decoding starts, so it stops
established clusters after a minor-version upgrade too, and it applies to
every node. On older releases the parameter does not exist and setting it
stops the server from starting. See
Configuring Spock for how to check.
PostgreSQL 15-17: The
max_replication_slotsparameter controls both slots and replication origin states. Account for both when sizing (one origin per subscription, and subscriptions are counted per replicated database).PostgreSQL 18+: A new parameter
max_active_replication_originsseparately controls origin states. The default value is 10, which may be insufficient. Set the value to at least the number of subscriptions this node applies -(nodes - 1) x replicated databasesin a full mesh - plus headroom.
After modifying postgresql.conf, restart PostgreSQL using your
OS-specific command.
In the following example, the systemctl commands restart and verify
the PostgreSQL service:
Verify the service is active and running.
On each node, modify the pg_hba.conf
file to allow connections between the nodes.
Add entries for both regular and replication connections. Replace
<node_1_IP_address> and <node_2_IP_address> with your actual IP
addresses.
In the following example, the configuration entries allow connections from both nodes:
The example above uses trust authentication for simplicity and is
not recommended for production systems. In production, use
appropriate authentication methods like scram-sha-256 or md5.
After modifying pg_hba.conf, reload the server configuration to apply the
changes (no restart required):
Create the Spock Extension
On each node, connect to PostgreSQL and create the Spock extension.
In the following example, the CREATE EXTENSION command creates the
Spock extension:
Spock uses the spock schema to provide replication functionality.
Do not delete, create, or modify files in the spock schema
directly. Use Spock functions and procedures to manage replication.
Create Nodes and Configure Replication
This section describes how to set up bidirectional replication between the two nodes.
For this guide, the nodes are named n1 and n2.
On Node 1 (n1)
Follow these steps to create the node definition and add tables to the replication set.
Create the node definition with the following command:
Add tables to the default replication set with this command:
If you are working in a schema other than
public, adjust the schema name accordingly.
On Node 2 (n2)
Follow these steps to create the node definition, add tables, and create the subscription.
Create the node definition with the following command:
Add tables to the default replication set with this command:
Create the subscription from n2 to n1 with these commands:
On Node 1 (n1)
Create the reverse subscription from n1 to n2 with the following commands:
On Both Nodes (n1 and n2)
To ensure DDL statements are automatically replicated across your cluster, run these commands on both nodes.
In the following example, the ALTER SYSTEM commands enable automatic
DDL replication:
These settings enable the following features:
- DDL statements are automatically replicated through the default replication set.
- New tables are automatically added to replication sets; tables with primary keys are added to the default set, and tables without primary keys are added to the default_insert_only set.
Verify the Cluster
On each node, use the following command to verify that nodes are properly configured.
In the following example, the SELECT command displays the configured
nodes:
Expected output:
Then, use the following command to verify that subscriptions are active and replicating.
In the following example, the SELECT command displays the subscription
status:
Expected output:
The status field should display replicating.
Test Replication
Perform a simple replication test using the following steps.
On n1, create a test table with the following commands:
On n2, verify the table exists and contains the data with this query:
Expected output:
On n2, insert a new row with the following command:
On n1, verify both rows are present with this query:
Expected output:
Both messages should appear on both nodes, confirming that bidirectional replication is working.
Next Steps
Your two-node Spock cluster is now operational. The following documents describe the next steps for configuring and managing the cluster.
- The Configuring Spock document describes conflict resolution settings and advanced configuration options.
- The Spock Functions Reference document provides detailed information about monitoring functions and replication management.
- The Managing DDL Replication document explains how to control automatic DDL replication behavior.
Troubleshooting
If you encounter issues, review the following common problems and solutions.
- Check the
pg_hba.confentries and ensure the nodes can connect to each other if replication is not starting. - Verify that
max_replication_slotsandmax_wal_sendersare set to sufficient values when a subscription is stuck initializing. A subscription that is synchronizing needs a second slot and walsender on the provider in addition to those held by its apply stream; see Sizing Postgres Resources for Spock. - If DDL is not replicating, confirm that the automatic DDL replication settings are enabled on both nodes.
- If errors are not clear, review the PostgreSQL logs for detailed error messages.
For more information, see the following resources:
- The Spock Functions Reference document provides detailed function documentation.
- The Advanced Configuration Options document describes additional configuration parameters.
- The Managing DDL Replication document explains DDL replication features.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.3 - Using Spock to Create a Two-Node Cluster
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The upstream example in step 3 gives postgresql.conf as the path to pg_hba.conf. Authentication rules belong in the actual pg_hba.conf; SHOW hba_file; reports its path. See known upstream issues.
After installing and initializing Postgres and creating the Spock Extension, you can use the following steps to configure a two-node cluster. In the examples that follow, we’ll be creating a cluster that contains two nodes, named n1 and n2 that listen for Postgres server connections on port 5432.
Connect to each node, and use the following commands to initialize a cluster:
sudo /usr/pgsql-17/bin/postgresql-17-setup initdbsudo systemctl enable postgresql-17Use your choice of editor to open the
postgresql.conffile (located in/var/lib/pgsql/17/data/postgresql.conf) and add the following parameters to the bottom of the file:wal_level = 'logical'max_worker_processes = 20max_replication_slots = 10max_wal_senders = 10shared_preload_libraries = 'spock'track_commit_timestamp = onThese values are sized for this two-node example, which replicates a single database. Before moving to production, or if you add nodes or databases, size them from your topology using Sizing Postgres Resources for Spock - subscriptions are created per database, so slots, walsenders, and workers scale with node count multiplied by replicated database count, and
max_worker_processesis additionally shared with parallel query workers and needs one slot per database in the instance, one for the supervisor, and one more for the slot sync worker.Edit the
pg_hba.conffile (useSHOW hba_file;to find its path) and allow connections betweenn1andn2; the following commands are provided as an example only, and are not recommended for production systems as they will open your system for connection from any client:host all all 0.0.0.0/0 trustlocal replication all trusthost replication all 0.0.0.0/0 trustUse the
spock.node_createcommand to create the provider and subscriber nodes; onn1, use the command:SELECT spock.node_create (node_name := 'n1', dsn := 'host=<n1_ip_address> port=<n1_port> dbname=<db_name>');On
n2:SELECT spock.node_create (node_name := 'n2', dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>');On
n1, use thespock.repset_add_all_tablescommand to add the tables in thepublicschema to thedefaultreplication set. If you are working in another schema, customize this command as needed:SELECT spock.repset_add_all_tables('default', ARRAY['public']);On n2, use the
spock.sub_createcommand to create the subscription between n2 and n1; the name of the subscription issub_n2_n1:SELECT spock.sub_create (subscription_name := 'sub_n2_n1', provider_dsn := 'host=<n1_ip_address> port=<n1 port> dbname=<db_name>');SELECT spock.sub_wait_for_sync('sub_n2_n1');On
n1, create a corresponding subscription ton2namedsub_n1_n2:SELECT spock.sub_create (subscription_name := 'sub_n1_n2', provider_dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>');To ensure that modifications to your DDL statements are automatically replicated, connect to each node with a Postgres client and invoke the following SQL commands:
ALTER SYSTEM SET spock.enable_ddl_replication=on;ALTER SYSTEM SET spock.include_ddl_repset=on;ALTER SYSTEM SET spock.allow_ddl_from_functions=on;SELECT pg_reload_conf();Then, check the status of each node:
A simple test to check that your system is replicating is to connect to the Postgres server on n1 and add an object (like a table), and then confirm that it is available on n2. Similarly, you can create an object on n2, and confirm that it has been created on n1.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.4 - Sizing Postgres Resources for Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock replication consumes three separate, independently-configured Postgres resources: background worker slots, walsender slots, and replication slots/origins. Each is governed by a different parameter, and each is sized from a different property of your cluster.
Many of the values shown in the tutorials are a starting point for a small test cluster, not a recommendation for production. This page explains what Spock actually launches so you can size each parameter deliberately.
Every parameter on this page backed by an explicit recommendation requires
a server restart to change. Under-sizing them is not a soft failure:
Spock raises an ERROR when a worker cannot be registered and the
supervisor retries in a loop, so replication does not start at all. Formulas
include a small amount of headroom partially to prevent this.
What Spock Runs on Each Node
| Process | How many | Counts against |
|---|---|---|
| Supervisor | 1 per instance, always running | max_worker_processes |
| Slot sync worker | 1 per instance | max_worker_processes |
| Manager | 1 per connectable database in the instance | max_worker_processes |
| Apply worker | 1 per enabled subscription | max_worker_processes |
| Table sync worker | at most 1 concurrently per subscription | max_worker_processes |
| Walsender | 1 per subscription streaming from this node, plus 1 more per subscription during table sync | max_wal_senders |
Four of these counts are commonly misjudged.
A slot sync worker exists on every node, not just standbys. These workers copy logical replication slots to each physical standby so that failovers do not force a full resync of every subscriber. These workers remain idle on primary nodes but still consume a worker slot, so are included in the formula. See Slot Synchronization below for more information.
Managers are launched for every connectable database, not just the ones
using Spock. The supervisor cannot determine whether a database contains a
Spock node without connecting to it, and a background worker cannot switch
databases. So it launches a manager for every database in pg_database with
datallowconn = true; managers that find no Spock node exit immediately.
On a default cluster that means postgres and template1 each get a
short-lived manager in addition to your replicated database. template0 is
excluded because it does not allow connections.
Walsenders are not background workers. They are governed by
max_wal_senders and counted separately in MaxBackends. Raising
max_worker_processes does nothing for walsender exhaustion, and vice versa.
Subscriptions are per database, not per node. A Spock node is created inside a single database, and each subscription connects one database on this instance to the corresponding database on one other instance. An instance that replicates several databases therefore hosts one Spock node per replicated database, and each of those nodes carries its own full set of subscriptions. Everything downstream of the subscription count such as apply workers, table sync workers, walsenders, slots, and origins, all scale with node count multiplied by replicated database count, not node count alone.
Slot Synchronization
Slot synchronization is not optional for a cluster with a physical standby: a promotion without it forces every subscriber to recreate its slot and re-sync its tables. What changes between PostgreSQL versions is only who supplies the worker.
| PostgreSQL | Supplied by | Charged to max_worker_processes |
|---|---|---|
| 15, 16 | Spock’s spock_failover_slots background worker | Yes |
| 17 | Either, depending on sync_replication_slots | Yes - Spock registers its worker regardless, and it stands down when the native one is enabled |
| 18+ | PostgreSQL’s native slotsync worker | No - it is a dedicated postmaster process, counted separately in MaxBackends |
Budget a worker for it on every node and every version. Where PostgreSQL supplies the worker the budgeted slot simply becomes headroom, which costs nothing beyond a little shared memory and spares you a version-dependent formula. Logical Slot Failover covers the configuration each mechanism needs.
Sizing max_worker_processes
For one node, at peak:
spock_workers = 1 # supervisor
+ 1 # slot sync worker
+ D # connectable databases in this instance
+ S # apply workers: one per enabled subscription
+ S # table sync workers: worst case, one per subscription
max_worker_processes = spock_workers
+ max_parallel_workers # shared pool - see below
+ other_extension_workers # pg_cron, pg_squeeze, ...
+ 2 # headroom
Where:
Nis the number of Spock nodes in the cluster.Dis the number of databases in the instance withdatallowconn = true, includingpostgresandtemplate1— not just the databases participating in replication.Ris the number of databases in this instance that actually participate in Spock replication (R <= D). It is1in most deployments.Sis the total number of enabled subscriptions across all databases in the instance. In a fully-meshed cluster ofNnodes each replicating the sameRdatabases,S = R * (N - 1). With a single replicated database that reduces to the familiarS = N - 1.
max_worker_processes is a shared pool. Parallel query workers
(max_parallel_workers, default 8), native logical replication workers
(max_logical_replication_workers), and background workers belonging to
other extensions all draw from the same allocation. A parallel-heavy
workload can starve replication of worker slots. Autovacuum workers are
the exception — they have their own autovacuum_max_workers allocation.
Recommended Minimums
Assuming a single replicated database alongside postgres and template1
(D = 3, R = 1), the default max_parallel_workers = 8, and no other
worker-using extensions:
| Cluster | Spock Workers | Total Workers |
|---|---|---|
| 2-node | 7 | 20 |
| 3-node | 9 | 20 |
| 4-node | 11 | 24 |
| 5-node | 13 | 24 |
| 8-node | 19 | 32 |
The totals are rounded up to leave room for growth; there is no meaningful
cost to over-provisioning max_worker_processes beyond a small amount of
shared memory, and the parameter cannot be changed without a restart.
Add to these numbers if your instance hosts more databases, replicates more
than one database, or runs other extensions that register background workers.
Each additional replicated database costs 1 manager (if the database is
not already counted in D) plus 2 * (N - 1) workers for its apply and sync
workers, so a 3-node cluster replicating three databases needs 3 * 2 * 2 = 12
apply and sync workers per instance rather than 4.
Sizing max_replication_slots and max_wal_senders
Each node holds a logical replication slot for every subscription that streams from it, plus a transient slot for each in-progress table sync. Sync slots are created as persistent slots (not temporary), so each one occupies a slot until the sync finishes and the slot is dropped. Every one of those slots has a walsender behind it while it is streaming, so set both parameters to the same value and compute it once, from the slot count.
The default is 10 for max_replication_slots and max_wal_senders. Consider
this a minimum value for each. If any formulas provide a value below 10,
simply retain the default value.
Where N is the number of Spock nodes and R the number of replicated
databases in the instance:
max_replication_slots = 2 * R * (N - 1) # apply slot + sync slot per subscription
+ physical_and_failover_slots
+ 2 # headroom for pg_basebackup and ad-hoc tooling
max_wal_senders = max_replication_slots
R is 1 in most deployments. A 5-node mesh replicating a single database, with
one physical standby per node, needs 2 * 1 * 4 + 1 + 2 = 11 for both
parameters; the same mesh replicating three databases needs
2 * 3 * 4 + 1 + 2 = 27.
PostgreSQL’s logical replication documentation recommends setting
max_wal_senders to at least max_replication_slots plus the number of
physical replicas connected at the same time. That extra term covers
physical standbys that stream without a slot; the formula above already
gives each physical standby a slot in physical_and_failover_slots, so
adding them a second time would double-count. Sizing every node from the
same formula, standbys included, also satisfies the separate rule that a
standby’s max_wal_senders be at least as high as its primary’s.
Not every replication connection is a walsender. Table sync workers open a
second, non-replication connection to run COPY, which draws from
max_connections. The slot sync worker on a standby likewise reaches the
primary over an ordinary connection. Both Spock’s worker and PostgreSQL’s
native one cost the primary a max_connections slot, not a walsender.
Replication Origins
Postgres uses origins to track local state for remote replication slots.
Internally, Postgres tracks replication origins separately from slots and
pins their count to max_replication_slots in Postgres versions 15-17. Our
formula should make it impossible for there to be more origins than slots in
those versions of Postgres.
However, Postgres 18 introduces max_active_replication_origins with a
default value of 10, which may be too low for an active Spock cluster. For
the sake of simplicity, we encourage using this simple formula for that
parameter:
max_active_replication_origins = max_replication_slots
This should cause Postgres 18+ to operate with a sufficiently large origin pool.
Worked Examples
Because these settings require so many inputs, this documentation provides some examples.
3-Node Mesh
Three nodes, each with a single replicated database app, plus the default
postgres and template1 databases. Each node subscribes to the other two,
and each node has one physical standby.
Per node: D = 3, R = 1, S = R * (N - 1) = 2.
5-Node Mesh
Five nodes, each with replicated databases app and ledger, plus the default
postgres and template1 databases. Each node subscribes to the other four,
and each node has two physical standbys, common in clusters leveraging safe
synchronous replication.
Per node: D = 4, R = 2, S = R * (N - 1) = 8.
Verifying Your Configuration
List the Spock workers currently running on a node:
Each Spock worker reports its role and the OIDs it serves in backend_type -
for example spock supervisor, spock manager 16384, and
spock apply 16384:1.
Compare the number of background workers in use against the limit:
The exclusion list names the client backends and auxiliary processes that do
not draw on max_worker_processes; everything left over does. The list of
auxiliary process types changes between major versions, so check it against
pg_stat_activity
for your version.
Diagnosing Exhaustion
worker registration failed, you might want to increase max_worker_processes setting
Postgres refused to register a background worker because
max_worker_processes is fully allocated. Recompute with the formula above,
remembering that parallel query workers share the pool, and restart.
could not register spock worker: all background worker slots are already used
Spock’s own worker-tracking array — sized to max_worker_processes at
startup — has no free entry. A worker that exits cleanly releases its entry
immediately, but a worker that crashes leaves its entry reserved for the
same database until that database’s manager (or the supervisor) reclaims it.
Repeated worker crashes across many different databases can therefore exhaust
the array while Postgres still reports free worker slots. Check the server log
for the preceding crash and address that; raising max_worker_processes
enlarges the array but does not fix the underlying failures.
Subscription stuck in initializing
Usually max_replication_slots or max_wal_senders on the provider. A
subscription that is initializing needs a slot and walsender for its sync
worker in addition to those already held by its apply stream, which is why a
cluster that replicates fine in steady state can fail to add or resync a
table. See Troubleshooting.
Increasing replication lag with idle apply workers
If spock.lag_tracker shows growing lag but apply workers are not running,
check the server log for worker registration failures — the manager retries
registration on a delay, so an exhausted worker pool presents as intermittent
apply rather than a hard stop.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.5 - Configuring Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Add the following postgresql.conf settings on each node in your Spock
replication scenario before creating the Spock extension:
These values suit a small cluster of two or three nodes replicating a single database. Subscriptions - and the workers, walsenders, and slots that follow from them - scale with node count multiplied by the number of replicated databases, so an instance replicating several databases needs proportionally more of each. For anything larger, or for an instance hosting several databases or other extensions that use background workers, size each parameter with the formulas in Sizing Postgres Resources for Spock. All three require a server restart to change.
output_plugin_librariesA 2026 PostgreSQL security fix (CVE-2026-6471, back-patched to every
supported major) added the output_plugin_libraries parameter, and a
library may no longer be used as an output plugin unless it is listed
there. Its default, 'pgoutput, test_decoding', does not include
spock_output, so on such a server logical decoding fails with:
The check runs every time decoding starts, not only when the slot is
created, so an established cluster stops replicating after a minor-version
upgrade too. Add spock_output to the list, keeping the core defaults, as
shown above, on every node — including standbys, which need it once
promoted.
Only set the parameter if your server has it. On a PostgreSQL release
predating the fix an unrecognised parameter in postgresql.conf stops the
server from starting at all. To check, run against a server that is up:
A NULL result means the parameter does not exist and must not be set. You can also ask the binary, with no server running:
After modifying the parameters and restarting the Postgres server with your OS-specific restart command, connect with psql and create the Spock extension:
You will also need to modify your
pg_hba.conf file
to allow logical replication connections from localhost and between nodes.
Logical replication connections are treated by pg_hba.conf as regular
connections to the provider database.
After modifying the pg_hba.conf file on each node, reload the server
configuration to apply the changes (no restart required):
Advanced Configuration Options for Spock
You can use the following configuration parameters (GUCs) on the psql
command line with a SET statement or in a Postgres configuration file
(for example, postgresql.conf) to configure a Spock installation.
spock.allow_ddl_from_functions
spock.allow_ddl_from_functions enables spock to automatically replicate
DDL statements that are called within functions to also be automatically
replicated. This can be turned off if these functions are expected to run
on every node. When this is set to off, statements replicated from
functions adhere to the same rule previously described for
include_ddl_repset. If a table possesses a defined primary key, it will be
added into the default replication set; alternatively, they will be added
to the default_insert_only replication set.
spock.apply_change_logging
spock.apply_change_logging controls per-change JSON logging by the apply
worker. After each change is successfully applied locally, a single JSON
object is written to the PostgreSQL server log (at LOG level) so that
operators can correlate replayed changes with their origin and commit
timestamp. This is intended for debugging and auditing; it adds log volume
proportional to the apply workload, so leave it at the default in normal
operation.
The following values are possible:
none(the default) - no per-change logging.key_only- for eachINSERT/UPDATE/DELETE, log the action, schema-qualified table, primary-key values, origin, and commit timestamp.verbose- all of the above, plus the old and new row data for each change.
Replicated DDL is logged (with its SQL text) in both key_only and
verbose modes. This option can be set by a superuser via SET, or
reloaded with the SIGHUP mechanism (for example,
SELECT pg_reload_conf()); a server restart is not required.
spock.channel_counters
spock.channel_counters is a boolean value (the default is true) that
enables or disables the Spock channel statistic information collection. This
option can only be set when the postmaster starts.
spock.check_all_uc_indexes
This feature is experimental and OFF by default. Use this feature at
your own risk.
This parameter enhances conflict resolution during INSERT operations in
scenarios where a row exists that meets unique constraints defined on the
table (rather than primary keys or replication identity).
If this GUC is enabled, Spock will continue to check unique constraint
indexes, after checking the primary key or replica identity index. Only one
conflict will be resolved, using Last-Write-Wins logic. This includes the
primary key or replica identity index. If a second conflict occurs, the outcome is recorded in the
spock.resolutions table if spock.save_resolutions is enabled; otherwise
it is not persisted.
Partial unique constraints are supported, but nullable unique constraints are not. Deferrable constraints are not supported, are filtered out and are not checked, and therefore may still cause an exception during the final commit.
Unique constraint indexes are checked in OID order, after the primary key. It is therefore possible for the resolution of a unique constraint to change the primary key value.
Child tables / foreign keys are not checked or handled. Therefore, if resolving a unique constraint changes the primary key value, you can inadvertently create orphaned foreign key records.
spock.conflict_resolution
spock.conflict_resolution sets the resolution method for any detected
conflicts between local data and incoming changes. The only supported value
in current Spock releases is:
last_update_wins(the default) - the version of data with the newest commit timestamp will be kept (this can be either the local or the remote version).
To enable conflict resolution, the track_commit_timestamp setting must be
enabled.
spock.deny_all_ddl
spock.deny_all_ddl is a boolean value (the default is false) that
enables or disables the execution of DDL statements within a Spock
configured cluster. This option can be set at postmaster startup, with the
SIGHUP mechanism, or on the command line with SQL if you’re a superuser.
spock.enable_ddl_replication
spock.enable_ddl_replication enables
automatic replication of ddl statements through
the default replication set.
spock.exception_behaviour
Use this GUC to specify the commit behavior of Postgres when it encounters an ERROR within a transaction:
transdiscard(the default) - setspock.exception_behaviourtotransdiscardto instruct the server to discard a transaction if any operation within that transaction returns anERROR.discard- setspock.exception_behaviourtodiscardto continue processing (and replicating) without interrupting server use; the server will commit any operation (any portion of a transaction) that does not return anERRORstatement.sub_disable- setspock.exception_behaviourtosub_disableto disable the subscription for the node on which the exception was reported; transactions for the disabled node will be added to a queue that is written to the WAL log file; when the subscription is enabled, replication will resume with the transaction that caused the exception, followed by the other queued transactions; you can use thespock.sub_alter_skiplsnfunction to skip the transaction that caused the exception and resume processing with the next transaction in the queue.
Note that the value you choose for spock.exception_behaviour could
potentially result in a large WAL log if transactions are allowed to
accumulate.
spock.event_history_size
spock.event_history_size sets how many recent events the spock.events
view keeps in shared memory. Once the history is full the oldest event is
dropped for each new one. The parameter accepts values from 16 to
1048576 (the default is 1024) and can only be set when the postmaster
starts.
spock.exception_logging
Use this GUC to specify which operations or transactions are written to the exception log table:
all(the default) - setspock.exception_loggingtoallto instruct the server to record all transactions that contain one or more failed operations in thespock.exception_logtable; note that this setting will log all operations that are part of a transaction if one operation fails.discard- add a row to thespock.exception_logtable for any discarded operation; successful transactions are not logged.none- instructs the server to not log any operation or transactions to the exception log table.
spock.exception_replay_queue_size - DEPRECATED
This parameter will not be supported after version 5.X.
When Spock encounters a replication exception, it attempts to resolve the
exception by entering exception-handling mode, based on the value of
spock.exception_behaviour. Spock then writes any transaction up to a
default size of 4MB to memory, and the apply worker replays the
transaction from memory. This provides a massive speed and performance
increase in the handling of the vast majority of exceptions. The memory
size is configurable with spock.exception_replay_queue_size.
Now, Spock performs as specified by the
spock.exception_behaviour parameter.
spock.extra_connection_options
You can use the spock.extra_connection_options parameter in the
postgresql.conf file to assign connection options that apply to all
connections made by Spock. This can be a useful place to set up custom
keepalive options, etc.
spock defaults to enabling TCP keepalives to ensure that it notices when
the upstream server disappears unexpectedly. To disable them add
keepalives = 0 to spock.extra_connection_options.
wal_sender_timeout
For Spock replication, set wal_sender_timeout to a conservative value such
as 5min (300000ms) on each node in postgresql.conf:
The default PostgreSQL value of 60s can cause spurious disconnects when
the subscriber is busy applying a large transaction and cannot send feedback
in time. A higher value gives the apply worker enough headroom while still
detecting truly dead connections. Liveness detection is primarily handled by
TCP keepalives, and spock.apply_idle_timeout provides an additional
subscriber-side safety net.
spock.apply_idle_timeout
Maximum idle time (in seconds) before the apply worker reconnects to the
provider. This acts as a safety net for detecting a hung walsender that keeps
the TCP connection alive but stops sending data. The timer resets on any
received message. Set to 0 to disable and rely solely on TCP keepalive for
liveness detection. Default: 300 (5 minutes).
spock.sync_timeout
Overrides the time (in seconds) budgeted for a single synchronisation wait in
the node management routines - waiting for a sync event to arrive on a peer,
waiting for a node to catch up, or waiting for a subscription to start
replicating. Default: 0, meaning each routine keeps its own built-in limit
(3 minutes). Only a positive value takes effect, so leaving this unset
preserves the behaviour those routines have always had.
Raise it on large databases. The built-in limits are sized for small clusters, where a node joins in seconds; when catchup legitimately takes minutes or hours, the routines fail with a timeout long before the work is done. It can be raised for a single operation rather than cluster-wide:
This bounds a whole wait, not an individual probe of a remote node. Routines that additionally bound each remote probe - so that one unresponsive peer cannot consume the entire budget - keep their own, much smaller limit for that purpose.
spock.read_retry_count
Number of times the apply worker re-reads the local relation when a row
targeted by a remote UPDATE or DELETE is not yet visible. On each retry
the apply worker waits for any concurrently-applying transaction to finish
and then searches the local relation again. If the row is still missing
after the configured number of retries, the apply worker falls through to
the standard row-missing handling path (conflict resolution and/or the
exception handler, depending on the configured
spock.exception_behaviour).
Set to 0 to disable retries entirely (the row-missing path runs
immediately). Valid range is 0 to 100. Default: 5. Changes take
effect on SIGHUP (for example, SELECT pg_reload_conf()); a server
restart is not required.
Logical Slot Failover (HA Standby)
Spock creates logical replication slots on each provider node. For high availability with a physical standby, these slots must be synchronized to the standby so that replication can resume without data loss after a failover.
See Logical Slot Failover for full setup
instructions, including a runbook step for clearing
synchronized_standby_slots on the promoted node after a failover.
The behaviour depends on the PostgreSQL version:
| PostgreSQL | Slot sync mechanism | Spock worker |
|---|---|---|
| 15, 16 | Spock built-in spock_failover_slots worker | Runs on every node |
| 17 | Spock worker OR native sync_replication_slots | Spock worker yields to native if enabled |
| 18+ | Native sync_replication_slots (required) | Not registered |
Whichever mechanism applies, a slot sync worker is present on every node, primary and standby alike, so include one in the worker budget - see Sizing Postgres Resources for Spock.
PostgreSQL 17 and Later (Native Slot Sync)
On PostgreSQL 17+, Spock marks every logical slot with the FAILOVER flag
at creation time. PostgreSQL’s built-in slotsync worker then synchronizes
those slots automatically.
On PostgreSQL 17, Spock’s worker only yields to native slotsync when you
set sync_replication_slots = on (below). On PostgreSQL 18+, Spock’s own
failover worker is not registered, so the native mechanism is required.
Either way, PostgreSQL’s own slot synchronization must be configured. To
switch a PostgreSQL 17 standby that Spock’s worker has been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker;
setting sync_replication_slots = on alone is not enough.
First create the physical replication slot on the primary. The standby streams
through it, and its catalog_xmin (fed back via hot_standby_feedback) is what
protects the synchronized logical slots from being invalidated:
Primary (postgresql.conf):
Standby (postgresql.conf):
Only logical slots created with failover = true are synchronized. Spock 6.0.0
sets that flag when it creates a slot, and the upgrade from 5.x sets it on
existing slots; see
Upgrading Spock to 6.0.0
for any it skips.
After a failover, subscribers only need to update their host= in the
connection string — replication resumes from the last synchronized LSN with
no data loss. However, if the promoted node has
synchronized_standby_slots set, you must clear or update it first —
otherwise its walsenders wait forever on the now-orphaned physical slot(s) and
logical replication to subscribers freezes. See the
runbook in Logical Slot Failover
for when this applies and the exact steps.
PostgreSQL 15, 16, and 17 (Spock Built-in Worker)
On PostgreSQL 15, 16, and 17, Spock’s spock_failover_slots background worker
handles slot synchronization. On PostgreSQL 17 it yields to the native
slotsync worker when sync_replication_slots = on is enabled. Configure it
with the GUCs below.
spock.synchronize_slot_names
List of slot name patterns to synchronize from primary to physical standby.
Accepts name prefixes (name:foo) or LIKE patterns (name_like:spock%).
Default: name_like:%% (synchronize all logical slots).
Used on PostgreSQL 15, 16, and 17 (when sync_replication_slots is not
enabled). On PostgreSQL 17 with native slotsync active, or on PostgreSQL 18+,
this setting is ignored.
spock.drop_extra_slots
When on (the default), the spock_failover_slots worker drops any slots
on the standby that do not match spock.synchronize_slot_names.
spock.primary_dsn
Connection string used by the spock_failover_slots worker to connect to
the primary and read slot state. If empty, primary_conninfo from
postgresql.conf is used.
spock.pg_standby_slot_names
Comma-separated list of physical replication slot names that must confirm durable flush of a given LSN before the walsender is allowed to replicate logical changes beyond that LSN. This prevents a physical standby from falling behind a logical subscriber.
Used on every supported PostgreSQL version, with or without native slot
sync. PostgreSQL’s own synchronized_standby_slots has no equivalent of
spock.standby_slots_min_confirmed: it waits for every slot it names, so
with it one standby that is down stops logical replication to every
subscriber. Use only one of them; setting both is redundant. For a failover slot
synchronized_standby_slots is applied first and waits for all of its
slots, so when it names every slot listed here this setting adds nothing,
and the walsender logs that; a slot listed only here still counts. A
listed slot that does not exist can never confirm: with the default -1
the walsender waits until wal_sender_timeout, logs a warning naming the
slot, and starts over, so after a promotion either create the slots on
the new primary or clear the setting there.
spock.standby_slots_min_confirmed
Number of slots from spock.pg_standby_slot_names that must confirm a
given LSN before logical replication is allowed to proceed. The default
-1 requires all listed slots to confirm. 0 disables the check.
With a value lower than the number of listed slots, subscribers can receive
changes that some standbys do not have yet. After a failure, promote the
standby with the highest pg_last_wal_receive_lsn(): it has every change
sent to a subscriber. Promoting a standby that is further behind leaves
subscribers with rows the new primary never had.
spock.failover_slots_naptime
How long the spock_failover_slots worker sleeps between slot-synchronization
passes, in milliseconds. A smaller value keeps the standby’s synchronized slots
closer to the primary — narrowing the window in which a promotion can find a
stale slot — at the cost of more frequent sync passes. Default: 1000 (1s).
Range: 1–3600000. Settable at runtime with SIGHUP (reload).
Used on PostgreSQL 15, 16, and 17 (when sync_replication_slots is not
enabled) — the versions on which the built-in worker performs the sync.
spock.failover_slots_feedback_naptime
Shorter retry interval, in milliseconds, used instead of
spock.failover_slots_naptime while the standby has not yet received or fed
back the WAL a slot needs. Default: 10000 (10s). Range: 1–3600000.
Settable at runtime with SIGHUP (reload).
spock.failover_slots_recreate_invalidated
Whether the spock_failover_slots worker drops and recreates a synchronized
slot whose copy on the standby was invalidated, for example because the
standby removed WAL or the primary removed catalog rows the copy still
needed. Such a copy looks current but cannot serve a subscriber after a
promotion. With the default on, the worker reports it with a WARNING,
drops it and creates it again from the primary. The new copy stays a
temporary slot until the primary’s slot has caught up with it, while the
worker keeps synchronizing the other slots; if the standby is promoted
before then, the copy is dropped. A temporary copy belongs to the worker
process: if the worker exits for any reason, for example because the
primary is restarting and cannot be reached, the copy is dropped with it,
and the worker that the postmaster starts a minute later creates it again
at the standby’s position of that time, which the primary’s slot has to
pass again. If a temporary copy is invalidated while the worker holds it,
PostgreSQL terminates the worker to release the slot, with the same
effect. With off, the worker
leaves the copy as it is and reports it once, so it can be looked at
before anything is dropped; it is recreated on the first pass after the
setting is turned back on. Settable at runtime with SIGHUP (reload).
Used on PostgreSQL 15, 16, and 17 (when sync_replication_slots is not
enabled). On PostgreSQL 17 with native slotsync active, or on PostgreSQL 18+,
this setting is ignored.
spock.failover_slots_database
The instructions below describe the 6.0.0-beta.2 snapshot. On the 5.0 maintenance branch, v5.0.15-rc.2 adds connection retries and shortens the worker restart delay to 15 seconds. See the 5.0.15 candidate notes and its configuration reference.
The database the spock_failover_slots worker connects to on the standby.
A synchronized slot copy holds the primary’s positions, but not the
snapshot the primary saved for the slot, which physical replication does
not carry. After a promotion, decoding from such a copy has to build a new
snapshot, and transactions that commit before it is consistent are never
sent to the subscriber. When this setting names a database, the worker
decodes each copy’s WAL on the standby, as PostgreSQL 17’s native slot sync
does, so the copy only points at positions where the standby has saved a
snapshot of its own. A new copy is made persistent only once that
snapshot is consistent. While a transaction older than a copy’s
restart_lsn is still open on the primary, decoding cannot reach a
consistent snapshot; the copy is reported once and left as it is until
the transaction ends, and the worker goes on with the other slots.
The check is off by default. While the setting is empty, every copy is synchronized without it, as in earlier releases, and is reported once (a WARNING on PostgreSQL 16 and 17, a LOG entry on 15); after a promotion, such a copy can still skip transactions the old primary committed shortly before the failover.
On PostgreSQL 16 this must be the database the synchronized slots belong
to, normally the Spock database. Copies in another database are
synchronized without the check, reported once with a WARNING, and carry
the same risk. The worker connects to one database only, so with Spock in
several databases on PostgreSQL 16, name the most important one; the
slots of the others are not protected. On PostgreSQL 17, any one database
covers the slots of every database. The standby also needs
wal_level = logical. PostgreSQL 15 cannot decode WAL on a standby, so
there the check is not available and each copy is noted once in the log
instead. Default: empty. Requires a restart.
On PostgreSQL 16 and 17 the worker stays connected to this database on
every node where the setting is present, including a primary, where it
otherwise sleeps, and a PostgreSQL 17 standby using native slot sync. As
with any open connection, DROP DATABASE, ALTER DATABASE ... RENAME and
CREATE DATABASE ... TEMPLATE on that database then fail. Stopping the
worker frees the database only until it restarts 60 seconds later; use
DROP DATABASE ... WITH (FORCE), or clear the setting and restart the
server. If connecting fails, for example because the database does not
exist, the worker reports it, carries on without the check, and does not
try again until the server is restarted. The same happens when the
database is dropped on the primary: replaying the drop on the standby ends
the worker, the restarted worker cannot connect to the database, and the
worker after that keeps synchronizing slots without the check.
The check is made on PostgreSQL 16 and 17 (when sync_replication_slots is
not enabled). On PostgreSQL 17 with native slot sync active, the worker still
connects but makes no check. On PostgreSQL 17, native slot sync is the
recommended setup; it gives every copy a consistent snapshot without this
setting. Turning on sync_replication_slots alone is not enough to switch:
native slot sync has further requirements and will not take over the copies
the Spock worker made, so until those are dropped most or all slots stop
being synchronized. See
Switching a PostgreSQL 17 standby from the Spock worker.
On PostgreSQL 15 and 18+, this setting is ignored.
On PostgreSQL 17, once the worker has taken over from native slot sync, a copy that native slot sync made is synchronized like any other, but a standby cannot drop it. If the primary drops that slot, the worker leaves the copy and reports it once; it is dropped on the promoted node.
spock.include_ddl_repset
spock.include_ddl_repset enables spock to automatically add tables to
replication sets at the time they are created on each node. Tables with
primary keys will be added to the default replication set, and tables
without primary keys will be added to the default_insert_only replication
set. Altering a table to add or remove a primary key will make the correct
adjustment to which replication set the table is part of. Setting a table to
unlogged will remove it from replication. Detaching a partition will not
remove it from replication.
spock.log_origin_change
spock.log_origin_change indicates whether changes to a row’s
origin should be logged to the PostgreSQL log. Rows may be being updated
locally by regular SQL operations, or by replication from apply workers.
Note that rows that are changed locally (not from replication) have the
origin value of 0. This is distinct from an unavailable or unknown origin:
a NULL value in spock.resolutions.local_origin, or unknown in
PostgreSQL logs, indicates that the origin metadata could not be determined
— it does not mean the change was local. For example:
The default of none is recommended because otherwise the amount of entries
may become numerous. The other options allow for monitoring when updates
occur outside expected patterns.
The following configuration values are possible:
none(the default) - do not log any origin change information.remote_only_differs- only log origin changes when the existing row was from one remote publisher and was changed by another remote publisher.since_sub_creation- log origin changes whether a publisher changed a row that was previously from another publisher or updated it locally, but only since the time when the subscription was created.
spock.log_verbosity
spock.log_verbosity controls the verbosity of Spock’s own debug log
output. Spock emits internal DEBUG1/DEBUG2 messages that are normally
silent, because PostgreSQL’s log_min_messages typically defaults to
warning. Lowering log_min_messages globally would surface those
messages, but it would also flood the log with unrelated PostgreSQL debug
output.
Instead, this setting promotes Spock’s own debug messages to LOG level
(which is written to the server log under any normal log_min_messages
setting), without changing log_min_messages. The value controls how much
detail is promoted:
normal(the default) - promote nothing; Spock’sDEBUG1/DEBUG2messages keep their native (normally silent) levels.debug1- promote Spock’sDEBUG1messages toLOG.debug2- promote both Spock’sDEBUG1andDEBUG2messages toLOG.
This option can be set by a superuser via SET, or reloaded with the
SIGHUP mechanism (for example, SELECT pg_reload_conf()); a server
restart is not required.
spock.non_conflicting_inserts
spock.non_conflicting_inserts is a boolean value (the default is off)
with which you assert that a replicated INSERT can never collide with a row
that already exists locally - because, for example, every node generates keys
from its own range.
Applying an INSERT normally costs two pieces of work that only a possible
collision justifies: a lookup for the conflicting local row, and a
speculative insertion that lets the unique indexes report a duplicate instead
of raising one. When this parameter is on, the apply worker skips both and
inserts the row directly.
Nothing checks the assertion. If a collision does occur, the index raises
duplicate key value violates unique constraint, the transaction is aborted,
and the outcome is decided by
spock.exception_behaviour - the row is not
resolved by spock.conflict_resolution and is not recorded in
spock.resolutions. Leave this parameter off unless collisions are
impossible by design rather than merely rare.
This option can only be set when the postmaster starts.
spock.save_resolutions
spock.save_resolutions is a boolean value (the default is false) that
logs all conflict resolutions to the spock.resolutions table. This option
can only be set when the postmaster starts.
spock.resolutions_retention_days
spock.resolutions_retention_days controls how long rows are kept in the
spock.resolutions table before the apply worker automatically deletes them.
The default is 100 days. Set to 0 to disable automatic cleanup entirely,
in which case rows accumulate indefinitely until removed manually.
This setting takes effect on pg_reload_conf() (no restart required).
spock.stats_max_entries
spock.stats_max_entries specifies the maximum number of entries that can
be stored into the Spock channel statistic. This option can only be set when
the postmaster starts. The parameter accepts values from -1 to INT_MAX
(the default is -1).
spock.temp_directory
spock.temp_directory defines the system path where temporary files needed
for schema synchronization are written. This path needs to exist and be
writable by the user running Postgres. The default is empty, which tells
Spock to use the default temporary directory based on environment or
operating system settings.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6 - Managing a Spock Installation
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension is a powerful addition to any PostgreSQL installation; management features of the Spock extension allow you to seamlessly:
- replicate partitioned tables.
- create logical row-based data filters.
- set a cluster to READ-ONLY mode; this restricts non-superusers to read-only operations, while superusers can still perform both read and write operations.
- use a trigger to manage replication set membership.
- use Snowflake sequences for sequence management in a distributed cluster.
- use the Lolor extension to replicate large objects.
- enable automatic DDL replication.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.1 - Automatic DDL Replication
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock extension can automatically replicate DDL statements. To enable
automatic DDL replication, set the following parameters to on:
spock.enable_ddl_replicationenables replication of ddl statements through the default replication set. Some DDL statements are intentionally not replicated (likeCREATE DATABASE). Other DDL statements are replicated, but can lead to replication issues (like theCREATE TABLE... AS...statement). In the case ofCREATE TABLE... AS..., the DDL statement is replicated before the table is added to the replication set, leading to potential data irregularities. Some DDL statements are replicated, but might potentially create an issue in a 3+ node cluster (ie.DROP TABLE).spock.include_ddl_repsetenables spock to automatically add tables to replication sets at the time they are created on each node. Tables with Primary Keys will be added to thedefaultreplication set, and tables without Primary Keys will be added to thedefault_insert_onlyreplication set. Altering a table to add or remove a primary key will also modify which replication set the table is a member of. Setting a table tounloggedremoves the table from replication. Detaching a partition will not remove a table from replication.spock.allow_ddl_from_functionsenables spock to automatically replicate DDL statements that are called within functions. Setspock.allow_ddl_from_functionstooffif each function is expected to execute on every node. When set tooff, statements replicated from functions adhere to the same rule described forinclude_ddl_repset. If a table possesses a primary key, it will be added into thedefaultreplication set; alternatively, they will be added to thedefault_insert_onlyreplication set.
To completely block all DDL across the cluster (including DDL that would otherwise be replicated automatically), use:
spock.deny_all_ddl- a boolean value, defaultfalse. When set totrue, Spock rejects any DDL statement executed on the node. This is useful as a guard during sensitive maintenance windows or while a node is being added or repaired. The setting can be changed by a superuser at runtime (PGC_SUSET); a server reload is not required.
It’s best to set these parameters to on only when the database schema
matches exactly on all nodes - either when all databases have no objects, or
when all databases have exactly the same objects and all tables are added to
replication sets.
You can also use the spock.replicate_ddl() function to instruct Spock
to enable automatic DDL replication. Starting automatic DDL replication
with this function instructs Spock to check the statement type of each
transaction, and execute and replicate statements identified as DDL.
During the auto replication process, spock generates messages that provide information about the execution. Here are the descriptions for each message:
DDL statement replicated.This message is an INFO level message. It is displayed whenever a DDL statement is successfully replicated. To include these messages in the server log files, the configuration must have
log_min_messages=INFOset.DDL statement replicated, but could be unsafe.This message serves as a warning. It is generated when certain DDL statements, though successfully replicated, are deemed potentially unsafe. For example, statements like
CREATE TABLE... AS...will trigger this warning.This DDL statement will not be replicated.This warning message is generated when auto replication is active, but the specific DDL is either unsupported or intentionally excluded from replication.
table 'test' was added to default replication set.This is a LOG message providing information about the replication set used for a given table when
spock.include_ddl_repsetis set.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.2 - Automatically Assigning Tables to Replication Sets
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Automatic DDL replication is a great alternative to using a trigger to manage replication sets, but if you do need to dynamically modify replication rules, column or row filters, or partition filters, this trigger might be useful. This trigger does not replicate the DDL statements across nodes, but automatically adds newly created tables to a replication set on the node on which the trigger fires.
Before using the trigger, you should modify this trigger to account for all
flavors of CREATE TABLE statements you might run. Since the trigger
executes in a transaction, if the code in the trigger fails, the transaction
is rolled back, including any CREATE TABLE statements that caused the
trigger to fire. This means that statements like CREATE UNLOGGED TABLE will
fail if the trigger fails.
Please note that you must ensure that while using the trigger, automatic replication of DDL commands is disabled. You can use the following commands on the PSQL command line to disable automatic DDL updates:
You can use the event trigger facility to describe rules that define replication sets for newly created tables. For example:
The code snippet shown above adds any new table created in the config
schema into a replication set named configuration, and adds all other new
tables (which are not created by extensions) to the default replication
set.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.3 - Filtering
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock allows row based filtering on both the provider side and the subscriber side.
Row Filtering on the Provider
On the provider, you can implement row filtering with the row_filter
property of the spock.repset_add_table function. The row_filter is a
normal PostgreSQL expression with the same limitations as the CHECK
constraint.
A simple row_filter would look something like row_filter := 'id > 0';
this filter ensures that only rows where values of id column is greater
than zero are replicated.
You can use a volatile function inside row_filter but use caution with
regard to writes as any expression that will do writes could potentially
throw an error and stop replication.
It’s worth noting that the row_filter is running inside the
replication session, so session specific expressions such as CURRENT_USER
will have the values of the replication session and not the session that did
the writes.
Row Filtering on the Subscriber
On the subscriber, row-based filtering can be implemented using the standard
BEFORE TRIGGER mechanism. You must mark triggers as either ENABLE REPLICA
or ENABLE ALWAYS or they will not be executed by the replication
process.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.4 - Replicating Partitioned Tables
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
By default, when you add a partitioned table to a Spock replication set,
Spock will include all the current partitions of a partitioned table. If you
partition a table, or add partitions to a partitioned table at a later date,
you will need to use the
spock.repset_add_partition
function to add them to your replication sets. The DDL for the partitioned
table and partitions must reside on the subscriber nodes (like a
non-partitioned table).
When you remove a partitioned table from a replication set, by default, the
partitions of the table will also be removed. You should use
spock.repset_remove_partition
to update the cluster’s meta-data.
Replication of partitioned tables is a bit different from normal tables. During an initial synchronization, we query the partitioned table (or parent) to get all the rows for synchronization purposes and don’t synchronize the individual partitions. After the initial sync of data, the normal operations resume and the partitions start replicating like normal tables.
If you add individual partitions to a replication set, they will be replicated like regular tables (to the table of the same name as the partition on each subscriber). This has performance advantages if your partitioning definition is the same on both provider and subscriber, as the partitioning logic does not have to be executed with each sync.
During the initial cluster setup and sync, table partitions are not
synced directly. Instead, the parent table is synced with the source
with data from all partitions, and the partitions are populated properly
on the destination preserving the table structure. This partitioning
behavior is equivalent to setting synchronize_data = false for
individual partitions during the initial sync.
When setup completes (after the initial sync), both the parent table and partitions are monitored for modifications, and changes are replicated as they are made.
When partitions are replicated through a partitioned table, TRUNCATE
commands always replicate to the complete list of affected tables or
partitions.
You can use a row_filter clause with a partitioned table, as well as
with individual partitions.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.5 - Using LOLOR to Manage Large objects
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
PostgreSQL’s logical decoding facility does not support decoding changes to large objects; we recommend instead using the LOLOR extension to manage large objects.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.6 - Using Spock in Read-Only Mode
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock supports operating a node in read-only mode. Read-only status is managed using a GUC parameter named spock.readonly, which can be set to one of three values:
| Value | Description |
|---|---|
off | No restrictions. All users may write. This is the default. |
local | Non-superuser local sessions are read-only. Replicated writes from apply workers are still permitted, so inbound replication continues normally. Superusers may still perform write operations. (The legacy alias user is accepted for backward compatibility.) |
all | Non-superuser local sessions and apply workers are blocked from writing. Superusers may still perform write operations. Use this mode when you need to stop both local application writes and inbound replication. |
The setting is at cluster level: either all databases are read-only or all databases are read-write (the usual setting).
Read-only mode is enforced by setting PostgreSQL’s transaction_read_only flag for affected sessions. This means that any statement that would modify data — including DML (INSERT, UPDATE, DELETE), DDL, TRUNCATE, and DCL (GRANT, REVOKE) — will be rejected by PostgreSQL’s standard read-only transaction checks.
The databases are in read-only mode at the SQL level: however, the checkpointer, background writer, walwriter, and the autovacuum launcher are still running. This means that the database files are not read-only and that in some cases the database may still write to disk.
Setting Read-Only Mode
Only a superuser can modify the spock.readonly parameter. The value can be changed using the ALTER SYSTEM command:
To set the mode for the current session only:
To query the current status:
Superuser writes and outbound replication
In both local and all modes, superusers are exempt from the read-only
restriction and may perform write operations. The readonly setting has no
effect on the walsender (outbound replication). Any writes made by a
superuser are captured in WAL and will be replicated outbound to other nodes
in the cluster, regardless of the readonly mode.
To perform repair operations that should not replicate to other nodes, use
spock.repair_mode() to suppress outbound
replication of DML/DDL statements:
Behavior of all mode
In all mode, apply workers detect the setting and stop consuming inbound
WAL — internally each worker raises a FATAL and exits, and the manager
restarts it once read-only is cleared. When the mode is switched back to
off or local, replication resumes from where it left off, provided
the upstream replication slot still retains the necessary WAL. Plan for
slot retention (max_slot_wal_keep_size, disk capacity) before placing a
node in all mode for an extended period; if the upstream slot is
recycled while the node is read-only, replication cannot resume from the
prior position and the node will need to be re-synchronized.
Notes:
- Only superusers can set and unset the
spock.readonlyparameter. - By using a GUC parameter, you can easily manage the node’s read-only status through standard PostgreSQL configuration mechanisms.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.6.7 - Using Spock with Snowflake Sequences
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Snowflake extension
provides a sequence-based unique ID solution to replace the Postgres
built-in bigserial data type in distributed replication clusters.
Snowflake sequences minimize the risk of assigning an identical key
value on different nodes at the same time; this prevents potential data
conflicts.
Spock strongly recommends using Snowflake sequences instead of legacy Postgres sequences. Snowflake sequences alleviate concerns that network lag could disrupt sequences in distributed transactions.
Using a Snowflake sequence
allows you to take full advantage of the benefits offered by a
distributed, multi-master replication solution. Snowflake provides an
int8 and sequence-based unique ID solution to optionally replace the
Postgres built-in bigserial data type.
Comparing Sequence Types
The following example compares the level of detail stored with a
traditional Postgres sequence (id values 1 and 2) versus the
level of detail available with a Snowflake sequence (id values
135824181823537153 and 135824609030176769):
The table preserves upstream output. With the v2.6.1 bit layout, the two larger IDs both encode node 0 and count 1. Snowflake functions
Snowflake Sequence Structure
Unlike Postgres sequences, a Snowflake sequence consists of a timestamp, a counter, and a unique node identifier; the structure ensures over 18 trillion unique sequence numbers. Snowflake sequences provide the following capabilities:
- A Snowflake sequence lets you add or modify data in different regions while ensuring a unique transaction sequence.
- A Snowflake sequence preserves unique transaction identifiers without manual administrative management of a numbering scheme.
- A Snowflake sequence lets you compare ID generation times across nodes. Clock skew and the interval between ID generation and commit can affect the observed order.
Internally, Snowflake sequences are 64-bit integers represented
externally as bigint values. The 64 bits divide into the following
bit fields:
- Bit 63 is unused and represents the sign of
int8. - Bits 22–62 store the timestamp with millisecond precision.
- Bits 12–21 store the unique pgEdge Distributed Postgres node number.
- Bits 0–11 store the counter within one millisecond.
The timestamp is a 41-bit unsigned value representing millisecond
precision with an epoch of 2023-01-01. The counter is a 12-bit
unsigned value that increments per ID allocation; this provides 4096
unique IDs per millisecond, or 4 million IDs per second. The node
number is a 10-bit unique identifier for the Postgres instance inside
a global cluster; you set this value using the snowflake.node GUC
in the postgresql.conf file.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7 - Adding a Node to a Replicating Cluster
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
There are several tools and scripts you can use to add a node to a cluster; the way that you choose should depend on the use and state of your cluster:
- Use Z0DAN to Add or Remove a Node with Zero Downtime
Z0DAN is a spock utility that provides scripts that you can use to seamlessly add or remove a node from your cluster with zero downtime.
- Use pgBackRest to Add a Node to a Replicating Cluster with Minimal Downtime
pgBackRest is an open-source tool that you can use to add a node to a replicating cluster with minimal interruption.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7.1 - Modifying a Cluster with Zodan
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Zodan provides tools to add or remove a node with zero downtime. The scripts are located in the samples/Z0DAN directory of the Spock GitHub repository.
During node addition, Zodan seamlessly manages creation of the new node, subscription management (both to and from the node), replication slot creation, data synchronization, replication slot advancement, and final activation of subscriptions.
During node removal, Zodan simplifies removing fully-functional or failed nodes from a cluster. When you remove a node from a cluster, the removal does not delete Postgres artifacts (the database, data directory, log files, etc.).
Zodan simplifies removing partially added nodes created during failed node add operations. Additional cleanup steps may be required before attempting another node deployment on the target host.
Each script must be run from the target node being added or removed.
Key Differences Between using Zodan and the Manual Process
The following differences highlight how Zodan automates and simplifies node addition:
Zodan stores sync LSNs and uses them later to ensure subscriptions start from the correct point even if hours pass between steps.
Zodan automatically detects existing schemas on the new node and populates the
skip_schemaparameter, preventing conflicts during structure sync.Zodan checks Spock versions before starting. Every node must be 5.0.9 or later, and the new node must run the same or a newer major.minor version than every existing node (patch levels may differ). So a 6.0.x node can join a 5.0.x cluster, and further 6.0.x nodes can join the resulting mixed cluster from any source node; a new node older than an existing node is rejected.
Zodan includes the
verify_subscription_replicating()function after enabling subscriptions to ensure they reach replicating status.When adding to a single-node cluster, Zodan handles the process differently — no disabled subscriptions are needed.
Zodan shows final status of all nodes and subscriptions across the entire cluster, not just the new node.
For more information, review the following resources:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7.1.1 - Tutorial: Adding a Node to a Cluster with Zero Downtime
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
In this detailed walkthrough, we add a fourth node to a three-node cluster
with zero downtime. In our example, the cluster nodes are n1 (the source
node), n2, n3, and the new node is n4.
Important Prerequisites and Warnings
- The new node should not be accessible to users while adding the node.
- Disable
auto_ddlon all cluster nodes. - Do not modify your DDL during node addition.
- The users must be identical on the source and target node. You must create any users on the target node before proceeding; the permissions must be identical for all users on both the source and target nodes.
- The ZODAN process validates that all users from the source node exist on the new node before proceeding with cluster addition. This prevents replication failures caused by missing user permissions.
- The Spock configuration must be identical on both the source and the target node.
- All nodes in your cluster must be available to Spock for the duration of the node addition.
- The procedure should be performed on the new node being added.
- The
dblinkextension must be installed on the node from which commands likeSELECT spock.add_node()are being run. - Prepare the new node to meet all of the prerequisites described here.
- If the process fails, do not immediately retry a command until you ensure that all artifacts created by the workflow have been removed.
- The automated
spock.add_node()procedure allows 180 seconds (3 minutes) for each wait for a sync event between nodes. If replication lag exceeds this window, the procedure will raise an exception. Ensure network latency and replication lag are within acceptable limits before starting, or raise the budget for the session withspock.sync_timeout, as described in Setting the Synchronisation Timeout below. When following the manual workflow below, you callspock.wait_for_sync_event()directly and supply your own timeout (the examples use 1200 seconds), so neither the default norspock.sync_timeoutapplies.
Creating a Node Manually
If you are not using spock.node_create to create the new node, you will
need to complete the following steps:
- Initialize the new node with
initdb. - Create a database.
- Create a database user.
- Follow the instructions at the GitHub repository to build and install Spock on the database.
- Add
spockto theshared_preload_librariesparameter in thepostgresql.conffile. - Restart the server to update the configuration.
- Use the
CREATE EXTENSION spockcommand to create the Spock extension.
Sample Configuration and New Node Creation Steps
In our example, the cluster configuration details include the following information:
- Database:
inventory - User:
pgedge - Password:
1safepassword - n1 (source): port 5432
- n2 (replica): port 5433
- n3 (replica): port 5434
- n4 (new node): port 5435
- Host: 127.0.0.1
The steps used to configure the new node (n4) include the following commands. The commands initialize the database and install Spock:
Using the Zodan Procedure to Add a Node
After creating the node, you can use Zodan scripts to simplify adding a node to a cluster.
To use the SQL script, connect to the new node that you wish to add to the
pgEdge cluster. In the following example, the psql command connects to the
new node:
Load the Zodan procedures with the following command:
Then, use spock.add_node() from the new node to create the node
definition. In the following example, the spock.add_node procedure adds node n4 to
the cluster:
The spock.add_node function executes the steps required to add a node to
the cluster; a detailed explanation of the steps performed follows below.
Should a problem occur during this process, you can source the
zodremove.sql script and call the spock.remove_node procedure to
remove the node or reverse partially completed steps. The
spock.remove_node procedure should be called on the node being removed.
Setting the Synchronisation Timeout
spock.add_node() waits at several points for the nodes to synchronise -
for a sync event to arrive on a peer, for the new node to catch up, and
for a subscription to start replicating. Each of those waits is allowed
180 seconds (3 minutes) by default, which is sized for a small cluster
where a node joins in seconds. On a large database, catchup can
legitimately take minutes or hours, and the procedure fails with a timeout
long before the work is done.
To raise the budget, set
spock.sync_timeout in the
same session, before calling the add_node procedure:
The new value applies to every synchronisation wait the procedure
performs, and it reverts when the session ends, so a long-running node
addition does not need a cluster-wide configuration change. To raise the
limit for every session, set the parameter in postgresql.conf instead.
The setting bounds a whole wait, not an individual probe of a remote node; steps that also bound each remote probe - so that one unresponsive peer cannot consume the entire budget - keep their own, much smaller limit for that purpose.
Manually Adding a Node to a Cluster
The steps that follow outline the process Zodan goes through
when adding a node. You can manually perform the same steps to add a node
to a cluster instead of using spock.add_node above.
Check the Spock Version Compatibility
Before starting the node addition, verify that all nodes (n1, n2, n3, and n4) are running the exact same version of Spock. This prevents compatibility issues during replication setup.
If any node has a different version, the process will abort with an error.
On the orchestrator node, check the Spock version with the following commands:
Validate Prerequisites
You should ensure that the new node is in good condition before adding the node to your replicating cluster.
Perform safety checks to ensure node n4 is a clean slate:
- The n4 node must have the database and Spock extension installed.
- The n4 node must have no user data or existing replication configuration.
- Verify that a node named n4 does not already exist in the cluster.
If any prerequisite fails, the process aborts to prevent conflicts.
Confirm that the Database Exists on n4
Try to connect to the database on n4. If this fails, the database does not exist and needs to be created first.
In the following example, the query checks whether the database exists on n4:
Confirm that n4 Has No User-Created Tables
The new node must be empty; there can be no user tables in user schemas (system tables and extension tables are acceptable). If user tables exist, ZODAN will abort because syncing would overwrite existing data.
In the following example, the query checks for user-created tables on n4:
Confirm that n4 Does Not Exist in the Cluster
Check if a node with the name n4 is already registered in the cluster. If the node exists, ZODAN aborts to prevent duplicate node names. The following example checks to see if n4 already exists in the cluster:
Confirm that n4 Contains No Subscriptions
In the following example, the query checks whether n4 has any existing subscriptions:
Confirm that n4 Contains No Replication Sets
In the following example, the query checks whether n4 has any replication sets:
Create a Replication Node on n4
After confirming the state of the new node, you can add the node to your cluster. In this step, you will create a Spock node object on n4:
- This registers n4 as a participant in the replication cluster.
- Think of this like giving n4 an ID badge that says “I’m part of this cluster now.”
After this step, n4 is visible in the spock.node table on all nodes.
Create a Node on n4
Using dblink, connect to n4 and run spock.node_create() to register
the node. The DSN tells other nodes how to connect to n4.
In the following example, the spock.node_create function registers n4 as
a cluster participant:
Confirm the Initial Node Count
In the following example, the query retrieves the current node count:
Create Disabled Subscriptions and Slots
This is the critical bookmarking stage. During this stage, the process completes the following steps:
- Create subscriptions from n2 to n4 and n3 to n4, but keep them disabled.
- Before creating each subscription, trigger a
sync_event()which returns an LSN (log sequence number). You can think of the LSN as a bookmark in the replication stream. - Save these bookmarks in a temporary table for later use.
- When enabling these subscriptions later, transactions will start from exactly the right position. This ensures no data is missed or duplicated.
- Subscriptions remain disabled because n4 should get all initial data from n1 (the source) in one clean sync.
The n2 to n4 and n3 to n4 subscriptions are just being prepared now, but will not start moving data until later.
Identify All Existing Nodes
Query the cluster to find all of the nodes (n1, n2, n3, n4) and their connection strings. In the following example, the query retrieves all nodes and their DSNs:
For n2 to n4: Trigger Sync Event on n2 and Store LSN
Call sync_event() on n2, which inserts a special marker into the n2
replication stream and returns the LSN where the marker was inserted.
Store this LSN (0/1A7D1E0) in a temp table. Later, when enabling the
sub_n2_n4 subscription, use this stored LSN to ensure the subscription
starts from exactly this point, guaranteeing no data loss.
In the following example, commands trigger a sync event and store the LSN:
Create a Replication Slot on n2
A replication slot is like a queue that holds all changes from n2 that need to be sent to n4. Even though the subscription is disabled, the slot starts collecting changes immediately. This ensures no data is lost between now and when the subscription is enabled.
In the following example, the commands create a replication slot on n2:
Create Disabled Subscription on n4 from n2
We create the subscription object on n4, but with enabled := false.
This tells n4 you will eventually subscribe to n2, but not yet. The
subscription knows about the slot on n2 but is not actively pulling data
yet.
Repeat the Previous Steps for n3 to n4
In the following example, the commands perform the same operations for n3 to n4:
Configure Cross-Node Replication
A logical slot retains WAL on the node where it is created. The following historical examples connect to n2 and n3. Those slots retain changes on n2 and n3. Before allowing writes on n4, verify the slots on n4 that will serve its subscribers. The examples below do not establish that protection on n4.
Now prepare for replication directing the data flow from n4 to the replica nodes (n2, n3):
- Create replication slots on n2 and n3 that will hold changes from n4.
- These slots will be used later when creating subscriptions for n2 and n3 to receive data from n4.
- Create these slots early so they start buffering any changes from n4 immediately, even before the subscriptions are created.
This prevents data loss if n4 receives writes during the setup process.
Create a Slot on n2 for a Future Subscription (sub_n4_n2)
Create a replication slot on n2 named spk_inventory_n2_sub_n4_n2. This
slot will queue up changes from n4 that need to be sent to n2. The slot is
ready, but there is no subscription using the slot yet; that comes later.
In the following example, the command creates a replication slot on n2:
Create a Slot on n3 for a Future Subscription (sub_n4_n3)
In the following example, the command creates a replication slot on n3:
Trigger a Sync on Other Nodes, Wait on Source
Before copying data from n1 to n4, ensure n1 has all the latest data from n2 and n3.
- Any writes that happened on n2 or n3 must be fully replicated to n1 first.
- For example, if a user inserted data on n2 one second ago, that data must be on n1 before copying n1’s data to n4, or n4 would be missing that recent insert.
- By triggering a sync event on n2 and waiting for the event on n1, you can confirm that n1 has received everything from n2 up to this exact moment.
Process: Trigger sync_event on n2 (inserts a marker into the n2
replication stream), wait on n1 for that marker to arrive, and repeat
for n3.
Sync n2 to n1
Call the sync_event() function on n2, which returns an LSN (0/1C9F400).
Then on n1, wait for that specific LSN to be replicated. When
wait_for_sync_event() completes, you are guaranteed that n1 has received
all changes from n2 up to and including that LSN.
In the following example, the commands trigger a sync event and wait for completion:
Sync n3 to n1
Perform the same process on n3. Trigger sync_event() on n3, get the LSN
(0/1D0E510), and then wait for that LSN on n1. After both syncs complete,
n1 is fully caught up with both n2 and n3.
In the following example, the commands trigger a sync event on n3 and wait for completion on n1:
Copy the Source to New Subscription
This is the big data copy step.
- Create an enabled subscription on n4 from n1 with
synchronize_structure=trueandsynchronize_data=true. - This causes Spock to dump the entire schema (tables, indexes, constraints, etc.) from n1, restore that schema on n4, and copy all table data from n1 to n4.
- Before creating the subscription, detect if n4 has any existing schemas
that should be omitted from the sync (like monitoring tools, management
schemas). Build a
skip_schemaarray with these schema names. When Spock syncs the structure, Spock excludes these schemas usingpg_dump --exclude-schema. When copying data, Spock also skips tables in these schemas. This prevents overwriting local tools or extensions on n4.
This can take minutes to hours depending on database size (a 100GB database might take 30+ minutes to sync).
Detect Existing Schemas on n4
Query the n4 information_schema to find all user-created schemas
(excluding system schemas like pg_catalog, information_schema,
spock, public). If schemas like mgmt_tools or monitoring are
found, they will be excluded from replication.
In the following example, the query detects existing schemas on n4:
Create an Enabled Subscription on n4 from n1
Create a subscription (sub_n1_n4) on n4, pointing to n1 as the provider.
The key parameters include:
synchronize_structure := true- Dump and restore schema from n1.synchronize_data := true- Copy all table data from n1.enabled := true- Start replicating immediately.skip_schema := ARRAY['mgmt_tools','monitoring']::text[]- Exclude detected schemas.forward_origins := ARRAY[]::text[]- Do not forward changes that originated elsewhere.
What Spock does internally:
- Run pg_dump on n1 with –exclude-schema=mgmt_tools –exclude-schema=monitoring
- Restore dump on n4
- For each table in replication sets on n1: Skip tables in mgmt_tools and monitoring schemas → Run COPY command to transfer data from n1 to n4
- Once initial sync completes, start streaming ongoing changes from n1 to n4
Trigger a Sync on the Source Node and Wait on the New Node
After the initial bulk data copy, there might be a small lag to recover changes that happened on n1 while the copy was in progress.
- This confirms that n4 has caught up completely with n1 before proceeding.
- Trigger a
sync_eventon n1 (marking the current position in the n1 stream); then, wait on n4 for that marker to arrive. When the marker arrives, n4 has received and applied everything from n1 up to this point.
For example: You start copying 100GB at 10:00 AM, but while copying, users insert 1000 rows on n1 between 10:00-10:30. The copy completes at 10:30, but those 1000 rows are still being streamed. You must wait until all 1000 rows have been applied on n4 so you do not lose data.
Trigger a Sync Event on n1
Insert a sync marker into the n1 replication stream at the current position. The LSN returned (0/1E1F620) represents this exact moment in the n1 transaction log.
In the following example, the command triggers a sync event on n1:
Wait for Sync Event on n4
On n4, wait for the sync marker that matches the returned LSN (0/1E1F620)
to arrive and be processed. This is a blocking call; the call will not
return until the n4 subscription from n1 has replicated up to this LSN.
The timeout (1200 seconds = 20 minutes) is a value chosen for this manual
example to give plenty of headroom; tune it to suit your environment. It
prevents waiting forever if something goes wrong. (The automated
spock.add_node() procedure uses a shorter 180-second internal timeout
for its sync waits, as noted in the prerequisites.)
In the following example, the command waits for the sync event on n4:
Check the Commit Timestamp and Advance Slots
This is a critical optimization step.
Earlier, n4 received a full copy of all data from n1, which includes data that originally came from n2 and n3. Those nodes now have disabled subscriptions waiting to activate (sub_n2_n4 and sub_n3_n4). The replication slots on n2 and n3 have been buffering changes.
If you enable those subscriptions now, n4 will receive duplicate data (n4 already has n2’s data via n1, then will get the data again directly from n2).
Solution: Use the lag_tracker to find the exact timestamp when n4 last
received data from n2 (even though the data came via n1). Then advance the
n2 replication slot to skip past all data up to that timestamp. When
enabling sub_n2_n4 later, the subscription only sends new changes that
happened after the sync, not old data that n4 already has.
Steps for each replica node: Check the n4 lag_tracker to get the
commit_timestamp for the last change from n2. On n2, convert that
timestamp to an LSN using get_lsn_from_commit_ts(). Then, advance
the n2 replication slot to that LSN. Repeat these steps for n3.
Get the Commit Timestamp for n2 to n4
Query the n4 lag_tracker table, which tracks replication progress to
find the row where origin_name='n2' and receiver_name='n4'. The
commit_timestamp tells us the last time n4 received a change that
originated from n2. Even though the change came through n1, lag_tracker
tracks the original source.
In the following example, the query retrieves the commit timestamp:
Advance the Slot on n2
This is a two-step process: Use spock.get_lsn_from_commit_ts() to
convert the timestamp (2025-01-15 10:30:45.123456) into an LSN that
corresponds to that point in the n2 transaction log. Then, use
pg_replication_slot_advance() to move the slot’s restart_lsn forward
to that position.
The slot spk_inventory_n2_sub_n2_n4 has been buffering all changes to
n2. By advancing the slot, you discard everything up to this LSN (n4
already has the data). Now the slot only contains new changes that n4
needs.
In the following example, the commands convert the timestamp and advance the slot:
Repeat for n3 to n4
In the following example, the commands perform the same operations for n3 to n4:
Enable Disabled Subscriptions
In this step, activate subscriptions from replica nodes to new node using stored sync LSNs.
Remember when you created disabled subscriptions and stored sync LSNs? Now we bring it all together. Enable those subscriptions (sub_n2_n4 and sub_n3_n4), and use the stored LSNs to verify they start from the correct position.
Why the stored LSNs matter: When you created sub_n2_n4 and triggered
sync_event on n2, you got LSN 0/1A7D1E0. That LSN marked the exact
moment you created the replication slot. Between then and now, hours may
have passed. The replication slot has been buffering changes, but you need
to ensure the subscription starts processing from that original bookmark
point, not skipping ahead.
The verification: After enabling each subscription, call
wait_for_sync_event() with the stored LSN. This confirms that the
subscription has processed up to at least that sync point before you
continue.
After the slot advancement: The slots were advanced to skip duplicate data. Now when you enable the subscriptions, they will only send new changes that happened after the initial sync, which is exactly what you want.
Enable sub_n2_n4 on n4
Next, call spock.sub_enable() on n4 to activate the subscription. The
subscription worker process starts, connects to n2, and begins pulling
changes from the replication slot.
The following example enables the subscription:
Wait for Stored Sync Event from n2
Then, retrieve the LSN we stored (0/1A7D1E0) and use the LSN in
the wait_for_sync_event() function. This is the key to the entire
ZODAN approach. We are verifying that the subscription has caught up to
the sync point we marked when we first set things up. This guarantees
data consistency.
In the following example, the query retrieves the stored LSN and waits for the sync event:
Verify the Subscription is Replicating
Check the subscription status using the sub_show_status() function. We
want to see status='replicating', which means the subscription worker
is active, connected to n2, and successfully applying changes. Any other
status (down, initializing) would indicate a problem.
The following example checks the subscription status on n4:
Repeat the Steps for sub_n3_n4
In the following example, commands enable the subscription and verify replication:
Create Subscriptions from Other Nodes to New Node
This step enables bidirectional replication from n4 to all other nodes.
Up to this point, data has been flowing TO n4 from other nodes. Now we set up the reverse paths. Data will flow FROM n4 TO other nodes. We create subscriptions on n1, n2, and n3 that subscribe FROM n4.
We waited until n4 was fully populated with data before allowing other nodes to subscribe to it. If we had created these subscriptions earlier, the other nodes would try to sync from an empty n4, which would cause problems.
These subscriptions have synchronize_structure=false and
synchronize_data=false because n1, n2, and n3 already have all the
data. We only want them to receive NEW changes that happen ON n4 from
now on, not copy existing data.
After this, the cluster is fully bidirectional:
- n1 sends to n4, n4 sends to n1
- n2 sends to n4, n4 sends to n2
- n3 sends to n4, n4 sends to n3
Create sub_n4_n1 on n1
Create a subscription ON n1 that points TO n4 as the provider. This is commonly misunderstood; the subscription is created on the RECEIVER node (n1), not the sender (n4). After this, any INSERT/UPDATE/DELETE that happens directly on n4 will replicate to n1.
The following example creates the subscription:
Create sub_n4_n2 on n2
This is the same concept. We create a subscription on n2 that pulls from n4. Now n2 will receive changes that happen on n4.
In the following example, the command creates the subscription on n2:
Create sub_n4_n3 on n3
The following command creates the subscription on n3:
Monitor Replication Lag
Next, we will verify that n4 is keeping up with n1.
We monitor the lag_tracker table on n4 to ensure replication from n1 is keeping up. The lag_tracker shows the time difference between when a transaction was committed on n1 and when the transaction was applied on n4.
If lag is growing (for example, 5 seconds, then 10 seconds, then 30 seconds), n4 cannot keep up with the write load from n1. This could indicate the following issues:
- Network bandwidth issues.
- n4 hardware is slower than n1.
- Long-running transactions blocking replication.
We want lag under 59 seconds, or lag_bytes=0 (meaning n4 has processed everything). If lag stays consistently low, n4 is successfully integrated.
The following example monitors replication lag:
Show All Nodes
Next, we will verify that all of the nodes are registered; the following query displays all registered nodes:
Show the Status of all Subscriptions
Next, we want to verify that all subscriptions are replicating. In the following example, the query displays subscription status across all nodes:
Verification
Next, we perform a series of tests to verify that the cluster is replicating between n1 and n4.
First, we create a test table and insert data:
Test Replication between n4 and n1
Next, we insert data on n4:
Then, verify replication on n1:
Our Final Cluster Topology
All nodes are now bidirectionally replicating:
- n1, n2, n3, and n4 are all bidirectionally connected.
- Total subscriptions: 12 (each node subscribes to 3 others).
Troubleshooting
The following sections share commands that can help diagnose issues you encounter while adding a node:
Subscription Status Stuck in ‘initializing’ or ‘down’
The following commands can help you identify places where a node is encountering issues with replication status:
Node Addition Fails with a Timeout
If spock.add_node() raises a timeout while waiting for a sync event or
for the new node to catch up, the node is likely larger than the default
3-minute budget allows for. Remove the partially added node with
spock.remove_node, then retry with a longer budget, as described in
Setting the Synchronisation
Timeout:
Use the lag query below to gauge how long catchup actually takes before choosing a value.
Replication Lag Too High
Use the following command to check replication lag on a subscribing node:
Slot Not Advancing
Use the following command to check the status of a replication slot:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7.1.2 - Tutorial: Updating the Postgres Version with a Rolling Update
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Zodan’s add_node and remove_node procedures move data between nodes
regardless of which PostgreSQL major version each node runs. Because
of this, the same node-replacement strategy used to roll a Spock
version forward also upgrades PostgreSQL itself. During the upgrade,
you:
- build a replacement node on the target PostgreSQL major version.
- add it to the cluster.
- confirm it is replicating.
- remove the node it replaces.
Since the replacement node is fully live and replicating before the node it replaces is removed, the cluster never drops below its optimal node count and the application sees no interruption - a true zero-downtime rolling upgrade of the PostgreSQL version. When a node also carries a physical standby for high availability, bootstrapping that standby and bringing it under Patroni folds into the same per-node loop, so high availability is preserved, before you move on to the next node.
In this tutorial, a three-node cluster running PostgreSQL 16 (n1,
n2, n3) rolls forward to PostgreSQL 18, becoming n1b, n2b, and
n3b in turn. If you are also moving to a newer Spock version in the
same rollout, the two upgrades combine in a single pass of
add/verify/remove per node.
Important Prerequisites and Warnings
- Each replacement node should not be accessible to users while it is being added.
- Disable automatic DDL replication on every node
(
spock.enable_ddl_replication = off), and do not run DDL on the cluster for the duration of the rollout. - The users must be identical on the source and the replacement node. Create any users on the replacement node before proceeding; permissions must be identical for all users on both the source and the replacement node.
- Zodan validates that all users from the source node exist on the replacement node before proceeding. This prevents replication failures caused by missing user permissions.
- All nodes in the cluster must be available to Spock for the duration of each add/remove step.
- Run each
add_nodeandremove_nodecall from the node being added or removed. - The
dblinkextension must be installed on the node from whichadd_nodeorremove_nodeis called. - On a node whose PostgreSQL build has the
output_plugin_librariesparameter (the patch versions in Checking PostgreSQL Version Compatibility Before Each Step and later), it must listspock_output, or logical decoding with Spock fails. On an older build the parameter does not exist and must not be set. - If a step fails partway, do not immediately retry. Confirm every artifact the workflow created has been removed first, as described in Troubleshooting below.
add_nodeallows 180 seconds for each wait for a sync event between nodes. If replication lag exceeds this window, the call raises an exception. Confirm network latency and replication lag are within acceptable limits before starting, or raise the budget for the session withspock.sync_timeout.- Do not remove an old node until its replacement reports
replicatingstatus. - Keep at least two nodes running at all times; never remove the second-to-last old node and the first new node in the same window.
- A rolling PostgreSQL update can only move a cluster forward. Unlike a Spock version mismatch, Zodan does not check PostgreSQL version ordering itself - see Checking PostgreSQL Version Compatibility Before Each Step.
The examples run every instance on one host and use 127.0.0.1.
When a node and its standby, or the nodes of the cluster, run on
separate hosts, use addresses each host can reach in connection
strings, listen and connect_address, and the etcd URLs, and
point every Patroni member of a scope at the same DCS. Replace the
<...> password placeholders with your own unique secrets.
Checking PostgreSQL Version Compatibility Before Each Step
Zodan’s check_spock_version_compatibility procedure (invoked
automatically by add_node) checks only the Spock extension version;
it does not check the PostgreSQL server version. Before adding
a replacement node, you can confirm its PostgreSQL patch version
number yourself against the source node:
The replacement node’s server_version_num must be the same as or
greater than the source node’s. The following table describes the
first patch version of each PostgreSQL major version that has the
output_plugin_libraries parameter. On those versions and later it
must list spock_output; on earlier ones leave it unset:
| PostgreSQL major version | Minimum patch version |
|---|---|
| 15 | 15.19 |
| 16 | 16.15 |
| 17 | 17.11 |
| 18 | 18.6 |
Preparing a Replacement Node
Each replacement node needs its own host (or port, on a single host),
data directory, and a PostgreSQL and Spock build at the target
version, prepared before you call add_node. Add the pgEdge
repository to the replacement node’s host and install pgEdge
Enterprise Postgres and Spock for the target version, as described in
Installing pgEdge Enterprise
Postgres.
For PostgreSQL 18 on RHEL, Rocky Linux, or AlmaLinux:
On Ubuntu or Debian:
In our example, the replacement node runs on its own port on the same
host as the node it replaces; n1b runs on port 5442. Initialize
its data directory on the target PostgreSQL version:
Before starting the replacement node for the first time, edit the
postgresql.conf file:
- set the settings Spock requires, as in Configuring Spock, using the source node’s values.
- size replication origin tracking for the target version.
shared_preload_libraries only takes effect when the server
starts, so set it now rather than after CREATE EXTENSION spock
has already run.
PostgreSQL 15 through 17 track replication origins with the
max_replication_slots parameter; PostgreSQL 18 and later uses the
max_active_replication_origins parameter. Set the parameter to the
number of subscriptions required:
Copy any spock.* settings the existing nodes use, such as the
conflict resolution settings, so the replacement behaves the same.
Without wal_level = logical, add_node cannot create the slots it
needs on the replacement, and it does not stop: it reports the failure
only as a notice, and only when called with verb := true.
Start Postgres on the replacement node’s port, then connect with
psql to confirm the settings took effect:
Create the database and user, matching the source node exactly:
Install the Spock extension built against the target PostgreSQL version:
If the node it replaces runs behind a physical standby for high
availability, and the replacement node’s target version is PostgreSQL
18 or later, also configure the server’s native
sync_replication_slots mechanism before adding it to the cluster -
Spock’s own failover worker does not run on PostgreSQL 18+. Both
approaches below need a replication role, a known superuser password,
and a pg_hba.conf entry permitting both to connect; set these up
once, on the replacement node, before choosing a path:
Add entries to /path/to/data/n1b/pg_hba.conf permitting the standby
host to open a replication connection and, if you choose the Patroni
path below, a superuser connection for Patroni’s own health checks:
Choose one of the following approaches:
Manage the standby pair through Patroni, as described in step 3 of Rolling the Update Across the Cluster below.
Configure the native path by hand:
Create a physical replication slot on the replacement node, for its future standby to stream through:
Take a base backup of the replacement node into the standby’s data directory, streaming through that slot:
standby.signalis what makes the server start as a standby;pg_basebackup -Rwould also write it, but it would put aprimary_conninfowithoutdbnameintopostgresql.auto.conf, which overrides the one set in the next steps, and slot sync needsdbname.Set
synchronized_standby_slotsin the replacement node’spostgresql.conf, naming that slot:On the standby itself, point it at the replacement node and enable native slot sync in its
postgresql.conf:After starting the standby, confirm the slot synchronized:
See Logical Slot Failover (HA Standby) for the full reference, including the PostgreSQL 15/16 path and upgrading existing slots.
Rolling the Update Across the Cluster
Repeat the following four steps once per node, moving from n1 to
n3 in our example. Finish all steps for one node before starting the
next.
Connect to the prepared replacement node and load the Zodan workflow:
NoteBoth
zodan.sqlandzodremove.sqlare located in the samples/Z0DAN directory of the Spock GitHub repository.Then add the replacement node, sourcing it from whichever node in the cluster is reachable and already caught up - the node you are replacing is the simplest choice for the first replacement:
Confirm the replacement node is fully caught up and replicating in both directions before touching the node it replaces:
Every subscription involving
n1bshould reportreplicating, including the subscriptions to and fromn2andn3thatadd_nodecreated automatically.If the node being retired runs behind a physical standby for high availability, build a matching standby for
n1band bring the pair under Patroni, then cut over to it. Skip this step if the cluster does not use physical standbys.Patroni and a DCS (Distributed Configuration Store) must be installed and reachable from
n1band its future standby host before either node can run under Patroni. This tutorial usesetcdas the DCS, the most common choice for Patroni. Install Patroni on both hosts:This installs Patroni’s etcd client library, not the etcd server itself. If no etcd cluster already serves the rest of your Spock cluster’s Patroni pairs, install and start one. Package name and installation method vary by platform; see the etcd releases page if your package manager does not provide one. A production etcd deployment needs an odd number of members (3 or 5) for quorum; the following configures a single-member etcd suitable for this tutorial:
Confirm
n1band its standby host can reach the DCS before continuing:Bring
n1bunder Patroni as the leader of a new Patroni cluster, rather than letting Patroni bootstrap it from scratch -n1bis already initialized and already running with the dataadd_nodepopulated. Patroni only runs its bootstrap process against an emptydata_dir, so pointing it atn1b’s existing, populated directory makes Patroni adopt the running instance as the cluster’s first member instead:sync_replication_slotsandhot_standby_feedbackare the two settings the native slot sync path needs on a standby; set them on bothn1bandn1b_standbyrather than only on whichever is the standby today, since either one can end up in that role after a promotion.synchronized_standby_slotsis deliberately left out ofpostgresql.parametershere - it is set directly on whichever node is primary, by theon_role_changecallback below, and declaring it as a static Patroni-managed parameter would fight that callback: Patroni reconciles managed parameters back to the value in its own configuration, which would undo the callback’s update after every promotion.Start Patroni against the running instance:
Then point a second Patroni instance at the same
scopeand DCS endpoint, under the member namen1b_standby, with an emptydata_dir. Patroni finds the existing cluster in the DCS and, on first start, runspg_basebackupitself againstn1bto populate that empty directory - connecting as thereplicatorrole over the replication connection permitted by thepg_hba.confentry added above, using the credentials in theauthentication.replicationblock below. No manualpg_basebackupstep is needed on this path; Patroni’s bootstrap process runs it for you:Confirm
n1b_standbyjoined and is streaming before moving on:Also confirm, on
n1b, that the slot backing the standby has synced before relying on it for failover:synchronized_standby_slotsnames a Patroni-managed physical slot, and Patroni’s auto-created slots are named after the member, not the role - the slot namedn1b_standbyonly exists whilen1b_standbyis not the primary. Theon_role_changecallback named in both Patroni configurations above resets the setting on a future promotion to whichever member is then the standby. Patroni reads its local configuration only at start and on reload, so if you add the callback to a member that is already running, reload it afterwards:The following script, deployed on
n1bwithSIBLING_MEMBERset ton1b_standbyandLOCAL_PORTset to5442(and onn1b_standbywith them set ton1band5452), setssynchronized_standby_slotsto the other member’s name whenever this node becomes the primary:The callback only fires on a future promotion, so set the initial value by hand now, on
n1bwhile it is still the leader:With
n1b_standbystreaming and the callback in place on both nodes, cut over: repoint anything that depended on the old node’s standby - a VIP, a DNS record, or a connection string used for read traffic or disaster recovery - at the new Patroni cluster. Leave the old node’s standby running until the cutover is confirmed; step 4 removes the old primary, and its standby can be stopped once the rest of the cluster is healthy.A later promotion of
n1b_standbyis a separate event from this cutover, and needs its own plan: Spock’s subscriptions onn2andn3connect ton1busing the rawhost=127.0.0.1 port=5442address from theadd_nodecall above, and Patroni does not repoint that address for them. Ifn1bis reachable only through a VIP or DNS record that Patroni (orkeepalivedalongside it) moves to whichever member is primary, pointnew_node_dsnat that stable address instead of a node’s raw host and port when you calladd_node, and no further Spock-level action is needed after a promotion. Without such an abstraction in front of the pair, repoint each subscription by hand after a promotion, from any node whose subscription still points at the old address:node_add_interfacewrites only to the local node catalog; it is not replicated. Run it on every node whose subscription you will repoint, heren2andn3, sincesub_alter_interfacelooks the interface up locally:Then run
sub_alter_interfaceon each of those nodes:spock.gen_sub_name(provider_node, subscriber_node)names each subscription, sosub_n1b_n2is the subscription onn2whose provider isn1b; confirm the exact names for your cluster withSELECT sub_name FROM spock.subscription;on each node before repointing them.Move application traffic from
n1ton1b, and confirm no new connections are arriving atn1.remove_nodedrops every subscription to and fromn1at once and does not wait for anything, so any write onn1that has not reached the other nodes by then is lost. Whenn1takes no writes, emit a sync event on it:Wait for it on every other node, passing the LSN it returned. The
resultcolumn must come backt:Then load the removal workflow on the node being retired, and remove it from the cluster:
remove_nodedoes not delete the retired node’s database, data directory, or logs; stop the instance and reclaim its resources once you confirm the rest of the cluster is healthy.
With n1 replaced by n1b, repeat steps 1 through 4 for n2 and
n3, sourcing each new node from any node already in the cluster -
old or new - that runs a PostgreSQL version no newer than the
replacement node itself.
Re-enabling DDL Replication
Once every node is replaced, turn automatic DDL replication back on, on every node, as in Upgrading Spock:
Verifying the Rollout
After replacing all nodes, confirm the whole cluster runs the target PostgreSQL version and reports a clean replication topology:
Run the dblink query once per node, changing the port.
show_all_nodes lists the nodes; show_all_subscription_status
reports each subscription’s status.
The following table describes what to check in the output before considering the rollout complete:
| Field | What to confirm |
|---|---|
| PostgreSQL version | Every node reports the target version. |
| Node name | Only n1b, n2b, and n3b remain; no old node is listed. |
| Subscription status | Every subscription between every pair of nodes reports replicating. |
Troubleshooting
add_nodefails withcannot synchronize structure from provider running PostgreSQL, or the replacement node’s apply worker exits withcannot synchronize structure from upstream server version. The replacement node’spg_dumpcannot dump from a PostgreSQL version newer than itself. The node named as the source runs a newer PostgreSQL major version than the replacement node. Rebuild the replacement node on an equal or newer PostgreSQL major version, or source it from a different node that is not newer than the replacement, and retry.Logical decoding fails with
library "spock_output" may not be used as an output plugin. The node’s build has theoutput_plugin_librariesparameter and it does not listspock_output. Add it topostgresql.confand runSELECT pg_reload_conf();; no restart is needed. Do not set the parameter on a build that does not have it: an unrecognized parameter stops the server from starting.add_nodereports that it could not create a replication slot. Checkwal_level = logicalandmax_replication_slotson the replacement node.add_nodereports a failed slot creation only as a notice, only withverb := true, and carries on; the subscriptions it then creates do not replicate.add_nodetimes out waiting for a sync event on a large database. Raise the wait budget for the session withspock.sync_timeoutbefore callingadd_nodeagain.A step fails partway through
add_node. Do not retry immediately. Sourcezodremove.sqland callspock.remove_node()on the partially added node first, to clear any subscriptions and slots it created, then retry the add.
For more information, review the following resources:
- Modifying a Cluster with Zodan
- Using Zodan Scripts and Workflows
- Tutorial: Adding a Node to a Cluster with Zero Downtime
- Logical Slot Failover (HA Standby)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7.1.3 - Zodan: Zero-Downtime Node Addition for Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Zodan provides tools to add or remove a node with zero downtime. The scripts are located in the samples/Z0DAN directory of the Spock GitHub repository.
Zodan’s workflows and scripts streamline the process of adding a node to or removing a node from a Spock cluster. Zodan features the following scripts and workflows:
- The zodan.sql workflow is a complete
SQL-based workflow that uses
dblinkto perform the same add node operations from within Postgres. - The zodremove.sql workflow is a complete
SQL-based workflow that uses
dblinkto perform the same removal operations from within Postgres.
Components
The following scripts and workflows are available via Zodan.
Using the zodan.sql SQL Workflow
The SQL-based implementation utilizes the Postgres dblink extension to
handle node addition directly from within the database. This method is
ideal for environments where you may not have access to a shell or Python.
Within the workflow, SQL commands orchestrate the following operations:
add_node- The main procedure to orchestrate the full workflow.create_node- Register the new node viaspock.node_create.get_spock_nodes- Fetch current node metadata from a remote node.create_subandenable_sub- Manage subscription creation and activation.create_replication_slot- Create and configure logical replication slots.sync_eventandwait_for_sync_event- Coordinate data synchronization events.get_commit_timestampandadvance_replication_slot- Align replication states.
To use the workflow, execute the following command in your Postgres
session. In the following example, the spock.add_node procedure adds a
new node to the cluster:
In the following example, the command adds node n4 to the cluster:
The zodremove.sql Workflow
The SQL-based implementation utilizes the Postgres dblink extension to
handle node removal directly from within the database. This method is
ideal for environments where you may not have access to a shell or Python.
Within the workflow, SQL commands orchestrate the following operations:
spock.remove_node- Main procedure to orchestrate the full workflow.spock.remove_node_subscriptions- Manages removing subscriptions. Also removes the replication slot if there are no remaining subscriptions.spock.remove_node_replication_sets- Removes published repsets on the node being removed.spock.remove_node_from_cluster_registry- Removes the node from the cluster.
The workflow is located in the samples/Z0DAN directory of the Spock GitHub repository.
To use the workflow, call a command from your Postgres session. In the
following example, the Z0DAN spock.remove_node procedure removes a node
from the cluster. Note that spock.remove_node is a Z0DAN utility
procedure provided by zodremove.sql; it is not a built-in function of
the Spock extension.
In the following example, the command removes node n4 from the cluster:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7.2 - Adding a Node with pgBackRest
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
You can use a pgBackRest backup to populate a new cluster node, and then
add that node to your cluster with the Spock extension. In the following
high-level walkthrough, we walk through the steps you can use to add a
fourth node (n4) to a three-node cluster (n1, n2, and n3).
Create a pgBackRest stanza. This step is required as the stanza defines the cluster configuration, which is essential for backup and restore operations.
Perform a full backup of your primary node,
n1. The backup can be stored in an S3 bucket, a network-shared folder, or a local directory (if all nodes are on the same machine).Restore the backup from
n1to the data directory ofn4. This preparesn4to become a replica ofn1.Configure streaming replication on
n4, making the node a replica ofn1. This ensures thatn4contains all transactions onn1since the backup was taken, ensuringn4is 100 percent synchronized withn1.Use the
ALTERcommand to set nodesn1,n2, andn3to read-only mode and reload the configuration on these nodes to apply the changes. This step is crucial becausen4has configurations copied fromn1that are not valid forn4. By making the nodes read-only, you ensure no transactions occur while you modify the configurations.Terminate all ongoing transactions on
n1,n2, andn3. This prevents any long-running queries from interfering during the configuration changes.Edit the
shared_preload_librariesparameter onn4, removingspock. This prevents Spock from using the old configuration fromn1onn4.Start
n4, allowing the node to become a replica ofn1. This step ensures thatn4contains all transactions fromn1.Promote
n4to the role of primary node or configure the node as a standalone node with Spock disabled. This step finalizesn4as the new primary node in your replication setup.Remove all replication sets and nodes from the configuration. This clears any old replication configurations that are no longer needed.
Re-add
spockto theshared_preload_librariesparameter onn4. This preparesn4to handle replication in the new role.Restart
n4to apply the changes made in the previous steps.Reintegrate
n4into the replication cluster withn1,n2, andn3.Remove the read-only mode from
n1,n2, andn3, allowing them to resume normal operations.Add the following subscriptions between the new node (
n4) and Nodes 1, 2, and 3 (n1,n2,n3):- The
subn1n4subscription syncs n1 with n4. - The
subn2n4subscription syncs n2 with n4. - The
subn3n4subscription syncs n3 with n4. - The
subn4n1subscription syncs n4 with n1. - The
subn4n2subscription syncs n4 with n2. - The
subn4n3subscription syncs n4 with n3.
- The
Verify that all nodes (
n1,n2,n3, andn4) are properly configured and synchronized within the cluster. Ensure that replication is functioning as expected by checking the status of all nodes.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.7.3 - Tutorial: Upgrading the Postgres Version In Place with pg_upgrade
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
If your database is too large for your system’s free storage to hold
a second full copy, you can upgrade the node’s existing data directory
in place with pg_upgrade.
pg_upgrade migrates a node’s existing data directory to a new
PostgreSQL major version in place. Run with --link, it hard-links
the new cluster’s files to the old cluster’s rather than copying them.
This avoids doubling storage: the new data directory shares disk
blocks with the old one instead of duplicating them.
The trade-off is downtime for that one node. Unlike the rolling
replacement strategy, there is no freshly built node standing by to
take over its traffic while it upgrades - the node goes down, runs
pg_upgrade, and comes back up on the new version before it rejoins
the cluster. The upgrade is zero-downtime for the application only
because the other nodes in the cluster keep serving traffic during
that window; it is not zero-downtime for the node itself.
This tutorial upgrades a three-node cluster (n1, n2, n3) running
PostgreSQL 16 to PostgreSQL 18, one node at a time, without a second full copy
of any node’s data. pg_upgrade still needs a new, empty data directory for
each node, but in link mode it holds hard links to the old files rather than
copies of them. When a node also carries a physical standby for high
availability, rebuilding that standby and bringing it under Patroni folds into
the same per-node loop, so high availability is preserved before you move on to
the next node.
Prerequisites and Warnings
Important Prerequisites and Warnings
- The cluster needs at least three nodes. With one node down for its upgrade, at least two others must remain available to serve the application.
- Your load balancer, connection pooler, or application must be able to stop routing traffic to a node before it goes down for upgrade, and resume routing to it afterward. There is no replacement node to absorb that traffic automatically.
- Disable automatic DDL replication on every node
(
spock.enable_ddl_replication = off), and do not run DDL on the cluster for the duration of the rollout. pg_upgrade --linkrequires the old and new data directories to be on the same filesystem, so that hard links are possible. On a filesystem without hard links, or with the directories on separate volumes,pg_upgradestops withcould not create hard link between old and new data directories; it does not fall back to copying.--linkmode ties the old and new clusters’ data files together. After you start the new cluster, you cannot go back to running the old one; treat the oldpostgresql.conf,pg_hba.conf, and any other node-specific configuration as reference material to port forward, not something you can revert to.pg_upgradedoes not carry Spock’s replication origins over, on any PostgreSQL version. This procedure records them before the upgrade and restores them afterwards (steps 2 and 19), and drops and recreates the other nodes’ subscriptions to the node without copying data (steps 3 and 20).- While a node is down, the other nodes keep WAL for their
subscriptions to it. If
max_slot_wal_keep_sizeis set, make sure it allows for the whole upgrade window, or those slots can be invalidated and the node will need a full rebuild. spock.show_all_subscription_status()andspock.show_all_nodes()are Zodan procedures. Loadzodan.sqlfrom the Spock distribution, which needs thedblinkextension, on the node you run them from.- Run
pg_upgrade --checkagainst the node before running the real upgrade, and resolve everything it reports. - A node’s physical standby cannot continue streaming once the node’s major version changes; the standby must be rebuilt from the upgraded node, not upgraded in place alongside it.
The examples run every instance on one host and use 127.0.0.1.
When a node and its standby, or the nodes of the cluster, run on
separate hosts, use addresses each host can reach in connection
strings, listen and connect_address, and the etcd URLs, and
point every Patroni member of a scope at the same DCS. Replace the
<...> password placeholders with your own unique secrets.
Upgrading the Cluster with pg_upgrade
Repeat the following steps once per node, moving from n1 to n3 in
our example. Finish all steps for one node before starting the next.
Drain traffic from the node being upgraded at the load balancer, pooler, or application layer, and confirm no new connections are arriving at it.
Make sure every other node has applied everything
n1committed, and record what the upgrade will lose. With traffic drained, emit a sync event onn1:Wait for it on every other node, passing the LSN it returned. The
resultcolumn must come backt:Then confirm on
n1that every slot has confirmed past that LSN; this query must return no rows:A physical slot, such as the one a standby streams through, always has a
NULLconfirmed_flush_lsn, which is why the query is limited to logical slots.pg_upgradedoes not carry Spock’s replication origins over, so record where each ofn1’s subscriptions has applied up to. Every row must show an LSN; aNULLmeans a subscription with no origin, which you must resolve before upgrading:Also record, on every other node, the definition of its subscription to
n1, so you can recreate it unchanged in step 20:spock.gen_sub_name(provider_node, subscriber_node)names each subscription, sosub_n1_n2is the subscription onn2whose provider isn1. Confirm the names for your cluster withSELECT sub_name FROM spock.subscription;on each node.Disable
n1’s own subscriptions, so it stops applying, and wait untilSELECT * FROM spock.sub_show_status();onn1no longer shows any asreplicating:While
n1is still running, drop every other node’s subscription to it.sub_dropremoves the subscription’s slot onn1only when it can reachn1; a subscription dropped later leaves its slot behind onn1. No data is lost, because step 2 confirmed that every node had applied all ofn1’s changes:If this node already runs under Patroni, pause it so that manually stopping PostgreSQL below does not trigger an automatic restart - Patroni’s own documentation names major-version upgrades as the intended use case for this mode.
--waitreturns only once every member has seen the pause, so the stop below cannot race it:Record the Spock version the node runs; step 4 needs it, and the server cannot answer once it is down:
Then stop PostgreSQL on the node:
Install the target PostgreSQL version and Spock on the host, alongside the existing installation; see Installing pgEdge Enterprise Postgres. For PostgreSQL 18 on RHEL, Rocky Linux, or AlmaLinux:
On Ubuntu or Debian:
pg_upgraderecreates the Spock extension in the new cluster at the version you recorded in step 3, and the new server loads the Spock library installed for the target PostgreSQL version. Install that same Spock version for the target version. If the only package for the target version carries a newer Spock, runALTER EXTENSION spock UPDATE;in every database where Spock is installed once the node is up in step 8, before step 19. The other nodes keep their version until their own turn, so the cluster runs mixed Spock versions while the rollout is in progress, as it does in the node-by-node procedure in Upgrading Spock. Finish the rollout on every node before adding a node with Zodan:add_noderequires the new node’s Spock version to be the same as or newer than every existing node’s.Initialize a new data directory on the target PostgreSQL version.
pg_upgrademigrates data into an already-initialized cluster; it does not create one. On a PostgreSQL 16 or later target,pg_upgradecopies the old cluster’s encoding and locale settings into the new cluster itself, soinitdbneeds no encoding or locale option. The data checksum setting is not copied and must match the old cluster, orpg_upgradestops. Read it from the stopped data directory:If the checksum version is
1, enable checksums:If it is
0, disable them explicitly. PostgreSQL 18initdbenables checksums by default, so leaving the option out does not match a cluster without them:pg_upgradedoes not carry configuration files forward; the new data directory has only the defaultsinitdbwrote. Configure it now, before step 6:pg_upgrade --checkreadswal_level,max_replication_slotsandoutput_plugin_librariesfrom the new cluster, and fails if they cannot hold the old cluster’s logical slots when the old cluster is PostgreSQL 17 or later. Copypg_hba.confas-is, since authentication rules do not change with the PostgreSQL version:Then add the Spock settings to the new data directory’s
postgresql.conf, using the old node’s values where they are larger.max_replication_slotsmust be at least the number of logical slots on the old node:output_plugin_librariesexists only from the patch versions in the table below. Set it only if the new binaries have it: on an older patch version the server does not recognize the parameter and will not start. Check withSELECT current_setting('output_plugin_libraries', true);, which returns NULL when the parameter does not exist. The following table describes the first patch version of each major version that has it:PostgreSQL major version Minimum patch version 15 15.19 16 16.15 17 17.11 18 18.6 Run
pg_upgrade --checkfirst, against the target version’s binaries, to confirm there are no blocking issues:Pass
--linkto the check too, so it also confirms hard links work between the two directories.Then run the upgrade itself, adding
--linkto hard-link the data files instead of copying them:Port any other settings the node needs from the old
postgresql.conf(memory, logging, connection limits and similar) to the new one before you start it. Do the same for the oldpostgresql.auto.conf, which holds everything set withALTER SYSTEM, and for any file the old configuration pulls in withinclude;pg_upgradecarries none of them over. Review each setting against the target version’s documentation rather than copying the files whole, since parameters are renamed or removed between major versions.Start PostgreSQL on the new version:
If this node runs behind a physical standby for high availability, stop it now - physical replication cannot continue once the primary’s major version changes. Skip steps 9 through 18 if the node does not use a physical standby.
Install the target PostgreSQL version on the standby’s host, alongside its existing installation, the same way you did for the primary in step 4.
Updating Patroni to use the Upgraded Instance
If this standby pair already runs under Patroni, you can reuse this node’s own existing Patroni cluster and the DCS (Distributed Configuration Store) behind it, rather than standing up either from scratch.
Optional: if this is the first time this node and its standby are being brought under Patroni, install Patroni and a DCS on both hosts first. This tutorial uses
etcdas the DCS, the most common choice for Patroni:This installs Patroni’s etcd client library, not the etcd server itself. If no etcd cluster already serves the rest of your Spock cluster’s Patroni pairs, install and start one. Package name and installation method vary by platform; see the etcd releases page if your package manager does not provide one. A production etcd deployment needs an odd number of members (3 or 5) for quorum; the following configures a single-member etcd suitable for this tutorial:
Confirm both hosts can reach the DCS before continuing, whether it is freshly started or already serving this pair:
Point this node’s Patroni configuration at the upgraded instance. If this is the first time the node is being brought under Patroni, write a new config for it as the leader of a new Patroni cluster, rather than letting Patroni bootstrap it from scratch - the data directory is already initialized and already running the data
pg_upgradeproduced, and Patroni only runs its bootstrap process against an emptydata_dir; pointing it at the existing, populated directory makes Patroni adopt the running instance as the cluster’s first member instead. If the node was already under Patroni before this upgrade, update its existing config’sdata_dirandbin_dirto the values below instead of writing a new file.pg_upgradepreserves roles and their passwords, and step 5 above already copiedpg_hba.confforward, so areplicatorrole and itspg_hba.confentry from an existing standby still work unchanged.Optional: set a password on the
postgressuperuser only if one is not already set:If the node was already under Patroni, its DCS still records the old cluster’s system identifier, and
pg_upgradegave the upgraded cluster a new one. Patroni refuses to manage a data directory whose system identifier does not match, so the old cluster state has to go before Patroni can adopt the upgraded instance. Stop the Patroni process on bothn1andn1_standby, then remove the scope’s state from the DCS.patronictl removeasks you to type the cluster name and confirm:This deletes only the DCS keys for
n1-cluster, not any data directory. It also deletes the scope’s dynamic configuration, which ends the pause from step 3 and drops any settings you applied withpatronictl edit-config; record those first withpatronictl -c /path/to/n1_patroni.yml show-config n1-clusterand apply them again once Patroni is running.Whether the node was already under Patroni or is being brought under it for the first time, start Patroni on
n1with the configuration from step 12. With no cluster state in the DCS and PostgreSQL already running on a populateddata_dir, Patroni adopts the running instance as the leader rather than bootstrapping a new one:Then bring up
n1_standbyas a new member: its old data directory holds the old, now-incompatible major version and cannot be reused. Run Patroni on the standby’s own host, pointed at the samescopeand DCS, under the member namen1_standby, with an emptydata_dir. Patroni finds the cluster in the DCS and, on first start, runspg_basebackupitself againstn1to populate that empty directory. Ifn1_standbywas already under Patroni, edit its existing config to the values below:Confirm
n1_standbyjoined and is streaming before moving on:Also confirm, on
n1, that the slot backing the standby has synced:synchronized_standby_slotsnames a Patroni-managed physical slot, and Patroni auto-creates one such slot per standby member - on whichever node is currently primary - named after that standby member rather than after its role. Today that slot is namedn1_standbyand exists onn1; ifn1_standbyis ever promoted, that slot disappears and a new one namedn1appears onn1_standbyinstead, representingn1as the new standby. Theon_role_changecallback named in both Patroni configurations above resets the setting on a future promotion to whichever member is then the standby. Patroni reads its local configuration only at start and on reload, so if you add the callback to a member that is already running, reload it afterwards:The following script, deployed on
n1withSIBLING_MEMBERset ton1_standbyandLOCAL_PORTset to5432(and onn1_standbywith them set ton1and5442), setssynchronized_standby_slotsto the other member’s name whenever this node becomes the primary:The callback only fires on a future promotion, so set the initial value by hand now, on
n1while it is still the leader:A later promotion of
n1_standbyis a separate event from this setup, and needs its own plan: Spock’s subscriptions onn2andn3connect ton1using whichever address was configured when those subscriptions were created, and Patroni does not repoint that address for them. Ifn1is reachable only through a VIP or DNS record that Patroni (orkeepalivedalongside it) moves to whichever member is primary, no further Spock-level action is needed after a promotion. Without such an abstraction in front of the pair, repoint each subscription by hand after a promotion, from any node whose subscription still points at the old address.node_add_interfacewrites only to the local node catalog; it is not replicated. Run it on every node whose subscription you will repoint, heren2andn3, sincesub_alter_interfacelooks the interface up locally:Then run
sub_alter_interfaceon each of those nodes. The subscriptions it names are the ones step 20 recreates, so this only applies once step 20 is done:spock.gen_sub_name(provider_node, subscriber_node)names each subscription, sosub_n1_n2is the subscription onn2whose provider isn1; confirm the exact names for your cluster withSELECT sub_name FROM spock.subscription;on each node before repointing them.Put
n1’s replication origins back where step 2 recorded them, before its subscriptions run again. For each subscription, create the origin ifpg_upgradedid not keep it, then advance it to the recorded LSN:Confirm each origin now shows its recorded LSN:
On every other node, recreate its subscription to
n1from the definition recorded in step 2. Do not copy data: step 2 made sure every node already held all ofn1’s changes, andn1has taken no writes since. The following example recreates the subscription onn2whose provider isn1:Do not set
synchronize_data := truehere. The data sync copies each table into the existing one without emptying it first, so it fails on the rows the node already holds.Re-enable
n1’s own subscriptions, then confirm every subscription to and fromn1reportsreplicating:Then check the status of every subscription in the cluster:
Restore traffic to the node at the load balancer, pooler, or application layer.
With n1 upgraded, repeat steps 1 through 22 for n2 and n3.
Each node’s standby must be built from a pg_basebackup against that
specific node, never against another one - n2_standby streams from
n2, not from n1, even though Spock keeps their table data
identical.
A physical standby is tied to the exact system identifier and
Spock catalog rows (its own spock.node/spock.subscription
entries) of the instance it shadows, so it can be promoted into
that instance’s exact identity; a standby built from n1 and
promoted in place of n2 would still carry n1’s identity and
subscriptions, breaking the mesh rather than replacing n2.
Each node’s physical standby, if it has one, also belongs under its
own Patroni scope (n2-cluster, n3-cluster) with its own leader -
never add n2 or n3 as a member of n1-cluster. Patroni elects one
primary per scope, and n1, n2, and n3 each remain independent
primaries in the Spock mesh, not standbys of one another. The DCS
deployment itself can still be shared: one etcd cluster can serve
every node’s Patroni scope, so long as each scope’s name is unique.
Re-enabling DDL Replication
Once every node is upgraded, turn automatic DDL replication back on, on every node, as in Upgrading Spock:
Verifying the Rollout
When every node has been upgraded, confirm the whole cluster runs the target PostgreSQL version and reports a clean replication topology:
Run the dblink query once per node, changing the port.
The following table describes what to check in the output before considering the rollout complete:
| Field | What to confirm |
|---|---|
| PostgreSQL version | Every node reports the target version. |
| Subscription status | Every subscription between every pair of nodes reports replicating. |
Troubleshooting
pg_upgrade --checkreports an incompatible extension version. Install the Spock build for the target PostgreSQL version on the node before upgrading;pg_upgradechecks that every extension in the old cluster has a matching library available for the new one.pg_upgrade --linkfails withcould not create hard link between old and new data directories. The old and new data directories are on different filesystems or volumes. Place the new data directory on the same filesystem as the old one, or run without--linkand accept the storage cost of a full copy.A subscription on the upgraded node fails because its replication origin does not exist. The origin was not restored before the subscription was enabled. Disable it, restore the origin as in step 19 from the position recorded in step 2, then enable it again.
The application still routes traffic to a node that is down for upgrade. Confirm the load balancer, pooler, or application-level routing actually removed the node from rotation in step 1 before you stopped it in step 3, rather than relying on connection failures to redirect traffic.
For more information, review the following resources:
- Modifying a Cluster
- Logical Slot Failover (HA Standby)
- Tutorial: Updating the Postgres Version with a Rolling Update
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.8 - Conflict Types
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
For conflict avoidance using delta-apply columns, see Conflict Avoidance and Delta-Apply Columns.
In a multi-master replication environment, conflicts occur when two or more nodes make changes to the same row (as identified by a primary key or replica identity) at overlapping times. Spock detects these conflicts during the apply phase on the subscribing node and resolves them according to a configurable resolution strategy.
Each conflict is classified as one of the types described below.
Resolvable conflicts are recorded in the spock.resolutions table
(when spock.save_resolutions is enabled); non-resolvable conflicts
are recorded in spock.exception_log.
Summary Table
| Conflict Type | DML | Resolvable |
|---|---|---|
insert_exists | INSERT | Yes |
update_origin_differs | UPDATE | N/A (normal flow, not recorded) |
update_exists | UPDATE | No (unique constraint violated), saved in spock.exception_log |
update_missing | UPDATE | No (row not found), saved in spock.exception_log |
delete_origin_differs | DELETE | N/A (normal flow, not recorded) |
delete_missing | DELETE | Yes |
delete_exists | DELETE | Yes |
A conflict is resolvable when Spock can automatically choose a
winning tuple and continue replication without operator intervention.
update_missing and update_exists are not resolvable and result in
an ERROR that is recorded in spock.exception_log.
insert_exists
A remote INSERT arrives but a row with the same primary key (or replica identity) already exists on the local node. This typically happens when two nodes independently insert a row with the same key.
Spock detects the conflict by looking up the incoming tuple against
unique indexes (primary key, replica identity, and optionally all
unique constraints when spock.check_all_uc_indexes is enabled).
Resolution: The configurable conflict resolver (default
last_update_wins) compares the commit timestamps of the local and
remote rows. The winner’s values are applied as an UPDATE to the
existing row.
update_origin_differs
A remote UPDATE targets a row whose local copy was last modified by a
different replication origin. In a multi-master topology this is the
normal flow of replication – two nodes each modify a row and the
changes propagate – so Spock does not treat it as a true conflict.
PostgreSQL’s native logical replication does classify it as a conflict,
however, so Spock tracks the type for completeness and supports
optional logging via the spock.log_origin_change GUC.
Spock detects this by comparing replorigin_session_origin (the
source of the incoming change) with the origin recorded on the local
tuple. Changes from the same origin or the same local transaction are
silently applied without any conflict reporting.
Resolution: The configurable conflict resolver (default
last_update_wins) determines the winner. Since this is normal
replication flow, the event is not written to spock.resolutions
regardless of which side wins.
update_exists
A remote UPDATE is applied successfully via the replica identity, but the new row values violate a unique constraint on a different index. For example, the UPDATE changes a column that is part of a secondary unique index and the new value collides with another existing row.
This conflict type matches the definition used by PostgreSQL 18’s native logical replication. Spock reports it to the PostgreSQL server log and PG18 conflict statistics when the unique constraint violation is detected.
Resolution: This conflict is not automatically resolvable. The
error is written to spock.exception_log.
update_missing
A remote UPDATE cannot find the target row on the local node. The row may have been deleted locally, or it may never have arrived due to a replication gap.
Spock retries the lookup several times (with short waits) in case the row is being inserted by a concurrent transaction. If the row still cannot be found after retries, the conflict is raised.
Resolution: This conflict is not resolvable. Spock raises an
ERROR, which is logged to spock.exception_log.
delete_origin_differs
A remote DELETE targets a row that exists locally but was last modified
by a different replication origin. As with update_origin_differs,
this is normal replication flow rather than a true conflict – one node
deletes a row while another node’s earlier update is still in flight.
Spock tracks the type because PostgreSQL’s native logical replication
considers it a conflict, and supports optional logging via
spock.log_origin_change.
If the local tuple came from the same origin as the incoming delete, or from the same local transaction, the delete is applied silently with no conflict reporting.
Resolution: The configurable conflict resolver (default
last_update_wins) determines the winner. When the remote DELETE
wins, the delete proceeds. When the local tuple wins (it is newer),
the delete is skipped and the row is preserved; this case is reported
as delete_exists instead.
delete_missing
A remote DELETE cannot find the target row on the local node. The row was likely already deleted by a local or other replicated transaction.
As with update_missing, Spock retries the lookup several times
before confirming the row is absent.
Resolution: The conflict is automatically resolved by skipping the
delete (skip). Since the row is already gone, the desired end state
has been achieved. The event is recorded in the spock.resolutions
table.
delete_exists
A remote DELETE arrives but the local copy of the row has a more recent commit timestamp than the delete. This is unique to Spock and does not have a counterpart in native PostgreSQL logical replication.
This occurs when one node deletes a row while another node updates it with a later timestamp. The delete is the older operation, so the updated row should be preserved.
Resolution: The delete is skipped and the local (newer) row is
kept (skip / keep_local). The event is recorded in the
spock.resolutions table.
Conflict Resolution Strategies
The spock.conflict_resolution GUC controls how resolvable conflicts
(all types except update_missing and update_exists) are decided. In
current Spock releases the only supported value is:
| Strategy | Behavior |
|---|---|
last_update_wins | The row with the most recent commit timestamp wins (default). |
last_update_wins requires track_commit_timestamp = on in
postgresql.conf.
Tiebreaker: When two rows have identical commit timestamps, Spock
uses the tiebreaker value from the spock.node configuration to
determine a winner. The node with the lower tiebreaker value wins. By
default the tiebreaker is set to the node’s unique ID.
Tiebreaker resolution is always local. Every node keeps its own copy
of what it believes each node’s tiebreaker to be, read from its own
spock.node.info column. A node’s info (including tiebreaker) is
populated once – either when the node is created, or when another node
first subscribes to it (via spock.sub_create(), which fetches the
provider’s node metadata at that moment).
A node’s own location, country, and info (including tiebreaker)
can be changed afterward with
spock.node_alter –
the recommended way, since it validates a tiebreaker value and merges
info rather than replacing it – or with a raw UPDATE spock.node.
Either way, the change propagates automatically to every node that
subscribes to it directly (see
Automatic Node Metadata Propagation):
Every node that subscribes to n1 directly picks this up with no
further action. The message is not forwarded through a cascade topology
(Node A → Node B → Node C): Node C normally has no spock.node row for
n1 unless it subscribes to n1, so there is nothing for it to update.
A node that has a row for n1 but did not apply the message keeps the old
value. This happens when the transaction carrying the message is skipped or
discarded by the exception handling. Use
spock.node_refresh_info
to catch up on demand:
Leaving some nodes unrefreshed has the same effect as updating them with different values: the cluster ends up with disagreeing tiebreaker values for the same node, which can cause different nodes to resolve the identical conflict differently.
Frozen Tuples and Missing Timestamp Data
Timestamp-based conflict resolution depends on commit timestamp and origin information being available for the local tuple. There are two cases where this information is missing:
Frozen tuples. PostgreSQL periodically “freezes” old row versions,
replacing their transaction ID with FrozenTransactionId. Once
frozen, the original commit timestamp and origin can no longer be
retrieved. When Spock encounters a frozen local tuple during conflict
resolution, it treats the local timestamp as zero. Since any real
remote timestamp is greater than zero, the remote change always wins.
No conflict is logged because the local origin could not be
determined.
track_commit_timestamp = off. If commit timestamp tracking is
disabled, Spock cannot retrieve origin or timestamp information for
any local tuple. In this case, Spock copies the remote origin and
timestamp into the local values. The same-origin check then sees
matching origins and treats the change as normal replication flow –
no conflict is detected or logged. This effectively makes conflict
resolution invisible: the remote change is always applied silently.
For reliable conflict detection and resolution,
track_commit_timestamp must be set to on.
Conflict Logging
spock.save_resolutions(defaultoff) – When enabled, resolved conflicts are written to thespock.resolutionstable with full tuple details in JSON format.spock.conflict_log_level(defaultLOG) – Controls the PostgreSQL log level at which detected conflicts are reported. Set to a level belowlog_min_messagesto suppress log output.spock.log_origin_change(defaultnone) – Controls whetherupdate_origin_differsanddelete_origin_differsevents (normal replication flow) are logged to the PostgreSQL server log. These events are never written tospock.resolutions. Options:none,remote_only_differs,since_sub_creation.
Comparison with PostgreSQL 18 Native Logical Replication
PostgreSQL 18 introduced built-in conflict detection for logical replication. Spock’s conflict types are aligned with PostgreSQL’s definitions (same names, same enum ordering) so that the two systems report conflicts in a consistent way. The key differences are in how each system resolves conflicts and where it records them.
| Conflict Type | PostgreSQL 18 | Spock (with last update wins) |
|---|---|---|
insert_exists | Logs and raises ERROR. | Resolves via last_update_wins; transforms INSERT into UPDATE of the winning tuple. |
update_origin_differs | Logs and always applies the remote tuple. | Resolves via last_update_wins; local tuple can win. Treated as normal replication flow (not a true conflict) with optional logging via log_origin_change. |
update_exists | Detects unique constraint violation on updated row; logs. | Logs and records in spock.exception_log. |
update_missing | Logs and skips. | Logs and records in spock.exception_log. |
delete_origin_differs | Logs and always applies the delete. | Resolves via last_update_wins; local tuple can win (reported as delete_exists). Treated as normal replication flow (not a true conflict) with optional logging. |
delete_missing | Logs and skips. | Logs and skips. Records in spock.resolutions. |
delete_exists | No equivalent. | Unique to Spock. The local row is newer than the remote DELETE, so the delete is skipped and the row is preserved. |
Resolution. PostgreSQL 18 does not resolve conflicts – it either
applies the remote change unconditionally or skips the operation, and
logs the event. Spock adds configurable resolution strategies (default
last_update_wins) with a tiebreaker mechanism, allowing the local
tuple to win when it is more recent.
Persistence. PostgreSQL 18 writes conflicts only to the PostgreSQL
server log. Spock additionally persists certain conflicts in the
spock.resolutions table (with full tuple details in JSON) –
specifically insert_exists, delete_missing, and delete_exists –
and non-resolvable conflicts (update_missing, update_exists) in
spock.exception_log. Origin-differs events are not persisted to
either table.
Statistics. On PostgreSQL 18, Spock reports all conflict types to
the native pgstat subscription conflict statistics, so they appear
in the same views used by built-in logical replication.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.9 - Conflict-Free Delta-Apply Columns (Conflict Avoidance)
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Conflicts can arise if a node is subscribed to multiple providers, or when local writes happen on a subscriber node. Without Spock, logical replication can also encounter issues when resolving the value of a running sum (such as a YTD balance).
Suppose that a running bank account sum contains a balance of
$1,000. Two transactions conflict because they overlap with each from
two different multi-master nodes. Transaction A is a $1,000 withdrawal
from the account. Transaction B is also a $1,000 withdrawal from the
account. The correct balance is $-1,000. The Delta-Apply algorithm
fixes this problem and highly conflicting workloads with this scenario
(for example, a tpc-c like benchmark) now run correctly at lightning
speeds.
In the past, Postgres users have relied on special data types and numbering schemes to help prevent conflicts. Unlike other solutions, Spock’s powerful and simple conflict-free delta-apply columns instead manage data update conflicts with the following logic:
- the old value is captured in WAL files.
- a new value comes in from a transaction.
- before the new value overwrites the old value, a delta value is created from the above two steps; that delta is correctly applied.
To simplify: local_value + (new_value - old_value)
Note that on a conflicting transaction, the delta-apply column will be correctly calculated and applied.
To make a column a conflict-free delta-apply column, ensuring that the value
replicated is the delta of the committed changes (the old value plus or
minus any new value) to a given record, you need to apply the following
settings to the column: log_old_value=true, delta_apply_function=spock.delta_apply. For example:
As a special safety-valve feature, if you ever need to re-set a
log_old_value column you can temporarily alter the column to
log_old_value is false.
Conflict Configuration Options
You can configure some Spock extension behaviors with configuration options
that are set in the postgresql.conf file or via ALTER SYSTEM SET:
spock.conflict_resolution = last_update_winssets the resolution method tolast_update_winsfor any detected conflicts between local data and incoming changes; the version of data with newest commit timestamp is kept; note that thetrack_commit_timestampPostgreSQL setting must also beenabled.spock.conflict_log_levelsets the log level for reporting detected conflicts; the default isLOG; if the parameter is set to a value lower thanlog_min_messages, resolved conflicts are not written to the server log; accepted values are the same as for thelog_min_messagesPostgreSQL setting (see possible values); this setting is used primarily to suppress logging of conflicts.
Handling INSERT-RowExists or INSERT/INSERT Conflicts
If Spock encounters a conflict caused by a constraint violation (unique
constraint, primary key, or replication identity) Spock can automatically
transform an INSERT into an UPDATE, updating all columns of the existing
row.
By default, when an INSERT statement targets a row that already exists,
Spock detects the conflict and transforms the operation into an UPDATE
statement, applying changes to all columns of the existing row. The event is
recorded in the spock.resolutions table.
Extended constraint violation behavior is controlled by the
spock.check_all_uc_indexes parameter. The default value is off; when set
to on, Spock will perform the following actions:
- scan all valid unique constraints (as well as the primary key and replica identity).
- scan non-null unique constraints (including the primary key or replica identity index) in OID order.
- locate and resolve conflicting rows encountered during an
INSERTstatement.
If spock.check_all_uc_indexes is enabled, Spock will resolve only
the first conflict identified, using Last-Write-Wins logic. If a second
conflict occurs, an exception is recorded in the spock.resolutions
table as either Keep-Local or Apply-Remote.
This feature is experimental; enable this feature at your own risk.
Handling DELETE-RowMissing Conflicts
Given that the purpose of the DELETE statement is to remove the row anyway,
we do not log these as exceptions, since the desired outcome of removing the
row has obviously been achieved, one way or the other. Instead
DELETE-RowMissing conflicts are automatically written to the
spock.resolutions table since the desired result has been achieved.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.10 - Monitoring the Configuration and Health of Your Cluster
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension provides several ways you can monitor data health in your Postgres cluster:
- You can query informational tables in the
spockschema to review information about your cluster configuration and status. - The status views
spock.node_status,spock.subscription_status,spock.worker_status,spock.slot_statusandspock.eventsgive a complete picture of a node without reading the server log. - The Spock extension’s Lag Tracking utility allows you to review node-specific metrics for replication lag.
- Use Spock’s Sync Event utility to watch for a specific transaction to replicate.
- Use the ACE (Active Consistency Engine) to evaluate cluster health.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.10.1 - Finding Cluster Information
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The following table describes informational tables in the spock schema:
| Table Name | Description |
|---|---|
channel_table_stats | This view tracks per-table statistics for a given subscription, including total inserts, updates, deletes, conflicts, and delta apply column changes. The view includes the following columns: subid, relid, sub_name, table_name, n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dca |
channel_summary_stats | This view aggregates statistics from channel_table_stats across tables, showing overall metrics grouped by subscription. The view includes the following columns: subid, sub_name, n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dca |
events | This view lists recent state changes of the node kept in shared memory: subscriptions enabled or disabled, workers started, stopped or failed, provider connects, extension upgrades. See Monitoring a Node. The view includes the following columns: event_id, event_time, event_type, severity, subscription_id, subscription_name, pid, lsn, detail |
depend | This is an internal-use table that tracks dependent objects (e.g., tables added for replication or row filters). If such objects are dropped, they are also removed from Spock’s tracking. The table includes the following columns: classid, objid, objsubid, refclassid, refobjid, refobjsubid, deptype |
exception_log | This table logs unrecoverable errors or conflicts encountered by Spock during the replication process. The table includes the following columns: remote_origin, remote_commit_ts, command_counter, retry_errored_at, remote_xid, local_origin, local_commit_ts, table_schema, table_name, operation (contains one of the following: BEGIN, COMMIT, INSERT, UPDATE, DELETE, or DDL), local_tup, remote_old_tup, remote_new_tup, ddl_statement, ddl_user, error_message |
exception_status | This table is not used internally by Spock. This table exists to support ACE by tracking specific status details. The table includes the following information columns: remote_origin, remote_commit_ts, retry_errored_at, remote_xid, status, resolved_at, resolution_details |
exception_status_detail | The table includes the following columns: remote_origin, remote_commit_ts, command_counter, retry_errored_at, remote_xid, status, resolved_at, resolution_details |
local_node | This table contains one row with information for the local node. It contains the node_id and node_local_interface and can be joined with the previous two tables to show all local node information only. |
local_sync_status | This table displays the synchronization status of relations (tables) added to subscriptions. Shows all tables if a full sync was requested, or individual tables if sync was limited to specific tables. The table includes the following columns: sync_kind, sync_subid, sync_nspname, sync_relname, sync_status, sync_statuslsn |
node | This table contains one row per replication node. This table contains: node_id, node_name, and optionally the location, country, and info. |
node_interface | This table contains one row per node interface. This table contains: if_id, if_name, if_nodeid, and if_dsn columns which represent the connection information for that node. |
node_status | This view returns one row describing the whole node: versions, worker and subscription counts, WAL retained by slots, replication lag and the time of the last events. See Monitoring a Node. |
peer_status | This view lists every node this node knows about with its interfaces and the subscription that brings its changes here. See Monitoring a Node. |
pii | This is an optional table in which you can define columns that contain personally identifiable information (pii). You can add information such as the schema, table, and column names and then use this table to create column filters when adding tables to replication sets. The table contains the following columns: id, pii_schema, pii_table, pii_column |
progress | This is an internal-use table that tracks replication progress, including source node, commit LSN, commit timestamp, and origin’s current WAL insert location. The table includes the following columns: node_id, remote_node_id, remote_commit_ts, remote_commit_lsn, remote_insert_lsn, last_updated_ts, updated_by_decode |
queue | This is an internal-use table used during AutoDDL, subscription/table synchronization, and native sequence synchronization processes. The table includes the following information columns: queued_at, role, replication_sets, message_type, message |
replication_set | This table contains one row per replication set. It contains the set_id, set_nodeid, set_name and four boolean columns: replicate_insert, replicate_update, replicate_delete, and replicate_truncate. This table also contains three rows by default for the default, default_insert_only, and ddl_sql replication sets. |
replication_set_seq | This table contains one row per replication set sequence. It contains set_id and set_seqoid. |
replication_set_table | This table contains one row per table that is in any replication set. It contains the set_id, set_reloid (the table name), set_att_list, and set_row_filter. The last two columns contain the row and column filters on that table for replication. |
replication_set_status | This view lists the replication sets of the local node with their replicate flags and the number of tables, sequences and subscriptions using each. |
resolutions | This table contains one row per resolution made on this node. It contains the id, node_name, log_time, relname, idxname, conflict_type (update_update), conflict_resolution (keep_local), local_origin, local_tuple, local_xid, local_timestamp, remote_origin, remote_tuple, remote_xid, remote_timestamp, remote_lsn. |
settings | This view shows the spock parameters and the core parameters replication depends on, with unit, source and pending restart. |
slot_status | This view describes every spock replication slot of the database together with the walsender serving it, the WAL it holds back and the feedback lag. See Monitoring a Node. |
sequence_state | This is an internal-use table that stores state information for native sequence synchronization. The table includes the following columns: seqoid, cache_size, last_value |
subscription | This table contains one row per subscription. It contains the following columns: sub_id, sub_name, sub_origin, sub_target, sub_origin_if, sub_target_if, sub_enabled, sub_slot_name, sub_replication_sets (an array of replication sets that have been added to the subscription), sub_forward_origins, sub_apply_delay, sub_force_text_transfer, sub_skip_lsn (a pg_lsn set by spock.sub_alter_skiplsn), sub_skip_schema (an array of schemas to skip during apply), and sub_created_at (timestamp of subscription creation). |
subscription_stats | This view returns the activity counters of every subscription: worker starts and failures, provider connects, messages and transactions received, tuple and conflict counters, and the last error. See Monitoring a Node. |
subscription_status | This view describes every subscription on one row: configuration, status, the apply worker serving it, replication positions and lag, and the last error. See Monitoring a Node. |
system_status | This view returns one row about the host and the instance: disk space, load, connections, long and idle transactions, wraparound age, database statistics and WAL archiving. See Monitoring a Node. |
table_sync_status | This view shows local_sync_status with readable sync_kind and sync_status values. |
tables | This table contains one row per table in the database. It contains the following columns: relid, nspname (the schema), relname (the tablename), and set_name (null if that table is not added to any replication set). |
worker_status | This view lists the spock processes of the node: supervisor, manager, apply and sync workers, with their status and the subscription or table they serve. See Monitoring a Node. |
Examples
The following examples demonstrate how to query the informational tables to monitor and validate your Spock replication cluster.
Validating Spock Configuration for a Two-Node Cluster
You can use the Spock extension to confirm that nodes are created and replication is happening.
Query spock.node to check node creation status: an empty result set means
the node creation command has not yet been run, while a single row confirms
the node exists.
Query spock.subscription to check subscription creation status: an empty
result set means no subscription has been created on this node, while a
single row confirms a subscription exists.
You can connect to the database server and query the spock.node table to
return information about configured nodes:
Confirming that a Functioning Subscription Exists
You can connect to the database server and query the spock.subscription
table to return information about a subscription:
Note that the value of sub_enabled is t if the subscription is currently
replicating.
Listing Tables that are Part of a Replication Scenario
You can connect to the database server and query the
spock.replication_set_table table to return similar information:
Listing Tables that are not Part of a Replication Cluster
You can query the spock.tables table to identify tables that are not yet
part of a replication set; if the set name is null, the table is not part
of a replication set.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.10.2 - Lag Tracking
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The Spock extension’s lag tracking feature shows how far behind a subscriber is when compared to a provider node in terms of write-ahead log (WAL) replication. You can use this feature to understand replication delays and monitor streaming health.
Tracking is implemented via a SQL view named spock.lag_tracker, which
exposes key metrics for replication lag on a per-node basis. For example:
The following table describes the columns displayed by spock.lag_tracker:
| Column Name | Description |
|---|---|
| origin_name | Name of the provider node. |
| receiver_name | Name of the subscriber node. |
| commit_timestamp | Commit time of the last transaction received from the provider. |
| commit_lsn | Log sequence number (LSN) of the commit on the provider. |
| remote_insert_lsn | WAL insert position on the provider when the commit was sent. |
| received_lsn | Last acknowledged log sequence number (LSN) received from the provider. |
| replication_lag_bytes | The amount of data the subscriber is behind. |
| replication_lag | Time delay between when the transaction was committed on the provider and when processed locally. |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.10.3 - Monitoring a Node with the Spock Status Views
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock keeps the state of a node in shared memory and exposes it through a
set of views in the spock schema. Together they answer the questions an
operator would otherwise take to the server log: is every subscription
replicating, which workers are running, how far behind is each provider,
how much WAL is a slot holding back, and what happened recently.
| View | One row per | Purpose |
|---|---|---|
spock.system_status | host | Host and instance health: disk, load, connections, long transactions, wraparound age, archiving. |
spock.node_status | node | The whole node on one row: versions, counts, WAL, lag, last events. |
spock.subscription_status | subscription | Configuration, status, serving worker, replication position and lag, last error. |
spock.subscription_stats | subscription | Activity counters: worker starts, connects, transactions, tuples, conflicts, errors. |
spock.worker_status | spock process | Supervisor, manager, apply and sync workers with their state. |
spock.slot_status | replication slot | Provider side: walsender state, positions and retained WAL per spock slot. |
spock.table_sync_status | subscription or table | Initial synchronization state in readable form. |
spock.peer_status | known node | Every node this node knows, with the subscription that brings its changes here. |
spock.replication_set_status | replication set | Replication sets of the local node with table, sequence and subscriber counts. |
spock.settings | parameter | The spock parameters and the core parameters replication depends on. |
spock.events | event | Recent state changes: enable, disable, restarts, errors, upgrades. |
spock.node_report() runs all of them one after another and returns the
node as a single text report; see The full report.
All views are scoped to the current database. spock.lag_tracker,
spock.progress and the spock.channel_*_stats views remain available and
feed the views above.
System status
spock.system_status is one row about the host and the PostgreSQL
instance. It answers the questions that come before any replication
question: is the disk full, is the machine overloaded, are connections
exhausted, is a long or idle transaction holding back vacuum and the
replication slots, is WAL archiving failing.
| Column | Description |
|---|---|
hostname, os_name, os_release, architecture, cpu_count, memory_bytes | The host. |
load_average_1min, load_average_5min, load_average_15min | System load averages. |
data_directory, data_disk_total_bytes, data_disk_free_bytes | The data directory and the space on its volume. |
wal_disk_total_bytes, wal_disk_free_bytes, wal_size_bytes | The volume holding pg_wal, measured separately in case it is a symlink, and the size of pg_wal. |
database_size_bytes | Size of the current database. |
postgres_version, postmaster_pid, postmaster_start_time, uptime, in_recovery | The instance. |
max_connections, connections, active_connections, idle_in_transaction | Client connections and their state. |
longest_transaction, longest_idle_in_transaction | Age of the oldest open transaction and of the oldest idle one; both hold back vacuum and slot catalog_xmin. |
waiting_on_locks | Sessions currently waiting for a lock. |
prepared_transactions | Prepared transactions, which hold locks and xmin until resolved. |
physical_standbys | Streaming replicas other than spock subscribers. |
oldest_xid_age | Age of the database’s oldest transaction id, towards wraparound. |
xact_commit, xact_rollback, deadlocks, recovery_conflicts, temp_files, temp_bytes, checksum_failures, database_stats_reset | From pg_stat_database for this database. |
archive_mode, archived_count, last_archived_time, archive_failed_count, last_archive_failure | WAL archiving state; a failing archiver fills the WAL volume. |
Node status
spock.node_status always returns exactly one row, even before a node has
been created.
| Column | Description |
|---|---|
node_id, node_name, location, country | The local node, NULL when none exists. |
database_name | The current database. |
hostname, operating_system, postmaster_start_time | The host and the server start. |
spock_version | Version of the loaded shared library. |
extension_version | Version of the installed extension in the catalog. |
extension_update_pending | True when the library is newer than the extension; the manager runs ALTER EXTENSION UPDATE on its next start. |
postgres_version | Server version. |
spock_started_at | When spock shared memory was initialized, normally the postmaster start. |
postmaster_pid, supervisor_pid, manager_pid | Process ids of the postmaster, the supervisor and this database’s manager. |
readonly_mode | Current value of spock.readonly. |
apply_paused | True while spock.pause_apply_workers() is in effect. |
worker_slots, worker_slots_used | Background worker slots spock can use and how many are taken. |
subscriptions, subscriptions_enabled, subscriptions_replicating | Subscription counts. |
replication_slots, replication_slots_active | Spock slots of this database and how many have a connected walsender. |
apply_workers, sync_workers | Running worker counts. |
workers_restart_pending | Workers that exited with an error and wait for the manager to restart them. |
pending_exceptions | Transactions currently being retried under spock.exception_behaviour. |
replicated_tables, unreplicated_tables | Tables of this node in some replication set, and tables in none. |
current_wal_lsn | Current WAL position, replay position on a standby. |
wal_size_bytes | Size of pg_wal, read through spock.wal_size_bytes(), which sums the files itself so that a role without pg_monitor can read it. |
data_disk_free_bytes, wal_disk_free_bytes | Free space on the volumes holding the data directory and pg_wal. |
max_retained_wal_bytes | WAL held back by the slowest spock slot. |
max_replication_lag_bytes, max_replication_lag | Largest lag over all subscriptions. |
exceptions_logged | Rows in spock.exception_log. |
last_event_time, last_error_event_time | Time of the newest event, and of the newest error event. |
events_retained, events_recorded | Events kept in the history and recorded since start. |
Subscription status
spock.subscription_status is the first place to look when replication
seems stuck.
| Column | Description |
|---|---|
subscription_id, subscription_name, enabled | The subscription. |
status | replicating, initializing, starting (the worker is up but not streaming yet, as during a reconnect loop), down (enabled but no worker), disabled or unknown. |
provider_node, provider_dsn | The provider; the password in the DSN is replaced with asterisks. |
slot_name, replication_sets, forward_origins, apply_delay, skip_lsn, skip_schema, force_text_transfer, created_at | Configuration. |
sync_status | Initial synchronization state of the subscription as a whole. |
worker_pid, worker_status, worker_started_at | The apply worker. worker_status is restart pending after a failure. |
worker_terminated_at, worker_restart_delay | When the last worker failed and how long the manager waits before restarting it, in milliseconds. |
worker_paused | True while the worker sleeps because apply is paused. |
in_exception_handling | True while the worker replays a failed transaction under spock.exception_behaviour. |
pending_exception_lsn, pending_exception_error | Commit LSN and first error of the transaction being retried, if any. |
origin_lsn | Last durably applied provider LSN, from spock.replication_origin_status(). |
remote_commit_lsn, remote_commit_ts, remote_insert_lsn, received_lsn | Positions from spock.progress. |
replication_lag_bytes | WAL the provider has written that this node has not yet applied. |
replication_lag | Time between the last applied commit on the provider and its apply here. |
last_message_received, last_xact_applied | When data last arrived from the provider and when a transaction was last committed here. |
time_since_last_message | How long ago data last arrived; a silent provider shows here first. |
worker_blocked_by_pids, worker_blocking_pid, worker_blocking_query | Set while the worker waits for a lock: the sessions holding it and what the first one runs. |
worker_starts, worker_failures, xacts_applied, apply_errors | Counters from spock.subscription_stats. |
last_apply_error, last_error_sqlstate, last_error_pid, last_error_message | The most recent error of the apply worker: when, its SQLSTATE, the process that raised it, and the message with DETAIL and CONTEXT. |
Subscription statistics
spock.subscription_stats has one row for every subscription with the
counters collected by its apply and sync workers. Counters survive worker
restarts and are reset with spock.reset_subscription_stats(subid), or for
all subscriptions with no argument. Every counter has a matching last_*
timestamp of its most recent change.
| Column | Description |
|---|---|
worker_starts, worker_failures | Apply worker starts, and exits with an error. |
sync_worker_starts, sync_worker_failures | The same for the sync workers that copy tables; a resync adds one start per table. |
provider_connects, provider_disconnects, idle_timeouts | Connections to the provider, connection losses together with connection attempts that failed (so while the provider is down this counts every retry), and reconnects forced by spock.apply_idle_timeout. |
messages_received, bytes_received | Data messages received from the provider. |
xacts_applied, xacts_skipped, xacts_discarded | Transactions committed locally, skipped through sub_skip_lsn, and discarded under transdiscard. |
apply_errors, sync_errors | Errors raised in apply and in sync workers. An apply error counts once per failed transaction. |
deadlocks, lock_timeouts, constraint_violations, resource_errors | The same errors classified by SQLSTATE: deadlock detected, lock not available, class 23 and class 53. |
tables_synced | Tables whose initial synchronization completed. |
n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dca | Tuple counters, summed from spock.channel_table_stats. |
confl_* | Conflict counters by type; NULL before PostgreSQL 18. |
last_error_message, last_error_lsn, last_error_sqlstate, last_error_pid | The most recent worker error with DETAIL and CONTEXT, the provider LSN it happened at, its SQLSTATE and the process that raised it. |
stats_reset | When the counters were last reset. |
Workers
spock.worker_status lists the supervisor, the manager of this database,
and every apply and sync worker, including slots of failed workers that are
waiting to be restarted.
| Column | Description |
|---|---|
worker_slot, worker_type, pid | Slot in shared memory, supervisor, manager, apply or sync, and process id. |
worker_status | starting, running, idle, stopping, stopped, failed or restart pending. |
subscription_id, subscription_name | For apply and sync workers. |
sync_schema_name, sync_table_name | The table a sync worker copies. |
started_at, xact_start, backend_state, wait_event_type, wait_event | From pg_stat_activity. |
blocked_by_pids, blocking_pid, blocking_xact_start, blocking_query | Set while the worker waits for a lock held by another session, from pg_blocking_pids(). |
paused, in_exception_handling, sync_pending | Apply worker flags. |
replay_stop_lsn, remote_wal_insert_lsn | Positions the worker works towards and has last seen on the provider. |
generation, terminated_at, restart_delay | Registration counter, time of the last failure, restart delay in milliseconds. |
Replication slots
spock.slot_status is the provider side view: one row per spock
replication slot of the current database, joined with the walsender that
serves it.
| Column | Description |
|---|---|
slot_name, active, active_pid | The slot and its walsender. |
client_name, client_addr, connected_at, state | The connected subscriber, from pg_stat_replication. |
restart_lsn, confirmed_flush_lsn, sent_lsn, write_lsn, flush_lsn, replay_lsn | Positions. |
retained_wal_bytes | WAL kept on disk for this slot. |
pending_wal_bytes | WAL the subscriber has not confirmed yet. |
write_lag, flush_lag, replay_lag, last_reply_time | Feedback timing. |
wal_status, safe_wal_size, catalog_xmin, catalog_xmin_age, temporary, two_phase | From pg_replication_slots; a growing catalog_xmin_age means the slot holds back catalog vacuum. |
decoded_txns, decoded_bytes, spill_*, stream_*, decode_stats_reset | Decoding work done for the slot, from pg_stat_replication_slots. Growing spill_bytes means transactions larger than logical_decoding_work_mem. |
slot_group_* | Shared state of the slot group, for parallel slots only. |
Peers, replication sets and settings
spock.peer_status lists every node in spock.node with its interfaces
(passwords hidden), whether it is the local node, and the subscription that
brings its changes here with that subscription’s status and lag. A node
with several subscriptions has one row per subscription.
spock.replication_set_status lists the replication sets of the local node
with their replicate flags, the number of tables and sequences in each, and
how many local subscriptions include the set. Tables that are in no set at
all are listed by spock.tables where set_name IS NULL.
spock.settings shows every spock.* parameter and the core parameters
replication depends on (wal_level, max_worker_processes,
max_replication_slots, max_wal_senders, max_slot_wal_keep_size,
track_commit_timestamp, shared_preload_libraries, the walsender and
walreceiver timeouts, synchronous commit settings and
logical_decoding_work_mem), with unit, source and whether a restart is
pending. Connection strings in parameters have their password hidden.
Events
spock.events is a ring of recent state changes kept in shared memory,
oldest first. The number of events kept is set by
spock.event_history_size. The history is cleared by a postmaster restart,
and spock.reset_events() clears the events of the current database.
| Column | Description |
|---|---|
event_id | Increases by one per event and is never reused. |
event_time, event_type, severity | When, what, and info, warning or error. |
sqlstate | The SQLSTATE of a worker_error or stream_error event. |
subscription_id, subscription_name, provider_node | The subscription concerned, if any, and the node its changes come from. |
pid | The reporting process. |
lsn | The provider LSN the event refers to: the start position of a stream, the commit LSN of a skipped, discarded or failed transaction, the position a subscription was disabled at. NULL for lifecycle events such as worker starts. |
detail | A short description. |
Event types:
| Type | Recorded when |
|---|---|
node_created, node_dropped | spock.node_create() and spock.node_drop() complete. |
subscription_created, subscription_dropped | A subscription is created or dropped. |
subscription_enabled, subscription_disabled | A subscription is enabled or disabled, by an operator or by exception handling. |
subscription_altered | Interface, replication sets, skip_lsn, options or a synchronization request changed. |
worker_started, worker_stopped, worker_failed | A manager, apply or sync worker starts, exits cleanly, or exits with an error. |
worker_error | An error is raised inside an apply or sync worker. The detail carries the message with DETAIL and CONTEXT. |
provider_connected, provider_disconnected | The replication connection to the named provider is established, with the start LSN, or lost, with the error. |
transaction_skipped, transaction_discarded | A transaction is skipped through sub_skip_lsn or discarded under transdiscard. |
sync_started, sync_finished, sync_failed | Initial copy of a table. sync_failed carries the error that ended the copy; the next sync worker for that table records a second sync_failed saying the table was abandoned after the earlier failure, and no further attempt is made. |
slot_created, stream_started, stream_stopped, stream_error | Provider side: a spock slot is created, a walsender starts streaming to a subscriber (its address, spock version and protocol in the detail, the slot position in lsn), stops (recorded as the walsender exits, so a subscriber that disconnects or restarts produces one), or fails with an error while decoding. |
apply_paused, apply_resumed | spock.pause_apply_workers() and spock.resume_apply_workers(). |
repair_mode_enabled, repair_mode_disabled | spock.repair_mode(). |
extension_upgraded | The manager updated the extension to the library version. |
Events are recorded when the reporting code runs, whether or not the surrounding transaction commits.
The full report
spock.node_report() returns the whole node as text, section by section:
system status, installed extensions, settings, node status, peers,
subscriptions, subscription statistics, workers, pending exceptions,
replication slots, replication sets, tables in no replication set, table
synchronization, lag by node pair, recent exceptions, recent conflict
resolutions and recent events. Wide views are printed one row per block,
lists as aligned tables. A section whose query fails, for example
node_status for a role without EXECUTE on the functions behind it,
prints one error line and the report continues.
In psql, \pset format unaligned and \o report.txt before the call
produce a plain file that can be attached to a ticket. The report contains
no passwords.
spock.report_section(title, query, expanded) is the formatter behind
the report and can render any query the same way.
Common tasks
The recipes below cover the questions that used to require the server log.
Run them in psql with expanded output (\x) when a row is wide.
Is the node healthy?
One row answers it. Anything other than zero in workers_restart_pending,
a difference between subscriptions_enabled and subscriptions_replicating,
or a last_error_event_time that is more recent than you expect deserves a
look.
Why is a subscription not replicating?
Start with the subscription row. status tells whether a worker runs at
all, worker_status and worker_terminated_at show a failed worker
waiting for its restart delay, and last_error_message is the error the
worker last raised, without opening the log.
Then read the events of that subscription, newest first:
A subscription that was disabled by exception handling shows a
subscription_disabled event with the detail disabled by exception handling and the origin LSN of the failing transaction in lsn; the row in
spock.exception_log has the failing tuple.
Is a worker blocked or deadlocking?
A worker waiting for a lock shows wait_event_type = 'Lock' and the
session holding the lock in blocked_by_pids and blocking_query. A
deadlock or lock timeout aborts the transaction; the worker exits and is
restarted, and the error is classified.
Is a worker restarting in a loop?
worker_starts and worker_failures climb together when the apply worker
crashes on every attempt. The events show the interval and the reason. Sync
workers have their own pair of counters, so a resync of many tables does
not look like a restart loop here.
What changed overnight?
Everything that is not routine has a severity above info.
Enable and disable calls, interface switches, replication set changes,
sub_skip_lsn, pause and resume, repair mode and extension upgrades are
all info or warning events with the operator’s backend pid in pid.
How far behind is each provider?
replication_lag_bytes is WAL the provider has written that this node has
not applied yet. replication_lag is the time between the last applied
commit on the provider and its apply here. Both come from
spock.progress and are also available per node pair in
spock.lag_tracker.
Is a slot holding back WAL on the provider?
Run this on the provider. A slot with active = false or a growing
retained_wal_bytes points at a subscriber that is down or lagging.
Is the initial synchronization finished?
The row without a table is the subscription itself. Sync workers in flight
are listed in spock.worker_status with worker_type = 'sync' and the
table they copy.
Did the extension get upgraded?
spock.node_status compares the loaded library with the installed
extension. After a binary upgrade the manager updates the extension on its
next start and records the change.
Starting a fresh measurement
Counters and events accumulate since the postmaster started. Reset them before a benchmark or after fixing an incident so that the next numbers are clean.
spock.reset_channel_stats() clears the per-table tuple counters
separately.
Watching from outside
The views are plain SQL, so any monitoring agent can poll them. Poll
spock.events by event_id to fetch only new rows, and treat a gap in
ids as history that was dropped because spock.event_history_size was too
small for the polling interval. spock.get_monitor_summary() reports how
full the event ring and the counters table are. The read-only views and
the functions they call are granted to pg_monitor; the role also needs
USAGE on the schema:
For now, USAGE on the spock schema also allows calling spock’s
management functions. Grant it only to trusted roles, and treat every
function that changes something as needing a superuser. Members of
pg_monitor cannot reset counters or events: spock.reset_events() and
spock.reset_subscription_stats() stay with the superuser. The
node_report() sections on spock.tables, spock.lag_tracker,
spock.exception_log and spock.resolutions need SELECT on those,
which the grant does not include; without it each shows as one error line.
Underlying functions
The views are built on functions that return the raw shared memory contents. They are useful for tooling that wants unfiltered rows.
| Function | Returns |
|---|---|
spock.get_worker_status() | Every worker slot of the cluster, with database_id. |
spock.get_events() | Every event in the history, with database_id. Superuser or pg_monitor. |
spock.get_apply_stats() | The counters of every subscription of the current database. Superuser or pg_monitor. |
spock.get_slot_groups() | Slot groups with attached walsenders. |
spock.get_monitor_summary() | Capacity and usage of the shared memory structures. |
spock.get_system_info() | Host name, operating system, CPU, memory, load averages, disk space of the data and WAL volumes, postmaster start, PostgreSQL and spock versions. Superuser or pg_monitor; the data directory only with pg_read_all_settings. |
spock.get_pending_exceptions() | Transactions being retried under exception handling, with their first error and the position of the failing change in the transaction. Superuser or pg_monitor. |
spock.replication_origin_status() | Every replication origin with its remote progress, as pg_replication_origin_status shows a superuser. Superuser or pg_monitor. |
spock.reset_events() | Clears the event history of the current database. Superuser only. |
spock.reset_subscription_stats(subid) | Resets the activity and conflict counters of one or all subscriptions. Superuser only. |
spock.redact_dsn(text) | Returns a connection string with its password hidden. |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.10.4 - Using spock.sync_event to Confirm Synchronization
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sync_event enables event tracking and synchronization between a
provider and a subscriber node in a Spock logical replication setup. You can
use spock.sync_event to ensure that all changes up to a specific point
(indicated by the PostgreSQL Log Sequence Number or LSN) on the provider have
been received and applied on the subscriber.
To mark the start of the sync event and return the LSN of the event on the subscriber node, you call a function on the node you have selected to act as a provider node:
spock.sync_event()
Then, you monitor a procedure on the node you have selected to act as the subscriber node that detects the presence of the LSN, and confirms when it has been received and applied:
spock.wait_for_sync_event(...) (see the Synopsis for the
required arguments)
Synopsis
Invoked on the provider node, this function returns the current pg_lsn
value, representing a point-in-time value for your replication scenario. The
syntax of spock.sync_event is:
spock.sync_event(transactional boolean DEFAULT false) RETURNS pg_lsn
When transactional is false (the default), the sync event marker is
emitted into the WAL stream immediately, independent of the calling
transaction. When transactional is true, the marker is bound to the
calling transaction and is only visible to subscribers if the transaction
commits.
Invoked on a subscriber node, spock.wait_for_sync_event is available in two
flavors - the first uses the origin_id (an oid) as an identifier for the
node, while the second uses the node name as an identifier:
spock.wait_for_sync_event(OUT result boolean, origin_id oid, lsn pg_lsn, timeout int DEFAULT 0, wait_if_disabled bool DEFAULT false)spock.wait_for_sync_event(OUT result boolean, origin name, lsn pg_lsn, timeout int DEFAULT 0, wait_if_disabled bool DEFAULT false)
This procedure waits on the subscriber node to alert you when the specified LSN (from the provider) is received and applied to the node.
Parameters:
origin_idororigin: Identifies the provider node (by OID or name).lsn: The target LSN to wait for.timeout: (Optional) Number of seconds to wait before timing out. The default is 0 (wait indefinitely).wait_if_disabled: (Optional) Controls how a missing or disabled subscription is handled. The default isfalse.When
wait_if_disabledisfalse(the default), the procedure requires the subscription from the origin node to this node to already exist and be enabled. It raises an error if no such subscription is found, or if the subscription is disabled at any point while waiting:When
wait_if_disabledistrue, neither condition is an error. The procedure keeps polling until the subscription exists, becomes enabled, and reaches the target LSN, or untiltimeoutexpires. Use this when the subscription may not be ready yet - for example on a newly added node whose subscriptions are still being created, or while a subscription is temporarily disabled during a maintenance operation. Because a missing subscription is not reported, pass a non-zerotimeoutso a subscription that is never created does not wait forever.wait_if_disabledonly affects the subscription checks. It does not suppress the argument validation both flavors perform first, so these are still raised immediately regardless of its value:In particular, the name-based flavor requires the origin node to already be registered in
spock.node. If you are waiting on a node that is still joining the cluster, that row may not exist yet either - resolve theorigin_idonce the node is registered, or retry the call.
Returns:
result = true- LSN has been received and applied.result = false- Timeout occurred before the LSN was reached. Withwait_if_disabled = truethis also covers the case where the subscription never existed or never became enabled within the timeout.
Examples
On a provider node:
SELECT spock.sync_event();
-- Returns: 0/16342B0 (example output)
On a subscriber node:
The first parameter is the OUT result placeholder; pass NULL for it in
the CALL statement and read the OUT value from the procedure result.
To wait on a node whose subscription may not be created or enabled yet, pass
wait_if_disabled = true along with a timeout:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11 - Spock Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The following user functions are available via the Spock extension:
| Command | Description |
|---|---|
| Node Management Functions | You can add and remove nodes dynamically using Spock interfaces. |
| spock.node_info | Returns information about the node on which the function is invoked. |
| spock.node_create | Define a node for spock. |
| spock.node_drop | Remove a spock node. |
| node_add_interface | Add a new node interface. |
| spock.node_drop_interface | Delete a node interface. |
| spock.node_alter | Change this node’s own location, country, and/or info (merging info), validating a tiebreaker if one is set. |
| spock.node_refresh_info | Refresh this node’s cached copy of a peer’s (or every peer’s) location, country, and info. |
| Replication Set Management Functions | Replication sets provide a mechanism to control which tables in the database will be replicated and which actions on those tables will be replicated. Each replicated set can specify individually if INSERTs, UPDATEs, DELETEs and TRUNCATEs on the set are replicated. Each table can be in multiple replication sets, and each subscriber can subscribe to multiple replication sets. The resulting set of tables and actions replicated is the union of the sets the table is in. Spock installation creates three replication sets: default, default_insert_only and ddl_sql. The default replication set is defined to replicate all changes to tables in it. The default_insert_only replication set only replicates INSERT statements, and is meant for use by tables that don’t have primary key. The ddl_sql replication set is defined to replicate schema changes specified by spock.replicate_ddl. |
| spock.repset_create | Define a replication set. |
| spock.repset_alter | Modify a replication set. |
| repset_drop | Remove a replication set. |
| spock.repset_add_partition | Add a partition to a replication set. |
| spock.repset_remove_partition | Remove a partition from the replication set that the parent table is a part of. |
| spock.repset_add_table | Add table(s) to replication set. |
| spock.repset_add_all_tables | Add all existing table(s) to the replication set. |
| spock.repset_remove_table | Remove table from replication set. |
| spock.repset_show_table | |
| spock.repset_add_seq | Adds a sequence to a replication set. |
| spock.repset_add_all_seqs | Adds all sequences from the specified schemas to a replication set. |
| spock.repset_remove_seq | Remove a sequence from a replication set. |
| spock.sync_seq | Synchronize the specified sequence. |
| Subscription Management Functions | |
| spock.sub_create | Create a subscription. |
| spock.sub_drop | Delete a subscription. |
| spock.sub_disable | Put a subscription on hold, and disconnect from the provider. |
| spock.sub_enable | Make a subscription live. |
| spock.sub_add_repset | Add a replication set to a subscription. |
| spock.sub_remove_repset | Drop a replication set from a subscription. |
| spock.sub_show_status | Display the status of the subcription. |
| spock.sub_show_table | Show subscription tables. |
| spock.sub_alter_interface | Modify an interface to a subscription. |
| spock.sub_wait_for_sync | Pause until the subscription is synchronized. |
| spock.sub_alter_skiplsn | Skip transactions until the specified lsn. |
| spock.sub_alter_sync | Synchronize all missing tables. |
| spock.sub_alter_options | Change one or more subscription options in a single atomic operation. |
| spock.sub_resync_table | Synchronize a specific table. |
| Miscellaneous Management Functions | |
| spock.table_wait_for_sync | Pause until a table finishes synchronizing. |
| spock.replicate_ddl | Enable DDL replication. |
| spock_version | Returns the Spock version in a major/minor version form: 4.0.10. Defined in the public schema so invoked without the spock. prefix. |
| spock_version_num | Returns the Spock version in a single numeric form: 40010. Defined in the public schema so invoked without the spock. prefix. |
| spock.get_channel_stats | Returns tuple traffic statistics. |
| spock.get_apply_stats | Returns the activity counters of every subscription; the source of the spock.subscription_stats view. |
| spock.get_events | Returns the recent events of the node; the source of the spock.events view. |
| spock.get_monitor_summary | Returns capacity and usage of the spock shared memory structures. |
| spock.get_pending_exceptions | Returns the transactions apply workers are retrying under exception handling. |
| spock.get_system_info | Returns host, operating system and version information of the node. |
| spock.get_slot_groups | Returns the slot groups with attached walsenders. |
| spock.get_subscription_stats | Returns the conflict counters of a subscription (PostgreSQL 18 and later). |
| spock.get_worker_status | Returns every spock worker slot; the source of the spock.worker_status view. |
| spock.get_country | Returns the country code if explicitly set; returns ?? if not set. |
| spock.lag_tracker | Returns a list of slots, with commit_lsn and commit_timestamp for each. |
| spock.repair_mode | Used to manage the state of replication - If set to true, stops replicating statements, including DDL; when false, resumes replication. |
| spock.replicate_ddl | Replicate a specific statement. |
| spock.redact_dsn | Returns a connection string with its password hidden. |
| spock.reset_channel_stats | Reset the channel statistics. |
| spock.reset_events | Clears the event history shown by spock.events. |
| spock.reset_subscription_stats | Resets the activity and conflict counters of one subscription, or of all subscriptions. |
| spock.report_section | Renders the rows of a query as an aligned text table or as one block per row. |
| spock.node_report | Returns the whole node as a text report: versions, settings and every monitoring view. |
| spock_max_proto_version | The highest Spock native protocol supported by the current binary/build. Defined in the public schema so invoked without the spock. prefix. |
| spock_min_proto_version | The lowest build for which this Spock binary is backward compatible. Defined in the public schema so invoked without the spock. prefix. |
| spock.table_data_filtered | Scans the specified table and returns rows that match the row filter from the specified replication set(s). Row filters are added to a replication set when adding a table with repset_add_table. |
| spock.terminate_active_transactions | Terminates all active transactions. |
| spock.wait_slot_confirm_lsn | Wait for the confirmed_flush_lsn of the specified slot, or all logical slots if none given. |
| spock.xact_commit_timestamp_origin | Returns the commit timestamp and origin of the specified transaction. |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1 - Spock Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
You can access the reference pages in this section via online help; at the terminal window, enter:
command_name --help
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.1 - spock.cleanup_resolutions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.cleanup_resolutions() function manually deletes old rows from the
spock.resolutions table.
Synopsis
Description
Deletes rows from spock.resolutions whose log_time is older than the
retention window. Returns the number of rows deleted.
This function is a superuser-only manual trigger for the same cleanup that
the apply worker runs automatically once per day. It is useful for
immediate cleanup via pg_cron or when the apply worker has not been
running.
When days is provided it takes precedence over
spock.resolutions_retention_days, including when the GUC is set to 0
(automatic cleanup disabled). If days is omitted, the GUC value is used;
if the GUC is also 0, the function returns 0 without deleting anything.
Arguments
The function accepts the following argument:
days- Retention window in days. Overridesspock.resolutions_retention_daysfor this call. Pass an explicit value to perform a one-off cleanup when automatic cleanup is disabled (resolutions_retention_days = 0). Default isNULL(use the GUC value).
Example
Delete rows older than the configured retention window:
Delete rows older than 60 days, regardless of the GUC setting:
See Also
spock.resolutions_retention_days
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.2 - spock.gen_slot_name()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.spock_gen_slot_name()
SYNOPSIS
spock.spock_gen_slot_name(dbname name, provider_node name, subscription name)
RETURNS
The generated replication slot name as a name type.
DESCRIPTION
Generates a standardized replication slot name for a Spock subscription.
This function creates a consistent naming convention for replication slots based on the database name, provider node name, and subscription name. The generated name follows Spock’s internal naming scheme to ensure uniqueness and traceability.
This function that performs a calculation without accessing the database or modifying any data. It can be used to predict what slot name Spock will generate for a given subscription configuration.
ARGUMENTS
dbname
The name of the database.
provider_node
The name of the provider node.
subscription
The name of the subscription.
EXAMPLE
The following example executes the function; the database name is postgres, the node name is n1, and the subscription name is sub_n2n1:
postgres=# SELECT spock.spock_gen_slot_name('postgres', 'n1', 'sub_n2n1');
spock_gen_slot_name
--------------------------
spk_postgres_n1_sub_n2n1
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.3 - spock.get_country()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.get_country()
SYNOPSIS
spock.get_country ()
RETURNS
The country code configured for the node as text, or ?? if not set.
DESCRIPTION
Returns the spock.country property that was set during node creation. You can modify the property after configuration; modification requires a server restart to apply the change.
This function retrieves the value of the spock.country configuration parameter for the current session. The country code is typically used in multi-region or geo-distributed replication topologies to identify the geographic location of nodes and apply region-specific routing or filtering rules.
This function does not modify any data.
ARGUMENTS
This function takes no arguments.
EXAMPLE
If the spock.country parameter has not been set, the function returns:
postgres=# SELECT spock.get_country();
get_country
-------------
??
(1 row)
If spock.country is set to US, the function returns:
postgres=# SELECT spock.get_country();
get_country
-------------
US
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.4 - spock.max_proto_version()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock_max_proto_version()
SYNOPSIS
spock_max_proto_version()
RETURNS
The maximum spock protocol version supported by the installed Spock extension as an integer. The protocol version determines compatibility between Spock versions.
DESCRIPTION
Returns the maximum protocol version supported by the Spock extension.
This function queries the Spock extension and returns the highest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use the lower of the two maximum protocol versions. This ensures compatibility between nodes running different Spock releases.
The protocol version is returned as an integer value. Higher numbers indicate newer protocol versions with additional features.
This is a read-only query function that does not modify data. This function is defined in the public schema.
ARGUMENTS
This function takes no arguments.
EXAMPLE
The following command shows that the current version of Spock uses protocol version 4:
postgres=# SELECT spock_max_proto_version();
spock_max_proto_version
-------------------------
4
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.5 - spock.min_proto_version()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock_min_proto_version()
SYNOPSIS
spock_min_proto_version()
RETURNS
The minimum Spock protocol version supported by the installed Spock extension as an integer. The protocol version determines compatibility between Spock versions.
DESCRIPTION
Returns the minimum protocol version supported by the Spock extension.
This function queries the Spock extension and returns the lowest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use a protocol version that falls within the supported range of both nodes. The minimum protocol version defines the lower bound of compatibility - nodes supporting only protocol versions below this minimum cannot replicate with this Spock installation.
The protocol version is returned as an integer value. This minimum version ensures backward compatibility with older Spock releases while still allowing the use of newer protocol features when both nodes support them.
This is a read-only query function that does not modify data. This function is defined in the public schema.
ARGUMENTS
This function takes no arguments.
EXAMPLE
The following command shows that the version of Spock in use is using protocol version 3:
postgres=# SELECT spock_min_proto_version();
spock_min_proto_version
-------------------------
3
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.6 - spock.node_add_interface()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_add_interface()
SYNOPSIS
spock.node_add_interface (node_name name, interface_name name, dsn text)
RETURNS
The OID of the newly created interface. Returns NULL if any argument is NULL.
DESCRIPTION
Adds a new network interface definition to an existing Spock node; the network interface has an associated connection string that is used when the interface is referenced by other nodes.
Interfaces allow a single node to be reachable through multiple connection endpoints. This is commonly used in environments where nodes are accessible through different hostnames, IP addresses, private networks, public networks, or load balancers.
The interface definition consists of a name and a PostgreSQL DSN string that describes how other nodes should connect to this node.
This function writes metadata into the Spock catalogs but does not modify PostgreSQL server configuration or networking settings.
This command must be executed by a superuser.
ARGUMENTS
node_name
The name of an existing Spock node.
interface_name
A unique name for this interface on the node.
dsn
A PostgreSQL connection string that other nodes will use to connect to this node. The user in this string should equal the OS user. This connection string should be reachable from outside and match the one used later in the sub-create command. For example: host=10.1.2.5 port=5432 user=rocky
EXAMPLE
The following example adds an interface named private_net that uses the connection string defined in the last argument of the function call (‘host=10.0.0.10 port=5432 dbname=postgres’):
postgres=# SELECT spock.node_add_interface('n1', 'private_net',
'host=10.0.0.10 port=5432 dbname=postgres');
node_add_interface
--------------------
1239112588
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.7 - spock.node_alter()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_alter()
SYNOPSIS
spock.node_alter (p_location text DEFAULT NULL, p_country text DEFAULT NULL, p_info_patch jsonb DEFAULT NULL)
RETURNS
true on success. Raises an error if p_info_patch is not a JSON object,
or if it contains a tiebreaker key that is not a JSON number, is not a
whole number, or does not fit a 32-bit integer.
DESCRIPTION
Changes the local node’s own location, country, and/or info, merging
p_info_patch into the existing info rather than replacing it. Only
this node’s own row can be altered – there is no node_name argument,
since (unlike spock.node_refresh_info) there is only ever one valid
target: the local node.
Any omitted argument (left NULL) is left unchanged: p_location and
p_country each independently overwrite only if non-NULL, and
p_info_patch is merged key-by-key into the existing info (via ||)
only if non-NULL – an existing key not mentioned in the patch is left
as-is, not removed.
A tiebreaker key inside p_info_patch is validated: it must be a JSON
number (not a string, and not JSON null), a whole number, and fit a
32-bit integer, or the call raises an error and changes nothing. This is
the safe way to change a node’s tiebreaker; see the Tiebreaker section in
conflict_types.md for what the tiebreaker
does and why validation matters here.
This ends in the same UPDATE spock.node that a hand-written UPDATE
would use, so it propagates identically: automatically to every direct
subscriber of this node (see
Automatic node metadata propagation),
with no manual step required. A raw UPDATE spock.node SET ... on this
node’s own row remains fully supported and behaves the same way –
spock.node_alter exists to validate the input and merge info safely,
not to gate access to the underlying table.
ARGUMENTS
p_location
Optional. Replaces this node’s location. Left unchanged if omitted
(or NULL).
p_country
Optional. Replaces this node’s country. Left unchanged if omitted
(or NULL).
p_info_patch
Optional. A JSON object merged into this node’s existing info
(existing keys not mentioned are preserved). Left unchanged if
omitted (or NULL). A tiebreaker key, if present, must be a JSON
number representable as a 32-bit integer.
EXAMPLE
Assign a custom tiebreaker on n1, without disturbing any other info
keys already set:
n1=# SELECT spock.node_alter(p_info_patch => '{"tiebreaker": 42}'::jsonb);
node_alter
------------
t
(1 row)
Every direct subscriber of n1 picks this up automatically – no
spock.node_refresh_info call needed:
n2=# SELECT info->>'tiebreaker' FROM spock.node WHERE node_name = 'n1';
?column?
----------
42
(1 row)
Update location and country together in one call:
n1=# SELECT spock.node_alter(p_location => 'us-east', p_country => 'US');
node_alter
------------
t
(1 row)
An invalid tiebreaker is rejected and changes nothing:
n1=# SELECT spock.node_alter(p_info_patch => '{"tiebreaker": "42"}'::jsonb);
ERROR: invalid "tiebreaker" value "42": must be a JSON number, not a string or null
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.8 - spock.node_create()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_create()
SYNOPSIS
spock.node_create (node_name name, dsn text, location text, country text, info jsonb)
RETURNS
The OID of the newly created Spock node.
DESCRIPTION
Creates a new Spock node definition.
A node represents a PostgreSQL instance that participates in Spock replication. The node definition includes the connection information that other nodes will use to communicate with this node.
Optional metadata fields such as location, country, and info can be provided to describe the node for organizational or management purposes. These values are stored in the Spock catalogs but are not required for replication to function.
This function writes metadata into the Spock catalogs but does not modify Postgres server configuration or networking settings.
This command must be executed by a superuser.
ARGUMENTS
node_name
A unique name for the Spock node.
dsn
A PostgreSQL connection string that other nodes will use to connect to this node.
location
Optional descriptive text indicating the physical or logical location of the node. The default is NULL.
country
Optional country code or name associated with the node. The default is NULL.
info
Optional JSONB field for storing arbitrary metadata about the node. The default is NULL.
A tiebreaker key in this field overrides the node’s default
last-update-wins tiebreaker (otherwise the node’s unique ID). Each
node caches this value locally, populated once when it first learns
about the node. A later change (via spock.node_alter, the
recommended way, or a raw UPDATE) propagates automatically to every
direct subscriber. spock.node_refresh_info updates a node that missed
the change – see the Tiebreaker section in conflict_types.md for
details.
EXAMPLE
In the following example, Spock creates a node named n3, with a connection to a database named ‘inventory’:
inventory=# SELECT spock.node_create('n3','host=10.0.0.12 port=5432 dbname=inventory');
node_create
-------------
9057
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.9 - spock.node_drop_interface()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_drop_interface()
SYNOPSIS
spock.node_drop_interface (node_name name, interface_name name)
RETURNS
true if the interface was dropped successfully.
Raises an ERROR if the interface does not exist, the call has invalid parameters or insufficient privileges, or the interface cannot be removed.
DESCRIPTION
Removes an existing network interface definition from a Spock node.
This function deletes the interface definition from the Spock catalogs. It does not modify PostgreSQL server configuration or networking settings; it only removes Spock’s logical representation of the interface.
Other nodes that were using this interface to connect will no longer be able to use it. To avoid a client error, ensure that no active subscriptions rely on this interface before attempting to remove it.
This function writes metadata into the Spock catalogs but does not modify PostgreSQL server configuration or networking settings.
This command must be executed by a superuser.
ARGUMENTS
node_name
The name of an existing Spock node.
interface_name
The name of the interface to remove from the node.
EXAMPLE
The following example drops an interface named ‘private_net’:
inventory=# SELECT spock.node_drop_interface('n3', 'private_net');
node_drop_interface
---------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.10 - spock.node_drop()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_drop()
SYNOPSIS
spock.node_drop(node_name name, ifexists boolean)
RETURNS
true if the node was dropped successfully.
false if the node did not exist and ifexists was set to true.
ERROR if the call has invalid parameters, if the invoker has insufficient privileges, or the node cannot be removed due to existing dependencies.
DESCRIPTION
Removes an existing Spock node from the cluster metadata.
This function deletes the node definition and all associated metadata from the Spock catalogs. It does not remove any PostgreSQL data directory or stop the PostgreSQL server; it only removes Spock’s logical representation of the node.
If ifexists is set to false (default), an error is raised when the specified node does not exist. If ifexists is true, the function returns false instead of raising an error.
This command must be executed by a superuser and modifies Spock catalog tables.
ARGUMENTS
node_name
The name of the existing Spock node to remove.
ifexists
If true, do not raise an error when the node does not exist; return false instead. Default is false.
EXAMPLE
The following function call drops a node named ’n3':
inventory=# SELECT spock.node_drop('n3');
node_drop
-----------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.11 - spock.node_info()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_info()
SYNOPSIS
spock.node_info()
RETURNS
A record containing information about the local Spock node:
- node_id is the OID of the node.
- node_name is the name of the node.
- sysid is the system identifier.
- dbname is the database name.
- replication_sets is the available replication sets.
- location is the node location (if set).
- country is the node country (if set).
- info is additional metadata stored in JSONB format (if set).
DESCRIPTION
Returns information about the local Spock node.
This function queries the Spock catalogs and returns metadata about the current node, including its identifier, name, database information, and any optional descriptive fields that were set during node creation.
This is a read-only query function that does not modify data.
ARGUMENTS
This function takes no arguments.
EXAMPLE
postgres=# SELECT * FROM spock.node_info();
-[ RECORD 1 ]----+--------------------------------------
node_id | 49708
node_name | n1
sysid | 7600444661598442547
dbname | postgres
replication_sets | "default",default_insert_only,ddl_sql
location |
country |
info |
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.12 - spock.node_refresh_info()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.node_refresh_info()
SYNOPSIS
spock.node_refresh_info (p_node_name name DEFAULT NULL)
RETURNS
true if the refresh (or, with no argument, every refresh attempted)
succeeded; false if one or more nodes could not be refreshed when called
with no argument. Raises an error if called with a specific node_name
that does not exist or that names the local node, or if refreshing that
node fails for any reason – including an unreachable or misconfigured
interface, a dsn that now answers as a different node, or any other error
from the remote fetch.
DESCRIPTION
Re-fetches a known peer node’s location, country, and info (including
any tiebreaker key within info) directly from that node, and overwrites
this node’s locally cached copy.
spock.node is a local catalog: each node populates its row for a peer
once, either when that node is created or when a subscription to it is
first created. A peer’s later location/country/info change – most
commonly to assign a custom tiebreaker and resolve an equal-tiebreaker
collision – propagates automatically to every node that subscribes to
that peer directly (see
Automatic Node Metadata Propagation),
with no call to this function needed. The message is not forwarded, and a
node normally has a row for a peer only through its own subscription to it,
so a cascade node that does not subscribe to the changed peer has no row to
refresh. This function is needed when a node’s cached row missed an update,
for example because the transaction carrying it was skipped or discarded,
and to force a specific peer’s info to be re-fetched on demand.
spock.sub_resync_table() warns when the provider’s row differs from the
cached one. See the Tiebreaker section in
conflict_types.md for why this matters and why
spock.node is not simply replicated wholesale.
Called with a specific node_name, only that node’s row is refreshed and
any failure refreshing it is reported as an error. Called with no
argument, every known node other than the local one is refreshed on a
best-effort basis: a node that fails to refresh for any reason logs a
WARNING and does not stop the others from being refreshed, and the
overall return value is false if any node failed.
This command must be executed by a superuser.
ARGUMENTS
p_node_name
Optional. The name of a single peer node to refresh. If omitted (or NULL), every node other than the local one is refreshed.
EXAMPLE
After assigning a custom tiebreaker on n1 to resolve a collision:
n1=# UPDATE spock.node SET info = COALESCE(info, '{}'::jsonb) ||
'{"tiebreaker": 42}' WHERE node_name = 'n1';
Refresh that on every other node:
n2=# SELECT spock.node_refresh_info('n1');
node_refresh_info
--------------------
t
(1 row)
Or refresh everything this node knows about in one call:
n3=# SELECT spock.node_refresh_info();
node_refresh_info
--------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.13 - spock.replicate_ddl()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.replicate_ddl()
SYNOPSIS
spock.replicate_ddl (command text[], replication_sets text[], search_path text, role text)
RETURNS
true if the DDL command was successfully executed and queued for replication.
false if the command execution fails or replication queueing fails.
When called with a text array, returns a set of boolean values, one for each command in the array.
DESCRIPTION
Executes DDL commands locally and queues them for replication to subscribers.
This function runs the specified DDL command on the local node first, then adds it to the replication queue for execution on all subscriber nodes that are subscribed to one of the specified replication sets.
The function accepts either a single DDL command as text or an array of DDL commands. When provided with an array, each command is executed and queued sequentially.
The search_path and role parameters allow you to control the execution context for the DDL command on both the provider and subscriber nodes.
This function writes to the replication queue and modifies the database schema locally before propagating changes.
This command must be executed by a user with sufficient privileges to execute the DDL command.
ARGUMENTS
command
A DDL command as text, or an array of DDL commands to execute and replicate.
replication_sets
An array of replication set names. Only subscribers subscribed to one of these sets will receive and execute the DDL. Default is ‘{ddl_sql}’.
search_path
The schema search path to use when executing the DDL command. Default is the current session’s search_path setting.
role
The role (user) under which to execute the DDL command. Default is the current user.
EXAMPLES
The following command creates a table and instructs Spock to replicate the DDL to other nodes:
postgres=# SELECT spock.replicate_ddl('CREATE TABLE users (id SERIAL PRIMARY KEY,
name TEXT)');
-[ RECORD 1 ]-+--
replicate_ddl | t
The following command alters the table adding a column, and instructs Spock to replicate the DDL to other nodes:
postgres=# SELECT spock.replicate_ddl('ALTER TABLE users ADD COLUMN email TEXT',
'{default,ddl_sql}');
-[ RECORD 1 ]-+--
replicate_ddl | t
The following command creates a table and an index on the tables, and instructs Spock to replicate DDL to other nodes:
postgres=# SELECT spock.replicate_ddl(ARRAY['CREATE TABLE orders (id SERIAL)',
'CREATE INDEX ON orders(id)']);
-[ RECORD 1 ]-+--
replicate_ddl | t
-[ RECORD 2 ]-+--
replicate_ddl | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.14 - spock.repset_add_all_seqs()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_all_seqs()
SYNOPSIS
spock.repset_add_all_seqs (set_name name, schema_names text[], synchronize_data boolean)
RETURNS
true if all sequences were successfully added to the replication set.
ERROR if the call has invalid parameters, insufficient privileges, or the operation fails.
DESCRIPTION
Adds all existing sequences from the specified schemas to a replication set.
This function registers all sequence objects found in the given schemas with the specified replication set. Only sequences that exist at the time of execution are added; sequences created afterward must be added separately using spock.repset_add_seq().
The synchronize_data parameter controls whether sequence values are immediately synchronized across nodes. When set to true, the current value of each sequence is propagated to subscribers.
This function writes metadata into the Spock catalogs to track which sequences are part of the replication set.
This command must be executed by a superuser.
Warning: If you’re deploying a multi-master replication scenario, we recommend that you not add sequences to a replication set. Instead, use Snowflake Sequences to manage sequences in a distributed environment and avoid conflicts.
ARGUMENTS
set_name
The name of an existing replication set.
schema_names
An array of schema names from which all sequences will be added.
synchronize_data
If true, synchronize the current value of each sequence immediately. Default is false.
EXAMPLE
You can specify one or more schemas in the call to repset_add_all_seqs. The first command adds the sequences in the ‘public’ schema to the ‘default’ replication set:
postgres=# SELECT spock.repset_add_all_seqs('default', ARRAY['public']);
-[ RECORD 1 ]-------+--
repset_add_all_seqs | t
The following command adds all sequences in the schemas named ‘public’ and ‘alice’ to the ‘default’ replication set:
postgres=# SELECT spock.repset_add_all_seqs('default', ARRAY['public', 'alice'],true);
-[ RECORD 1 ]-------+--
repset_add_all_seqs | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.15 - spock.repset_add_all_tables()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_all_tables()
SYNOPSIS
spock.repset_add_all_tables (set_name name, schema_names text[], synchronize_data boolean)
RETURNS
true if every replicatable table was added to the replication set.
false if the call has invalid parameters, insufficient privileges, or the operation fails.
DESCRIPTION
Adds all existing tables from the specified schemas to a replication set.
This function registers all table objects found in the given schemas with the specified replication set. Only tables that exist at the time of execution are added; tables created afterward must be added separately using spock.repset_add_table().
A table that cannot be replicated is skipped and reported with a WARNING naming its schema and table; the remaining tables are still added. A table is skipped when the replication set replicates UPDATEs or DELETEs and the table has no index-based replica identity, or when the table belongs to an extension listed in spock.reserved_object. A schema listed in spock.reserved_object is reported once and passed over as a whole.
A replication set that replicates UPDATEs or DELETEs has to locate the affected row on the subscriber, so it can only take tables with an index-based replica identity — a PRIMARY KEY, or a unique index on NOT NULL columns nominated with ALTER TABLE … REPLICA IDENTITY USING INDEX. Note that REPLICA IDENTITY FULL and REPLICA IDENTITY NOTHING do not qualify, even when the table has a PRIMARY KEY. Tables without an index-based replica identity can be added to a set that replicates only INSERTs and TRUNCATEs.
Unlike spock.repset_add_table(), which raises an error when the table cannot be replicated, this function never refuses the whole call on account of a single relation. A schema that does not exist is still an error.
Views, materialized views, sequences, and UNLOGGED and TEMPORARY tables are not considered at all.
Partitioned tables and their partitions are collected independently, each in its own right, and each is checked separately. ALTER TABLE … REPLICA IDENTITY does not cascade to partitions in any supported PostgreSQL version, so a partitioned table and its partitions can differ here: a partition may be skipped while its parent is added, or the reverse. Spock resolves replication set membership per relation, so a skipped partition means changes to the rows stored in that partition are not replicated, even when the parent is a member.
The synchronize_data parameter controls whether existing table data is immediately synchronized to subscribers. When set to true, a full table copy is initiated for each table on all subscribers subscribed to the replication set.
This function writes metadata into the Spock catalogs to track which tables are part of the replication set.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
schema_names
An array of schema names from which all tables will be added.
synchronize_data
If true, synchronize existing table data to all subscribers immediately. Default is false.
EXAMPLE
Specify the names of one or more schemas in an array to add all of the tables in the schemas to the specified replication set; the following command adds all of the tables in the public schema to the default replication set:
postgres=# SELECT spock.repset_add_all_tables('default', ARRAY['public']);
-[ RECORD 1 ]---------+--
repset_add_all_tables | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.16 - spock.repset_add_partition()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset-add-partition ()
SYNOPSIS
spock.repset_add_partition ( parent regclass, partition regclass, row_filter text)
RETURNS
0 if the parent table is not a partitioned table or if all partitions are already in the replication sets.
A positive integer indicating the count of partitions successfully added to replication sets.
DESCRIPTION
Adds a partition of a table to the same replication set(s) as its parent table.
This function is used when working with partitioned tables to ensure that new or existing partitions are properly included in replication. If the partition argument is omitted, Spock automatically discovers and adds all partitions of the specified parent table.
An optional row_filter can be supplied to limit which rows from the partition are replicated.
This function writes metadata into the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
parent
The parent partitioned table, specified as a regclass.
partition
A specific partition table to add. If omitted, all partitions of the parent are added. The default is NULL.
row_filter
An optional SQL expression used to filter which rows from the partition are replicated. The default is NULL.
EXAMPLE
Add all four partitions of a parent table (named ‘public.sales_parent’) to the replication set to which the parent belongs:
SELECT spock.repset_add_partition('public.sales_parent');
-[ RECORD 1 ]--------+--
repset_add_partition | 4
Add a specific partition (named public.sales_2026_q1) to the replication set to which the parent table belongs:
postgres=# SELECT spock.repset_add_partition(
'public.sales_parent',
'public.sales_2026_q1',
'region = ''US'''
);
-[ RECORD 1 ]--------+--
repset_add_partition | 1
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.17 - spock.repset_add_seq()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_seq()
SYNOPSIS
spock.repset_add_seq ( set_name name, relation regclass, synchronize_data boolean)
RETURNS
- true if the sequence was successfully added to the replication set.
- Raises an ERROR if the sequence is already a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Adds a sequence to an existing Spock replication set.
Once added, changes to the sequence value are replicated to subscribers that are subscribed to the replication set. This ensures that nextval operations remain consistent across nodes in a multi-master environment.
If synchronize_data is true, the current sequence value is immediately synchronized to all subscribers.
This function updates metadata stored in the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The sequence to add, specified as a regclass (for example, ‘public.my_sequence’).
synchronize_data
If true, the current sequence value is synchronized to all subscribers. The default is false.
EXAMPLE
Add a sequence (named public.sales_order_no_seq) to the ‘default’ replication set:
postgres=# SELECT spock.repset_add_seq('default', 'public.sales_order_no_seq');
repset_add_seq
----------------
t
(1 row)
Add a sequence (named public.sales_invoice_no_seq) and synchronize its current value:
postgres=# SELECT spock.repset_add_seq(
'default',
'public.sales_invoice_no_seq',
synchronize_data := true
);
repset_add_seq
----------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.18 - spock.repset_add_table()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_add_table()
SYNOPSIS
spock.repset_add_table ( set_name name, relation regclass, synchronize_data boolean, columns text[], row_filter text, include_partitions boolean )
RETURNS
- true if the table was successfully added to the replication set.
- Raises an ERROR if the table is already a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Adds a specific table to an existing Spock replication set.
This function allows fine-grained control over what data is replicated by optionally specifying:
- A subset of columns to replicate.
- A row filter to restrict which rows are replicated.
- Whether partitions of a partitioned table should also be included.
If synchronize_data is set to true, existing table data is copied to all subscribers that are subscribed to this replication set. Otherwise, only future changes are replicated.
When used with partitioned tables, include_partitions controls whether child partitions are automatically included in the replication set.
This function writes metadata into the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The table to add, specified as a regclass (for example, ‘public.mytable’).
synchronize_data
If true, existing table data is synchronized to all subscribers. Default is false.
columns
An optional list of column names to replicate. If NULL, all columns are replicated.
row_filter
An optional SQL WHERE clause used to filter which rows are replicated.
include_partitions
If true and the table is partitioned, all partitions are included automatically. Default is true.
EXAMPLE
The following command adds a table named public.accounts to the demo_repset replication set with full replication:
SELECT spock.repset_add_table('demo_repset', 'public.accounts');
The following command adds a table named public.accounts to the demo_repset replication set, and synchronizes existing data:
SELECT spock.repset_add_table('demo_repset',
'public.accounts',
synchronize_data := true);
The following command adds only specific columns (id and balance) from the public.accounts table to the demo_repset replication set, and filters the rows:
SELECT spock.repset_add_table('demo_repset',
'public.accounts',
columns := ARRAY['id','balance'],
row_filter := 'balance > 0');
WARNING: Use caution when synchronizing data with a valid row filter.
Using synchronize_data=true with a valid row_filter is usually a
one-time operation for a table. Executing it again with a modified
row_filter won’t synchronize data to the subscriber. You may need to call
spock.sub_resync_table() to fix it.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.19 - spock.repset_alter()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_alter()
SYNOPSIS
spock.repset_alter ( set_name name, replicate_insert boolean, replicate_update boolean, replicate_delete boolean, replicate_truncate boolean )
RETURNS
The OID of the altered replication set.
DESCRIPTION
Modifies the replication behavior of an existing Spock replication set.
Each replication set defines which types of table operations are replicated to subscribers. This function allows you to change those behaviors after the set has been created.
Any argument left as NULL will retain its current setting. Only the specified operation types are modified.
This function updates metadata in the Spock catalogs and does not change PostgreSQL server configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
replicate_insert
If true, INSERT operations are replicated; the default is NULL.
replicate_update
If true, UPDATE operations are replicated; the default is NULL.
replicate_delete
If true, DELETE operations are replicated; the default is NULL.
replicate_truncate
If true, TRUNCATE operations are replicated; the default is NULL.
EXAMPLE
The following command enables all operations in the demo_repset replication set:
postgres=# SELECT spock.repset_alter('demo_repset',
replicate_insert := true,
replicate_update := true,
replicate_delete := true,
replicate_truncate := true);
repset_alter
--------------
3356172311
(1 row)
The following command disables DELETE and TRUNCATE replication in the audit_only replication_set:
postgres=# SELECT spock.repset_alter('audit_only',
replicate_delete := false,
replicate_truncate := false);
repset_alter
--------------
3744767607
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.20 - spock.repset_create()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_create()
SYNOPSIS
spock.repset_create ( set_name name, replicate_insert boolean = true, replicate_update boolean = true, replicate_delete boolean = true, replicate_truncate boolean = true )
RETURNS
The OID of the newly created replication set.
DESCRIPTION
Creates a new Spock replication set.
A replication set defines which types of table operations are replicated to subscribers. Tables can later be added to this replication set with other Spock functions.
By default, all data modification operations are replicated; INSERT, UPDATE, DELETE, and TRUNCATE.
You can selectively disable specific operation types when creating the set.
This function writes metadata into the Spock catalogs but does not alter any PostgreSQL server configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The unique name for the replication set.
replicate_insert
If true (the default), INSERT operations are replicated.
replicate_update
If true (the default), UPDATE operations are replicated.
replicate_delete
If true (the default), DELETE operations are replicated.
replicate_truncate
If true (the default), TRUNCATE operations are replicated.
EXAMPLE
The following example creates a replication set named demo_repset; all operations are replicated to the set:
postgres=# SELECT spock.repset_create('demo_repset');
repset_create
---------------
3356172311
(1 row)
The following command creates a replication set named audit_only; only INSERT and UPDATE statements are replicated:
postgres=# SELECT spock.repset_create('audit_only',
replicate_delete := false,
replicate_truncate := false);
repset_create
---------------
3744767607
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.21 - spock.repset_drop()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_drop()
SYNOPSIS
spock.repset_drop (set_name name, ifexists boolean)
RETURNS
true if the replication set was successfully dropped.
false if the replication set does not exist and ifexists is true.
ERROR if the replication set does not exist and ifexists is false.
DESCRIPTION
Drops an existing replication set.
This function removes a replication set from the Spock configuration. When a replication set is dropped, all table, sequence, and DDL memberships associated with it are removed. However, the actual tables and sequences themselves remain in the database - only their association with the replication set is deleted.
Dropping a replication set does not affect existing subscriptions that reference it, but those subscriptions will stop receiving changes for objects that were in the dropped replication set. Subscriptions can be modified to remove the dropped replication set using spock.sub_remove_repset().
The ifexists parameter controls error-handling behavior for the function; when set to true, the function returns false if the replication set does not exist instead of raising an error. This is useful in situations where the replication set may or may not be present.
This function modifies the Spock catalogs but does not modify any user data or the Postgres server configuration.
ARGUMENTS
set_name
The name of the replication set to drop.
ifexists
If true, the function returns false instead of raising an error when the replication set does not exist. Defaults to false.
EXAMPLE
The following command drops a replication set named demo_repset; it does not raise an error if the set does not exist:
postgres=# SELECT spock.repset_drop('demo_repset', true);
repset_drop
-------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.22 - spock.repset_remove_partition()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_remove_partition()
SYNOPSIS
spock.repset_remove_partition (parent regclass, partition regclass)
RETURNS
The number of partitions removed from replication sets as an integer.
DESCRIPTION
Removes a partition or all partitions of a partitioned table from the replication sets that include the parent table.
This function removes partition tables from replication without affecting the parent table’s replication membership. When a specific partition is provided, only that partition is removed. When the partition parameter is NULL, all partitions of the parent table are removed from replication.
This is useful when you want to exclude specific partitions from replication while keeping the parent table and other partitions replicated. For example, you might want to replicate recent partitions but not historical data stored in older partitions.
Removing a partition from replication does not drop the partition table itself - it only removes the partition from the replication sets. The partition remains in the database and can still be accessed locally.
The function returns the count of partitions that were actually removed from replication sets. If no partitions were removed (because they were not in any replication sets), it returns 0.
This function modifies the Spock catalogs but does not modify any user data or PostgreSQL server configuration.
ARGUMENTS
parent
The parent partitioned table whose partition(s) should be removed from replication.
partition
The specific partition to remove from replication. If NULL, all partitions of the parent table are removed. Defaults to NULL.
EXAMPLE
SELECT spock.repset_remove_partition('public.mytable',
'public.mytable_202012');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.23 - spock.repset_remove_seq()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_remove_seq ()
SYNOPSIS
spock.repset_remove_seq ( set_name name, relation regclass)
RETURNS
- true if the sequence was successfully removed from the replication set.
- Raises an ERROR if the sequence is not a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Removes a sequence from an existing Spock replication set.
After removal, changes to the sequence value are no longer replicated to subscribers of the replication set.
This function updates metadata stored in the Spock catalogs and does not modify PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The sequence to remove, specified as a regclass (for example, ‘public.my_sequence’).
EXAMPLE
Remove a sequence (public.orders_id_seq) from a replication set (demo_repset):
postgres=# SELECT spock.repset_remove_seq('demo_repset', 'public.orders_id_seq');
repset_remove_seq
-------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.24 - spock.repset_remove_table()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_remove_table ()
SYNOPSIS
spock.repset_remove_table ( set_name name, relation regclass, include_partitions boolean)
RETURNS
- true if the table was successfully removed from the replication set.
- Raises an ERROR if the table is not a member of the replication set, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Removes a table from an existing Spock replication set. After removal, changes to this table will no longer be replicated to subscribers that are subscribed to the replication set.
If the table is partitioned, the include_partitions argument controls whether all child partitions are also removed from the replication set.
This function updates metadata stored in the Spock catalogs and does not modify the PostgreSQL configuration.
This command must be executed by a superuser.
ARGUMENTS
set_name
The name of an existing replication set.
relation
The table to remove, specified as a regclass (for example, ‘public.mytable’).
include_partitions
If true and the table is partitioned, all partitions are also removed from the replication set. Default is true.
EXAMPLE
Remove a table (public.users) from the default replication set:
postgres=# SELECT spock.repset_remove_table('default', 'public.users');
repset_remove_table
---------------------
t
(1 row)
Remove a partitioned table named public.sales_parent from the default replication set without removing its partitions:
postgres=# SELECT spock.repset_remove_table('default',
'public.users',
include_partitions := false);
---------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.25 - spock.repset_show_table()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.repset_show_table()
SYNOPSIS
spock.repset_show_table (relation regclass, repsets text[])
RETURNS
A record containing detailed information about how a table is configured for replication:
- relid is the OID of the table relation.
- nspname is the schema name of the table.
- relname is the table name.
- att_list is an array of column names included in replication.
- has_row_filter is true if a row filter is applied to the table.
- relkind is the relation kind (‘r’ for regular table, ‘p’ for partitioned table).
- relispartition is true if the table is a partition of a partitioned table.
DESCRIPTION
Returns detailed replication configuration information for a specific table within the specified replication sets.
This function queries how a table is configured for replication across one or more replication sets. It shows which columns are included in replication, whether row filtering is applied, and metadata about the table type and partition status.
The att_list field shows the specific columns that will be replicated. If all columns are replicated, this will contain all column names. If column filtering was configured when the table was added to a replication set, only the specified columns appear in this list.
The has_row_filter field indicates whether a row filter expression is applied to the table, which would limit which rows are replicated based on custom criteria.
The repsets parameter allows you to check the table’s configuration across multiple replication sets. The function returns information based on how the table is configured in those sets.
This is a read-only query function that does not modify any data.
ARGUMENTS
relation
The table to query information about.
repsets
An array of replication set names to check the table’s configuration within.
EXAMPLE
The following command shows detailed information about the public.invoices table:
postgres=# SELECT * FROM spock.repset_show_table('public.invoices',
ARRAY['default', 'ddl_sql']);
-[ RECORD 1 ]--+-----------------------------------------
relid | 17241
nspname | public
relname | invoices
att_list | {order_id,customer_id,order_date,amount}
has_row_filter | f
relkind | r
relispartition | f
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.26 - spock.sub_add_repset()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_add_repset()
SYNOPSIS
spock.sub_add_repset (subscription_name name, replication_set name)
RETURNS
true if the replication set was successfully added.
Raises an ERROR if the subscription does not exist, the replication set is already attached, or the call has invalid parameters or insufficient privileges.
DESCRIPTION
Adds a replication set to an existing subscription.
This function modifies a subscription to begin receiving changes from an additional replication set on the provider node. The subscription will start consuming events from the newly added replication set immediately.
This operation does not perform data synchronization. It only activates the consumption of future events from the replication set. If you need to synchronize existing data from the replication set, you must handle that separately.
This function writes metadata into the Spock catalogs.
Returns NULL if any argument is NULL.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of an existing subscription.
replication_set
The name of the replication set to add to the subscription.
EXAMPLE
The following example adds a replication set named audit_only to a subscription named sub_n2_n1:
postgres=# SELECT spock.sub_add_repset('sub_n2_n1', 'audit_only');
-[ RECORD 1 ]--+--
sub_add_repset | t
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.27 - spock.sub_alter_interface()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_alter_interface()
SYNOPSIS
spock.sub_alter_interface (subscription_name name, interface_name name)
RETURNS
true if the interface was successfully changed.
Raises an ERROR if the subscription or interface does not exist, or if the call has invalid parameters or insufficient privileges.
DESCRIPTION
Changes the network interface used by a subscription to connect to its provider node.
This function modifies an existing subscription to use a different interface when establishing the replication connection to the provider. The specified interface must already exist on the provider node.
This is useful for switching between different network paths, such as moving from a public network to a private network connection, or switching to a different hostname or IP address for the same provider node.
The subscription connection will be restarted using the new interface.
This function writes metadata into the Spock catalogs.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of an existing subscription.
interface_name
The name of an existing interface on the provider node.
EXAMPLE
The following example modifies the interface used when connecting to the replication cluster to use the connection string associated with an interface named private_net:
postgres=# SELECT spock.sub_alter_interface('sub_n2_n1', 'private_net');
sub_alter_interface
---------------------
t
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.28 - spock.sub_alter_options()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_alter_options()
SYNOPSIS
spock.sub_alter_options (subscription_name name, options jsonb)
RETURNS
true if the
optionsobject contained at least one key; the Spock catalog is updated and the apply worker is signalled to restart.false if the
optionsobject was empty ({}); the catalog is not touched and the apply worker is not restarted.Raises an ERROR if the subscription does not exist, if
optionsis not a JSON object, if an unrecognised key is supplied, or if any option value fails validation.
DESCRIPTION
Changes one or more options on an existing subscription in a single atomic operation.
Only the keys present in the options object are modified; omitted
options retain their current values. If the object is empty ({}), the
function returns false without touching the catalog or restarting the
apply worker.
When at least one key is present in options, the function writes the
new values to the Spock catalog and signals the apply worker to restart
so that they take effect. The caller can use spock.sub_show_status()
or spock.sub_wait_for_sync() to confirm the worker has restarted and
reached replicating status.
ARGUMENTS
subscription_name
The name of an existing subscription.
options
A JSON object whose keys are the option names to change. Unrecognised keys raise an error. Supported keys:
forward_origins
A JSON array of origin names whose transactions the subscriber should apply or receive based on their origin. The only accepted element is the string “all”. Pass an empty array ([]) to disable origin forwarding.
See Origin Forwarding for the restriction on combining this with other enabled subscriptions.
apply_delay
A PostgreSQL interval string (e.g. “2 seconds”, “500ms”, “0”) that sets how long the apply worker waits before applying each transaction. The value must be a string; passing a bare number raises an error.
skip_schema
A JSON array of schema names to exclude from apply. Pass an empty array ([]) to clear the exclusion list.
EXAMPLE
Set a 2-second apply delay:
postgres=# SELECT spock.sub_alter_options('sub_n2_n1',
'{"apply_delay": "2 seconds"}');
sub_alter_options
-------------------
t
(1 row)
Enable forwarding of all origins and exclude the audit schema in a
single call:
postgres=# SELECT spock.sub_alter_options('sub_n2_n1',
'{"forward_origins": ["all"], "skip_schema": ["audit"]}');
sub_alter_options
-------------------
t
(1 row)
No-op call (empty object); returns false without restarting the worker:
postgres=# SELECT spock.sub_alter_options('sub_n2_n1', '{}');
sub_alter_options
-------------------
f
(1 row)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.29 - spock.sub_alter_skiplsn()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_alter_skiplsn()
SYNOPSIS
spock.sub_alter_skiplsn (subscription_name name, lsn pg_lsn) RETURNS boolean
RETURNS
true if the skip LSN was successfully set, false otherwise.
DESCRIPTION
Advances the replication position of an existing subscription to the specified Log Sequence Number (LSN). This is typically used as a recovery operation when a subscription is unable to proceed due to a problematic change in the replication stream. Any changes between the old LSN and the specified LSN will be permanently skipped.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of an existing subscription.
lsn
The Log Sequence Number to which the subscription should advance.
EXAMPLE
SELECT spock.sub_alter_skiplsn('sub_n1_to_n2', '0/16B6A50');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.30 - spock.sub_alter_sync
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_alter_sync() function synchronizes all unsynchronized tables
in all sets in a single operation.
Synopsis
Description
The spock.sub_alter_sync() function synchronizes all unsynchronized tables
in all sets in a single operation. The function copies and synchronizes
tables one by one. The function does not wait for completion before returning
to the caller; use spock.sub_wait_for_sync() to wait for completion.
Arguments
The function accepts the following arguments:
- The
subscription_nameargument specifies the name of an existing subscription. - The
truncateargument accepts a boolean value; when set totrue, the function truncates tables before copying, and the default value isfalse.
Example
In the following example, the spock.sub_alter_sync() function synchronizes
all unsynchronized tables for a subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.31 - spock.sub_create()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_create()
SYNOPSIS
spock.sub_create (subscription_name name, provider_dsn text, replication_sets text[], synchronize_structure boolean, synchronize_data boolean, forward_origins text[], apply_delay interval, force_text_transfer boolean, enabled boolean, skip_schema text[])
RETURNS
The OID of the newly created subscription.
DESCRIPTION
Creates a subscription from the current node to a provider node.
This function establishes a replication subscription that allows the current (subscriber) node to receive changes from the specified provider node. The subscription defines which replication sets to subscribe to and how to handle initial synchronization.
The command returns immediately without waiting for the subscription to complete its initialization. Use spock.sub_wait_for_sync() to wait for the subscription to finish synchronizing and begin replicating.
The subscription_name is used as the application_name for the replication connection, making it visible in pg_stat_replication. This can be useful for monitoring and for configuring synchronous_standby_names in synchronous replication scenarios.
This function writes metadata into the Spock catalogs and initiates a replication connection to the provider.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
A unique name for the subscription. Must be unique across the cluster. This name appears in pg_stat_replication as application_name.
provider_dsn
A PostgreSQL connection string specifying how to connect to the provider node.
replication_sets
An array of replication set names to subscribe to. Accepted values are default, default_insert_only, ddl_sql.
synchronize_structure
If true, synchronize table and schema structure from the provider before starting replication. Default is false.
synchronize_data
If true, perform an initial data copy for all tables in the subscribed replication sets. Default is false.
forward_origins
Controls which changes to replicate based on their origin. Use ‘{}’ to
only replicate changes originating locally on the provider node (origin ID 0,
i.e. not already replicated in from another node — useful for bidirectional
replication to avoid forwarding changes in a loop). Use {all} to replicate all
changes regardless of origin. The default is {} (local-origin changes only).
See Origin Forwarding for the restriction on combining this with other enabled subscriptions.
apply_delay
An interval specifying how long to delay applying changes from the provider. Useful for delayed standby scenarios. Default is ‘0’.
force_text_transfer
If true, replicate all columns using text representation. This is slower but allows type conversions on the subscriber. Default is false.
enabled
If true, the subscription is enabled immediately. If false, the subscription is created but not activated. Default is true.
skip_schema
An array of schema names to exclude from structure and data synchronization. Default is ‘{}’ (no schemas skipped).
EXAMPLE
SELECT spock.sub_create('sub_n2_n1',
'host=127.0.0.1 port=5432 dbname=postgres');
SELECT spock.sub_create('sub_n2_n1',
'host=10.0.0.10 port=5432 dbname=postgres',
replication_sets := '{default}',
synchronize_structure := true,
synchronize_data := true);
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.32 - spock.sub_disable
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_disable() function disables a subscription and disconnects
from the provider.
Synopsis
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.immediate- Iftrue, the subscription is disabled immediately; otherwise it is disabled at the end of the current transaction. The default isfalse.
Example
In the following example, the spock.sub_disable() function disables a
subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.33 - spock.sub_drop()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.sub_drop()
SYNOPSIS
spock.sub_drop (subscription_name name, ifexists boolean)
RETURNS
The OID of the dropped subscription.
DESCRIPTION
Disconnects and removes a subscription from the cluster.
This function terminates the replication connection for the specified subscription and removes all associated metadata from the Spock catalogs. It does not affect data that has already been replicated to the subscriber.
If ifexists is set to false (default), an error is raised when the specified subscription does not exist. If ifexists is true, the function returns successfully without error.
Returns NULL if any argument is NULL.
This command must be executed by a superuser.
ARGUMENTS
subscription_name
The name of the existing subscription to remove.
ifexists
If true, do not raise an error when the subscription does not exist. Default is false.
EXAMPLE
SELECT spock.sub_drop('sub_n2_n1');
SELECT spock.sub_drop('sub_n2_n1', true);
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.34 - spock.sub_enable
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_enable() function enables a subscription. Replication workers
then resume normal processing for that subscription.
Synopsis
Description
The spock.sub_enable() function enables a subscription.
This fails if another subscription on this node already has origin forwarding active; see Origin Forwarding.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.immediate- Iftrue, the subscription is started immediately; otherwise the subscription will be started only at the end of the current transaction. The default isfalse.
Example
In the following example, the spock.sub_enable() function enables a
subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.35 - spock.sub_remove_repset
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_remove_repset() function removes a replication set from a
subscription.
Synopsis
Description
The spock.sub_remove_repset() function removes a replication set from a
subscription.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.replication_set- The name of the replication set to remove.
Example
In the following example, the spock.sub_remove_repset() function removes a
replication set named test from a subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.36 - spock.sub_resync_table
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_resync_table() function resynchronizes one existing table.
Synopsis
Description
The spock.sub_resync_table() function resynchronizes one existing table.
After the resynchronization is scheduled, the function compares the cached
spock.node row of the subscription’s provider with the provider’s own row.
If they differ, it raises a WARNING that suggests
spock.node_refresh_info(). The check does not
change spock.node, and a provider that cannot be reached for the check
produces a WARNING without failing the resynchronization.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.relation- The name of an existing table, optionally schema qualified.truncate- Truncate the table before synchronization; the default value istrue. Omitting the argument truncates the target table. Passfalseto keep existing rows. In that case, conflicting incoming rows can cause errors.
Example
In the following example, the spock.sub_resync_table() function
resynchronizes a table named public.users for a subscription named
sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.37 - spock.sub_show_status
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_show_status() function displays the status and basic
information about a subscription.
Synopsis
Returns
A set of rows describing the current state of one or more subscriptions. Each row contains:
- the name of the subscription.
- the current replication status.
- the name of the provider node.
- the connection string used to reach the provider.
- the name of the logical replication slot used by the subscription.
- the replication sets associated with the subscription.
- the origins that are forwarded by this subscription.
Status Values
The following table describes each possible value for the status
column:
| Status | Description |
|---|---|
replicating | The apply worker is running and initial synchronization is complete; changes from the provider are being applied normally. |
initializing | The apply worker is running but initial synchronization has not yet completed; table data is still being copied from the provider. |
disabled | The subscription was explicitly disabled with spock.sub_disable(); the apply worker is not running. |
down | The subscription is enabled but the apply worker is not running; the worker may not have started yet or may have exited unexpectedly. |
unknown | The apply worker is running but no synchronization status record was found; this is a transient state that typically resolves quickly. |
Description
spock.sub_show_status() displays detailed runtime information about
Spock subscriptions on the current node.
If a specific subscription name is provided, only that subscription is
shown. If NULL (the default), the function returns status for all
subscriptions on the node.
This function is useful for monitoring replication health, validating configuration, and verifying which replication sets and origins are in use. The information is derived from Spock catalog metadata and the current state of logical replication workers.
This function does not modify any configuration.
Arguments
subscription_name- The optional name of an existing subscription. If no name is provided, the function shows the status for all subscriptions on the local node.
Example
To display the status of all subscriptions, run:
In the following example, the spock.sub_show_status() function displays the
status of a subscription named sub_n1_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.38 - spock.sub_show_table
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_show_table() function displays the synchronization status of a
table.
Synopsis
Description
The spock.sub_show_table() function shows the synchronization status of a
table.
Arguments
The function accepts the following arguments:
subscription_name- The name of an existing subscription.relation- The name of an existing table, optionally qualified.
Example
In the following example, the spock.sub_show_table() function displays the
synchronization status of a table named test for a subscription named
sub_n2:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.39 - spock.sub_wait_for_sync
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sub_wait_for_sync() function waits until a specified subscription
has completed its initial schema and data synchronization.
Synopsis
Description
The spock.sub_wait_for_sync() function waits until the specified subscription
has completed its initial schema and data synchronization, and any pending
table resynchronizations have finished.
This function blocks the current session until the subscription is fully synchronized. The function monitors both the initial sync phase (if the subscription is newly created) and any tables that are undergoing individual resynchronization due to replication set changes or manual resync operations.
For optimal results, execute spock.wait_slot_confirm_lsn() on the provider
node after making replication set changes that trigger resyncs. This approach
ensures the provider has flushed all necessary changes before checking sync
status on the subscriber. Only after the provider confirms the LSN should you
call spock.sub_wait_for_sync() on the subscriber.
The function will continue waiting indefinitely until synchronization completes, so callers should ensure the subscription is actively processing and that there are no blocking issues preventing sync completion.
Arguments
The function accepts the following argument:
subscription_name- The name of the subscription to monitor for sync completion.
Example
In the following example, the spock.sub_wait_for_sync() function waits for a
subscription named sub_n2_n1 to complete synchronization:
For more information about using subscription synchronization with Zero-Downtime Add Node, see the ZODAN Tutorial.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.40 - spock.sync_event
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sync_event() function creates a synchronization event in the
replication stream and returns its Log Sequence Number (LSN).
Synopsis
Returns
The function returns the Log Sequence Number (LSN) of the created
synchronization event as pg_lsn.
Description
The spock.sync_event() function creates a synchronization event in the
replication stream and returns its LSN.
This function inserts a special synchronization marker into the logical
replication stream at the current write position. The returned LSN identifies
this marker’s location in the write-ahead log and can be used with functions
like spock.wait_slot_confirm_lsn() to verify that subscribers have processed
replication up to this point.
Synchronization events are useful for coordinating activities across multiple nodes in a replication topology. By creating a sync event on a provider and then waiting for subscribers to reach that LSN, you can ensure all nodes have processed a consistent set of changes before proceeding with operations that depend on synchronized state.
The sync event itself does not contain data or modify any tables; the event serves purely as a coordination marker in the replication stream.
This function modifies the replication stream by inserting a sync marker.
Arguments
transactional(optional, defaultfalse) - Whenfalse, the sync event marker is emitted immediately into the WAL stream, independent of the calling transaction. Whentrue, the marker is bound to the calling transaction and is only visible to subscribers if the transaction commits.
Example
In the following example, the spock.sync_event() function creates a
synchronization event and returns the LSN:
For more information about using synchronization events with Zero-Downtime Add Node, see the ZODAN Tutorial.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.41 - spock.sync_seq
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The spock.sync_seq() function synchronizes the current state of a sequence
to all subscribers.
Synopsis
Description
Captures the current value of a sequence on the provider node and pushes it into the replication stream so that subscribers can update their local copy to match. This ensures sequence values remain coordinated across nodes.
This function must be executed on the provider node. The sequence state update is embedded in the transaction where this function is called, and subscribers apply the update when they replicate that transaction.
Replication set filtering applies — only subscribers whose subscriptions include the replication set containing this sequence will receive the update.
Arguments
The function accepts the following argument:
relation- The name of the sequence to synchronize, optionally schema-qualified.
Example
In the following example, the spock.sync_seq() function synchronizes a
sequence named public.sales_order_no_seq:
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.42 - spock.table_wait_for_sync()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.table_wait_for_sync()
SYNOPSIS
spock.table_wait_for_sync (subscription_name name, relation regclass)
RETURNS
void (returns nothing upon successful completion).
DESCRIPTION
Waits until the specified table has completed synchronization for the given subscription.
This function blocks the current session until the specified table finishes its synchronization process. This is useful when you need to ensure a specific table is fully synchronized before proceeding with operations that depend on its data.
Unlike spock.sub_wait_for_sync() which waits for all tables in a subscription to sync, this function targets a single table. This allows for more granular control when monitoring synchronization progress or when only specific tables are critical to downstream operations.
For optimal results, execute spock.wait_slot_confirm_lsn() on the provider node after making replication set changes that trigger table resyncs. This ensures the provider has flushed all necessary changes before checking sync status on the subscriber. Only after the provider confirms the LSN should you call spock.table_wait_for_sync() on the subscriber.
The function will continue waiting indefinitely until the table synchronization completes, so callers should ensure the subscription is actively processing and that there are no blocking issues preventing sync completion.
ARGUMENTS
subscription_name
The name of the subscription to monitor.
relation
The name of the table to wait for, specified as a regclass (can be schema-qualified).
EXAMPLE
SELECT spock.table_wait_for_sync('sub_n2_n1', 'public.mytable');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.43 - spock.version_num()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.spock_version_num()
SYNOPSIS
spock.spock_version_num ()
RETURNS
The version number of the installed Spock extension as an integer.
DESCRIPTION
Returns the version number of the Spock extension as an integer.
This function queries the Spock extension and returns its version encoded as an integer value. The integer format allows for easy version comparison in SQL queries without string parsing.
The integer typically represents the version in a format like XXYYZZ where XX is the major version, YY is the minor version, and ZZ is the patch version. For example, version 3.1.0 might be represented as 30100.
This is a read-only query function that does not modify any data.
ARGUMENTS
This function takes no arguments.
EXAMPLE
The following command returns the current Spock extension version as an integer:
postgres=# SELECT spock.spock_version_num();
-[ RECORD 1 ]-----+------
spock_version_num | 50005
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.44 - spock.version()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.spock_version()
SYNOPSIS
spock.spock_version ()
DESCRIPTION
Returns the Spock version in a human-readable major/minor form (for example, 5.0.5).
EXAMPLE
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.45 - spock.wait_slot_confirm_lsn()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.wait_slot_confirm_lsn()
SYNOPSIS
spock.wait_slot_confirm_lsn (slotname name, target pg_lsn)
RETURNS
void (returns nothing upon successful completion).
DESCRIPTION
Waits until the specified replication slot has confirmed receipt of changes up to the target Log Sequence Number (LSN).
This function blocks the current session until the replication slot’s confirmed flush LSN reaches or exceeds the specified target LSN. This is useful for ensuring that a subscriber has received and acknowledged replication changes before proceeding with subsequent operations.
The confirmed flush LSN represents the position up to which the subscriber has successfully received, applied, and durably stored the replicated changes. This function provides a synchronization mechanism to coordinate activities between the provider and subscriber nodes.
If the replication slot does not exist, the function will raise an error. The function will continue waiting indefinitely until the target LSN is reached, so callers should ensure the target LSN is reachable and that the subscription is actively processing changes.
This function does not modify any data but may block for an extended period depending on replication lag and network conditions.
ARGUMENTS
slotname
The name of the replication slot to monitor.
target
The target Log Sequence Number to wait for. The function returns when the slot’s confirmed flush LSN reaches or exceeds this value.
EXAMPLE
The following command waits for a slot named spock_local_sync_346_79a to confirm that it has received changes to the target LSN (0/3000000):
SELECT spock.wait_slot_confirm_lsn('spock_local_sync_346_79a',
'0/3000000');
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.1.46 - spock.xact_commit_timestamp_origin()
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock.xact_commit_timestamp_origin()
SYNOPSIS
spock.xact_commit_timestamp_origin (xid xid, OUT timestamp timestamptz, OUT roident oid)
RETURNS
A record containing transaction commit information:
- timestamp is the commit timestamp of the transaction.
- roident is the replication origin identifier of the transaction.
DESCRIPTION
Returns the commit timestamp and replication origin identifier for a given transaction ID.
This function queries PostgreSQL’s commit timestamp tracking system to retrieve when a specific transaction was committed and which replication origin it came from. The replication origin identifies the source node in a multi-node replication topology, allowing you to trace where changes originated.
The commit timestamp tracking feature (track_commit_timestamp) must be enabled in PostgreSQL for this function to return meaningful results. If commit timestamp tracking is disabled, the function may return NULL or raise an error.
The replication origin identifier (roident) will be 0 for transactions
committed locally on this node (i.e., not replicated in from another node).
For replicated transactions, it identifies the origin node from which the
changes were received. A NULL result for the timestamp or origin means the
origin metadata is unavailable or unknown (for example, because
track_commit_timestamp was not enabled at the time of the commit) — NULL
is distinct from 0 and does not indicate a local change.
This is a read-only query function that does not modify any data.
ARGUMENTS
xid
The transaction ID to query.
EXAMPLE
SELECT * FROM spock.xact_commit_timestamp_origin('12345'::xid);
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.2 - Management Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
You can use the following settings to manage your replication clusters.
| Command | Description |
|---|---|
| spock.get_country | Returns the country code configured for the node. |
| spock_max_proto_version | Returns the maximum protocol version supported by Spock. Defined in the public schema so invoked without the spock. prefix. |
| spock_min_proto_version | Returns the minimum protocol version supported by Spock. Defined in the public schema, so invoked without the spock. prefix. |
| spock.node_info | Returns information about the local Spock node. |
| spock_version | Returns the version string of the Spock extension. Defined in the public schema so invoked without the spock. prefix. |
| spock_version_num | Returns the version number of Spock as an integer. Defined in the public schema so invoked without the spock. prefix. |
spock.get_country
Use spock.get_country to retrieve the country code configured for the node.
spock.get_country()
Returns the spock.country property that was set during node creation. You
can modify the property after configuration; modification requires a server
restart to apply the change.
This function retrieves the value of the spock.country configuration parameter for the current session. The country code is typically used in multi-region or geo-distributed replication topologies to identify the geographic location of nodes and apply region-specific routing or filtering rules.
This function takes no arguments.
spock_max_proto_version
Use spock_max_proto_version to retrieve the maximum protocol version
supported by Spock.
spock_max_proto_version()
Returns the maximum protocol version supported by the Spock extension.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns the highest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use the lower of the two maximum protocol versions. This ensures compatibility between nodes running different Spock releases.
spock_min_proto_version
Use spock_min_proto_version to retrieve the minimum protocol version
supported by Spock.
spock_min_proto_version()
Returns the minimum protocol version supported by the Spock extension.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns the lowest protocol version number it can use for replication communication. The protocol version determines the features and capabilities available for replication between nodes.
When establishing replication connections between nodes running different Spock versions, the nodes negotiate to use a protocol version that falls within the supported range of both nodes. The minimum protocol version defines the lower bound of compatibility.
spock.node_info
Use spock.node_info to retrieve information about the local Spock node.
spock.node_info()
This function queries the Spock catalogs and returns metadata about the current node, including its identifier, name, database information, and any optional descriptive fields that were set during node creation.
This function takes no arguments.
spock_version
Use spock_version to retrieve the version string of the Spock extension.
spock_version()
Returns the version number of the Spock extension.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns its version as a text string. The version string typically follows semantic versioning format (for example, “4.0.1” or “5.0.4”).
spock_version_num
Use spock_version_num to retrieve the version number of Spock as an
integer.
spock_version_num()
Returns the version number of the Spock extension as an integer.
This function takes no arguments, and is defined in the public
schema so must be invoked without the spock. prefix.
This function queries the Spock extension and returns its version encoded as an integer value. The integer format allows for easy version comparison in SQL queries without string parsing.
The integer typically represents the version in a format like XXYYZZ where XX is the major version, YY is the minor version, and ZZ is the patch version. For example, version 3.1.0 might be represented as 30100.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.3 - Node Management
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Use commands listed in this section to manage the nodes in your replication cluster.
| Command | Description |
|---|---|
| spock.node_add_interface | Add an additional interface to a node. |
| spock.node_create | Create a spock node. |
| spock.node_drop | Drop a spock node. |
| spock.node_drop_interface | Remove an existing interface from a node. |
| spock.node_info | Returns information about the local Spock node. |
| spock.node_alter | Change this node’s own location, country, and/or info (merging info), validating a tiebreaker if one is set. |
| spock.node_refresh_info | Refresh this node’s cached copy of a peer’s (or every peer’s) location, country, and info. |
Creating a Node
To create a node with Spock, connect to the server with psql and use the
spock.node_create command:
Parameters include:
- a name for the node.
- the dsn of the server on which the node resides.
The DSN is similar to a connection string to the node you’re creating.
For example, the DSN to connect to the acctg database with an ip
address of 10.1.1.1, using credentials that belong to carol would
be: host=10.1.1.1 user=carol dbname=acctg.
The location, country, and info are all optional inputs to label nodes
and have a default of null.
For example, the following command:
Creates a node named n1 that connects to the accounting database on
178.12.15.12, authenticating with the credentials of a user named carol.
Dropping a Node
To drop a node with Spock, connect to the server with psql, and use the
spock.node_drop command:
Parameters include:
- the name of the node.
ifexistsis a boolean value that suppresses an error if the node does not exist when set totrue.
For example, the following command:
Drops a node named n1. If the node does not exist, an error message will
be suppressed because ifexists is set to true.
Automatic Node Metadata Propagation
A change to a node’s own location, country, or info – whether via
spock.node_alter or a raw
UPDATE spock.node SET ... WHERE node_id = (SELECT node_id FROM spock.node_info())
– propagates automatically to every node that subscribes to it directly.
No manual step is required for a direct subscriber to pick up the change.
The message is not forwarded through a cascade topology (Node A → Node B →
Node C): only Node B, as A’s direct subscriber, receives A’s change. Node C
normally has no spock.node row for A unless it subscribes to A, so there
is nothing for it to update.
A node that has a row for the changed node but did not apply the message
keeps the old values. This happens when the transaction carrying the message
is skipped (for example with skip_lsn) or discarded by the exception
handling. Run spock.node_refresh_info
on that node to catch up. A table resynchronization does not replay these
messages, but spock.sub_resync_table() warns when the provider’s row
differs from the cached one.
An incoming change is applied only if the node named in the message has
the same node_id locally as the node that sent it. Otherwise it is
skipped and logged as a WARNING: either the name is unknown locally
(rows are never created from these messages), or the name and the
sender’s node_id disagree with the local copy. This is a defensive
check against a corrupted or misconfigured peer, not something normal
operation triggers.
Node Management Functions
You can add and remove nodes dynamically with the following SQL functions.
spock.node_create
Use spock.node_create to create a replication node.
spock.node_create(node_name name, dsn text, location text DEFAULT NULL, country text DEFAULT NULL, info jsonb DEFAULT NULL)
Parameters:
node_nameis the name of the new node; only one node is allowed per database.dsnis the connection string to the node. For nodes that are supposed to be providers, this should be reachable from the subscription nodes.location(optional) is a text label for the node’s physical location.country(optional) is a text label for the node’s country.info(optional) is a JSON object for any additional node metadata. Atiebreakerkey overrides the node’s default conflict-resolution tiebreaker; see the Tiebreaker section in conflict_types.md for how each node caches this independently and what that means for changing it cluster-wide.
spock.node_drop
Use spock.node_drop to drop a replication node.
spock.node_drop(node_name name, ifexists bool)
Parameters:
node_nameis the name of an existing node.ifexistsspecifies the Spock extension behavior with regards to error messages. Iftrue, an error is not thrown when the specified node does not exist. The default isfalse.
spock.node_add_interface
Use spock.node_add_interface to add an interface to a node.
spock.node_add_interface(node_name name, interface_name name, dsn text)
When a node is created, the interface for it is also created using the dsn
specified in the spock.node_create command, and with the same name as the node.
This interface allows adding alternative interfaces with different connection
strings to an existing node.
Parameters:
node_nameis the name of an existing node.interface_nameis the name of a new interface to be added.dsnis the connection string to the node used for the new interface.
spock.node_drop_interface
Use spock.node_drop_interface to remove an existing interface from a node.
spock.node_drop_interface(node_name name, interface_name name)
Parameters:
node_nameis the name of an existing node.interface_nameis the name of an existing interface.
spock.node_info
Use spock.node_info to return information about the local Spock node.
spock.node_info()
This function queries the Spock catalogs and returns metadata about the current node, including its identifier, name, database information, and any optional descriptive fields that were set during node creation.
This is a read-only query function that does not modify data.
Returns one row with the following columns:
| Column | Type | Description |
|---|---|---|
node_id | oid | The object identifier of the local node. |
node_name | text | The name of the local node. |
sysid | text | The PostgreSQL system identifier for this instance. |
dbname | text | The name of the current database. |
replication_sets | text | Comma-separated list of replication sets associated with this node. |
location | text | Optional location label; NULL if not set during node creation. |
country | text | Optional country label; NULL if not set during node creation. |
info | jsonb | Optional JSON metadata; NULL if not set during node creation. |
spock.node_alter
Use spock.node_alter to change the local node’s own location,
country, and/or info, merging info rather than replacing it, with a
tiebreaker key (if present in the patch) validated as a whole JSON
number that fits a 32-bit integer.
spock.node_alter(p_location text DEFAULT NULL, p_country text DEFAULT NULL, p_info_patch jsonb DEFAULT NULL)
Unlike spock.node_refresh_info, this only ever targets the local node –
there is no node-name argument. It ends in the same UPDATE spock.node
that a hand-written UPDATE would use, so it propagates the same way; see
Automatic Node Metadata Propagation
above. See spock_node_alter.md for full
details and examples.
Parameters:
p_location(optional) replaces this node’slocation; left unchanged if omitted.p_country(optional) replaces this node’scountry; left unchanged if omitted.p_info_patch(optional) is merged into this node’s existinginfo; left unchanged if omitted. Atiebreakerkey inside it must be a JSON number representable as a 32-bit integer, or the call raises an error and changes nothing.
spock.node_refresh_info
Use spock.node_refresh_info to refresh this node’s cached copy of a
peer’s location, country, and info (including any tiebreaker key
within info).
spock.node_refresh_info(p_node_name name DEFAULT NULL)
spock.node is a local catalog: each node populates its row for a peer
once, either when that node is created or when a subscription to it is
first created. A direct subscriber picks up a peer’s later changes
automatically – see
Automatic Node Metadata Propagation
above – but the message is not forwarded, and it is lost if the
transaction carrying it is skipped or discarded.
spock.node_refresh_info is the way to catch such a node up on demand, in
bulk for every known peer at once, or to recover a specific peer’s info
without waiting on it to change again. See the Tiebreaker section in
conflict_types.md.
Parameters:
p_node_name(optional) is the name of a single peer node to refresh. If omitted, every node other than the local one is refreshed, best-effort: a node that fails to refresh for any reason (an unreachable or misconfigured interface, a dsn that now answers as a different node, or any other error from the remote fetch) logs a warning rather than aborting the rest.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.4 - Replication Set Management
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Replication sets provide a mechanism to control which tables in the database will be replicated and which actions on those tables will be replicated. Use the following commands to create and manage replication sets.
| Command | Description |
|---|---|
| spock.repset_create | Create a new replication set. |
| spock.repset_alter | Modify an existing replication set. |
| spock.repset_drop | Remove a replication set. |
| spock.repset_add_table | Adds a table to replication set. |
| spock.repset_add_all_tables | Adds all tables in a given schema(s). |
| spock.repset_remove_table | Remove a table from replication set. |
| spock.repset_add_seq | Adds a sequence to a replication set. |
| spock.repset_add_all_seqs | Adds all sequences from the given schemas. |
| spock.repset_remove_seq | Remove a sequence from a replication set. |
| spock.sub_add_repset | Adds a replication set to a subscriber. |
| spock.sub_remove_repset | Removes a replication set from a subscriber. |
Creating a Replication Set
To create a replication set with Spock, connect to the server with psql and
use the spock.repset_create command:
Parameters include:
replication_set_nameis the name of the replication set.
Use the four remaining parameters to specify the content type to replicate:
- when
replicate_insertistrue,INSERTstatements are replicated; the default istrue. - when
replicate_updateistrue,UPDATEstatements are replicated; the default istrue. - when
replicate_deleteistrue,DELETEstatements are replicated; the default istrue. - when
replicate_truncateistrue,TRUNCATEstatements are replicated; the default istrue.
For example, the following command:
Adds a replication set named accts that replicates all statements except
TRUNCATE statements.
Adding a Table to a Replication Set
To add a table to a replication set with Spock, connect to the server with
psql and invoke the spock.repset_add_table command:
Parameters include:
set_nameis the name of an existing replication set.relationis the name or OID of the table to add.synchronize_datais a boolean value that instructs the server to synchronize table data on all related subscribers; the default isfalse.columnsspecifies a list of columns to replicate; the default isNULL(all columns).row_filteris a row filtering expression; the default isNULL(no filtering).include_partitionsis a boolean value; specifytrueto include all partitions; the default istrue.
For example, the following command:
Adds a table named payables to a replication set named accts. Since no
columns are specified, all columns will be replicated.
Reserved Schemas and Extensions
Some schemas and extensions are reserved and are treated specially by Spock.
They are listed in the spock.reserved_object catalog, which is the single
source of truth for three behaviours:
exclude_from_dump: the object is left out of the structure-sync dump used when a subscription synchronizes structure. Restoring these on a subscriber that already has them would fail.block_in_repset: a table in this schema, or belonging to this extension, may not be added to a replication set.replicate_ddl: whenfalse, AutoDDL keeps the object’s DDL node-local – it runs where issued but is not shipped to other nodes. The default istrue.For an extension,
CREATE EXTENSION,ALTER EXTENSION,DROP EXTENSION,COMMENT ON EXTENSIONandSECURITY LABEL ON EXTENSIONare kept local; run them on each node. ADROP EXTENSIONthat names both a node-local extension and a replicated one is refused while DDL replication is on; drop them in separate statements.CREATE EXTENSION ... CASCADEof a replicated extension that requires a node-local one is also refused, even when every required extension is already installed; create the node-local extension on each node first, then run theCREATE EXTENSIONwithoutCASCADE.spock.replicate_ddl()refuses all of these statements for a node-local extension. Whatever a statement on a node-local extension does withCASCADEalso stays on the local node: objects that depend on the extension are dropped only there, and extensions thatCREATE EXTENSION ... CASCADEinstalls are installed only there.A statement that removes a node-local extension without naming it is not caught:
DROP EXTENSION ... CASCADEof an extension it requires,DROP SCHEMA ... CASCADEof a schema it was created in, orDROP OWNED BYits owner. Such a statement replicates, and each peer must then drop the node-local extension from its apply worker. Drop the node-local extension on each node first.For a schema, only DDL whose target schema Spock can identify is kept local:
CREATESCHEMA/TABLE/TABLE AS/SEQUENCE/VIEW/INDEX,ALTER TABLE, andDROPof those object kinds. Other DDL against the schema (for exampleGRANT,COMMENT,TRUNCATE, orALTER ... SET SCHEMA) is not classified and replicates as usual. A singleDROPis kept local only when every object it names is node-local; do not mix a node-local object and a replicated one in oneDROP, as the shipped command cannot be rewritten to drop only the replicated object.
Spock seeds the following built-in rows, and they cannot be removed or modified:
| Object | exclude_from_dump | block_in_repset | replicate_ddl |
|---|---|---|---|
spock | yes | yes | yes |
snowflake | yes | yes | yes |
lolor | yes | no | yes |
coldfront | yes | no | yes |
pgedge_ace (schema only) | yes | yes | no |
spock, snowflake, lolor and coldfront each have both a schema and an
extension row. The replicate_ddl column above is the value on the
schema row. The extension rows have replicate_ddl = true (replicated),
except lolor, whose extension row is false: lolor refuses to be created
or dropped by an apply worker, so CREATE, ALTER and DROP EXTENSION lolor are run on each node instead of being replicated.
exclude_from_dump/block_in_repset apply to both rows.
lolor is excluded from the dump but is intentionally allowed in replication
sets: its tables must replicate so that large objects survive a
DROP EXTENSION on every node, not only where the drop was issued.
coldfront is the pgEdge tiered storage extension. Every node creates its
objects with its own CREATE EXTENSION coldfront, so structure sync leaves
them out. Its tables stay allowed in replication sets because Coldfront adds
several of them to the default set itself, among them the bakery claim
tables and the tiered view registry, to coordinate writes across the mesh.
The cold data behind a tiered view lives in shared Iceberg storage outside
PostgreSQL and is not replicated by Spock.
pgedge_ace is the schema used by the pgEdge ACE utility. It is node-local
configuration/state, not application data: its DDL is kept local for the
classified statement kinds above (replicate_ddl=no), and its tables can
never be added to a replication set (block_in_repset=yes), so
CREATE SCHEMA pgedge_ace and the tables underneath it stay local to the
node where they were issued.
To reserve an additional schema or extension of your own, use
spock.reserved_object_add:
Use spock.reserved_object_remove('ace', 'schema') to drop your own entry.
Reserved objects are node-local configuration: apply the same additions on
each node of the cluster. Operator-added rows are preserved across
pg_dump/pg_restore; the built-in rows are always re-seeded.
Removing a Table from a Replication Set
To remove a table from a replication set with Spock, connect to the server
with psql and invoke the spock.repset_remove_table command:
Parameters include:
set_nameis the name of the replication set in which the table resides.relationis the name or OID of the table that will be removed.include_partitionsis a boolean value; specifytrueto also remove partitions of the partitioned table; the default istrue.
For example, the following command:
Removes a table named payables from a replication set named accts.
Replication Set Management Functions
The following functions are provided for managing replication sets:
spock.repset_create
Use spock.repset_create to create a new replication set.
spock.repset_create(set_name name, replicate_insert bool, replicate_update bool, replicate_delete bool, replicate_truncate bool)
Parameters:
set_nameis the unique name of the set.replicate_insertistrueifINSERTstatements are replicated; the default istrue.replicate_updateistrueifUPDATEstatements are replicated; the default istrue.replicate_deleteistrueifDELETEstatements are replicated; the default istrue.replicate_truncateistrueifTRUNCATEstatements are replicated; the default istrue.
spock.repset_alter
Use spock.repset_alter to change the parameters of an existing replication
set.
spock.repset_alter(set_name name, replicate_insert bool DEFAULT NULL, replicate_update bool DEFAULT NULL, replicate_delete bool DEFAULT NULL, replicate_truncate bool DEFAULT NULL)
Parameters:
set_nameis the name of an existing replication set that will be modified by this function.replicate_insertistrueifINSERTstatements are replicated. PassNULL(the default) to leave the current value unchanged.replicate_updateistrueifUPDATEstatements are replicated. PassNULL(the default) to leave the current value unchanged.replicate_deleteistrueifDELETEstatements are replicated. PassNULL(the default) to leave the current value unchanged.replicate_truncateistrueifTRUNCATEstatements are replicated. PassNULL(the default) to leave the current value unchanged.
spock.repset_drop
Use spock.repset_drop to remove the specified replication set.
spock.repset_drop(set_name name, ifexists boolean DEFAULT false)
Parameters:
set_nameis the name of an existing replication set.ifexistscontrols whether dropping a non-existent replication set raises an error. Whentrue, no error is raised if the set is missing; the default isfalse.
spock.repset_add_table
Use spock.repset_add_table to add a table to a replication set.
spock.repset_add_table(set_name name, relation regclass, synchronize_data boolean DEFAULT false, columns text[] DEFAULT NULL, row_filter text DEFAULT NULL, include_partitions boolean DEFAULT true)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the table to be added to the set.synchronize_dataistrueif the table data is to be synchronized on all subscribers which are subscribed to the specified replication set; the default isfalse.columnsis the list of columns to replicate. Normally when all columns should be replicated, this will be set toNULL(the default).row_filteris a row filtering expression; the default isNULL(no filtering).include_partitionsistrueto also add partitions of a partitioned table; the default istrue.
Use caution when synchronizing data with a valid row filter. Using
synchronize_data=true with a valid row_filter is usually a one-time
operation for a table. Executing it again with a modified row_filter
won’t synchronize data to subscriber. You may need to call
spock.sub_resync_table() to fix it.
spock.repset_add_all_tables
Use spock.repset_add_all_tables to add all tables in the specified schemas
to the replication set.
spock.repset_add_all_tables(set_name name, schema_names text[], synchronize_data boolean DEFAULT false)
Only existing tables are added; tables that will be created in the future will not be added automatically.
Parameters:
set_nameis the name of an existing replication set.schema_namesis an array of names of existing schemas from which tables should be added.synchronize_datainstructs Spock to synchronize the table data on all nodes which are subscribed to the given replication set when set totrue; the default isfalse.
spock.repset_remove_table
Use spock.repset_remove_table to remove a table from a replication set.
spock.repset_remove_table(set_name name, relation regclass, include_partitions boolean DEFAULT true)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the table to be removed from the set.include_partitionsistrueto also remove partitions of the partitioned table; the default istrue.
spock.repset_add_seq
Use spock.repset_add_seq to add a sequence to a replication set.
spock.repset_add_seq(set_name name, relation regclass, synchronize_data boolean DEFAULT false)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the sequence to be added to the set.synchronize_datainstructs Spock to synchronize the sequence on all nodes which are subscribed to the given replication set when set totrue; the default isfalse.
spock.repset_add_all_seqs
Use spock.repset_add_all_seqs to add all sequences from the given schemas.
spock.repset_add_all_seqs(set_name name, schema_names text[], synchronize_data boolean DEFAULT false)
Only existing sequences are added; any sequences that will be created in the future will not be added automatically.
Parameters:
set_nameis the name of an existing replication set.schema_namesis an array of names of existing schemas from which sequences should be added.synchronize_dataspecifytrueto synchronize the sequence value immediately; the default isfalse.
spock.repset_remove_seq
Use spock.repset_remove_seq to remove a sequence from a replication set.
spock.repset_remove_seq(set_name name, relation regclass)
Parameters:
set_nameis the name of an existing replication set.relationis the name or OID of the sequence to be removed from the set.
You can view information about which table(s) is in which replication set by
querying the spock.tables view.
spock.sub_add_repset
Use spock.sub_add_repset to add a replication set to a subscriber.
spock.sub_add_repset(subscription_name name, replication_set name)
Does not synchronize replication; only activates consumption of events.
Parameters:
subscription_nameis the name of an existing subscription.replication_setis the name of replication set to add.
spock.sub_remove_repset
Use spock.sub_remove_repset to remove a replication set from a subscriber.
spock.sub_remove_repset(subscription_name name, replication_set name)
Parameters:
subscription_nameis the name of an existing subscription.replication_setis the name of replication set to remove.
spock.reserved_object_add
Use spock.reserved_object_add to reserve a schema or extension (see
Reserved Schemas and Extensions). If the
object is already reserved, its flags are updated. Built-in objects cannot be
changed.
spock.reserved_object_add(p_name name, p_kind text, p_exclude_from_dump bool DEFAULT true, p_block_in_repset bool DEFAULT true, p_replicate_ddl bool DEFAULT true)
Parameters:
p_nameis the schema or extension name.p_kindis'schema'or'extension'.p_exclude_from_dumpkeeps the object out of the structure-sync dump; the default istrue.p_block_in_repsetblocks the object from replication sets; the default istrue.p_replicate_ddl: passfalseto keep the object node-local so AutoDDL does not ship its DDL to other nodes (aspgedge_aceand thelolorextension are). The default istrue, and an explicitNULLis taken astrue.
spock.reserved_object_remove
Use spock.reserved_object_remove to remove one of your own reserved objects.
Built-in objects are protected and cannot be removed.
spock.reserved_object_remove(p_name name, p_kind text)
Parameters:
p_nameis the schema or extension name.p_kindis'schema'or'extension'.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.11.5 - Subscription Management Functions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Each node in a multi-master scenario contains one or more subscriptions that identify the publisher node; the subscriber acts as the replication target for the publisher.
| Command | Description |
|---|---|
| spock.sub_create | Create a subscription. |
| spock.sub_drop | Drop a subscription. |
| spock.sub_disable | Disable a subscription and disconnect it from the provider. |
| spock.sub_enable | Enables a disabled subscription. |
| spock.sub_alter_interface | Switch the subscription to use a different interface to connect to the provider node. |
| spock.sub_alter_sync | Synchronize all unsynchronized tables in a single operation. |
| spock.sub_alter_options | Change one or more subscription options in a single atomic operation. |
| spock.sub_resync_table | Resynchronize a single table. |
| spock.sub_wait_for_sync | Wait for a subscription to finish synchronization after a spock.sub_create or spock.sub_alter_sync. |
| spock.table_wait_for_sync | Wait only for the subscription’s initial sync and a named table. |
| spock.sub_show_status | Shows status and basic information about subscription. |
| spock.sub_show_table | Shows synchronization status of a table. |
| spock.sub_add_repset | Adds a replication set to a subscriber. |
| spock.sub_remove_repset | Removes a replication set from a subscriber. |
Creating a Subscription
To create a subscription from the current node to a publisher node with Spock,
connect to the server with psql and invoke the spock.sub_create command:
Parameters include:
subscription_nameis the unique name of the subscription.provider_dsnis the connection string to a provider.replication_setsis an array of replication sets that you wish to subscribe to. The sets must already exist; the default is{default,default_insert_only,ddl_sql}.synchronize_structureis a boolean value that specifies if Spock should synchronize the structure from provider to the subscriber; the default isfalse.synchronize_dataspecifies if Spock should synchronize data from provider to the subscriber; the default isfalse.forward_originsis an array of origin names to forward. See Origin Forwarding below for supported values and the restriction on combining this with other enabled subscriptions.apply_delayspecifies how long to delay replication; the default is0seconds.- set
force_text_transfertotrueto force the provider to replicate all columns using a text representation (which is slower, but may be used to change the type of a replicated column on the subscriber); the default isfalse. enabledcontrols whether the subscription is started immediately after creation. The default istrue.skip_schemais an array of schema names whose changes should be ignored by the apply worker. The default is{}(an empty array, meaning no schemas are skipped).
For example, the following command:
Creates a subscription named accts that connects to the accounting
database on 178.12.15.12, authenticating with the credentials of a user
named carol. The payables replication set is subscribed to the new
subscription.
Dropping a Subscription
To drop a subscription with Spock, connect to the server with psql and invoke
the spock.sub_drop command:
Parameters include:
subscription_nameis the name of the existing subscription.- if
ifexistsistrue, an error is not thrown if the specified subscription does not exist; the default isfalse.
For example, the following command:
Drops a subscription named accts; if the subscription does not exist, an
error message will be suppressed by the true trailing parameter (ifexists = true).
Origin Forwarding
forward_origins controls whether a subscription’s apply worker also
processes transactions that did not originate on the immediate provider, but
were relayed through it from a peer further upstream (a cascade or multi-hop
topology). {} (the default) forwards only the provider’s own
locally-originated changes — the setting used for ordinary bidirectional
replication between two nodes, since forwarding a peer’s changes back to
itself would loop. {all} forwards every change regardless of origin.
A forwarding worker advances the replication origin of the local subscription matching the peer it’s relaying (for example, a subscription to that peer created disabled ahead of time, so it can later start from the right position instead of a full resync). At most one local subscription may match a given peer; if more than one does, replication fails with an ambiguous-match error. If the matching subscription is also enabled, its own apply worker owns the same origin, and the two would conflict. Spock avoids this by requiring that a subscription with forwarding active be the only enabled subscription on the node:
- Enabling forwarding (
{all}) on a subscription — viaspock.sub_createwithenabled := true,spock.sub_enable, orspock.sub_alter_optionson an already-enabled subscription — fails if another subscription is already enabled on this node. - Enabling a subscription (
spock.sub_createwithenabled := true, orspock.sub_enable) fails if another subscription on this node already has forwarding active. - Changing
forward_originson a subscription that stays disabled is always allowed; the restriction is only checked once the subscription is actually enabled.
Subscription Management Functions
You can use the following settings to control and manage your subscriptions.
spock.sub_create
Use spock.sub_create to create a subscription from current node to the
provider node.
spock.sub_create(subscription_name name, provider_dsn text, replication_sets text[], synchronize_structure boolean, synchronize_data boolean, forward_origins text[], apply_delay interval, force_text_transfer boolean, enabled boolean, skip_schema text[])
The command does not wait for completion before returning to the caller.
Parameters:
subscription_nameis the unique name of the subscription.provider_dsnis the connection string to a provider.replication_setsis an array of existing replication sets to which you are subscribing. The default is{default,default_insert_only,ddl_sql}.synchronize_structuretells Spock if it should synchronize the structure from the provider to the subscriber; the default isfalse.synchronize_datatells Spock to synchronize data from provider to the subscriber; the default isfalse.forward_originsis an array of origin names to forward. See Origin Forwarding above for supported values and the restriction on combining this with other enabled subscriptions.apply_delayis the number of seconds to delay replication; the default is0seconds.force_text_transferforces the provider to replicate all columns using a text representation (which is slower, but may be used to change the type of a replicated column on the subscriber) when set totrue. The default isfalse.enabledcontrols whether the subscription is started immediately after creation. The default istrue.skip_schemais an array of schema names whose changes should be ignored by the apply worker. The default is{}.
The subscription_name is used as application_name by the replication
connection. This means that it’s visible in the pg_stat_replication
monitoring view. It can also be used in synchronous_standby_names when
Spock is used as part of a synchronous replication setup.
Use spock.sub_wait_for_sync(subscription_name) to wait for the
subscription to asynchronously start replicating and complete any needed
schema and/or data sync.
spock.sub_drop
Use spock.sub_drop to disconnect the subscription and remove it from the
catalog.
spock.sub_drop(subscription_name name, ifexists bool)
Parameters:
subscription_nameis the name of an existing subscription.ifexiststells the Spock extension how to handle the error if the subscription does not exist. Iftrue, an error is not thrown if the subscription does not exist; the default isfalse.
spock.sub_disable
Use spock.sub_disable to disable a subscription and disconnect it from the
provider.
spock.sub_disable(subscription_name name, immediate bool)
Parameters:
subscription_nameis the name of an existing subscription.immediatetells Spock when to stop the subscription. If set totrue, the subscription is stopped immediately; if set tofalse(the default), it will be only stopped at the end of current transaction.
spock.sub_enable
Use spock.sub_enable to enable a disabled subscription.
spock.sub_enable(subscription_name name, immediate bool)
Parameters:
subscription_nameis the name of the existing subscription.immediatetells Spock when to start the subscription. If set totrue, the subscription is started immediately; if set tofalse(the default), it will only be started at the end of the current transaction.
This fails if another subscription on this node already has forwarding active; see Origin Forwarding above.
spock.sub_alter_interface
Use spock.sub_alter_interface to modify the subscription to use a different
interface to connect to provider node.
spock.sub_alter_interface(subscription_name name, interface_name name)
Parameters:
subscription_nameis the name of an existing subscription.interface_nameis the name of an existing interface of the current provider node.
spock.sub_alter_sync
Use spock.sub_alter_sync to synchronize all unsynchronized tables in all sets in a
single operation.
spock.sub_alter_sync(subscription_name name, truncate boolean DEFAULT false)
Tables are copied and synchronized one by one. The command does not wait for
completion before returning to the caller. Use spock.sub_wait_for_sync to
wait for completion.
Parameters:
subscription_nameis the name of an existing subscription.truncatetells Spock if it should truncate tables before copying. Iftrue, tables will be truncated before copy; the default isfalse.
spock.sub_resync_table
Use spock.sub_resync_table to resynchronize an existing table.
spock.sub_resync_table(subscription_name name, relation regclass)
The table may not be the target of any foreign key constraints.
After scheduling the resynchronization, the function raises a WARNING if
the cached spock.node row of the provider differs from the provider’s own
row; see spock.sub_resync_table.
This function will truncate the table immediately, and only then begin
synchronising it, so it will be empty while being synced. The command does
not wait for completion before returning to the caller; use
spock.table_wait_for_sync to wait for completion.
Parameters:
subscription_nameis the name of an existing subscription.relationis the name of an existing table, optionally qualified.
spock.sub_wait_for_sync
Use spock.sub_wait_for_sync to wait for a subscription to finish
synchronization after a spock.sub_create or spock.sub_alter_sync.
spock.sub_wait_for_sync(subscription_name name)
This function waits until the subscription’s initial schema/data sync, if any, are done, and until any tables pending individual resynchronisation have also finished synchronising.
Parameters:
subscription_nameis the name of an existing subscription.
For best results, run SELECT spock.wait_slot_confirm_lsn(NULL, NULL) on the
provider after any replication set changes that requested resyncs, and only
then call spock.sub_wait_for_sync on the subscriber.
spock.table_wait_for_sync
Use spock.table_wait_for_sync to wait only for the subscription’s initial
sync and the named table.
spock.table_wait_for_sync(subscription_name name, relation regclass)
Same as spock.sub_wait_for_sync, but waits only for the subscription’s
initial sync and the named table. Other tables pending resynchronisation are
ignored.
spock.wait_slot_confirm_lsn
Use spock.wait_slot_confirm_lsn to wait until all replication slots on the
current node have replayed up to the xlog insert position at time of call on
all providers.
SELECT spock.wait_slot_confirm_lsn(NULL, NULL)
Returns when all slots’ confirmed_flush_lsn passes the
pg_current_wal_insert_lsn() at time of call.
Options include:
- optionally may wait for only one replication slot (first argument).
- optionally may wait for an arbitrary log sequence number (LSN) passed
instead of the insert LSN (second argument); both are usually just left
NULL.
This function is very useful to ensure all subscribers have received changes up to a certain point on the provider.
spock.sub_show_status
Use spock.sub_show_status to show status and basic information about a
subscription.
spock.sub_show_status(subscription_name name DEFAULT NULL)
Parameters:
subscription_nameis the optional name of an existing subscription. If omitted (orNULL), the function will show the status of all subscriptions on the local node.
The function returns one row per subscription with these columns:
subscription_name, status, provider_node, provider_dsn,
slot_name, replication_sets, forward_origins.
spock.sub_show_table
Use spock.sub_show_table to show the synchronization status of a table.
spock.sub_show_table(subscription_name name, relation regclass)
Parameters:
subscription_nameis the name of an existing subscription.relationis the name of an existing table, optionally qualified.
spock.sub_add_repset
Use spock.sub_add_repset to add one replication set into a subscriber.
spock.sub_add_repset(subscription_name name, replication_set name)
Does not synchronize, only activates consumption of events.
Parameters:
subscription_nameis the name of an existing subscription.replication_setis the name of a replication set to add to the specified subscription.
spock.sub_remove_repset
Use spock.sub_remove_repset to remove one replication set from a subscriber.
spock.sub_remove_repset(subscription_name name, replication_set name)
Parameters:
subscription_nameis the name of the existing subscription.replication_setis the name of replication set to remove.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.12 - Upgrading the Spock Extension
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
If you build the Spock extension from source, you can remove, build, and upgrade the Spock extension like you would any other Postgres extension.
If you’re upgrading a secure production environment, shut down each node sequentially and perform the following steps:
- Disable auto-DDL.
- Stop the Postgres server.
- Build the updated Spock binaries for your Postgres version.
- Restart the Postgres server; this triggers extension schema upgrade checks (Spock’s background worker detects the version mismatch and runs any required schema migrations automatically).
- Use the psql command line to verify the Spock version in use and the node status.
- After upgrading all of the nodes in your cluster, enable Auto-DDL and restart the service on each node.
A detailed description of each step in the upgrade process is provided below.
Disabling Auto-DDL
Before stopping a node, disable DDL replication to prevent schema changes during the upgrade. Connect to each node and run:
Or, set the following parameter in postgresql.conf on each node:
Then, reload the configuration:
This step is essential if old and new versions are incompatible.
Stopping the Postgres Server
Before upgrading the Spock binary, stop the Postmaster on the server that you’re working on:
This step is essential if old and new versions are incompatible.
Building the New Spock Binaries
Before building the extension, you’ll need to obtain updated Spock source code. If you regularly build the Spock extension from source code (available at https://github.com/pgEdge/spock), use git to obtain an updated source set; then:
The installation copies the following files:
spock.so→$(pg_config --pkglibdir)/;spock.control→$(pg_config --sharedir)/extension/;spock--5.0.1.sqlandspock--5.0.0--5.0.1.sql→$(pg_config --sharedir)/extension/.
Next, you should verify that the updated Spock files are installed. You can use the following commands to confirm the version update.
Check the library timestamp:
Check the control file:
Check that an upgraded .sql file exists; for example:
Restarting the Postgres Server
Then, use pg_ctl to restart the Postgres postmaster process:
When the server restarts, Spock’s database manager background worker
automatically detects the version mismatch and upgrades the extension schema
(with spock_manage_extension() in spock.c).
Verifying the Extension Upgrade
After building the extension, you can verify the version of the extension that is in use and the state of your replication cluster. Use the psql command line to invoke the commands that follow.
Connect to the database with psql:
Verify the Spock version that is in use:
Then, verify that the node is replicating. Check that subscriptions are active with the following commands:
Check the replication slots:
Check the node status:
Enabling Auto-DDL and Restarting the Service on Each Node
After upgrading all of the nodes in your cluster, connect to each node with psql and enable DDL replication:
Or you can modify the parameter in the postgresql.conf file:
Reload the configuration:
Then, on each node, restart the service:
Final Verification
After performing the steps listed above on each server in the cluster, use the following command to verify the replication status of each node:
You should confirm that:
- all nodes report consistent versions (the target version).
- replication lag is minimal or zero.
- no errors appear in PostgreSQL or Spock logs.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.13 - Recovery
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
2.13.1 - Recovering from Catastrophic Node Failure
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Suppose your cluster is running smoothly with five nodes — n1, n2, n3, n4, and n5 — all connected using Spock logical replication. Node n1 sends transactions to the other four nodes. Then something goes wrong: perhaps because of network delay, n2 has not yet received all of the transactions that n3, n4, and n5 have already applied. Before n2 can catch up, n1 crashes. You are left with n2 lagging behind the others, and no way for it to get the missing data from n1. This is a catastrophic node failure scenario.
Depending on how you run your cluster, more than one node may accept writes. Later in this document, we also show a multiple-node failure example where a second node had also originated transactions before failing.
In the following sections, we’ll walk through how to recover a node using Spock for replication with the Active Consistency Engine (ACE). In each scenario, we use a fully synchronized node as our source of truth. ACE repairs the missing data and can preserve the origin ID and commit timestamp for each repaired row so that replication metadata stays correct and your cluster remains consistent and conflict-free.
This document covers two cases:
- single node failure (one node fails and another is lagging)
- multiple node failure (two or more nodes fail and one or more survivors are behind).
The same idea applies in both cases; you identify what is missing on the surviving node(s), then repair the nodes using a node with complete data, preserving the origin ID and timestamp for every repaired row.
Single Node Failure vs. Multiple Node Failure
The following diagrams show the two scenarios and how to recover.
Scenario 1: One Node has Failed, and One Node is Lagging
In our first example, one node (n1) fails, while another node (n2) is lagging behind because it did not receive all of that node’s transactions. The other survivors (n3, n4, n5) have complete data.
flowchart LR
subgraph failed [Failed]
N1[n1 failed]
end
subgraph behind [Behind]
N2[n2 missing rows from n1]
end
subgraph source [Source of truth]
N3[n3 complete]
N4[n4 complete]
N5[n5 complete]
end
N1 -.->|was replicating to| N2
N3 -->|recover from| N2Implementing a Recovery
- Node n1 has failed.
- Node n2 is lagging.
Our source of truth has to be: n3, n4, or n5
Our first step is to clean up. First, we will use Spock commands to drop the subscriptions to n1, and then drop node n1 from the cluster.
Then, on our survivor (n2), and for each table, run:
table-diff --preserve-origin n1 --until <n1_failure_time>
Then, on our survivor (n2), for each table with differences, run the ACE
table-repair command, specifying the --recovery-mode,
--source-of-truth n3, and --preserve-origin options.
These steps ensure that n2 contains all of the rows that originated on n1.
Note: These are high-level steps. Detailed instructions for each step, including exact commands and options, are provided later in this document starting at Phase 1: Assess the Damage. In some cases, tables may still show differences after an initial repair; see the Troubleshooting section for guidance.
Scenario 2: Multiple Nodes have Failed, and One Node is Lagging
In our next example, we’ll assume multiple nodes have failed (for our example, we’ll use n1 and n4). If two (or more) nodes fail, leaving one or more survivors, the damaged survivor (node n2 is lagging, but not down) may be missing rows that originated from either n1 or n4. To recover, pick one fully synchronized survivor as the source of truth (we’ll use n3) and recover n2, adding data from both n1 and n4.
In this example, we’ll assume n4 was also accepting writes before it failed, so some rows in the cluster have an origin ID of n4.
flowchart LR
subgraph failed [Failed]
N1[n1 failed]
N4[n4 failed]
end
subgraph behind [Behind]
N2[n2 missing rows from n1 and n4]
end
subgraph source [Source of truth]
N3[n3 complete]
N5[n5 complete]
end
N1 -.->|was replicating to| N2
N4 -.->|was replicating to| N2
N3 -->|recover n2 for both n1 and n4| N2Implementing a Recovery
- Nodes n1 and n4 have failed.
- Node n2 is lagging.
Our source of truth has to be: n3 or n5
Our first step is to clean up the replication scenario. Drop the subscriptions to n1 and n4 before dropping the nodes from the cluster.
Then, on each surviving node, and for each table, run the table-diff command
against each failed node including the --preserve-origin and failure_time
options:
table-diff --preserve-origin n1 --until <n1_failure_time>
table-diff --preserve-origin n4 --until <n4_failure_time>
Each run will return one diff file per table/origin combination.
Then, on n2, for each table with differences, run table-repair
with --recovery-mode, --source-of-truth n3, and --preserve-origin.
These steps will ensure n2 contains all of the rows that originated on n1 and n4, with the origin ID and timestamp preserved for each.
In the case of a multiple-node failure, you run diff and repair once per failed origin. For each table, that means one diff (and one repair) for n1 and one diff (and one repair) for n4. The source of truth (n3) is the same for all repairs.
Implementing Repairs in Both Cases
flowchart TD
subgraph single [Single node failure]
S1[n1 fails, n2 behind]
S2[Drop n1. Diff vs n1. Repair n2 from n3.]
S1 --> S2
end
subgraph multi [Multiple node failure]
M1[n1 and n4 fail, n2 behind]
M2[Drop n1 and n4. Diff vs n1, then vs n4.]
M3[Repair n2 from n3 for n1 rows. Repair n2 from n3 for n4 rows.]
M1 --> M2 --> M3
endIn both cases you:
- Clean up the failed node(s) in Spock.
- Run table-diff on all tables—once per failed origin in the multiple-node case.
- Run table-repair with
--preserve-originand a single source of truth so that origin ID and commit timestamp are preserved for each repaired row.
What Happens in a Catastrophic Node Failure of a Single Node
When one node fails mid-replication, some of its transactions may have been applied on some subscribers but not others. In our single-failure example:
- n1 has failed and is no longer available.
- n2 received fewer transactions from n1 (for example, due to network delay) and is behind.
- n3, n4, and n5 received all of n1’s transactions and are fully synchronized.
You need to bring n2 back in line with n3, n4, and n5. ACE does this by
comparing tables across the surviving nodes, focusing only on data that
originated from n1 and was committed before the failure. It then repairs n2
using a chosen source of truth (in our example, n3). When you use the
--preserve-origin option, ACE preserves each repaired row’s origin ID
(the node that originally wrote the row) and commit timestamp (to
microsecond precision) so that replication metadata remains correct.
The following diagram shows the state at the moment of failure of our single node, n1:
sequenceDiagram
participant N1 as n1 (failed)
participant N2 as n2 (behind)
participant N3 as n3 (up to date)
participant N4 as n4 (up to date)
participant N5 as n5 (up to date)
Note over N1: Sends transactions to all
rect rgb(230, 240, 255)
N1->>N2: Partial replication (e.g. 3 of 5)
N1->>N3: Full replication (all 5)
N1->>N4: Full replication (all 5)
N1->>N5: Full replication (all 5)
end
N1--xN1: Crash (n1 offline)
Note over N2: Missing rows from n1
Note over N3..N5: Complete - use as source of truthBefore You Begin
Before you start the recovery process, make sure you have the following in place:
- ACE installed and configured on a host that can reach your surviving nodes. ACE is used to compare and repair table data across nodes. For building, installing, and configuring ACE, see the ACE repository and its documentation (including configuration).
- Access to your surviving nodes (n2, n3, n4, and n5). You’ll need to run ACE commands and, for Spock cleanup, connect to each node with a Postgres client.
- The approximate time when the failed node (or nodes) failed. You’ll use this as a cutoff when running ACE so that only data committed before the failure is considered.
- Origin tracking enabled. Your Spock cluster should have
track_commit_timestamp = onin Postgres so that ACE can use commit timestamps and origin ID for recovery and for preserving them when repairing rows.
Recovery is a multi-step process. Take your time, and run the
validation steps so you can confirm that all tables match before
resuming normal operations. To preserve the origin ID and commit
timestamp for repaired rows, include the --preserve-origin flag
with every table-repair command in Phase 4. In some cases, tables
may still show differences after an initial repair (for example, if
writes occurred during the diff or repair). The
Troubleshooting section at the end of this
document covers the most common causes and how to resolve them.
Overview of the Recovery Workflow
Recovery has five main phases; you should approach these phases in order:
Assess the damage – Check replication status and identify which nodes are behind and which are fully synchronized.
Spock cleanup – Drop subscriptions and slots for the failed node and remove the failed node from the cluster.
Identify all missing data – Run ACE table-diff on every replicated table to see which tables have differences and what is missing on n2.
Repair all affected tables – For each table that has differences, run ACE table-repair using n3 (or your chosen node) as the source of truth. Use
--preserve-originso that the origin ID and commit timestamp are preserved for every repaired row.Validate – Re-run table-diff on all repaired tables to confirm that n2 matches the other survivors.
Because n2 might be missing data from more than one table, you must check all of your tables, not just one. The sections below walk you through each phase and show you the commands to run.
Phase 1: Assess the Damage
Connect to your surviving nodes and check replication status. You need to
confirm which nodes are behind and which have all of the data. You can use
spock.sub_show_status()
to see subscription status and any lag.
For example, connect to n2 and run:
The output will list each subscription with its current status and lag. A
subscription that shows a large lag or a status of down or initializing
when it should be replicating indicates that the node is behind. For
example:
In this output, sub_n2_n1 is down — that confirms n2 lost its
connection to n1 (which has failed). The subscriptions to n3, n4, and n5
are still healthy. To gauge how far behind n2 is, query
spock.lag_tracker for replication lag
in bytes and time.
Determine the approximate time when the failed node (or nodes) failed. You’ll need this timestamp for the ACE commands in Phase 3 and 4. If you have logs or monitoring, use that; otherwise use the last known good time before the failure.
Phase 2: Spock Cleanup
Once you’ve confirmed that the failed node (in our case, n1) is gone and won’t be coming back in this recovery, you need to remove it from the cluster so that the remaining nodes no longer expect replication from or to n1.
On each surviving node (n2, n3, n4, n5):
Drop subscriptions that involved the failed node.
If a subscription was receiving from n1 or sending to n1, drop it using
spock.sub_drop(). For example, on n2 you might drop the subscription that connected n2 to n1.Remove the failed node from the cluster.
From one of the surviving nodes, call
spock.node_drop()to remove n1. This removes the node entry from the Spock catalog.
Dropping the node and subscriptions is irreversible; make sure you have identified the failed node correctly and that you do not need to bring n1 back before doing this.
After cleanup, your cluster has four nodes: n2, n3, n4, and n5. The next steps use ACE to fix the data on n2.
If two or more nodes failed (e.g. n1 and n4), you’ll perform these steps for each node.
Phase 3: Identify All of the Missing Data
To recover n2, you need to know which tables have differences and
what is missing. ACE’s
table-diff
command compares table data across nodes. When you run it with
--preserve-origin n1 and --until <timestamp>, it limits the comparison
to rows whose origin ID is n1 and whose commit timestamp is at or before
that time—exactly what you need after n1 has failed.
You must run table-diff for every table that is replicated in your
cluster. If you only run it for one table, you might repair that table but
leave others out of sync.
Step 1: Get a List of All Tables to Check
First, get the list of tables that participate in replication. You can get
this from the spock.tables view, which lists every table along with the
replication set (if any) it belongs to. Connect to any surviving node (for
example, n3) and run:
Alternatively, you can list all tables in the schema you replicate:
Use this list for the next step. In the examples below, we’ll use tables
like customers, orders, and products; replace these with your actual
schema and table names.
Step 2: Run table-diff on Every Table
For each table in your list, run ACE table-diff with the failed node as
the origin and your failure timestamp as the cutoff. Replace
2026-02-11T14:30:00Z with the time when n1 failed, and replace
mycluster with your ACE cluster name.
For a single table (for example, public.customers):
What these options do:
--nodes n2,n3,n4,n5– Compare only the surviving nodes (n2 and the nodes that have full data).--preserve-origin n1– Only consider rows whose origin ID is n1, so you don’t mix in later local writes on the survivors.--until 2026-02-11T14:30:00Z– Only consider rows committed at or before this time (use RFC3339 format).--output json– Writes a diff report to a JSON file that you’ll use for repair.
ACE returns a diff file with a name that contains the schema and table name;
for example, public_customers_diffs-20260211143000.json. Repeat the diff
command for every other table; for example:
Step 3: Review the Diff Reports
After running table-diff on all tables, check the output. ACE will report whether each table has differences. For tables that do have differences, note the name of the diff file (it will include the table name and a timestamp). You’ll use those files when you perform the repair steps. Tables that have no differences don’t need repair.
If you have a multiple node failure (e.g. n1 and n4 both failed), run table-diff once per failed origin per table. For example, if your survivors are n2, n3, n5. For each table you run two diffs (one from each node) and get two diff files:
Review the diff reports; then in Phase 4, run table-repair for each of these diff files using same source of truth (e.g. n3).
If you have multiple tables, you can script the diff step. The following example loops through a list of table names (customize the list to match your schema):
Phase 4: Repair All Affected Tables
For each table that had differences in Phase 3, run ACE table-repair
using the diff file that was produced. You must run repair in recovery
mode and include --preserve-origin so that repaired rows keep their
original origin ID and commit timestamp. Without
--preserve-origin, repaired rows would get n2’s origin ID and a new
commit time, which can cause replication conflicts and incorrect ordering.
With --preserve-origin, ACE writes each repaired row with the same origin
ID and commit timestamp it had on the source of truth, so n2’s replication
metadata stays correct.
Choose one node as the source of truth for repair. In our scenario, n3 (and
n4 and n5) have the complete data, so we chose n3. You can let ACE
auto-select the source of truth based on which survivor has the highest
origin LSN for n1, or you can set it explicitly with --source-of-truth n3.
Repair Command for Each Table
For each table that had differences, run the following command, replacing
the diff filename and table name with the ones from your table-diff run:
--diff-file– The JSON file produced by table-diff for this table.--nodes n2,n3,n4,n5– The surviving nodes (n2 will be repaired; n3 is the source of truth).--recovery-mode– Required when the diff was created with--preserve-origin; tells ACE this is a catastrophic-failure recovery.--source-of-truth n3– Use n3’s copy of the data to repair n2. You can omit this and let ACE choose the survivor with the highest LSN for n1, but if there are ties or missing LSNs, you must specify the source.--preserve-origin– Preserves the origin ID and commit timestamp for each repaired row (to microsecond precision). Repaired rows on n2 will show the same origin ID and commit time as on the source of truth, so replication metadata stays correct.
Repeat for every table that had differences, for example:
Multiple node failure (e.g. n1 and n4 both failed): You have one diff
file per (table, failed origin). Run table-repair for each of those
diff files, using the same source of truth (n3) and --preserve-origin
every time. ACE writes a new filename for each table-diff run; use the file
from your n1 diff run for the first repair and the file from your n4 diff
run for the second. Example for one table:
In both commands the source of truth is n3; origin ID and commit timestamp are preserved for every repaired row.
Always use --preserve-origin when repairing after a catastrophic node
failure. This option ensures that the origin ID and commit
timestamp are preserved for every repaired row. If you omit it,
repaired rows will have n2’s origin ID and a new timestamp, which can
cause replication conflicts and incorrect conflict resolution.
For more details on recovery mode and how origin ID and timestamp preservation works, see the ACE repository and the ACE docs: Using ACE for CNF recovery and the table-repair command reference.
Phase 5: Validate That All Tables Match
After repairing every affected table, verify that n2 now matches n3, n4,
and n5. Re-run table-diff for each repaired table without
--preserve-origin and --until. That compares the full table content
across the survivors:
If ACE reports that the tables match, n2 has been successfully recovered.
At this point you can resume normal operations: re-enable or recreate any
subscriptions that were dropped during cleanup (for example, subscriptions
from n2 to n3, n4, and n5 so that n2 receives new writes), and allow
application traffic to flow again. If writes were occurring on other nodes
during the repair, a final table-diff run (without --preserve-origin or
--until) will confirm that n2 has caught up completely.
If any table still shows differences, review the diff report and consider re-running repair for that table or checking for ongoing writes during the diff. See the Troubleshooting section for common causes and remedies.
flowchart LR
subgraph before [Before Recovery]
N2_before[n2 missing data]
N3_before[n3 complete]
N4_before[n4 complete]
N5_before[n5 complete]
end
subgraph after [After Recovery]
N2_after[n2 repaired]
N3_after[n3 complete]
N4_after[n4 complete]
N5_after[n5 complete]
end
before --> afterWhy Preserve Origin ID and Timestamp?
The repairs that ACE writes to n2 originated on n1. Each row has an origin ID (that identifies which node wrote it) and a commit timestamp (that identifies when it was committed). Spock uses these for conflict resolution and to keep replication consistent.
If you repair without --preserve-origin, the repaired rows get n2’s
origin ID and a new commit timestamp. That can cause:
- Replication conflicts – If n1 ever comes back or you add another node with n1’s history, the cluster may see the same row with different origin IDs and timestamps and report conflicts.
- Incorrect ordering – Spock uses commit timestamps and origin ID for conflict resolution (for example, last-write-wins). Wrong timestamps or origin IDs can lead to wrong outcomes.
- Lost data lineage – You lose an accurate record of which node produced which data.
If you repair with --preserve-origin, ACE keeps the original origin
ID and commit timestamp (to microsecond precision) for each repaired row.
The repaired rows on n2 then match the replication metadata they had on the
source of truth, so conflict resolution and data lineage stay correct.
For catastrophic node failure recovery, always use --preserve-origin when
you run table-repair.
Important Considerations when using ACE
Review the following considerations before performing a recovery with ACE.
Multi-Table Recovery
When performing a recovery between nodes with multiple tables:
- Check every table – Run table-diff on all replicated tables, not just one. Only then will you see the full picture of what is missing on n2.
- Prioritize if needed – If you have many tables, you can repair critical tables first, then the rest. Just ensure you eventually run diff and repair for every affected table.
- Same cutoff for all – Use the same
--untiltimestamp for every table so that you’re consistently fencing at the same failure time. - Same source of truth – Using one node (e.g., n3) as source of truth for all tables keeps the process simple. If you have a reason to use different sources per table, you can, but document it so you don’t get confused later.
Large Tables
For very large tables, ACE supports options such as --table-filter to
restrict the comparison to a subset of rows. This allows you to run diff
and repair in chunks. See the
ACE table-diff command documentation
for details.
When to Specify –source-of-truth
If you omit --source-of-truth, ACE will try to pick the survivor with the
highest origin LSN for n1. If LSN information is missing on the survivors
or there’s a tie, ACE will ask you to specify the source. In that case,
choose any node that you know has the most complete data set (in our
example, n3, n4, or n5).
Catastrophic Failure vs. Network Partition
A catastrophic node failure means the node is gone (crashed, unrecoverable). A network partition might mean the node is still running but temporarily unreachable. If you’re only dealing with a partition, you might prefer to wait for connectivity to return or to fail over in a planned way rather than dropping the node and doing ACE recovery. Use this procedure when you’ve decided that the node is permanently lost for this cluster.
Troubleshooting
ACE says LSN Information is Missing
Specify --source-of-truth explicitly (e.g. --source-of-truth n3) so
ACE doesn’t need to probe LSNs.
More than One node is behind
Run diff and repair commands for all potentially lagging nodes in
--nodes. The source of truth should be a node that has full data; repair
will fix the others.
Auto source-of-truth selection fails or ties
Provide --source-of-truth <node_name> with the name of a node you know has
the complete data.
Origin metadata missing for some rows
ACE may log a warning and repair those rows without preserving origin ID and
timestamp. Ensure track_commit_timestamp = on and that the diff was run
with --preserve-origin; check the diff file and ACE logs.
Tables still differ after repair
Re-run table-diff without --preserve-origin to see the current state. If
writes occurred during repair, run diff again and repair if needed. For large
tables, consider performing a chunked repair with --table-filter.
Source node fails mid-replay
If the node you chose as your source of truth (e.g., n3) fails or becomes unavailable while ACE is still running repairs, stop the repair immediately and switch to a different fully-synchronized survivor before continuing.
- Confirm which remaining nodes still have complete data (re-run
spock.sub_show_status()on each one and check for lag). - Pick a new source of truth (e.g., n4 or n5) and re-run
table-repairwith--source-of-truth n4for any tables that were not yet fully repaired.
If your cluster has only three nodes and the source-of-truth node also fails mid-replay, you may have no fully-synchronized survivor left. In that situation you cannot guarantee a complete, conflict-free repair and some data loss is possible. Minimize this risk by keeping at least one additional warm standby or by pausing application writes before starting the recovery.
Recovery fails entirely (non-Spock failure)
If the recovery cannot be completed — for example, because the lagging node itself has suffered hardware or OS failure during the repair process — you may need to rebuild it from scratch rather than repair it in place. In that case, remove the damaged node from the cluster and add a fresh replacement using the ZODAN node-management procedures:
- Remove the damaged node – Use
spock.node_drop()(and drop related subscriptions) on the surviving nodes to clean up the cluster registry. - Add a replacement node – Use ZODAN’s
add_nodeprocedure to bring a new node into the cluster. ZODAN handles slot creation, initial sync, and subscription wiring automatically. See the ZODAN documentation and the ZODAN tutorial for step-by-step instructions.
Post-Recovery Validation Checklist
After completing all repair steps, work through the following checklist before returning the cluster to normal production traffic.
Replication Status
- Run
SELECT * FROM spock.sub_show_status();on every node and confirm all subscriptions showreplicatingwith zero (or near-zero) lag. - Confirm that subscriptions dropped during Phase 2 cleanup have been re-created and are active.
- Verify that the recovered node (n2) appears in
SELECT * FROM spock.node;on all surviving nodes and that its DSN is correct.
Replication Slot Cleanup
- Run
SELECT slot_name, active, restart_lsn FROM pg_replication_slots;on each node and confirm there are no stale or inactive slots left over from the failed node or from the recovery process. - If any orphaned slots remain (for example, a slot for n1 that was
never dropped), remove them with
SELECT pg_drop_replication_slot('<slot_name>');on the node that owns the slot.
Data Integrity Check
Re-run
table-diffon all repaired tables without--preserve-originor--untilto confirm the full table content matches across all nodes:Confirm ACE reports no differences for every table.
Spot-check row counts on the recovered node against a known-good survivor for critical tables:
If
track_commit_timestamp = on, verify that origin IDs and commit timestamps on repaired rows match the source of truth (usepg_xact_commit_timestamp()andspock.xact_commit_timestamp_origin()).
Final Sign-off
- Monitor replication lag for at least 15–30 minutes after re-enabling application traffic to confirm the recovered node is keeping up.
- Review PostgreSQL logs on the recovered node for any replication errors or warnings.
- Document the recovery: nodes affected, failure time used for
--until, source of truth used, and any tables that required re-repair.
Summary
In summary, the basic steps required to recover a lagging or damaged node vary only based on how many nodes you need to repair or rebuild:
In the event of a single node failure:
Assess the damage – Identify which nodes are behind and determine when the failure occurred.
Clean up Spock – Drop subscriptions to the failed node and remove it from the cluster.
Identify missing data – Run ACE table-diff on all replicated tables with
--preserve-origin node_nameand--until <failure_time>.Repair affected tables – Run ACE table-repair with the following command options:
--recovery-mode--source-of-truth n3--preserve-origin(critical for maintaining replication metadata)
Validate the recovery – Re-run table-diff to confirm all tables match across surviving nodes.
The process is similar for a multi-node failure with these key differences:
Assess the damage – Identify which nodes are behind and when each failure occurred.
Clean up Spock – Drop subscriptions to all failed nodes and remove all of the failed nodes from the cluster.
Identify missing data – Run table-diff once for each failed origin, for each table:
--preserve-origin n1with n1’s failure time--preserve-origin n4with n4’s failure time
Repair affected tables – Run table-repair for each diff file produced:
- Use the same
--source-of-truth(e.g., n3) for all repairs - Always include
--preserve-origin
- Use the same
Validate recovery – Re-run table-diff to confirm all tables match
Critical Reminder
In both scenarios, always use --preserve-origin to ensure that origin ID
and commit timestamp are preserved for every repaired row. Check all
replicated tables to ensure the lagging node is fully recovered.
See also
- ACE (Active Consistency Engine) on GitHub — build, install, and configure ACE; command reference and architecture docs are in the repository.
- ACE documentation —
configuration, CNF recovery, and command reference (e.g.
table-diff,table-repair).
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.14 - Logical Slot Failover
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock creates logical replication slots on each provider node. For high availability with a physical standby, these slots must be synchronized to the standby so that replication can resume without data loss after a failover.
How It Works
When a primary server fails and a physical standby is promoted, any active logical subscribers must be able to continue replicating from the new primary. This requires the logical replication slots, which track each subscriber’s replication position, to be present and up to date on the standby before the failover occurs.
Without slot synchronization, a failover would require manual slot recreation and a full re-sync of all subscriber tables.
PostgreSQL Version Behaviour
| PostgreSQL | Slot sync mechanism | Spock worker |
|---|---|---|
| 15, 16 | Spock built-in spock_failover_slots worker | Registered on every node; synchronizes only while in recovery |
| 17 | Spock worker or native sync_replication_slots | Yields to native if enabled |
| 18+ | Native sync_replication_slots (required) | Not registered |
The mechanism changes with the version, but the requirement does not: a slot
sync worker is running on every node of the cluster, primary and standby
alike. It is started before the server knows which role it will hold, so on a
primary it stays resident and idle, waking only to check whether the server
has entered recovery. Spock’s own worker is registered from
shared_preload_libraries and occupies one max_worker_processes slot;
PostgreSQL’s native worker is a dedicated postmaster process outside that
pool. Budget a worker for it on every node either way - see
Sizing Postgres Resources for Spock.
On PostgreSQL 17+, Spock marks every logical slot with the FAILOVER flag
at creation time. This enables PostgreSQL’s built-in slotsync worker to pick
them up automatically.
On PostgreSQL 18+, Spock’s own failover worker is not registered at all.
The native slotsync worker is the only mechanism that copies the slots.
Spock’s walsender hold-back (spock.pg_standby_slot_names with
spock.standby_slots_min_confirmed) stays available on every version, since
synchronized_standby_slots can only wait for all of its slots.
Which settings you need
There are two sync paths, and each needs a different set of settings. Both paths also assume the base Spock settings are already in place.
Base settings (all versions, every node)
These are the settings Spock needs to replicate at all. They are covered in Installing and Configuring Spock.
Size these for your cluster rather than copying the numbers - see
Sizing Postgres Resources for Spock. Slots, walsenders, and
origins scale with the number of other nodes multiplied by the number of
replicated databases in the instance, and max_replication_slots and
max_wal_senders should be set to the same value. Note that a physical
standby adds a slot to that value on the primary, and that a slot sync worker
occupies one max_worker_processes slot on every node.
On PostgreSQL 18, also size max_active_replication_origins (default 10) to at
least the number of subscriptions this node applies - (nodes - 1) x replicated databases in a full mesh - plus some headroom. Setting it equal to
max_replication_slots is the simplest safe choice.
Native path (PostgreSQL 17 with sync_replication_slots = on, and PostgreSQL 18)
Core PostgreSQL copies the slots. Set these in addition to the base settings.
| Setting | Node | Value | Purpose |
|---|---|---|---|
sync_replication_slots | standby | on | Turns on the core slot sync worker. Required on 18, optional on 17. |
hot_standby_feedback | standby | on | Stops the primary from removing catalog rows the slots still need. |
primary_slot_name | standby | physical slot name | The physical slot the standby streams through. |
primary_conninfo | standby | connection string with dbname | How the standby reaches the primary. |
synchronized_standby_slots | primary | physical slot name | Holds logical walsenders back until every listed standby has the changes. With more than one standby, use the two Spock settings below instead when “any N of them” is wanted; use only one of the two mechanisms. |
spock.pg_standby_slot_names | primary | '' | Physical slots that must confirm an LSN before logical replication advances. Optional. |
spock.standby_slots_min_confirmed | primary | -1 | How many of those slots must confirm. -1 means all; 1 keeps replicating while one standby of several is down. |
slot failover = true | primary | per slot | Only slots with this flag are synced. Spock 6.0.0 sets it at creation; older slots are handled during upgrade. |
With spock.standby_slots_min_confirmed lower than the number of listed
slots, subscribers can receive changes that some standbys do not have yet.
After a failure, promote the standby with the highest
pg_last_wal_receive_lsn(): it has every change sent to a subscriber.
Promoting a standby that is further behind leaves subscribers with rows the
new primary never had.
A standby inherits spock.pg_standby_slot_names from whichever file carries
it, including a postgresql.conf or postgresql.auto.conf that
pg_basebackup copies. After a promotion the new primary has none of the
physical slots it names, so with -1 every logical walsender waits for them
until wal_sender_timeout and warns; create the slots there or clear the
setting, as for synchronized_standby_slots in the runbook below. A
walsender that is waiting does not notice a server shutdown before that
timeout either.
The physical slot must exist on the primary before the standby connects:
Spock worker path (PostgreSQL 15, 16, and 17 when sync_replication_slots is off)
The Spock background worker on the standby copies the slots. Set these in addition to the base settings.
| Setting | Node | Default | Purpose |
|---|---|---|---|
hot_standby_feedback | standby | on (you set it) | Required before the worker will synchronize anything, and stops the primary from removing needed catalog rows. |
primary_slot_name | standby | physical slot name | The physical slot the standby streams through. |
primary_conninfo | standby | connection string | How the standby reaches the primary. |
spock.synchronize_slot_names | standby | name_like:%% | Which slots to sync. All by default. |
spock.drop_extra_slots | standby | on | Drop standby slots that no longer exist on the primary. |
spock.primary_dsn | standby | '' | Connection to the primary. Falls back to primary_conninfo when empty. |
spock.pg_standby_slot_names | primary | '' | Physical slots that must confirm an LSN before logical replication advances. Optional. |
spock.standby_slots_min_confirmed | primary | -1 | How many of those slots must confirm. -1 means all. |
spock.failover_slots_naptime | standby | 1000 | Worker sleep between slot-sync passes, in ms (SIGHUP; range 1–3600000). |
spock.failover_slots_feedback_naptime | standby | 10000 | Shorter retry, in ms, while waiting for standby WAL feedback (SIGHUP; range 1–3600000). |
spock.failover_slots_recreate_invalidated | standby | on | Drop and recreate a synchronized slot whose copy was invalidated on the standby. off leaves it as it is and reports it once. PG15-17 only; ignored on PG17 with native slot sync and on PG18+ (SIGHUP). |
spock.failover_slots_database | standby | '' | Database the worker connects to so it can decode each copy on the standby and give it a consistent snapshot. Off by default; without it, transactions can be lost after a promotion. PG16-17 only, ignored on PG18+; on PG16 it must be the slots’ database (restart). |
hot_standby_feedback = on plus a physical slot named by primary_slot_name is
the important pair. Without both, the primary can remove catalog rows a slot
still needs, and the slot is invalidated with a message about conflicting with
recovery.
Setup: PostgreSQL 17 and 18 (Native)
This is the native slot sync path. It is the only option on PostgreSQL 18. On
PostgreSQL 17 it is optional: the Spock worker runs by default, and setting
sync_replication_slots = on on the standby tells Spock to step aside and let
core PostgreSQL do the sync instead. Native sync only copies slots that have
failover = true. Spock 6.0.0 sets that flag when it creates a slot. If you
have slots from an older Spock release, see the upgrade section below. To
switch a PostgreSQL 17 standby the Spock worker has been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker
instead: setting sync_replication_slots = on alone leaves most or all
slots unsynchronized.
1. Create a physical replication slot on the primary
2. Configure the primary (postgresql.conf)
3. Configure the standby (postgresql.conf)
4. Verify slot synchronization
On the standby, confirm that Spock’s logical slots are synchronized:
All Spock slots should show synced = true and failover = true.
5. After failover
After promoting the standby, subscribers only need to update their connection string to point to the new primary. Replication resumes from the last synchronized LSN with no data loss and no slot recreation required.
Important: if the promoted node has synchronized_standby_slots or
spock.pg_standby_slot_names set, you must adjust it before replication will
resume: both name physical slots the new primary does not have. See
Runbook: clear synchronized_standby_slots after promotion
below.
Switching a PostgreSQL 17 standby from the Spock worker
Copies that the Spock worker made on the standby have synced = false.
Native slot sync will not take over a slot of the same name, and keeps
failing until those copies are gone. To switch:
On the primary, list the slots the standby should carry. The Spock worker copies every logical slot that
spock.synchronize_slot_namesmatches (all of them by default), but native slot sync copies only slots withfailover = true:spock.slot_enable_failover()sets the flag on Spock’s own slots (see Upgrading Spock to 6.0.0). Set it on any other slot you want kept, for example withALTER SUBSCRIPTION ... SET (failover = true)on a PostgreSQL subscriber, with the subscription disabled while you run it. A slot without it is not synchronized after the switch. Leave the primary’s standby holdback (spock.pg_standby_slot_namesorsynchronized_standby_slots) as it is; if neither is set, see step 2 of the native setup.On the standby, check
wal_level = logicaland thatprimary_conninfoincludesdbname. Native slot sync opens a normal database connection withprimary_conninfo, not a replication one, so its user needs apg_hba.confentry andCONNECTon that database on the primary; the Spock worker may have connected as someone else throughspock.primary_dsn. Then setsync_replication_slots = onand reload. The Spock worker stops synchronizing.Wait one
spock.failover_slots_naptime, then list the copies the Spock worker made on the standby. A pass that was already running can outlast the wait and make a copy after the drop; step 4 finds it.A copy has the same name as a slot on the primary. A slot that exists only on the standby, such as one created there for decoding on the standby, is not a copy: leave it. A copy that shows
active = trueis in use, and the drop fails until the process inactive_pidstops using it; stop that client, or end it withpg_terminate_backend(active_pid). Drop each copy by name:Run the query from Verify slot synchronization until every slot with
failover = trueon the primary appears on the standby withsynced = trueand noinvalidation_reason. If a drop in step 3 failed, or a copy still showssynced = false, drop it again. If no slot appears, check the standby’s log for slot sync connection errors. Native slot sync keeps a new copy temporary, and out of this query, until the slot’s consumer on the primary has moved past the position the standby reserved for it; meanwhile the standby logs “could not synchronize replication slot”. A slot whose subscriber is idle, paused or down can stay that way until the subscriber catches up.
Until native slot sync has recreated a slot, the standby has no usable copy of it, so do not promote the standby in between.
Runbook: clear synchronized_standby_slots after promotion
When synchronized_standby_slots is configured (Setup step 2 above), the
provider’s walsenders hold back logical decoding until every physical slot
named in that list has confirmed flush of the relevant LSN. This is what
keeps a physical standby from falling behind a logical subscriber, but it
has a sharp edge on failover.
The setting is meant for the primary, but the standby often has it too:
- it was already in the primary’s
postgresql.auto.confwhen the standby was built withpg_basebackup, which copies that file, - the same
postgresql.confis deployed to every node, or - a cluster manager such as Patroni applies one configuration to every member (see Running Under Patroni).
If the standby has it, then once it is promoted the setting still lists the
physical slot(s) that fed replication to that node before promotion. Those
slots are now orphaned: nothing is consuming them any more, so they never
confirm, and the promoted node’s walsenders sit blocked waiting on them
indefinitely. The practical symptom is that logical replication to
subscribers freezes immediately after a promotion that otherwise looked
successful. Check on the promoted node with SHOW synchronized_standby_slots;.
When it is set, clearing it is a mandatory post-promotion step, not optional cleanup:
The physical slot itself lives on the server that created it. In the setup
above that is the old primary, so drop spock_standby_slot there once that
node is rebuilt or retired:
Under Patroni the member slots are Patroni’s: it removes a departed member’s
slot after member_slots_ttl, so do not drop them by hand.
If the new topology has its own physical standby(s), set
synchronized_standby_slots to the physical slot(s) for that standby
instead of clearing it to ''. The point is to remove references to
orphaned slots, not to leave the setting pointing at slots nothing will ever
consume.
Add this step to your failover runbook alongside the subscriber DSN update described above; skipping it is the most common cause of “failover succeeded but replication stopped” reports when native failover slots are in use.
Running Under Patroni (PostgreSQL 17+)
Patroni manages replication slots itself, and the way it does so decides which of Spock’s two mechanisms can work under it.
- Member slots. With
postgresql.use_slots: true(the default) Patroni creates one physical slot per replica on that replica’s upstream, named after the member (see naming below), and drops it once the member has been gone formember_slots_ttl(default30min). On a switchover the new leader creates fresh slots for the others. - Permanent slots. Slots listed under
slots:in the dynamic configuration survive switchover. Permanent logical slots are copied from the leader to each replica by stopping and restarting the replica, then advanced everyloop_waitseconds. That is Patroni’s own answer to logical slot failover, written before PostgreSQL had one. - Unknown slots. On a replica, Patroni drops logical slots it does not
manage. Since Patroni 4.1.0 it leaves slots created with
failover = truealone, with one exception on PostgreSQL 17 and later: on a replica it removes failover slots whosesyncedis false, which is what a former leader’s own slots look like after a switchover, so that PostgreSQL’s slotsync worker can recreate them as synchronized copies of the new leader’s. Patroni 4.1.4 fixed a crash in that path.
Spock’s built-in spock_failover_slots worker is unreliable under Patroni.
It copies logical slots to the standby by hand and relies on the standby’s
physical slot, through hot_standby_feedback, to pin catalog_xmin on the
primary. Patroni drops and recreates that physical slot as the topology
changes, which lets vacuum on a busy primary remove catalog rows a copied
slot still needs; the slot is then invalidated (invalidation_reason = rows_removed) and the subscriber has to resynchronize from scratch.
The path that works is PostgreSQL’s own: Spock creates its logical slots
with the FAILOVER flag, so with sync_replication_slots = on the slotsync
worker keeps them current on every member, and Patroni, from 4.1.0 on,
stays out of their way. On PostgreSQL 18 this is the only path, because
Spock’s worker is not registered there. On PostgreSQL 17 Spock’s worker
runs unless sync_replication_slots = on is set, so under Patroni set it;
for a member the Spock worker has already been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker.
The mechanism is the one described under
Setup: PostgreSQL 17 and 18 (Native);
this section is about where those settings go in a Patroni configuration
and what a switchover does to them.
Requirements: Patroni 4.1.4 or later, on PostgreSQL 17 or later. On an
older Patroni release, protect the slots with an ignore_slots entry in the
dynamic configuration, so that Patroni neither drops nor copies them:
Required settings
| Setting | Value | Where | Restart? | Why |
|---|---|---|---|---|
sync_replication_slots | on | dynamic config | No (reload) | PostgreSQL’s slotsync worker copies flagged slots to every replica |
hot_standby_feedback | on | dynamic config | No (reload) | Required by slot synchronization; pins catalog_xmin so vacuum cannot remove rows a slot needs. Patroni turns it on by itself only when permanent logical slots are configured, so set it |
wal_level | logical | dynamic config | Yes | Required for logical decoding and for slot synchronization |
output_plugin_libraries | include spock_output | dynamic config, every member | No (reload) | Only on servers that have the parameter (see below). A synchronized slot keeps spock_output as its plugin, so a member missing this setting cannot serve replication once promoted |
postgresql.use_slots | true | Patroni config | n/a | The default. Patroni creates the member slot each replica streams through and sets primary_slot_name to it, which slot synchronization requires |
max_replication_slots / max_wal_senders | sized to cluster | dynamic config | Yes | Member slots plus Spock’s logical slots on every node; see Sizing |
synchronized_standby_slots | standby member slot name(s) | dynamic config or callback | No (reload) | Optional but recommended; holds the leader’s walsenders back until the standby has the WAL. See the sharp edge |
Two requirements of slot synchronization need no action under Patroni: the
primary_conninfo Patroni writes for a replica always carries dbname, and
primary_slot_name is the member slot.
“Dynamic config” means Patroni’s DCS-backed configuration:
bootstrap.dcs.postgresql.parameters when you first bootstrap the cluster,
and patronictl edit-config for a running one. The next subsection shows the
full bootstrap block.
Where the settings go (bootstrap)
Cluster-wide PostgreSQL parameters belong in Patroni’s dynamic configuration
(bootstrap.dcs.postgresql.parameters at bootstrap, patronictl edit-config
afterwards) so every member, current and future leader, agrees on them.
Set them there, not in a per-node postgresql.conf.
output_plugin_libraries arrived with PostgreSQL’s 2026 security fix
(CVE-2026-6471, back-patched to every supported major): a library may not be
used as an output plugin unless it is listed there, and the default excludes
spock_output. A synchronized slot keeps spock_output as its plugin, so a
member without this setting looks healthy while it is a replica and then fails
to serve replication the moment it is promoted — the failure surfaces during a
switchover, which is the worst time to find it. It is PGC_SUSET, so Patroni
reloads it without a restart.
Do not set it on a release that predates the fix: an unrecognised parameter
stops the server from starting, and pushing one through the DCS stops every
member. Check first, on each member, with
SELECT current_setting('output_plugin_libraries', true) — a NULL result means
the parameter does not exist.
Do not declare the Spock logical slots as Patroni permanent logical
slots (the slots: block). That is the hand copying the native path
replaces: Patroni would restart replicas to copy the slots and advance them
itself, in competition with the slotsync worker. Leave the slots: block to
physical slots you need preserved, and the logical slots to PostgreSQL.
Slot names
Patroni derives a member’s slot name from the member name: lowercased, with
- and . turned into _, any other character outside [a-z0-9_] spelled
as u followed by its four-digit code point, and cut at 63 characters. A
member pg-node.1 streams through slot pg_node_1. Whatever names the slots
in synchronized_standby_slots has to follow the same rule, which is why the
sample callback below asks Patroni for the name rather than computing it.
The switchover sharp edge: synchronized_standby_slots
synchronized_standby_slots names the physical slot(s) the leader’s
walsenders must wait for, so that no logical subscriber gets ahead of the
standby that may be promoted. Under Patroni those are the member slots, so
on a two-member cluster with leader n2 and replica r1 the leader needs:
The edge is that this value is role-specific while Patroni’s dynamic
configuration is cluster-wide. Hardcode 'r1' and switch over so that r1
becomes leader, and the new leader waits for a slot named after itself, which
does not exist on it: its walsenders block and logical replication freezes.
This is the failure the
post-promotion runbook
describes, and under Patroni it recurs on every switchover unless handled.
The same wait applies to any listed member that is down. Its slot stays on
the leader, inactive, until member_slots_ttl expires and Patroni drops it,
and a slot that is inactive or missing blocks alike. A standby that stops
therefore stops logical replication until it is back or removed from the
list.
Three ways to handle it:
Automate it with a callback and a periodic reconcile. Patroni runs the
on_role_changecallback on promotion and demotion with the argumentson_role_change <role> <scope>; the role isprimaryorreplica(masteron releases before 4.0). On becoming leader the script setssynchronized_standby_slotsto the slots of the other members that are up and reloads; on becoming a replica it clears it.That callback alone is not enough, because Patroni does not run it when a standby that was down comes back, nor when one goes away. A standby that rejoins after a promotion would stay off the list, and subscribers could advance ahead of it. So the same script is also run periodically on every member, from cron or a systemd timer, as
set_synchronized_standby_slots.sh reconcile <scope>: it asks Patroni for the member’s current role and brings the setting up to date, touching it only when it differs. A standby is protected from the first reconcile after it streams again; choose the interval accordingly.A reference implementation ships with Spock at
samples/set_synchronized_standby_slots.sh. It reads the member name frompatroni.yml, derives slot names with Patroni’s own function, skips members that are not running or streaming, and leaves the setting untouched when the member list cannot be read. It supports Patroni’s own member slots only, withuse_slotson and no hand-madeprimary_slot_name. Review and adapt it before production use.Let Patroni manage it. Patroni’s development branch has a
manage_synchronized_standby_slotsoption that keepssynchronized_standby_slotsequal to the synchronous standbys ofsynchronous_standby_names; it needssynchronous_modeand is not in a released version at the time of writing (4.1.5 is the latest). Once it ships, prefer it to the callback on clusters that run synchronous replication.Leave it unset and accept the trade-off. Nothing freezes on switchover, but the leader no longer waits for the standby before letting subscribers advance, so a subscriber can be slightly ahead of the standby at the moment of promotion and the new leader marginally behind it. For zero data loss, use one of the two options above.
What a switchover does
patronictl switchoverdemotes the leader and promotes a replica.- On the new leader the synchronized Spock slots become usable; the subscribers only need their DSN pointed at it, as described under After failover.
- The old leader rejoins as a replica. Its own Spock slots carry
failover = trueandsynced = false; Patroni 4.1.0 and later drops them there, and the slotsync worker recreates them as synchronized copies from the new leader. - Whatever manages
synchronized_standby_slotshas to run: the callback fires on both nodes, or you apply the runbook by hand.
Verify
After bootstrap, and again after a switchover, confirm every replica carries the flagged, synchronized slots:
synced and failover should both be true and invalidation_reason
NULL. If failover is false, the slot was created by a Spock release
before 6.0.0 and the upgrade could not flag it. See
Upgrading Spock to 6.0.0 for how to handle it.
On the leader, SHOW synchronized_standby_slots should name the slots of
the replicas that are up, and patronictl list should show them streaming.
Setup: PostgreSQL 15 and 16 (Spock Worker)
On PostgreSQL 15 and 16, the spock_failover_slots background worker
periodically copies slot state from the primary. The worker is registered on
every node, but it only does this work while the server is in recovery; on a
primary it idles.
Requirements
hot_standby_feedback = onon the standby (required before the worker will synchronize anything)- The standby must be able to connect to the primary
Configuration GUCs
| GUC | Default | Description |
|---|---|---|
spock.synchronize_slot_names | name_like:%% | Slot name patterns to sync (all by default) |
spock.drop_extra_slots | on | Drop standby slots not matching the pattern |
spock.primary_dsn | '' | DSN to connect to primary (falls back to primary_conninfo) |
spock.pg_standby_slot_names | '' | Physical slots that must confirm LSN before logical replication advances |
spock.standby_slots_min_confirmed | -1 | How many slots from pg_standby_slot_names must confirm (-1 = all) |
spock.failover_slots_naptime | 1000 | Worker sleep between slot-sync passes, in ms (SIGHUP; range 1–3600000) |
spock.failover_slots_feedback_naptime | 10000 | Shorter retry, in ms, while waiting for standby WAL feedback (SIGHUP; range 1–3600000) |
spock.failover_slots_recreate_invalidated | on | Drop and recreate a synchronized slot whose copy was invalidated on the standby; off leaves it as it is and reports it once. PG15-17 only; ignored on PG17 with native slot sync and on PG18+ (SIGHUP) |
spock.failover_slots_database | '' | Database the worker connects to so it can decode each copy on the standby and give it a consistent snapshot; off by default. PG16-17 only, ignored on PG18+; on PG16 the slots’ database (restart) |
Example (postgresql.conf on standby)
Upgrading Spock to 6.0.0
New slots created by Spock 6.0.0 already have failover = true. Slots created
by an older Spock release do not, and native slot sync on PostgreSQL 17 and 18
ignores slots that do not have the flag. The upgrade turns the flag on for those
existing slots.
This section covers only the failover part of the upgrade. For the full procedure (disabling auto-DDL, installing the new binaries, and restarting each node), follow Upgrading the Spock Extension first. The steps below run after the 6.0.0 binaries are installed.
1. Run the extension update
PostgreSQL walks the version chain (5.0.8 to 5.0.9 to 5.0.10 to 5.0.11 to
5.0.12 to 5.0.13 to 5.0.14 to 6.0.0) and runs each step in order. The 5.0.14
to 6.0.0 step calls
spock.slot_enable_failover() for you.
spock.slot_enable_failover() behaves as follows:
- On PostgreSQL 16 and older it does nothing, because the flag does not exist.
- On a standby it does nothing, because the flag can only be set on a primary.
- It sets
failover = trueon each Spock logical slot that does not already have it. - It skips any slot that is in use at that moment and prints a NOTICE naming the slot.
- It returns the number of slots it changed.
2. Handle any skipped slots
A slot that is actively streaming to a subscriber cannot be changed while it is held, so the function leaves it alone and tells you which one. To set the flag on those slots, pause the subscribers that hold them and run the function again on the primary:
3. Verify
On the primary, every Spock slot should now show failover as true:
The upgrade does not change any PostgreSQL settings. On PostgreSQL 18,
configure native slot sync on the standby yourself as described in
Setup: PostgreSQL 17 and 18 (Native):
sync_replication_slots = on, dbname in primary_conninfo, and the
physical slot listed in synchronized_standby_slots on the primary. To switch a
PostgreSQL 17 standby to the native path, follow
Switching a PostgreSQL 17 standby from the Spock worker.
Monitoring
Check slot sync status (PG17+)
Check if native slotsync worker is active (PG17+)
Check spock worker is running (PG15/16)
This row is present on primaries too, where the worker is resident but idle,
so a hit here confirms only that the worker was registered - not that slots
are being synchronized. Confirm that on the standby by comparing
confirmed_flush_lsn against the primary, and look for the
slot synchronization from primary now active message in the standby log.
FAQ
Q: Do I need to do anything after a failover?
On PG17+: update the subscriber’s host= in their DSN, and, if the promoted
node has synchronized_standby_slots set, clear/adjust it as described in the
runbook above.
No slot recreation is needed.
On PG15/16: Spock’s worker on the standby (now primary) stops
synchronizing slots, since the server is no longer in recovery. The worker
process itself remains, idle, and still holds its max_worker_processes slot.
Subscribers reconnect automatically.
Q: What if sync_replication_slots is not configured on PG18?
Spock’s worker is not registered on PG18. If sync_replication_slots = on
is not set, logical slots will not be synchronized to standbys, and a
failover will require manual slot recreation and table re-sync.
Q: Can I use both mechanisms on PG17?
No. If sync_replication_slots = on is set on PG17, Spock’s worker detects
this and skips its sync loop, deferring to the native worker entirely. To
switch a standby the Spock worker has been syncing, follow
Switching a PostgreSQL 17 standby from the Spock worker.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.15 - Limitations and Restrictions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock has several limitations and restrictions that users should be aware of when designing and implementing replication scenarios.
Superuser Privileges Are Required
Currently, the Spock extension requires superuser privileges to configure replication and administration.
UNLOGGED and TEMPORARY Tables Are Not Replicated
UNLOGGED and TEMPORARY tables will not and cannot be replicated, much
like with physical streaming replication.
One Database at a Time
To replicate multiple databases you must set up individual provider or subscriber relationships for each. There is no way to configure replication for all databases in a PostgreSQL install at once.
PRIMARY KEY or REPLICA IDENTITY Required
UPDATEs and DELETEs cannot be replicated for tables that lack a PRIMARY KEY or other valid replica identity such as using an index, which must be
unique, not partial, not deferrable, and include only columns marked NOT
NULL. Replication has no way to find the tuple that should be updated or
deleted since there is no unique identifier.
REPLICA IDENTITY FULL is not supported as a standalone replication identity
for UPDATE or DELETE operations. However, it is supported when used in
conjunction with Delta-Apply columns on tables that have a primary key. For
tables without a primary key or Delta-Apply configuration, UPDATE and DELETE
operations require a PRIMARY KEY or explicit REPLICA IDENTITY USING INDEX.
Only One Unique Index or Constraint or PK
If more than one upstream is configured or the downstream accepts local
writes, only one UNIQUE index should be present on downstream replicated
tables. Conflict resolution can only use one index at a time, so conflicting
rows may ERROR if a row satisfies the PRIMARY KEY but violates a UNIQUE
constraint on the downstream side.
You can have additional unique constraints upstream if the downstream consumer gets writes from that upstream and nowhere else. The rule is that the downstream constraints must not be more restrictive than those on the upstream(s).
Partial secondary unique indexes are permitted, but will be ignored for conflict resolution purposes.
spock.check_all_uc_indexes is an experimental
GUC that
adds INSERT conflict resolution by allowing Spock to consider all unique
constraints, not just the primary key or replica identity.
Unique Constraints Must Not Be Deferrable
Deferrable unique constraints and primary keys are silently skipped during INSERT conflict resolution. This means that if your only unique constraint on a table is deferrable, INSERT conflicts will not be detected, potentially leading to duplicate rows on subscriber nodes.
On the downstream end, spock may also emit the error:
Recommendation: Ensure all tables have at least one non-deferrable unique constraint (preferably the primary key) for reliable conflict detection.
No Replication Queue Flush
There is no support for freezing transactions on the master and waiting until all pending queued xacts are replayed from slots.
This means that care must be taken when applying table structure changes. If there are committed transactions that are not yet replicated and the table structure of the provider and subscriber are changed at the same time in a way that makes the subscriber table incompatible with the queued transactions replication will stop.
Administrators should either ensure that writes to the provider are stopped
before making schema changes, or use the spock.replicate_ddl function to
queue schema changes so they are replayed at a consistent point on the
subscriber.
In multi-master configurations, using spock.replicate_ddl alone is not
sufficient. The subscriber may be generating new transactions with the old
structure after the schema change is committed on the provider. Users must
ensure writes are stopped on all nodes and all slots are caught up before
making schema changes.
FOREIGN KEYS
Foreign keys constraints are not enforced for the replication process - what
succeeds on provider side gets applied to subscriber even if the FOREIGN KEY
would be violated.
TRUNCATE
Using TRUNCATE ... CASCADE will only apply the CASCADE option on the
provider side.
(Properly handling this would probably require the addition of ON TRUNCATE CASCADE
support for foreign keys in PostgreSQL).
TRUNCATE ... RESTART IDENTITY is replicated. The sequence restart is
applied on subscriber nodes. Note that this may cause sequence value
divergence if sequences are not managed via pgEdge Snowflake.
Sequences
We strongly recommend that you use pgEdge Snowflake Sequences rather than using the legacy sequences described below.
The state of sequences added to replication sets is replicated periodically
and not in real-time. Dynamic buffer is used for the value being replicated
so that the subscribers actually receive future state of the sequence. This
minimizes the chance of subscriber’s notion of sequence’s last_value
falling behind but does not completely eliminate the possibility.
It might be desirable to call sync_sequence to ensure all subscribers have
up to date information about given sequence after big events in the database
such as data loading or during the online upgrade.
It is generally recommended to use bigserial and bigint types for
sequences on multi-node systems as smaller sequences might reach end of the
sequence space fast.
Users who want to have independent sequences on provider and subscriber can
avoid adding sequences to replication sets and create sequences with step
interval equal to or greater than the number of nodes. And then setting a
different offset on each node. Use the INCREMENT BY option for CREATE SEQUENCE or ALTER SEQUENCE, and use setval(...) to set the start point.
Triggers
Apply process and the initial COPY process both run with
session_replication_role set to replica which means that ENABLE REPLICA
and ENABLE ALWAYS triggers will be fired.
PostgreSQL Version Differences
Spock can replicate across PostgreSQL major versions. Despite that, long term cross-version replication is not considered a design target, though it may often work. Issues where changes are valid on the provider but not on the subscriber are more likely to arise when replicating across versions.
It is safer to replicate from an old version to a newer version since PostgreSQL maintains solid backward compatibility but only limited forward compatibility. Initial schema synchronization is only supported when replicating between same version of PostgreSQL or from lower version to higher version.
Replicating between different minor versions makes no difference at all.
Database Encoding Differences
Spock does not support replication between databases with different encoding.
The encoding must match on all nodes in the cluster. While UTF-8 is
commonly used and recommended for international character support, any
encoding is acceptable as long as it is consistent across all nodes.
Large Objects
PostgreSQL’s logical decoding facility does not support decoding changes to large objects; we recommend using the LOLOR extension to manage large objects.
Note that DDL limitations apply, so extra care needs to be taken when using
replicate_ddl_command().
Delta-Apply Column Requirements
Columns configured for Delta-Apply conflict resolution must have a NOT NULL
constraint. If a NULL value is encountered during delta application, the apply
worker will error with:
Ensure all Delta-Apply columns are defined with NOT NULL before enabling
this feature.
Mixed Spock and Native Logical Replication
Spock uses its own 16-bit node_id (derived from node name hash) to track transaction origins in commit timestamps, rather than PostgreSQL’s RepOriginId. Both ID spaces overlap (0-65535), which can cause ambiguity if Spock and native PostgreSQL logical replication run on the same database.
Recommendation: Avoid running Spock and native logical replication subscriptions on the same database.
Row and Column Filters
Row and column filters have the following limitations.
System Columns Cannot Be Filtered
System columns (such as oid or xmin) cannot be used in row filters or
column filters. Column and row filters work correctly on tables with OIDs,
but the system columns themselves cannot be filtered.
Row Filter Expression Constraints
Row filters are normal PostgreSQL expressions with the same limitations as CHECK constraints.
A row filter can call random() or now(). random() is VOLATILE and can change on each call. now() is STABLE within a transaction, but different transactions can see different values. Consider when the expression is evaluated to avoid inconsistent results and replication errors.
Row Filter Session Context
Row filters run in the replication session context, not the original
session context. This means that session-specific expressions (like
CURRENT_USER) will have replication session values, not the original
session values.
Column Filter Behavior
When using column filters, note the following behaviors:
- Dropping a filtered column automatically removes it from the filter.
- New columns are not automatically included in existing filters.
- Column filters must be updated manually to include new columns.
Partitioned Tables
Partitioned tables have specific replication limitations.
New Partitions Not Automatically Replicated
When partitions are added after initial synchronization, they must be
added manually using the spock.repset_add_partition() function.
The parent table is synchronized during initial sync, but individual partitions are not synced directly. New partitions created after sync require explicit addition to the replication set.
Detached Partitions Not Automatically Removed
Detaching a partition does not automatically remove it from replication.
You must use spock.repset_remove_partition() to update cluster metadata
and remove the partition from the replication set.
DDL Replication Limitations
Some DDL statements are intentionally not replicated.
DDL Statements Not Replicated
The following types of DDL statements are not replicated:
CREATE DATABASE- Database creation is not replicated.CREATE TABLE...AS...- This statement is replicated but may be unsafe because the table is replicated before being added to the replication set.
In multi-node clusters with three or more nodes, some DDL statements (such
as DROP TABLE) may cause replication issues.
DDL Replication Best Practices
For best results, enable automatic DDL replication only when the schema matches exactly on all nodes. This means either all databases have no objects, or all databases have exactly the same objects with all tables in the replication sets.
Spock Schema
The spock schema is managed internally by Spock and has the following
restriction.
Direct Modification Prohibited
Do not delete, create, or modify files in the spock schema directly. Use
Spock functions and procedures to manage replication. Direct schema
modification can corrupt replication metadata and cause replication
failures.
Read-Only Mode
Read-only mode has the following limitation.
Read-Only at SQL Level Only
The spock.readonly parameter enforces read-only restrictions at the SQL
level for non-superusers. However, background processes (checkpointer,
background writer, WAL writer, and autovacuum) continue to run and may
write to disk.
This means that database files are not truly read-only, and some disk writes may still occur even when read-only mode is enabled.
Replication Position Skipping
Using spock.sub_alter_skiplsn() to skip replication positions has the
following critical limitation.
Skipped Data Not Replayed or Repaired
The spock.sub_alter_skiplsn() operation does not replay or repair
skipped data. Any changes between the old LSN and the specified LSN are
permanently ignored by the subscriber.
Use this function only when you understand the data implications and accept that skipped changes will be lost on the subscriber node.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.16 - Internals
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
2.16.1 - Design proposals
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
2.16.1.1 - Eliminating the Spock checkpoint hook and per-commit WAL flush for spock.progress
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Date: 2026-04-21 (revised 2026-05-01 to reflect as-built behavior) Status: Implemented
Two design changes from the original proposal, both expanding scope:
remote_commit_tsis recovered post-crash via apg_commit_tsscan, not left NULL. The original design accepted NULL as a freshness regression; the implementation runs a backward scan ofpg_commit_tsfor the relevant origin and repopulates the field. Promoted from a “follow-up” to a goal sospock.progressshows an accurate timestamp after a crash. The recoveredprev_remote_tsis also intended to be useful for the planned parallel-apply rework.- The RMGR (id 144) is kept, retargeted from apply-progress recovery to per-event progress records. The original design deleted it entirely. The shipped version retains the registration and emits one WAL record per affected
SpockGroupHashentry at eachresource.datdump call site (clean shutdown,add_node, table-sync). Each record carries the fullSpockApplyProgresssnapshot for that entry. The records are not required for state recovery; they exist so apg_waldumptrace shows the exact progress snapshot persisted at each event LSN — useful for incident reconstruction over time. A singleXLogFlushat the end of each emit batch gives WAL durability symmetric withresource.dat’sdurable_rename().Sections below are updated to reflect what shipped.
Problem
Spock currently maintains the spock.progress view via three coupled mechanisms:
- A custom WAL RMGR (
src/spock_rmgr.c) that emits aSPOCK_RMGR_APPLY_PROGRESSrecord on every applied remote-origin commit and callsXLogFlushsynchronously (in addition to theXLogFlushthat core’sCommitTransactionCommandalready performs). - A
Checkpoint_hook(registered insrc/spock.c:1248) that dumps the in-memorySpockGroupHashtoPGDATA/spock/resource.datat every Postgres checkpoint. This requires a patch to Postgres core (src/backend/access/transam/xlog.candsrc/include/access/xlog.h) to add the hook callout. - A load/redo path that seeds shmem from
resource.datduringshmem_startup_hookand overwrites with WAL redo ofAPPLY_PROGRESSrecords during recovery.
This design has two costs:
- A Postgres core patch (4 lines across 2 files) must be maintained for each supported Postgres version.
- An extra synchronous
XLogFlushon every applied remote-origin commit, purely to persist monitoring data — doubling the fsync pressure of the apply hot path.
Investigation showed that Spock’s apply worker already uses Postgres’s native replication origins (replorigin_session_get_progress) to determine the resume LSN on reconnect. The correctness-critical “where do I resume from” question is handled entirely by stock logical-replication protocol. The checkpoint hook and WAL RMGR exist only to preserve additional monitoring-level fields (remote_commit_ts, remote_insert_lsn, received_lsn, last_updated_ts) across crashes. The checkpoint hook in particular was added (commit a4b93e8) to handle the case where apply workers are idle across a checkpoint — keepalive-driven advances of remote_insert_lsn are never WAL-logged, so the hook is the only path that preserves them.
Goal
Remove the Postgres core patch (Checkpoint_hook) and the extra per-commit XLogFlush, while preserving user-visible spock.progress behavior across clean and crash restarts. Recover remote_commit_ts after crash via a backward scan of pg_commit_ts for the relevant origin so the view shows an accurate timestamp; the recovered prev_remote_ts is also intended to be useful for the planned parallel-apply rework.
Non-goals
- Changing the
spock.progresscolumn schema or the SQL-level API. - Altering apply-worker resume semantics (which are already handled by Postgres replication origins and need no change).
- Removing or reshaping the
SpockGroupHashshmem layout or theSpockApplyProgressstruct. - Recovering
last_updated_tsprecisely (apply-time timestamp). Post-crash, set to the recoveredremote_commit_ts(the publisher’s commit timestamp) — a lower bound on local apply time that under-reports lag rather than zeroing it. Refreshes on the next applied commit.
Design overview
The shipped design keeps resource.dat as a snapshot written at three call sites — clean shutdown (supervisor before_shmem_exit), add_node, and table-sync — and replaces WAL-based durability with three components:
- Replication origins as the source of truth for
remote_commit_lsn. At apply-worker startup, read the origin’s LSN and reconcile shmem against it. Ifresource.datholds a stale LSN for an entry (file_lsn < origin_lsn), the file’s timestamp fields for that entry are cleared to NULL pending recovery by step 3. - A forced keepalive on apply-worker (re)connect. The subscriber sends a status-update message with
replyRequested=trueimmediately afterspock_start_replicationreturns. Postgres’s walsender responds with a ‘k’ keepalive carrying its currentsentPtr. The apply worker’s existing keepalive handler populatesremote_insert_lsnandreceived_lsnin shmem within milliseconds of reconnect, rather than waiting forwal_sender_timeout / 2(default 30s) to elapse. - A backward
pg_commit_tsscan to recoverremote_commit_tsper origin. When reconcile detects stale or absent state, a follow-on routinerecover_progress_timestamps_from_commit_ts()walkspg_commit_tsbackward from the latest xid, filtering on the publisher’s origin id, and writes the max-by-ts back into shmem. Termination at 1000 commits seen for the origin or 1M xids total scanned, whichever first.last_updated_tsis set to the same recoveredremote_commit_tsso the XOR invariant inprogress_update_structholds; using the publisher’s commit_ts (rather than the subscriber’s wall clock) gives a lower bound on local apply time that under-reports lag instead of hiding it as zero.
Together these handle every shmem field without WAL or checkpoint-time persistence:
| Field | Source | When authoritative |
|---|---|---|
remote_commit_lsn | Replication origin (replorigin_session_get_progress) | At apply-worker startup, always correct |
remote_commit_ts | resource.dat if validated against origin LSN; else pg_commit_ts scan | Preserved across clean restart; recovered post-crash; NULL only on fresh first start (no commits yet) |
remote_insert_lsn | Forced ‘k’ keepalive | Within ~ms of apply worker connect |
received_lsn | Same | Same |
last_updated_ts | GetCurrentTimestamp() at each update; post-crash set to the recovered remote_commit_ts | Always advances during apply; post-crash pinned to the recovered publisher commit_ts as a lower bound on local apply time (under-reports lag rather than zeroing it); refreshes on next applied commit |
prev_remote_ts | Set together with remote_commit_ts (same value) | Same as remote_commit_ts — recovered alongside |
Architecture
Startup flow
Phase 1 — shmem_startup_hook (pre-recovery).
Runs via spock_group_shmem_startup(), unchanged from today except that the spock RMGR no longer carries apply-progress records so WAL recovery has no state-bearing Spock records to redo:
- Create the empty
SpockGroupHashHTAB. - Call
spock_group_resource_load()to loadPGDATA/spock/resource.datif present and valid (version andsystem_identifiermatch). Each record is upserted into the hash viaspock_group_progress_update(). - No state-bearing WAL redo for Spock records. The RMGR (id 144) is retained but its only record type is a dump-event marker whose redo handler emits a
LOGline and does not touch shmem.
At the end of phase 1, shmem contains either an empty hash or the contents of the last clean shutdown’s resource.dat. Values may be stale if a crash occurred since that shutdown.
Phase 2 — per-apply-worker reconciliation.
In spock_apply_main(), after replorigin_session_setup() returns the session’s origin but before spock_start_replication() is called, each worker reconciles its own shmem entry. reconcile_progress_with_origin() returns a ReconcileResult enum so the caller can gate Phase 3 (the recovery scan) on whether reconcile detected staleness.
- Compute the shmem key:
(MyDatabaseId, MySubscription->target->id, MySubscription->origin->id). - Fetch
origin_lsn = replorigin_session_get_progress(false). - Acquire
SpockCtx->apply_group_master_lockin exclusive mode; HASH_ENTER for the entry:- Entry absent. Initialize with
remote_commit_lsn = origin_lsn, other fields zero/NULL. Result:RECONCILE_FILE_ABSENT. - Entry present,
file_lsn == origin_lsn. File is in sync with the origin. Keepremote_commit_tsandlast_updated_tsas loaded. Result:RECONCILE_FILE_IN_SYNC. - Entry present,
file_lsn < origin_lsn. File is stale for this entry. Overwriteremote_commit_lsnwithorigin_lsn; clearremote_commit_tsandlast_updated_tsto 0; bumpremote_insert_lsnandreceived_lsnup to at leastorigin_lsnto preserve theinsert_lsn >= commit_lsninvariant (the forced keepalive will refresh them shortly). Result:RECONCILE_FILE_STALE. - Entry present,
file_lsn > origin_lsn. Anomalous; shouldn’t occur in normal flow. Log a warning and preferorigin_lsn(same body as STALE). Result:RECONCILE_FILE_ANOMALY.
- Entry absent. Initialize with
- Release the lock and return the result.
Phase 2 lives in the apply worker (not the shmem_startup_hook) because the startup hook runs before catalogs and subscriptions are readable.
Phase 3 — pg_commit_ts scan to recover remote_commit_ts.
If reconcile returned anything other than RECONCILE_FILE_IN_SYNC, run recover_progress_timestamps_from_commit_ts(entry, target_origin) where target_origin = MySubscription->origin->id (the publisher’s spock node id, which is what pg_commit_ts records for applied xacts on the subscriber — handle_origin() overwrites replorigin_session_origin per-message with that value).
The scan walks backward from ReadNextTransactionId() - 1 in batches of SPOCK_TS_RECOVERY_BATCH_SIZE (1000), calling TransactionIdGetCommitTsData(xid, &ts, &origin) for each xid. Filter: origin == target_origin. Track per-origin running_max_ts and seen_count. Terminate when:
seen_count >= SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN(1000), ortotal_scanned >= SPOCK_TS_RECOVERY_SCAN_LIMIT(1M), or- backward scan reaches
FirstNormalTransactionId.
The 1000-commits-per-origin termination is justified by concurrency width: the publisher’s max in-flight xacts is bounded well below 1000 by max_connections and pooler limits, so any commit older than the 1000th observed has a strictly smaller commit_ts than the max already seen — even under parallel apply where xid order ≠ commit_ts order on the subscriber.
If running_max_ts > 0, write it under the master lock to remote_commit_ts, prev_remote_ts, and last_updated_ts (XOR invariant in progress_update_struct requires remote_commit_ts and last_updated_ts to be both zero or both non-zero). Using the recovered publisher commit_ts for last_updated_ts rather than the subscriber’s wall clock gives a lower bound on local apply time, which under-reports lag instead of hiding it. The next applied commit refreshes last_updated_ts to the actual subscriber-side GetCurrentTimestamp(). If running_max_ts == 0, log a WARNING and proceed with NULL.
The constants are #defines in src/spock_progress_recovery.c (SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN, SPOCK_TS_RECOVERY_SCAN_LIMIT, SPOCK_TS_RECOVERY_BATCH_SIZE). Convert to GUCs only if profiling motivates tuning.
A LOG line is emitted on completion in either path: “ts recovery: file in sync with origin, skipping scan” (skip) or “ts recovery: scanned N xids, found K commits, recovered remote_commit_ts” (run). LOG rather than INFO because INFO is client-only and does not reach the server log for a bgworker.
track_commit_timestamp = on is required. Spock already enforces this via the spock.conflict_resolution GUC’s check_hook (the only allowed value last_update_wins requires it), which fires at postmaster start. The recovery scan therefore does not need its own guard — by the time it runs, the GUC is guaranteed on.
Phase 4 — forced keepalive.
Immediately after spock_start_replication() returns, before entering the receive loop, the apply worker calls a new helper:
This sends an ‘r’ status-update message with replyRequested=true but leaves send_feedback()’s static bookkeeping untouched. The walsender’s ProcessStandbyReplyMessage sees the flag and calls WalSndKeepalive(false, InvalidXLogRecPtr), which emits a ‘k’ with the publisher’s current sentPtr. The subscriber’s existing keepalive handler routes it through UpdateWorkerStats, populating remote_insert_lsn and received_lsn in shmem.
Runtime flow
Commit path (handle_commit in src/spock_apply.c:992-1023).
Delete the spock_apply_progress_add_to_wal(&sap) call. The surrounding SpockApplyProgress construction remains; spock_group_progress_update_ptr() continues to update shmem. Net: one fewer XLogFlush per applied remote-origin commit.
Keepalive path.
Unchanged. UpdateWorkerStats() updates remote_insert_lsn / received_lsn in shmem for every incoming message.
spock_group_progress_force_set_list() (add_node path).
Used during add_node to populate the new node’s view of mesh-peer progress from read_peer_progress() output. These entries are deduplication state for forwarded transactions in a mesh (not just monitoring), so they must be crash-durable before the first clean shutdown.
Transformation:
- Remove the per-entry
spock_apply_progress_add_to_wal(sap)call. - Per entry: acquire master lock → mutate shmem → release lock (no I/O under the lock).
- After the loop: call
spock_group_resource_dump()once to persist all entries atomically viadurable_rename.
Rationale: resource.dat is a full-snapshot dump, not an incremental format, so N per-entry dumps would rewrite the entire file N times. A single post-loop dump gives equivalent durability (add_node is all-or-nothing at the admin level) with O(1) file writes.
spock_group_progress_update_list() (table-sync path).
Same transformation as force_set_list: drop the per-entry WAL call, add a single spock_group_resource_dump() after the loop.
Shutdown flow
The clean-shutdown dump runs from the supervisor’s before_shmem_exit callback (spock_supervisor_on_exit in src/spock.c), not from postmaster context. The supervisor first poll-waits for sibling apply/sync workers to clear their PGPROC slots (~5 s ceiling), then calls spock_group_resource_dump() followed by spock_rmgr_log_resource_dump(SPOCK_DUMP_SHUTDOWN, NULL). Running in the supervisor process is required for the WAL emit (postmaster has no backend slot for XLogInsert); the drain wait ensures the file dump and the SHUTDOWN forensic records both reflect each worker’s last update to SpockGroupHash. This is the sole remaining runtime producer of resource.dat on clean exit.
Code changes
Delete
spock_checkpoint_hook()function insrc/spock_group.c(no longer registered or referenced).extern void spock_checkpoint_hook(...)declaration ininclude/spock_group.h.- The apply-progress recovery contents of
src/spock_rmgr.c(the redo handler that replayedSPOCK_RMGR_APPLY_PROGRESSrecords into shmem). The file itself is retained — see “Trim, do not delete” below. - The
spock_apply_progress_add_to_wal()emit helper.
Remove one-liners
src/spock.c—Checkpoint_hook = spock_checkpoint_hook;.src/spock_apply.c:handle_commit—spock_apply_progress_add_to_wal(&sap);.src/spock_group.c:spock_group_progress_update_list—spock_apply_progress_add_to_wal(sap);.src/spock_group.c:spock_group_progress_force_set_list—spock_apply_progress_add_to_wal(sap);.#include "spock_rmgr.h"ininclude/spock_group.h(was a circular include with no consumer).
Trim, do not delete
src/spock_rmgr.c— replace the apply-progress recovery contents with a single record typeSPOCK_RMGR_RESOURCE_DUMP. New emit helperspock_rmgr_log_resource_dump(event, changed_entries)is called at each of the threeresource.datdump call sites. Each call emits one WAL record per progress entry, carrying the fullSpockApplyProgresssnapshot for that entry so apg_waldumptrace shows exactly what state was on disk at each event LSN — useful for incident reconstruction over time. A singleXLogFlushat the end of each emit batch covers all records.- For
SHUTDOWNandADD_NODE: caller passesNULLforchanged_entries; the helper walksSpockGroupHashand emits a record per entry. Both events reflect changes across all subscriptions. - For
TABLE_SYNC: caller passes the same list ofSpockApplyProgress *it just used to update shmem. Only the affected subscription’s entries are emitted, since table-sync is per-subscription. - Redo handler emits a
LOGline per record showing event type, sequence in batch, key, LSNs, andcommit_ts. Records are not used for state recovery.
- For
include/spock_rmgr.h— replace declarations to match the trimmed contents (SPOCK_RMGR_ID = 144,SPOCK_RMGR_RESOURCE_DUMP = 0x10,SpockResourceDumpReccarryingevent_type+entry_seq/entry_total+ the embeddedSpockApplyProgress,SpockResourceDumpEvent, the emit helper).src/spock.c—spock_rmgr_init()call retained in_PG_init. Header include retained.
Modify
src/spock_progress_recovery.candinclude/spock_progress_recovery.h(new module) — single public entry pointspock_init_progress_state(XLogRecPtr origin_lsn). File-static internals: theReconcileResultenum,reconcile_progress_with_origin(),recover_progress_timestamps_from_commit_ts(), and theSPOCK_TS_RECOVERY_*#defines.src/spock_apply.c— add a new helperrequest_initial_status_update(PGconn *conn, XLogRecPtr startpos)that emits an ‘r’ message withreplyRequested=truewithout touchingsend_feedback’s static state.src/spock_apply.c:spock_apply_main— betweenreplorigin_session_setupandspock_start_replication, callspock_init_progress_state(origin_lsn)once; this internally runs reconcile and (if reconcile detected staleness) thepg_commit_tsscan. Afterspock_start_replicationreturns, callrequest_initial_status_update.src/spock_group.c:spock_group_progress_force_set_list— drop the WAL call; add a singlespock_group_resource_dump()followed byspock_rmgr_log_resource_dump(SPOCK_DUMP_ADD_NODE, ...)after the loop.src/spock_group.c:spock_group_progress_update_list— same withSPOCK_DUMP_TABLE_SYNC.src/spock.c:spock_supervisor_main— registerspock_supervisor_on_exitviabefore_shmem_exit. The callback poll-waits for apply/sync workers to detach via a new helperspock_any_apply_worker_running()(insrc/spock_worker.c), then callsspock_group_resource_dump()followed byspock_rmgr_log_resource_dump(SPOCK_DUMP_SHUTDOWN, NULL). The previous postmaster-contextspock_on_shmem_exitinsrc/spock_shmem.cis removed entirely; both file and WAL dumps now have a single owner that runs in the supervisor process whereXLogInsertis permitted.
Keep unchanged
- Clean-shutdown gating semantics (only dumps if
code == 0) — preserved inspock_supervisor_on_exit. spock_group_resource_load(),spock_group_resource_dump()— load/dump file-format code.SpockApplyProgressandSpockGroupEntrystruct layouts.spock.progressSQL view andget_apply_group_progress()function.
Postgres core patch removal
The patch can be reverted entirely after the Spock-side removal. Four lines across two files:
postgresql/src/backend/access/transam/xlog.c:173—Checkpoint_hook_type Checkpoint_hook = NULL;.postgresql/src/backend/access/transam/xlog.c:7648-7649— 2-lineif (Checkpoint_hook) Checkpoint_hook(...)invocation insideCreateCheckPoint.postgresql/src/include/access/xlog.h:218-219— typedef +extern PGDLLIMPORTdeclaration.
No other Spock or Postgres-patch code depends on Checkpoint_hook.
Edge cases
Forced keepalive: publisher never responds. Not blocking. The apply worker proceeds into its normal receive loop; remote_insert_lsn / received_lsn stay at seeded values (or NULL) until a ‘k’ or ‘w’ arrives via Postgres’s own wal_sender_timeout / 2 cadence. Worst case matches current behavior.
Startup: origin exists but resource.dat is missing. Phase 2 initializes a fresh shmem entry with remote_commit_lsn = origin_lsn and NULL timestamps. Equivalent to first-time start.
Startup: resource.dat entry for a subscription that was dropped. Old entry sits in shmem; no apply worker reconciles it. Matches current behavior. Optional follow-up: purge unknown entries after catalog is readable.
Startup: origin LSN is InvalidXLogRecPtr. Subscription exists but nothing has been applied. Reconcile still runs first: if the loaded resource.dat entry has file_lsn > 0 it is treated as ANOMALY (file ahead of origin) — commit_lsn is overwritten to 0, timestamps cleared, insert/received bumped to 0. If file_lsn == 0 the IN_SYNC branch keeps the file as-is. The pg_commit_ts scan is then skipped via the XLogRecPtrIsInvalid(origin_lsn) short-circuit in spock_init_progress_state, since a fresh origin has no progress to recover and pg_commit_ts rows from a prior subscription would only backfill stale historical timestamps.
add_node retry. Failed mid-loop leaves shmem partially updated and the file untouched (dump runs only after the loop completes). Second run’s unconditional overwrite (init_progress_fields then progress_update_struct) replaces partial state; dump runs after the loop. Fine.
add_node interrupted after dump. All entries persisted; re-run is idempotent.
Multiple apply workers. Each worker reconciles its own key under the master lock. No cross-worker interference. Forced keepalive is per-connection.
Post-crash with publisher offline. remote_commit_ts is recovered from the subscriber’s pg_commit_ts (which survives the crash) by the Phase 3 scan. Recovery does not depend on the publisher being reachable. The only situation that yields NULL is one where pg_commit_ts itself has no entries for this origin within the last 1M xids — typically a fresh subscription that has not yet applied any commits.
Recovery scan finds nothing. If the subscriber has no pg_commit_ts entries with roident == target_origin in the last 1M xids, running_max_ts stays 0. We log a WARNING and proceed with NULL remote_commit_ts. This is rare and matches the fresh-subscription case anyway.
Recovery scan picks up unrelated commits. The filter roident == MySubscription->origin->id is the publisher’s spock node id, not subscription-unique. Sibling subscriptions to the same publisher, or a dropped/recreated subscription with old commits still in the 1M-xid window, can contribute to running_max_ts. Under monotonic publisher clocks the max-by-ts naturally prefers the most recent commit (current sub), so the failure mode is narrow: clock skew between drop and recreate, or scenarios where stale commits are newer than current ones. Impact is forensic-only — prev_remote_ts is not consumed today (apply-group ordering is disabled). The planned parallel-apply rework is the natural place to revisit.
Concurrency width vs. termination bound. The scan stops after observing 1000 commits per origin, which is correct only if max in-flight concurrent xacts on the publisher is bounded below 1000. PostgreSQL’s max_connections defaults to 100, and pooled deployments cap effective concurrency well below that. If a deployment ever exceeds it, the constant is a single #define to bump.
Publisher clock skew (NTP step-back). running_max_ts is the max-by-ts. If the publisher’s clock steps backward such that commit_ts order disagrees with commit order, the recovered prev_remote_ts may not match the next transaction’s required_commit_ts from the publisher. Theoretical only — the apply-group ordering machinery that consumes prev_remote_ts is currently disabled. The planned parallel-apply rework will revisit. Out of scope for this design.
Shmem hash full during force_set_list. Warn and continue (existing behavior unchanged). Post-loop dump persists whichever entries made it in.
Concurrent shutdown during reconciliation. Worker completes its update under the lock, releases, exits on next CHECK_FOR_INTERRUPTS. Shutdown hook dumps resource.dat with the reconciled values. Reconciliation-then-dump cannot leave shmem more stale than the file.
Testing
Modified existing tests
tests/tap/t/008_rmgr.pl— rewrote Phase 4 assertions for the new reconcile semantics. Covers the multi-origin case (Scenario A: file has stale entry, Scenario B: file has no entry for an origin). The test issues aCHECKPOINTbefore SIGKILL so the apply worker’s WAL is durable past batch-2; without this, walwriter-cadence races could leave recovery’s origin LSN at batch-1 and reconcile would take the IN_SYNC path instead of STALE.tests/tap/t/022_rmgr_progress_post_checkpoint_crash.pl— rewrote to assert that reconcile detectsfile_lsn < origin_lsnafter a crash, advancesremote_commit_lsnfrom the replication origin, and (with the recovery scan) thatremote_commit_tsis recovered non-NULL post-crash. Also asserts CHECKPOINT does NOT updateresource.dat(regression guard against re-introducing the checkpoint hook).
New tests
023_forced_keepalive_timing.pl— setwal_sender_timeout=10minso the timer-driven path is disabled; assertremote_insert_lsnpopulates within 1 second (proves the forced keepalive, not the timer, drove the refresh).026_no_double_wal_flush.pl— countpg_stat_wal.wal_syncdelta over 30 applied commits; assert delta < N (no per-commit forced fsync on the apply hot path).027_remote_commit_ts_recovery.pl— apply commits, clean restart, more commits, CHECKPOINT, SIGKILL, restart; assertremote_commit_tsis non-NULL post-crash (recovered via thepg_commit_tsscan).029_remote_commit_ts_recovery_clean_shutdown.pl— clean restart only; assert the skip-pathLOGline (“file in sync with origin, skipping scan”) fires and the run-path log does not, andremote_commit_tsis preserved.
Deferred / not implemented
track_commit_timestamp = offtest. Cannot occur in practice because spock’s existingspock.conflict_resolutionGUC validation aborts the postmaster at startup if the GUC is off. The recovery scan is unreachable in that scenario.- Idle-cluster test (no commits in last 1M xids). Would require either >1M unrelated xids of activity or a temporary constant override. Both too heavy for v1.
add_nodeinterrupted mid-loop test. Out of scope for this design; covered by existingadd_nodeintegration tests.
Regression safety checks
spock.progresscolumn set unchanged.read_peer_progress()SQL function output unchanged.- Downstream tools reading
spock.progress(spockctrl, monitoring scripts) see no schema or column-type changes.
Follow-ups (out of scope)
- Convert
SPOCK_TS_RECOVERY_*#defines to GUCs if any deployment ever needs to tune them. - Generalize the forensic RMGR record into a small audit-event family covering more rare events (
add_node/drop_nodelifecycle, subscription state transitions, sync start/end). Sketched separately in2026-05-01-spock-audit-rmgr-design.md. - Revisit the parallel-apply ordering coordinate. The current
commit_ts-based approach is exposed to publisher clock skew; alternatives will be considered alongside the parallel-apply rework. - Multi-origin shared scan: a single backward pass that populates all origins’ shmem entries at once, gated by a per-origin “recovery done” flag in
SpockGroupEntry. Worth doing only if profiling shows per-worker scan cost matters. - Purging
resource.datentries that reference subscriptions that no longer exist. - Removing the obsolete
updated_by_decodefield from theSpockApplyProgressstruct layout. (prev_remote_tsis still actively used as the wait/signal coordinate for the parallel-apply machinery — keep until that rework lands.)
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.16.1.2 - Spock Node Monitoring: Design of the spock_monitor subsystem
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Date: 2026-09-23
Status: Implemented, regression tested
Component: src/spock_monitor.c, include/spock_monitor.h
PostgreSQL: 15 to 19
A Word version of this document is kept next to it as
spock-monitor-design.docx.
1. Summary
Operators of a Spock cluster have had to read the PostgreSQL server log to answer routine questions: is every subscription replicating, did a worker restart overnight, why was a subscription disabled, how much WAL is a slot holding back, did the extension get upgraded. The catalog and the existing statistics views describe configuration and cumulative counters but not state changes or failures.
The monitoring subsystem records state changes as events and keeps
per-subscription activity counters in shared memory, and exposes them
together with worker, slot and replication progress through eleven views in
the spock schema. A query against spock.node_status or
spock.subscription_status gives the complete picture of a node;
spock.events gives the recent history. The module is also the single home
of all monitoring C code, absorbing the channel counters, the apply group
progress function and the slot confirmation wait.
2. Goals and non-goals
Goals
- Replace log reading for day to day operation: every notable state change is queryable.
- One row per node, per subscription, per worker and per slot, with column names that need no legend.
- Cheap on the apply hot path: a spinlock and a few integer adds per message, no catalog writes, no WAL.
- Safe in error paths: recording an error must never allocate memory, block or raise.
- Same source on every supported PostgreSQL version; version specific data such as the PG18 conflict counters degrade to NULL.
- One module for all monitoring code, with PostgreSQL naming and layout conventions.
Non-goals
- Durability across a postmaster restart. Events and counters live in shared memory only; the catalog and pgstat remain the durable stores.
- Transactional semantics. An event is recorded when the reporting code runs, whether or not its transaction commits.
- Cluster wide aggregation. Each node reports about itself; a fleet view is left to external tooling that reads the views on every node.
3. Architecture
The subsystem has three layers: shared memory structures written by spock
processes, C functions that read them and return rows, and SQL views that
join those rows with the catalogs and with core views such as
pg_stat_replication and pg_stat_activity.
| Layer | Elements | Owner |
|---|---|---|
| Shared memory | Event ring (SpockMonitorShmem), per-subscription counters (SpockMonitorStatsHash) | spock_monitor.c, allocated by spock_shmem.c |
| Producers | Worker attach and detach, apply loop, sync worker, output plugin, node and subscription management functions, exception handler, extension manager, emit_log_hook | One call at each site |
| SQL functions | get_worker_status, get_events, get_apply_stats, get_slot_groups, get_monitor_summary, reset_events, reset_subscription_stats, get_channel_stats, reset_channel_stats, apply_group_progress, wait_slot_confirm_lsn | spock_monitor.c |
| Views | system_status, node_status, subscription_status, subscription_stats, worker_status, slot_status, peer_status, replication_set_status, settings, table_sync_status, events | sql/spock--6.0.0.sql and the 5.x upgrade script |
Producers never format SQL or touch the catalog. They call one of a handful
of functions declared in spock_monitor.h, which copy fixed size data into
shared memory under a lock. Readers take a consistent copy of each entry
and build tuples outside any spinlock.
4. Shared memory
4.1 Event ring
Events are stored in a fixed size ring inside one ShmemInitStruct
allocation named spock monitor. The capacity is the
spock.event_history_size GUC (default 1024, PGC_POSTMASTER).
The header holds the LWLock, the time shared memory was initialized
(reported as spock_started_at), the next event id, and head and count
indexes. Appending when full advances the head, so the oldest event is
dropped. Event ids keep increasing across resets, which lets a poller detect
both new events and gaps. The ring is cluster wide; the views filter on the
current database and keep events without a database, such as those of the
supervisor.
Each event type has a fixed name and severity in a table indexed by the
enum, so adding a type means adding one enum member and one table row.
Severities are info, warning and error; warning covers state changes
an operator would want to know about even when they were requested, such as
a subscription being disabled, repair mode being switched on or a
transaction being skipped.
4.2 Per-subscription counters
Counters live in a fixed size shared hash keyed by (dboid, subid), sized
at max(64, 4 * max_worker_processes) entries. The multiple leaves room for
disabled subscriptions whose history should survive while they are down.
Every counter carries the time of its last increment. That one rule gives
the view its last_worker_start, last_provider_connect,
last_xact_applied and last_apply_error columns without separate fields,
and keeps the reader generic: two small tables in spock_get_apply_stats()
map counters to count columns and to timestamp columns, checked at compile
time against the column enum.
| Counter | Incremented when |
|---|---|
worker_starts | An apply worker attaches to its shared memory slot. |
worker_failures | An apply worker detaches after an error exit. |
sync_worker_starts, sync_worker_failures | The same for sync workers, so a resync is told apart from an apply worker restart. |
provider_connects | START_REPLICATION succeeded in the apply worker. |
provider_disconnects | apply_work() classified an error as connection loss. A sync worker’s failed connection is recorded as an event and as the last error but not counted here, so the two counters pair. |
idle_timeouts | spock.apply_idle_timeout forced a reconnect. |
messages_received, bytes_received | A data message was read from the stream. |
xacts_applied | A remote transaction committed locally. |
xacts_skipped | A transaction was skipped through sub_skip_lsn. |
xacts_discarded | A transaction was discarded under transdiscard. |
apply_errors, sync_errors | An ERROR was raised in an apply or sync worker (section 6). |
deadlocks, lock_timeouts, constraint_violations, resource_errors | The same errors classified by SQLSTATE. |
tables_synced | A sync worker finished a table without failure. |
A worker caches a pointer to its entry in MySpockMonitorStats when it
attaches. Entries in a HASH_FIXED_SIZE shared hash are never moved, so the
pointer stays valid for the life of the process. Counting is then a
spinlock, an add and a timestamp. Backends that only record events do not
touch the hash.
Subscription ids come from a cycling sequence, so an id can be reused. Each entry counts the workers attached to it. Dropping a subscription removes the entry at once when no worker is attached; otherwise the entry is only marked dropped and the last worker to detach removes it, so a worker never writes through a pointer into a freed element. A worker that attaches to an entry marked dropped, because the id was reused, resets it.
4.3 Locking
- One LWLock in the tranche
spock_monitorprotects the ring and the hash structure. Individual entries have a spinlock for their counters. - The monitor lock is a leaf: no other lock is taken while holding it. It
may be acquired while
SpockCtx->lockis held, never the other way round. - The error reporting path uses
LWLockConditionalAcquireand skips the event if the lock is busy, so error reporting can never block. - Readers hold the monitor lock only while copying the ring or the entries into local memory, so that error reporting, which only tries the lock, is not held off while a result is formatted.
5. Instrumentation points
Each producer adds one call at the place where the state change is already logged, so the event and the log line always agree.
| Event type | Call site |
|---|---|
node_created, node_dropped | spock_create_node(), spock_drop_node() after the catalog change |
subscription_created, subscription_dropped | spock_create_subscription(), spock_drop_subscription() |
subscription_enabled, subscription_disabled | spock_alter_subscription_enable(), spock_alter_subscription_disable(), spock_disable_subscription() in the exception handler |
subscription_altered | Interface change, replication set add and remove, skip_lsn, options, synchronize and resynchronize table |
worker_started, worker_stopped, worker_failed | spock_worker_attach() and spock_worker_detach(); the failure detail carries the last recorded error message |
worker_error | emit_log_hook, for any ERROR or FATAL in a spock worker |
provider_connected, provider_disconnected | spock_start_replication(); the connection loss branch of apply_work() |
transaction_skipped, transaction_discarded | stop_skipping_changes(); the transdiscard branch of handle_commit() |
sync_started, sync_finished, sync_failed | spock_sync_main() and spock_sync_worker_finish() |
slot_created, stream_started, stream_stopped | pg_decode_startup() with and without is_init; pg_decode_shutdown() |
apply_paused, apply_resumed | spock_pause_apply_workers(), spock_resume_apply_workers() |
repair_mode_enabled, repair_mode_disabled | spock_repair_mode() |
extension_upgraded | spock_manage_extension() after ALTER EXTENSION UPDATE |
Worker start and stop are recorded in the generic attach and detach code,
so the manager, every apply worker and every sync worker are covered by two
call sites. The detach hook runs before SpockCtx->lock is taken, which
keeps the lock order simple.
6. Error capture
Rather than instrumenting each error site, the module hooks the existing
emit_log_hook installed by spock.c. spock_monitor_report_error() is
called for every report and applies these rules:
- Ignore unless the process is a spock worker (
MySpockWorkeris set) or a walsender running the spock output plugin, and shared memory is attached. - Ignore levels below ERROR and at or above PANIC; a PANIC path must not take locks.
- Treat connection class errors (connection failure, admin shutdown,
cannot connect now and the related codes) as a lost peer, never as an
apply error. In a worker the hook records them as
provider_disconnectedwith the message kept as the last error, which covers failures at connect or START_REPLICATION time that no handler catches.apply_work()uses the same predicate for its connection-loss branch and reports through the same function before rethrowing; it flags the rethrow so the hook does not count it again. In a walsender such an error is the subscriber going away and nothing is recorded. - In a walsender, record a
stream_errorevent with the slot name, the SQLSTATE and the message. The output plugin marks the process at startup and clears the mark at shutdown. Only a walsender is marked: a regular backend decoding a slot through the SQL functions gets no shutdown call when decoding fails, and its later errors must not be reported as stream errors. - For apply and sync workers, bump
apply_errorsorsync_errorsand the matching class counter (deadlock, lock timeout, constraint violation, resource error), and store the message, SQLSTATE, pid and the current origin LSN as the last error. - Record a
worker_errorevent with the message and SQLSTATE, using a conditional lock acquire.
The message stored is the error message followed by the DETAIL and CONTEXT
lines, so a constraint violation carries the failing row and the apply
context. The function is guarded against re-entry and does no allocation:
the text is formatted with snprintf into fixed buffers.
An ERROR caught by a PG_CATCH is never emitted: PostgreSQL longjmps
before EmitErrorReport(), and the apply worker’s handler copies and
flushes the error. The hook therefore only sees errors that end the worker.
The two paths of apply_work() that swallow an error, the first exception
that enters replay and the sub_disable path, call
spock_monitor_report_error() on the copied ErrorData themselves; the
paths that rethrow leave it to the hook so that an error is counted once.
Under sub_disable the replay ends with a synthetic error requesting the
disable; the worker remembers that the transaction’s first error was
already reported and does not report that one. Row level errors during a
discard replay are not counted again, so apply_errors counts failed
transactions rather than failed rows.
7. SQL surface
7.1 Functions
Functions return raw shared memory rows and are the tooling interface. Set
returning functions use InitMaterializedSRF and OUT parameters; the C
code checks the column count against its enum with an assertion.
| Function | Returns |
|---|---|
spock.get_worker_status() | Every worker slot in the cluster plus the supervisor, with database_id |
spock.get_events() | Every event in the ring, oldest first, with database_id |
spock.get_apply_stats() | Counters of every subscription of the current database, with PG18 conflict counters |
spock.get_slot_groups() | Slot groups with attached walsenders |
spock.get_monitor_summary() | One row: start time, supervisor pid, slot and capacity usage |
spock.get_system_info() | One row: host name, operating system, CPU, memory, load averages, statvfs() of the data directory and of pg_wal, postmaster start, PostgreSQL and spock versions |
spock.get_pending_exceptions() | Exception log slots with a recorded error: the transactions being retried, with failed_action_number, the position of the failing change in its transaction |
spock.report_section(title, query, expanded) | The rows of a query as text, values in PostgreSQL text form |
spock.node_report(recent) | The whole node as a text report, one section per view |
spock.reset_events() | Empties the ring; ids keep increasing |
spock.reset_subscription_stats(subid) | Resets activity and, on PG18, conflict counters of one or all subscriptions |
spock.redact_dsn(text) | Connection string with the password hidden, keyword and URI forms |
7.2 Views
Views are named by what they show: *_status for state, *_stats for
counters. Columns use full words, never abbreviations, and the same word for
the same thing everywhere (subscription_name, provider_node,
worker_pid, replication_lag_bytes).
| View | Rows | Built from |
|---|---|---|
spock.system_status | Exactly one | get_system_info(), pg_stat_activity, pg_prepared_xacts, pg_stat_replication, pg_database, pg_stat_database, pg_stat_archiver, spock.wal_size_bytes() |
spock.node_status | Exactly one | get_monitor_summary(), local_node, pg_extension, aggregates over the other views, spock.wal_size_bytes() |
spock.subscription_status | One per subscription | subscription, node, node_interface, local_sync_status, get_worker_status() (lateral, running worker preferred), pg_stat_activity, progress, replication_origin_status(), subscription_stats |
spock.subscription_stats | One per subscription | get_apply_stats() and channel_summary_stats, counters coalesced to zero |
spock.worker_status | One per worker | get_worker_status(), pg_stat_activity, pg_blocking_pids() for the session holding a lock the worker waits for |
spock.slot_status | One per spock slot | pg_replication_slots, pg_stat_replication, get_slot_groups(), current or replay WAL position |
spock.table_sync_status | One per sync row | local_sync_status with readable kind and status |
spock.peer_status | One per node and subscription | node, node_interface, subscription_status |
spock.replication_set_status | One per replication set | replication_set with counts over its tables, sequences and subscriptions |
spock.settings | One per parameter | pg_settings, spock parameters and the core replication parameters, DSNs redacted |
spock.events | One per event | get_events(), subscription and node for the provider name |
The status text of a subscription is computed in SQL with the same rule as
spock.sub_show_status(): replicating, initializing or unknown while
a worker runs, otherwise disabled or down. Computing it in the view
keeps node_status usable before a local node exists, where the function
would raise an error.
The slot view uses only columns present in pg_replication_slots since
PostgreSQL 15, because one SQL script serves every version. It falls back
to pg_last_wal_replay_lsn() on a standby so it never raises during
recovery.
7.3 The report
spock.node_report() is a plpgsql function that calls
spock.report_section() once per view. The formatter runs the query twice:
once through row_to_json to learn the column names in query order, then
with every column cast to text so that values appear as PostgreSQL prints
them rather than as JSON. Each section’s query runs inside its own
exception block, so a failing view produces one error line instead of
aborting the report. Passwords never appear: the views already redact
connection strings, and spock.settings redacts the DSN parameters.
The exception handler keeps one shared slot per subscription with the
commit LSN of the transaction in flight and the first error raised for it.
spock.get_pending_exceptions() reports only slots with an error, because
the LSN alone is set for every transaction.
8. Compatibility and upgrade
- The same SQL section is appended to
spock--6.0.0.sqland tospock--5.0.14--6.0.0.sql. Every catalog column the views reference exists since 5.0.6, so an upgraded node ends with the same objects as a fresh install. spock.get_apply_worker_status()is kept for existing callers, as a SQL function overspock.get_worker_status()returning the 5.x columns and rows. Its C symbol stays as a stub that raises an error, because pg_upgrade from 5.x recreates the old C binding before the extension update replaces it.spock_monitoring.cis removed.spock.wait_slot_confirm_lsn(),spock.get_channel_stats(),spock.reset_channel_stats()andspock.apply_group_progress()keep their SQL definitions and C symbols and now live inspock_monitor.c.spock.reset_subscription_stats()keeps its SQL definition and C symbol, so the existing upgrade script needs no change, but it now resets both counter sets and no longer raises before PostgreSQL 18.- Conflict counters are fetched through the pgstat entry under
PG_VERSION_NUM >= 180000and are NULL otherwise. - Shared memory grows by the ring plus the hash.
SpockMonitorStatsEntryis 800 bytes, dominated by its 512-bytelast_error_messageand the two per-counter arrays, so the hash costs roughly that plus dynahash overhead for each subscription tracked, bounded bymax(64, 4 * max_worker_processes)entries.SpockMonitorEventis 560 bytes, dominated by its 512-bytedetail, so the ring costsspock.event_history_size * 560bytes: 560 kB at the default 1024, and a megabyte or more if the setting is raised. Size shared memory from that figure rather than from the event count alone.
9. Testing
The regression test tests/regress/sql/monitor.sql runs after basic and
checks, on the provider, node_status, worker_status, slot_status and
the provider side events, and on the subscriber, subscription_status,
worker_status, table_sync_status, subscription_stats after real
traffic, the events of subscription creation and worker start, both reset
functions, and that disabling and enabling a subscription produces the
expected events and a worker restart that is visible in the counters.
Values that vary between runs are compared, not printed. The full suite of
41 tests passes on PostgreSQL 18.
10. Limitations and future work
- The views and the functions they call (
get_system_info(),get_events(),get_apply_stats(),get_pending_exceptions(),replication_origin_status(), which stands in for the superuser-onlypg_replication_origin_status) are granted topg_monitor; a superuser or a member of that role reads them.wal_size_bytes()stays callable by any role, as the total WAL size is not sensitive. The reset functions are superuser only. - The subscription stats hash is bounded at
max(64, 4 * max_worker_processes)entries. Past that,spock_monitor_attach_stats()returns NULL and logs it; the worker carries on and the subscription operates normally, but its counters are not recorded:spock.subscription_statsstill has its row, with every counter read as 0 and every timestamp as NULL, so a subscription past the bound looks idle rather than unrecorded.spock.node_status.channel_stats_fullreports the same condition for the channel counter hash. - The ring is cluster wide, so a database with heavy activity can age out the events of a quiet one. A per-database ring would remove this at the cost of more shared memory.
- Events and counters are lost at postmaster restart. If history across restarts is wanted, a background worker could periodically append events to a spock catalog table.
pg_replication_slotscolumns added in PostgreSQL 17 (failover,invalidation_reason,inactive_since) are not shown; a version conditional view would be needed.- Replication set changes on the provider (table added or removed) are not events; they are visible in the catalog and could be added with two call sites.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.16.2 - Historical plans
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Browse the upstream reference pages in this section.
2.16.2.1 - remote_commit_ts Recovery via pg_commit_ts Scan — Implementation Plan
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: After crash recovery, scan pg_commit_ts backward to recover the most-recent remote_commit_ts per origin so spock.progress shows accurate values post-crash; the recovered prev_remote_ts is also intended to be useful for the planned parallel-apply rework.
Architecture: New file-static function recover_progress_timestamps_from_commit_ts() in src/spock_apply.c, called from spock_apply_main after reconcile_progress_with_origin and before spock_start_replication, gated on a new ReconcileResult enum so the scan only runs when the loaded resource.dat is stale or missing. Termination after observing 1000 commits per origin or scanning 1M xids total. Hard error if track_commit_timestamp is off.
Tech Stack: C (Postgres extension), Postgres SLRU API (TransactionIdGetCommitTsData), Perl TAP tests (existing SpockTest module).
Pre-flight:
File Structure
| File | Role | Change |
|---|---|---|
src/spock_apply.c | Apply worker main, reconcile, new recovery function | Modify |
tests/tap/t/027_remote_commit_ts_recovery.pl | Happy path | Create |
tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl | Skip-path verification | Create |
tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl | Error-path verification | Create |
No header changes — ReconcileResult is file-static.
Task 1: Refactor reconcile_progress_with_origin to return ReconcileResult
Why first: The recovery function needs to know which reconcile branch was taken so it can skip when the file is in sync. Threading the enum through is purely structural with no behavioral change, so it’s safe to land first.
Files:
Modify:
src/spock_apply.c— add enum near other forward declarations (~line 245-260), change function signature atsrc/spock_apply.c:2937-2938, update caller atsrc/spock_apply.c:4216.Step 1.1: Add the enum near the existing forward declarations
Locate the forward declarations block at src/spock_apply.c:248-257:
Replace the last line with the enum and updated declaration:
- Step 1.2: Update the function definition to return the enum
At src/spock_apply.c:2937, change:
to:
In the body (current src/spock_apply.c:2944-3043), each branch must return the appropriate enum value.
- The early-return at the top (
!SpockGroupHash || !SpockCtx) — change toreturn RECONCILE_FILE_ABSENT;. The hash isn’t set up; treat as absent. - The
entry == NULLcase (hash full) — changereturn;toreturn RECONCILE_FILE_ABSENT;and continue with the existing WARNING. - The
if (!found)branch — after the existing log line,result = RECONCILE_FILE_ABSENT;. - The
else if (entry->progress.remote_commit_lsn == origin_lsn)branch —result = RECONCILE_FILE_IN_SYNC;. - The
else if (entry->progress.remote_commit_lsn < origin_lsn)branch —result = RECONCILE_FILE_STALE;. - The final
else(anomaly) branch —result = RECONCILE_FILE_ANOMALY;.
Concretely, declare ReconcileResult result; near the top of the function, set it in each branch, and return it after LWLockRelease.
- Step 1.3: Update the caller to receive the result
At src/spock_apply.c:4216, change:
to:
The variable is unused for now; Task 4 wires it up. Suppress the unused-variable warning by adding (void) reconcile_result; directly below the call, with a comment /* used in Task 4 */.
- Step 1.4: Build and verify no behavioral regression
Expected: clean build, no new warnings.
Expected: all subtests pass (this test exercises the reconcile path most heavily).
- Step 1.5: Commit
Task 2: Add the recovery constants
Files:
Modify:
src/spock_apply.c— add#defines near the top of the file, after the existing macros / includes.Step 2.1: Add the three
#defines
Find an appropriate spot near the top of src/spock_apply.c (after the includes, near other apply-side #defines if present, or otherwise just before the forward declarations). Add:
- Step 2.2: Build to verify
Expected: clean build (no use sites yet, but the macros exist).
- Step 2.3: Commit
Task 3: Write the failing happy-path test (027)
Why before implementation: Establishes the regression target — running this test against main (or after Task 2) must fail; running it after Task 4 must pass.
Files:
Create:
tests/tap/t/027_remote_commit_ts_recovery.plStep 3.1: Create the test file
Write tests/tap/t/027_remote_commit_ts_recovery.pl with the following content:
Make it executable:
- Step 3.2: Run the test — confirm it fails as expected
Expected: the test FAILS at the “post-crash remote_commit_ts is NOT NULL” assertion. Without the recovery scan, the field remains NULL after crash (current behavior).
- Step 3.3: Commit
Task 4: Implement the scan and wire the call site
Files:
Modify:
src/spock_apply.c— addrecover_progress_timestamps_from_commit_tsfunction and call it fromspock_apply_main. Add INFO logs.Step 4.1: Add the forward declaration
Near the existing forward declarations (src/spock_apply.c:248-260, the same block where Task 1 added ReconcileResult), add:
- Step 4.2: Add the include for
commit_ts.h
Near the top of src/spock_apply.c (in the #include block), add:
- Step 4.3: Implement the scan function
Add the function after reconcile_progress_with_origin (i.e., after the existing block ending at src/spock_apply.c:3043):
- Step 4.4: Wire the call site in
spock_apply_main
At src/spock_apply.c:4216 (where Task 1 introduced reconcile_result), replace:
with:
Note on target_origin: replorigin_session_origin is the standard Postgres global, set by replorigin_session_setup(originid) at src/spock_apply.c:4212, two lines before the reconcile call. It is the correct RepOriginId to filter by.
- Step 4.5: Build and run test 027
Expected: all subtests pass. The “post-crash remote_commit_ts is NOT NULL” assertion now succeeds.
- Step 4.6: Run the existing crash-recovery regression to ensure no regression
Expected: both pass. Note that 022’s assertion is($post_commit_ts, '', "remote_commit_ts is NULL post-crash...") is now WRONG — recovery populates it. You must update 022 in this same task.
- Step 4.7: Update test 022 to reflect new behavior
In tests/tap/t/022_rmgr_progress_post_checkpoint_crash.pl at the assertion block (around line 191-197), change:
to:
Also update the file header comment block where it says remote_commit_ts is NULL post-crash to reflect the recovery behavior.
- Step 4.8: Re-run 022 to confirm the update
Expected: all subtests pass.
- Step 4.9: Commit
Task 5: Write the failing track_commit_timestamp off test (030)
Files:
Create:
tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.plStep 5.1: Create the test
Write tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl:
Note: the log path may need adjusting based on how SpockTest configures log_directory / log_filename. Inspect tests/tap/SpockTest.pm if $sub_dir/log/postgresql-1.log doesn’t match. The pattern matching for the error message is tolerant (case-insensitive, just looks for “track_commit_timestamp” near “on”).
- Step 5.2: Run the test — confirm it fails as expected
Expected: the test FAILS at the “logged ERROR about track_commit_timestamp” check, because Task 4 has no guard. Without the guard, the recovery scan calls TransactionIdGetCommitTsData which returns false for every xid (no commit_ts data) and the scan logs “no commits found” instead of erroring.
- Step 5.3: Commit
Task 6: Add the track_commit_timestamp guard
Files:
Modify:
src/spock_apply.c— add the guard at the top ofrecover_progress_timestamps_from_commit_ts.Step 6.1: Add the guard
At the top of recover_progress_timestamps_from_commit_ts (added in Task 4.3), insert immediately after the variable declarations:
The variable track_commit_timestamps (note plural) is the standard Postgres GUC global, declared in access/commit_ts.h (already included in Task 4.2).
- Step 6.2: Build
Expected: clean build.
- Step 6.3: Run test 030 — should now pass
Expected: all subtests pass.
- Step 6.4: Run test 027 to confirm no regression
Expected: all subtests pass.
- Step 6.5: Commit
Task 7: Add the clean-shutdown skip-path test (029)
Files:
Create:
tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.plStep 7.1: Create the test
Write tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl:
- Step 7.2: Run the test
Expected: all subtests pass. The skip-path INFO log was added in Task 4 and the recovery function is gated on RECONCILE_FILE_IN_SYNC — both already in place by this point.
- Step 7.3: Commit
Task 8: Final regression sweep
- Step 8.1: Run the full TAP suite
Expected: all tests pass, including 008, 022, 023, 026, and the three new tests (027, 029, 030).
- Step 8.2: Verify the commit log
Expected: a clean linear sequence — refactor, constants, test 027 (failing), implement, test 030 (failing), guard, test 029.
- Step 8.3: No commit needed; the work is complete.
If this lands as a PR, the user will decide whether to fold the design doc into the PR (currently uncommitted in the working tree).
Self-Review
- Spec coverage: every section of the spec maps to a task: enum and skip-gating (Task 1, 4), constants (Task 2), scan logic (Task 4),
track_commit_timestampguard (Task 6), INFO logs (Task 4, 7), tests 027/029/030 (Tasks 3, 7, 5). Test 028 (idle/empty cluster) is deferred per the spec’s discussion that triggering “no commits found” in a TAP test requires either a constant override or 1M+ unrelated xids — both are too heavy for v1. - Type consistency:
ReconcileResultenum (Task 1) is used in Task 4’s call site.target_originisRepOriginId.running_max_tsisTimestampTz. Constants areint64-safe via the(int64) total_scannedcast. - Placeholder scan: every step has executable code or commands. The only soft spot is the log-path detection in tests 029 and 030 — handled with a comment instructing the implementer to inspect
SpockTest.pmif the default path doesn’t match.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.16.3 - Design decisions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Explanations of why things are done the way they are.
Why does spock_output exist when there’s wal2json etc?
spock_output does plenty more than convert logical decoding change
messages to a wire format and send them to the client.
It handles format negotiations, sender-side filtering using pluggable hooks (and the associated plugin handling), etc. The protocol itself is also important, and incorporates elements like binary datum transfer that can’t be easily or efficiently achieved with json.
Custom binary protocol
Why do we have a custom binary protocol inside the walsender / copy both protocol, rather than using a json message representation?
Speed and compactness. It’s expensive to create json, with lots of allocations. It’s expensive to decode it too. You can’t represent raw binary in json, and must encode it, which adds considerable overhead for some data types. Using the obvious, easy to decode json representations also makes it difficult to do later enhancements planned for the protocol and decoder, like caching row metadata.
The protocol implementation is fairly well encapsulated, so in future it should be possible to emit json instead for clients that request it. Right now that’s not the priority as tools like wal2json already exist for that.
Column metadata
The output plugin sends metadata for columns - at minimum, the column names - before each row that first refers to that relation.
The reason metadata must be sent is that the upstream and downstream table’s attnos don’t necessarily correspond. The column names might, and their ordering might even be the same, but any column drop or column type change will result in a dropped column on one side. So at the user level the tables look the same, but their attnos don’t match, and if we rely on attno for replication we’ll get the wrong data in the wrong columns. Not pretty.
That could be avoided by requiring that the downstream table be strictly maintained by DDL replication, but:
- We don’t want to require DDL replication
- That won’t work with multiple upstreams feeding into a table
- The initial table creation still won’t be correct if the table has dropped
columns, unless we (ab)use
pg_dump’s--binary-upgradesupport to emit tables with dropped columns, which we don’t want to do.
So despite the bandwidth cost, we need to send metadata.
Support for type metadata is penciled in to the protocol so that clients that don’t have table definitions at all - like queueing engines - can decode the data. That’ll also permit type validation sanity checking on the apply side with logical replication.
The upstream expects the client to cache this metadata and re-use it when data is sent for the relation again. Cache size controls, an LRU and purge notifications will be added later; for now the client must cache everything indefinitely.
Relation metadata cache size controls
The relation metadata cache will have downstream size control added. The downstream will send a parameter indicating that it supports caching, and the maximum cache size desired.
Since there is no downstream-to-upstream communication after the startup params there’s no easy way for the downstream to tell the upstream when it purges cache entries. So the downstream cache is a slave cache that must depend strictly on the upstream cache. The downstream tells the upstream how to manage its cache and then after that it just follows orders.
To keep the caches in sync so the upstream never sends a row without knowing the downstream has metadata for it cached the downstream must always cache relation metadata when it receives it, and may not purge it from its cache until it receives a purge message for that relation from the upstream. If a new metadata message for the same relation arrives it must replace the old entry in the cache.
The downstream does not have to promptly purge or invalidate cache entries when it gets purge messages from the upstream. They are just notifications that the upstream no longer expects the downstream to retain that cache entry and will re-send it if it is required again later.
Not an extension
There’s no extension script for spock_output. That’s by design. We’ve tried really hard to avoid needing one, allowing applications using spock_output to entirely define any SQL level catalogs they need and interact with them using the hooks.
That way applications don’t have to deal with some of their catalog data being in spock_output extension catalogs and some being in their own.
There’s no issue with dump and restore that way either. The app controls it entirely and spock_output doesn’t need any policy or tools for it.
spock_output is meant to be a re-usable component of other solutions. Users shouldn’t need to care about it directly.
Hooks
Quite a bit of functionality that could be done directly in the output plugin is instead delegated to pluggable hooks. Replication origin filtering for example.
That’s because spock_output tries hard not to know anything about the topology of the replication cluster and leaves that to applications using the plugin.
Hook entry point as a SQL function
The hooks entry point is a SQL function that populates a passed internal
struct with hook function pointers.
The reason for this is that hooks are specified by a remote peer over the network. We can’t just let the peer say “dlsym() this arbitrary function name and call it with these arguments” for fairly obvious security reasons. At bare minimum all replication using hooks would have to be superuser-only if we did that.
The SQL entry point is only called once per decoding session and the rest of the calls are plain C function pointers.
The startup reply message
The protocol design choices available to spock are constrained by being
contained in the copy-both protocol within the fe/be protocol, running as a
logical decoding plugin. The plugin has no direct access to the network socket
and can’t send or receive messages whenever it wants, only under the control of
the walsender and logical decoding framework.
The only opportunity for the client to send data directly to the logical
decoding plugin is in the START_REPLICATION parameters, and it can’t send
anything to the client before that point.
This means there’s no opportunity for a multi-way step negotiation between client and server. We have to do all the negotiation we’re going to in a single exchange of messages - the setup parameters and then the replication start message. All the client can do if it doesn’t like the offer the server makes is disconnect and try again with different parameters.
That’s what the startup message is for. It reports the plugin’s capabilities and tells the client which requested options were honoured. This gives the client a chance to decide if it’s happy with the output plugin’s decision or if it wants to reconnect and try again with different options. Iterative negotiation, effectively.
Unrecognised parameters MUST be ignored by client and server
To ensure upward and downward compatibility, the output plugin must ignore parameters set by the client if it doesn’t recognise them, and the client must ignore parameters it doesn’t recognise in the server’s startup reply message.
This ensures that older clients can talk to newer servers and vice versa.
For this to work, the server must never enable new functionality such as protocol message types, row formats, etc without the client explicitly specifying via a startup parameter that it understands the new functionality. Everything must be negotiated.
Similarly, a newer client talking to an older server may ask the server to enable functionality, but it can’t assume the server will actually honour that request. It must check the server’s startup reply message to see if the server confirmed that it enabled the requested functionality. It might choose to disconnect and report an error to the user if the server didn’t do what it asked. This can be important, e.g. when a security-significant hook is specified.
Support for transaction streaming
Presently logical decoding requires that a transaction has committed before it can begin sending it to the client. This means long running xacts can take 2x as long, since we can’t start apply on the replica until the xact is committed on the master.
Additionally, a big xact will cause large delays in apply of smaller transactions because logical decoding reorders transactions into strict commit order and replays them in that sequence. Small transactions that committed after the big transaction cannot be replayed to the replica until the big transaction is transferred over the wire, and we can’t get a head start on that while it’s still running.
Finally, the accumulation of a big transaction in the reorder buffer means that storage on the upstream must be sufficient to hold the entire transaction until it can be streamed to the replica and discarded. That is in addition to the copy in retained WAL, which cannot be purged until replay is confirmed past commit for that xact. The temporary copy serves no data safety purpose; it can be regenerated from retained WAL is just a spool file.
There are big upsides to waiting until commit. Rolled-back transactions and subtransactions are never sent at all. The apply/downstream side is greatly simplified by not needing to do transaction ordering, worry about interdependencies and conflicts during apply. The commit timestamp is known from the beginning of replay, allowing for smarter conflict resolution behaviour in multi-master scenarios. Nonetheless sometimes we want to be able to stream changes in advance of commit.
So we need the ability to start streaming a transaction from the upstream as its changes are seen in WAL, either applying it immediately on the downstream or spooling it on the downstream until it’s committed. This requires changes to the logical decoding facilities themselves, it isn’t something spock_output can do alone. However, we’ve left room in spock_output to support this when support is added to logical decoding:
Flags in most message types let us add fields if we need to, like a HAS_XID flag and an extra field for the transaction ID so we can differentiate between concurrent transactions when streaming. The space isn’t wasted the rest of the time.
The upstream isn’t allowed to send new message types, etc, without a capability flag being set by the client. So for interleaved xacts we won’t enable them in logical decoding unless the client tells us the client is prepared to cope with them by sending additional startup parameters.
Note that for consistency reasons we still have to commit things in the same order on the downstream. The purpose of transaction streaming is to reduce the latency between the commit of the last xact before a big one and the first xact after the big one, minimising the duration of the stall in the flow of smaller xacts perceptible on the downstream.
Transaction streaming also makes parallel apply on the downstream possible, though it is not necessary to have parallel apply to benefit from transaction streaming. Parallel apply has further complexities that are outside the scope of the output plugin design.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.16.4 - spock Output Plugin
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This is the logical decoding
output plugin
for spock. Its purpose is to extract a change stream from a PostgreSQL
database and send it to a client over a network connection using a
well-defined, efficient protocol that multiple different applications can
consume.
The primary purpose of spock_output is to supply data to logical
streaming replication solutions, but any application can potentially use its
data stream. The output stream is designed to be compact and fast to decode,
and the plugin supports upstream filtering of data (through hooks) so that only
the required information is sent.
Only one database is replicated, rather than the whole PostgreSQL install. A subset of that database may be selected for replication, currently based on table and on replication origin. Filtering by a WHERE clause can be supported easily in future.
No triggers are required to collect the change stream and no external ticker or other daemon is required. The stream of changes is accumulated using replication slots, as supported in PostgreSQL 9.4 or newer, and sent on top of the PostgreSQL streaming replication protocol.
Unlike block-level (“physical”) streaming replication, the change stream from
spock_output is compatible across different PostgreSQL
versions and can even be consumed by non-PostgreSQL clients.
Because logical decoding is used, only the changed rows are sent on the wire. There’s no index change data, no vacuum activity, etc transmitted.
The use of a replication slot means that the change stream is reliable and crash-safe. If the client disconnects or crashes it can reconnect and resume replay from the last message that client processed. Server-side changes that occur while the client is disconnected are accumulated in the queue to be sent when the client reconnects. This reliability also means that server-side resources are consumed whether or not a client is connected.
Why another output plugin?
See DESIGN.md for a discussion of why using one of the existing
generic logical decoding output plugins like wal2json to drive a logical
replication downstream isn’t ideal. It’s mostly about speed.
Architecture and high level interaction
The output plugin is loaded by a PostgreSQL walsender process when a client
connects to PostgreSQL using the PostgreSQL wire protocol with connection
option replication=database, then uses
the CREATE_REPLICATION_SLOT ... LOGICAL ... or START_REPLICATION SLOT ... LOGICAL ... commands to start streaming changes. (It can also be used via
SQL level functions
over a non-replication connection, but this is mainly for debugging purposes).
The client supplies parameters to the START_REPLICATION SLOT ... LOGICAL ...
command to specify the version of the spock protocol it supports,
whether it wants binary format, etc.
The output plugin processes the connection parameters and the connection enters
streaming replication protocol mode, sometimes called “COPY BOTH” mode because
it’s based on the protocol used for the COPY command. PostgreSQL then calls
functions in this plugin to send it a stream of transactions to decode and
translate into network messages. This stream of changes continues until the
client disconnects.
The only client-to-server interaction after startup is the sending of periodic
feedback messages that allow the replication slot to discard no-longer-needed
change history. The client must send feedback, otherwise pg_xlog on the
server will eventually fill up and the server will stop working.
Usage
The overall flow of client/server interaction is:
- Client makes PostgreSQL fe/be protocol connection to server
- Connection options must include
replication=databaseanddbname=[...]parameters - The PostgreSQL client library can be
libpqor anything else that supports the replication sub-protocol - The same mechanisms are used for authentication and protocol encryption as for a normal non-replication connection
- Connection options must include
- Client issues
IDENTIFY_SYSTEM- Server responds with a single row containing system identity info
- Client issues
CREATE_REPLICATION_SLOT slotname LOGICAL 'spock'if it’s setting up for the first time- Server responds with success info and a snapshot identifier
- Client may at this point use the snapshot identifier on other connections while leaving this one idle
- Client issues
START_REPLICATION SLOT slotname LOGICAL 0/0 (...options...)to start streaming, which loops:- Server emits
spockmessage block encapsulated in a replication protocolCopyDatamessage - Client receives and unwraps message, then decodes the
spockmessage block - Client intermittently sends a standby status update message to server to confirm replay
- Server emits
- … until client sends a graceful connection termination message on the fe/be protocol level or the connection is broken
The details of IDENTIFY_SYSTEM, CREATE_REPLICATION_SLOT and START_REPLICATION are discussed in the replication protocol docs and will not be repeated here.
Make a replication connection
To use the spock plugin you must first establish a PostgreSQL FE/BE
protocol connection using the client library of your choice, passing
replication=database as one of the connection parameters. database is a
literal string and is not replaced with the database name; instead the database
name is passed separately in the usual dbname parameter. Note that
replication is not a GUC (configuration parameter) and may not be passed in
the options parameter on the connection, it’s a top-level parameter like
user or dbname.
Example connection string for libpq:
'user=postgres replication=database sslmode=verify-full dbname=mydb'
The plug-in name to pass on logical slot creation is 'spock'.
Details are in the replication protocol docs.
Get system identity
If required you can use the IDENTIFY_SYSTEM command, which reports system
information:
systemid | timeline | xlogpos | dbname | dboid
---------------------+----------+-----------+--------+-------
6153224364663410513 | 1 | 0/C429C48 | testd | 16385
(1 row)
Details are in the replication protocol docs.
Create the slot if required
If your application creates its own slots on first use and hasn’t previously connected to this database on this system you’ll need to create a replication slot. This keeps track of the client’s replay state even while it’s disconnected.
The slot name may be anything your application wants up to a limit of 63 characters in length. It’s strongly advised that the slot name clearly identify the application and the host it runs on.
Pass spock as the plugin name.
e.g.
CREATE_REPLICATION_SLOT "reporting_host_42" LOGICAL "spock";
CREATE_REPLICATION_SLOT returns a snapshot identifier that may be used with
SET TRANSACTION SNAPSHOT
to see the database’s state as of the moment of the slot’s creation. The first
change streamed from the slot will be the change immediately after this
snapshot was taken. The snapshot is useful when cloning the initial state of a
database being replicated. Applications that want to see the change stream
going forward, but don’t care about the initial state, can ignore this. The
snapshot is only valid as long as the connection that issued the
CREATE_REPLICATION_SLOT remains open and has not run another command.
Send replication parameters
The client now sends:
START_REPLICATION SLOT "the_slot_name" LOGICAL (
'Expected_encoding', 'UTF8',
'Max_proto_major_version', '1',
'Min_proto_major_version', '1',
...moreparams...
);
to start replication.
The parameters are very important for ensuring that the plugin accepts
the replication request and streams changes in the expected form. spock
parameters are discussed in the separate spock protocol documentation.
Process the startup message
spock_output will send a CopyData message containing its
startup message as the first protocol message. This message contains a
set of key/value entries describing the capabilities of the upstream output
plugin, its version and the Pg version, the tuple format options selected,
etc.
The downstream client may choose to cleanly close the connection and disconnect at this point if it doesn’t like the reply. It might then inform the user or reconnect with different parameters based on what it learned from the first connection’s startup message.
Consume the change stream
spock_output now sends a continuous series of CopyData
protocol messages, each of which encapsulates a spock protocol message
as documented in the separate protocol docs.
These messages provide information about transaction boundaries, changed rows, etc.
The stream continues until the client disconnects, the upstream server is restarted, the upstream walsender is terminated by admin action, there’s a network issue, or the connection is otherwise broken.
The client should send periodic feedback messages to the server to acknowledge that it’s replayed to a given point and let the server release the resources it’s holding in case that change stream has to be replayed again. See “Hot standby feedback message” in the replication protocol docs for details.
Disconnect gracefully
Disconnection works just like any normal client; you use your client library’s usual method for closing the connection. No special action is required before disconnection, though it’s usually a good idea to send a final standby status message just before you disconnect.
Tests
There are two sets of tests bundled with spock_output: the pg_regress
regression tests and some custom Python tests for the protocol.
The pg_regress tests check invalid parameter handling and basic
functionality. They’re intended for use by the buildfarm using an in-tree
make check, but may also be run with an out-of-tree PGXS build against an
existing PostgreSQL install using make clean installcheck.
The Python tests are more comprehensive, and examine the data sent by
the extension at the protocol level, validating the protocol structure,
order and contents. They can run using the SQL-level logical decoding
interface or, with a psycopg2 containing https://github.com/psycopg/psycopg2/pull/322,
with the walsender / streaming replication protocol. The Python-based tests
exercise the internal binary format support, too. See test/README.md for
details.
The tests may fail on installations that are not utf-8 encoded because the payloads of the binary protocol output will have text in different encodings, which aren’t visible to psql as text to be decoded. Avoiding anything except 7-bit ascii in the tests should prevent the problem.
Changeset forwarding
It’s possible to use spock_output to cascade replication between multiple
PostgreSQL servers, in combination with an appropriate client to apply the
changes to the downstreams.
There are two forwarding modes:
Forward everything. Transactions are replicated whether they were made directly on the immediate upstream or some other node upstream of it. This is the only option when running on 9.4. All rows from transactions are sent.
Selected by not setting a row or transaction filter hook.
Filtered forwarding. Transactions are replicated unless a client-supplied transaction filter hook says to skip this transaction. Row changes are replicated unless the client-supplied row filter hook (if provided) says to skip that row.
Selected by installing a transaction and/or row filter hook (see “hooks”).
The server will enable changeset origin
information. It will set forward_changeset_origins to true in the startup
reply message to indicate this. It will then send changeset origin messages
after the BEGIN for each transaction, per the protocol documentation. Origin
messages are omitted for transactions originating directly on the immediate
upstream to save bandwidth. If forward_changeset_origins is true then
transactions without an origin are always from the immediate upstream that’s
running the decoding plugin.
Clients may use this facility to form arbitrarily complex topologies when combined with hooks to determine which transactions are forwarded. An obvious case is bi-directional (mutual) replication.
Selective replication
By specifying a row filter hook it’s possible to filter the replication stream server-side so that only a subset of changes is replicated.
Hooks
spock_output exposes a number of extension points where applications can
modify or override its behaviour.
All hooks are called in a memory context that lasts for the duration of the logical decoding session. They may switch to longer lived contexts if needed, but are then responsible for their own cleanup.
Hook setup function
The downstream must specify the fully-qualified name of a SQL-callable function
on the server as the value of the hooks.setup_function client parameter.
The SQL signature of this function is
CREATE OR REPLACE FUNCTION funcname(hooks internal, memory_context internal)
RETURNS void STABLE
LANGUAGE c AS 'MODULE_PATHNAME';
Permissions are checked. This function must be callable by the user that the output plugin is running as. The function name must be schema-qualified and is parsed like any other qualified identifier.
The function receives a pointer to a newly allocated structure of hook function pointers to populate as its first argument. The function must not free the argument.
If the hooks need a private data area to store information across calls, the
setup function should get the MemoryContext pointer from the 2nd argument,
then MemoryContextAlloc a struct for the data in that memory context and
store the pointer to it in hooks->hooks_private_data. This will then be
accessible on future calls to hook functions. It need not be manually freed, as
the memory context used for logical decoding will free it when it’s freed.
Don’t put anything in it that needs manual cleanup.
Hooks other than the hook setup function and the startup hook are called in a short-lived memory context. If they want to preserve anything they allocate after the hook returns they must switch to the memory context that was passed to the setup function and allocate it there.
Each hook has its own C signature (defined below) and the pointers must be directly to the functions. Hooks that the client does not wish to set must be left null.
An example is provided in examples/hooks and the argument structs are defined
in spock_output/hooks.h, which is installed into the PostgreSQL source
tree when the extension is installed.
Each hook that is enabled results in a new startup parameter being emitted in the startup reply message. Clients must check for these and must not assume a hook was successfully activated because no error is seen.
Hook functions are called in the context of the backend doing logical decoding.
Except for the startup hook, hooks see the catalog state as it was at the time
the transaction or row change being examined was made. Access to non-catalog
tables is unsafe unless they have the user_catalog_table reloption set. Among
other things this means that it’s not safe to invoke arbitrary functions,
user-defined procedures, etc, from hooks.
Startup hook
The startup hook is called when logical decoding starts.
This hook can inspect the parameters passed by the client to the output plugin as in_params. These parameters must not be modified.
It can add new parameters to the set to be returned to the client in the
startup parameters message, by appending to List out_params, which is
initially NIL. Each element must be a DefElem with the param name
as the defname and a String value as the arg, as created with
makeDefElem(...). It and its contents must be allocated in the
logical decoding memory context.
For walsender based decoding the startup hook is called only once, and cleanup might not be called at the end of the session.
Multiple decoding sessions, and thus multiple startup hook calls, may happen in a session if the SQL interface for logical decoding is being used. In that case it’s guaranteed that the cleanup hook will be called between each startup.
When successfully enabled, the output parameter hooks.startup_hook_enabled is
set to true in the startup reply message.
Unlike the other hooks, this hook sees a snapshot of the database’s current state, not a time-traveled catalog state. It is safe to access all tables from this hook.
Also unlike other hooks, the startup hook is called in a memory context with the same lifetime of the decoding session. It’s called in the same context as the one that’s passed to the hook setup hook.
Transaction filter hook
The transaction filter hook can exclude entire transactions from being decoded and replicated based on the node they originated from.
It is passed a const TxFilterHookArgs * containing:
- The hook argument supplied by the client, if any
- The
RepOriginIdthat this transaction originated from
and must return boolean, where true retains the transaction for sending to the client and false discards it. (Note that this is the reverse sense of the low level logical decoding transaction filter hook).
The hook function must not free the argument struct or modify its contents.
The transaction filter hook is only called on PostgreSQL 9.5 and above. It is ignored on 9.4.
Note that individual changes within a transaction may have different origins to the transaction as a whole; see “Origin filtering” for more details. If a transaction is filtered out, all changes are filtered out even if their origins differ from that of the transaction as a whole.
When successfully enabled, the output parameter
hooks.transaction_filter_enabled is set to true in the startup reply message.
Memory allocated in this hook is freed at the end of the call.
Row filter hook
The row filter hook is called for each row. It is passed information about the table, the transaction origin, and the row origin.
It is passed a const RowFilterHookArgs* containing:
- The hook argument supplied by the client, if any
- The
Relationthe change affects - The change type - ‘I’nsert, ‘U’pdate or ‘D’elete
It can return true to retain this row change, sending it to the client, or false to discard it.
The function must not free the argument struct or modify its contents.
Note that it is more efficient to exclude whole transactions with the transaction filter hook rather than filtering out individual rows.
When successfully enabled, the output parameter
hooks.row_filter_enabled is set to true in the startup reply message.
Memory allocated in this hook is freed at the end of the call.
Shutdown hook
The shutdown hook is called when a decoding session ends. You can’t rely on this hook being invoked reliably, since a replication-protocol walsender-based session might just terminate. It’s mostly useful for cleanup to handle repeated invocations under the SQL interface to logical decoding.
You don’t need a hook to free memory you allocated, unless you explicitly
switched to a longer lived memory context like TopMemoryContext. Memory
allocated in the hook context will be automatically freed when the decoding
session shuts down.
Limitations
The advantages of logical decoding in general and spock_output in
particular are discussed above. There are also some limitations that apply to
spock_output, and to Pg’s logical decoding in general.
Notably:
Mostly one-way communication
Per the protocol documentation, the downstream can’t send anything except replay progress messages to the upstream after replication begins, and can’t re-initialise replication without a disconnect.
To achieve downstream-to-upstream communication, clients can use a regular libpq connection to the upstream then write to tables or call functions. Alternately, a separate replication connection in the opposite direction can be created by the application to carry information from downstream to upstream.
See “Protocol flow” in the protocol documentation for more information.
Doesn’t replicate global objects/shared catalog changes
PostgreSQL has a number of object types that exist across all databases, stored in shared catalogs. These include:
- Roles (users/groups)
- Security labels on users and databases
Such objects cannot be replicated by spock_output. They’re managed with DDL that
can’t be captured within a single database and isn’t decoded anyway.
Global object changes must be synchronized via some external means.
Physical replica failover
Logical decoding cannot follow a physical replication failover because replication slot state is not replicated to physical replicas. If you fail over to a streaming replica you have to manually reconnect your logical replication clients, creating new slots, etc. This is a core PostgreSQL limitation.
Also, there’s no built-in way to guarantee that the logical replication slot from the failed master hasn’t replayed further than the physical streaming replica you failed over to. You could receive changes on your logical decoding stream from the old master that never made it to the physical streaming replica. This is true (albeit very unlikely) even if the physical streaming replica is synchronous because PostgreSQL sends the replication data anyway, then just delays the commit’s visibility on the master. Support for strictly ordered standbys would be required in PostgreSQL to avoid this.
To achieve failover with logical replication you cannot mix in physical standbys. The logical replication client has to take responsibility for maintaining slots on logical replicas intended as failover candidates and for ensuring that the furthest-ahead replica is promoted if there is more than one.
Can only replicate complete transactions
Logical decoding can only replicate a transaction after it has committed. This usefully skips replication of rolled back transactions, but it also means that very large transactions must be completed upstream before they can begin on the downstream, adding to replication latency.
Replicates only one transaction at a time
Logical decoding serializes transactions in commit order, so spock_output cannot replay interleaved concurrent transactions. This can lead to high latencies when big transactions are being replayed, since smaller transactions get queued up behind them.
Unique index required for inserts or updates
To replicate INSERTs or UPDATEs it is necessary to have a PRIMARY KEY
or a (non-partial, columns-only) UNIQUE index on the table, so the table
has a REPLICA IDENTITY. Without that spock_output doesn’t know what
old key to send to allow the receiver to tell which tuple is being updated.
UNLOGGED tables aren’t replicated
Because UNLOGGED tables aren’t written to WAL, they aren’t replicated by
logical or physical replication. You can only replicate UNLOGGED tables
with trigger-based solutions.
Unchanged fields are often sent in UPDATE
Because there’s no tracking of dirty/clean fields when a tuple is updated, logical decoding can’t tell if a given field was changed by an update. Unchanged fields can only by identified and omitted if they’re a variable length TOASTable type and are big enough to get stored out-of-line in a TOAST table.
Troubleshooting and debugging
Non-destructively previewing pending data on a slot
Using the json mode of spock_output you can examine pending transactions
on a slot without consuming them, so they are still delivered to the usual
client application that created/owns this slot. This is best done using the SQL
interface to logical decoding, since it gives you finer control than using
pg_recvlogical.
You can only peek at a slot while there is no other client connected to that slot.
Use spock_slot_peek_changes to examine the change stream without
destructively consuming changes. This is extremely helpful when trying to
determine why an error occurs in a downstream, since you can examine a
transaction in json (rather than binary) format. It’s necessary to supply a
minimal set of required parameters to the output plugin.
e.g. given setup:
CREATE TABLE discard_test(blah text);
SELECT 'init' FROM pg_create_logical_replication_slot('demo_slot', 'spock_output');
INSERT INTO discard_test(blah) VALUES('one');
INSERT INTO discard_test(blah) VALUES('two1'),('two2'),('two3');
INSERT INTO discard_test(blah) VALUES('three1'),('three2');
you can peek at the change stream with:
SELECT location, xid, data
FROM spock_slot_peek_changes('demo_slot', NULL, NULL,
'min_proto_version', '1', 'max_proto_version', '1',
'startup_params_format', '1', 'proto_format', 'json');
The two NULLs mean you don’t want to stop decoding after any particular
LSN or any particular number of changes. Decoding will stop when there’s nothing
left to decode or you cancel the query.
This will emit a key/value startup message then change data rows like:
location | xid | data
0/4E8AAF0 | 5562 | {"action":"B", has_catalog_changes:"f", xid:"5562", first_lsn:"0/4E8AAF0", commit_time:"2015-11-13 14:26:21.404425+08"}
0/4E8AAF0 | 5562 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"one"}}
0/4E8AB70 | 5562 | {"action":"C", final_lsn:"0/4E8AB30", end_lsn:"0/4E8AB70"}
0/4E8ABA8 | 5563 | {"action":"B", has_catalog_changes:"f", xid:"5563", first_lsn:"0/4E8ABA8", commit_time:"2015-11-13 14:26:32.015611+08"}
0/4E8ABA8 | 5563 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"two1"}}
0/4E8ABE8 | 5563 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"two2"}}
0/4E8AC28 | 5563 | {"action":"I","relation":["public","discard_test"],"newtuple":{"blah":"two3"}}
0/4E8ACA8 | 5563 | {"action":"C", final_lsn:"0/4E8AC68", end_lsn:"0/4E8ACA8"}
....
The output is the LSN (log sequence number) associated with a change, the top level transaction ID that performed the change, and the change data as json.
You can see the transaction boundaries by xid changes and by the “B"egin and “C"ommit messages, and you can see the individual row “I"nserts. Replication origins, commit timestamps, etc will be shown if known.
See http://www.postgresql.org/docs/current/static/functions-admin.html for information on the peek functions.
If you want the binary format you can get that with
spock_slot_peek_binary_changes and the native protocol, but that’s
generally much less useful.
Manually discarding a change from a slot
Sometimes it’s desirable to manually purge one or more changes from a replication slot. This is usually an error recovery step when problems arise with the downstream code that’s replaying from the slot.
You can use the peek functions to determine the point in the stream you want to discard up to, as identified by LSN (log sequence number). See “non-destructively previewing pending data on a slot” above for details.
You can’t control the point you start discarding from, it’s always from the current stream position up to a point you specify. If the peek shows that there’s data you still want to retain you must make sure that the downstream replays up to the point you want to keep changes and sends replay confirmation. In other words there’s no way to cut a sequence of changes out of the middle of the pending change stream.
Once you’ve peeked the stream and know the LSN you want to discard up to, you
can use spock_slot_get_changes, specifying an upto_lsn, to consume
changes from the slot up to but not including that point. That will be the
point at which replay resumes.
For example, if you wanted to discard the first transaction in the example
from the section above, i.e. discard xact 5562 and start decoding at xact
5563 from its’ BEGIN lsn 0/4E8ABA8, you’d run:
SELECT location, xid, data
FROM spock_slot_get_changes('demo_slot', '0/4E8ABA8', NULL,
'min_proto_version', '1', 'max_proto_version', '1',
'startup_params_format', '1', 'proto_format', 'json');
Note that _get_changes is used instead of _peek_changes and that
the upto_lsn is '0/4E8ABA8' instead of NULL.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.16.5 - Spock Protocol
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
spock_output defines a libpq subprotocol for streaming tuples, metadata, etc., from the decoding plugin to receivers.
This protocol is an inner layer in a stack:
- TCP or unix sockets
- libpq protocol
- libpq replication subprotocol (COPY BOTH etc.)
- spock output plugin => consumer protocol
- libpq replication subprotocol (COPY BOTH etc.)
- libpq protocol
so clients can simply use libpq’s existing replication protocol support, directly or via their libpq-wrapper driver.
This is a binary protocol intended for compact representation.
spock_output also supports a json-based text protocol with json
representations of the same changesets, supporting all the same hooks etc.,
intended mainly for tracing/debugging/diagnostics. That protocol is not
discussed here.
Table of Contents
- Protocol Flow
- Protocol Messages
- Startup Message
- Startup Errors
- Arguments Client Supplies to Output Plugin
- Extensibility
- JSON Protocol
Protocol Flow
The protocol flow is primarily from upstream walsender/decoding plugin to the downstream receiver.
The only information that flows downstream-to-upstream is:
- The initial parameter list sent to
START_REPLICATION; and - replay progress messages
We can accept an arbitrary list of params to START_REPLICATION. After
that we have no general-purpose channel for information to flow upstream. That
means we can’t do a multi-step negotiation or handshake for determining the
replication options to use, binary protocol, etc.
The main form of negotiation is the client getting a “take it or leave it” set of settings from the server in an initial startup message sent before any replication data (see below) and, if it doesn’t like them, reconnecting with different startup options.
Except for the negotiation via initial parameter list and then startup message the protocol flow is the same as any other walsender-based logical replication plugin. The data stream is sent in COPY BOTH mode as a series of CopyData messages encapsulating replication data, and ends when the client disconnects. There’s no facility for ending the COPY BOTH mode and returning to the walsender command parser to issue new commands. This is a limitation of the walsender interface, not spock_output.
Protocol Messages
The individual protocol messages are discussed in the following sub-sections. Protocol flow and logic comes in the next major section.
Absolutely all top-level protocol messages begin with a message type byte. While represented in code as a character, this is a signed byte with no associated encoding.
Since the PostgreSQL libpq COPY protocol supplies a message length there’s no need for top-level protocol messages to embed a length in their header.
BEGIN Message
A stream of rows starts with a BEGIN message. Rows may only be sent after a
BEGIN and before a COMMIT.
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal B (0x42) |
| flags | uint8 | 0-3: Reserved, client must ERROR if set and not recognised. |
| lsn | uint64 | “final_lsn” in decoding context - currently it means lsn of commit |
| commit time | uint64 | “commit_time” in decoding context |
| remote XID | uint32 | “xid” in decoding context |
Forwarded Transaction Origin Message
The message after the BEGIN may be a forwarded transaction origin message
indicating what upstream node the transaction came from.
Sent if the immediately prior message was a BEGIN message, the upstream
transaction was forwarded from another node, and replication origin forwarding
is enabled, i.e. forward_changeset_origins is t in the startup reply
message.
A “node” could be another host, another DB on the same host, or pretty much
anything. Whatever origin name is found gets forwarded. The origin identifier
is of arbitrary and application-defined format. Applications should prefix
their origin identifier with a fixed application name part, like bdr_,
myapp_, etc. It is application-defined what an application does with
forwarded transactions from other applications.
An origin message with a zero-length origin name indicates that the origin could not be identified but was (probably) not the local node. It is client-defined what action is taken in this case.
It is a protocol error to send/receive a forwarded transaction origin message
at any time other than immediately after a BEGIN message.
The origin identifier is typically closely related to replication slot names and replication origins’ names in an application system.
For more detail see Changeset Forwarding in the README.
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal O (0x4f) |
| flags | uint8 | 0-3: Reserved, application must ERROR if set and not recognised |
| origin_lsn | uint64 | LSN (XLogRecPtr) of the transaction’s commit record on its origin node (as opposed to the forwarding node’s commit LSN, which is ’lsn’ in the BEGIN message) |
| origin_identifier_length | uint8 | Length in bytes of origin_identifier |
| origin_identifier | signed char[origin_identifier_length] | An origin identifier of arbitrary, upstream-application-defined structure. Should be text in the same encoding as the upstream database. NULL-terminated. Should be 7-bit ASCII. |
COMMIT Message
A stream of rows ends with a COMMIT message.
There is no ROLLBACK message because aborted transactions are not sent by the
upstream.
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal C (0x43) |
| Flags | uint8 | 0-3: Reserved, client must ERROR if set and not recognised |
| Commit LSN | uint64 | commit_lsn in decoding commit decode callback. This is the same value as in the BEGIN message, and marks the end of the transaction. |
| End LSN | uint64 | end_lsn in decoding transaction context |
| Commit time | uint64 | commit_time in decoding transaction context |
INSERT, UPDATE or DELETE Message
After a BEGIN or metadata message, the downstream should expect to receive
zero or more row change messages, composed of an insert/update/delete message
with zero or more tuple fields, each of which has one or more tuple field
values.
The row’s relidentifier must match that of the most recently preceding metadata message. All consecutive row messages must currently have the same relidentifier. (Later extensions to add metadata caching will relax these requirements for clients that advertise caching support; see the documentation on metadata messages for more detail).
It is an error to decode rows using metadata received after the row was received, or using metadata that is not the most recently received metadata revision that still predates the row. I.e. in the sequence M1, R1, R2, M2, R3, M4: R1 and R2 must be decoded using M1, and R3 must be decoded using M2. It is an error to use M4 to decode any of the rows, to use M1 to decode R3, or to use M2 to decode R1 and R2.
Row messages may not arrive except during a transaction as delimited by BEGIN
and COMMIT messages. It is an error to receive a row message outside a
transaction.
Any unrecognised tuple type or tuple part type is an error on the downstream that must result in a client disconnect and error message. Downstreams are expected to negotiate compatibility, and upstreams must not add new tuple types or tuple field types without negotiation.
The downstream reads rows until the next non-row message is received. There is no other end marker or any indication of how many rows to expect in a sequence.
Row Message Header
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal Insert (0x49), Update (0x55) or Delete (0x44) |
| flags | uint8 | Row flags (reserved) |
| relidentifier | uint32 | relidentifier that matches the table metadata message sent for this row. (Not present in BDR, which sends nspname and relname instead) |
| [tuple parts] | [composite] |
One or more tuple-parts fields follow.
Tuple Fields
| Message | Type/Size | Notes |
|---|---|---|
| Tuple type | signed char | Identifies the kind of tuple being sent. |
| tupleformat | signed char | T (0x54) |
| natts | uint16 | Number of fields sent in this tuple part. (Present in BDR, but meaning significantly different here) |
| [tuple field values] | [composite] |
Tuple tupleformat compatibility
Unrecognised tupleformat kinds are a protocol error for the downstream.
Tuple Field Value Fields
These message parts describe individual fields within a tuple.
There are two kinds of tuple value fields, abbreviated and full. Which is being read is determined based on the first field, kind.
Abbreviated tuple value fields are nothing but the message kind:
| Message | Type/Size | Notes |
|---|---|---|
| kind | signed char | null (0x6e) field |
Full tuple value fields have a length and datum:
| Message | Type/Size | Notes |
|---|---|---|
| kind | signed char | internal binary (0x62) field |
| length | int4 | Only defined for kind = i|b|t |
| data | [length] | Data in a format defined by the table metadata and column kind. |
Tuple Field Values Kind Compatibility
Unrecognised field kind values are a protocol error for the downstream. The downstream may not continue processing the protocol stream after this point.
The upstream may not send internal or binary format values to the downstream without the downstream negotiating acceptance of such values. The downstream will also generally negotiate to receive type information to use to decode the values. See the section on startup parameters and the startup message for details.
Table/Row Metadata Messages
Before sending changed rows for a relation, a metadata message for the relation must be sent so the downstream knows the namespace, table name, column names, optional column types, etc. A relidentifier field, an arbitrary numeric value unique for that relation on that upstream connection, maps the metadata to following rows.
A client should not assume that relation metadata will be followed immediately (or at all) by rows, since future changes may lead to metadata messages being delivered at other times. Metadata messages may arrive during or between transactions.
The upstream may not assume that the downstream retains more metadata than the one most recent table metadata message. This applies across all tables, so a client is permitted to discard metadata for table x when getting metadata for table y. The upstream must send a new metadata message before sending rows for a different table, even if that metadata was already sent in the same session or even same transaction. This requirement will later be weakened by the addition of client metadata caching, which will be advertised to the upstream with an output plugin parameter.
Columns in metadata messages are numbered from 0 to natts-1, reading consecutively from start to finish. The column numbers do not have to be a complete description of the columns in the upstream relation, so long as all columns that will later have row values sent are described. The upstream may choose to omit columns it doesn’t expect to send changes for in any given series of rows. Column numbers are not necessarily stable across different sets of metadata for the same table, even if the table hasn’t changed structurally.
A metadata message may not be used to decode rows received before that metadata message.
Table Metadata Header
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | Literal R (0x52) |
| flags | uint8 | 0-6: Reserved, client must ERROR if set and not recognised. |
| relidentifier | uint32 | Arbitrary relation id, unique for this upstream. In practice this will probably be the upstream table’s oid, but the downstream can’t assume anything. |
| nspnamelength | uint8 | Length of namespace name (incl. terminating \0) |
| nspname | signed char[nspnamelength] | Relation namespace (null terminated) |
| relnamelength | uint8 | Length of relation name (incl. terminating \0) |
| relname | char[relname] | Relation name (null terminated) |
| attrs block | signed char | Literal: A (0x41) |
| natts | uint16 | Number of attributes |
| [fields] | [composite] | Sequence of ’natts’ column metadata blocks, each of which begins with a column delimiter followed by zero or more column metadata blocks, each with the same column metadata block header. This chunked format is used so that new metadata messages can be added without breaking existing clients. |
Column Delimiter
Each column’s metadata begins with a column metadata header. This comes immediately after the natts field in the table metadata header or after the last metadata block in the prior column.
It has the same char header as all the others, and the flags field is the same size as the length field in other blocks, so it’s safe to read this as a column metadata block header.
Currently, the only defined flag is 0x1 indicating that the column is part of the relation’s identity key.
| Message | Type/Size | Notes |
|---|---|---|
| blocktype | signed char | C (0x43) - column |
| flags | uint8 | Column info flags |
Column Metadata Block Header
All column metadata blocks share the same header, which is the same length as a column delimiter:
| Message | Type/Size | Notes |
|---|---|---|
| blocktype | signed char | Identifies the kind of metadata block that follows. |
| blockbodylength | uint16 | Length of block in bytes, excluding blocktype char and length field. |
Column Name Block
This block just carries the name of the column, nothing more. It begins with a column metadata block, and the rest of the message is the column name.
| Message | Type/Size | Notes |
|---|---|---|
| [column metadata block header] | [composite] | blocktype = N (0x4e) |
| colname | char[blockbodylength] | Column name. |
Column Type Block
T.B.D.
Not defined in first protocol revision.
Likely to send a type identifier (probably the upstream oid) as a reference to a “type info” protocol message to be delivered before. Then we can cache the type descriptions and avoid repeating long schemas and names, just using the oids.
Needs to have room to handle:
- built-in core types
- extension types (ext version may vary)
- enum types (CREATE TYPE … AS ENUM)
- range types (CREATE TYPE … AS RANGE)
- composite types (CREATE TYPE … AS (…))
- custom types (CREATE TYPE ( input = x_in, output = x_out ))
… some of which can be nested
Startup Message
After processing output plugin arguments, the upstream output plugin must send a startup message as its first message on the wire. It is a trivial header followed by alternating key and value strings represented as null-terminated unsigned char strings.
This message specifies the capabilities the output plugin enabled and describes the upstream server and plugin. This may change how the client decodes the data stream, and/or permit the client to disconnect and report an error to the user if the result isn’t acceptable.
If replication is rejected because the client is incompatible or the server is unable to satisfy required options, the startup message may be followed by a libpq protocol FATAL message that terminates the session. See Startup Errors below.
The parameter names and values are sent as alternating key/value pairs as null-terminated strings, e.g.
key1\0parameter1\0key2\0value2\0
| Message | Type/Size | Notes |
|---|---|---|
| Message type | signed char | S (0x53) - startup |
| Startup message version | uint8 | Value is always “1”. |
| (parameters) | null-terminated key/value pairs | See table below for parameter definitions. |
Startup Message Parameters
Since all parameter values are sent as strings, the value types given below specify what the value must be reasonably interpretable as.
| Key name | Value type | Description |
|---|---|---|
| max_proto_version | integer | Newest version of the protocol supported by output plugin. Currently 5. |
| min_proto_version | integer | Oldest protocol version supported by server. Currently 4. |
| proto_version | integer | The negotiated protocol version selected by the server based on the overlap between client and server ranges. |
| coltypes | boolean | Column types will be sent in table metadata. Currently always false. |
| pg_version_num | integer | PostgreSQL server_version_num of server, if it’s PostgreSQL. e.g. 180000 |
| pg_version | string | PostgreSQL server_version of server, if it’s PostgreSQL. e.g. “18.0” |
| pg_catversion | uint32 | Version of the PostgreSQL system catalogs on the upstream server, if it’s PostgreSQL. |
| database_encoding | string | The native text encoding of the database the plugin is running in. |
| encoding | string | Field values for textual data will be in this encoding in native protocol text, binary or internal representation. For the native protocol this is currently always the same as database_encoding. For text-mode json protocol this is always the same as client_encoding. |
| forward_changeset_origins | bool | Tells the client that the server will send changeset origin information. See Changeset forwarding for details. |
| walsender_pid | integer | PID of the walsender process on the upstream server. |
| spock_version | string | Spock version string of the upstream server. e.g. “4.0.11” |
| spock_version_num | integer | Spock numeric version of the upstream server. e.g. 40011 |
| no_txinfo | bool | Echo of the client’s no_txinfo setting. When true, variable transaction info such as XIDs, LSNs, and timestamps are omitted from output. Mainly for tests. Currently ignored for protos other than json. |
Startup Message ‘binary’ Parameters
| Key name | Value type | Description |
|---|---|---|
| binary.internal_basetypes | boolean | If true, PostgreSQL internal binary representations for row field data may be used for some or all row fields, where the type is appropriate and the binary compatibility parameters of upstream and downstream match. See binary.want_internal_basetypes in the output plugin parameters for details. May only be true if binary.want_internal_basetypes was set to true by the client in the parameters and the client’s accepted binary format matches that of the server. |
| binary.binary_basetypes | boolean | If true, external binary format (send/recv format) may be used for some or all row field data where the field type is a built-in base type whose send/recv format is compatible with binary.binary_pg_version. May only be set if binary.want_binary_basetypes was set to true by the client in the parameters and the client’s accepted send/recv format matches that of the server. |
| binary.basetypes_major_version | uint16 | The PostgreSQL major version that internal binary format values are compatible with. Corresponds to PG_VERSION_NUM/100 on the upstream server. |
| binary.binary_pg_version | uint16 | The PostgreSQL major version that send/recv format values will be compatible with. This is not necessarily the actual upstream PostgreSQL version. |
| binary.sizeof_int | uint8 | sizeof(int) on the upstream. |
| binary.sizeof_long | uint8 | sizeof(long) on the upstream. |
| binary.sizeof_datum | uint8 | sizeof(Datum) on the upstream (the PostgreSQL Datum typedef). |
| binary.maxalign | uint8 | Upstream PostgreSQL server’s MAXIMUM_ALIGNOF value - platform dependent, determined at build time. |
| binary.bigendian | bool | True iff the upstream is big-endian. |
| binary.float4_byval | bool | Upstream PostgreSQL’s float4_byval compile option. |
| binary.float8_byval | bool | Upstream PostgreSQL’s float8_byval compile option. |
| binary.integer_datetimes | bool | Whether TIME, TIMESTAMP and TIMESTAMP WITH TIME ZONE will be sent using integer or floating point representation. Usually this is the value of the upstream PostgreSQL’s integer_datetimes compile option. |
Startup Errors
If the server rejects the client’s connection - due to non-overlapping protocol support, unrecognised parameter formats, unsupported required parameters like hooks, etc - then it will follow the startup reply message with a normal libpq protocol error message. (Current versions send this before the startup message).
Arguments Client Supplies to Output Plugin
The one opportunity for the downstream client to send information (other than replay feedback) to the upstream is at connect-time, as an array of arguments to the output plugin supplied to START LOGICAL REPLICATION.
There is no back-and-forth, no handshake.
As a result, the client mainly announces capabilities and makes requests of the output plugin. The output plugin will ERROR if required parameters are unset, or where incompatibilities that cannot be resolved are found. Otherwise the output plugin reports what it could and could not honour in the startup message it sends as the first message on the wire down to the client. The client chooses whether to continue replay or to disconnect and report an error to the user, then possibly reconnect with different options.
Output Plugin Arguments
The output plugin’s key/value arguments are specified in pairs, as key and value. They’re what’s passed to START_REPLICATION, etc.
All parameters are passed in text form. They should be limited to 7-bit ASCII, since the server’s text encoding is not known, but may be normalized precomposed UTF-8. The types specified for parameters indicate what the output plugin should attempt to convert the text into. Clients should not send text values that are outside the range for that type.
Capabilities
Many values are capabilities flags for the client, indicating that it understands optional features like metadata caching, binary format transfers, etc. In general the output plugin may disregard capabilities the client advertises as supported and act as if they are not supported. If a capability is advertised as unsupported or is not advertised the output plugin must not enable the corresponding features.
In other words, don’t send the client something it’s not expecting.
Protocol Versioning
Two parameters max_proto_version and min_proto_version, which clients must always send, allow negotiation of the protocol version. The output plugin must ERROR if the client protocol support does not overlap its own protocol support range.
The protocol version is only incremented when there are major breaking changes that all or most clients must be modified to accommodate. Most changes are done by adding new optional messages and/or by having clients advertise capabilities to opt in to features.
The current protocol version range is 4 (min) to 5 (max). Both nodes must be running Spock version >= 50000 to use protocol versions 4 and 5.
The startup_params_format parameter identifies the format of the startup parameter set itself (currently always “1”). Parameters are looked up by name and may appear in any order.
| Key | Type | Value(s) | Notes |
|---|---|---|---|
| startup_params_format | uint32 | 1 | The format version of this startup parameter set. Currently always 1. Required, ERROR if missing. |
| max_proto_version | uint32 | 4-5 | Newest version of the protocol supported by client. Output plugin must ERROR if supported version too old. Required, ERROR if missing. |
| min_proto_version | uint32 | 4-5 | Oldest version of the protocol supported by client. Output plugin must ERROR if supported version too old. Required, ERROR if missing. |
Client Requirements and Capabilities
| Key | Type | Default | Notes |
|---|---|---|---|
| expected_encoding | string | null | The text encoding the downstream expects field values to be in. Applies to text, binary and internal representations of field values in native format. Has no effect on other protocol content. If specified, the upstream must honour it. For json protocol, must be unset or match client_encoding. (Current plugin versions ERROR if this is set for the native protocol and not equal to the upstream database’s encoding). |
| proto_format | string | null | Protocol format requested. “native” (documented here) or “json”. Default is native (binary). |
| no_txinfo | boolean | false | When true, requests that variable transaction info such as XIDs, LSNs, and timestamps be omitted from output. Mainly for tests. Currently ignored for protos other than json. |
Spock-Specific Parameters
These parameters are specific to the Spock replication extension and control what data is replicated.
| Key | Type | Default | Notes |
|---|---|---|---|
| spock.forward_origins | string | null | Comma-separated list of replication origin names to forward. Currently only the special value “all” is accepted. |
| spock.replication_set_names | string | null | Comma-separated list of replication set names to subscribe to. If specified, only changes in the named replication sets are sent. |
| spock.replicate_only_table | string | null | Qualified table name (schema.table) to replicate. If specified, only changes to this single table are sent. Used during initial table synchronization. |
| hooks.setup_function | string | null | Legacy parameter for backwards compatibility with Spock 1.x. Currently ignored. |
General Client Information
These keys tell the output plugin about the client. They’re mainly for informational purposes. In particular, the versions must not be used to determine compatibility for binary or send/recv format, as non-PostgreSQL clients will simply not send them at all but may still understand binary or send/recv format fields.
| Key | Type | Default | Notes |
|---|---|---|---|
| pg_version | uint32 | null | PostgreSQL PG_VERSION_NUM of the downstream, if it’s PostgreSQL. e.g. 180000. Note: despite the name, this is the numeric version (equivalent to the startup message’s pg_version_num). |
| spock_version | string | null | Spock version string of the downstream. e.g. “4.0.11”. Logged on the upstream if it differs from the server’s version. |
| spock_version_num | uint32 | null | Spock numeric version of the downstream. e.g. 40011. Logged on the upstream if it differs from the server’s version. |
Parameters Relating to Exchange of Binary Values
The downstream may specify to the upstream that it is capable of understanding binary (PostgreSQL internal binary datum format), and/or send/recv (PostgreSQL binary interchange) format data by setting the binary.want_binary_basetypes and/or binary.want_internal_basetypes options, or other yet-to-be-defined options.
An upstream output plugin that does not support one or both formats may ignore the downstream’s binary support and send text format, in which case it may ignore all binary.* parameters. All downstreams must support text format. An upstream output plugin must not send binary or send/recv format unless the downstream has announced it can receive it. If both upstream and downstream support both formats an upstream should prefer binary format and fall back to send/recv, then to text, if compatibility requires.
Internal and binary format selection should be done on a type-by-type basis. It is quite normal to send ’text’ format for extension types while sending binary for built-in types.
The downstream must specify its compatibility requirements for internal and binary data if it requests either or both formats. The upstream must honour these by falling back from binary to send/recv, and from send/recv to text, where the upstream and downstream are not compatible.
An unspecified compatibility field must be presumed to be unsupported by the downstream so that older clients that don’t know about a change in a newer version don’t receive unexpected data. For example, in the unlikely event that PostgreSQL 99.8 switched to 128-bit DPD (Densely Packed Decimal) representations of NUMERIC instead of the current arbitrary-length BCD (Binary Coded Decimal) format, a new binary.dpd_numerics parameter would be added. Clients that didn’t know about the change wouldn’t know to set it, so the upstream would presume it unsupported and send text format NUMERIC to those clients. This also means that clients that support the new format wouldn’t be able to receive the old format in binary from older servers since they’d specify dpd_numerics = true in their compatibility parameters.
At this time a downstream may specify compatibility with only one value for a given option; i.e. a downstream cannot say it supports both 4-byte and 8-byte sizeof(int). Leaving it unspecified means the upstream must assume the downstream supports neither. (A future protocol extension may allow clients to specify alternative sets of supported formats).
The pg_version option must not be used to decide compatibility. Use binary.basetypes_major_version instead.
| Key name | Value type | Default | Description |
|---|---|---|---|
| binary.want_binary_basetypes | boolean | false | True if the client accepts binary interchange (send/recv) format rows for PostgreSQL built-in base types. |
| binary.want_internal_basetypes | boolean | false | True if the client accepts PostgreSQL internal-format binary output for base PostgreSQL types not otherwise specified elsewhere. |
| binary.basetypes_major_version | uint32 | null | The PostgreSQL major version the downstream expects binary and send/recv format values to be in. Corresponds to PG_VERSION_NUM/100 in PostgreSQL. e.g. 180 for PostgreSQL 18.0. |
| binary.sizeof_int | uint32 | null | sizeof(int) on the downstream. |
| binary.sizeof_long | uint32 | null | sizeof(long) on the downstream. |
| binary.sizeof_datum | uint32 | null | sizeof(Datum) on the downstream (the PostgreSQL Datum typedef). |
| binary.bigendian | bool | null | True iff the downstream is big-endian. |
| binary.float4_byval | bool | null | Downstream PostgreSQL’s float4_byval compile option. |
| binary.float8_byval | bool | null | Downstream PostgreSQL’s float8_byval compile option. |
| binary.integer_datetimes | bool | null | Downstream PostgreSQL’s integer_datetimes compile option. |
Note:
binary.maxalignis not sent by the downstream client. It is only present in the upstream’s startup message. The upstream uses its own MAXIMUM_ALIGNOF for binary compatibility decisions.
Extensibility
Because of the use of optional parameters in output plugin arguments, and the confirmation/response sent in the startup packet, a basic handshake is possible between upstream and downstream, allowing negotiation of capabilities.
The output plugin must never send non-optional data or change its wire format without confirmation from the client that it can understand the new data. It may send optional data without negotiation.
When extending the output plugin arguments, add-ons are expected to prefix all keys with the extension name, and should preferably use a single top level key with a json object value to carry their extension information. Additions to the startup message should follow the same pattern.
Hooks and plugins can be used to add functionality specific to a client.
JSON Protocol
If proto_format is set to json then the output plugin will emit JSON
instead of the custom binary protocol. JSON support is intended mainly for
debugging and diagnostics.
The JSON format supports all the same hooks.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.17 - Troubleshooting Spock
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This document provides solutions to common issues encountered when using Spock for PostgreSQL logical replication.
Start with the Status Views
Before reading the server log, query the status views. They hold the last error of every apply worker and a history of recent events on the node:
Common Replication Issues
This section describes common problems that prevent replication from working correctly and provides solutions for each issue.
Replication Not Starting
If replication fails to start, check the following items:
Verify
pg_hba.confentries allow secure connections between nodes.Test network connectivity between nodes with the following command:
You can check the PostgreSQL logs for detailed error messages with this command:
You can verify that the Spock extension is created on both nodes with this query:
Subscription Stuck in Initializing State
If a subscription remains in the initializing state, verify the following configuration parameters.
Check that
max_replication_slotsis set to a sufficient value:A subscription that is initializing needs two slots on the provider: the one held by its apply stream, plus one created for the sync worker that copies the table data. Subscriptions are per database, so size for
2 x subscribers x replicated databasesper node, plus any physical or failover slots. On PostgreSQL 15-17 this parameter also caps replication origins.Verify that
max_wal_sendersis set to a sufficient value:Set this equal to
max_replication_slots: every slot has a walsender behind it while it streams, so the accounting above applies unchanged. A shortfall here is the most common reason a cluster that replicates fine in steady state cannot add or resync a table.For PostgreSQL 18+, check the
max_active_replication_originssetting:Ensure that the value is at least the number of subscriptions this node applies -
(nodes - 1) x replicated databasesin a full mesh - plus headroom.If parameters were modified, restart PostgreSQL with this command:
Check the subscription status with this query:
DDL Not Replicating
If DDL statements are not replicating across nodes, check the following settings.
Verify that automatic DDL replication is enabled with this query:
The value should be
on.Check that the
include_ddl_repsetparameter is enabled:Ensure that schema structures match on both nodes before enabling auto-DDL.
To confirm that DDL is replicated from functions, verify this setting is enabled:
Some DDL statements are intentionally not replicated, such as CREATE DATABASE. The CREATE TABLE...AS... statement generates a warning:
“DDL statement replicated, but could be unsafe.”
UPDATE or DELETE Operations Fail
If UPDATE or DELETE operations fail with unable to find tuple errors,
the table may be missing a primary key or replica identity.
To resolve this issue, choose one of the following solutions:
Add a primary key to the table with the following command:
Alternatively, set a replica identity using a unique index:
The unique index must be non-partial, non-deferrable, and use NOT NULL
columns.
REPLICA IDENTITY FULL is only supported with Delta-Apply columns on
primary key tables.
Unique Constraint Conflicts
If you encounter unique constraint violations during replication, ensure
only one UNIQUE index or constraint exists on downstream tables.
The error message for deferrable index constraints appears as follows:
To resolve this issue, convert deferrable constraints to non-deferrable:
Delta-Apply Column Errors
If you receive a delta apply column can’t operate NULL values error, ensure all Delta-Apply columns have NOT NULL constraints.
Then configure the Delta-Apply column with the following command:
Configuration Issues
This section covers problems related to PostgreSQL and Spock configuration parameters that can cause replication issues.
Missing Required Parameters
The following parameters are required in postgresql.conf for Spock to
function properly:
The three numeric values shown are a small-cluster starting point. If you are
troubleshooting worker registration failures, stuck subscriptions, or apply
workers that will not start, size them from your actual topology using
Sizing Postgres Resources for Spock - the defaults in the
tutorials do not account for parallel query workers sharing the
max_worker_processes pool, nor for the per-database managers, the
supervisor, and the slot sync worker that every node runs.
After modifying postgresql.conf, restart PostgreSQL with this command:
Decoding Fails on spock_output
Replication stops — either a new subscription never leaves the initializing state, or an established subscription stops applying after a minor-version upgrade — and the provider’s log records:
A 2026 PostgreSQL security fix (CVE-2026-6471, back-patched to every supported
major) added the output_plugin_libraries parameter, and a library may no
longer be used as an output plugin unless it is listed there. The default,
'pgoutput, test_decoding', excludes spock_output.
The check runs whenever logical decoding starts, not only when the slot is created, so this is not limited to new subscriptions: a cluster that has been replicating for months will stop the first time a walsender starts decoding after the upgrade. Add the library on every node a subscription may connect to — which, in a mesh, is all of them — keeping the core defaults:
Include physical standbys and Patroni replicas that hold synchronized failover
slots: a copied slot keeps spock_output as its plugin, so a standby missing
this setting serves replication only until it is promoted, and then fails.
The parameter is PGC_SUSET, so SELECT pg_reload_conf(); is enough — no
restart needed. The apply worker on the subscriber treats the failure as a
lost connection and reconnects by itself once the provider has been
reloaded; the subscription is not disabled.
Only set the parameter if your server has it; on a release predating the fix,
an unrecognised parameter in postgresql.conf stops the server from starting.
Check with:
A NULL result means the parameter does not exist and must not be set.
Conflict Resolution Issues
If conflicts are causing replication to stop, check the conflict resolution setting with this query:
The only supported value is:
last_update_wins- Keep the version with the newest commit timestamp.
To change the setting, use the following command:
The last_update_wins setting requires track_commit_timestamp = on.
Exception Handling Behavior
If replication is stopping due to errors, check the exception behavior setting with this query:
The following values are available:
transdiscard- Discard the entire transaction on ERROR.discard- Continue processing without the ERROR statement.sub_disable- Disable the subscription and queue transactions.
To change the setting, use the following command:
You can check the exception log table for details with this query:
Performance Issues
This section addresses performance-related problems that can affect replication speed and efficiency.
High Replication Lag
If replication lag is increasing, check the lag status with this query:
The query displays replication_lag_bytes and replication_lag for each
subscription. spock.lag_tracker shows the same figures per node pair. On
the provider, spock.slot_status shows how much WAL each subscriber still
has to fetch in pending_wal_bytes.
Possible causes and solutions include:
- Insufficient
max_worker_processes- increase the value; see Sizing Postgres Resources for Spock. Remember that parallel query workers draw from the same pool, so a parallel-heavy workload can starve apply workers even when the value looks generous, and that the supervisor, the per-database managers, and the slot sync worker each consume a slot before any apply worker starts. - Network bandwidth limitations - check network throughput.
- Large transactions - break into smaller transactions if possible.
- Slow subscriber hardware - upgrade hardware or reduce workload.
Node Failure and Recovery
This section explains how to recover from node failures and restore replication after a node becomes unavailable.
Catastrophic Node Failure
If a node fails catastrophically, use ACE (Active Consistency Engine) to recover missing data.
The recovery workflow involves five phases:
Assess damage by checking subscription status on surviving nodes.
Clean up Spock metadata by dropping subscriptions to the failed node:
Identify missing data using ACE table-diff with these flags:
Repair affected tables using ACE table-repair:
Validate by re-running table-diff without flags to confirm tables match.
Always use the --preserve-origin flag during recovery to maintain
replication metadata. Without this flag, repaired rows get wrong
origin IDs and timestamps, causing conflicts.
Subscription Down Status
If a subscription shows down status, check the following items:
Read the last error of the apply worker and the recent events of the subscription:
A
worker_statusofrestart pendingmeans the worker failed and the manager will retry afterworker_restart_delaymilliseconds.Verify the provider node is running and accessible.
Check replication slots on the provider with this query:
Review PostgreSQL logs on both provider and subscriber nodes if the views do not explain the failure.
Restart the subscription with these commands:
Upgrade Issues
This section provides guidance on verifying and troubleshooting Spock installations after upgrading to a new version.
Post-Upgrade Verification
After upgrading Spock, verify the installation with the following checks.
Check that the extension matches the installed library and that the upgrade was recorded:
Verify subscription status with this query:
Check replication slots on each provider with this query:
Monitor replication lag with this query:
DDL Replication After Upgrade
If DDL replication was disabled for the upgrade, re-enable it on all nodes with the following commands:
Special Feature Issues
This section covers troubleshooting for advanced Spock features including row filters, column filters, and partitioned tables.
Row Filter Errors
If row filters are causing replication to stop, check for volatile functions in the filter expression.
random() is VOLATILE and can return different values on successive calls. now() is STABLE within a transaction and can differ across transactions. Review when the filter is evaluated.
Replace volatile functions with stable or immutable alternatives, or remove them from the filter.
Column Filter Issues
If columns are missing after filtering, note the following behaviors:
- System columns (
oid,xmin) cannot be filtered. - Dropping a filtered column automatically removes it from the filter.
- New columns are not automatically included in existing filters.
Update the filter to include new columns with this command:
Partitioned Table Replication
If new partitions are not replicating, add them manually with the following command:
The parent table is synced during initial sync, but new partitions
created after sync must be added explicitly. Pass partition := NULL
(or omit it) to add every existing partition of the parent at once.
You can also pass an optional row_filter argument to restrict which
rows from the partition are replicated.
Checking Logs
Most replication errors are visible without the log: the last error of each
apply worker is in spock.subscription_status.last_error_message, and errors
raised in a spock worker are recorded as worker_error rows in
spock.events.
Not every one of them reaches that view. Connection failures and PANIC are left out, and an event is dropped rather than waited for when the ring is briefly locked. The log remains the place for the full context of an error, such as the statement and the detail lines, and the place to look when a worker failed and the views do not say why.
PostgreSQL logs provide detailed information about replication errors and issues.
Locate log files with this query:
On RHEL/Rocky Linux, logs are typically located at:
Monitor logs in real-time with this command:
Filter for Spock-related messages with this command:
Getting Help
If you cannot resolve your issue using this troubleshooting guide, gather the following information before requesting support:
- Spock version from
SELECT extversion FROM pg_extension WHERE extname = 'spock'; - PostgreSQL version from
SELECT version(); - Operating system and version
- Configuration settings from
postgresql.conf - Relevant error messages from PostgreSQL logs
- Subscription status from
SELECT * FROM spock.sub_show_status(); - Node status from
SELECT * FROM spock.node; - Replication lag from
SELECT * FROM spock.lag_tracker;
For more information, see the following resources:
- The Spock Functions Reference document provides detailed function documentation.
- The Configuring Spock document describes configuration parameters and settings.
- The Limitations and Restrictions document explains known limitations and constraints that may affect your replication setup.
- The FAQ document answers frequently asked questions.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.18 - Frequently Asked Questions
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Using a Column Filter
What happens if I set up a column filter on a table with OIDS? Can I filter on xmin?
Column filters work fine on tables with OIDs, but spock cannot filter on system columns like
oidorxmin.What happens if a column being filtered on is dropped?
Currently in spock replication, you can drop even a primary key on the provider. If a column being filtered on is dropped on the provider, it is removed from the column filter too. Use
spock.repset_show_table()to confirm this behavior.Columns on each subscriber remain as defined, which is correct and expected. In this state, the subscriber replicates INSERTs, but does not replicate UPDATEs and DELETEs.
If I add a column, does it automatically get included?
If you add a column to a table on the provider, it is not automatically added to the column filter.
Using a Row Filter
Can I create a
row_filteron a table with OIDS? Can I filter on xmin?Yes,
row_filterbehavior works fine for table with OIDs, but spock cannot filter on system columns (likexmin).What types of functions can we execute in a
row_filter? Can we use a volatile sampling function, for example?We can execute immutable, stable and volatile functions in a
row_filter. Exercise caution with regard to writes as any expression which will do writes can potentially throw an error and stop replication.Volatile sampling function in
row_filter: This would not work in practice as it would not get correct snapshot of the data in live system. Theoretically with static data, it works.Can we test a JSONB datatype that includes some form of attribute filtering?
Yes, a
row_filteron attributes of JSONB datatype works fine.
Using apply_delay with Time Changes
Does
apply_delayaccommodate time zone changes, for example Daylight Savings Time?Note: the physical replication parameter
recovery_min_apply_delaybehaves differently — if set during daylight savings time, you may get that interval plus the time change (e.g., 1h delay instead of 2h), which could require stopping and starting the database service twice per year.Spock’s
apply_delayis interval-based and accommodates time changes like Daylight Savings Time. The configured interval stays constant and is not affected by DST or other time zone shifts. However, we do not recommend running heavy workloads during a time change as spock replication needs some time (~5 minutes) to recover.
Node failure and recovery
What should I do if a node crashes and another node is left behind (for example, missing some transactions)?
If one node fails and a subscriber did not receive all of that node’s transactions before the failure, you can recover the lagging node using the Active Consistency Engine (ACE). ACE compares table data across the surviving nodes, identifies what is missing on the lagging node, and repairs it using a fully synchronized node as the source of truth. You can preserve original timestamps and origin IDs so that replication metadata stays correct. For a step-by-step procedure, see Recovering from Catastrophic Node Failure.
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.19 - Spock Release Notes
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock 6.0.0-beta.2
This section lists what changed since 6.0.0-beta.1, for those testing the beta. Most items are covered in full in the 6.0.0 notes below. This section will be removed at general availability.
Upgrading from beta 1
Beta 1 and beta 2 both install extension version
6.0.0, but the catalog differs between them, so a plainALTER EXTENSION spock UPDATEdoes nothing on a beta 1 node. Update a beta 1 node this way instead:Pause DDL on the cluster.
Install the beta 2 binaries and restart the node.
In every database where Spock is installed, run:
Repeat for each node, then resume DDL.
On each primary, check that every Spock slot has the
failoverflag:For any slot still showing
false, pause the subscriber that holds it and runSELECT spock.slot_enable_failover();on the primary.
The first command adds the objects beta 2 needs (the
spock.reserved_objectcatalog and its functions, the node metadata functions and the trigger onspock.node, and the monitoring views and functions with theirpg_monitorgrants), removesspock.wait_for_apply_worker(), reimplementsspock.get_apply_worker_status()overspock.get_worker_status(), marksspock.md5_aggparallel safe on a node upgraded from 5.x, and sets thefailoverflag on existing slots. The second only sets the version name back to6.0.0.The
failoverflag matters on PostgreSQL 17 and 18, where native slot sync copies only flagged slots to a standby. Beta 1’s upgrade from 5.x did not flag the slots that already existed, so a beta 1 node upgraded from 5.x may have slots that would be missing on the standby after a failover. Slots created by 6.0.0 already have the flag. The first command flags the rest, but skips any slot in use at that moment and prints a NOTICE naming it. On PostgreSQL 16 and older, or with Spock’s own slot sync worker on 17, the flag is not used and step 5 can be skipped.Until a database has been updated, AutoDDL, adding tables to a replication set and structure sync fail there with
catalog "spock.reserved_object" does not exist, and its apply workers fail when a peer changes its location, country or info, becausespock.node_info_apply()is missing. Running the commands on a node that already has beta 2’s catalog changes nothing. These two update steps will be removed at general availability.The upgrade from 5.0.x now starts at 5.0.14. A 5.0.11, 5.0.12 or 5.0.13 node still upgrades in one
ALTER EXTENSION spock UPDATE, through 5.0.14.On a server with PostgreSQL’s fix for CVE-2026-6471,
spock_outputmust be listed inoutput_plugin_libraries. See Upgrading below.On PostgreSQL 18,
spock.pg_standby_slot_namesdid nothing on beta 1, so a value set there, or one inherited by a promoted standby, had no effect. Beta 2 honours it: with the defaultspock.standby_slots_min_confirmedof-1a logical walsender waits for every named slot untilwal_sender_timeoutand then starts over, so replication stalls while a named slot is missing. Check the value on each PostgreSQL 18 node before installing beta 2, and either create the slots it names or clear the setting.
Node monitoring
The largest change since beta 1. See Node monitoring views in the 6.0.0
notes for what each view shows. SELECT on the views, and EXECUTE on the
functions they read, is granted to pg_monitor. USAGE on the spock
schema is not, so a monitoring role needs that granted as well.
GUC
spock.event_history_size(integer, default1024, range 16 to 1048576,POSTMASTER): how many recent events thespock.eventsview keeps in shared memory.
Views
spock.node_status: the whole node on one row: versions, pending upgrade, worker and subscription counts, WAL retained by slots, replication lag, last events.spock.peer_status: the known nodes.spock.subscription_status: configuration, status, serving worker, replication position and lag, and the last error of every subscription.spock.subscription_stats: per-subscription worker starts and failures, provider connects, messages, transactions, tuple and conflict counters.spock.worker_status: supervisor, manager, apply and sync workers, including workers waiting for a restart.spock.slot_status: provider side: spock slots with their walsender, positions, retained WAL and feedback lag.spock.table_sync_status: table synchronization state.spock.replication_set_status: the replication sets.spock.system_status: disk space, load, connections, long and idle transactions, wraparound age, archiving.spock.settings: the parameters replication depends on.spock.events: the history of recent events.
Functions
spock.node_report(recent integer DEFAULT 50) RETURNS SETOF text: the whole node as one text report for support cases: host and versions, installed extensions, settings, every monitoring view, and the most recent exceptions, conflict resolutions and events.spock.replication_origin_status(): the replication origins and their progress, readable bypg_monitor, sincepg_replication_origin_statusis for superusers only.- Internal functions behind the views and
node_report():spock.get_worker_status(),spock.get_events(),spock.reset_events(),spock.get_apply_stats(),spock.get_slot_groups(),spock.get_monitor_summary(),spock.get_system_info(),spock.get_pending_exceptions(),spock.redact_dsn(),spock.wal_size_bytes()andspock.report_section().get_system_info(),get_events(),get_apply_stats()andget_pending_exceptions()are executable bypg_monitoronly, andreset_events()by superusers only.
Changed
spock.get_apply_worker_status()is now a SQL function overspock.get_worker_status(), with the same columns and rows as before.spock.get_worker_status()and thespock.worker_statusview cover every worker type and give more detail.spock.reset_subscription_stats()also resets the new activity counters, on every supported PostgreSQL version, and EXECUTE on it is revoked from PUBLIC.
Other GUC changes
New
spock.sync_timeout(seconds, default0,USERSET): the time limit for a single wait in the node management routines.0keeps each routine’s built-in limit.spock.non_conflicting_inserts(boolean, defaultoff,POSTMASTER): asserts that a replicatedINSERTcan never collide with a local row, so the apply worker skips the conflict lookup and the speculative insertion.spock.failover_slots_naptime(milliseconds, default1000,SIGHUP) andspock.failover_slots_feedback_naptime(milliseconds, default10000,SIGHUP): how often Spock’s failover-slots worker syncs slots. It used to wait a fixed 60 seconds.spock.failover_slots_recreate_invalidated(boolean, defaulton,SIGHUP): whether the failover-slots worker drops and recreates a synchronized slot whose copy was invalidated on the standby. Off leaves the copy as it is and reports it once.spock.failover_slots_database(string, default empty,POSTMASTER): on PostgreSQL 16 and 17, the database the failover-slots worker connects to so it can decode each slot copy on the standby. Without it a copy has no snapshot of its own, and after a promotion transactions committed shortly before the failover can be skipped. On PostgreSQL 16 it must be the database the slots belong to.
Changed
spock.pause_timeout: the 300-second maximum is removed.spock.restart_delay_default,spock.restart_delay_on_exceptionandspock.output_delayare now declared in milliseconds, so they accept values with units such as'5s'.spock.restart_delay_defaultnow applies to every apply-worker restart, including after a lost connection or a temporary error.
Other SQL function and catalog changes
The monitoring views and functions are listed under Node monitoring above.
New
- Table
spock.reserved_object, listing the schemas and extensions Spock keeps out of the structure-sync dump, out of replication sets, or out of DDL replication. spock.reserved_object_add(p_name name, p_kind text, p_exclude_from_dump boolean DEFAULT true, p_block_in_repset boolean DEFAULT true, p_replicate_ddl boolean DEFAULT true).spock.reserved_object_remove(p_name name, p_kind text).spock.node_alter(p_location text, p_country text, p_info_patch jsonb), which changes the local node’s metadata and validates atiebreakervalue.spock.node_refresh_info(p_node_name name DEFAULT NULL), which fetches the metadata of one peer, or of every peer, again.spock.slot_enable_failover() RETURNS integer, called by the 5.x upgrade.- Internal functions
spock.node_info_emit(),spock.node_info_apply(),spock.node_info_broadcast()andspock.node_refresh_info_one(), and thenode_info_broadcast_triggertrigger onspock.node. EXECUTE on the first two and onnode_refresh_info_one()is revoked from PUBLIC.
Removed
spock.wait_for_apply_worker(p_subbid bigint, timeout int).
Changed
spock.repset_add_all_tables()now skips a table it cannot add, with a warning, instead of failing the whole call.
Other changes
- The failover-slots worker no longer stops synchronizing every slot while it waits for the primary’s copy of a new slot to catch up. The new copy stays a temporary slot until then and is dropped, not kept, if the standby is promoted first.
- The walsender hold-back on
spock.pg_standby_slot_nameswithspock.standby_slots_min_confirmedis installed on PostgreSQL 18 and later again. It had been dropped there together with the failover slot worker, but native slot sync only replaces the worker: PostgreSQL’ssynchronized_standby_slotswaits for every slot it names, so with two standbys one that is down stopped replication to every subscriber. - The failover-slots worker recreates a slot copy that was invalidated on
the standby, instead of advancing a copy that could never be used and
breaking the subscription only after a promotion. See
spock.failover_slots_recreate_invalidatedabove. - On PostgreSQL 16 and 17, with
spock.failover_slots_databaseset andwal_level = logicalon the standby, the failover-slots worker decodes each slot copy on the standby so it has a consistent snapshot. Without it, transactions committed shortly before a failover could be missed after the promotion. A copy that cannot be decoded is reported once with a WARNING. - On PostgreSQL 17, once the failover-slots worker has taken over from native slot sync, a copy made by native slot sync whose slot the primary drops no longer makes the worker fail and restart every minute.
- A change already being applied when
spock.sub_resync_table()empties the table is skipped, instead of failing and, withspock.exception_behaviour = sub_disable, disabling the subscription. The same holds for a partition whose partitioned table is being resynchronized. A table sync requested in the middle of a remote transaction now starts its sync worker. - Under
last_update_wins, an incomingUPDATEalways won against a local row thatVACUUMhad frozen, even when the local change was newer, so nodes could end up with different values. The commit timestamp of a frozen row is now found. - A procedure that runs
COMMITorROLLBACK, called over the extended query protocol with a bound parameter, could crash the server.spock.wait_for_sync_event()does this, so a client such as psycopg or JDBC waiting for a sync event could crash a node. - With
spock.apply_change_loggingon, a table whose columns are laid out differently on the provider and the subscriber was logged with values under the wrong columns, and could crash the apply worker on every restart. - Two table syncs finishing at the same time could both write
resource.dat, ending the apply worker and leaving its subscription disabled after the restart. - On PostgreSQL 19, AutoDDL runs
REPACK (ANALYZE)andREPACK (CONCURRENTLY)locally and does not replicate them, since neither can run inside the apply worker’s transaction. spock.sub_wait_for_sync()andspock.table_wait_for_sync()raise an error instead of waiting forever when a subscription has no sync status row, and the apply worker rejects a Spock message too short to hold its type.- Direct DDL against the
spockandsnowflakeschemas is refused while DDL replication is on. - Large objects stored by lolor can be replicated, and Zodan
add_nodecopies them to the new node. - Zodan
add_nodecan add a 6.0.0 node to a cluster of 5.0.9 or later nodes, and copies the source node’s replication sets to the new node. forward_originscannot be active on a subscription while another subscription on the node is enabled.- The apply worker restarts and tries again after a temporary error, such as a deadlock or lock timeout, instead of treating it as a data exception.
pg_upgradeof a Spock node on PostgreSQL 17 and later no longer fails withresource manager with ID 144 not registered.- A node’s location, country and info, including its
tiebreaker, are sent to its direct subscribers when they change.spock.sub_resync_table()warns when the provider’s row differs from the local copy. - A replicated
INSERTthat collides with a row committed locally at the same moment goes to conflict resolution instead of failing with a duplicate key error. EachINSERTinto a table with a unique index now takes a speculative insertion; seespock.non_conflicting_insertsabove. - With three or more nodes, a conflict between two changes with the same
commit timestamp is decided by the existing row’s real origin, so nodes
that agree on every node’s
tiebreakerpick the same winner. When the row’s origin is unknown, the applying node is used, as before. A row copied by the initial table sync records a local origin ID, which can still be taken for a different node. TheCONFLICT: ... wins over ... by tiebreakerlog messages now name the existing row’s origin and the incoming change’s origin instead of the current and remote node. - Table sync no longer fails with
SET TRANSACTION SNAPSHOT must be called before any querywhen an extension such as pg_duckdb runs a query onSET. - Documentation on running logical slot failover under Patroni, with the
sample
samples/set_synchronized_standby_slots.sh. - Bug fixes from 5.0.11 to 5.0.14. From 5.0.13: a promoted
physical standby of a subscriber no longer asks the provider to resend
transactions the subscriber had already applied, which showed up as
conflicts or as duplicate rows in tables without a primary key;
spock.sub_wait_for_sync()andspock.table_wait_for_sync()no longer crash the server when the subscription is dropped while they wait; a pg_dump or pg_restore failure during structure sync reports how the child exited instead of an unrelated error such asInvalid argument; and table sync no longer fails against an origin older than 5.0.7, which lacksspock.pause_apply_workers(). From 5.0.14, besides the failover-slots, frozen-row andCALLfixes listed above: a slot named inspock.pg_standby_slot_namesthat does not exist is reported even when the other slots meetspock.standby_slots_min_confirmed, a slot named twice is counted once, AutoDDL no longer replicatesCLUSTERwithout a table orCLUSTERon a partitioned table, and an apply worker no longer reports the exception log full while it has free entries, or leaves a Spock lock held when it really is full. - An error from the provider’s startup message, or a malformed
BEGIN, no longer makes the apply worker write outside its exception log entry in shared memory. The worker restarts afterspock.restart_delay_defaultinstead. - AutoDDL failed
CREATE SCHEMA ... CREATE TABLE ...withrelation "..." does not exist, which aborted the statement. This happened on PostgreSQL 19 RC2, and on earlier versions when the statement ran from a function or over the extended query protocol. - Builds against PostgreSQL 19 beta 3, beta 4, RC1 and RC2, and against
PostgreSQL 15.20, 16.16, 17.11, 17.12 and 18.7. The
attoptionsserver patches were refreshed for changes in these releases; only context lines changed.
Spock 6.0.0
The on-disk catalog format and the GUC surface both change in this release;
see Upgrading below before running ALTER EXTENSION spock UPDATE.
Highlights
- Catastrophic node failure recovery — new ACE-based workflow with origin-preserving repair prevents silent data divergence after node loss.
- Progress tracking moved to WAL + shared memory — eliminates
heavyweight catalog writes in the apply hot path;
spock.progressis now a view backed byspock.apply_group_progress(). - More granular conflict classification — seven conflict types (up from four), with origin-aware suppression and DELETE conflicts now resolved through timestamp-based resolution.
- Automatic node metadata propagation — a node’s
location,country, andinfo(including its conflict-resolutiontiebreaker) now propagate automatically to every direct subscriber on change, via the newspock.node_alter()function or a plainUPDATE; no more silently disagreeing tiebreakers from a forgottenspock.node_refresh_info(). - Per-subscription conflict statistics on PostgreSQL 18+ via a custom pgstat kind.
- Node monitoring views:
spock.node_status,spock.subscription_status,spock.subscription_stats,spock.worker_status,spock.slot_statusandspock.eventsgive the complete picture of a node without reading the server log. - Liveness and feedback refactor — TCP keepalive replaces the fragile
wal_sender_timeoutworkaround; newspock.apply_idle_timeoutGUC. - Logical slot failover uses native PostgreSQL slotsync on PG17+ / PG18+.
- Rolling upgrade support — protocol negotiation (v4 for 5.0.x, v5 for 6.0+) enables zero-downtime rolling upgrades.
- Exception handling refactor — stable behaviour under TRANSDISCARD /
SUB_DISABLE; original error messages preserved in
spock.exception_log. - Replay queue spills to disk instead of refetching from the publisher.
- Reserved schemas and extensions are configurable — a new
spock.reserved_objectcatalog controls which schemas and extensions are left out of structure sync, replication sets and DDL replication. - Mixed-version node addition — Zodan
add_nodecan add a 6.0.0 node to a cluster of 5.0.9 or later nodes. - Large object replication — tables of the lolor extension can join a
replication set, and Zodan
add_nodecopies large objects to the new node. - PostgreSQL 19 support — compatibility work across core patches and
version-specific API changes (replication-origin session state folded into
replorigin_xact_state,CLUSTERfolded intoREPACK, thepgstatand recovery-conflict signalling changes, and theRepOriginIdrename). Spock builds against PostgreSQL 19 beta 3, beta 4 and RC1. This support is preliminary: PostgreSQL 19 has not been released, and Spock on 19 is not supported for production use.
Catastrophic node failure recovery
Spock 6.0 documents and supports a structured recovery workflow for the scenario where a node fails permanently and one or more surviving nodes are lagging behind. Using the Active Consistency Engine (ACE), operators can:
- Identify which rows are missing on lagging survivors using
table-diff --preserve-origin. - Repair the lagging node from a fully-synchronized survivor using
table-repair --recovery-mode --source-of-truth --preserve-origin.
The --preserve-origin flag is important: it ensures that repaired rows
retain their original origin ID and commit timestamp, so replication
metadata stays correct and the cluster remains conflict-free. Without it,
repaired rows would appear as local changes and could trigger false
conflicts.
Both single-node and multi-node failure scenarios are covered. See Catastrophic Node Failure Recovery for the full guide.
Replication progress tracking
Replication progress is no longer tracked in the spock.progress catalog
table. Spock now tracks it live in shared memory and persists a snapshot
to $PGDATA/spock/resource.dat. On apply-worker startup, Spock
reconciles the snapshot against the durable replication-origin LSN: if
resource.dat is stale, remote_commit_lsn is advanced from the origin
and stale timestamp fields are cleared (to be refreshed by subsequent
apply).
A custom resource manager (id 144) emits one WAL record per
SpockGroupHash entry at each resource.dat dump event, visible via
pg_waldump for debugging, not used for state recovery.
The catalog surface has been restructured accordingly:
spock.progressis now a view over the newspock.apply_group_progress()set-returning function, filtered to the current database. Code that read the previous table of the same name continues to work, but writes are no longer possible. Useapply_group_progress()directly (or the view) for live data, and use the newspock.read_peer_progress(slot, provider_node_id, subscriber_node_id)function during slot snapshot import.spock.lag_trackerview redefined. The oldlast_received_lsncolumn has been renamed tocommit_lsnto reflect what it actually is, and a newreceived_lsncolumn reports the last LSN sent by the publisher (matching thepgoutputprotocol convention).remote_insert_lsnis now updated on every incoming WAL record rather than only on COMMIT, so lag readings are more responsive.
Exception handling improvements
- Fixed TRANSDISCARD / SUB_DISABLE handling during the commit phase in retry mode, preventing apply-worker death loops.
- Eliminated “(unknown action)” in error-context strings and NULL error
messages in
exception_log. The originally-failing row now carries the real error message; bystander rows in the same transaction refer to the entry containing the root cause message. - Added
initial_operationfield to track which DML operation caused a transaction discard. - Subscriptions stuck in an unrecoverable synchronization stage are now disabled rather than restarted indefinitely.
Exception replay: spill to disk
spock.exception_replay_queue_size has changed semantics.
- Before: a single byte threshold (default 4 MiB ≈ 4194304). When the in-memory queue exceeded the threshold, Spock could not replay the transaction and would refetch it from the publisher.
- Now: a soft cap (default
4MB, unitMB). When the queue exceeds the cap, subsequent entries spill to a temporary file on disk. Set to0to disable spilling and allow unbounded memory use (improves throughput for very large transactions; allocation failure falls back tospock.exception_behaviour).
spock.exception_behaviour continues to control the action on
unrecoverable errors:
| Value | Action |
|---|---|
discard | Skip the failed transaction and continue replication. |
transdiscard | Roll back the failed transaction and continue. |
sub_disable | Disable the subscription and exit cleanly. |
Logical Slot Failover
- On PostgreSQL 17+, Spock creates all logical replication slots with
the
FAILOVERflag, allowing PostgreSQL’s built-in slotsync worker (sync_replication_slots = on) to automatically synchronize them to physical standbys. - On PostgreSQL 18+, Spock’s own
spock_failover_slotsbackground worker is no longer registered. The native PostgreSQL slotsync worker fully replaces it. See the Logical Slot Failover section of the configuration guide for requiredpostgresql.confsettings. - On PostgreSQL 17, Spock’s worker remains active but automatically
yields to the native slotsync worker if
sync_replication_slots = onis set, preventing conflicts. - Where Spock’s own worker runs (PostgreSQL 15 to 17):
- It syncs slots every
spock.failover_slots_naptime(1 second by default) instead of every 60 seconds. - It recreates a slot copy that was invalidated on the standby, instead
of advancing a copy that could never be used.
spock.failover_slots_recreate_invalidated = offleaves such a copy in place for inspection and reports it once. - It no longer stops syncing every slot while the primary’s slot catches up with a new copy. The new copy stays a temporary slot until then and is dropped, not kept, if the standby is promoted first.
- On PostgreSQL 16 and 17, with
spock.failover_slots_databaseset andwal_level = logicalon the standby, it decodes each copy on the standby so the copy has a consistent snapshot, as PostgreSQL 17’s own slot sync does. Without it, transactions committed shortly before a failover could be missed after the promotion. A copy that cannot be decoded is reported once with a WARNING. The worker stays connected to that database, so commands such asDROP DATABASEon it fail.
- It syncs slots every
More granular conflict classification
v5.0 classified conflicts into four types. v6.0 expands this to seven, adopting PostgreSQL-native conflict-type naming:
| v5.0 type | v6.0 type(s) | What changed |
|---|---|---|
insert_exists | insert_exists | No change. |
update_update | update_exists / update_origin_differs | Spock now distinguishes between an update whose local origin matches the incoming origin (suppressed silently) and one whose local origin differs (evaluated through resolution). update_exists is used for update constraint violations. |
update_delete | update_missing | Renamed for clarity. |
delete_delete | delete_missing / delete_origin_differs | Spock now logs whether the missing row was last modified by a different origin. |
| (new) | delete_exists | A remote DELETE arrives, but the local row has been updated more recently than the delete’s timestamp. The newer local version is preserved. |
Existing spock.resolutions data is migrated automatically during
ALTER EXTENSION spock UPDATE (see Catalog changes below).
DELETE operations now use conflict resolution
In v5.0, when a DELETE found a matching local row, it was applied
immediately without consulting conflict resolution. In v6.0, DELETE
operations go through timestamp-based resolution, just like updates. This
enables the new delete_exists classification — Spock can determine
whether a delete should be applied or whether a newer local version should
be preserved.
Automatic node metadata propagation
A node’s location, country, and info (including a tiebreaker key
used to break same-timestamp conflicts – see Tiebreaker in
conflict_types.md) previously had to be manually
re-fetched onto every other node with spock.node_refresh_info() after
any change; a node left unrefreshed would silently keep disagreeing with
the rest of the cluster about that peer’s tiebreaker.
v6.0 propagates such a change automatically to every node that
subscribes to it directly, via a new AFTER UPDATE trigger on
spock.node and a custom logical-replication message – deliberately
direct-subscribers-only, not forwarded through a cascade topology, so it
introduces no message-ordering dependency on the existing replication
stream. The new spock.node_alter() function is the recommended way to
make the change: it validates a tiebreaker value (must be a whole JSON
number that fits a 32-bit integer) and merges an info patch rather than
replacing it wholesale; a raw UPDATE spock.node on the node’s own row
continues to work and propagates the same way. spock.node_refresh_info()
updates a node whose cached row missed a change, for example because the
transaction carrying it was skipped or discarded, and spock.sub_resync_table()
warns when the provider’s row differs from the cached one. See
Automatic Node Metadata Propagation
and spock.node_alter for
details.
Cascade replication origin tracking
v6.0 adds support for tracking and forwarding replication origins in cascade topologies (Node A → Node B → Node C). The origin name is now included in ORIGIN messages when the protocol version is 5 or higher. This ensures that conflict evaluation on Node C has accurate origin information even when changes pass through intermediate Node B.
If Node C also has a disabled subscription directly to Node A, Spock now advances that subscription’s replication origin as forwarded changes from Node A arrive through Node B. When the direct subscription is later enabled, it starts from where the forwarded changes left off, so rows already received through Node B are not sent again.
A subscription cannot activate forward_origins while another subscription
is already enabled on the same node, and a subscription cannot be enabled
while another has forwarding active; clear forward_origins
(spock.sub_alter_options) or disable the other subscription first. See
Origin Forwarding for
details.
Per-subscription conflict statistics
On PostgreSQL 18+, Spock registers a custom pgstat kind
(SPOCK_PGSTAT_KIND_LRCONFLICTS) to count replication conflicts per
subscription. New SQL functions spock.get_subscription_stats(subid)
and spock.reset_subscription_stats(subid) read and reset them. On
PostgreSQL versions before 18, get_subscription_stats() raises a
feature-not-supported error; reset_subscription_stats() works on every
version, since it also resets the activity counters behind
spock.subscription_stats.
Node monitoring views
Spock now keeps a history of recent events and per-subscription activity
counters in shared memory, and exposes them together with worker, slot and
replication state through a set of views in the spock schema:
spock.node_status: the whole node on one row: library and extension version, pending upgrade, worker and subscription counts, WAL retained by slots, replication lag, last events.spock.subscription_status: configuration, status, serving worker, replication position and lag, and the last error of every subscription.spock.subscription_stats: apply and sync worker starts and failures, provider connects, messages, transactions, tuple and conflict counters.spock.worker_status: supervisor, manager, apply and sync workers, including workers waiting for a restart.spock.slot_status: provider side: spock slots with their walsender, positions, retained WAL and feedback lag.spock.events: subscription enable and disable, worker start, stop and failure, provider connects and disconnects, skipped and discarded transactions, table synchronization, extension upgrades.spock.peer_status,spock.replication_set_statusandspock.settingsfor the known nodes, the replication sets and the parameters replication depends on.spock.system_statusfor the health of the host and the instance: disk space of the data and WAL volumes, load, connections, long and idle transactions, wraparound age, archiving.spock.node_report()returns the whole node as one text report: host and versions, installed extensions, settings and every view in turn.- Errors are kept with SQLSTATE, DETAIL, CONTEXT, time and pid, classified
into deadlocks, lock timeouts, constraint violations and resource errors,
and errors of the walsender running the output plugin are recorded as
stream_errorevents. Workers waiting for a lock show the blocking session.
The event history size is set by the new spock.event_history_size GUC.
spock.reset_subscription_stats() now resets both the activity and the
conflict counters. spock.get_apply_worker_status() is kept, now as a SQL
function over the new spock.get_worker_status(), which with the
spock.worker_status view covers every worker type. The GUC, views and
functions are listed under Node monitoring GUCs, views and functions
below.
Liveness and feedback refactoring
The wal_sender_timeout-based liveness mechanism has been replaced with a
cleaner two-layer model:
- TCP keepalive as the primary liveness detector (detects dead network or host in ~25 seconds).
wal_sender_timeout=0on replication connections so the walsender never disconnects due to missing feedback.spock.apply_idle_timeout(default 300s) as a subscriber-side safety net for hung-but-connected walsenders.
This replaces the maybe_send_feedback() workaround that coupled
subscriber behaviour to a server GUC it cannot control.
Read-only mode refactoring
Read-only mode has been refactored to use PostgreSQL’s native
DefaultXactReadOnly mechanism instead of manual command-type filtering:
READONLY_USERrenamed toREADONLY_LOCAL(the old name is retained as a backward-compatible alias) to clarify that it restricts local (non-replication) connections.- In
READONLY_ALLmode, the apply worker sends keepalive feedback but skips applying new transactions. - Read-only mode changes are detected before applying the next
transaction (
CHECK_FOR_INTERRUPTSmoved to top of the replay loop).
Rolling upgrade via protocol negotiation
Spock now negotiates an output-plugin protocol version between publisher and subscriber (Protocol 4 for v5.0.x, Protocol 5 for v6.0+). This enables zero-downtime rolling upgrades: a v6.0 subscriber can apply from a v5 publisher and vice versa, with protocol-5-only features (such as cascade origin forwarding) activated only when both sides support them.
An incompatible upstream is now rejected early: create_subscription()
runs the version check at DDL time when synchronize_structure is
requested, and a structure sync from a newer-major upstream is refused
(pg_dump cannot read a newer server) instead of failing opaquely after a
slot and snapshot were created.
Zodan: data-loss fix when adding a node under write load
When adding a node while existing nodes were handling writes, the new node could permanently miss rows or accumulate stale updates. The root cause was that apply workers were not paused during slot creation (sub-second operation), so the captured resume LSN could fall before the COPY boundary. The fix pauses apply workers during slot creation and captures the resume LSN deterministically.
Additional Zodan fixes in 6.0:
- Slots and subscriptions are now named consistently as
sub_{provider}_{subscriber}via the newspock.gen_sub_name()helper. remove_nodedrops subscriptions from thespock.subscriptioncatalog instead of guessing names.- Phase 3 catch-up wait aligned and
spock.sync_event()parameterised to avoid the Phase 9 handshake deadlock. - Mixed versions —
add_nodecan add a 6.0.0 node to a cluster whose nodes run 5.0.9 or later, instead of requiring every node to be upgraded first. Existing nodes may already be mixed. The new node must run the same or a newer version than every existing node. - Replication sets are copied — the new node gets the source node’s replication sets, including user-created sets, column lists, row filters, and tables removed from a set. Before, the subscriptions named only the three built-in sets, so tables in a user-created set were neither sent nor received.
- Large objects — the new node may have lolor installed as long as its tables are empty, and must have it when the source replicates lolor tables. The initial data sync copies the large objects.
- Longer waits — the new
spock.sync_timeoutGUC raises the time limit on each wait in the node management routines, which was fixed at about three minutes and too short for large databases.spock.pause_timeoutno longer has a 300-second maximum. - The old Python versions,
zodan.pyandzodremove.py, are removed. Use the SQL procedures.
AutoDDL improvements
AutoDDL has been refactored and hardened:
Centralized in
spock_autoddl.c— all AutoDDL plumbing moved into a single module for maintainability.Simplified control flow — dropped the recursive tag-matching heuristic in favour of clearer early-exit filters.
Extension script guard — internal subcommands during
CREATE EXTENSION/ALTER EXTENSION UPDATEare no longer replicated.Transaction guards — AutoDDL hook no longer fails when utility commands (e.g.,
CLUSTERwithout a table name) execute outside a transaction context.Filtered non-transactional DDL — commands that cannot execute inside transaction blocks on subscribers (e.g.,
CLUSTERon partitioned tables,VACUUM) are filtered on the publisher side before being queued.Temporary-relation DDL not replicated —
CREATE TABLE … (LIKE temp)andCREATE TABLE … AS SELECT … FROM tempare skipped, since the temporary relation does not exist on the subscriber.Replication-set stickiness on
ALTER TABLE— withspock.include_ddl_repsetenabled,ALTER TABLEno longer evicts a table from a user-defined replication set unless it adds or drops a primary key / replica identity. InlineADD COLUMN … PRIMARY KEYandREPLICA IDENTITY FULLtables are now classified correctly.Safe
search_pathinterpolation — replicated DDL ships a validSET search_patheven when the session path is empty.Direct DDL against
spockandsnowflakeis refused (behaviour change) — whilespock.enable_ddl_replicationis on, a statement whose target schema is one of the built-in extension-owned schemas now fails outright:These schemas are populated by extension scripts, where AutoDDL is already suppressed, so a runtime statement against them is almost always a mistake. Previously such a statement half-applied: the command text replicated to peers while the relation was silently kept out of every replication set. See Upgrading for what this affects.
An extension’s own DDL during
DROP EXTENSIONstays node-local — withspock.allow_ddl_from_functionson, DDL an extension ran while being dropped was queued for replication, even though every peer runs the same cleanup when it applies theDROP EXTENSION. For lolor this left peers unable to drop the extension and stalled apply. TheDROP EXTENSIONitself still replicates, except for a node-local extension (below).CREATE,ALTERandDROP EXTENSION lolorare no longer replicated. lolor refuses to be created or dropped by an apply worker, so every peer logged the replicated statement inspock.exception_logand discarded it, while the node that ran it reported it as replicated. Thelolorextension row inspock.reserved_objecthasreplicate_ddl = false, and AutoDDL runs these statements only where they are issued, with a WARNING saying so. Run them on each node.COMMENT ON EXTENSION lolorandSECURITY LABEL ON EXTENSION lolorstay local too. ADROP EXTENSIONnaming lolor together with another extension is refused while DDL replication is on, and so isCREATE EXTENSION ... CASCADEof an extension that requires lolor.spock.replicate_ddl()refuses these statements for lolor.
Reserved schemas and extensions
Spock keeps some schemas and extensions out of the structure-sync dump and
out of replication sets. That list used to be fixed in the code. It is now
the spock.reserved_object catalog, with three settings per row:
exclude_from_dump: left out of the structure-sync dump.block_in_repset: its tables may not be added to a replication set.replicate_ddl: whenfalse,CREATE,ALTERandDROP EXTENSIONfor the extension run only on the node where they are issued. For a schema, the same holds for the DDL statements AutoDDL can trace to the schema; others, such asGRANT, still replicate. See the list in Replication Set Management. The default istrue.
The built-in rows cannot be changed or removed:
| Object | exclude_from_dump | block_in_repset | replicate_ddl |
|---|---|---|---|
spock | yes | yes | yes |
snowflake | yes | yes | yes |
lolor | yes | no | schema yes, extension no |
coldfront | yes | no | yes |
pgedge_ace | yes | yes | no |
Add your own with spock.reserved_object_add() and remove them with
spock.reserved_object_remove(). Your rows are kept across dump and
restore. See
Reserved Schemas and Extensions
for details.
Exclusion from the dump now applies whether or not the object exists on the subscriber. Before, an object present only on the provider was never excluded.
repset_add_all_tables() skips tables it cannot add
spock.repset_add_all_tables() used to fail, and add nothing, when any one
table had no replica identity index. It now adds the tables it can and
prints a warning naming each table it skipped. Tables in a reserved schema
or owned by a reserved extension are skipped the same way. Naming a
reserved schema in the call is still an error, and
spock.repset_add_table() still fails for a table it cannot add.
The message now says “replica identity index” instead of blaming a missing
primary key, since a table with a primary key and REPLICA IDENTITY FULL
or NOTHING is also rejected.
Memory and stability
- Replay queue spills to disk (see Exception replay above) instead of triggering a worker restart, eliminating the unpredictable restarts and replication lag spikes seen with large transactions.
- Resource leak fixes:
- Row filter processing no longer leaks resource-owner entries when many rows are filtered out.
remotetupleis now freed after use in the conflict reporting path.
- Shared memory initialization centralized in
spock_shmem.cwith proper handling of startup, checkpointer, and background-worker processes.
Bug fixes specific to 6.0
- WAL recovery crash after apply-worker failure — when an apply worker crashed and triggered a server restart, WAL recovery could fail due to improperly initialized shared memory structures. Shared memory init has been refactored to handle startup, checkpointer, and background-worker processes correctly.
remote_insert_lsnlost after crash recovery — the value was not included in WAL records and defaulted to 0 after crash recovery, breaking lag tracking inspock.lag_tracker.- Generated columns — tables containing
GENERATED ALWAYS AS … STOREDcolumns caused replication errors because generated columns were treated as regular columns during COPY, protocol messages, default-value filling, and conflict resolution. Now properly excluded. - Replica index lookup with
REPLICA IDENTITY FULL— cached index information was not invalidated before callingRelationGetReplicaIndex(), causing incorrect index usage when switching between replica identity modes. - Hash table iteration safety — fixed removal-during-iteration
corruption, missing NULL checks for
HASH_FIXED_SIZEtables, and torn reads of 64-bit counters without spinlock protection. - Skip LSN mechanism — a successfully skipped transaction in
SUB_DISABLEmode would incorrectly disable the subscription again due to LSN mismatch between the skip point (BEGIN LSN) and the clear point (COMMIT LSN). Exception-handling state is now cleared after a successful skip. - Table sync failure detection — COPY failures during table sync were
silently swallowed and the sync worker retried indefinitely.
PQgetResult()is now called afterPQputCopyEnd()to detect failures, and a newSYNC_STATUS_FAILEDstate stops retry loops and surfaces clear error messages. - Un-appliable TRUNCATE loop — in
discardmode a TRUNCATE that failed on the subscriber (e.g. the relation does not exist) crash-looped the apply worker. It is now wrapped in a subtransaction, logged, and discarded like other DML. pg_upgradefailed on PostgreSQL 17 and later —pg_upgradedecodes each logical slot’s remaining WAL to check it is drained, and Spock’s resource manager was not registered in the serverspg_upgradestarts. The check failed withresource manager with ID 144 not registered.- Apply idle timeout treated as a data exception — when
spock.apply_idle_timeoutfired in the middle of a transaction, the error went down the data-exception path, so the subscription could be disabled or a good transaction discarded. It is now handled like a lost connection. - Clock skew in progress tracking — an origin commit timestamp ahead of
the subscriber’s clock, or forwarded transactions whose timestamps do not
rise with the provider’s WAL position, tripped an assertion in
assert-enabled builds.
remote_commit_lsnnow advances independently of the timestamp fields. - Replay entries restored from the spill file were not terminated — a truncated or malformed record read back from disk could be scanned past the end of its buffer instead of being rejected.
- Peer sessions use a fixed time format — Spock reads commit timestamps
from other nodes as text, and their meaning depended on each side’s
DateStyleandTimeZone. Where the two differed, the same text could mean a different moment, which matters when a timestamp picks the LSN to advance a slot to duringadd_node. Peer connections now requestdatestyle=ISO, and a peer timestamp without an explicit UTC offset is rejected. - Initial sync with a row filter on a table with a dropped column — rows were read at the wrong offsets after a dropped column, giving corrupt rows or a crash.
- Sync worker lost the original error — a failure while creating the
slot during table sync was reported as
errstart was not calledinstead of the real error. - Replicated
INSERTracing a local insert — the apply worker looked for a conflicting row and, finding none, inserted. A row committed locally in between was missed, and the insert failed with a duplicate key error instead of going to conflict resolution. The row is now inserted speculatively with every immediate unique index as an arbiter, and a reported duplicate is looked up and resolved. This adds a speculative insertion to eachINSERTinto a table with a unique index;spock.non_conflicting_insertsturns it off where collisions cannot happen. A collision on a unique index other than the one used to find the row still raises a duplicate key error unlessspock.check_all_uc_indexesis on. - Equal-timestamp ties in a mesh of three or more nodes — the tiebreaker compared the applying node with the origin of the incoming change. When a node resolved a conflict between writes from two other nodes, it could pick a different winner than they did. The tie is now decided between the existing row’s recorded origin and the incoming change’s origin, falling back to the applying node when the row’s origin is unknown.
- Table sync with pg_duckdb — the session
SETs were sent inside the COPY transaction, so an extension that runs a query onSETmade the snapshot import fail withSET TRANSACTION SNAPSHOT must be called before any query. They are now sent before the transaction starts. - Change in flight during a resync —
spock.sub_resync_table()marks the table as being synchronized and empties it, but the apply worker reread its list of tables under synchronization only between remote transactions. A change already being applied met the emptied table, and anUPDATEthat found no row disabled the subscription undersub_disable. Such changes are now skipped, including changes to a partition whose partitioned table is being resynchronized; the sync worker’s copy contains them. A table sync requested in the middle of a remote transaction also failed to start its sync worker. last_update_winsagainst a frozen row — the commit timestamp of a local row was looked up through its xmin, which reads as frozen onceVACUUMfreezes the row, and the row then counted as older than any change. An older incomingUPDATEoverwrote the newer local value, so nodes could diverge. This affects every supported PostgreSQL version:VACUUM (FREEZE)and aggressive vacuums freeze recently written rows, and since PostgreSQL 16 a normalVACUUMcan too. The original xid is now used.- Crash after a procedure that ends its transaction — after a
CALLthat runsCOMMITorROLLBACKover the extended query protocol with a bound parameter, AutoDDL read the statement from freed memory and the server crashed.spock.wait_for_sync_event()runsROLLBACK, so a psycopg or JDBC client waiting for a sync event could crash a node. spock.apply_change_loggingwith different column layouts — values were read at the provider’s column positions, so they were logged under the wrong columns when the provider and the subscriber order or drop columns differently, and a value of one type printed as another could crash the apply worker on every restart.- Concurrent
resource.datwrites — two table syncs finishing at the same time wrote the same temporary file, and the second rename failed, ending the apply worker and leaving its subscription disabled after the restart. REPACKon PostgreSQL 19 — AutoDDL queuedREPACK (ANALYZE)andREPACK (CONCURRENTLY), which cannot run inside the apply worker’s transaction. They now run locally only, as table-less and partitionedCLUSTERalready did.- Failover-slots worker — on PostgreSQL 15 to 17 it advanced a slot copy that had been invalidated on the standby, so the copy looked current but the subscription broke after promotion; it waited for a lagging primary slot without a time limit, syncing no other slot meanwhile, and if promotion came during the wait it kept a copy that skipped commits; on PostgreSQL 16 and 17 a copy had no snapshot of its own, so transactions committed shortly before a failover could be missed; and on PostgreSQL 17 a copy made by native slot sync whose slot the primary dropped made the worker restart every minute. See Logical Slot Failover above.
spock.sub_wait_for_sync()andspock.table_wait_for_sync()waited forever for a subscription that had no sync status row. They now raise an error.
Security
- DSN password obfuscation — passwords in DSN connection strings are no longer visible in error messages or log output. A message-filter hook wipes password characters from error messages before they are written.
Other notable changes
- Protocol cleanup — removed unused SPI API support from the Spock protocol; fixed multiple protocol parameter validation issues.
- Prevented adding tables from ignored schemas to replication sets.
- Snowflake removal — removed snowflake-related functions and documentation since it is now in its own repository.
- SpockCtrl removal — removed the SpockCtrl utility code.
- Windows support removal — dropped Win32-specific code paths; Spock targets POSIX-only environments.
--exclude-extension— extended use of the pg_dump option (PostgreSQL 17+).- PostgreSQL 18 support — compatibility work across core patches, initdb, row filters, and compiler warnings.
- Source tree restructured under
src/andinclude/directories. - Packaging — the repository now builds the
spock60RPM and DEB packages itself. Debian bullseye, which has reached end of life, is no longer built. - Documentation — a new guide on sizing PostgreSQL resources for Spock
by node and database count (see Sizing), a
SECURITY.mdexplaining how to report vulnerabilities, and theoutput_plugin_librariesrequirement in the README and the configuration, installation and troubleshooting guides. The guide to running logical slot failover under Patroni, with the samplesamples/set_synchronized_standby_slots.sh, is carried over from 5.0.12 (see Logical Slot Failover).
GUC changes
New
spock.apply_idle_timeout(int seconds, default300,SIGHUP) — safety net for detecting a hung walsender that keeps the TCP connection alive but stops sending data. The timer resets on any received message. Set to0to disable and rely solely on TCP keepalive for liveness detection.spock.output_delay(int milliseconds, default0, range 0–60000,SIGHUP) — artificial delay in the publisher-side output plugin. Used to reproduce conflict and lag scenarios in tests.spock.resolutions_retention_days(int days, default100,SIGHUP) — TTL for rows inspock.resolutions. Rows older than this are deleted periodically by the apply worker. Set to0to disable automatic cleanup. Complementsspock.cleanup_resolutions(days)and the new index onresolutions(log_time).spock.enable_quiet_mode(bool, defaultoff,SIGHUP) — when enabled, downgrades DDL replication INFO/WARNING messages to LOG level and suppresses dependent-object reporting inDROP CASCADEoperations. Intended for regression tests and production environments where less verbose output is desired.spock.log_verbosity(enumnormal/debug1/debug2, defaultnormal,SUSET) — promotes Spock’s ownDEBUG1/DEBUG2messages toLOGso they survive a normallog_min_messages.spock.apply_change_logging(enumnone/key_only/verbose, defaultnone,SUSET) — emits per-change JSON from the apply worker (action, table, key, origin, commit timestamp; plus row data inverbose).spock.read_retry_countallows for configuring the number of retries when an expected row is not found. The default matches the previously hard-coded value of 5 (there is 1ms of sleep between each retry). Setting it to 0 disables retries. This helps when a node has a large lag and we do not want to slow down processing.spock.sync_timeout(int seconds, default0,USERSET) — the time limit for one wait in the node management routines: for a sync event to arrive, for a peer to catch up, or for a subscription to start replicating. Raise it on large databases, where catching up takes longer than the built-in limits allow.0keeps each routine’s built-in limit. It can be set for one operation, for exampleSET spock.sync_timeout = '2h'.spock.failover_slots_naptime(int milliseconds, default1000, range 1–3600000,SIGHUP) — how long Spock’s failover-slots worker sleeps between slot sync passes. It used to be a fixed 60 seconds, which let a standby’s slots fall up to a minute behind.spock.failover_slots_feedback_naptime(int milliseconds, default10000, range 1–3600000,SIGHUP) — the shorter retry interval the failover-slots worker uses while waiting for the standby to receive the WAL a slot needs. Both failover-slots settings matter only where Spock’s own worker runs: PostgreSQL 15 and 16, and 17 whensync_replication_slotsis off.spock.non_conflicting_inserts(bool, defaultoff,POSTMASTER) — asserts that a replicatedINSERTcan never collide with a local row, for example because each node generates keys from its own range. The apply worker then skips the conflict lookup and the speculative insertion and inserts the row directly. Nothing checks the assertion: a collision raises a duplicate key error, handled byspock.exception_behaviourrather than by conflict resolution.spock.failover_slots_recreate_invalidated(bool, defaulton,SIGHUP) — whether Spock’s failover-slots worker drops and recreates a slot copy that was invalidated on the standby.offleaves the copy as it is, so the cause can be looked into, and reports it once; the copy is recreated on the first pass after the setting is turned back on.spock.failover_slots_database(string, default empty,POSTMASTER) — on PostgreSQL 16 and 17, the database Spock’s failover-slots worker connects to so it can decode each slot copy on the standby and give it a consistent snapshot. On PostgreSQL 16 it must be the database the slots belong to. Empty keeps the old behaviour, under which transactions committed shortly before a failover can be missed after the promotion.
Removed
spock.use_spi— no longer used; the legacy SPI apply path is gone.spock.feedback_frequency— replaced by internal pacing.spock.batch_inserts- unused.
Changed
spock.exception_replay_queue_size: default4194304→4, unit changed from bytes to MB, semantics changed from a hard threshold (with publisher refetch) to a soft cap (with disk spill). See above.spock.pause_timeout: the 300-second maximum is removed, for very large or long-running transactions. The default is still 10 seconds.spock.restart_delay_default,spock.restart_delay_on_exceptionandspock.output_delayare now declared in milliseconds, so they accept values with units ('5s') andSHOWreports the unit. Their values do not change.spock.restart_delay_defaultnow applies to every apply-worker restart, including after a lost connection or a temporary error, so a problem that does not clear cannot become a tight restart loop.
Catalog changes
- New:
spock.sub_id_generatorsequence (replaces inline oid-from-counter generation for subscription rows). - New:
spock.reserved_objecttable, the list of reserved schemas and extensions (see Reserved schemas and extensions above). Built-in rows are protected by a trigger, and only user-added rows are dumped. - New index
spock.resolutions(log_time)to supportspock.cleanup_resolutions(). spock.resolutions.conflict_typevalues renamed during upgrade:update_update→update_exists,update_delete→update_missing,delete_delete→delete_missing.insert_existsis unchanged.spock.subscription.sub_skip_schemais now correctly typed astext[](the column was added astextin 5.0.2 but the C code always treated the bytes astext[]; the 5.0.7 step migration relabels the catalog so no rewrite or downtime is required).- New monitoring views: see Node monitoring GUCs, views and functions below.
New functions
spock.apply_group_progress()— set-returning health view (backsspock.progress).spock.read_peer_progress(slot, provider_node_id, subscriber_node_id)— used by zodan when importing a slot snapshot.spock.get_subscription_stats(subid)/spock.reset_subscription_stats(subid)— per-subscription conflict statistics (reading them needs PostgreSQL 18 or later).spock.cleanup_resolutions(days int DEFAULT NULL)— TTL-based cleanup of the resolutions log. Default permissions revoke EXECUTE from PUBLIC.spock.sub_alter_options(subscription_name name, options text[])— bulk subscription option changes, with input validation and no-op restart skipping.spock.reserved_object_add(p_name name, p_kind text, p_exclude_from_dump boolean DEFAULT true, p_block_in_repset boolean DEFAULT true, p_replicate_ddl boolean DEFAULT true)— reserve a schema or extension, or change an existing row.spock.reserved_object_remove(p_name name, p_kind text)— remove a reserved schema or extension you added.spock.slot_enable_failover() RETURNS integer— sets thefailoverflag on Spock’s logical slots on PostgreSQL 17 and later, and returns how many it changed. The upgrade from 5.x calls it. EXECUTE is revoked from PUBLIC.spock.node_alter(p_location text, p_country text, p_info_patch jsonb)— validated way to change the local node’s own location/country/info (merging info, validating atiebreakerpatch); see Automatic node metadata propagation above.spock.node_refresh_info(p_node_name name DEFAULT NULL) RETURNS boolean: fetches a peer’s location, country and info again from the peer itself, or every peer’s when called without a name, for a cached row that missed a change. Called with a name, it raises an error if that node cannot be refreshed. Called without one, it warns about each peer it cannot refresh and returnsfalseif any failed.spock.node_info_emit()/spock.node_info_apply()/spock.node_info_broadcast()(trigger function, backing the newnode_info_broadcast_triggeronspock.node) /spock.node_refresh_info_one()— internal plumbing behind node metadata propagation and refresh; not intended to be called directly (EXECUTErevoked fromPUBLIC, except on the trigger function).- The monitoring functions: see Node monitoring GUCs, views and functions below.
Removed functions
spock.convert_column_to_int8(regclass, smallint)— superseded.spock.convert_sequence_to_snowflake(regclass)— superseded.spock.wait_for_apply_worker(p_subbid bigint, timeout int)— had no callers since SpockCtrl was removed.
Node monitoring GUCs, views and functions
The monitoring added in 6.0, in one place. Node monitoring views above
describes what it shows. SELECT on the views, and EXECUTE on the functions
they read, is granted to pg_monitor. USAGE on the spock schema is not,
so a monitoring role needs that granted as well.
GUC
spock.event_history_size(int, default1024, range 16 to 1048576,POSTMASTER): how many recent events thespock.eventsview keeps in shared memory. Once the history is full, each new event drops the oldest, and the history is lost on restart.
Views
spock.node_status: the whole node on one row: versions, pending upgrade, worker and subscription counts, WAL retained by slots, replication lag, last events.spock.peer_status: the known nodes.spock.subscription_status: configuration, status, serving worker, replication position and lag, and the last error of every subscription.spock.subscription_stats: per-subscription worker starts and failures, provider connects, messages, transactions, tuple and conflict counters.spock.worker_status: supervisor, manager, apply and sync workers, including workers waiting for a restart.spock.slot_status: provider side: spock slots with their walsender, positions, retained WAL and feedback lag.spock.table_sync_status: table synchronization state.spock.replication_set_status: the replication sets.spock.system_status: disk space, load, connections, long and idle transactions, wraparound age, archiving.spock.settings: the parameters replication depends on.spock.events: the history of recent events.
Functions
spock.node_report(recent integer DEFAULT 50) RETURNS SETOF text: the whole node as one text report for support cases: host and versions, installed extensions, settings, every monitoring view, and the most recent exceptions, conflict resolutions and events.spock.replication_origin_status(): the replication origins and their progress, readable bypg_monitor, sincepg_replication_origin_statusis for superusers only.- Internal functions behind the views and
node_report():spock.get_worker_status(),spock.get_events(),spock.reset_events(),spock.get_apply_stats(),spock.get_slot_groups(),spock.get_monitor_summary(),spock.get_system_info(),spock.get_pending_exceptions(),spock.redact_dsn(),spock.wal_size_bytes()andspock.report_section().get_system_info(),get_events(),get_apply_stats()andget_pending_exceptions()are executable bypg_monitoronly, andreset_events()by superusers only. spock.reset_subscription_stats(subid)also resets the activity counters behindspock.subscription_stats, on every supported PostgreSQL version, and only superusers can run it.spock.get_apply_worker_status()is now a SQL function overspock.get_worker_status(), with the same columns and rows as before.
Bug fixes carried forward from the 5.0.x line
These shipped in 5.0.6 – 5.0.14 and are included in 6.0.0. The 5.0.14 fixes are listed under Other changes in the 6.0.0-beta.2 notes above.
- A promoted physical standby of a subscriber could replay transactions the subscriber had already applied. The apply worker’s commits record the origin node’s progress, not the subscription’s, so crash recovery and a physical standby left the subscription’s replication origin where the last checkpoint or base backup put it, and a promoted standby asked the provider to resend everything after that point. The apply and sync workers now write the subscription’s progress to WAL after each commit. (5.0.13)
spock.sub_wait_for_sync()andspock.table_wait_for_sync()crashed the server if the subscription was dropped while they waited. They now report that the subscription does not exist. (5.0.13)- pg_dump and pg_restore failures during structure sync were reported with
a stale
errnomessage such asInvalid argument. The error now gives the child’s exit code or signal. (5.0.13) - Table sync failed with
function does not existagainst an origin older than 5.0.7, which lacksspock.pause_apply_workers()andspock.resume_apply_workers(). Sync now skips pausing and resuming in that case. (5.0.13) - Handle upstream connection loss cleanly without replication-origin
advance leak. Previously a stale libpq socket fd produced an
epoll_ctl(EINVAL)cascade and the recovery path could silently advance the replication origin past an in-flight remote transaction, causing it to be missed on reconnect (and, withspock.exception_behaviour = transdiscard, its rows would land inspock.exception_logwitherror_message = unknown). The apply worker nowPG_RE_THROWs on connection-class errors and the manager respawns it from the last durably-committed remote LSN. - Preserve the original error message in
spock.exception_logwhen applying undertransdiscard/sub_disable. The originally-failing row now carries the real error message; bystander rows in the same transaction are recorded asunavailableinstead ofunknown. - zodan: name slots and subscriptions consistently
(
sub_{provider}_{subscriber}) via the newspock.gen_sub_name()helper;remove_nodedrops subscriptions from thespock.subscriptioncatalog instead of guessing names; pause apply workers during slot creation to prevent data loss when adding a new node; align Phase 3 catch-up wait and parameterisespock.sync_event()to avoid the Phase 9 handshake deadlock. - Prevent data loss on
resync_tablewhen the subscriber is read-only (SPOC-440). - Fix stale
local_tuplepointer in the INSERT exception path for a missing relation;SUB_DISABLEnow exits cleanly instead of dereferencing freed memory. - Suppress repeated
hot_standby_feedback offERROR spam when a standby is used for reporting (not failover). - Fix stack-use-after-scope in
spock_connect_base()(ASan finding). - Fix resource owner bug
apply_replay_bytesint→uint64overflow fix (b4ba9bdf)- A lost provider connection under
SUB_DISABLEcould disable the subscription: the resent transaction was mistaken for one that had failed to apply. - The apply worker retries after temporary errors — deadlocks,
lock_timeout, running out of a resource (SQLSTATE class 53), or a provider that is restarting or in recovery (57P02, 57P03) — instead of treating them as data exceptions that disable the subscription or discard the transaction. The worker exits without advancing the replication origin and the provider resends the transaction. - Restarting an apply worker in the middle of a transaction could disable
the subscription under
SUB_DISABLE. The failure marker is now cleared when the worker exits onSIGTERM. - An error between transactions left the apply worker in replay mode for
the next transaction, which had never failed, so under
TRANSDISCARDorSUB_DISABLEit could be discarded or disable the subscription. - Two subscriptions whose names share a prefix (such as
subandsub_parallel) shared one exception-log slot. The lookup now compares the whole name, and no longer reads past the end of the array. spock.get_lsn_from_commit_ts()could hang on an idle node. Its WAL scan now stops at the end of WAL as it was when the scan began.- The failover-slots worker died whenever the walreceiver reconnected to
the primary, when
spock.primary_dsnwas not set. It now waits for the next cycle. - Two retry messages lowered from LOG to DEBUG1 still reached the server log with default settings, because the level check was backwards.
- A column that exists on the provider but not on the subscriber put the apply worker in a restart loop. It is now handled like a missing table, and the error names every missing column.
- Tuple data from the provider is checked against the local column definition before use, so a tuple that does not fit is rejected instead of applied. Names and attribute counts in RELATION messages are checked too, and a subscriber built without lz4 rejects an lz4-compressed value.
Upgrading
The upgrade from 5.0.14 to 6.0.0 is a single ALTER EXTENSION spock UPDATE
once the binaries are swapped. Earlier 5.0.x releases upgrade in the same
single step, through 5.0.14. The upgrade:
- drops the legacy
spock.progresstable and recreates it as a view, - replaces the
spock.lag_trackerview definition, - migrates
spock.resolutions.conflict_typevalues, - adds the new functions, the
sub_id_generatorsequence and thespock.reserved_objectcatalog, - drops
spock.wait_for_apply_worker(), - replaces the C
spock.get_apply_worker_status()with a SQL function overspock.get_worker_status(), - adds the
node_info_broadcast_triggertrigger onspock.node, - adds the monitoring views and functions, and grants the read side to
pg_monitor, - refreshes the parallel-safety attributes on
spock.md5_agg_sfunc,spock.md5_aggandspock.spock_gen_slot_name, - turns on the
failoverflag for existing logical slots by callingspock.slot_enable_failover(), so PostgreSQL 17 and 18 slot synchronization picks them up. This is a no-op on PostgreSQL 16 and older and on a standby, and it skips slots that are in use at the time. See Logical Slot Failover for how to handle any skipped slots.
Check your runbooks and automation for direct DDL against the spock or
snowflake schemas before upgrading. Statements such as
DROP TABLE snowflake.x or CREATE INDEX on a spock table succeeded on
5.0.x and now raise an error (see AutoDDL improvements above). Any
procedure that needs to keep doing this must set
spock.enable_ddl_replication = off for the session first, which is also
what the error hint says. The restriction covers only the built-in
extension-owned schemas: schemas you reserve yourself with
spock.reserved_object_add() are unaffected, and pgedge_ace continues to
accept DDL and keep it node-local.
PostgreSQL’s 2026 security fix for CVE-2026-6471 added the
output_plugin_libraries parameter, and its default leaves out
spock_output, so logical decoding fails on a server with the fix. Set
output_plugin_libraries = 'pgoutput, test_decoding, spock_output' on every
node, physical standbys included, and only on servers that have the
parameter. See Configuring Spock.
The apply worker now restarts and tries again after a temporary error such
as a deadlock or lock timeout. If the problem never clears, expect the
worker to restart every spock.restart_delay_default (5 seconds by default)
instead of a disabled subscription or a discarded transaction.
Spock 5.0.15 release candidate (5.0 branch)
pgEdge published v5.0.15-rc.2 on November 23, 2026. The 5.0 branch still lists v5.0.14 as its latest stable tag. The candidate has no schema changes. Its release notes describe three fixes for the failover slot worker:
- When the primary is idle, a new slot copy on the standby can now become permanent in the same synchronization pass. The worker waits for the standby to receive the primary slot’s
restart_lsn, then creates the copy at that position. Previously promotion could discard a temporary copy and leave the subscriber without a slot. - When the standby cannot decode the WAL for an existing copy, the worker keeps the copy’s
restart_lsnin place until the standby has received the WAL up to the intended position. - If
spock.failover_slots_databaseis unavailable, slot synchronization continues without the consistent snapshot check. On a standby the worker retries when the database accepts connections. For other connection failures it retries immediately once, then after one minute, doubling the delay up to five minutes. The postmaster restarts an exited worker after 15 seconds, down from 60.
Spock 5.0.14
Upgrade Notes
There are no schema changes in 5.0.14.
On PostgreSQL 16 and later, we recommend setting the new
spock.failover_slots_databasesetting on each standby to the Spock database. It makes sure a subscriber is not missing transactions after the standby is promoted in a failover. Without it, a few transactions that committed on the primary shortly before the failover may never be sent to subscribers. Slot copies are then synchronized as in 5.0.13, and each one is reported once with a WARNING. The database has to be named because the failover slot worker runs once per server, not in any one database. The setting requires a restart. While it is set, the worker stays connected to that database, soDROP DATABASEandALTER DATABASE ... RENAMEon it fail unless you useWITH (FORCE)or clear the setting. See Configuring Spock.AutoDDL no longer replicates CLUSTER without a table, CLUSTER on a partitioned table, or, on PostgreSQL 19, REPACK with ANALYZE or CONCURRENTLY. These commit on their own partway through and broke the apply worker. They now run only on the node where they are issued, so run them on each node yourself. During a rolling upgrade, a node still on 5.0.13 can still send them, so avoid them or turn off AutoDDL until every node is on 5.0.14.
Bug Fixes
On a physical standby, the failover slot worker kept advancing a slot copy that had been invalidated, so it looked current but could not serve a subscriber after a promotion. The worker now reports such a copy, drops it and recreates it from the primary. The new
spock.failover_slots_recreate_invalidatedsetting turns that off.Creating a slot copy on the standby held up the sync of every other slot until the primary’s slot caught up, and a copy still waiting at promotion was kept with positions it could not serve. A new copy is now a temporary slot until the primary has caught up, and is dropped if the standby is promoted first.
A slot copy carried the primary’s positions but not its snapshot, so after a promotion the transactions that committed before decoding was consistent were never sent. With the new
spock.failover_slots_databasesetting the worker decodes each copy on the standby so that it has a consistent snapshot.On PostgreSQL 17 and later, a copy made by native slot sync whose slot the primary later dropped made the worker fail and restart every minute. The worker now leaves it and reports it once.
A physical slot named in
spock.pg_standby_slot_namesthat does not exist was never reported when the other named slots already satisfiedspock.standby_slots_min_confirmed, so the walsender could wait on it silently. The missing slot is now named in a warning even when the quorum is met, and the warning is issued again if the setting is reloaded to name a different missing slot.A slot listed twice in
spock.pg_standby_slot_nameswas counted twice, so with the defaultspock.standby_slots_min_confirmedof -1,'sb1,sb1'needed two confirmations from one slot and held replication untilwal_sender_timeouton every attempt. Repeated names are now ignored.An apply worker could fail with
unable to find an empty exception log slotwhile most entries were still free, for example when subscriptions with the same name in different databases started at the same time. The error also left a Spock shared memory lock held, so the manager workers,spock.sub_create()andspock.sub_show_status()hung until the server was restarted. The error is now raised only when the log is really full, the lock is released first, and the worker restarts afterspock.restart_delay_default.Under
last_update_wins, an incoming UPDATE always won against a local row that VACUUM had frozen, even when the local change was newer, so nodes could end up with different values. Since PostgreSQL 16, VACUUM can freeze recently written rows. Spock now finds the commit timestamp of a frozen row from its original transaction ID.A procedure that ran COMMIT or ROLLBACK, called over the extended query protocol (psycopg, JDBC) with a bound parameter, could crash the backend and restart the node.
spock.wait_for_sync_event()runs ROLLBACK, so just waiting for a sync event from such a client was enough. Spock read the statement after the procedure had freed it. It now decides whether the statement is DDL before running it.A replicated CLUSTER without a table crashed the apply worker on the subscriber, restarting the postmaster and replaying the statement on every restart. CLUSTER on a partitioned table, and REPACK with ANALYZE or CONCURRENTLY on PostgreSQL 19, had the same problem or hung the worker. These forms are no longer replicated. See Upgrade Notes.
Spock failed to build against PostgreSQL 19 RC1, which changed the signature of
RelationFindReplTupleByIndex().The Debian packages for different PostgreSQL major versions could not have their debug symbol packages installed together, because each one shipped the same build-id file for
spockctrl.spockctrlis no longer in the-dbgsympackage.
Spock 5.0.13
Upgrade Notes
- There are no schema changes in 5.0.13.
Bug Fixes
A promoted standby of a subscriber could replay transactions the subscriber had already applied. The subscription’s replication origin was not written to the WAL, so a standby resumed from the last checkpoint’s position. The apply and sync workers now log the origin’s progress after each commit.
spock.sub_wait_for_sync()andspock.table_wait_for_sync()crashed the backend if the subscription was dropped during the wait. They now report that the subscription does not exist.pg_dump and pg_restore failures during structure sync were reported with a stale
errnomessage such asInvalid argument. The error now gives the child’s exit code or signal.Sync failed with
function does not existagainst an origin older than 5.0.7, which lacksspock.pause_apply_workers()andspock.resume_apply_workers(). Sync now skips pausing and resuming in that case.
Spock 5.0.12
Upgrade Notes
There are no schema changes in 5.0.12.
PostgreSQL’s 2026 security fix for CVE-2026-6471 (back-patched to every supported major) added the
output_plugin_librariesparameter, and a library may no longer be used as an output plugin unless it is listed there. Its default excludesspock_output, so on a server carrying the fix logical decoding fails withlibrary "spock_output" may not be used as an output plugin. The check runs whenever decoding starts, not only at slot creation, so this stops an established cluster after a minor-version upgrade - not just new subscriptions. Setoutput_plugin_libraries = 'pgoutput, test_decoding, spock_output'on every node, physical standbys included, and only on servers that have the parameter- on older releases an unrecognised parameter stops the server from starting. See Configuring Spock. The regression and TAP test suites and the Docker test image now check for the parameter and set it themselves.
When the apply worker fails for a reason that has nothing to do with the data (a deadlock, a lock timeout, a provider that is restarting), it now restarts and tries again instead of treating the failure as an exception. See Bug Fixes. If the problem never goes away, you will see the apply worker restart every
spock.restart_delay_default(5 seconds by default) rather than a disabled subscription or a discarded transaction.
Bug Fixes
The apply worker now retries after temporary errors. Some errors have nothing to do with the replicated data: PostgreSQL picked the apply worker as a deadlock victim,
lock_timeoutfired, the server briefly ran out of a resource (SQLSTATE class 53), or the provider was restarting or still in recovery (57P02, 57P03). All of these succeed if tried again. Before, they went down the same path as a permanent data error, so depending onspock.exception_behaviourthe subscription was disabled or the transaction was written tospock.exception_logand thrown away, even though the provider would happily have sent it again. Now the worker exits without moving the replication origin, the manager starts it again, and the provider resends the transaction. Every restart path, including the existing one for a lost connection, now waitsspock.restart_delay_defaultbefore starting again, so a problem that does not clear cannot turn into a tight restart loop.Tables with
GENERATED ALWAYS AS ... STOREDcolumns caused replication errors. Generated columns were handled like ordinary columns during the initial table copy, in the replication protocol, when filling in defaults for missing columns, and during conflict resolution. They are now left out everywhere, and the subscriber computes them from the column definition.AutoDDL failed after utility commands that run outside a transaction block, such as
CLUSTERwith no table name. These commands commit after each table, so by the time the AutoDDL hook ran there was no open transaction and no snapshot, and the catalog lookups and the queue insert failed. AutoDDL now starts a transaction and takes a snapshot itself when it needs to.spock.get_lsn_from_commit_ts()could hang on an idle node. The function scans the node’s WAL for the last local commit at or before a timestamp, but the scan had no stopping point, so once it caught up it sat waiting for WAL that nobody was going to write. Anadd_noderun was seen stuck behind this call for over eleven minutes. The scan now stops at the end of WAL as it stood when it began, takes the commit timestamp and origin from the WAL record instead ofpg_commit_ts, counts local two-phase commits written by other applications, and refuses to run on a server in recovery. A timestamp with no matching commit still returns the slot’srestart_lsn, now logged at DEBUG1.A failure between transactions could make the apply worker mishandle the next one. When a transaction fails to apply, the worker restarts, the provider resends it, and the worker runs it again in what the code calls replay mode: each row is tried in a subtransaction so the failing row can be written to
spock.exception_logandspock.exception_behaviourcan decide what to do with it. Replay mode is meant for that one transaction. But an error raised between transactions switched the worker into replay mode with no failed transaction to attach it to, and the flag stayed set for whatever the provider sent next. That transaction, which had never failed, ran as a replay and underTRANSDISCARDorSUB_DISABLEwas thrown away or used to disable the subscription. The worker now turns replay mode on only for the transaction that actually failed, and any other transaction clears the recorded failure.A replayed transaction that applied nothing was still committed. Under
TRANSDISCARDandSUB_DISABLEevery row of a replay runs in a subtransaction that is always rolled back, so a replay applies no rows. The check for “replayed but hit no error” ran only after the replication origin had moved forward and the transaction had committed, so the origin ended up past a transaction that was never applied. The transaction was lost while the log said it had been discarded on purpose. The check now runs first and the transaction is rolled back instead, so the provider resends it. Transactions skipped withspock.sub_alter_skiplsnare exempt.Two subscriptions whose names share a prefix (for example
subandsub_parallel) shared one exception-log slot, because the lookup compared only the first few characters. Sharing the slot means sharing the commit LSN that marks a transaction as having already failed, so a failure recorded by one subscription could push the other into replay mode for a transaction that never failed. The lookup now compares the whole name. The same code also read, and could have written, one entry past the end of the array.The failover-slots worker died whenever the walreceiver reconnected to the primary. Without
spock.primary_dsnthe worker takes the primary’s connection string from the walreceiver, which blanks that string for the whole of every connection attempt, not only at standby startup. The connection then failed, the worker exited, and failover slots stopped syncing until it restarted. The worker now waits for the next cycle.Two retry messages for serialization failures are lowered from LOG to DEBUG1, but the check that decides whether to print them at the new level was backwards. With default settings they went to the server log no matter what
log_min_messagessaid. Also marked a deliberate switch fall-through in the apply worker so clang stops warning about it on every build before PostgreSQL 19.Restarting an apply worker in the middle of a transaction could disable the subscription. The worker records the commit LSN of every transaction it begins, not only ones that fail, and a clean shutdown left the marker behind, so the provider’s resend of the interrupted transaction looked like a transaction that had already failed. Under
SUB_DISABLEthat disabled the subscription for no real error. The marker is now cleared when the worker exits onSIGTERM.A column that exists on the provider but not on the subscriber put the apply worker in a restart loop. The error was raised while opening the table, before the per-row subtransaction exception handling needs, so
spock.exception_behaviournever got a say and the error came back on every retry without end. A missing column is now handled like a missing table: the first attempt raises the error, the retry discards the change and logs it through the normal exception path. The message also names every column the local table is missing, so repairing a drifted schema no longer costs one column per apply attempt.Tuple data arriving on the wire is now checked against the local column definition before it is used. Each attribute is copied out of the message into its own buffer and its length checked, so a tuple that does not fit the local column is rejected rather than applied. That is what happens after a provider-only
ALTER COLUMN TYPEwith DDL replication off: the apply worker exits and retries until the two schemas agree. Names and attribute counts in the RELATION message are validated too, and a subscriber built without lz4 now rejects an lz4-compressed value instead of storing it.
Other Changes
Refreshed the
attoptionsserver patch for theheap_update()change in PostgreSQL 17.11, 18.5 and 19 beta 3. One hunk’s context lines no longer matched and the patch was rejected. Only context lines changed.Spock builds against PostgreSQL 19 beta 3 and 4, with a new
compat/19layer for the API changes in that beta (CLUSTERfolded intoREPACK, the recovery-conflict signalling changes, tuple-descriptor finalisation, and the flattenedReorderBufferTXNcommit-time field).CREATE EXTENSIONaccepts major version 19, and CI and the release packaging cover it. This is preliminary: PostgreSQL 19 is still in beta, the compatibility layer will change before it is released, and Spock on 19 is not supported for production use.Dropped Debian bullseye from the platforms the release workflow builds packages for. It has reached end of life.
Removed the old Z0DAN Python files and their TAP test.
add_nodeandremove_nodeare provided by the SQL implementation.New documentation on running logical slot failover under Patroni on PostgreSQL 17 and later. It covers the parameters you need, the settings to put in the bootstrap DCS, and what to do about
synchronized_standby_slotson a switchover. A sample Patronion_role_changecallback,samples/set_synchronized_standby_slots.sh, resetssynchronized_standby_slotsafter a promotion. See Logical Slot Failover.Documented the
wait_if_disabledargument ofspock.wait_for_sync_event().TAP suite: tests share one set of log and wait helpers instead of each carrying a copy, cluster startup waits for the servers to be ready instead of sleeping 17 seconds, and a single test can be run on its own with
prove. New tests cover retry after temporary errors, real deadlocks, replay mode carrying over between transactions,spock.get_lsn_from_commit_ts(), a worker restart in the middle of a transaction, and a column missing on the subscriber.
Spock 5.0.11
New Features
Add
spock.use_native_failover_slots(default off, PGC_POSTMASTER). When enabled, spock marks logical slots with the FAILOVER flag on PG17+, yields to PostgreSQL’s native slotsync worker on PG17 whensync_replication_slots=on, and does not register spock’s own failover-slot worker on PG18+. Off preserves the existing worker-based behavior. Read on the subscriber node that creates the logical replication slot; changing it requires a server restart. See Logical Slot Failover for setup steps and the required post-promotionsynchronized_standby_slotsrunbook.Sync failover slots to the standby every 1s by default instead of a hard-coded 60s, shrinking the window in which a promotion can find a stale slot. The interval is now tunable via
spock.failover_slots_naptime(and the feedback-wait retry viaspock.failover_slots_feedback_naptime), both SIGHUP-settable in millisecondsNever copy the
pgedge_aceschema to a node joining viaadd_node. ACE state is node-local, so its objects are now excluded from both the schema copy and the data sync, even when an ACE table belongs to a replication set.
Bug Fixes
- Fixed a bug where a transient provider connection loss could incorrectly disable a subscription under SUB_DISABLE exception handling. A transaction retransmitted after a reconnect is no longer misclassified as an apply failure, so replication resumes normally instead of stopping.
Spock 5.0.10
Bug Fixes
- Improve apply performance on tables with a unique index over a frequently NULL column. Rows with a NULL in such a key are now recognized as non-conflicting without an unnecessary index scan, avoiding a slowdown that grew with table size.
- Correctly handle conflicts on
NULLS NOT DISTINCTunique indexes. On these indexes (PostgreSQL 15+) two NULL values are treated as equal, so matching NULL-keyed rows are now resolved through normal conflict resolution (last-update-wins) instead of failing with a duplicate-key error. - Fix a
could not open relationerror in the apply worker when an index is dropped while replication is running. The worker now refreshes its cached view of a table’s indexes before using it. - Fix gradual memory growth during a transaction that logs to
spock.exception_log. Memory used while recording exceptions is now released per row instead of accumulating until the transaction commits. - Record the real cause of a discarded transaction in
spock.exception_loginstead of the opaque placeholderunavailable. The failing command’s message is now stored (prefixed with its SQLSTATE where informative), and the other rows of the transaction note that they were discarded as collateral, making it possible to provide the root cause of the exception. - Fix ZODAN (
add_node) version checking. Spock versions were compared as text, so5.0.10sorted below5.0.4and a valid node was wrongly rejected. Versions are now compared numerically, and nodes may differ in patch level as long as their major.minor matches, allowing rolling upgrades. - Fix a spurious “tiebreaker values are equal” WARNING on timestamp-tied conflicts in single-writer topologies (and on node-id hash collisions). The tiebreaker now compares the applying node against the remote sender, and node-id collisions are detected at node creation.
Spock 5.0.9
New Features
- Initial PostgreSQL 19 support. Adds the server-side patches required to build and run Spock against PostgreSQL 19.
Bug Fixes
- Fix silently dropped writes after a synchronous-standby failover. Spock could report an incorrect replication position to the publisher, so a promoted standby resumed from the wrong point and lost the changes in between. The position reported to the publisher is now always taken from the publisher’s own WAL stream.
- Fix
spock_failover_slotsstalling on PG17+ standbys. Slot synchronization could hold replication-slot and proc-array locks exclusively long enough to block every backend trying to start up on the standby, freezing the worker and any new connections. The sync path now uses shorter, shared locks matching PostgreSQL’s own slot code. - Fix manager-worker respawn loop when databases are dropped or have
connections disabled (
datconnlimit = -2) concurrently with Spock starting a per-database worker. The database OID is now revalidated immediately before the worker is registered to avoid race. - Reduce per-row work and memory growth in the apply path. Replicated changes no longer re-open a table’s indexes for every row, and transient memory is freed per row instead of building up over the transaction.
Performance
- Skip building conflict log messages that would not be logged. When the log
level is suppressed, Spock no longer formats the conflicting rows for an
ereport()that would be discarded, speeding up apply on high-conflict workloads. Recording conflicts inspock.resolutionsis unaffected.
Spock 5.0.8
Bug Fixes
- Fix subscriber crash on transactions larger than 2 GB.
apply_replay_byteswas declared asint, causing signed-integer overflow and a crash when a single replicated transaction exceeded 2 GB of WAL data. Changed touint64. - The apply worker now exits cleanly when the upstream connection dies
(firewall reload, walsender SIGKILL/RST, walsender ping timeout) and the
manager respawns it from the last durably-committed remote LSN. Previously
a stale libpq socket fd produced an
epoll_ctl()cascade with a follow-onerror during exception handlingper disconnect, and a corner of the recovery path could silently advance the replication origin past the in-flight remote transaction, causing it to be skipped on reconnect. - Removed native PG17+/PG18 slot-sync integration. Spock no longer creates slots with (FAILOVER), does not defer to PostgreSQL’s slotsync worker, and keeps spock_failover_slots active on PG18; the spock worker is once again the only path for failover-slot sync on 5.x.
- spock_failover_slots: handle primary disconnects and post-promotion edge cases. Reconnects to the primary on transient failure during sync; fixes a PG15/16 PANIC where a freshly promoted standby could enter a crash loop because the synchronized slot’s restart_lsn was below the standby’s WAL floor; tolerates invalid/zero LSNs and catalog_xmin values that previously tripped assertions.
Spock 5.0.7
New Features
Logical Slot Failover Improvements
- On PostgreSQL 17+, Spock now creates all logical replication slots with
the
FAILOVERflag, allowing PostgreSQL’s built-in slotsync worker (sync_replication_slots = on) to automatically synchronize them to physical standbys. - On PostgreSQL 18+, Spock’s own
spock_failover_slotsbackground worker is no longer registered. The native PostgreSQL slotsync worker fully replaces it. See the Logical Slot Failover section in the configuration guide for requiredpostgresql.confsettings. - On PostgreSQL 17, Spock’s worker remains active but automatically yields
to the native slotsync worker if
sync_replication_slots = onis set, preventing conflicts.
Bug Fixes
- Preserve the original error message in
spock.exception_logwhen applying inTRANSDISCARDorSUB_DISABLEmode. Previously the original error was written only to the server log and lost before the retry pass; every row in the discarded transaction was logged witherror_message = NULL(stored as “unknown”). The originally-failing row now carries the real error message, while the bystander rows in the same transaction are recorded as “unavailable” instead of the misleading “unknown” fallback. - Fix missing data when adding a new node. An apply worker that committed
between
ensure_replication_slot_snapshotandadjust_progress_infocould advancespock.progresspast the COPY snapshot boundary, causing the new node to permanently skip those changes. Apply workers are now paused via an atomic flag and condition variable inSpockContextfor the duration of slot creation and resumed onceadjust_progress_infocompletes. - Fix apply worker crash with
epoll_ctl() failed: Invalid argumentafter a provider connection died. The socket fd captured beforestream_replay:was never refreshed, so a stale fd was passed toWaitLatchOrSocketon re-entry. The fd is now refreshed atstream_replay:and the worker exits cleanly so the postmaster can restart and reconnect it. - Fix PG15/16 failover slot loss on promotion: reconnect with retry and guard against a zero WAL flush LSN.
- ZODAN:
create_sub_on_new_node_to_src_node(Phase 9 ofadd_node) was generating subscription names assub_{subscriber}_{provider}instead of the expectedsub_{provider}_{subscriber}convention, causingremove_nodeto fail when looking up subscriptions by name. A newspock.gen_sub_name(provider_node, subscriber_node)helper is now used in place of inline name concatenations. - ZODAN: the
remove_nodecleanup loop tried to drop subscriptions by guessing names and nodes, which broke whenevercross_wireandadd_nodeused different naming conventions. It now performs a per-nodeDROPof every subscription read directly from thespock.subscriptioncatalog. - Since 5.0.2 there was a bug with spock.subscription.sub_skip_schema having the incorrect type, it should be text[]. Fixed, including in the spock-5.0.6–5.0.7.sql migration script to repair.
- Fix a rare bug where under high concurrency when using delta apply columns a ResourceOwner exception may occur.
- Have more meaningful messages appear in spock.exception_log.
Operational Improvements
- Documentation: filled out
snowflake.md; revisedupgrading_spock.md; fixed event-trigger syntax (EXECUTE FUNCTIONinstead of the deprecatedEXECUTE PROCEDURE); standardized function-reference filenames to match function names exactly; removed obsoletebatch_inserts.md - Test infrastructure aligned with
main:run_tests.shandSpockTest.pmnow use absoluteTESTLOGDIRpaths, derive per-test log filenames, and isolatepsqlfrom a developer’spsqlrc/history. New regression tests added for failover slots (018), exception-handling/TRANSDISCARD error quality (013), and the stale-fd-after-connection-death scenario (019). - Avoid unnecessarily waiting after sync_event()
Spock 5.0.6
New Features
- New
spock.feedback_frequencyGUC that controls how often feedback is sent to the WAL sender. Feedback is sent every n messages, where n is the configured value. Note that feedback is also sent everywal_sender_timeout / 2seconds. - New
spock.log_origin_changeGUC to control logging of row origin changes to the PostgreSQL log. Origin changes caused by replication are no longer written to thespock.resolutionstable, as they are informational and not true conflicts. Three modes are available:none— Do not log origin changes (default)remote_only_differs— Log only when a row from one remote publisher is updated by a different remote publishersince_sub_creation— Log origin changes for tuples modified after subscription creation (suppresses noise from pg_restored data)
- New
sub_created_atcolumn onspock.subscriptionto help distinguish pre-existing data (e.g. from pg_restore) from post-subscription data. - COPY TO is considered read-only and can now be run when a node is in read-only mode.
Performance Improvements
- Deferred
spock.progresscatalog writes. The progress table was previously updated on every committed transaction and every keepalive, causing significant table bloat and I/O overhead. Progress catalog writes are now batched and flushed at most once per second from the main apply loop. Shared memory is still updated immediately internally for correctness.
Bug Fixes
- Fix initdb assertion failure in attoptions patch for PG15/16/17.
- Fix two bugs in the table re-sync routine: WAL sending is now switched off during truncate and re-sync to prevent data loss, and the infinite wait was fixed when no more DML is committed by using the last committed LSN instead of the last received LSN.
- Use NULL for unknown
local_origininspock.resolutionsinstead of an invalid origin ID when origin cannot be determined (e.g. pg_dump, frozen transactions, truncated commit timestamps). Also fixed off-by-one errors inspock_conflict_row_to_json()that were overwriting thelocal_originNULL flag. - Fix Zodan initialization issue:
present_final_cluster_statenow executes a COMMIT to allow newly created subscriptions to update their state, and final cluster state now checks all subscriptions across the cluster. - Suppress hot_standby_feedback off error messages in log in case a read replica is used for reporting and not failover (it is required for failover).
- Fix bug when applying changes to a table that has been dropped.
Operational Improvements
add_nodeis now restricted to run only on a new (uninitialized) node, preventing accidental misuse.
Spock 5.0.5 on Feb 12, 2026
- Fix segfault that occurs when using new Postgres minor releases like 18.2.
- Zero Downtime Add Node (Zodan) minor bug fixes and improvements
- Updated documentation
Spock 5.0.4 on Oct 8, 2025
- Reduce memory usage for transactions with many inserts.
- When a subscriber’s apply worker updates a row that came from the same
origin, spock will no longer log it in the
spock.resolutionstable, reversing behavior that has been in place since 5.0.0.- Improved handling to block replicating DDL when adding an extension.
- Improved documentation
- Zero Downtime Add Node Improvements:
- New health checks and verifications (ex: version compatibility) before and during the add node process.
- New remove node SQL procedure (
spock.remove_node()in samples/Zodan/zodremove.sql) and python script (samples/Zodan/zodremove.py). This also handles removing nodes that were partially added when the user decided to undo this work. - Handle DSN strings that contain quotes.
- Bug fixes:
- Log messages containing credentials will now obfuscate password information.
- Fix bug when the subscriber receives DML for tables that do not exist.
This case will be handled according to the configured
spock.exception_behavioursetting (SUB_DISABLE,DISCARD,TRANSDISCARD). - Fix bug where spock incorrectly outputs a message that DDL was replicated when a transaction is executing in repair mode.
v5.0.3 on Sep 26, 2025
- Spock 5.0.3 adds support for Postgres 18.
- When using row filters with Postgres 18 such as in the functions spock.repset_add_table() or spock.repset_add_partition(), allowable filters are now stricter. Expressions may not use UDFs nor reference another table, similar to native logical replication in Postgres.
v5.0.2 on Sept 22, 2025
- Improved logging for all Zodan phases in both the stored procedure and Python examples.
- You can use the new Zodan skip_schema parameter to exclude schemas when
you’re adding a node, preventing local extension metadata from being copied.
- Added skip_schema option to sub_create. When synchronize_structure = true, schemas listed in skip_schema are not synced.
- dblink-based stored procedure for add node leverages skip_schema to skip preexisting schemas on the new node, avoiding failures on already existing schemas.
- Python add_node now mirrors stored procedure semantics, including skip_schema handling, structure sync, and logging. It works as a direct alternative to the procedure and no longer requires the dblink extension.
- Spock has been updated to use the PostgreSQL License.
v5.0.1 on Aug 27, 2025
- Bug fix for an incorrect commit timestamp being used for the case of updating a row that was inserted in the same transaction. A consequence was possible incorrect resolution handling for updates.
- Use the default search_path in the replicate_ddl() function.
- Prevent false positives for conflict detection when using partial unique indexes.
- New sample files for adding nodes with zero downtime.
- Python example
- Added enhanced add node support in stored procedures in
samples/zodan.sql
- Add a second node when there is only one node.
- Extended support for adding 3rd, 4th and subsequent nodes.
- Chain adding new nodes off of the previously added new node (eg: add N2 off N1, then add N3 off N2).
v5.0 on July 15, 2025
- Spock functions and stored procedures now support node additions and major
PostgreSQL version. This means:
- existing nodes are able to maintain full read and write capability while a new node is populated and added to the cluster.
- You can perform PostgreSQL major version upgrades as a rolling upgrade by adding a new node with the new major PostgreSQL version, and then removing old nodes hosting the previous version.
- Exception handling performance improvements are now managed with the spock.exception_replay_queue_size GUC.
- Previously, replication lag was estimated on the source node; this meant that if there were no transactions being replicated, the reported lag could continue to increase. Lag tracking is now calculated at the target node, with improved accuracy.
- Spock 5.0 implements LSN Checkpointing with
spock.sync()andspock.wait_for_sync_event(). This feature allows you to identify a checkpoint in the source node WAL files, and watch for the LSN of the checkpoint on a replica node. This allows you to guarantee that a DDL change, has replicated from the source node to all other nodes before publishing an update. - The
spockctrlcommand line utility and sample workflows simplify the management of a Spock multi-master replication setup for PostgreSQL.spockctrlprovides a convenient interface for:- node management
- replication set management
- subscription management
- ad-hoc SQL execution
- workflow automation
- Previously, replicated
DELETEstatements that attempted to delete a missing row were logged as exceptions. Since the purpose of aDELETEstatement is to remove a row, we no longer log these as exceptions. Instead these are now logged in theResolutionstable. INSERTconflicts resulting from a duplicate primary key or identity replica are now transformed into anUPDATEthat updates all columns of the existing row, using Last-Write-Wins (LWW) logic. The transaction is then logged in the node’sResolutionstable, as either:keep localif the local node’sINSERThas a later timestamp than the arrivingINSERTapply remoteif the arrivingINSERTfrom the remote node had a later timestamp
- In a cluster composed of distributed and physical replica nodes, Spock 5.0
improves performance by tracking the Log Sequence Numbers (LSNs) of
transactions that have been applied locally but are still waiting for
confirmation from physical replicas. A final
COMMITconfirmation is provided only after those LSNs are confirmed on the physical replica. This provides a two-phase acknowledgment:- Once when the target node has received and applied the transaction.
- Once when the physical replica confirms the commit.
- The
spock.check_all_uc_indexesGUC is an experimental feature (disabledby default); use this feature at your own risk. If this GUC isenabled, Spock will continue to check unique constraint indexes, after checking the primary key / replica identity index. Only one conflict will be resolved, using Last-Write-Wins logic. If a second conflict occurs, an exception is recorded in thespock.exception_logtable.
Version 4.1
- Hardening Parallel Slots for OLTP production use.
- Commit Order
- Skip LSN
- Optionally stop replicating in an Error
- Enhancements to Automatic DDL replication
Version 4.0
- Full re-work of parallel slots implementation to support mixed OLTP workloads
- Improved support for delta_apply columns to support various data types
- Improved regression test coverage
- Support for Large Object Logical Replication
- Support for pg17
The retained v3.3 production-release notes list the following enhancements over v3.2:
- Automatic replication of DDL statements
Version 3.2
- Support for pg14
- Support for Snowflake Sequences
- Support for setting a database to ReadOnly
- A couple small bug fixes from pgLogical
- Native support for Failover Slots via integrating pg_failover_slots extension
- Parallel slots support for insert only workloads
Version 3.1
- Support for both pg15 and pg16
- Prelim testing for online upgrades between pg15 & pg16
- Regression testing improvements
- Improved support for in-region shadow nodes (in different AZ’s)
- Improved and documented support for replication and maintaining partitioned tables.
Version 3.0 (Beta) includes the following important enhancements beyond the BDR/pg_logical base:
- Support for pg15 (support for pg10 thru pg14 dropped)
- Support for Asynchronous Multi-Master Replication with conflict resolution
- Conflict-free delta-apply columns
- Replication of partitioned tables (to help support geo-sharding)
- Making database clusters location aware (to help support geo-sharding)
- Better error handling for conflict resolution
- Better management & monitoring stats and integration
- A ‘pii’ table for making it easy for personally identifiable data to be kept in country
- Better support for minimizing system interruption during switch-over and failover
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
2.20 - pglogical to Spock function names
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Spock’s function names are shorter than pglogical’s, so a cluster or a script being ported from pglogical 2 needs almost every call renamed. This page maps each pglogical function to its Spock equivalent.
Verified against pglogical 2.4.8 and Spock 6.0.0. Where a Spock function has a reference page, its name links to it.
Nodes
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.create_node() | spock.node_create() |
pglogical.drop_node() | spock.node_drop() |
pglogical.alter_node_add_interface() | spock.node_add_interface() |
pglogical.alter_node_drop_interface() | spock.node_drop_interface() |
pglogical.pglogical_node_info() | spock.node_info() |
Subscriptions
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.create_subscription() | spock.sub_create() |
pglogical.drop_subscription() | spock.sub_drop() |
pglogical.alter_subscription_interface() | spock.sub_alter_interface() |
pglogical.alter_subscription_disable() | spock.sub_disable() |
pglogical.alter_subscription_enable() | spock.sub_enable() |
pglogical.alter_subscription_add_replication_set() | spock.sub_add_repset() |
pglogical.alter_subscription_remove_replication_set() | spock.sub_remove_repset() |
pglogical.show_subscription_status() | spock.sub_show_status() |
pglogical.show_subscription_table() | spock.sub_show_table() |
Replication sets
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.create_replication_set() | spock.repset_create() |
pglogical.alter_replication_set() | spock.repset_alter() |
pglogical.drop_replication_set() | spock.repset_drop() |
pglogical.replication_set_add_table() | spock.repset_add_table() |
pglogical.replication_set_add_all_tables() | spock.repset_add_all_tables() |
pglogical.replication_set_remove_table() | spock.repset_remove_table() |
pglogical.replication_set_add_sequence() | spock.repset_add_seq() |
pglogical.replication_set_add_all_sequences() | spock.repset_add_all_seqs() |
pglogical.replication_set_remove_sequence() | spock.repset_remove_seq() |
pglogical.show_repset_table_info() | spock.repset_show_table() |
Synchronisation
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.alter_subscription_synchronize() | spock.sub_alter_sync() |
pglogical.alter_subscription_resynchronize_table() | spock.sub_resync_table() |
pglogical.synchronize_sequence() | spock.sync_seq() |
pglogical.wait_for_subscription_sync_complete() | spock.sub_wait_for_sync() |
pglogical.wait_for_table_sync_complete() | spock.table_wait_for_sync() |
pglogical.wait_slot_confirm_lsn() | spock.wait_slot_confirm_lsn() |
DDL, utilities and version information
| pglogical 2.4 | Spock 6.0 |
|---|---|
pglogical.replicate_ddl_command() | spock.replicate_ddl() |
pglogical.table_data_filtered() | spock.table_data_filtered() |
pglogical.xact_commit_timestamp_origin() | spock.xact_commit_timestamp_origin() |
pglogical.pglogical_gen_slot_name() | spock.spock_gen_slot_name() |
pglogical_version() | spock.spock_version() |
pglogical_version_num() | spock.spock_version_num() |
pglogical_max_proto_version() | spock.spock_max_proto_version() |
pglogical_min_proto_version() | spock.spock_min_proto_version() |
Functions with no Spock equivalent
pglogical.queue_truncate() has no counterpart. Spock controls whether
TRUNCATE replicates with the replication set’s replicate_truncate
option, set with spock.repset_create()
or spock.repset_alter(),
rather than with a function call.
Spock functions with no pglogical ancestor
Spock adds functions that pglogical never had, so a port is not finished when
the last name in the table above has been changed. See the
function list for the full set; the additions
include spock.sync_event(), spock.wait_for_sync_event(),
spock.repset_add_partition(), spock.sub_alter_options() and
spock.sub_alter_skiplsn().
Upstream source · d05e2e2b6a82 · Copyright (c) 2021–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
3 - LOLOR
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
The English source is 1.3.0 development snapshot; latest stable tag v1.2.3, pinned at 1548836b0df0. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
On a normal drop, the event trigger checks replication and stored objects, then calls lolor.disable() if needed to restore the native function names. The object-access hook rejects removal if those names are still parked. Migrate the objects back to native storage before dropping the extension. Pinned implementation
lolor is an extension that makes Postgres-style large objects compatible with logical Replication.
Postgres supports large objects as related chunks as described in the pg_largeobject table. Large objects provide stream-style access to user data stored in a special large-object structure in the catalog. Large objects stored in catalog tables require special handling during replication; the lolor extension allows for the storage of large objects in non-catalog tables, aiding in replication of large objects.
lolor creates and manages large object related tables in the lolor schema:
Postgres large objects allow you to store large files within the database. Each large object is recognised by an OID that is assigned at the time of its creation. lolor stores objects in smaller segments within a separate system table and generates associated OIDs for large objects that are distinct from those of native large objects.
Use of the lolor extension requires Postgres 16 or newer.
Migrating large objects
Migration is a manual step in both directions: you decide when to move existing large objects into lolor storage, and you move them back before dropping the extension. Dropping the extension never moves data: it is refused while any object remains in lolor storage.
Native to lolor (manual)
If your database already contains native Postgres large objects, call
migrate_from_native() after enabling the extension. The migration preserves
original OIDs, owners, ACLs, and data, so existing application references remain
valid.
The function returns the number of large objects migrated. It is safe to call when there are no native large objects. This step is intentionally not automatic: it requires superuser privileges and should be performed during a maintenance window.
Lolor to native (before DROP EXTENSION)
Move the large objects back to native Postgres storage, then drop the extension:
Both paths preserve OIDs, owners, ACLs, comments and data, and copy pages verbatim so sparse large objects stay sparse.
A helper supports verifying a migration across nodes:
An object access hook refuses to remove the extension while it is enabled or
while any object remains in lolor storage, on every path that reaches it
(DROP EXTENSION, DROP SCHEMA lolor CASCADE, DROP OWNED BY). The drop
itself only puts the native pg_catalog.lo_* names back. To discard whatever
is in lolor storage instead, a superuser can set lolor.allow_unsafe_drop = on
for the session that runs the drop. It skips every check, and the drop then
does not restore the native function names either, so run lolor.disable()
first if lolor is enabled. While lolor is enabled, a normal drop renames the
native functions back, so it has the same requirements as lolor.disable():
no other session connected to the database, and a client session. A disabled
lolor renames nothing, and the drop has no such requirement.
lolor.enable() and lolor.disable() refuse while
any other session is connected to the database, and refuse to run from
anything but a client session. Reconnect client sessions after enable() or
disable(): libpq caches the large object function OIDs per connection.
Two helpers find and repair objects whose roles have been dropped:
When the spock extension is installed, both migration functions run under
spock.repair_mode(), so the row-shuffling migration DML is not replicated
to other nodes. This is essential for migrate_to_native(): its deletes from
the lolor tables would otherwise replicate while the native re-creation stayed
local, destroying large objects on the other nodes.
Even with spock, migration is refused if a non-spock logical replication slot
(e.g. pgoutput, wal2json) exists, since repair mode only suppresses spock’s
own output plugin and those consumers would still decode the migration DML:
migrate_to_native() raises an ERROR, while migrate_from_native() warns and
returns -1 without doing anything. Drop the offending slots before migrating.
Without spock, the migration DML cannot be excluded from logical decoding, so
both functions refuse to migrate while logical replication slots exist in the
database: migrate_from_native() raises a WARNING and returns -1 without
doing anything (0 is reserved for “nothing to migrate”), while
migrate_to_native() raises an ERROR. Drop all logical replication slots before
migrating; merely disabling a subscription is not sufficient, since its slot
retains the changes and delivers them when replication resumes.
Dropping the extension
In a replicated cluster the lolor tables are published, subscribed, or both, and the drop is refused while any of that is still true: the drop itself would succeed, but the other side would keep sending or expecting rows for tables this node no longer has. Unwind replication first, in this order:
Stop creating and changing large objects on every node, and let replication drain. Then confirm the nodes agree:
Stop publishing the tables. With Spock, remove them from the replication set on every provider node that publishes them:
With native logical replication, drop them from the publication instead:
A publication created
FOR TABLES IN SCHEMA lolordrops them withALTER PUBLICATION mypub DROP TABLES IN SCHEMA lolor. AFOR ALL TABLESpublication publishes them for as long as it exists: drop it, or recreate it with an explicit table list.Stop subscribing to them. A node that synchronized the tables when its spock subscription was created still counts them as replicated; refresh the subscription on that node so it forgets tables that are no longer in the provider’s replication sets:
A native subscription is refreshed with:
From here no node publishes the tables and no subscription expects changes for them, so the order of the per-node steps below does not matter.
Migrate the data out on every node, connecting to each node directly; with spock the migration runs in repair mode and is not replicated:
The migration refuses while a logical replication slot of any plugin other than spock’s exists in the database, and a native subscription keeps its slot on the publisher even when refreshed or disabled. Drop the native subscriptions that point at the node, which removes their slots, before migrating there.
Drop the extension on each node, connecting to each node directly, with no other client session connected to the database:
Without replication there is a single node: stop large object use, run
lolor.migrate_to_native(), and drop the extension, with the same
single-session requirement while lolor is enabled.
Limitations
- Native Postgres large object functionality cannot be used while you are using the lolor extension.
- lolor does not support the following statements against objects held in lolor storage:
ALTER LARGE OBJECT,GRANT ON LARGE OBJECT,COMMENT ON LARGE OBJECT, andREVOKE ON LARGE OBJECT. Owners, ACLs and comments set while an object was in native storage are preserved across migration in both directions. lolor.enable(),lolor.disable(), the migration functions,CREATE EXTENSION lolor, and dropping the extension while lolor is enabled, refuse while any other session is connected to the database, the same rule asALTER DATABASE ... RENAME: a renamed function keeps its OID, so a session that already resolved thelo_*functions keeps calling the previous implementation, and the row movement cannot be made atomic for other backends either. The calling session must reconnect afterenable()ordisable(). They also refuse to run from anything but a client session, so replicated DDL cannot drive them from an apply worker. Only client sessions count: background workers such as replication apply workers do not call thelo_*functions by name. To count reliably, each of these operations takes an exclusive lock on the database first, so a new connection to it waits until the operation’s transaction ends. In single-user mode they run without the session check.- The loaded library and the installed extension must be the same version for
lolor.enable(),lolor.disable(), the migration functions,lolor.check_orphans(),lolor.fix_orphans()and dropping the extension. After installing new library files, runALTER EXTENSION lolor UPDATEin each database before using them; until then they refuse and name both versions. - Objects in lolor storage are rows in ordinary tables and so cannot participate in
pg_shdepend.DROP ROLE,DROP OWNED BYandREASSIGN OWNED BYdo not see them: a role that owns them or appears in their ACL can be dropped without a warning, andREASSIGN OWNED/DROP OWNEDleave them untouched. Before dropping a role, runREASSIGN OWNED BYorDROP OWNED BYin each database that has lolor, thenDROP ROLE. For the role that owns the extension useREASSIGN OWNED BY:DROP OWNED BYwould remove the extension too, and is refused while any object remains in lolor storage. Afterwards runlolor.check_orphans()in each such database and repair anything it reports withlolor.fix_orphans(new_owner);lolor.migrate_to_native()refuses while orphans exist. - Dropping lolor is refused while
lolor.pg_largeobject,lolor.pg_largeobject_metadataorlolor.pg_largeobject_descriptionis in a spock replication set, a publication or a subscription on this node, or was synchronized to this node through a spock subscription, whichever way the drop is spelled. The drop itself would succeed; what breaks is replication afterwards, since the other side keeps sending rows for a table this node no longer has. Remove the tables from the replication set, publication or subscription first, then migrate the objects out and drop. The refusal is enforced when the tables are deleted, not only by the event trigger, so disabling event triggers does not get around it. A spock subscriber knows the tables as replicated only from their initial synchronization; a table added to a replication set later is not seen by the check on that node. The step-by-step order is in Dropping the extension. - Role OIDs come from a cluster-wide counter that wraps around, so a new role can receive a dropped role’s OID and silently become the owner or grantee of that role’s orphaned objects. This cannot be detected after the fact, which is another reason to run
lolor.check_orphans()promptly after dropping roles. - Large object migration is node-local. Native large objects live in
pg_catalog.pg_largeobject, which is never replicated, so each node holds an independent set andmigrate_from_native()migrates only the local node’s objects; with spock installed, the migration DML runs in repair mode and is not replicated. Run the migration on every node that holds native large objects, connecting to each node directly. It refuses to run inside an apply worker, so sending it through DDL replication fails on every subscriber. Migrated objects keep their original native OIDs, which are not node-encoded: if different nodes hold different objects under the same OID, the nodes’ lolor contents will diverge and later replicated changes to those objects can conflict. Newly created large objects are collision-free, since new OIDs are node-encoded vialolor.nodeand checked against existing rows. To make that hazard an error rather than silent divergence, collect the other nodes’ OIDs withlolor.native_lo_oids()and pass them in:SELECT lolor.migrate_from_native(peer_oids => ARRAY[...])refuses when any of them collide. After migrating every node, comparelolor.digest()across nodes to confirm they converged.
Continue reading
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
3.1 - Installing and Configuring lolor
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
lolor is supported on Postgres versions 16 and later.
lolor ships with pgEdge Distributed Postgres and pgEdge Enterprise Postgres, so a pgEdge deployment provides the extension for you. The Control Plane installs the lolor package on each node as part of standard cluster setup.
If you manage Postgres yourself, you can compile and install the extension from the source code, following the same guidelines as any other Postgres extension built with PGXS. Make sure that your PATH environment variable includes the directory where pg_config (under your PostgreSQL installation) is located.
lolor must be loaded at server start. Add it to shared_preload_libraries in postgresql.conf and restart; CREATE EXTENSION lolor, LOAD 'lolor' and any call that reaches one of lolor’s functions fail with lolor must be loaded via "shared_preload_libraries" when the library was loaded on demand; the native pg_catalog.lo_* functions are not affected while lolor is not installed or is disabled. The guard that protects large objects when the extension is dropped is an object access hook, which is only in place in every backend when the library is preloaded.
Then connect to your Postgres database and create the extension with the command:
Configuring lolor
You must set the lolor.node parameter on each node in your replication cluster before using the extension. The value can be from 1 to 15 (0 means unset); it is encoded in the four low bits of every large object OID lolor generates, so each node must use a different value.
You can also change the search_path to pick large object related tables from the lolor schema:
lolor renames any existing methods in pg_catalog.lo_* to pg_catalog.lo_*_orig, and new versions of these methods are introduced. If you remove the extension, the renamed pg_catalog.lo_*_orig functions are restored to their initial names.
When you replicate large objects with Spock, the tables pg_largeobject, pg_largeobject_metadata and pg_largeobject_description must belong to your replication set. The third table holds the comment of each object that was migrated from native storage; without it, a lo_unlink() leaves the comment behind on the other nodes, and a node that is added or resynchronized later does not receive the comments. Connect to the lolor database and add them with spock.repset_add_table:
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
3.2 - lolor Release Notes
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
lolor 1.3.0
These notes describe pinned main development. The latest stable tag checked on November 21, 2026 remains v1.2.3.
On a normal drop, the event trigger checks replication and stored objects, then calls lolor.disable() if needed to restore the native function names. The object-access hook rejects removal if those names are still parked. Migrate the objects back to native storage before dropping the extension. Pinned implementation
- Add bidirectional large object migration between native PostgreSQL and lolor storage, implemented as a direct relation-to-relation copy in C (
lolor.migrate_storage()) rather than a loop through the large object API:lolor.migrate_from_native(peer_oids oid[] DEFAULT NULL)moves native large objects into lolor storage. It is a manual step afterCREATE EXTENSION lolor, requires superuser, and returns the number of objects moved or -1 if the migration was refused.lolor.migrate_to_native()moves them back, whether or not lolor is enabled. It is a manual step before dropping the extension; the drop is refused while any object remains in lolor storage and no longer migrates anything itself.- Both directions preserve OIDs, owners, ACLs, comments and the exact page layout, so sparse objects stay sparse. Ownership and ACLs are recorded in
pg_shdependon the way back, soDROP ROLE,REASSIGN OWNEDandDROP OWNEDsee the objects again. Comments are parked inlolor.pg_largeobject_descriptionwhile an object is in lolor storage. Native objects are removed with the same bookkeeping asDROP(dependencies, comments and labels), but without the per-object locksDROPtakes, so a database with more large objects than the lock table can hold is migrated without raisingmax_locks_per_transaction. - Storage layouts are verified against the running server at migration time. Security labels, which lolor storage cannot represent, cause
migrate_from_native()to refuse. OID conflicts are reported with the conflicting OIDs. - Migration holds
ShareRowExclusiveLockon both stores until commit. Ordinary large object access takesRowExclusiveLock, which does not conflict with itself, so a concurrentlo_write()could otherwise be lost silently. Opposing migrations take their locks in a fixed order and cannot deadlock. - Both migration functions refuse while any other session is connected to the database, and refuse to run from anything but a client session.
- With spock installed, both functions run under
spock.repair_mode(). If a logical slot spock cannot suppress exists, a non-spock slot or any slot when spock is absent, they refuse rather than let subscribers decode the migration as row changes. - Migration is node-local: native large objects are never replicated, so run the migration on each node by connecting to it directly. Do not send it through DDL replication, which would run it inside every subscriber’s apply worker. Native OIDs are not node-encoded, so pass the other nodes’ OIDs (from
lolor.native_lo_oids()) aspeer_oidsto turn a cross-node collision into a refusal, and comparelolor.digest()across nodes afterwards. migrate_to_native()refuses with a clear error while any object refers to a dropped role, instead of failing part-way with “role N was concurrently dropped”; remove those objects withlo_unlink()and retry.
- New helpers
lolor.digest()andlolor.native_lo_oids()for cross-node checks after a node-local migration. - New helpers
lolor.check_orphans()andlolor.fix_orphans(new_owner)for objects whose owner, grantee or grantor has been dropped. Objects in lolor storage cannot participate inpg_shdepend, soDROP ROLEdoes not notice them;check_orphans()lists them and which reference is dangling, andfix_orphans()reassigns dead owners, replacing them in the ACL asREASSIGN OWNEDwould so that grants they made survive, and drops entries that still name a missing role. - Server-side large-object file permissions. Versions 1.0 through 1.2.2 granted excessive default execution rights on replacement file-import and export functions. Use the corrected extension SQL and verify function privileges after upgrade. Review which roles actually need server-side file access.
- The extension is no longer marked
trusted. Installing lolor renames functions inpg_catalogfor the whole database, which a non-superuser should not be able to do. - Fixed
DROP ROLEfailing with “unrecognized object class”. Creating a large object recorded apg_shdependrow whoseclassIdwas the OID oflolor.pg_largeobject, an ordinary table rather than a catalog. Any role that had created a large object became undroppable, and the rows were never cleaned up becauseinv_drop()deleted withPERFORM_DELETION_SKIP_ORIGINAL. lolor no longer records these rows, and the upgrade removes the ones already present.- The cleanup is per database, so
ALTER EXTENSION lolor UPDATEmust be run in every database that has lolor. Until it is,DROP ROLEanywhere in the cluster keeps reporting “owner of objects in database X”. - A database that ran
DROP EXTENSION loloron an earlier version still has the rows, now pointing at a table that no longer exists, and no upgrade script will run there. Clean it by hand as superuser in that database: find the stale class OIDs withSELECT DISTINCT classid FROM pg_shdepend WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND classid NOT IN (SELECT oid FROM pg_class), thenDELETE FROM pg_shdepend WHERE dbid = <that dbid> AND classid IN (<those OIDs>).
- The cleanup is per database, so
- lolor must now be listed in
shared_preload_libraries. Loading it on demand is refused:CREATE EXTENSION lolor,LOAD 'lolor'and any call that reaches one of lolor’s functions fail withlolor must be loaded via "shared_preload_libraries"; the nativepg_catalog.lo_*functions are not affected while lolor is not installed or is disabled. The drop guard below is an object access hook, which is only present in every backend and worker when the library is preloaded, and a missing or broken library now fails at server start rather than at the firstlo_open(). Upgrade in this order: install the new library files, addlolortoshared_preload_libraries, restart, then runALTER EXTENSION lolor UPDATEin each database. Between the file install and the restart, any session that loads the new library on demand gets that error, so restart promptly. - Removing the extension is guarded by an object access hook.
DROP EXTENSION,DROP SCHEMA lolor CASCADE,DROP OWNED BYand any other path that reaches the extension are refused while lolor is enabled or while any object remains in lolor storage, checked in the catalog at the moment of deletion from whichever backend performs it. The drop no longer migrates the objects out itself: runlolor.migrate_to_native()first. The event trigger only puts the nativepg_catalog.lo_*names back. The new superuser settinglolor.allow_unsafe_dropskips both checks and discards the contents of lolor storage. Because the drop renames the native functions back, it has the same requirements aslolor.disable(): no other session connected to the database, and a client session. - Dropping lolor is refused while its tables are in a spock replication set, a publication on this node, including one created
FOR ALL TABLESorFOR TABLES IN SCHEMA lolor, or a subscription on this node, or were synchronized to it through a spock subscription. The drop would succeed and replication would break afterwards: the other side keeps sending rows for a table this node no longer has, and a subscription removed byDROP OWNED BYleaves its slot behind. The error names the memberships; remove the tables from them first. The check is enforced when the tables are deleted, so it holds with event triggers disabled. lolor.enable()andlolor.disable()refuse to run from anything but a client session, so replicated DDL cannot execute them inside an apply worker, where a refusal would leave that node’s replication retrying forever.CREATE EXTENSION lolorhas the same requirements aslolor.enable(), since the install script renames the native functions the same way: no other session connected to the database, and a client session.lolor.enable(),lolor.disable()andlolor.is_enabled()now probe exact function signatures inpg_catalog. They previously matched onpronameacross every schema, so any user withCREATEon any schema could define a function namedlolor_lo_openand wedge lolor into a permanent “inconsistent state” that also blockedDROP EXTENSION. Both now emit a notice that client sessions must reconnect, since libpq caches the large object function OIDs per connection, and refuse while any other session is connected to the database, since a renamed function keeps its OID and other sessions cannot be made to see the switch.- The session check behind
lolor.enable(),lolor.disable(), the migration functions and the drop is done in C and takes an exclusive lock on the database before counting, so a session connecting at the same moment either is counted or waits until the operation’s transaction ends. Previously it was a snapshot ofpg_stat_activityand could miss such a session. Single-user mode is no longer refused. lolor.enable(),lolor.disable(), the migration functions,lolor.check_orphans(),lolor.fix_orphans()and dropping the extension refuse while the loaded library and the installed extension are different versions. A drop with new library files and an older installed extension would otherwise run that version’sdisable(), which still has the unqualified function lookups fixed in this release. RunALTER EXTENSION lolor UPDATEfirst.- Fixed the
lolor.nodeupper bound. The GUC accepted 0..16 while a generated OID reserves four bits for the node id, so node 16 did not fit: the node field of every OID it generated read back as 0. The bound is now derived from the encoding (LOLOR_MAX_NODE_ID), giving 0..15. If you havelolor.node = 16configured, the server still starts but logs16 is outside the valid range for parameter "lolor.node" (0 .. 15)and falls back to 0, which is the node id it was effectively using already. Set it to a value in 0..15, and check for OID collisions against whichever node is genuinely 0. - Expanded test coverage: TAP tests for dump/restore, streaming and logical replication, standby promotion, the drop paths, migration fidelity and locking, and cross-node OID collisions; regression tests for
lo_lseek,lo_tell,lo_truncate, the 64-bit interface, sparse objects, comment round trips,pg_shdependrestoration, permission enforcement, the orphan helpers and name squatting. The regression suite runs on its own preloaded instance. - Security hardening: addressed Codacy/Flawfinder warnings.
lolor 1.2.3
- Add support for PostgreSQL 19
- Add in-repo release workflow and RPM/DEB packaging
- Improve CI: build the test cluster from source, add PostgreSQL 19 to the test matrix, and bound test run time
lolor 1.2.2
- Fix lolor upgrades
- Fix issues with pg_upgrade. Note that this fixes upgrades with pg_upgrade going forward.
ALTER EXTENSION UPDATEfor upgrading the extension itself works, so if wanting to run pg_upgrade, first update your extension to 1.2.2, then run pg_upgrade - Address CVEs CVE-2022-26520, GHSA-673j-qm5f-xpv8
- PATH updated to match native Postgres packaging layout
- Make table OID caching safer
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
3.3 - Using lolor
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
The following command examples demonstrate using lolor:
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
3.4 - Using pg_upgrade with lolor
Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.
The pg_upgrade utility is used for upgrading Postgres versions.
You can use pg_upgrade with the lolor extension installed provided that you are using lolor version 1.2.2 or later. If you are using an older version of lolor, you will need to upgrade the extension first.
Both clusters must list lolor in shared_preload_libraries; without it the new cluster cannot load lolor’s library, so restoring the extension fails.
Before running pg_upgrade, you must disable lolor. After executing pg_upgrade, you can enable lolor. Use psql or another client to disable lolor:
Next, execute the upgrade. A sample pg_upgrade command appears below:
Then, use psql to enable lolor:
Reconnect any client sessions afterwards. lolor.enable() and
lolor.disable() change which function OID owns each pg_catalog.lo_* name,
and libpq resolves those OIDs once per connection and caches them for the life
of the connection. A session that used a large object before the switch would
otherwise keep calling the previous implementation.
Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.
4 - Snowflake
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
The English source is v2.6.1, pinned at 9506e1bd5c1f. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
Using a Snowflake sequence allows you to take full advantage of the benefits offered by a distributed, multi-master replication solution. Snowflake is a Postgres extension that provides an int8 and sequence based unique ID solution to optionally replace the Postgres built-in bigserial data type.
Internally, snowflakes are 64 bit integers represented externally as bigint values. The 64 bits are divided into bit fields:
- bit 63 - unused (sign of int8)
- bits 22-62 - timestamp with millisecond precision
- bits 12-21 - unique pgEdge Distributed Postgres node number
- bits 0-11 - counter within one millisecond
- The timestamp is a 41-bit unsigned value representing millisecond precision and an epoch of 2023-01-01.
- The counter is a 12-bit unsigned value that increments per ID allocation. This provides for 4096 unique IDs per millisecond, or 4 million IDs per second.
- The node number is a 10-bit unique identifier for the Postgres instance inside a global cluster. This value is set with the
snowflake.nodeGUC in thepostgresql.conffile.
Snowflake sequences let you:
- add or modify data in different regions while ensuring a unique transaction sequence.
- preserve unique transaction identifiers without manual/administrative management of a numbering scheme.
- compare ID generation times across nodes. Clock skew and the interval between ID generation and commit can affect the observed order.
Snowflake sequences also alleviate concerns that network lag could disrupt sequences in distributed transactions.
A Snowflake sequence is made up of a timestamp, a counter, and a unique node identifier; these components are sized to ensure over 18 trillion unique sequence numbers. The extension supports versatile commands and functions that simplify creating a new Snowflake sequence or converting an existing sequence.
Continue reading
- Changelog
- Converting a PostgreSQL Sequence to a Snowflake Sequence
- Creating a Snowflake Sequence in a New Cluster
- Reviewing Sequence Definitions in your Table Meta-data
- Snowflake Functions
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.1 - Changelog
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
All notable changes to the Snowflake extension are documented here.
2.6.1
Changed
- Version bump to 2.6.1 (no catalog changes). Includes release packaging and CI updates since 2.6.0.
2.6.0
Added
- Added support for Postgres 19
2.5.0
Added
- PG18 support: added a PG18 test configuration and adjusted the Docker build to skip LLVM bitcode compilation on PG18.
Changed
- Adopted three-digit (
MAJOR.MINOR.PATCH) versioning. The extension version is now2.5.0.
Fixed
- Fixed dump/restore of snowflake-converted sequences.
convert_sequence_to_snowflake()previously leftMAXVALUEat(old last_value + 1), butsnowflake.nextval()bypassesMAXVALUEand writes snowflake-sized values, sopg_dumpcould emit asetval()that failed to restore. Sequences are now converted withAS bigint MAXVALUE 9223372036854775807, and sequences converted by earlier versions are auto-repaired on upgrade. (SUP-140) - Fixed the SQL command used to convert sequences to Snowflake.
Security / CI
- Pinned GitHub Actions to full commit SHAs to harden against supply chain attacks.
- Removed
shell=Trueand shell-injection risks from test runner and helper subprocess calls; useshlex.split()for correct argument tokenization. - Fixed a SQL injection warning and a missing parameter in
execute_sqlite_query, and suppressed Bandit B603 warnings on internal test helper subprocess calls. - Fixed the Dockerfile
ARGhandling for newer BuildKit versions. - Updated the copyright year to 2026.
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.2 - Converting a PostgreSQL Sequence to a Snowflake Sequence
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
You cannot directly create a snowflake sequence; you must first create a sequence in Postgres and then convert it. Sequences are created explicitly with the CREATE SEQUENCE command but are also implicitly created by GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY table columns or SERIAL and BIGSERIAL columns. GENERATED AS IDENTITY is the recommended ANSI SQL method.
You can use the snowflake.convert_sequence_to_snowflake() function to convert individual sequences to snowflake sequences. Note that this converts the sequence definition; existing values in a sequence column will not change. The command syntax in SQL is:
`SELECT snowflake.convert_sequence_to_snowflake('sequence_name');`
Where
sequence_name is the name of a sequence.
There are a number of ways to return a list of sequences. One way is to use the Postgres psql client to execute the following command:
Another way is to query metadata catalog information directly in psql or another SQL editor.
The second command will include data type information, which is useful for learning which sequences will be converted to the BIGINT data type (64 bits).
Example: Converting an Existing Sequence
The example that follows demonstrates using the psql command line to convert a sequence; in this example, we are using a table named orders that has three columns; the last column is a sequence named id:
After creating the table, we insert data into the orders table. We only need to provide content for the first two columns, since the sequence definition keeps track of the value of the third column and adds it as needed:
When we select the rows from our table, we can see the sequence numbers in the id column:
To convert the sequence definition for the orders table to use Snowflake sequences, invoke the following command in psql or another SQL editor:
The conversion process modifies the sequence definition to use Snowflake sequences, but does not update existing rows. If we reconnect with psql and add new rows to the table, the new row’s id will be a Snowflake sequence:
In the query results that follows, you can see the unformatted sequence values in the id column, and the same information in the format column, formatted with the snowflake.format(id) function. The rows added before the conversion to Snowflake sequences show a fixed timestamp of 2022-12-31 19:00:00-05, while the Snowflake sequences have a unique id and timestamp.
Original entries in the table display a Postgres sequence, while entries made after the conversion display Snowflake sequences:
INCREMENT and Caching
Within the same millisecond, snowflake will allow a maximum of 4096 values. Some frameworks like the ORM framework Hibernate may be configured to try to fetch a sequence value, cache and assign a range by using an INCREMENT value for the sequence. Snowflake sequences honor the increment value, but you should not use a value greater than 4096. If you would like to change the increment value, use ALTER SEQUENCE <seq_name> INCREMENT <increment_value> NO MAXVALUE.
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.3 - Creating a Snowflake Sequence in a New Cluster
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
Before you use Snowflake sequences, each node in your cluster must have a unique snowflake.node identifier. The value ranges from 1 to 1023, and it must be distinct on every node in the cluster.
Setting snowflake.node in a managed deployment
A pgEdge deployment assigns snowflake.node for you, deriving the value from each node’s place in the cluster:
- the Control Plane sets
snowflake.nodefrom the node ordinal. - pgEdge Helm charts derive
snowflake.nodefrom each node name. - pgEdge Ansible playbooks set
snowflake.nodefrom the node zone.
When you deploy with one of these methods, no further action is needed to configure the node identifier.
Setting snowflake.node manually
For a self-managed or from-source installation, set the value yourself. Use ALTER SYSTEM to assign a unique node number, then reload the server so the change takes effect. The following example sets the node identifier to 10:
You can also add the parameter to the postgresql.conf file directly. The following line identifies the host as node 11:
After you edit postgresql.conf, reload the server for the change to take effect. You can reload from psql:
You can also reload the server with pg_ctl:
Once Snowflake is configured, you can begin to use Snowflake sequences by first converting them from Postgres sequences.
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.4 - Reviewing Sequence Definitions in your Table Meta-data
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
If you query the table meta-data before performing a sequence conversion with the \d+ orders command, the PostgreSQL sequence is defined in the Default column:
After performing a conversion, the \d+ table_name command shows a Default value of snowflake.nextval('orders_id_seq'::regclass):
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
4.5 - Snowflake Functions
Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.
You can query the following Snowflake functions at the psql command line to return useful information about tables that use Snowflake sequences.
snowflake.nextval([sequence regclass])
Generates the next Snowflake in the specified sequence. If no sequence is specified, the internal, database-wide sequence snowflake.id_seq is used. For example, the following query returns the next number in the orders_id_seq sequence:
snowflake.currval([sequence regclass])
Returns the current value of the specified sequence. This value is undefined until the function snowflake.nextval() has been called for the sequence in the current session. For example, the following query returns the current value of the orders_id_seq sequence:
snowflake.get_epoch(snowflake int8) Returns the Unix timestamp in seconds as a NUMERIC with three decimal places. Snowflake IDs store milliseconds relative to 2023-01-01 UTC. The function adds the offset from the Unix epoch before returning the value. The example returns 1704996539.845:
You can use the to_timestamp(snowflake.get_epoch(<value>)) function to convert the epoch into a timestamp. For example:
In v2.6.1, bits 12–21 of 136169504773242881 encode node 0 and the low 12 bits encode count 1. For this ID, get_node() returns 0, get_count() returns 1, and format() reports "id": 0 and "count": 1. The upstream transcripts below show different values. Pinned bit layout
snowflake.get_count(snowflake int8) Returns the count part of the given Snowflake as int4 value; count resets to 0 for each new millisecond. For example:
snowflake.get_node(snowflake int8) Returns the node number encoded in the ID. It reflects the snowflake.node setting at allocation time. Decoding does not read the issuing host’s configuration file. The historical upstream transcript follows.
snowflake.format(snowflake int8) Returns a jsonb object of the given Snowflake in the form: {"id": 1, "ts": "2023-10-16 17:57:26.361+00", "count": 0}. For example:
Upstream source · 9506e1bd5c1f · Copyright (c) 2023–2026, pgEdge, Inc.; portions Copyright the PostgreSQL Global Development Group and The Regents of the University of California. PostgreSQL License.
5 - SafeSession
Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.
The English source is v1.1, pinned at d66225fcceef. A Chinese edition of this snapshot is available. Check versions and sources before deploying.
pgEdge SafeSession is a PostgreSQL extension that enforces read-only sessions for specified database roles. It provides defense-in-depth protection using executor and utility hooks to block all write operations, DDL, and other potentially dangerous commands.
Features
- Block DML (INSERT, UPDATE, DELETE, MERGE) for restricted roles
- Block DDL (CREATE, ALTER, DROP, TRUNCATE, etc.)
- Block COPY FROM and COPY TO PROGRAM
- Block GRANT/REVOKE, VACUUM/ANALYZE
- Block volatile C-language function execution (which can bypass the executor)
- Prevent tampering with read-only GUC settings
- Role membership inheritance: members of restricted roles are also restricted
- Superuser exemption: superusers are never restricted, even if they are members of restricted roles
- Session-user anchored: SET ROLE cannot escape restrictions
- Configurable protection layers via GUCs
Requirements
- PostgreSQL 14 or later
- Must be loaded via
shared_preload_libraries
Installation
Build from Source
Configure PostgreSQL
Add the extension to shared_preload_libraries in
postgresql.conf:
Restart PostgreSQL for the change to take effect.
Create the Extension (Optional)
The extension is fully functional once loaded via
shared_preload_libraries. Running CREATE EXTENSION is
optional, but registers it in the pg_extension catalog
so it appears in \dx output:
Configuration
All GUCs are SUSET parameters (only superusers can modify them).
pgedge_safesession.roles
A comma-separated list of PostgreSQL role names whose sessions will be restricted to read-only operations.
Any session authenticated as one of these roles, or as a role that is a member of one of these roles, will be restricted to read-only operations.
pgedge_safesession.block_dml
Default: on
Block INSERT, UPDATE, DELETE, and MERGE for restricted roles.
pgedge_safesession.block_ddl
Default: on
Block DDL and other utility commands for restricted roles. Uses a whitelist approach: only explicitly allowed statements (SELECT, EXPLAIN, transaction control, SET, SHOW, LISTEN/NOTIFY, cursors, DO blocks) can execute.
pgedge_safesession.block_c_functions
Default: on
Block C-language function execution for restricted roles. By default, only volatile C functions are blocked. IMMUTABLE and STABLE C functions (such as PostGIS geometry operations or pgvector distance operators) are allowed since they promise no side effects.
pgedge_safesession.block_all_c_functions
Default: off
When enabled, blocks all C-language functions
regardless of volatility. This provides stricter
protection at the cost of blocking read-only extension
functions. Only applies when block_c_functions is on.
What is Blocked
For restricted sessions (with all protections enabled), the following operations are blocked:
- DML: INSERT, UPDATE, DELETE, MERGE (PostgreSQL 15+),
including data-modifying CTEs
(
WITH c AS (INSERT ... RETURNING ...) ...) - DDL: CREATE, ALTER, DROP, TRUNCATE, and all other schema modification commands
- COPY FROM: data import (COPY TO is allowed)
- COPY TO PROGRAM: program execution via COPY
- CREATE TABLE AS / SELECT INTO: table creation from
queries, including their
EXPLAIN ANALYZEforms - EXPLAIN ANALYZE of a writing statement: it executes the statement, so it is treated as a write
- GRANT / REVOKE: privilege modifications
- VACUUM / ANALYZE: maintenance commands
- CHECKPOINT: forces heavy I/O and emits WAL
- Two-phase commit: PREPARE TRANSACTION, COMMIT PREPARED, ROLLBACK PREPARED
- Side-effecting functions: volatile functions in
untrusted languages (C, internal, or an untrusted PL
such as
plpython3u), plus any volatile built-in (pg_catalog) function that is not on a small allow-list of built-ins confirmed to have no observable side effect (random(),clock_timestamp(), and similar). A volatile built-in is blocked by default; only functions verified harmless are exempted, so a new PostgreSQL release that adds a side-effecting built-in is blocked automatically. ADOblock orCALLin an untrusted language is blocked for the same reason. Arguments count as part of the statement, so a blocked function is rejected whether it is called directly, passed as aCALLargument, or passed as anEXECUTEparameter (including throughEXPLAIN EXECUTEandCREATE TABLE AS ... EXECUTE). A function reached only indirectly, through a view body, a row-level security policy’sUSING/WITH CHECKqual, or a domainCHECKconstraint, is rejected the same way as a direct call. For a domain this holds however the coercion that runs the constraint is reached: a cast, a prepared statement’s declared parameter type, a parameter bound over the extended query protocol, a PL/pgSQL variable’s declared type, or a function’sRETURNStype. - Fast-path function calls: the protocol behind libpq’s
PQfn, which the large-object client API is built on. It bypasses the parser and planner entirely, so the same function policy is applied to it directly. - Exclusive locks: LOCK TABLE with modes above ROW SHARE
- GUC tampering: any attempt to relax
transaction_read_onlyordefault_transaction_read_only, whether by setting one of them to a false value, by RESET or SET TO DEFAULT, or through SET TRANSACTION READ WRITE and SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE
What is Allowed
- SELECT: all read queries, including those using WHERE clauses, aggregates, and built-in functions
- EXPLAIN: query plans. Plain EXPLAIN only plans and is always allowed; EXPLAIN ANALYZE is allowed only when the statement it runs does not write.
- Transaction control: BEGIN, COMMIT, ROLLBACK, SAVEPOINT
- SET / RESET: non-protected GUC changes (e.g., work_mem)
- SET TRANSACTION: ISOLATION LEVEL and READ ONLY (tightening the transaction is allowed)
- Asserting read-only: setting
transaction_read_onlyordefault_transaction_read_onlyto on, which asks for the state that is already enforced. Clients that assert read-only on every connection they open, such as a connection pool with writes disabled, therefore work against restricted roles. - SHOW: display settings
- LISTEN / NOTIFY: notification channels
- Cursors: DECLARE, FETCH, CLOSE
- Connection-pooler resets: DISCARD ALL, DISCARD PLANS, and RESET ALL (they cannot relax the restriction, which is re-asserted per statement)
- DO blocks and CALL: in a trusted language (PL/pgSQL, SQL, …); any write inside is caught by the executor hook
- PL/pgSQL and SQL functions: read-only functions execute normally; any write attempt inside a function is caught by the executor hook, and a blocked function called from a SQL function body is rejected before the call runs
- IMMUTABLE/STABLE functions, and harmless volatile
built-ins such as
random()andclock_timestamp()
Security Model
Session User is the Anchor
The session user identity (set at connection time) is the
primary check. Even if a restricted user executes
SET ROLE to assume another role, the session user remains
restricted. This prevents bypass via role switching.
Superuser Exemption
Superusers are never restricted, even if they are members of a restricted role. The superuser check is based on the session user, so SECURITY DEFINER functions owned by superusers cannot bypass restrictions when called from a restricted session.
SECURITY DEFINER Functions
A SECURITY DEFINER function temporarily changes the effective user to the function owner. However, SafeSession checks the session user, not the effective user. This means a restricted session cannot use a SECURITY DEFINER function owned by a privileged user to perform writes.
Role Membership Inheritance
If role app_reader is listed in
pgedge_safesession.roles, then any role that is a member
of app_reader is also restricted. Membership is tested
with PostgreSQL’s is_member_of_role_nosuper(), so it
follows actual grants only.
The distinction matters because PostgreSQL otherwise reports a superuser as a member of every role in the database, with no grant behind it, which is the right answer for a privilege test and the wrong one here. Any mechanism that briefly makes the current user a superuser whilst the session user is not, such as a SECURITY DEFINER function owned by a superuser or an extension like supautils elevating a privileged role for a single command, would otherwise appear to be acting as a member of every restricted role and be blocked. Enforcement still anchors on the session user, so such elevation is not a way out of the restriction either: a restricted session stays restricted inside a superuser-owned SECURITY DEFINER function.
Restriction Changes and Cached Plans
Side-effecting function calls are detected when a statement or expression is parsed, and again when it is planned (to catch a function reached only through a view body or an RLS qual, which are substituted during query rewrite, after parse analysis), rather than when it is executed, so a plan cached before a session became restricted would otherwise be replayed without either check running again. That matters because a session can become restricted part-way through its life: the roles list can be edited and the configuration reloaded, or a role can be granted membership of a listed role, whilst sessions are open.
Becoming restricted is therefore treated as an invalidation
event, and the session’s cached plans are discarded exactly
as DISCARD PLANS does, so that everything is re-analysed
under the new state. This covers prepared statements and the
plans PL/pgSQL caches for its expressions alike. Plans built
whilst a session was restricted are left alone when the
restriction is lifted, since they have already been checked.
Belt-and-Suspenders
For every restricted session SafeSession also forces the
current transaction read-only (XactReadOnly), re-asserted
on each statement. This provides an additional layer of
protection that cannot be turned off: even if something
bypasses the hooks and attempts direct heap writes,
PostgreSQL’s own internal read-only checks will catch it.
The setting is applied without writing any session-level
GUC, so it leaves no state behind and does not interfere
with connection poolers.
Known Limitations
- The allow-list of harmless volatile built-in functions is deliberately conservative rather than exhaustive: a volatile built-in that is actually harmless but missing from the list is blocked anyway, which can surface as a restricted session being refused a read-only built-in call that a future release should add to the list. This is a usability trade-off in favour of failing closed: a newly added side-effecting built-in is blocked by default rather than silently allowed. A volatile function in a trusted language is allowed to run, and any write it performs is caught at execution instead.
- Enforcement anchors on the session user. A superuser can
still use
SET SESSION AUTHORIZATIONto become a restricted role (that is how the restriction is entered); this is by design and is not a bypass. - The roles list must be set from the server configuration
(
shared_preload_librariesis required, and the roles are normally set inpostgresql.confor withALTER SYSTEM). Setting it only for a single session withSETwould be undone by that session’sDISCARD ALLorRESET ALL. - SafeSession and Spock both install executor, utility, and planner hooks. They chain correctly, but if both are deployed the interaction has not been exhaustively tested.
- A blocked function is caught either when it appears in a
statement’s parse tree or when the executor compiles it as
part of an expression. A function PostgreSQL calls directly
through
fmgr, without compiling an expression around it, is seen by neither: a type’s own input and output functions, and an index access method’s support functions, are the cases that arise in practice. Reaching one requires a type or operator class that somebody else defined, since a restricted role cannot create either.
Example
Licence
See the Licence page for details.
Continue reading
Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.
5.1 - Changelog
Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.
All notable changes to the pgEdge SafeSession will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[1.1] - 2026-11-06
Changed
- Release workflow installs the repository client certificate before configuring the pgEdge package repositories, and verifies that the key matches the certificate, that the certificate and its issuer are within their validity periods, and that the chain issuer is the expected one
- Release workflow fails if the repository rewrite fails
- Release workflow pins the builder action by commit SHA
- Packaging no longer builds for Debian bullseye
- Packaging defaults now target v1.1
- Removed pgEdge Labs branding from the README and documentation landing page
[1.0] - 2026-08-25
Added
SECURITY.md, documenting how to report a vulnerability
[1.0-beta1] - 2026-08-21
Added
Initial release of pgEdge SafeSession
GUC
pgedge_safesession.roles(SUSET) to specify restricted rolesExecutorStart hook to block DML (INSERT, UPDATE, DELETE, MERGE) and C-language function execution
ProcessUtility hook to block DDL, COPY FROM, GRANT/REVOKE, VACUUM/ANALYZE, exclusive locks, and GUC tampering
Session-user anchored role checking: SET ROLE cannot escape restrictions
Superuser exemption: superusers are never restricted
Role membership inheritance via
is_member_of_role()Belt-and-suspenders: automatic
default_transaction_read_only = onfor restricted sessionsSECURITY DEFINER bypass prevention: session user is always checked regardless of effective user
Comprehensive regression test suite covering:
- Basic DML blocking
- SET ROLE bypass prevention
- PL/pgSQL and SQL function enforcement
- DDL blocking
- COPY FROM/TO handling
- CREATE TABLE AS / SELECT INTO blocking
- SECURITY DEFINER function enforcement
- Role membership inheritance and superuser exemption
Configurable protection layers via new SUSET GUCs:
block_dml: toggle DML blocking (default: on)block_ddl: toggle DDL blocking (default: on)block_c_functions: toggle C-language function blocking (default: on)block_all_c_functions: block all C functions regardless of volatility (default: off)
COPY TO PROGRAM blocking for restricted sessions
SET TRANSACTION READ WRITE blocking for restricted sessions
New regression tests for advanced attack vectors (PREPARE/EXECUTE, DO blocks, aggregates, WHERE clauses, SET TRANSACTION)
New regression tests for GUC toggle behavior
Changed
- C-language function blocking now only blocks VOLATILE
C functions by default. IMMUTABLE and STABLE C functions
(e.g., PostGIS geometry operations, pgvector distance
operators) are allowed. Use
block_all_c_functions = onto restore the previous behavior of blocking all C functions. - Built-in function blocking now denies any VOLATILE
built-in by default, allowing only a curated list of
built-ins confirmed to have no observable side effect
(e.g.,
random(),clock_timestamp()). Previously, built-ins were allowed by default and blocked only if their name matched a fixed denylist, regardless of volatility. PostgreSQL ships hundreds of volatile built-ins, and the old denylist covered only a small fraction of them.
Fixed
The fixes extend read-only policy enforcement to indirect function calls, transaction state and index maintenance. Role membership changes trigger checks on cached plans. After updating, test read-only pool settings, prepared queries and monitoring views with the restricted role, and review its grants.
Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.
5.2 - LICENCE()
Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.
The PostgreSQL License
Copyright (c) 2025 - 2026, pgEdge, Inc.
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL pgEdge, Inc. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF pgEdge, Inc. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
pgEdge, Inc. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN “AS IS” BASIS, AND pgEdge, Inc. HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.
6 - About this site
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
This independent PGSTY community edition collects pgEdge extension documentation, centered on Spock, with LOLOR, Snowflake, and SafeSession.
6.1 - Sources and attribution
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Versions and sources
The English edition was updated on November 21, 2026. Spock follows a pre-release tag; SafeSession and Snowflake follow release tags; LOLOR follows unreleased 1.3.0 development. Chinese covers all four component snapshots.
| Extension | English source | Channel |
|---|---|---|
| spock | d05e2e2b6a82 | v6.0.0-beta.2; pre-release |
| Spock 5.0 maintenance supplement | e710faa6fe21 | v5.0.15-rc.2 release notes and configuration changes |
| lolor | 1548836b0df0 | 1.3.0 development; latest stable v1.2.3 |
| safesession | d66225fcceef | v1.1 |
| snowflake | 9506e1bd5c1f | v2.6.1 |
Copyright and adaptations
Original notices credit pgEdge, Inc., the PostgreSQL Global Development Group, and The Regents of the University of California. Spock’s LICENSE and COPYRIGHT files use different year ranges, as do Snowflake’s notices. Each file is preserved separately and verbatim.
Adaptations include MkDocs admonition conversion, local link rewriting, stable heading IDs, navigation, Chinese translations, and editorial guides. Commands, conditions, limitations, and warnings retain their upstream meaning. No publication date is invented for undated material; snapshot_date in the manifest refers only to the pinned commit.
Every imported page links to its exact source commit. Credits are carried into HTML, print, Markdown, and LLMS outputs. See the complete license texts.
Chinese translations
The community edition has 118 English/Chinese page pairs. This review added 66 Chinese pages, revised all 32 earlier GLM-assisted drafts against the English edition, and restored the article text on four Chinese section indexes. The SafeSession manual and changelog and the LOLOR release notes describe security issues from the administrator’s perspective, including affected behavior and fixes. The import manifest records the scope of the AI-assisted self-review for each page.
Independence
This community site does not imply official pgEdge endorsement or stewardship of the upstream extensions. Product and company names identify their respective sources.
6.2 - License texts
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
The extension documentation is used under each repository’s PostgreSQL License. The files below preserve the original bytes, copyright years, and disclaimers. Scripts and configuration inherited from the former pgEdge community site retain MIT terms; OINK uses Apache-2.0. The source edition carries the PG.CENTER attribution notice. For additions in this edition, see the Mimus license.
spock
lolor
safesession
snowflake
6.3 - Maintenance and coverage
The upstream Spock manual covers 6.0.0-beta.2 and includes 5.0 maintenance notes. For deployment, configuration and recovery on Mimus, use Spock 5.0.15.
Reading and feedback
Search for function names, settings, or terms. Page controls provide light/dark modes, Paper / Slate / Ink / Terminal presets, Markdown, and print views. Paired translations support Duo View.
This site maintains documentation, not pgEdge software support. Report software issues to the relevant upstream repository. Documentation updates compare the pinned snapshot with a new revision before updating the import manifest.
Coverage
The four pinned upstream manuals have 118 English/Chinese page pairs, including section indexes, function references, release notes and source notices. Technical examples were compared with the English Markdown. Deployment procedures have not been exercised against a database in this documentation review.
Known upstream issues
- Step 3 of the two-node tutorial asks readers to edit
pg_hba.conf, but its example path ends inpostgresql.conf. Authentication rules belong in the instance’s actualpg_hba.conf;SHOW hba_file;reports its location. - The limitations page lists
CREATE TABLE...AS...under statements that are not replicated, then says that it is replicated. This contradiction is preserved from the snapshot; verify behavior for the version in use.
These issues occur in the pinned source snapshot and have not been submitted upstream by this site. Editorial notes are identified separately from the source text.