Skip to content

This is the multi-page printable view of this section.

Return to the regular view of this page

pgEdge upstream manuals

Documentation for core pgEdge extensions.

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

PG.CENTER edition · Upstream source

1 - Quick start

A reading path for a two-node Spock 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.

Read the installation prerequisites, then follow the complete two-node procedure. Spock requires PostgreSQL server patches, compatible table definitions, and authenticated connections between nodes.

Two PostgreSQL nodes accept reads and writes, with asynchronous bidirectional Spock replication.
Two-node replication. Commits complete locally; visibility on the other node depends on replication lag.

PG.CENTER edition · Upstream source

2 - Spock

The Spock extension provides multi-master (active-active) replication for pgEdge Distributed and Enterprise Postgres, versions 15, 16, 17, 18, and 19.

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.

Source version

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.

Welcome to Spock: Live Long and Prosper!

Continue reading


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.

PG.CENTER edition

2.1 - Installing and Configuring the Spock Extension

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.

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.

Warning

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:

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:

git clone https://github.com/pgEdge/spock.git

Then, apply the .diff files from the spock/patches/version directory that match your build version. To apply a patch, use the command:

patch -p1 < path_to_patch/patch_name

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:

export PATH=path_to_pg_config_file

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:

make
make install

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:

[sdouglas@lima-pg3 pg18]$ sudo -u postgres psql -U postgres -p 5432
psql (18.1)
Type "help" for help.

postgres=# SHOW data_directory;
SHOW config_file;
SHOW hba_file;

     data_directory     
------------------------
 /var/lib/pgsql/18/data
(1 row)

              config_file               
----------------------------------------
 /var/lib/pgsql/18/data/postgresql.conf
(1 row)

              hba_file              
------------------------------------
 /var/lib/pgsql/18/data/pg_hba.conf
(1 row)

Then, use your choice of editor to update the postgresql.conf file, adding required Postgres parameters to the end of the file:

wal_level = logical
max_worker_processes = 20   # see the sizing guide below
max_replication_slots = 10
max_wal_senders = 10
shared_preload_libraries = 'spock'
track_commit_timestamp = on
output_plugin_libraries = 'pgoutput, test_decoding, spock_output'
                            # only on servers that have this parameter; see below

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_slots parameter 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_origins was 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 databases in a full mesh - plus some headroom (similar sizing to max_replication_slots).

After modifying the Postgres parameters, use your OS-specific command to restart the Postgres server:

[sdouglas@lima-pg3 pg18]$ sudo systemctl restart postgresql-18
[sdouglas@lima-pg3 pg18]$ sudo systemctl status postgresql-18
● postgresql-18.service - PostgreSQL 18 database server
     Loaded: loaded (/usr/lib/systemd/system/postgresql-18.service; enabled; preset: disabled)
     Active: active (running) since Wed 2026-02-11 11:44:11 EST; 7s ago

Then, connect to the psql command line, and create the spock extension:

postgres=# CREATE EXTENSION spock;
CREATE EXTENSION
postgres=#

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:

host    all          all          <node_1_IP_address>/32    trust
host    all          all          <node_2_IP_address>/32    trust

host    replication  all          <node_1_IP_address>/32    trust
host    replication  all          <node_2_IP_address>/32    trust

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:

SELECT spock.node_create(
    node_name := 'provider1',
    dsn := 'host=providerhost port=5432 dbname=db'
);

Then, add the tables in the public schema to the default replication set:

SELECT spock.repset_add_all_tables('default', ARRAY['public']);

Once the provider node is configured, you can add subscribers. First, create the subscriber node:

SELECT spock.node_create(
    node_name := 'subscriber1',
    dsn := 'host=thishost port=5432 dbname=db'
);

Then, create the subscription which will start synchronization and replication on the subscriber node:

SELECT spock.sub_create(
    subscription_name := 'subscription1',
    provider_dsn := 'host=providerhost port=5432 dbname=db'
);

SELECT spock.sub_wait_for_sync('subscription1');

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.

PG.CENTER edition

2.2 - Creating a Spock Cluster: End-to-End Installation Guide

This guide walks you through installing Spock and creating a two-node active-active replication 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.

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.

  1. Add the pgEdge repository and install pgEdge Postgres with Spock.
  2. Configure PostgreSQL parameters for logical replication.
  3. Create the Spock extension on both nodes.
  4. Set up node definitions and bidirectional subscriptions.
  5. Enable automatic DDL replication across the cluster.
  6. Test the cluster to verify bidirectional replication works correctly.

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:

sudo dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-10.noarch.rpm

On RHEL 10, also enable the CodeReady Builder repository:

sudo subscription-manager repos --enable codeready-builder-for-rhel-10-$(arch)-rpms

On Rocky Linux 10 or AlmaLinux 10, enable the equivalent CRB repository instead:

sudo dnf config-manager --set-enabled crb

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:

sudo apt-get update
sudo apt-get install -y curl
sudo apt-get install -y gnupg2
sudo apt-get install -y lsb-release

Then, create the repository with the commands:

sudo curl -sSL https://apt.pgedge.com/repodeb/pgedge-release_latest_all.deb -o /tmp/pgedge-release.deb
sudo dpkg -i /tmp/pgedge-release.deb
sudo rm -f /tmp/pgedge-release.deb
sudo apt update
Note

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:

sudo dnf install -y pgedge-postgres18-server pgedge-postgres18-contrib pgedge-spock50_18

For Ubuntu/Debian:

sudo apt install -y pgedge-postgresql-18 pgedge-postgresql-18-spock50

On each node, initialize the PostgreSQL database cluster.

For RHEL/Rocky Linux/AlmaLinux:

sudo /usr/pgsql-18/bin/postgresql-18-setup initdb
sudo systemctl enable postgresql-18
sudo systemctl start postgresql-18

For Ubuntu/Debian:

sudo /usr/lib/postgresql/18/bin/initdb -D /var/lib/postgresql/18/data
sudo systemctl enable postgresql-18
sudo systemctl start postgresql-18

In the following example, the psql command connects to PostgreSQL to verify the installation:

sudo -u postgres psql -U postgres -p 5432

Once connected, confirm that you can see the configuration file locations.

In the following example, the SHOW commands display the PostgreSQL configuration file locations:

postgres=# SHOW data_directory;
     data_directory
------------------------
 /var/lib/pgsql/18/data
(1 row)

postgres=# SHOW config_file;
              config_file
----------------------------------------
 /var/lib/pgsql/18/data/postgresql.conf
(1 row)

postgres=# SHOW hba_file;
              hba_file
------------------------------------
 /var/lib/pgsql/18/data/pg_hba.conf
(1 row)

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.

  1. Download PostgreSQL source code from the Postgres project and navigate to the source directory.

  2. Clone the Spock repository with the following command:

    git clone https://github.com/pgEdge/spock.git
  3. Apply the version-specific patches with the following command:

    patch -p1 < spock/patches/version/patch_name
  4. Configure, build, and install PostgreSQL as described in the Postgres documentation.

  5. Add the pg_config file location to your PATH with this command:

    export PATH=path_to_pg_config_file
  6. Install the jansson library (required for Spock).

  7. Build and install Spock with the following commands:

    cd spock
    make
    make install

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:

 wal_level = logical
max_worker_processes = 20   # see the sizing guide
max_replication_slots = 10  # two per subscriber, per replicated database,
                            # plus one per physical standby; 10 covers a
                            # four-node mesh replicating one database
max_wal_senders = 10        # keep equal to max_replication_slots
shared_preload_libraries = 'spock'
track_commit_timestamp = on # needed for conflict resolution
listen_addresses = '*'
output_plugin_libraries = 'pgoutput, test_decoding, spock_output'
                            # only on servers that have this parameter; see below
Sizing max_worker_processes

This 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.

Note

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
  • PostgreSQL 15-17: The max_replication_slots parameter 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_origins separately 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 databases in 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:

sudo systemctl restart postgresql-18
sudo systemctl status postgresql-18

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:

# Regular connections
host    all          all          <node_1_IP_address>/32    trust
host    all          all          <node_2_IP_address>/32    trust
host    all          all          <subnet_address>/24     trust

# Replication connections
host    replication  all          <node_1_IP_address>/32    trust
host    replication  all          <node_2_IP_address>/32    trust
Warning

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):

SELECT pg_reload_conf();

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:

sudo -u postgres psql -U postgres -p 5432

postgres=# CREATE EXTENSION spock;
CREATE EXTENSION
postgres=#
Warning

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.

  1. Create the node definition with the following command:

    SELECT spock.node_create(
        node_name := 'n1',
        dsn := 'host=<n1_ip_address> port=<n1_port> dbname=<db_name>'
    );
  2. Add tables to the default replication set with this command:

    SELECT spock.repset_add_all_tables('default', ARRAY['public']);

    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.

  1. Create the node definition with the following command:

    SELECT spock.node_create(
        node_name := 'n2',
        dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>'
    );
  2. Add tables to the default replication set with this command:

    SELECT spock.repset_add_all_tables('default', ARRAY['public']);
  3. Create the subscription from n2 to n1 with these commands:

    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 Node 1 (n1)

Create the reverse subscription from n1 to n2 with the following commands:

SELECT spock.sub_create(
    subscription_name := 'sub_n1_n2',
    provider_dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>'
);

SELECT spock.sub_wait_for_sync('sub_n1_n2');

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:

ALTER SYSTEM SET spock.enable_ddl_replication = on;
ALTER SYSTEM SET spock.include_ddl_repset = on;
SELECT pg_reload_conf();

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:

SELECT * FROM spock.node;

Expected output:

postgres=# SELECT * FROM spock.node;
-[ RECORD 1 ]----
node_id   | 26863
node_name | n2
location  |
country   |
info      |
-[ RECORD 2 ]----
node_id   | 49708
node_name | n1
location  |
country   |
info      |

Then, use the following command to verify that subscriptions are active and replicating.

In the following example, the SELECT command displays the subscription status:

SELECT * FROM spock.sub_show_status();

Expected output:

 postgres=# SELECT * FROM spock.sub_show_status();
-[ RECORD 1 ]-----+--------------------------------------------------------------------
subscription_name | sub_n1
status            | replicating
provider_node     | n2
provider_dsn      | host=192.168.105.11 dbname=postgres user=postgres password=password
slot_name         | spk_postgres_n2_sub_n1
replication_sets  | {default,default_insert_only,ddl_sql}
forward_origins   |

The status field should display replicating.

Test Replication

Perform a simple replication test using the following steps.

  1. On n1, create a test table with the following commands:

    CREATE TABLE test (
        id SERIAL PRIMARY KEY,
        message TEXT
    );
    
    INSERT INTO test (message) VALUES ('Hello from n1');
  2. On n2, verify the table exists and contains the data with this query:

    SELECT * FROM test;

    Expected output:

    postgres=# SELECT * FROM test;
    -[ RECORD 1 ]------
    id      | 1
    message | Hello from n1
  3. On n2, insert a new row with the following command:

    INSERT INTO test (message) VALUES ('Hello from n2');
  4. On n1, verify both rows are present with this query:

    SELECT * FROM test;

    Expected output:

    postgres=# SELECT * FROM test;
    -[ RECORD 1 ]------
    id      | 1
    message | Hello from n1
    -[ RECORD 2 ]------
    id      | 2
    message | Hello from n2

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.

Troubleshooting

If you encounter issues, review the following common problems and solutions.

  • Check the pg_hba.conf entries and ensure the nodes can connect to each other if replication is not starting.
  • Verify that max_replication_slots and max_wal_senders are 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:


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.

PG.CENTER edition

2.3 - Using Spock to Create a Two-Node Cluster

After installing and initializing Postgres and creating the Spock Extension, you can use the following steps to configure 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.

Editorial note

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.

  1. Connect to each node, and use the following commands to initialize a cluster:

    sudo /usr/pgsql-17/bin/postgresql-17-setup initdb

    sudo systemctl enable postgresql-17

  2. Use your choice of editor to open the postgresql.conf file (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 = 20

    max_replication_slots = 10

    max_wal_senders = 10

    shared_preload_libraries = 'spock'

    track_commit_timestamp = on

    These 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_processes is 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.

  3. Edit the pg_hba.conf file (use SHOW hba_file; to find its path) and allow connections between n1 and n2; 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 trust

    local replication all trust

    host replication all 0.0.0.0/0 trust

  4. Use the spock.node_create command to create the provider and subscriber nodes; on n1, 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>');

  5. On n1, use the spock.repset_add_all_tables command to add the tables in the public schema to the default replication set. If you are working in another schema, customize this command as needed:

    SELECT spock.repset_add_all_tables('default', ARRAY['public']);

  6. On n2, use the spock.sub_create command to create the subscription between n2 and n1; the name of the subscription is sub_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');

  7. On n1, create a corresponding subscription to n2 named sub_n1_n2:

    SELECT spock.sub_create (subscription_name := 'sub_n1_n2', provider_dsn := 'host=<n2_ip_address> port=<n2_port> dbname=<db_name>');

  8. 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();

  9. Then, check the status of each node:

  SELECT * FROM spock.node;
   node_id | node_name | location | country | info
  ---------+-------------+----------+---------+------
   22201 | subscriber1 | | |
   53107 | provider1 | | |
  (2 rows)

  SELECT * FROM spock.sub_show_status();
   subscription_name | status | provider_node | provider_dsn | slot_name | replication_sets | forward_origins
  -------------------+-------------+---------------+------------------------------------------+--------------------------------------+---------------------------------------+-----------------
   subscription1 | replicating | provider1 | host=localhost port=5432 dbname=postgres | spk_postgres_provider1_subscription1 | {default,default_insert_only,ddl_sql} |
  (1 row)

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.

PG.CENTER edition

2.4 - Sizing Postgres Resources for Spock

Spock replication consumes three separate, independently-configured Postgres resources: background worker slots, walsender slots, and replication slots/origins.

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.

Warning

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

ProcessHow manyCounts against
Supervisor1 per instance, always runningmax_worker_processes
Slot sync worker1 per instancemax_worker_processes
Manager1 per connectable database in the instancemax_worker_processes
Apply worker1 per enabled subscriptionmax_worker_processes
Table sync workerat most 1 concurrently per subscriptionmax_worker_processes
Walsender1 per subscription streaming from this node, plus 1 more per subscription during table syncmax_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.

PostgreSQLSupplied byCharged to max_worker_processes
15, 16Spock’s spock_failover_slots background workerYes
17Either, depending on sync_replication_slotsYes - Spock registers its worker regardless, and it stands down when the native one is enabled
18+PostgreSQL’s native slotsync workerNo - 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:

  • N is the number of Spock nodes in the cluster.
  • D is the number of databases in the instance with datallowconn = true, including postgres and template1 — not just the databases participating in replication.
  • R is the number of databases in this instance that actually participate in Spock replication (R <= D). It is 1 in most deployments.
  • S is the total number of enabled subscriptions across all databases in the instance. In a fully-meshed cluster of N nodes each replicating the same R databases, S = R * (N - 1). With a single replicated database that reduces to the familiar S = N - 1.
Warning

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.

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:

ClusterSpock WorkersTotal Workers
2-node720
3-node920
4-node1124
5-node1324
8-node1932

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.

Default values

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.

Why the two values are equal

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.

# Background workers:
#   1 supervisor + 1 slot sync + 3 managers + 2 apply + 2 table sync = 9
#   + 8 max_parallel_workers + 2 headroom = 19; 20 to match the table above
max_worker_processes = 20

# Slots and walsenders, set equal:
#   (2 x 1 database x 2 subscribers) + 1 physical standby + 2 headroom = 7;
#   This is lower than the default of 10, so do not reduce.
max_replication_slots = 10
max_wal_senders = 10

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.

# Background workers:
#   1 supervisor + 1 slot sync + 4 managers + 8 apply + 8 table sync = 22
#   + 8 max_parallel_workers + 2 headroom = 32
max_worker_processes = 32

# Slots and walsenders, set equal:
#   (2 x 2 databases x 4 subscribers) + 2 standbys + 2 headroom = 20
max_replication_slots = 20
max_wal_senders = 20

Verifying Your Configuration

List the Spock workers currently running on a node:

SELECT pid, backend_type, datname
  FROM pg_stat_activity
 WHERE backend_type LIKE 'spock%'
 ORDER BY backend_type;

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:

SELECT current_setting('max_worker_processes')::int AS worker_limit,
       count(*) AS in_use
  FROM pg_stat_activity
 WHERE backend_type NOT IN (
         'client backend', 'walsender', 'autovacuum launcher',
         'autovacuum worker', 'checkpointer', 'background writer',
         'walwriter', 'walreceiver', 'walsummarizer', 'archiver',
         'startup', 'io worker', 'standalone backend');

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.

PG.CENTER edition

2.5 - Configuring Spock

Add the following postgresql.conf settings on each node in your Spock replication scenario before creating 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.

Add the following postgresql.conf settings on each node in your Spock replication scenario before creating the Spock extension:

wal_level = 'logical'
max_worker_processes = 20   # supervisor + slot sync worker + one per
                            # database + one per subscription + sync workers,
                            # and shared with parallel query - see the
                            # sizing guide
max_replication_slots = 10  # two per subscriber, per replicated database,
                            # plus one per physical standby; 10 covers a
                            # four-node mesh replicating one database
max_wal_senders = 10        # keep equal to max_replication_slots
shared_preload_libraries = 'spock'
track_commit_timestamp = on # needed for conflict resolution
output_plugin_libraries = 'pgoutput, test_decoding, spock_output'
                            # only on servers that have this parameter; see below

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_libraries

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. Its default, 'pgoutput, test_decoding', does not include spock_output, so on such a server logical decoding fails with:

ERROR:  library "spock_output" may not be used as an output plugin

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:

SELECT current_setting('output_plugin_libraries', true);

A NULL result means the parameter does not exist and must not be set. You can also ask the binary, with no server running:

postgres --describe-config | grep '^output_plugin_libraries'

After modifying the parameters and restarting the Postgres server with your OS-specific restart command, connect with psql and create the Spock extension:

[pg18]$ sudo -u postgres psql -U postgres -p 5432
psql (18.1)
Type "help" for help.

postgres=# CREATE EXTENSION spock;
CREATE 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):

SELECT pg_reload_conf();

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 each INSERT/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

Note

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) - set spock.exception_behaviour to transdiscard to instruct the server to discard a transaction if any operation within that transaction returns an ERROR.
  • discard - set spock.exception_behaviour to discard to continue processing (and replicating) without interrupting server use; the server will commit any operation (any portion of a transaction) that does not return an ERROR statement.
  • sub_disable - set spock.exception_behaviour to sub_disable to 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 the spock.sub_alter_skiplsn function 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) - set spock.exception_logging to all to instruct the server to record all transactions that contain one or more failed operations in the spock.exception_log table; note that this setting will log all operations that are part of a transaction if one operation fails.
  • discard - add a row to the spock.exception_log table 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:

wal_sender_timeout = '5min'

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.apply_idle_timeout = 300

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:

SET spock.sync_timeout = '2h';
CALL spock.add_node(...);

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.sync_timeout = 0

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.

spock.read_retry_count = 5

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:

PostgreSQLSlot sync mechanismSpock worker
15, 16Spock built-in spock_failover_slots workerRuns on every node
17Spock worker OR native sync_replication_slotsSpock 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:

SELECT pg_create_physical_replication_slot('physical_slot_name');

Primary (postgresql.conf):

# Hold logical walsenders back until the standby has confirmed the changes.
synchronized_standby_slots = 'physical_slot_name'

Standby (postgresql.conf):

sync_replication_slots = on                      # enable the native slotsync worker
hot_standby_feedback   = on                      # required; pins the primary's catalog vacuum
primary_slot_name      = 'physical_slot_name'    # the physical slot created above
primary_conninfo       = 'host=<primary_host> dbname=<dbname> ...'   # must include dbname

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).

spock.synchronize_slot_names = 'name_like:%%'

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.drop_extra_slots = on

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.primary_dsn = ''

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.

spock.pg_standby_slot_names = 'physical_slot_1,physical_slot_2'

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.

spock.standby_slots_min_confirmed = -1

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).

spock.failover_slots_naptime = 1000

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_feedback_naptime = 10000

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_recreate_invalidated = on

spock.failover_slots_database

Note

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.failover_slots_database = 'pgedge'

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:

-- Rows resolved from a locally-originated conflict (origin = 0)
SELECT * FROM spock.resolutions WHERE local_origin = 0;

-- Rows where origin metadata was unavailable at resolution time
SELECT * FROM spock.resolutions WHERE local_origin IS NULL;

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’s DEBUG1/DEBUG2 messages keep their native (normally silent) levels.
  • debug1 - promote Spock’s DEBUG1 messages to LOG.
  • debug2 - promote both Spock’s DEBUG1 and DEBUG2 messages to LOG.

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.resolutions_retention_days = 100

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.

PG.CENTER edition

2.6 - Managing a Spock Installation

The Spock extension is a powerful addition to any PostgreSQL installation; management features of the Spock extension allow you to seamlessly:

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:


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.

PG.CENTER edition

2.6.1 - Automatic DDL Replication

The spock extension can automatically replicate DDL statements.

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_replication enables replication of ddl statements through the default replication set. Some DDL statements are intentionally not replicated (like CREATE DATABASE). Other DDL statements are replicated, but can lead to replication issues (like the CREATE TABLE... AS... statement). In the case of CREATE 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_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 also modify which replication set the table is a member of. Setting a table to unlogged removes the table from replication. Detaching a partition will not remove a table from replication.

  • spock.allow_ddl_from_functions enables spock to automatically replicate DDL statements that are called within functions. Set spock.allow_ddl_from_functions to off if each function is expected to execute on every node. When set to off, statements replicated from functions adhere to the same rule described for include_ddl_repset. If a table possesses a primary key, it will be added into the default replication set; alternatively, they will be added to the default_insert_only replication 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, default false. When set to true, 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.

Note

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=INFO set.

  • 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_repset is 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.

PG.CENTER edition

2.6.2 - Automatically Assigning Tables to Replication Sets

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.

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:

ALTER SYSTEM SET spock.enable_ddl_replication=off;
ALTER SYSTEM SET spock.include_ddl_repset=off;
ALTER SYSTEM SET spock.allow_ddl_from_functions=off;
SELECT pg_reload_conf();

You can use the event trigger facility to describe rules that define replication sets for newly created tables. For example:

    CREATE OR REPLACE FUNCTION spock_assign_repset()
    RETURNS event_trigger AS $$
    DECLARE obj record;
    BEGIN
        FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands()
        LOOP
            IF obj.object_type = 'table' THEN
                IF obj.schema_name = 'config' THEN
                    PERFORM spock.repset_add_table('configuration', obj.objid);
                ELSIF NOT obj.in_extension THEN
                    PERFORM spock.repset_add_table('default', obj.objid);
                END IF;
            END IF;
        END LOOP;
    END;
    $$ LANGUAGE plpgsql;

    CREATE EVENT TRIGGER spock_assign_repset_trg
        ON ddl_command_end
        WHEN TAG IN ('CREATE TABLE', 'CREATE TABLE AS')
        EXECUTE FUNCTION spock_assign_repset();

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.

PG.CENTER edition

2.6.3 - Filtering

Spock allows row based filtering on both the provider side and the subscriber side.

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.

PG.CENTER edition

2.6.4 - Replicating Partitioned Tables

By default, when you add a partitioned table to a Spock replication set, Spock will include all the current partitions of a partitioned 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.

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.

Note

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.

Note

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.

PG.CENTER edition

2.6.5 - Using LOLOR to Manage Large objects

PostgreSQL’s logical decoding facility does not support decoding changes to large objects; we recommend instead using the LOLOR extension 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.

PG.CENTER edition

2.6.6 - Using Spock in Read-Only Mode

Spock supports operating a node 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:

ValueDescription
offNo restrictions. All users may write. This is the default.
localNon-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.)
allNon-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:

-- Block non-superuser local writes; inbound replication continues
ALTER SYSTEM SET spock.readonly = 'local';
SELECT pg_reload_conf();

-- Block all non-superuser writes including replication
ALTER SYSTEM SET spock.readonly = 'all';
SELECT pg_reload_conf();

-- Restore normal operation
ALTER SYSTEM SET spock.readonly = 'off';
SELECT pg_reload_conf();

To set the mode for the current session only:

SET spock.readonly TO local;

To query the current status:

SHOW spock.readonly;

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:

BEGIN;
SELECT spock.repair_mode(true);

-- Perform repair DML/DDL here...

SELECT spock.repair_mode(false);
COMMIT;

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.readonly parameter.
  • 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.

PG.CENTER edition

2.6.7 - Using Spock with Snowflake Sequences

The Snowflake extension provides a sequence-based unique ID solution to replace the Postgres built-in bigserial data type in distributed replication clusters.

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.

Note

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):

acctg=# SELECT id, snowflake.format(id), customer, invoice FROM orders;
         id         |                          format                           |        customer        |  invoice
--------------------+-----------------------------------------------------------+------------------------+------------
                  1 | {"id": 1, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Chesterfield Schools   | art_9338
                  2 | {"id": 2, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Chesterfield Schools   | math_9663
 135824181823537153 | {"id": 1, "ts": "2024-01-10 14:16:48.438-05", "count": 0} | Prince William Schools | math_8330
 135824609030176769 | {"id": 1, "ts": "2024-01-10 14:18:30.292-05", "count": 0} | Fluvanna Schools       | art_9447
(4 rows)
Version of the example

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.

PG.CENTER edition

2.7 - Adding a Node to a Replicating Cluster

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:

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.

PG.CENTER edition

2.7.1 - Modifying a Cluster with Zodan

Zodan provides tools to add or remove a node 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.

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.).

Note

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.

Note

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_schema parameter, 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.

PG.CENTER edition

2.7.1.1 - Tutorial: Adding a Node to a Cluster with Zero Downtime

In this detailed walkthrough, we add a fourth node to a three-node 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.

Warning

Important Prerequisites and Warnings

  • The new node should not be accessible to users while adding the node.
  • Disable auto_ddl on 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 dblink extension must be installed on the node from which commands like SELECT 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 with spock.sync_timeout, as described in Setting the Synchronisation Timeout below. When following the manual workflow below, you call spock.wait_for_sync_event() directly and supply your own timeout (the examples use 1200 seconds), so neither the default nor spock.sync_timeout applies.

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 spock to the shared_preload_libraries parameter in the postgresql.conf file.
  • Restart the server to update the configuration.
  • Use the CREATE EXTENSION spock command 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:

# Initialize database
initdb -D /path/to/data

# Start Postgres
pg_ctl -D /path/to/data start

# Create database and user
psql -c "CREATE DATABASE inventory;"
psql -c "CREATE USER pgedge WITH PASSWORD '1safepassword';"
psql -c "GRANT ALL ON DATABASE inventory TO pgedge;"

# Install Spock extension
psql -d inventory -c "CREATE EXTENSION spock;"
psql -d inventory -c "CREATE EXTENSION dblink;"

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:

psql -h 127.0.0.1 -p 5435 -d inventory -U pgedge

Load the Zodan procedures with the following command:

\i /path/to/zodan.sql

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:

CALL spock.add_node(
    src_node_name := 'n1',
    src_dsn := 'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=1safepassword',
    new_node_name := 'n4',
    new_node_dsn := 'host=127.0.0.1 dbname=inventory port=5435 user=pgedge password=1safepassword',
    verb := true,
    new_node_location := 'Los Angeles',
    new_node_country := 'USA',
    new_node_info := '{"key": "value"}'::jsonb
);

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:

SET spock.sync_timeout = '2h';

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.

Note

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:

-- Check source node version
SELECT version
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=1safepassword',
    'SELECT extversion FROM pg_extension WHERE extname = ''spock'''
) AS t(version text);
-- Expected: matches the version installed on every node in the cluster

-- Check new node version
SELECT version
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=pgedge password=1safepassword',
    'SELECT extversion FROM pg_extension WHERE extname = ''spock'''
) AS t(version text);
-- Expected: matches the version installed on every node in the cluster

-- Check all existing cluster nodes (n2, n3)
SELECT node_name, version
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'SELECT n.node_name,
            (SELECT extversion FROM pg_extension WHERE extname = ''spock'') as version
     FROM spock.node n'
) AS t(node_name text, version text);

-- Expected output: every node reports the same Spock version, e.g.
--  node_name |  version
-- -----------+----------
--  n1        | 5.0.6
--  n2        | 5.0.6
--  n3        | 5.0.6

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.
Note

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:

SELECT 1
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT 1'
) AS t(dummy int);
-- If no error, database exists

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:

SELECT count(*)
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT count(*) FROM pg_tables
     WHERE schemaname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'', ''spock'')
     AND schemaname NOT LIKE ''pg_temp_%''
     AND schemaname NOT LIKE ''pg_toast_temp_%'''
) AS t(count integer);
-- Expected: 0

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:

-- On orchestrator node (connected to n1)
SELECT count(*) FROM spock.node WHERE node_name = 'n4';
-- Expected: 0

Confirm that n4 Contains No Subscriptions

In the following example, the query checks whether n4 has any existing subscriptions:

SELECT count(*)
FROM spock.subscription s
JOIN spock.node n ON s.sub_origin = n.node_id
WHERE n.node_name = 'n4';
-- Expected: 0

Confirm that n4 Contains No Replication Sets

In the following example, the query checks whether n4 has any replication sets:

SELECT count(*)
FROM spock.replication_set rs
JOIN spock.node n ON rs.set_nodeid = n.node_id
WHERE n.node_name = 'n4';
-- Expected: 0

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.”
Note

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:

-- Via dblink to n4
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT spock.node_create(
        node_name := ''n4'',
        dsn := ''host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword'',
        location := ''Los Angeles'',
        country := ''USA'',
        info := ''{\"key\": \"value\"}''::jsonb
    )'
) AS t(node_id oid);

-- Expected output:
--  node_id
-- ---------
--    16389

Confirm the Initial Node Count

In the following example, the query retrieves the current node count:

SELECT count(*)
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'SELECT count(*) FROM spock.node'
) AS t(count integer);
-- Expected: 4 (n1, n2, n3, n4)

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.
Note

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:

SELECT n.node_name, i.if_dsn
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'SELECT n.node_name, i.if_dsn
     FROM spock.node n
     JOIN spock.node_interface i ON n.node_id = i.if_nodeid'
) AS t(node_name text, if_dsn text);

-- Expected output:
--  node_name |                              if_dsn
-- -----------+------------------------------------------------------------------
--  n1        | host=127.0.0.1 dbname=inventory port=5432 user=alice password=...
--  n2        | host=127.0.0.1 dbname=inventory port=5433 user=alice password=...
--  n3        | host=127.0.0.1 dbname=inventory port=5434 user=alice password=...
--  n4        | host=127.0.0.1 dbname=inventory port=5435 user=alice password=...

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:

-- Trigger sync event on n2
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
    'SELECT spock.sync_event()'
) AS t(sync_lsn pg_lsn);
-- Returns: 0/1A7D1E0

-- Store in temp table
CREATE TEMP TABLE IF NOT EXISTS temp_sync_lsns (
    origin_node text PRIMARY KEY,
    sync_lsn text NOT NULL
);

INSERT INTO temp_sync_lsns (origin_node, sync_lsn)
VALUES ('n2', '0/1A7D1E0')
ON CONFLICT (origin_node) DO UPDATE SET sync_lsn = EXCLUDED.sync_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:

-- On n2
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
    'SELECT slot_name, lsn
     FROM pg_create_logical_replication_slot(
         ''spk_inventory_n2_sub_n2_n4'',
         ''spock_output''
     )'
) AS t(slot_name text, lsn pg_lsn);

-- Expected output:
--         slot_name         |    lsn
-- --------------------------+------------
--  spk_inventory_n2_sub_n2_n4 | 0/1A7D1E8

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.

-- On n4
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT spock.sub_create(
        subscription_name := ''sub_n2_n4'',
        provider_dsn := ''host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword'',
        replication_sets := ARRAY[''default'', ''default_insert_only'', ''ddl_sql''],
        synchronize_structure := false,
        synchronize_data := false,
        forward_origins := ARRAY[]::text[],
        apply_delay := ''0''::interval,
        enabled := false,
        force_text_transfer := false,
        skip_schema := ARRAY[]::text[]
    )'
) AS t(subscription_id oid);

Repeat the Previous Steps for n3 to n4

In the following example, the commands perform the same operations for n3 to n4:

-- Trigger sync event on n3
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
    'SELECT spock.sync_event()'
) AS t(sync_lsn pg_lsn);
-- Returns: 0/1B8E2F0

-- Store LSN
INSERT INTO temp_sync_lsns (origin_node, sync_lsn)
VALUES ('n3', '0/1B8E2F0')
ON CONFLICT (origin_node) DO UPDATE SET sync_lsn = EXCLUDED.sync_lsn;

-- Create replication slot on n3
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
    'SELECT slot_name, lsn
     FROM pg_create_logical_replication_slot(
         ''spk_inventory_n3_sub_n3_n4'',
         ''spock_output''
     )'
) AS t(slot_name text, lsn pg_lsn);

-- Create disabled subscription on n4 from n3
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT spock.sub_create(
        subscription_name := ''sub_n3_n4'',
        provider_dsn := ''host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword'',
        replication_sets := ARRAY[''default'', ''default_insert_only'', ''ddl_sql''],
        synchronize_structure := false,
        synchronize_data := false,
        forward_origins := ARRAY[]::text[],
        apply_delay := ''0''::interval,
        enabled := false,
        force_text_transfer := false,
        skip_schema := ARRAY[]::text[]
    )'
) AS t(subscription_id oid);

Configure Cross-Node Replication

Edition note on slot ownership

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.
Note

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:

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
    'SELECT slot_name, lsn
     FROM pg_create_logical_replication_slot(
         ''spk_inventory_n2_sub_n4_n2'',
         ''spock_output''
     )'
) AS t(slot_name text, lsn pg_lsn);

Create a Slot on n3 for a Future Subscription (sub_n4_n3)

In the following example, the command creates a replication slot on n3:

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
    'SELECT slot_name, lsn
     FROM pg_create_logical_replication_slot(
         ''spk_inventory_n3_sub_n4_n3'',
         ''spock_output''
     )'
) AS t(slot_name text, lsn pg_lsn);

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.
Note

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:

-- Trigger sync event on n2
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
    'SELECT spock.sync_event()'
) AS t(sync_lsn pg_lsn);
-- Returns: 0/1C9F400

-- Wait for sync event on n1
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'CALL spock.wait_for_sync_event(true, ''n2'', ''0/1C9F400''::pg_lsn, 1200)'
) AS t(result bool);

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:

-- Trigger sync event on n3
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
    'SELECT spock.sync_event()'
) AS t(sync_lsn pg_lsn);
-- Returns: 0/1D0E510

-- Wait for sync event on n1
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'CALL spock.wait_for_sync_event(true, ''n3'', ''0/1D0E510''::pg_lsn, 1200)'
) AS t(result bool);

Copy the Source to New Subscription

This is the big data copy step.

  • Create an enabled subscription on n4 from n1 with synchronize_structure=true and synchronize_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_schema array with these schema names. When Spock syncs the structure, Spock excludes these schemas using pg_dump --exclude-schema. When copying data, Spock also skips tables in these schemas. This prevents overwriting local tools or extensions on n4.
Note

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:

SELECT string_agg(schema_name, ',') as schemas
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT schema_name
     FROM information_schema.schemata
     WHERE schema_name NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'', ''spock'', ''public'')
     AND schema_name NOT LIKE ''pg_temp_%''
     AND schema_name NOT LIKE ''pg_toast_temp_%'''
) AS t(schema_name text);
-- Returns: 'mgmt_tools,monitoring' (if any exist)

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
-- Build skip_schema array based on detected schemas
-- If schemas found: ARRAY['mgmt_tools','monitoring']::text[]
-- If no schemas: ARRAY[]::text[]

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT spock.sub_create(
        subscription_name := ''sub_n1_n4'',
        provider_dsn := ''host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword'',
        replication_sets := ARRAY[''default'', ''default_insert_only'', ''ddl_sql''],
        synchronize_structure := true,
        synchronize_data := true,
        forward_origins := ARRAY[]::text[],
        apply_delay := ''0''::interval,
        enabled := true,
        force_text_transfer := false,
        skip_schema := ARRAY[''mgmt_tools'',''monitoring'']::text[]
    )'
) AS t(subscription_id oid);

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_event on 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.
Note

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:

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'SELECT spock.sync_event()'
) AS t(sync_lsn pg_lsn);
-- Returns: 0/1E1F620

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:

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'CALL spock.wait_for_sync_event(true, ''n1'', ''0/1E1F620''::pg_lsn, 1200)'
) AS t(result bool);

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.

Warning

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.

Note

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:

SELECT commit_timestamp
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT commit_timestamp
     FROM spock.lag_tracker
     WHERE origin_name = ''n2'' AND receiver_name = ''n4'''
) AS t(commit_timestamp timestamp);
-- Returns: 2025-01-15 10:30:45.123456

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:

-- Get LSN from commit timestamp
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
    'WITH lsn_cte AS (
         SELECT spock.get_lsn_from_commit_ts(
             ''spk_inventory_n2_sub_n2_n4'',
             ''2025-01-15 10:30:45.123456''::timestamp
         ) AS lsn
     )
     SELECT pg_replication_slot_advance(''spk_inventory_n2_sub_n2_n4'', lsn)
     FROM lsn_cte'
) AS t(slot_name name, end_lsn pg_lsn);

Repeat for n3 to n4

In the following example, the commands perform the same operations for n3 to n4:

-- Get commit timestamp
SELECT commit_timestamp
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT commit_timestamp
     FROM spock.lag_tracker
     WHERE origin_name = ''n3'' AND receiver_name = ''n4'''
) AS t(commit_timestamp timestamp);
-- Returns: 2025-01-15 10:30:46.789012

-- Advance the slot on n3
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
    'WITH lsn_cte AS (
         SELECT spock.get_lsn_from_commit_ts(
             ''spk_inventory_n3_sub_n3_n4'',
             ''2025-01-15 10:30:46.789012''::timestamp
         ) AS lsn
     )
     SELECT pg_replication_slot_advance(''spk_inventory_n3_sub_n3_n4'', lsn)
     FROM lsn_cte'
) AS t(slot_name name, end_lsn pg_lsn);

Enable Disabled Subscriptions

In this step, activate subscriptions from replica nodes to new node using stored sync LSNs.

Note

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:

-- Enable the subscription
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT spock.sub_enable(
        subscription_name := ''sub_n2_n4'',
        immediate := true
    )'
) AS t(result bool);

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:

-- Retrieve stored LSN
SELECT sync_lsn FROM temp_sync_lsns WHERE origin_node = 'n2';
-- Returns: 0/1A7D1E0

-- Wait for that sync event on n4
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'CALL spock.wait_for_sync_event(true, ''n2'', ''0/1A7D1E0''::pg_lsn, 1200)'
) AS t(result bool);

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:

-- Check subscription status on n4
SELECT subscription_name, status, provider_node
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT subscription_name, status, provider_node
     FROM spock.sub_show_status()
     WHERE subscription_name = ''sub_n2_n4'''
) AS t(subscription_name text, status text, provider_node text);

-- Expected output:
--  subscription_name |   status    | provider_node
-- -------------------+-------------+---------------
--  sub_n2_n4         | replicating | n2

Repeat the Steps for sub_n3_n4

In the following example, commands enable the subscription and verify replication:

-- Enable subscription
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT spock.sub_enable(
        subscription_name := ''sub_n3_n4'',
        immediate := true
    )'
) AS t(result bool);

-- Retrieve stored LSN
SELECT sync_lsn FROM temp_sync_lsns WHERE origin_node = 'n3';
-- Returns: 0/1B8E2F0

-- Wait for stored sync event
SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'CALL spock.wait_for_sync_event(true, ''n3'', ''0/1B8E2F0''::pg_lsn, 1200)'
) AS t(result bool);

-- Verify status
SELECT subscription_name, status, provider_node
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
    'SELECT subscription_name, status, provider_node
     FROM spock.sub_show_status()
     WHERE subscription_name = ''sub_n3_n4'''
) AS t(subscription_name text, status text, provider_node text);

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:

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'SELECT spock.sub_create(
        subscription_name := ''sub_n4_n1'',
        provider_dsn := ''host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword'',
        replication_sets := ARRAY[''default'', ''default_insert_only'', ''ddl_sql''],
        synchronize_structure := false,
        synchronize_data := false,
        forward_origins := ARRAY[]::text[],
        apply_delay := ''0''::interval,
        enabled := true,
        force_text_transfer := false,
        skip_schema := ARRAY[]::text[]
    )'
) AS t(subscription_id oid);

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:

SELECT *
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
    'SELECT spock.sub_create(
        subscription_name := ''sub_n4_n2'',
        provider_dsn := ''host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword'',
        replication_sets := ARRAY[''default'', ''default_insert_only'', ''ddl_sql''],
        synchronize_structure := false,
        synchronize_data := false,
        forward_origins := ARRAY[]::text[],
        apply_delay := ''0''::interval,
        enabled := true,
        force_text_transfer := false,
        skip_schema := ARRAY[]::text[]
    )'
) AS t(subscription_id oid);

Create sub_n4_n3 on n3

The following command creates the subscription on n3:

SELECT * FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
    'SELECT spock.sub_create(
        subscription_name := ''sub_n4_n3'',
        provider_dsn := ''host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword'',
        replication_sets := ARRAY[''default'', ''default_insert_only'', ''ddl_sql''],
        synchronize_structure := false,
        synchronize_data := false,
        forward_origins := ARRAY[]::text[],
        apply_delay := ''0''::interval,
        enabled := true,
        force_text_transfer := false,
        skip_schema := ARRAY[]::text[]
    )'
) AS t(subscription_id oid);

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:

-- Monitor lag from n1 → n4 on n4
DO $$
DECLARE
    lag_interval interval;
    lag_bytes bigint;
BEGIN
    LOOP
        SELECT now() - commit_timestamp, replication_lag_bytes
        INTO lag_interval, lag_bytes
        FROM dblink(
            'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
            'SELECT now() - commit_timestamp, replication_lag_bytes
             FROM spock.lag_tracker
             WHERE origin_name = ''n1'' AND receiver_name = ''n4'''
        ) AS t(lag_interval interval, lag_bytes bigint);

        RAISE NOTICE 'n1 → n4 lag: % (bytes: %)',
            COALESCE(lag_interval::text, 'NULL'),
            COALESCE(lag_bytes::text, 'NULL');

        EXIT WHEN lag_interval IS NOT NULL
                  AND (extract(epoch FROM lag_interval) < 59 OR lag_bytes = 0);

        PERFORM pg_sleep(1);
    END LOOP;

    RAISE NOTICE 'Replication lag monitoring complete';
END;
$$;

-- Expected output:
-- NOTICE:  n1 → n4 lag: 00:00:02.345 (bytes: 1024)
-- NOTICE:  n1 → n4 lag: 00:00:01.123 (bytes: 512)
-- NOTICE:  n1 → n4 lag: 00:00:00.456 (bytes: 0)
-- NOTICE:  Replication lag monitoring complete

Show All Nodes

Next, we will verify that all of the nodes are registered; the following query displays all registered nodes:

SELECT n.node_id, n.node_name, n.location, n.country, i.if_dsn
FROM dblink(
    'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
    'SELECT n.node_id, n.node_name, n.location, n.country, i.if_dsn
     FROM spock.node n
     JOIN spock.node_interface i ON n.node_id = i.if_nodeid
     ORDER BY n.node_name'
) AS t(node_id integer, node_name text, location text, country text, if_dsn text);

-- Expected output:
--  node_id | node_name |  location   | country |                           if_dsn
-- ---------+-----------+-------------+---------+------------------------------------------------------------
--    16385 | n1        | New York    | USA     | host=127.0.0.1 dbname=inventory port=5432 user=alice ...
--    16386 | n2        | Chicago     | USA     | host=127.0.0.1 dbname=inventory port=5433 user=alice ...
--    16387 | n3        | Boston      | USA     | host=127.0.0.1 dbname=inventory port=5434 user=alice ...
--    16389 | n4        | Los Angeles | USA     | host=127.0.0.1 dbname=inventory port=5435 user=alice ...

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:

-- Get subscriptions from all nodes
SELECT node_name, subscription_name, status, provider_node
FROM (
    -- n1 subscriptions
    SELECT 'n1' as node_name, *
    FROM dblink(
        'host=127.0.0.1 dbname=inventory port=5432 user=alice password=1safepassword',
        'SELECT subscription_name, status, provider_node FROM spock.sub_show_status()'
    ) AS t(subscription_name text, status text, provider_node text)

    UNION ALL

    -- n2 subscriptions
    SELECT 'n2' as node_name, *
    FROM dblink(
        'host=127.0.0.1 dbname=inventory port=5433 user=alice password=1safepassword',
        'SELECT subscription_name, status, provider_node FROM spock.sub_show_status()'
    ) AS t(subscription_name text, status text, provider_node text)

    UNION ALL

    -- n3 subscriptions
    SELECT 'n3' as node_name, *
    FROM dblink(
        'host=127.0.0.1 dbname=inventory port=5434 user=alice password=1safepassword',
        'SELECT subscription_name, status, provider_node FROM spock.sub_show_status()'
    ) AS t(subscription_name text, status text, provider_node text)

    UNION ALL

    -- n4 subscriptions
    SELECT 'n4' as node_name, *
    FROM dblink(
        'host=127.0.0.1 dbname=inventory port=5435 user=alice password=1safepassword',
        'SELECT subscription_name, status, provider_node FROM spock.sub_show_status()'
    ) AS t(subscription_name text, status text, provider_node text)
) combined
ORDER BY node_name, subscription_name;

-- Expected output (12 rows):
--  node_name | subscription_name |   status    | provider_node
-- -----------+-------------------+-------------+---------------
--  n1        | sub_n2_n1         | replicating | n2
--  n1        | sub_n3_n1         | replicating | n3
--  n1        | sub_n4_n1         | replicating | n4
--  n2        | sub_n1_n2         | replicating | n1
--  n2        | sub_n3_n2         | replicating | n3
--  n2        | sub_n4_n2         | replicating | n4
--  n3        | sub_n1_n3         | replicating | n1
--  n3        | sub_n2_n3         | replicating | n2
--  n3        | sub_n4_n3         | replicating | n4
--  n4        | sub_n1_n4         | replicating | n1
--  n4        | sub_n2_n4         | replicating | n2
--  n4        | sub_n3_n4         | replicating | n3

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:

-- On n1
CREATE TABLE test_replication (id serial primary key, data text, created_at timestamp default now());
INSERT INTO test_replication (data) VALUES ('Test from n1');

-- On n4 (wait a few seconds)
SELECT * FROM test_replication;
-- Expected: Row appears on n4

Test Replication between n4 and n1

Next, we insert data on n4:

INSERT INTO test_replication (data) VALUES ('Test from n4');

Then, verify replication on n1:

-- On n1 (wait a few seconds)
SELECT * FROM test_replication;
-- Expected: Both rows appear on n1

Our Final Cluster Topology

        ┌──────┐
        │  n1  │ (source)
        └──┬───┘
     ┌─────┼─────┬─────┐
     │     │     │     │
  ┌──▼──┐ │  ┌──▼──┐ ┌▼────┐
  │ n2  │◄┼──┤ n3  │ │ n4  │ (new)
  └──┬──┘ │  └──┬──┘ └┬────┘
     │    │     │     │
     └────┴─────┴─────┘

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:

-- Check subscription status
SELECT * FROM spock.sub_show_status();

-- Check table sync status
SELECT * FROM spock.sub_show_table('sub_n2_n4', 'public.test_replication');

-- Check logs
SELECT * FROM pg_stat_replication;

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:

SET spock.sync_timeout = '2h';

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:

-- Check lag on receiver node
SELECT origin_name, receiver_name,
       now() - commit_timestamp as lag,
       replication_lag_bytes
FROM spock.lag_tracker
ORDER BY lag DESC;

Slot Not Advancing

Use the following command to check the status of a replication slot:

-- Check slot status
SELECT slot_name, slot_type, active, restart_lsn, confirmed_flush_lsn
FROM pg_replication_slots
WHERE slot_name LIKE 'spk_%';

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.

PG.CENTER edition

2.7.1.2 - Tutorial: Updating the Postgres Version with a Rolling Update

Zodan’s addnode and removenode procedures move data between nodes regardless of which PostgreSQL major version each node runs.

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.

Warning

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_node and remove_node call from the node being added or removed.
  • The dblink extension must be installed on the node from which add_node or remove_node is called.
  • On a node whose PostgreSQL build has the output_plugin_libraries parameter (the patch versions in Checking PostgreSQL Version Compatibility Before Each Step and later), it must list spock_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_node allows 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 with spock.sync_timeout.
  • Do not remove an old node until its replacement reports replicating status.
  • 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.
Note

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:

SELECT * FROM dblink(
  'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
  'SHOW server_version_num'
) AS t(source_version int);

SELECT * FROM dblink(
  'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>',
  'SHOW server_version_num'
) AS t(replacement_version int);

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 versionMinimum patch version
1515.19
1616.15
1717.11
1818.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:

sudo dnf install -y pgedge-postgres18-server pgedge-postgres18-contrib pgedge-spock50_18

On Ubuntu or Debian:

sudo apt install -y pgedge-postgresql-18 pgedge-postgresql-18-spock50

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:

initdb -D /path/to/data/n1b --username=postgres

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.
Note

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:

wal_level = logical
max_worker_processes = 20
max_replication_slots = 10
max_wal_senders = 10
shared_preload_libraries = 'spock'
track_commit_timestamp = on
output_plugin_libraries = 'pgoutput, test_decoding, spock_output'

# PostgreSQL 18 and later only:
max_active_replication_origins = 10

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:

pg_ctl -D /path/to/data/n1b -o "-p 5442" start
psql -p 5442 -c "SHOW shared_preload_libraries;"
psql -p 5442 -c "SHOW output_plugin_libraries;"

Create the database and user, matching the source node exactly:

psql -p 5442 -c "CREATE DATABASE inventory;"
psql -p 5442 -c "CREATE USER pgedge WITH PASSWORD '<pgedge-password>';"
psql -p 5442 -c "GRANT ALL ON DATABASE inventory TO pgedge;"

Install the Spock extension built against the target PostgreSQL version:

psql -p 5442 -d inventory -c "CREATE EXTENSION spock;"
psql -p 5442 -d inventory -c "CREATE EXTENSION dblink;"

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:

psql -p 5442 -c \
  "CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD '<replicator-password>';"
psql -p 5442 -c "ALTER ROLE postgres WITH PASSWORD '<postgres-password>';"

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:

host replication replicator 127.0.0.1/32 md5
host all          postgres   127.0.0.1/32 md5
psql -p 5442 -c "SELECT pg_reload_conf();"

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:

    1. Create a physical replication slot on the replacement node, for its future standby to stream through:

      SELECT pg_create_physical_replication_slot('n1b_standby_slot');
    2. Take a base backup of the replacement node into the standby’s data directory, streaming through that slot:

      pg_basebackup -h 127.0.0.1 -p 5442 -U replicator \
        -D /path/to/data/n1b_standby -S n1b_standby_slot -X stream -P
      touch /path/to/data/n1b_standby/standby.signal

      standby.signal is what makes the server start as a standby; pg_basebackup -R would also write it, but it would put a primary_conninfo without dbname into postgresql.auto.conf, which overrides the one set in the next steps, and slot sync needs dbname.

    3. Set synchronized_standby_slots in the replacement node’s postgresql.conf, naming that slot:

      synchronized_standby_slots = 'n1b_standby_slot'
    4. On the standby itself, point it at the replacement node and enable native slot sync in its postgresql.conf:

      sync_replication_slots = on
      primary_conninfo = 'host=127.0.0.1 port=5442 dbname=inventory user=replicator password=<replicator-password>'
      primary_slot_name = 'n1b_standby_slot'
      hot_standby_feedback = on
    5. After starting the standby, confirm the slot synchronized:

      SELECT slot_name, synced, failover, invalidation_reason
      FROM pg_replication_slots
      WHERE NOT temporary;

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.

  1. Connect to the prepared replacement node and load the Zodan workflow:

    \i /path/to/zodan.sql
    Note

    Both zodan.sql and zodremove.sql are 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:

    CALL spock.add_node(
        src_node_name := 'n1',
        src_dsn := 'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
        new_node_name := 'n1b',
        new_node_dsn := 'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>',
        verb := true,
        new_node_location := 'Los Angeles',
        new_node_country := 'USA',
        new_node_info := '{"role": "n1-replacement", "pg_version": "18"}'::jsonb
    );
  2. Confirm the replacement node is fully caught up and replicating in both directions before touching the node it replaces:

    CALL spock.show_all_subscription_status(
      'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>',
      true
    );

    Every subscription involving n1b should report replicating, including the subscriptions to and from n2 and n3 that add_node created automatically.

  3. If the node being retired runs behind a physical standby for high availability, build a matching standby for n1b and 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 n1b and its future standby host before either node can run under Patroni. This tutorial uses etcd as the DCS, the most common choice for Patroni. Install Patroni on both hosts:

    pip install patroni[etcd]

    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:

    # /etc/etcd/etcd.yml
    name: etcd0
    data-dir: /path/to/data/etcd0
    listen-client-urls: http://127.0.0.1:2379
    advertise-client-urls: http://127.0.0.1:2379
    listen-peer-urls: http://127.0.0.1:2380
    initial-advertise-peer-urls: http://127.0.0.1:2380
    initial-cluster: etcd0=http://127.0.0.1:2380
    initial-cluster-token: n1b-etcd
    initial-cluster-state: new
    etcd --config-file /etc/etcd/etcd.yml

    Confirm n1b and its standby host can reach the DCS before continuing:

    etcdctl --endpoints=127.0.0.1:2379 endpoint health

    Bring n1b under Patroni as the leader of a new Patroni cluster, rather than letting Patroni bootstrap it from scratch - n1b is already initialized and already running with the data add_node populated. Patroni only runs its bootstrap process against an empty data_dir, so pointing it at n1b’s existing, populated directory makes Patroni adopt the running instance as the cluster’s first member instead:

    scope: n1b-cluster
    namespace: /service/
    name: n1b
    
    restapi:
      listen: 127.0.0.1:8541
      connect_address: 127.0.0.1:8541
    
    etcd3:
      hosts: 127.0.0.1:2379
    
    postgresql:
      listen: 127.0.0.1:5442
      connect_address: 127.0.0.1:5442
      data_dir: /path/to/data/n1b
      bin_dir: /usr/pgsql-18/bin   # /usr/lib/postgresql/18/bin on Ubuntu or Debian
      parameters:
        sync_replication_slots: on
        hot_standby_feedback: on
      callbacks:
        on_role_change: /path/to/set_synchronized_standby_slots.sh
      authentication:
        replication:
          username: replicator
          password: <replicator-password>
        superuser:
          username: postgres
          password: <postgres-password>

    sync_replication_slots and hot_standby_feedback are the two settings the native slot sync path needs on a standby; set them on both n1b and n1b_standby rather than only on whichever is the standby today, since either one can end up in that role after a promotion. synchronized_standby_slots is deliberately left out of postgresql.parameters here - it is set directly on whichever node is primary, by the on_role_change callback 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:

    patroni /path/to/n1b_patroni.yml

    Then point a second Patroni instance at the same scope and DCS endpoint, under the member name n1b_standby, with an empty data_dir. Patroni finds the existing cluster in the DCS and, on first start, runs pg_basebackup itself against n1b to populate that empty directory - connecting as the replicator role over the replication connection permitted by the pg_hba.conf entry added above, using the credentials in the authentication.replication block below. No manual pg_basebackup step is needed on this path; Patroni’s bootstrap process runs it for you:

    scope: n1b-cluster
    namespace: /service/
    name: n1b_standby
    
    restapi:
      listen: 127.0.0.1:8542
      connect_address: 127.0.0.1:8542
    
    etcd3:
      hosts: 127.0.0.1:2379
    
    postgresql:
      listen: 127.0.0.1:5452
      connect_address: 127.0.0.1:5452
      data_dir: /path/to/data/n1b_standby
      bin_dir: /usr/pgsql-18/bin   # /usr/lib/postgresql/18/bin on Ubuntu or Debian
      parameters:
        sync_replication_slots: on
        hot_standby_feedback: on
      callbacks:
        on_role_change: /path/to/set_synchronized_standby_slots.sh
      authentication:
        replication:
          username: replicator
          password: <replicator-password>
        superuser:
          username: postgres
          password: <postgres-password>
    patroni /path/to/n1b_standby_patroni.yml

    Confirm n1b_standby joined and is streaming before moving on:

    patronictl -c /path/to/n1b_patroni.yml list n1b-cluster

    Also confirm, on n1b, that the slot backing the standby has synced before relying on it for failover:

    SELECT slot_name, synced, failover, invalidation_reason
    FROM pg_replication_slots
    WHERE NOT temporary;

    synchronized_standby_slots names a Patroni-managed physical slot, and Patroni’s auto-created slots are named after the member, not the role - the slot named n1b_standby only exists while n1b_standby is not the primary. The on_role_change callback 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:

    patronictl -c /path/to/n1b_patroni.yml reload n1b-cluster

    The following script, deployed on n1b with SIBLING_MEMBER set to n1b_standby and LOCAL_PORT set to 5442 (and on n1b_standby with them set to n1b and 5452), sets synchronized_standby_slots to the other member’s name whenever this node becomes the primary:

    #!/bin/bash
    # Patroni on_role_change callback.
    # Patroni invokes this script as:
    #   <script> <action> <role> <scope>
    # so the role is $2, not $1.
    # Resets synchronized_standby_slots to the sibling member's name
    # whenever Patroni promotes this node to primary.
    ROLE="$2"
    SIBLING_MEMBER="n1b_standby"
    LOCAL_PORT="5442"
    
    if [ "$ROLE" = "master" ] || [ "$ROLE" = "primary" ]; then
      psql -p "${LOCAL_PORT}" -U postgres -c \
        "ALTER SYSTEM SET synchronized_standby_slots = '${SIBLING_MEMBER}';"
      psql -p "${LOCAL_PORT}" -U postgres -c "SELECT pg_reload_conf();"
    fi

    The callback only fires on a future promotion, so set the initial value by hand now, on n1b while it is still the leader:

    psql -p 5442 -U postgres -c \
      "ALTER SYSTEM SET synchronized_standby_slots = 'n1b_standby';"
    psql -p 5442 -U postgres -c "SELECT pg_reload_conf();"

    With n1b_standby streaming 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_standby is a separate event from this cutover, and needs its own plan: Spock’s subscriptions on n2 and n3 connect to n1b using the raw host=127.0.0.1 port=5442 address from the add_node call above, and Patroni does not repoint that address for them. If n1b is reachable only through a VIP or DNS record that Patroni (or keepalived alongside it) moves to whichever member is primary, point new_node_dsn at that stable address instead of a node’s raw host and port when you call add_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_interface writes only to the local node catalog; it is not replicated. Run it on every node whose subscription you will repoint, here n2 and n3, since sub_alter_interface looks the interface up locally:

    SELECT spock.node_add_interface('n1b', 'n1b_standby_interface',
      'host=127.0.0.1 dbname=inventory port=5452 user=pgedge password=<pgedge-password>');

    Then run sub_alter_interface on each of those nodes:

    SELECT spock.sub_alter_interface('sub_n1b_n2', 'n1b_standby_interface');

    spock.gen_sub_name(provider_node, subscriber_node) names each subscription, so sub_n1b_n2 is the subscription on n2 whose provider is n1b; confirm the exact names for your cluster with SELECT sub_name FROM spock.subscription; on each node before repointing them.

  4. Move application traffic from n1 to n1b, and confirm no new connections are arriving at n1. remove_node drops every subscription to and from n1 at once and does not wait for anything, so any write on n1 that has not reached the other nodes by then is lost. When n1 takes no writes, emit a sync event on it:

    -- On n1
    SELECT spock.sync_event();

    Wait for it on every other node, passing the LSN it returned. The result column must come back t:

    -- On n1b, n2 and n3
    CALL spock.wait_for_sync_event(NULL, 'n1'::name, '<lsn-from-sync_event>'::pg_lsn, 600);

    Then load the removal workflow on the node being retired, and remove it from the cluster:

    \i /path/to/zodremove.sql
    CALL spock.remove_node(
      'n1',
      'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
      true
    );

    remove_node does 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:

ALTER SYSTEM SET spock.enable_ddl_replication = on;
SELECT pg_reload_conf();

Verifying the Rollout

After replacing all nodes, confirm the whole cluster runs the target PostgreSQL version and reports a clean replication topology:

SELECT * FROM dblink(
  'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>',
  'SHOW server_version'
) AS t(pg_version text);

CALL spock.show_all_nodes(
  'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>',
  true
);

CALL spock.show_all_subscription_status(
  'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>',
  true
);

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:

FieldWhat to confirm
PostgreSQL versionEvery node reports the target version.
Node nameOnly n1b, n2b, and n3b remain; no old node is listed.
Subscription statusEvery subscription between every pair of nodes reports replicating.

Troubleshooting

  • add_node fails with cannot synchronize structure from provider running PostgreSQL, or the replacement node’s apply worker exits with cannot synchronize structure from upstream server version. The replacement node’s pg_dump cannot 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 the output_plugin_libraries parameter and it does not list spock_output. Add it to postgresql.conf and run SELECT 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_node reports that it could not create a replication slot. Check wal_level = logical and max_replication_slots on the replacement node. add_node reports a failed slot creation only as a notice, only with verb := true, and carries on; the subscriptions it then creates do not replicate.

  • add_node times out waiting for a sync event on a large database. Raise the wait budget for the session with spock.sync_timeout before calling add_node again.

  • A step fails partway through add_node. Do not retry immediately. Source zodremove.sql and call spock.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:


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.

PG.CENTER edition

2.7.1.3 - Zodan: Zero-Downtime Node Addition for Spock

Zodan provides tools to add or remove a node 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.

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 dblink to perform the same add node operations from within Postgres.
  • The zodremove.sql workflow is a complete SQL-based workflow that uses dblink to 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 via spock.node_create.
  • get_spock_nodes - Fetch current node metadata from a remote node.
  • create_sub and enable_sub - Manage subscription creation and activation.
  • create_replication_slot - Create and configure logical replication slots.
  • sync_event and wait_for_sync_event - Coordinate data synchronization events.
  • get_commit_timestamp and advance_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:

CALL spock.add_node(
  'source_node_name',
  'src_dsn',
  'new_node_name',
  'new_node_dsn',
  true|false,               -- verbose? optional
  'new_node_location',      -- optional
  'new_node_country',       -- optional
  '{}'::jsonb               -- optional info
);

In the following example, the command adds node n4 to the cluster:

CALL spock.add_node(
  'n1',
  'host=127.0.0.1 dbname=pgedge port=5431 user=pgedge password=<PASSWORD>',
  'n4',
  'host=127.0.0.1 dbname=pgedge port=5434 user=pgedge password=<PASSWORD>'
);

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.

CALL spock.remove_node(
  'target_node_name',
  'target_dsn',
  true                      -- verbose_mode, optional boolean
);

In the following example, the command removes node n4 from the cluster:

CALL spock.remove_node(
  'n4',
  'host=127.0.0.1 dbname=pgedge port=5434 user=pgedge password=<PASSWORD>'
);

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.

PG.CENTER edition

2.7.2 - Adding a Node with pgBackRest

You can use a pgBackRest backup to populate a new cluster node, and then add that node to your cluster with 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.

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).

  1. Create a pgBackRest stanza. This step is required as the stanza defines the cluster configuration, which is essential for backup and restore operations.

  2. 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).

  3. Restore the backup from n1 to the data directory of n4. This prepares n4 to become a replica of n1.

  4. Configure streaming replication on n4, making the node a replica of n1. This ensures that n4 contains all transactions on n1 since the backup was taken, ensuring n4 is 100 percent synchronized with n1.

  5. Use the ALTER command to set nodes n1, n2, and n3 to read-only mode and reload the configuration on these nodes to apply the changes. This step is crucial because n4 has configurations copied from n1 that are not valid for n4. By making the nodes read-only, you ensure no transactions occur while you modify the configurations.

  6. Terminate all ongoing transactions on n1, n2, and n3. This prevents any long-running queries from interfering during the configuration changes.

  7. Edit the shared_preload_libraries parameter on n4, removing spock. This prevents Spock from using the old configuration from n1 on n4.

  8. Start n4, allowing the node to become a replica of n1. This step ensures that n4 contains all transactions from n1.

  9. Promote n4 to the role of primary node or configure the node as a standalone node with Spock disabled. This step finalizes n4 as the new primary node in your replication setup.

  10. Remove all replication sets and nodes from the configuration. This clears any old replication configurations that are no longer needed.

  11. Re-add spock to the shared_preload_libraries parameter on n4. This prepares n4 to handle replication in the new role.

  12. Restart n4 to apply the changes made in the previous steps.

  13. Reintegrate n4 into the replication cluster with n1, n2, and n3.

  14. Remove the read-only mode from n1, n2, and n3, allowing them to resume normal operations.

  15. Add the following subscriptions between the new node (n4) and Nodes 1, 2, and 3 (n1, n2, n3):

    • The subn1n4 subscription syncs n1 with n4.
    • The subn2n4 subscription syncs n2 with n4.
    • The subn3n4 subscription syncs n3 with n4.
    • The subn4n1 subscription syncs n4 with n1.
    • The subn4n2 subscription syncs n4 with n2.
    • The subn4n3 subscription syncs n4 with n3.
  16. Verify that all nodes (n1, n2, n3, and n4) 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.

PG.CENTER edition

2.7.3 - Tutorial: Upgrading the Postgres Version In Place with pg_upgrade

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 pgupgrade.

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

Warning

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 --link requires 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_upgrade stops with could not create hard link between old and new data directories; it does not fall back to copying.
  • --link mode 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 old postgresql.conf, pg_hba.conf, and any other node-specific configuration as reference material to port forward, not something you can revert to.
  • pg_upgrade does 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_size is 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() and spock.show_all_nodes() are Zodan procedures. Load zodan.sql from the Spock distribution, which needs the dblink extension, on the node you run them from.
  • Run pg_upgrade --check against 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.
Note

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.

  1. Drain traffic from the node being upgraded at the load balancer, pooler, or application layer, and confirm no new connections are arriving at it.

  2. Make sure every other node has applied everything n1 committed, and record what the upgrade will lose. With traffic drained, emit a sync event on n1:

    -- On n1
    SELECT spock.sync_event();

    Wait for it on every other node, passing the LSN it returned. The result column must come back t:

    -- On n2, then on n3
    CALL spock.wait_for_sync_event(NULL, 'n1'::name, '<lsn-from-sync_event>'::pg_lsn, 600);

    Then confirm on n1 that every slot has confirmed past that LSN; this query must return no rows:

    -- On n1
    SELECT slot_name, confirmed_flush_lsn
    FROM pg_replication_slots
    WHERE slot_type = 'logical'
      AND (confirmed_flush_lsn IS NULL
           OR confirmed_flush_lsn < '<lsn-from-sync_event>'::pg_lsn);

    A physical slot, such as the one a standby streams through, always has a NULL confirmed_flush_lsn, which is why the query is limited to logical slots.

    pg_upgrade does not carry Spock’s replication origins over, so record where each of n1’s subscriptions has applied up to. Every row must show an LSN; a NULL means a subscription with no origin, which you must resolve before upgrading:

    -- On n1
    SELECT s.sub_name, s.sub_slot_name, o.remote_lsn
    FROM spock.subscription s
    LEFT JOIN pg_replication_origin_status o
           ON o.external_id = s.sub_slot_name;

    Also record, on every other node, the definition of its subscription to n1, so you can recreate it unchanged in step 20:

    -- On n2 (sub_n1_n2), then on n3 (sub_n1_n3)
    SELECT sub_name, sub_replication_sets, sub_forward_origins,
           sub_apply_delay, sub_force_text_transfer, sub_skip_schema
    FROM spock.subscription
    WHERE sub_name = '<subscription-to-n1-on-this-node>';

    spock.gen_sub_name(provider_node, subscriber_node) names each subscription, so sub_n1_n2 is the subscription on n2 whose provider is n1. Confirm the names for your cluster with SELECT sub_name FROM spock.subscription; on each node.

  3. Disable n1’s own subscriptions, so it stops applying, and wait until SELECT * FROM spock.sub_show_status(); on n1 no longer shows any as replicating:

    -- On n1, once per subscription
    SELECT spock.sub_disable('sub_n2_n1');
    SELECT spock.sub_disable('sub_n3_n1');

    While n1 is still running, drop every other node’s subscription to it. sub_drop removes the subscription’s slot on n1 only when it can reach n1; a subscription dropped later leaves its slot behind on n1. No data is lost, because step 2 confirmed that every node had applied all of n1’s changes:

    -- On n2, then the matching subscription on n3
    SELECT spock.sub_drop('sub_n1_n2');

    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. --wait returns only once every member has seen the pause, so the stop below cannot race it:

    patronictl -c /path/to/n1_patroni.yml pause --wait n1-cluster

    Record the Spock version the node runs; step 4 needs it, and the server cannot answer once it is down:

    SELECT extversion FROM pg_extension WHERE extname = 'spock';

    Then stop PostgreSQL on the node:

    pg_ctl -D /path/to/data/n1 stop
  4. 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:

    sudo dnf install -y pgedge-postgres18-server pgedge-postgres18-contrib pgedge-spock50_18

    On Ubuntu or Debian:

    sudo apt install -y pgedge-postgresql-18 pgedge-postgresql-18-spock50

    pg_upgrade recreates 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, run ALTER 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_node requires the new node’s Spock version to be the same as or newer than every existing node’s.

  5. Initialize a new data directory on the target PostgreSQL version. pg_upgrade migrates data into an already-initialized cluster; it does not create one. On a PostgreSQL 16 or later target, pg_upgrade copies the old cluster’s encoding and locale settings into the new cluster itself, so initdb needs no encoding or locale option. The data checksum setting is not copied and must match the old cluster, or pg_upgrade stops. Read it from the stopped data directory:

    pg_controldata /path/to/data/n1 | grep "checksum version"

    If the checksum version is 1, enable checksums:

    /path/to/pg18/bin/initdb -D /path/to/data/n1_new --data-checksums

    If it is 0, disable them explicitly. PostgreSQL 18 initdb enables checksums by default, so leaving the option out does not match a cluster without them:

    /path/to/pg18/bin/initdb -D /path/to/data/n1_new --no-data-checksums

    pg_upgrade does not carry configuration files forward; the new data directory has only the defaults initdb wrote. Configure it now, before step 6: pg_upgrade --check reads wal_level, max_replication_slots and output_plugin_libraries from the new cluster, and fails if they cannot hold the old cluster’s logical slots when the old cluster is PostgreSQL 17 or later. Copy pg_hba.conf as-is, since authentication rules do not change with the PostgreSQL version:

    cp /path/to/data/n1/pg_hba.conf /path/to/data/n1_new/pg_hba.conf

    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_slots must be at least the number of logical slots on the old node:

    wal_level = logical
    max_worker_processes = 20
    max_replication_slots = 10
    max_wal_senders = 10
    shared_preload_libraries = 'spock'
    track_commit_timestamp = on
    output_plugin_libraries = 'pgoutput, test_decoding, spock_output'
    
    # PostgreSQL 18 and later only:
    max_active_replication_origins = 10

    output_plugin_libraries exists 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 with SELECT 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 versionMinimum patch version
    1515.19
    1616.15
    1717.11
    1818.6
  6. Run pg_upgrade --check first, against the target version’s binaries, to confirm there are no blocking issues:

    /path/to/pg18/bin/pg_upgrade \
      --old-datadir /path/to/data/n1 \
      --new-datadir /path/to/data/n1_new \
      --old-bindir /path/to/pg16/bin \
      --new-bindir /path/to/pg18/bin \
      --link --check

    Pass --link to the check too, so it also confirms hard links work between the two directories.

    Then run the upgrade itself, adding --link to hard-link the data files instead of copying them:

    /path/to/pg18/bin/pg_upgrade \
      --old-datadir /path/to/data/n1 \
      --new-datadir /path/to/data/n1_new \
      --old-bindir /path/to/pg16/bin \
      --new-bindir /path/to/pg18/bin \
      --link
  7. 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 old postgresql.auto.conf, which holds everything set with ALTER SYSTEM, and for any file the old configuration pulls in with include; pg_upgrade carries 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.

  8. Start PostgreSQL on the new version:

    pg_ctl -D /path/to/data/n1_new -o "-p 5432" start
  9. 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.

    pg_ctl -D /path/to/data/n1_standby stop
  10. 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

  11. 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 etcd as the DCS, the most common choice for Patroni:

    pip install patroni[etcd]

    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:

    # /etc/etcd/etcd.yml
    name: etcd0
    data-dir: /path/to/data/etcd0
    listen-client-urls: http://127.0.0.1:2379
    advertise-client-urls: http://127.0.0.1:2379
    listen-peer-urls: http://127.0.0.1:2380
    initial-advertise-peer-urls: http://127.0.0.1:2380
    initial-cluster: etcd0=http://127.0.0.1:2380
    initial-cluster-token: n1-etcd
    initial-cluster-state: new
    etcd --config-file /etc/etcd/etcd.yml

    Confirm both hosts can reach the DCS before continuing, whether it is freshly started or already serving this pair:

    etcdctl --endpoints=127.0.0.1:2379 endpoint health
  12. 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_upgrade produced, and Patroni only runs its bootstrap process against an empty data_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’s data_dir and bin_dir to the values below instead of writing a new file. pg_upgrade preserves roles and their passwords, and step 5 above already copied pg_hba.conf forward, so a replicator role and its pg_hba.conf entry from an existing standby still work unchanged.

    Optional: set a password on the postgres superuser only if one is not already set:

    psql -p 5432 -c "ALTER ROLE postgres WITH PASSWORD '<postgres-password>';"
    scope: n1-cluster
    namespace: /service/
    name: n1
    
    restapi:
      listen: 127.0.0.1:8541
      connect_address: 127.0.0.1:8541
    
    etcd3:
      hosts: 127.0.0.1:2379
    
    postgresql:
      listen: 127.0.0.1:5432
      connect_address: 127.0.0.1:5432
      data_dir: /path/to/data/n1_new
      bin_dir: /usr/pgsql-18/bin   # /usr/lib/postgresql/18/bin on Ubuntu or Debian
      parameters:
        sync_replication_slots: on
        hot_standby_feedback: on
      callbacks:
        on_role_change: /path/to/set_synchronized_standby_slots.sh
      authentication:
        replication:
          username: replicator
          password: <replicator-password>
        superuser:
          username: postgres
          password: <postgres-password>
  13. If the node was already under Patroni, its DCS still records the old cluster’s system identifier, and pg_upgrade gave 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 both n1 and n1_standby, then remove the scope’s state from the DCS. patronictl remove asks you to type the cluster name and confirm:

    patronictl -c /path/to/n1_patroni.yml remove n1-cluster

    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 with patronictl edit-config; record those first with patronictl -c /path/to/n1_patroni.yml show-config n1-cluster and 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 n1 with the configuration from step 12. With no cluster state in the DCS and PostgreSQL already running on a populated data_dir, Patroni adopts the running instance as the leader rather than bootstrapping a new one:

    patroni /path/to/n1_patroni.yml

    Then bring up n1_standby as 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 same scope and DCS, under the member name n1_standby, with an empty data_dir. Patroni finds the cluster in the DCS and, on first start, runs pg_basebackup itself against n1 to populate that empty directory. If n1_standby was already under Patroni, edit its existing config to the values below:

    scope: n1-cluster
    namespace: /service/
    name: n1_standby
    
    restapi:
      listen: 127.0.0.1:8542
      connect_address: 127.0.0.1:8542
    
    etcd3:
      hosts: 127.0.0.1:2379
    
    postgresql:
      listen: 127.0.0.1:5442
      connect_address: 127.0.0.1:5442
      data_dir: /path/to/data/n1_standby_new
      bin_dir: /usr/pgsql-18/bin   # /usr/lib/postgresql/18/bin on Ubuntu or Debian
      parameters:
        sync_replication_slots: on
        hot_standby_feedback: on
      callbacks:
        on_role_change: /path/to/set_synchronized_standby_slots.sh
      authentication:
        replication:
          username: replicator
          password: <replicator-password>
        superuser:
          username: postgres
          password: <postgres-password>
    patroni /path/to/n1_standby_patroni.yml
  14. Confirm n1_standby joined and is streaming before moving on:

    patronictl -c /path/to/n1_patroni.yml list n1-cluster
  15. Also confirm, on n1, that the slot backing the standby has synced:

    SELECT slot_name, synced, failover, invalidation_reason
    FROM pg_replication_slots
    WHERE NOT temporary;
  16. synchronized_standby_slots names 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 named n1_standby and exists on n1; if n1_standby is ever promoted, that slot disappears and a new one named n1 appears on n1_standby instead, representing n1 as the new standby. The on_role_change callback 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:

    patronictl -c /path/to/n1_patroni.yml reload n1-cluster

    The following script, deployed on n1 with SIBLING_MEMBER set to n1_standby and LOCAL_PORT set to 5432 (and on n1_standby with them set to n1 and 5442), sets synchronized_standby_slots to the other member’s name whenever this node becomes the primary:

    #!/bin/bash
    # Patroni on_role_change callback.
    # Patroni invokes this script as:
    #   <script> <action> <role> <scope>
    # so the role is $2, not $1.
    # Resets synchronized_standby_slots to the sibling member's name
    # whenever Patroni promotes this node to primary.
    ROLE="$2"
    SIBLING_MEMBER="n1_standby"
    LOCAL_PORT="5432"
    
    if [ "$ROLE" = "master" ] || [ "$ROLE" = "primary" ]; then
      psql -p "${LOCAL_PORT}" -U postgres -c \
        "ALTER SYSTEM SET synchronized_standby_slots = '${SIBLING_MEMBER}';"
      psql -p "${LOCAL_PORT}" -U postgres -c "SELECT pg_reload_conf();"
    fi
  17. The callback only fires on a future promotion, so set the initial value by hand now, on n1 while it is still the leader:

    psql -p 5432 -U postgres -c \
      "ALTER SYSTEM SET synchronized_standby_slots = 'n1_standby';"
    psql -p 5432 -U postgres -c "SELECT pg_reload_conf();"
  18. A later promotion of n1_standby is a separate event from this setup, and needs its own plan: Spock’s subscriptions on n2 and n3 connect to n1 using whichever address was configured when those subscriptions were created, and Patroni does not repoint that address for them. If n1 is reachable only through a VIP or DNS record that Patroni (or keepalived alongside 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_interface writes only to the local node catalog; it is not replicated. Run it on every node whose subscription you will repoint, here n2 and n3, since sub_alter_interface looks the interface up locally:

    SELECT spock.node_add_interface('n1', 'n1_standby_interface',
      'host=127.0.0.1 dbname=inventory port=5442 user=pgedge password=<pgedge-password>');

    Then run sub_alter_interface on each of those nodes. The subscriptions it names are the ones step 20 recreates, so this only applies once step 20 is done:

    SELECT spock.sub_alter_interface('sub_n1_n2', 'n1_standby_interface');

    spock.gen_sub_name(provider_node, subscriber_node) names each subscription, so sub_n1_n2 is the subscription on n2 whose provider is n1; confirm the exact names for your cluster with SELECT sub_name FROM spock.subscription; on each node before repointing them.

  19. Put n1’s replication origins back where step 2 recorded them, before its subscriptions run again. For each subscription, create the origin if pg_upgrade did not keep it, then advance it to the recorded LSN:

    -- On n1, once per row recorded in step 2
    SELECT pg_replication_origin_create('<sub_slot_name>')
    WHERE NOT EXISTS (SELECT 1 FROM pg_replication_origin
                      WHERE roname = '<sub_slot_name>');
    SELECT pg_replication_origin_advance('<sub_slot_name>', '<remote_lsn>'::pg_lsn);

    Confirm each origin now shows its recorded LSN:

    SELECT external_id, remote_lsn FROM pg_replication_origin_status;
  20. On every other node, recreate its subscription to n1 from the definition recorded in step 2. Do not copy data: step 2 made sure every node already held all of n1’s changes, and n1 has taken no writes since. The following example recreates the subscription on n2 whose provider is n1:

    -- On n2, then the matching subscription on n3
    SELECT spock.sub_create(
      subscription_name     := 'sub_n1_n2',
      provider_dsn          := 'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
      replication_sets      := '<recorded sub_replication_sets>',
      forward_origins       := '<recorded sub_forward_origins>',
      apply_delay           := '<recorded sub_apply_delay>',
      force_text_transfer   := <recorded sub_force_text_transfer>,
      skip_schema           := '<recorded sub_skip_schema>',
      synchronize_structure := false,
      synchronize_data      := false
    );

    Do not set synchronize_data := true here. The data sync copies each table into the existing one without emptying it first, so it fails on the rows the node already holds.

  21. Re-enable n1’s own subscriptions, then confirm every subscription to and from n1 reports replicating:

    -- On n1, once per subscription
    SELECT spock.sub_enable('sub_n2_n1', true);
    SELECT spock.sub_enable('sub_n3_n1', true);

    Then check the status of every subscription in the cluster:

    CALL spock.show_all_subscription_status(
      'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
      true
    );
  22. 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.

Note

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:

ALTER SYSTEM SET spock.enable_ddl_replication = on;
SELECT pg_reload_conf();

Verifying the Rollout

When every node has been upgraded, confirm the whole cluster runs the target PostgreSQL version and reports a clean replication topology:

SELECT * FROM dblink(
  'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
  'SHOW server_version'
) AS t(pg_version text);

CALL spock.show_all_subscription_status(
  'host=127.0.0.1 dbname=inventory port=5432 user=pgedge password=<pgedge-password>',
  true
);

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:

FieldWhat to confirm
PostgreSQL versionEvery node reports the target version.
Subscription statusEvery subscription between every pair of nodes reports replicating.

Troubleshooting

  • pg_upgrade --check reports an incompatible extension version. Install the Spock build for the target PostgreSQL version on the node before upgrading; pg_upgrade checks that every extension in the old cluster has a matching library available for the new one.

  • pg_upgrade --link fails with could 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 --link and 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:


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.

PG.CENTER edition

2.8 - Conflict Types

For conflict avoidance using delta-apply columns, see Conflict Avoidance and Delta-Apply Columns.

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 TypeDMLResolvable
insert_existsINSERTYes
update_origin_differsUPDATEN/A (normal flow, not recorded)
update_existsUPDATENo (unique constraint violated), saved in spock.exception_log
update_missingUPDATENo (row not found), saved in spock.exception_log
delete_origin_differsDELETEN/A (normal flow, not recorded)
delete_missingDELETEYes
delete_existsDELETEYes

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:

StrategyBehavior
last_update_winsThe 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):

-- on n1, one of these two (node_alter validates tiebreaker, UPDATE does not):
SELECT spock.node_alter(p_info_patch => '{"tiebreaker": <unique_integer>}'::jsonb);

UPDATE spock.node
   SET info = COALESCE(info, '{}'::jsonb) ||
              '{"tiebreaker": <unique_integer>}'
 WHERE node_id = (SELECT node_id FROM spock.node_info());

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:

-- on a node that has a stale row for n1:
SELECT spock.node_refresh_info('n1');   -- one node

SELECT spock.node_refresh_info();       -- or every known peer at once

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 (default off) – When enabled, resolved conflicts are written to the spock.resolutions table with full tuple details in JSON format.
  • spock.conflict_log_level (default LOG) – Controls the PostgreSQL log level at which detected conflicts are reported. Set to a level below log_min_messages to suppress log output.
  • spock.log_origin_change (default none) – Controls whether update_origin_differs and delete_origin_differs events (normal replication flow) are logged to the PostgreSQL server log. These events are never written to spock.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 TypePostgreSQL 18Spock (with last update wins)
insert_existsLogs and raises ERROR.Resolves via last_update_wins; transforms INSERT into UPDATE of the winning tuple.
update_origin_differsLogs 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_existsDetects unique constraint violation on updated row; logs.Logs and records in spock.exception_log.
update_missingLogs and skips.Logs and records in spock.exception_log.
delete_origin_differsLogs 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_missingLogs and skips.Logs and skips. Records in spock.resolutions.
delete_existsNo 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.

PG.CENTER edition

2.9 - Conflict-Free Delta-Apply Columns (Conflict Avoidance)

Conflicts can arise if a node is subscribed to multiple providers, or when local writes happen on a subscriber node.

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).

Note

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.
Note

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:

ALTER TABLE pgbench_accounts ALTER COLUMN abalance
  SET (log_old_value=true, delta_apply_function=spock.delta_apply);
ALTER TABLE pgbench_branches ALTER COLUMN bbalance
  SET (log_old_value=true, delta_apply_function=spock.delta_apply);
ALTER TABLE pgbench_tellers ALTER COLUMN tbalance
  SET (log_old_value=true, delta_apply_function=spock.delta_apply);

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_wins sets the resolution method to last_update_wins for any detected conflicts between local data and incoming changes; the version of data with newest commit timestamp is kept; note that the track_commit_timestamp PostgreSQL setting must also be enabled.
  • spock.conflict_log_level sets the log level for reporting detected conflicts; the default is LOG; if the parameter is set to a value lower than log_min_messages, resolved conflicts are not written to the server log; accepted values are the same as for the log_min_messages PostgreSQL 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 INSERT statement.
Warning

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.

PG.CENTER edition

2.10 - Monitoring the Configuration and Health of Your Cluster

The Spock extension provides several ways you can monitor data health in your Postgres 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 spock schema to review information about your cluster configuration and status.
  • The status views spock.node_status, spock.subscription_status, spock.worker_status, spock.slot_status and spock.events give 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.

PG.CENTER edition

2.10.1 - Finding Cluster Information

The following table describes informational tables in the spock schema:

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 NameDescription
channel_table_statsThis 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_statsThis 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
eventsThis 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
dependThis 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_logThis 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_statusThis 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_detailThe table includes the following columns: remote_origin, remote_commit_ts, command_counter, retry_errored_at, remote_xid, status, resolved_at, resolution_details
local_nodeThis 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_statusThis 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
nodeThis table contains one row per replication node. This table contains: node_id, node_name, and optionally the location, country, and info.
node_interfaceThis 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_statusThis 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_statusThis view lists every node this node knows about with its interfaces and the subscription that brings its changes here. See Monitoring a Node.
piiThis 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
progressThis 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
queueThis 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_setThis 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_seqThis table contains one row per replication set sequence. It contains set_id and set_seqoid.
replication_set_tableThis 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_statusThis view lists the replication sets of the local node with their replicate flags and the number of tables, sequences and subscriptions using each.
resolutionsThis 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.
settingsThis view shows the spock parameters and the core parameters replication depends on, with unit, source and pending restart.
slot_statusThis 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_stateThis is an internal-use table that stores state information for native sequence synchronization. The table includes the following columns: seqoid, cache_size, last_value
subscriptionThis 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_statsThis 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_statusThis 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_statusThis 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_statusThis view shows local_sync_status with readable sync_kind and sync_status values.
tablesThis 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_statusThis 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:

select * from spock.node;
-[ RECORD 1 ]--------
node_id   | 673694252
node_name | n1
location  |
country   |
info  	|
-[ RECORD 2 ]--------
node_id   | 560818415
node_name | n2
location  |
country   |
info  	|

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:

select * from spock.subscription;
-[ RECORD 1 ]-----------+--------------------------------------------------
sub_id              	| 3293941396
sub_name            	| sub_n1n2
sub_origin          	| 560818415
sub_target          	| 673694252
sub_origin_if       	| 4043145508
sub_target_if       	| 1437190346
sub_enabled         	| t
sub_slot_name       	| spk_demo_n2_sub_n1n2
sub_replication_sets	| {default,default_insert_only,ddl_sql,demo_repset}
sub_forward_origins 	|
sub_apply_delay     	| 00:00:00
sub_force_text_transfer | f

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:

select * from spock.replication_set_table;
-[ RECORD 1 ]--+-----------------
set_id     	| 2403235102
set_reloid 	| pgbench_accounts
set_att_list   |
set_row_filter |
-[ RECORD 2 ]--+-----------------
set_id     	| 2403235102
set_reloid 	| pgbench_branches
set_att_list   |
set_row_filter |
-[ RECORD 3 ]--+-----------------
set_id     	| 2403235102
set_reloid 	| pgbench_tellers
set_att_list   |
set_row_filter |

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.

select * from spock.tables where set_name is null;
-[ RECORD 1 ]-------------
relid	| 24846
nspname  | public
relname  | pgbench_history
set_name |

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.

PG.CENTER edition

2.10.2 - Lag Tracking

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.

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:

-[ RECORD 1 ]---------+------------------------------
origin_name           | node1
receiver_name         | node2
commit_timestamp      | 2025-06-30 09:27:57.317779+00
commit_lsn            | 0/15A2780
remote_insert_lsn     | 0/15A2780
received_lsn          | 0/15A2780
replication_lag_bytes | 0
replication_lag       | 00:00:04.014177

The following table describes the columns displayed by spock.lag_tracker:

Column NameDescription
origin_nameName of the provider node.
receiver_nameName of the subscriber node.
commit_timestampCommit time of the last transaction received from the provider.
commit_lsnLog sequence number (LSN) of the commit on the provider.
remote_insert_lsnWAL insert position on the provider when the commit was sent.
received_lsnLast acknowledged log sequence number (LSN) received from the provider.
replication_lag_bytesThe amount of data the subscriber is behind.
replication_lagTime 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.

PG.CENTER edition

2.10.3 - Monitoring a Node with the Spock Status Views

Spock keeps the state of a node in shared memory and exposes it through a set of views in the spock schema.

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.

ViewOne row perPurpose
spock.system_statushostHost and instance health: disk, load, connections, long transactions, wraparound age, archiving.
spock.node_statusnodeThe whole node on one row: versions, counts, WAL, lag, last events.
spock.subscription_statussubscriptionConfiguration, status, serving worker, replication position and lag, last error.
spock.subscription_statssubscriptionActivity counters: worker starts, connects, transactions, tuples, conflicts, errors.
spock.worker_statusspock processSupervisor, manager, apply and sync workers with their state.
spock.slot_statusreplication slotProvider side: walsender state, positions and retained WAL per spock slot.
spock.table_sync_statussubscription or tableInitial synchronization state in readable form.
spock.peer_statusknown nodeEvery node this node knows, with the subscription that brings its changes here.
spock.replication_set_statusreplication setReplication sets of the local node with table, sequence and subscriber counts.
spock.settingsparameterThe spock parameters and the core parameters replication depends on.
spock.eventseventRecent 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.

ColumnDescription
hostname, os_name, os_release, architecture, cpu_count, memory_bytesThe host.
load_average_1min, load_average_5min, load_average_15minSystem load averages.
data_directory, data_disk_total_bytes, data_disk_free_bytesThe data directory and the space on its volume.
wal_disk_total_bytes, wal_disk_free_bytes, wal_size_bytesThe volume holding pg_wal, measured separately in case it is a symlink, and the size of pg_wal.
database_size_bytesSize of the current database.
postgres_version, postmaster_pid, postmaster_start_time, uptime, in_recoveryThe instance.
max_connections, connections, active_connections, idle_in_transactionClient connections and their state.
longest_transaction, longest_idle_in_transactionAge of the oldest open transaction and of the oldest idle one; both hold back vacuum and slot catalog_xmin.
waiting_on_locksSessions currently waiting for a lock.
prepared_transactionsPrepared transactions, which hold locks and xmin until resolved.
physical_standbysStreaming replicas other than spock subscribers.
oldest_xid_ageAge of the database’s oldest transaction id, towards wraparound.
xact_commit, xact_rollback, deadlocks, recovery_conflicts, temp_files, temp_bytes, checksum_failures, database_stats_resetFrom pg_stat_database for this database.
archive_mode, archived_count, last_archived_time, archive_failed_count, last_archive_failureWAL archiving state; a failing archiver fills the WAL volume.
SELECT pg_size_pretty(data_disk_free_bytes) AS data_free,
       pg_size_pretty(wal_disk_free_bytes) AS wal_free,
       load_average_1min, connections, max_connections,
       longest_transaction, idle_in_transaction, deadlocks,
       archive_failed_count, last_archive_failure
  FROM spock.system_status;

Node status

spock.node_status always returns exactly one row, even before a node has been created.

ColumnDescription
node_id, node_name, location, countryThe local node, NULL when none exists.
database_nameThe current database.
hostname, operating_system, postmaster_start_timeThe host and the server start.
spock_versionVersion of the loaded shared library.
extension_versionVersion of the installed extension in the catalog.
extension_update_pendingTrue when the library is newer than the extension; the manager runs ALTER EXTENSION UPDATE on its next start.
postgres_versionServer version.
spock_started_atWhen spock shared memory was initialized, normally the postmaster start.
postmaster_pid, supervisor_pid, manager_pidProcess ids of the postmaster, the supervisor and this database’s manager.
readonly_modeCurrent value of spock.readonly.
apply_pausedTrue while spock.pause_apply_workers() is in effect.
worker_slots, worker_slots_usedBackground worker slots spock can use and how many are taken.
subscriptions, subscriptions_enabled, subscriptions_replicatingSubscription counts.
replication_slots, replication_slots_activeSpock slots of this database and how many have a connected walsender.
apply_workers, sync_workersRunning worker counts.
workers_restart_pendingWorkers that exited with an error and wait for the manager to restart them.
pending_exceptionsTransactions currently being retried under spock.exception_behaviour.
replicated_tables, unreplicated_tablesTables of this node in some replication set, and tables in none.
current_wal_lsnCurrent WAL position, replay position on a standby.
wal_size_bytesSize 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_bytesFree space on the volumes holding the data directory and pg_wal.
max_retained_wal_bytesWAL held back by the slowest spock slot.
max_replication_lag_bytes, max_replication_lagLargest lag over all subscriptions.
exceptions_loggedRows in spock.exception_log.
last_event_time, last_error_event_timeTime of the newest event, and of the newest error event.
events_retained, events_recordedEvents kept in the history and recorded since start.
SELECT node_name, extension_update_pending, subscriptions_replicating,
       replication_slots_active, workers_restart_pending,
       pg_size_pretty(max_retained_wal_bytes) AS retained_wal,
       max_replication_lag, last_error_event_time
  FROM spock.node_status;

Subscription status

spock.subscription_status is the first place to look when replication seems stuck.

ColumnDescription
subscription_id, subscription_name, enabledThe subscription.
statusreplicating, 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_dsnThe 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_atConfiguration.
sync_statusInitial synchronization state of the subscription as a whole.
worker_pid, worker_status, worker_started_atThe apply worker. worker_status is restart pending after a failure.
worker_terminated_at, worker_restart_delayWhen the last worker failed and how long the manager waits before restarting it, in milliseconds.
worker_pausedTrue while the worker sleeps because apply is paused.
in_exception_handlingTrue while the worker replays a failed transaction under spock.exception_behaviour.
pending_exception_lsn, pending_exception_errorCommit LSN and first error of the transaction being retried, if any.
origin_lsnLast durably applied provider LSN, from spock.replication_origin_status().
remote_commit_lsn, remote_commit_ts, remote_insert_lsn, received_lsnPositions from spock.progress.
replication_lag_bytesWAL the provider has written that this node has not yet applied.
replication_lagTime between the last applied commit on the provider and its apply here.
last_message_received, last_xact_appliedWhen data last arrived from the provider and when a transaction was last committed here.
time_since_last_messageHow long ago data last arrived; a silent provider shows here first.
worker_blocked_by_pids, worker_blocking_pid, worker_blocking_querySet while the worker waits for a lock: the sessions holding it and what the first one runs.
worker_starts, worker_failures, xacts_applied, apply_errorsCounters from spock.subscription_stats.
last_apply_error, last_error_sqlstate, last_error_pid, last_error_messageThe most recent error of the apply worker: when, its SQLSTATE, the process that raised it, and the message with DETAIL and CONTEXT.
SELECT subscription_name, status, worker_status, replication_lag,
       pg_size_pretty(replication_lag_bytes) AS lag, last_error_message
  FROM spock.subscription_status;

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.

ColumnDescription
worker_starts, worker_failuresApply worker starts, and exits with an error.
sync_worker_starts, sync_worker_failuresThe same for the sync workers that copy tables; a resync adds one start per table.
provider_connects, provider_disconnects, idle_timeoutsConnections 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_receivedData messages received from the provider.
xacts_applied, xacts_skipped, xacts_discardedTransactions committed locally, skipped through sub_skip_lsn, and discarded under transdiscard.
apply_errors, sync_errorsErrors raised in apply and in sync workers. An apply error counts once per failed transaction.
deadlocks, lock_timeouts, constraint_violations, resource_errorsThe same errors classified by SQLSTATE: deadlock detected, lock not available, class 23 and class 53.
tables_syncedTables whose initial synchronization completed.
n_tup_ins, n_tup_upd, n_tup_del, n_conflict, n_dcaTuple 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_pidThe most recent worker error with DETAIL and CONTEXT, the provider LSN it happened at, its SQLSTATE and the process that raised it.
stats_resetWhen 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.

ColumnDescription
worker_slot, worker_type, pidSlot in shared memory, supervisor, manager, apply or sync, and process id.
worker_statusstarting, running, idle, stopping, stopped, failed or restart pending.
subscription_id, subscription_nameFor apply and sync workers.
sync_schema_name, sync_table_nameThe table a sync worker copies.
started_at, xact_start, backend_state, wait_event_type, wait_eventFrom pg_stat_activity.
blocked_by_pids, blocking_pid, blocking_xact_start, blocking_querySet while the worker waits for a lock held by another session, from pg_blocking_pids().
paused, in_exception_handling, sync_pendingApply worker flags.
replay_stop_lsn, remote_wal_insert_lsnPositions the worker works towards and has last seen on the provider.
generation, terminated_at, restart_delayRegistration 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.

ColumnDescription
slot_name, active, active_pidThe slot and its walsender.
client_name, client_addr, connected_at, stateThe connected subscriber, from pg_stat_replication.
restart_lsn, confirmed_flush_lsn, sent_lsn, write_lsn, flush_lsn, replay_lsnPositions.
retained_wal_bytesWAL kept on disk for this slot.
pending_wal_bytesWAL the subscriber has not confirmed yet.
write_lag, flush_lag, replay_lag, last_reply_timeFeedback timing.
wal_status, safe_wal_size, catalog_xmin, catalog_xmin_age, temporary, two_phaseFrom pg_replication_slots; a growing catalog_xmin_age means the slot holds back catalog vacuum.
decoded_txns, decoded_bytes, spill_*, stream_*, decode_stats_resetDecoding 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.
SELECT slot_name, active, state, pg_size_pretty(retained_wal_bytes) AS retained,
       pg_size_pretty(pending_wal_bytes) AS pending, replay_lag
  FROM spock.slot_status;

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.

ColumnDescription
event_idIncreases by one per event and is never reused.
event_time, event_type, severityWhen, what, and info, warning or error.
sqlstateThe SQLSTATE of a worker_error or stream_error event.
subscription_id, subscription_name, provider_nodeThe subscription concerned, if any, and the node its changes come from.
pidThe reporting process.
lsnThe 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.
detailA short description.

Event types:

TypeRecorded when
node_created, node_droppedspock.node_create() and spock.node_drop() complete.
subscription_created, subscription_droppedA subscription is created or dropped.
subscription_enabled, subscription_disabledA subscription is enabled or disabled, by an operator or by exception handling.
subscription_alteredInterface, replication sets, skip_lsn, options or a synchronization request changed.
worker_started, worker_stopped, worker_failedA manager, apply or sync worker starts, exits cleanly, or exits with an error.
worker_errorAn error is raised inside an apply or sync worker. The detail carries the message with DETAIL and CONTEXT.
provider_connected, provider_disconnectedThe replication connection to the named provider is established, with the start LSN, or lost, with the error.
transaction_skipped, transaction_discardedA transaction is skipped through sub_skip_lsn or discarded under transdiscard.
sync_started, sync_finished, sync_failedInitial 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_errorProvider 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_resumedspock.pause_apply_workers() and spock.resume_apply_workers().
repair_mode_enabled, repair_mode_disabledspock.repair_mode().
extension_upgradedThe manager updated the extension to the library version.

Events are recorded when the reporting code runs, whether or not the surrounding transaction commits.

SELECT event_time, event_type, subscription_name, detail
  FROM spock.events
 WHERE severity <> 'info'
 ORDER BY event_id DESC
 LIMIT 20;

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.

SELECT * FROM spock.node_report();
SELECT * FROM spock.node_report(200);   -- list up to 200 events, exceptions and resolutions

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.

SELECT node_name, extension_update_pending,
       subscriptions_enabled, subscriptions_replicating,
       workers_restart_pending, apply_paused, readonly_mode,
       pg_size_pretty(max_retained_wal_bytes) AS retained_wal,
       max_replication_lag, last_error_event_time
  FROM spock.node_status;

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.

SELECT subscription_name, status, enabled, worker_status,
       worker_terminated_at, worker_restart_delay,
       in_exception_handling, last_apply_error, last_error_message
  FROM spock.subscription_status
 WHERE status <> 'replicating';

Then read the events of that subscription, newest first:

SELECT event_time, event_type, severity, detail
  FROM spock.events
 WHERE subscription_name = 'sub_n2_n1'
 ORDER BY event_id DESC
 LIMIT 20;

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.

SELECT worker_type, subscription_name, wait_event_type, wait_event,
       blocked_by_pids, blocking_pid, blocking_xact_start, blocking_query
  FROM spock.worker_status
 WHERE blocked_by_pids IS NOT NULL;

SELECT subscription_name, deadlocks, lock_timeouts,
       constraint_violations, resource_errors,
       last_error_sqlstate, last_apply_error, last_error_message
  FROM spock.subscription_stats;

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.

SELECT subscription_name, worker_starts, worker_failures,
       last_worker_failure, last_error_message
  FROM spock.subscription_stats
 WHERE worker_failures > 0;

SELECT event_time, event_type, detail
  FROM spock.events
 WHERE event_type IN ('worker_started', 'worker_failed', 'worker_error')
 ORDER BY event_id DESC
 LIMIT 30;

What changed overnight?

Everything that is not routine has a severity above info.

SELECT event_time, event_type, severity, subscription_name, detail
  FROM spock.events
 WHERE event_time > now() - interval '12 hours'
   AND severity <> 'info'
 ORDER BY event_id;

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?

SELECT subscription_name, provider_node,
       pg_size_pretty(replication_lag_bytes) AS lag_bytes,
       replication_lag, remote_commit_ts, received_lsn, origin_lsn
  FROM spock.subscription_status
 ORDER BY replication_lag_bytes DESC NULLS LAST;

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.

SELECT slot_name, active, client_name, state,
       pg_size_pretty(retained_wal_bytes) AS retained,
       pg_size_pretty(pending_wal_bytes) AS pending,
       replay_lag, last_reply_time, wal_status
  FROM spock.slot_status
 ORDER BY retained_wal_bytes DESC;

Is the initial synchronization finished?

SELECT subscription_name, schema_name, table_name, sync_kind, sync_status
  FROM spock.table_sync_status
 WHERE sync_status NOT IN ('ready', 'synchronized');

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.

SELECT spock_version, extension_version, extension_update_pending
  FROM spock.node_status;

SELECT event_time, detail
  FROM spock.events
 WHERE event_type = 'extension_upgraded';

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.

SELECT spock.reset_subscription_stats();   -- all subscriptions
SELECT spock.reset_subscription_stats(sub_id)
  FROM spock.subscription WHERE sub_name = 'sub_n2_n1';
SELECT spock.reset_events();

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:

GRANT pg_monitor TO monitoring_role;
GRANT USAGE ON SCHEMA spock TO monitoring_role;

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.

FunctionReturns
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.

PG.CENTER edition

2.10.4 - Using spock.sync_event to Confirm Synchronization

spock.syncevent enables event tracking and synchronization between a provider and a subscriber node in a Spock logical replication setup.

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_id or origin: 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 is false.

    When wait_if_disabled is false (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:

    ERROR:  No subscription found for replication 16443 => 16444
    ERROR:  Subscription 16443 => 16444 has been disabled

    When wait_if_disabled is true, neither condition is an error. The procedure keeps polling until the subscription exists, becomes enabled, and reaches the target LSN, or until timeout expires. 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-zero timeout so a subscription that is never created does not wait forever.

    wait_if_disabled only 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:

    ERROR:  Origin node 'provider_node' not found
    ERROR:  Invalid NULL origin_id

    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 the origin_id once 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. With wait_if_disabled = true this 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:

CALL spock.wait_for_sync_event(NULL, 'provider_node', '0/16342B0', 10);
-- result: true  (if applied within 10s), false otherwise

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:

CALL spock.wait_for_sync_event(NULL, 'provider_node', '0/16342B0', 300, true);
-- result: true once the subscription is enabled and has applied the LSN,
-- false if 300s elapse first (including if the subscription never appeared)

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.

PG.CENTER edition

2.11 - Spock Functions

The following user functions are available via 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 following user functions are available via the Spock extension:

CommandDescription
Node Management FunctionsYou can add and remove nodes dynamically using Spock interfaces.
spock.node_infoReturns information about the node on which the function is invoked.
spock.node_createDefine a node for spock.
spock.node_dropRemove a spock node.
node_add_interfaceAdd a new node interface.
spock.node_drop_interfaceDelete a node interface.
spock.node_alterChange this node’s own location, country, and/or info (merging info), validating a tiebreaker if one is set.
spock.node_refresh_infoRefresh this node’s cached copy of a peer’s (or every peer’s) location, country, and info.
Replication Set Management FunctionsReplication 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_createDefine a replication set.
spock.repset_alterModify a replication set.
repset_dropRemove a replication set.
spock.repset_add_partitionAdd a partition to a replication set.
spock.repset_remove_partitionRemove a partition from the replication set that the parent table is a part of.
spock.repset_add_tableAdd table(s) to replication set.
spock.repset_add_all_tablesAdd all existing table(s) to the replication set.
spock.repset_remove_tableRemove table from replication set.
spock.repset_show_table
spock.repset_add_seqAdds a sequence to a replication set.
spock.repset_add_all_seqsAdds all sequences from the specified schemas to a replication set.
spock.repset_remove_seqRemove a sequence from a replication set.
spock.sync_seqSynchronize the specified sequence.
Subscription Management Functions
spock.sub_createCreate a subscription.
spock.sub_dropDelete a subscription.
spock.sub_disablePut a subscription on hold, and disconnect from the provider.
spock.sub_enableMake a subscription live.
spock.sub_add_repsetAdd a replication set to a subscription.
spock.sub_remove_repsetDrop a replication set from a subscription.
spock.sub_show_statusDisplay the status of the subcription.
spock.sub_show_tableShow subscription tables.
spock.sub_alter_interfaceModify an interface to a subscription.
spock.sub_wait_for_syncPause until the subscription is synchronized.
spock.sub_alter_skiplsnSkip transactions until the specified lsn.
spock.sub_alter_syncSynchronize all missing tables.
spock.sub_alter_optionsChange one or more subscription options in a single atomic operation.
spock.sub_resync_tableSynchronize a specific table.
Miscellaneous Management Functions
spock.table_wait_for_syncPause until a table finishes synchronizing.
spock.replicate_ddlEnable DDL replication.
spock_versionReturns 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_numReturns the Spock version in a single numeric form: 40010. Defined in the public schema so invoked without the spock. prefix.
spock.get_channel_statsReturns tuple traffic statistics.
spock.get_apply_statsReturns the activity counters of every subscription; the source of the spock.subscription_stats view.
spock.get_eventsReturns the recent events of the node; the source of the spock.events view.
spock.get_monitor_summaryReturns capacity and usage of the spock shared memory structures.
spock.get_pending_exceptionsReturns the transactions apply workers are retrying under exception handling.
spock.get_system_infoReturns host, operating system and version information of the node.
spock.get_slot_groupsReturns the slot groups with attached walsenders.
spock.get_subscription_statsReturns the conflict counters of a subscription (PostgreSQL 18 and later).
spock.get_worker_statusReturns every spock worker slot; the source of the spock.worker_status view.
spock.get_countryReturns the country code if explicitly set; returns ?? if not set.
spock.lag_trackerReturns a list of slots, with commit_lsn and commit_timestamp for each.
spock.repair_modeUsed to manage the state of replication - If set to true, stops replicating statements, including DDL; when false, resumes replication.
spock.replicate_ddlReplicate a specific statement.
spock.redact_dsnReturns a connection string with its password hidden.
spock.reset_channel_statsReset the channel statistics.
spock.reset_eventsClears the event history shown by spock.events.
spock.reset_subscription_statsResets the activity and conflict counters of one subscription, or of all subscriptions.
spock.report_sectionRenders the rows of a query as an aligned text table or as one block per row.
spock.node_reportReturns the whole node as a text report: versions, settings and every monitoring view.
spock_max_proto_versionThe highest Spock native protocol supported by the current binary/build. Defined in the public schema so invoked without the spock. prefix.
spock_min_proto_versionThe lowest build for which this Spock binary is backward compatible. Defined in the public schema so invoked without the spock. prefix.
spock.table_data_filteredScans 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_transactionsTerminates all active transactions.
spock.wait_slot_confirm_lsnWait for the confirmed_flush_lsn of the specified slot, or all logical slots if none given.
spock.xact_commit_timestamp_originReturns 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.

PG.CENTER edition

2.11.1 - Spock Functions

You can access the reference pages in this section via online help; at the terminal window, enter:

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.

PG.CENTER edition

2.11.1.1 - spock.cleanup_resolutions

The spock.cleanupresolutions() function manually deletes old rows from the spock.resolutions 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.cleanup_resolutions() function manually deletes old rows from the spock.resolutions table.

Synopsis

spock.cleanup_resolutions(days integer DEFAULT NULL) RETURNS bigint

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. Overrides spock.resolutions_retention_days for this call. Pass an explicit value to perform a one-off cleanup when automatic cleanup is disabled (resolutions_retention_days = 0). Default is NULL (use the GUC value).

Example

Delete rows older than the configured retention window:

SELECT spock.cleanup_resolutions();

Delete rows older than 60 days, regardless of the GUC setting:

SELECT spock.cleanup_resolutions(60);

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.

PG.CENTER edition

2.11.1.2 - spock.gen_slot_name()

spock.spockgenslotname(dbname name, providernode name, subscription 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.

PG.CENTER edition

2.11.1.3 - spock.get_country()

The country code configured for the node as text, or ?? if not set.

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.

PG.CENTER edition

2.11.1.4 - spock.max_proto_version()

The maximum spock protocol version supported by the installed Spock extension as an integer.

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.

PG.CENTER edition

2.11.1.5 - spock.min_proto_version()

The minimum Spock protocol version supported by the installed Spock extension as an integer.

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.

PG.CENTER edition

2.11.1.6 - spock.node_add_interface()

spock.nodeaddinterface (nodename name, interfacename name, dsn text)

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.

PG.CENTER edition

2.11.1.7 - spock.node_alter()

spock.nodealter (plocation text DEFAULT NULL, pcountry text DEFAULT NULL, pinfopatch jsonb DEFAULT NULL)

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.

PG.CENTER edition

2.11.1.8 - spock.node_create()

spock.nodecreate (nodename name, dsn text, location text, country text, info jsonb)

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.

PG.CENTER edition

2.11.1.9 - spock.node_drop_interface()

spock.nodedropinterface (nodename name, interfacename 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.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.

PG.CENTER edition

2.11.1.10 - spock.node_drop()

spock.nodedrop(nodename name, ifexists boolean)

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.

PG.CENTER edition

2.11.1.11 - spock.node_info()

A record containing information about the local Spock node:

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.

PG.CENTER edition

2.11.1.12 - spock.node_refresh_info()

spock.noderefreshinfo (pnodename name DEFAULT NULL)

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.

PG.CENTER edition

2.11.1.13 - spock.replicate_ddl()

spock.replicateddl (command text[], replicationsets text[], searchpath text, role text)

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.

PG.CENTER edition

2.11.1.14 - spock.repset_add_all_seqs()

spock.repsetaddallseqs (setname name, schemanames text[], synchronizedata boolean)

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.

PG.CENTER edition

2.11.1.15 - spock.repset_add_all_tables()

spock.repsetaddalltables (setname name, schemanames text[], synchronizedata boolean)

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.

PG.CENTER edition

2.11.1.16 - spock.repset_add_partition()

spock.repsetaddpartition ( parent regclass, partition regclass, rowfilter text)

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.

PG.CENTER edition

2.11.1.17 - spock.repset_add_seq()

spock.repsetaddseq ( setname name, relation regclass, synchronizedata boolean)

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.

PG.CENTER edition

2.11.1.18 - spock.repset_add_table()

spock.repsetaddtable ( setname name, relation regclass, synchronizedata boolean, columns text[], rowfilter text, includepartitions boolean )

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.

PG.CENTER edition

2.11.1.19 - spock.repset_alter()

spock.repsetalter ( setname name, replicateinsert boolean, replicateupdate boolean, replicatedelete boolean, replicatetruncate boolean )

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.

PG.CENTER edition

2.11.1.20 - spock.repset_create()

spock.repsetcreate ( setname name, replicateinsert boolean = true, replicateupdate boolean = true, replicatedelete boolean = true, replicatetruncate boolean = true )

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.

PG.CENTER edition

2.11.1.21 - spock.repset_drop()

spock.repsetdrop (setname name, ifexists boolean)

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.

PG.CENTER edition

2.11.1.22 - spock.repset_remove_partition()

spock.repsetremovepartition (parent regclass, partition regclass)

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.

PG.CENTER edition

2.11.1.23 - spock.repset_remove_seq()

spock.repsetremoveseq ( setname name, relation regclass)

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.

PG.CENTER edition

2.11.1.24 - spock.repset_remove_table()

spock.repsetremovetable ( setname name, relation regclass, includepartitions boolean)

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.

PG.CENTER edition

2.11.1.25 - spock.repset_show_table()

spock.repsetshowtable (relation regclass, repsets text[])

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.

PG.CENTER edition

2.11.1.26 - spock.sub_add_repset()

spock.subaddrepset (subscriptionname name, replicationset 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.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.

PG.CENTER edition

2.11.1.27 - spock.sub_alter_interface()

spock.subalterinterface (subscriptionname name, interfacename 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.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.

PG.CENTER edition

2.11.1.28 - spock.sub_alter_options()

spock.subalteroptions (subscriptionname name, options jsonb)

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 options object contained at least one key; the Spock catalog is updated and the apply worker is signalled to restart.

  • false if the options object was empty ({}); the catalog is not touched and the apply worker is not restarted.

  • Raises an ERROR if the subscription does not exist, if options is 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.

PG.CENTER edition

2.11.1.29 - spock.sub_alter_skiplsn()

spock.subalterskiplsn (subscriptionname name, lsn pglsn) RETURNS boolean

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.

PG.CENTER edition

2.11.1.30 - spock.sub_alter_sync

The spock.subaltersync() function synchronizes all unsynchronized tables in all sets in a single operation.

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

spock.sub_alter_sync(subscription_name name, truncate boolean DEFAULT false)
RETURNS boolean

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_name argument specifies the name of an existing subscription.
  • The truncate argument accepts a boolean value; when set to true, the function truncates tables before copying, and the default value is false.

Example

In the following example, the spock.sub_alter_sync() function synchronizes all unsynchronized tables for a subscription named sub_n1_n2:

SELECT spock.sub_alter_sync('sub_n1_n2', 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.

PG.CENTER edition

2.11.1.31 - spock.sub_create()

spock.subcreate (subscriptionname name, providerdsn text, replicationsets text[], synchronizestructure boolean, synchronizedata boolean, forwardorigins text[], applydelay interval, forcetexttransfer boolean, enabled boolean, skipschema text[])

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.

PG.CENTER edition

2.11.1.32 - spock.sub_disable

The spock.subdisable() function disables a subscription and disconnects from the provider.

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

spock.sub_disable(subscription_name name, immediate boolean DEFAULT false)

Arguments

The function accepts the following arguments:

  • subscription_name - The name of an existing subscription.
  • immediate - If true, the subscription is disabled immediately; otherwise it is disabled at the end of the current transaction. The default is false.

Example

In the following example, the spock.sub_disable() function disables a subscription named sub_n1_n2:

SELECT spock.sub_disable('sub_n1_n2');
 sub_disable
-------------
 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.

PG.CENTER edition

2.11.1.33 - spock.sub_drop()

spock.subdrop (subscriptionname name, ifexists boolean)

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.

PG.CENTER edition

2.11.1.34 - spock.sub_enable

The spock.subenable() function enables a subscription.

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

spock.sub_enable(subscription_name name, immediate boolean)

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 - If true, the subscription is started immediately; otherwise the subscription will be started only at the end of the current transaction. The default is false.

Example

In the following example, the spock.sub_enable() function enables a subscription named sub_n1_n2:

SELECT spock.sub_enable('sub_n1_n2');
 sub_enable
-------------
 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.

PG.CENTER edition

2.11.1.35 - spock.sub_remove_repset

The spock.subremoverepset() function removes a replication set from a subscription.

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

spock.sub_remove_repset(subscription_name name, replication_set name)

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:

select spock.sub_remove_repset('sub_n1_n2', 'test');
 sub_remove_repset 
-------------------
 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.

PG.CENTER edition

2.11.1.36 - spock.sub_resync_table

The spock.subresynctable() function resynchronizes one existing 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

spock.sub_resync_table(subscription_name name, relation regclass, truncate boolean DEFAULT true)

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 is true. Omitting the argument truncates the target table. Pass false to 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:

SELECT spock.sub_resync_table('sub_n1_n2', 'public.users');
 sub_resync_table
------------------
 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.

PG.CENTER edition

2.11.1.37 - spock.sub_show_status

The spock.subshowstatus() function displays the status and basic information about a subscription.

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

spock.sub_show_status(subscription_name name DEFAULT NULL)

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:

StatusDescription
replicatingThe apply worker is running and initial synchronization is complete; changes from the provider are being applied normally.
initializingThe apply worker is running but initial synchronization has not yet completed; table data is still being copied from the provider.
disabledThe subscription was explicitly disabled with spock.sub_disable(); the apply worker is not running.
downThe subscription is enabled but the apply worker is not running; the worker may not have started yet or may have exited unexpectedly.
unknownThe 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:

SELECT * FROM spock.sub_show_status();

In the following example, the spock.sub_show_status() function displays the status of a subscription named sub_n1_n2:

SELECT * FROM spock.sub_show_status('sub_n1_n2');
-[ RECORD 1 ]-----+--------------------------------------------------------------------
subscription_name | sub_n1_n2
status            | replicating
provider_node     | n2
provider_dsn      | host=192.168.105.11 dbname=postgres user=postgres password=<redacted>
slot_name         | spk_postgres_n2_sub_n1
replication_sets  | {default,default_insert_only,ddl_sql,audit_only}
forward_origins   |

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.

PG.CENTER edition

2.11.1.38 - spock.sub_show_table

The spock.subshowtable() function displays the synchronization status of a 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

spock.sub_show_table(subscription_name name, relation regclass,
                     OUT nspname text, OUT relname text, OUT status text)

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:

SELECT * FROM spock.sub_show_table('sub_n2', 'test');
-[ RECORD 1 ]----
nspname | public
relname | test
status  | unknown

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.

PG.CENTER edition

2.11.1.39 - spock.sub_wait_for_sync

The spock.subwaitforsync() function waits until a specified subscription has completed its initial schema and data 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.

The spock.sub_wait_for_sync() function waits until a specified subscription has completed its initial schema and data synchronization.

Synopsis

spock.sub_wait_for_sync(subscription_name name)

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:

SELECT spock.sub_wait_for_sync('sub_n2_n1');
-[ RECORD 1 ]-----+-
sub_wait_for_sync |

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.

PG.CENTER edition

2.11.1.40 - spock.sync_event

The spock.syncevent() function creates a synchronization event in the replication stream and returns its Log Sequence Number (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.

The spock.sync_event() function creates a synchronization event in the replication stream and returns its Log Sequence Number (LSN).

Synopsis

spock.sync_event(transactional boolean DEFAULT false)

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, default false) - When false, the sync event marker is emitted immediately into the WAL stream, independent of the calling transaction. When true, 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:

SELECT spock.sync_event();
-[ RECORD 1 ]---------
sync_event | 0/333F410

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.

PG.CENTER edition

2.11.1.41 - spock.sync_seq

The spock.syncseq() function synchronizes the current state of a sequence to all subscribers.

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

spock.sync_seq(relation regclass) RETURNS boolean

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:

SELECT spock.sync_seq('public.sales_order_no_seq');
 sync_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.

PG.CENTER edition

2.11.1.42 - spock.table_wait_for_sync()

spock.tablewaitforsync (subscriptionname name, relation regclass)

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.

PG.CENTER edition

2.11.1.43 - spock.version_num()

The version number of the installed Spock extension as an integer.

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.

PG.CENTER edition

2.11.1.44 - spock.version()

Returns the Spock version in a human-readable major/minor form (for example, 5.0.5).

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

postgres=# SELECT spock.spock_version();
 spock_version
---------------
 5.0.5
(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.

PG.CENTER edition

2.11.1.45 - spock.wait_slot_confirm_lsn()

spock.waitslotconfirmlsn (slotname name, target pglsn)

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.

PG.CENTER edition

2.11.1.46 - spock.xact_commit_timestamp_origin()

spock.xactcommittimestamporigin (xid xid, OUT timestamp timestamptz, OUT roident oid)

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.

PG.CENTER edition

2.11.2 - Management Functions

You can use the following settings to manage your replication clusters.

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.

CommandDescription
spock.get_countryReturns the country code configured for the node.
spock_max_proto_versionReturns the maximum protocol version supported by Spock. Defined in the public schema so invoked without the spock. prefix.
spock_min_proto_versionReturns the minimum protocol version supported by Spock. Defined in the public schema, so invoked without the spock. prefix.
spock.node_infoReturns information about the local Spock node.
spock_versionReturns the version string of the Spock extension. Defined in the public schema so invoked without the spock. prefix.
spock_version_numReturns 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.

PG.CENTER edition

2.11.3 - Node Management

Use commands listed in this section to manage the nodes in your replication 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.

Use commands listed in this section to manage the nodes in your replication cluster.

CommandDescription
spock.node_add_interfaceAdd an additional interface to a node.
spock.node_createCreate a spock node.
spock.node_dropDrop a spock node.
spock.node_drop_interfaceRemove an existing interface from a node.
spock.node_infoReturns information about the local Spock node.
spock.node_alterChange this node’s own location, country, and/or info (merging info), validating a tiebreaker if one is set.
spock.node_refresh_infoRefresh 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:

SELECT spock.node_create(node_name, dsn)

Parameters include:

  • a name for the node.
  • the dsn of the server on which the node resides.
Note

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:

SELECT spock.node_create('n1', 'host=178.12.15.12 user=carol dbname=accounting');

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:

SELECT spock.node_drop(node_name, ifexists)

Parameters include:

  • the name of the node.
  • ifexists is a boolean value that suppresses an error if the node does not exist when set to true.

For example, the following command:

SELECT spock.node_drop('n1', true);

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_name is the name of the new node; only one node is allowed per database.
  • dsn is 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. A tiebreaker key 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_name is the name of an existing node.
  • ifexists specifies the Spock extension behavior with regards to error messages. If true, an error is not thrown when the specified node does not exist. The default is false.

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_name is the name of an existing node.
  • interface_name is the name of a new interface to be added.
  • dsn is 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_name is the name of an existing node.
  • interface_name is 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:

ColumnTypeDescription
node_idoidThe object identifier of the local node.
node_nametextThe name of the local node.
sysidtextThe PostgreSQL system identifier for this instance.
dbnametextThe name of the current database.
replication_setstextComma-separated list of replication sets associated with this node.
locationtextOptional location label; NULL if not set during node creation.
countrytextOptional country label; NULL if not set during node creation.
infojsonbOptional 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’s location; left unchanged if omitted.
  • p_country (optional) replaces this node’s country; left unchanged if omitted.
  • p_info_patch (optional) is merged into this node’s existing info; left unchanged if omitted. A tiebreaker key 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.

PG.CENTER edition

2.11.4 - Replication Set Management

Replication sets provide a mechanism to control which tables in the database will be replicated and which actions on those tables will be replicated.

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.

CommandDescription
spock.repset_createCreate a new replication set.
spock.repset_alterModify an existing replication set.
spock.repset_dropRemove a replication set.
spock.repset_add_tableAdds a table to replication set.
spock.repset_add_all_tablesAdds all tables in a given schema(s).
spock.repset_remove_tableRemove a table from replication set.
spock.repset_add_seqAdds a sequence to a replication set.
spock.repset_add_all_seqsAdds all sequences from the given schemas.
spock.repset_remove_seqRemove a sequence from a replication set.
spock.sub_add_repsetAdds a replication set to a subscriber.
spock.sub_remove_repsetRemoves 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:

SELECT spock.repset_create(replication_set_name, replicate_insert,
    replicate_update, replicate_delete, replicate_truncate)

Parameters include:

  • replication_set_name is the name of the replication set.

Use the four remaining parameters to specify the content type to replicate:

  • when replicate_insert is true, INSERT statements are replicated; the default is true.
  • when replicate_update is true, UPDATE statements are replicated; the default is true.
  • when replicate_delete is true, DELETE statements are replicated; the default is true.
  • when replicate_truncate is true, TRUNCATE statements are replicated; the default is true.

For example, the following command:

SELECT spock.repset_create('accts', true, true, true, false);

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:

SELECT 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 include:

  • set_name is the name of an existing replication set.
  • relation is the name or OID of the table to add.
  • synchronize_data is a boolean value that instructs the server to synchronize table data on all related subscribers; the default is false.
  • columns specifies a list of columns to replicate; the default is NULL (all columns).
  • row_filter is a row filtering expression; the default is NULL (no filtering).
  • include_partitions is a boolean value; specify true to include all partitions; the default is true.

For example, the following command:

SELECT spock.repset_add_table('accts', 'payables');

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: when false, AutoDDL keeps the object’s DDL node-local – it runs where issued but is not shipped to other nodes. The default is true.

    For an extension, CREATE EXTENSION, ALTER EXTENSION, DROP EXTENSION, COMMENT ON EXTENSION and SECURITY LABEL ON EXTENSION are kept local; run them on each node. A DROP EXTENSION that names both a node-local extension and a replicated one is refused while DDL replication is on; drop them in separate statements. CREATE EXTENSION ... CASCADE of 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 the CREATE EXTENSION without CASCADE. spock.replicate_ddl() refuses all of these statements for a node-local extension. Whatever a statement on a node-local extension does with CASCADE also stays on the local node: objects that depend on the extension are dropped only there, and extensions that CREATE EXTENSION ... CASCADE installs are installed only there.

    A statement that removes a node-local extension without naming it is not caught: DROP EXTENSION ... CASCADE of an extension it requires, DROP SCHEMA ... CASCADE of a schema it was created in, or DROP OWNED BY its 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: CREATE SCHEMA/TABLE/TABLE AS/SEQUENCE/VIEW/INDEX, ALTER TABLE, and DROP of those object kinds. Other DDL against the schema (for example GRANT, COMMENT, TRUNCATE, or ALTER ... SET SCHEMA) is not classified and replicates as usual. A single DROP is kept local only when every object it names is node-local; do not mix a node-local object and a replicated one in one DROP, 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:

Objectexclude_from_dumpblock_in_repsetreplicate_ddl
spockyesyesyes
snowflakeyesyesyes
loloryesnoyes
coldfrontyesnoyes
pgedge_ace (schema only)yesyesno

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:

-- keep a custom schema out of structure sync and out of replication sets
SELECT spock.reserved_object_add('ace', 'schema');

-- exclude an extension from the dump but still allow its tables in repsets
SELECT spock.reserved_object_add('myext', 'extension', p_block_in_repset := false);

-- keep a custom schema node-local: AutoDDL will not replicate its DDL
SELECT spock.reserved_object_add('myschema', 'schema', p_replicate_ddl := false);

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:

SELECT spock.repset_remove_table(set_name name, relation regclass,
    include_partitions boolean DEFAULT true)

Parameters include:

  • set_name is the name of the replication set in which the table resides.
  • relation is the name or OID of the table that will be removed.
  • include_partitions is a boolean value; specify true to also remove partitions of the partitioned table; the default is true.

For example, the following command:

SELECT spock.repset_remove_table('accts', 'payables');

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_name is the unique name of the set.
  • replicate_insert is true if INSERT statements are replicated; the default is true.
  • replicate_update is true if UPDATE statements are replicated; the default is true.
  • replicate_delete is true if DELETE statements are replicated; the default is true.
  • replicate_truncate is true if TRUNCATE statements are replicated; the default is true.

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_name is the name of an existing replication set that will be modified by this function.
  • replicate_insert is true if INSERT statements are replicated. Pass NULL (the default) to leave the current value unchanged.
  • replicate_update is true if UPDATE statements are replicated. Pass NULL (the default) to leave the current value unchanged.
  • replicate_delete is true if DELETE statements are replicated. Pass NULL (the default) to leave the current value unchanged.
  • replicate_truncate is true if TRUNCATE statements are replicated. Pass NULL (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_name is the name of an existing replication set.
  • ifexists controls whether dropping a non-existent replication set raises an error. When true, no error is raised if the set is missing; the default is false.

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_name is the name of an existing replication set.
  • relation is the name or OID of the table to be added to the set.
  • synchronize_data is true if the table data is to be synchronized on all subscribers which are subscribed to the specified replication set; the default is false.
  • columns is the list of columns to replicate. Normally when all columns should be replicated, this will be set to NULL (the default).
  • row_filter is a row filtering expression; the default is NULL (no filtering).
  • include_partitions is true to also add partitions of a partitioned table; the default is true.
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 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_name is the name of an existing replication set.
  • schema_names is an array of names of existing schemas from which tables should be added.
  • synchronize_data instructs Spock to synchronize the table data on all nodes which are subscribed to the given replication set when set to true; the default is false.

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_name is the name of an existing replication set.
  • relation is the name or OID of the table to be removed from the set.
  • include_partitions is true to also remove partitions of the partitioned table; the default is true.

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_name is the name of an existing replication set.
  • relation is the name or OID of the sequence to be added to the set.
  • synchronize_data instructs Spock to synchronize the sequence on all nodes which are subscribed to the given replication set when set to true; the default is false.

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_name is the name of an existing replication set.
  • schema_names is an array of names of existing schemas from which sequences should be added.
  • synchronize_data specify true to synchronize the sequence value immediately; the default is false.

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_name is the name of an existing replication set.
  • relation is 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_name is the name of an existing subscription.
  • replication_set is 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_name is the name of an existing subscription.
  • replication_set is 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_name is the schema or extension name.
  • p_kind is 'schema' or 'extension'.
  • p_exclude_from_dump keeps the object out of the structure-sync dump; the default is true.
  • p_block_in_repset blocks the object from replication sets; the default is true.
  • p_replicate_ddl: pass false to keep the object node-local so AutoDDL does not ship its DDL to other nodes (as pgedge_ace and the lolor extension are). The default is true, and an explicit NULL is taken as true.

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_name is the schema or extension name.
  • p_kind is '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.

PG.CENTER edition

2.11.5 - Subscription Management Functions

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.

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.

CommandDescription
spock.sub_createCreate a subscription.
spock.sub_dropDrop a subscription.
spock.sub_disableDisable a subscription and disconnect it from the provider.
spock.sub_enableEnables a disabled subscription.
spock.sub_alter_interfaceSwitch the subscription to use a different interface to connect to the provider node.
spock.sub_alter_syncSynchronize all unsynchronized tables in a single operation.
spock.sub_alter_optionsChange one or more subscription options in a single atomic operation.
spock.sub_resync_tableResynchronize a single table.
spock.sub_wait_for_syncWait for a subscription to finish synchronization after a spock.sub_create or spock.sub_alter_sync.
spock.table_wait_for_syncWait only for the subscription’s initial sync and a named table.
spock.sub_show_statusShows status and basic information about subscription.
spock.sub_show_tableShows synchronization status of a table.
spock.sub_add_repsetAdds a replication set to a subscriber.
spock.sub_remove_repsetRemoves 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:

SELECT spock.sub_create(subscription_name, provider_dsn, replication_sets,
    synchronize_structure, synchronize_data, forward_origins, apply_delay,
    force_text_transfer, enabled, skip_schema)

Parameters include:

  • subscription_name is the unique name of the subscription.
  • provider_dsn is the connection string to a provider.
  • replication_sets is 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_structure is a boolean value that specifies if Spock should synchronize the structure from provider to the subscriber; the default is false.
  • synchronize_data specifies if Spock should synchronize data from provider to the subscriber; the default is false.
  • forward_origins is 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_delay specifies how long to delay replication; the default is 0 seconds.
  • set force_text_transfer to true to 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 is false.
  • enabled controls whether the subscription is started immediately after creation. The default is true.
  • skip_schema is 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:

SELECT spock.sub_create('accts',
    'host=178.12.15.12 user=carol dbname=accounting',
    ARRAY['payables']);

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:

SELECT spock.sub_drop(subscription_name, ifexists)

Parameters include:

  • subscription_name is the name of the existing subscription.
  • if ifexists is true, an error is not thrown if the specified subscription does not exist; the default is false.

For example, the following command:

SELECT spock.sub_drop('accts', true);

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 — via spock.sub_create with enabled := true, spock.sub_enable, or spock.sub_alter_options on an already-enabled subscription — fails if another subscription is already enabled on this node.
  • Enabling a subscription (spock.sub_create with enabled := true, or spock.sub_enable) fails if another subscription on this node already has forwarding active.
  • Changing forward_origins on 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_name is the unique name of the subscription.
  • provider_dsn is the connection string to a provider.
  • replication_sets is an array of existing replication sets to which you are subscribing. The default is {default,default_insert_only,ddl_sql}.
  • synchronize_structure tells Spock if it should synchronize the structure from the provider to the subscriber; the default is false.
  • synchronize_data tells Spock to synchronize data from provider to the subscriber; the default is false.
  • forward_origins is 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_delay is the number of seconds to delay replication; the default is 0 seconds.
  • force_text_transfer forces 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 to true. The default is false.
  • enabled controls whether the subscription is started immediately after creation. The default is true.
  • skip_schema is 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_name is the name of an existing subscription.
  • ifexists tells the Spock extension how to handle the error if the subscription does not exist. If true, an error is not thrown if the subscription does not exist; the default is false.

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_name is the name of an existing subscription.
  • immediate tells Spock when to stop the subscription. If set to true, the subscription is stopped immediately; if set to false (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_name is the name of the existing subscription.
  • immediate tells Spock when to start the subscription. If set to true, the subscription is started immediately; if set to false (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_name is the name of an existing subscription.
  • interface_name is 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_name is the name of an existing subscription.
  • truncate tells Spock if it should truncate tables before copying. If true, tables will be truncated before copy; the default is false.

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.

Warning

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_name is the name of an existing subscription.
  • relation is 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_name is 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_name is the optional name of an existing subscription. If omitted (or NULL), 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_name is the name of an existing subscription.
  • relation is 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_name is the name of an existing subscription.
  • replication_set is 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_name is the name of the existing subscription.
  • replication_set is 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.

PG.CENTER edition

2.12 - Upgrading the Spock Extension

If you’re upgrading a secure production environment, shut down each node sequentially and perform the following steps:

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.

Note

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:

  1. Disable auto-DDL.
  2. Stop the Postgres server.
  3. Build the updated Spock binaries for your Postgres version.
  4. 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).
  5. Use the psql command line to verify the Spock version in use and the node status.
  6. 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:

ALTER SYSTEM SET spock.enable_ddl_replication = off;
SELECT pg_reload_conf();

Or, set the following parameter in postgresql.conf on each node:

spock.enable_ddl_replication = off

Then, reload the configuration:

SELECT pg_reload_conf();
Warning

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:

pg_ctl -D /path/to/data1 stop -m fast
Warning

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:

cd /path/to/spock-5.0.1
make clean
make
sudo make install

The installation copies the following files:

  • spock.so → $(pg_config --pkglibdir)/;
  • spock.control → $(pg_config --sharedir)/extension/;
  • spock--5.0.1.sql and spock--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:

ls -l $(pg_config --pkglibdir)/spock.so

Check the control file:

ls -l $(pg_config --sharedir)/extension/spock.control

Check that an upgraded .sql file exists; for example:

ls -l $(pg_config --sharedir)/extension/spock--5.0.0--5.0.1.sql

Restarting the Postgres Server

Then, use pg_ctl to restart the Postgres postmaster process:

pg_ctl -D /path/to/data1 restart

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:

psql -d database_name -p port_number

Verify the Spock version that is in use:

SELECT extname, extversion FROM pg_extension WHERE extname = 'spock';

Then, verify that the node is replicating. Check that subscriptions are active with the following commands:

SELECT sub_name, sub_enabled, sub_slot_name, sub_replication_sets
FROM spock.subscription;

Check the replication slots:

SELECT slot_name, active, restart_lsn FROM pg_replication_slots;

Check the node status:

SELECT * FROM spock.node;

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:

ALTER SYSTEM SET spock.enable_ddl_replication = on;
SELECT pg_reload_conf();

Or you can modify the parameter in the postgresql.conf file:

spock.enable_ddl_replication = on

Reload the configuration:

SELECT pg_reload_conf();

Then, on each node, restart the service:

pg_ctl -D /path/to/data1 restart

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:

SELECT application_name, state, sync_state, write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

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.

PG.CENTER edition

2.13 - Recovery

Recovery: section index.

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.

PG.CENTER edition · Upstream source

2.13.1 - Recovering from Catastrophic Node Failure

Suppose your cluster is running smoothly with five nodes — n1, n2, n3, n4, and n5 — all connected using Spock logical 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.

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| N2

Implementing 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| N2

Implementing 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.

Note

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
  end

In both cases you:

  1. Clean up the failed node(s) in Spock.
  2. Run table-diff on all tables—once per failed origin in the multiple-node case.
  3. Run table-repair with --preserve-origin and 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 truth

Before 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 = on in Postgres so that ACE can use commit timestamps and origin ID for recovery and for preserving them when repairing rows.
Note

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:

  1. Assess the damage – Check replication status and identify which nodes are behind and which are fully synchronized.

  2. Spock cleanup – Drop subscriptions and slots for the failed node and remove the failed node from the cluster.

  3. Identify all missing data – Run ACE table-diff on every replicated table to see which tables have differences and what is missing on n2.

  4. 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-origin so that the origin ID and commit timestamp are preserved for every repaired row.

  5. 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:

SELECT * FROM spock.sub_show_status();

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:

 subscription_name | status      | provider_node | replication_sets
-------------------+-------------+---------------+---------------------------------------
 sub_n2_n1         | down        | n1            | {default,default_insert_only,ddl_sql}
 sub_n2_n3         | replicating | n3            | {default,default_insert_only,ddl_sql}

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):

  1. 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.

  2. 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.

Warning

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:

SELECT nspname, relname, set_name
  FROM spock.tables
 WHERE set_name IS NOT NULL
 ORDER BY set_name, nspname, relname;

Alternatively, you can list all tables in the schema you replicate:

SELECT schemaname, tablename FROM pg_tables WHERE schemaname = 'public'
ORDER BY tablename;

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):

./ace table-diff \
  --nodes n2,n3,n4,n5 \
  --preserve-origin n1 \
  --until 2026-02-11T14:30:00Z \
  --output json \
  mycluster 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:

./ace table-diff \
  --nodes n2,n3,n4,n5 \
  --preserve-origin n1 \
  --until 2026-02-11T14:30:00Z \
  --output json \
  mycluster public.orders

./ace table-diff \
  --nodes n2,n3,n4,n5 \
  --preserve-origin n1 \
  --until 2026-02-11T14:30:00Z \
  --output json \
  mycluster public.products

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:

# Rows that originated from n1
./ace table-diff --nodes n2,n3,n5 --preserve-origin n1 \
  --until 2026-02-11T14:30:00Z --output json mycluster public.customers

# Rows that originated from n4 (use n4's failure time if different)
./ace table-diff --nodes n2,n3,n5 --preserve-origin n4 \
  --until 2026-02-11T14:35:00Z --output json mycluster public.customers

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):

FAILURE_UNTIL="2026-02-11T14:30:00Z"
CLUSTER="mycluster"
NODES="n2,n3,n4,n5"

for table in customers orders products invoices; do
  echo "Checking table: public.$table"
  ./ace table-diff \
    --nodes "$NODES" \
    --preserve-origin n1 \
    --until "$FAILURE_UNTIL" \
    --output json \
    "$CLUSTER" public."$table"
done

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:

./ace table-repair \
  --diff-file=public_customers_diffs-20260211143000.json \
  --nodes n2,n3,n4,n5 \
  --recovery-mode \
  --source-of-truth n3 \
  --preserve-origin \
  mycluster public.customers
  • --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:

./ace table-repair \
  --diff-file=public_orders_diffs-20260211143000.json \
  --nodes n2,n3,n4,n5 \
  --recovery-mode \
  --source-of-truth n3 \
  --preserve-origin \
  mycluster public.orders

./ace table-repair \
  --diff-file=public_products_diffs-20260211143000.json \
  --nodes n2,n3,n4,n5 \
  --recovery-mode \
  --source-of-truth n3 \
  --preserve-origin \
  mycluster public.products

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:

# Repair n2 for rows from n1
./ace table-repair \
  --diff-file=public_customers_diffs-20260211143000.json \
  --nodes n2,n3,n5 --recovery-mode --source-of-truth n3 \
  --preserve-origin mycluster public.customers

# Repair n2 for rows from n4 (different diff file from --preserve-origin n4)
./ace table-repair \
  --diff-file=public_customers_diffs-20260211143500.json \
  --nodes n2,n3,n5 --recovery-mode --source-of-truth n3 \
  --preserve-origin mycluster public.customers

In both commands the source of truth is n3; origin ID and commit timestamp are preserved for every repaired row.

Warning

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:

./ace table-diff --nodes n2,n3,n4,n5 --output json \
  mycluster public.customers
./ace table-diff --nodes n2,n3,n4,n5 --output json \
  mycluster public.orders
./ace table-diff --nodes n2,n3,n4,n5 --output json \
  mycluster public.products

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 --> after

Why 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 --until timestamp 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.

  1. Confirm which remaining nodes still have complete data (re-run spock.sub_show_status() on each one and check for lag).
  2. Pick a new source of truth (e.g., n4 or n5) and re-run table-repair with --source-of-truth n4 for any tables that were not yet fully repaired.
Warning

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_node procedure 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 show replicating with 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-diff on all repaired tables without --preserve-origin or --until to confirm the full table content matches across all nodes:

    ./ace table-diff --nodes n2,n3,n4,n5 --output json \
      mycluster public.<table_name>
  • Confirm ACE reports no differences for every table.

  • Spot-check row counts on the recovered node against a known-good survivor for critical tables:

    SELECT COUNT(*) FROM public.customers;
  • If track_commit_timestamp = on, verify that origin IDs and commit timestamps on repaired rows match the source of truth (use pg_xact_commit_timestamp() and spock.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:

  1. Assess the damage – Identify which nodes are behind and determine when the failure occurred.

  2. Clean up Spock – Drop subscriptions to the failed node and remove it from the cluster.

  3. Identify missing data – Run ACE table-diff on all replicated tables with --preserve-origin node_name and --until <failure_time>.

  4. 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)
  5. 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:

  1. Assess the damage – Identify which nodes are behind and when each failure occurred.

  2. Clean up Spock – Drop subscriptions to all failed nodes and remove all of the failed nodes from the cluster.

  3. Identify missing data – Run table-diff once for each failed origin, for each table:

    • --preserve-origin n1 with n1’s failure time
    • --preserve-origin n4 with n4’s failure time
  4. 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
  5. 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


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.

PG.CENTER edition

2.14 - Logical Slot Failover

Spock creates logical replication slots on each provider node.

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

PostgreSQLSlot sync mechanismSpock worker
15, 16Spock built-in spock_failover_slots workerRegistered on every node; synchronizes only while in recovery
17Spock worker or native sync_replication_slotsYields 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.

wal_level = logical
shared_preload_libraries = 'spock'
track_commit_timestamp = on
max_worker_processes = 20
max_replication_slots = 10
max_wal_senders = 10

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.

SettingNodeValuePurpose
sync_replication_slotsstandbyonTurns on the core slot sync worker. Required on 18, optional on 17.
hot_standby_feedbackstandbyonStops the primary from removing catalog rows the slots still need.
primary_slot_namestandbyphysical slot nameThe physical slot the standby streams through.
primary_conninfostandbyconnection string with dbnameHow the standby reaches the primary.
synchronized_standby_slotsprimaryphysical slot nameHolds 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_namesprimary''Physical slots that must confirm an LSN before logical replication advances. Optional.
spock.standby_slots_min_confirmedprimary-1How many of those slots must confirm. -1 means all; 1 keeps replicating while one standby of several is down.
slot failover = trueprimaryper slotOnly 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:

SELECT pg_create_physical_replication_slot('spock_standby_slot');

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.

SettingNodeDefaultPurpose
hot_standby_feedbackstandbyon (you set it)Required before the worker will synchronize anything, and stops the primary from removing needed catalog rows.
primary_slot_namestandbyphysical slot nameThe physical slot the standby streams through.
primary_conninfostandbyconnection stringHow the standby reaches the primary.
spock.synchronize_slot_namesstandbyname_like:%%Which slots to sync. All by default.
spock.drop_extra_slotsstandbyonDrop standby slots that no longer exist on the primary.
spock.primary_dsnstandby''Connection to the primary. Falls back to primary_conninfo when empty.
spock.pg_standby_slot_namesprimary''Physical slots that must confirm an LSN before logical replication advances. Optional.
spock.standby_slots_min_confirmedprimary-1How many of those slots must confirm. -1 means all.
spock.failover_slots_naptimestandby1000Worker sleep between slot-sync passes, in ms (SIGHUP; range 1–3600000).
spock.failover_slots_feedback_naptimestandby10000Shorter retry, in ms, while waiting for standby WAL feedback (SIGHUP; range 1–3600000).
spock.failover_slots_recreate_invalidatedstandbyonDrop 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_databasestandby''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

SELECT pg_create_physical_replication_slot('spock_standby_slot');

2. Configure the primary (postgresql.conf)

# Hold walsenders back until the standby has confirmed this LSN,
# preventing logical subscribers from getting ahead of the standby.
synchronized_standby_slots = 'spock_standby_slot'

3. Configure the standby (postgresql.conf)

sync_replication_slots = on
primary_conninfo = 'host=<primary_host> port=5432 dbname=<dbname> user=replicator'
primary_slot_name = 'spock_standby_slot'
hot_standby_feedback = on

4. Verify slot synchronization

On the standby, confirm that Spock’s logical slots are synchronized:

SELECT slot_name, synced, failover, invalidation_reason
FROM pg_replication_slots
WHERE NOT temporary;

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:

  1. On the primary, list the slots the standby should carry. The Spock worker copies every logical slot that spock.synchronize_slot_names matches (all of them by default), but native slot sync copies only slots with failover = true:

    SELECT slot_name, plugin, failover
    FROM pg_replication_slots
    WHERE slot_type = 'logical' AND NOT temporary;

    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 with ALTER 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_names or synchronized_standby_slots) as it is; if neither is set, see step 2 of the native setup.

  2. On the standby, check wal_level = logical and that primary_conninfo includes dbname. Native slot sync opens a normal database connection with primary_conninfo, not a replication one, so its user needs a pg_hba.conf entry and CONNECT on that database on the primary; the Spock worker may have connected as someone else through spock.primary_dsn. Then set sync_replication_slots = on and reload. The Spock worker stops synchronizing.

  3. 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.

    SELECT slot_name, plugin, active, active_pid
    FROM pg_replication_slots
    WHERE slot_type = 'logical' AND NOT synced AND NOT temporary;

    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 = true is in use, and the drop fails until the process in active_pid stops using it; stop that client, or end it with pg_terminate_backend(active_pid). Drop each copy by name:

    SELECT pg_drop_replication_slot('<slot_name>');
  4. Run the query from Verify slot synchronization until every slot with failover = true on the primary appears on the standby with synced = true and no invalidation_reason. If a drop in step 3 failed, or a copy still shows synced = 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.conf when the standby was built with pg_basebackup, which copies that file,
  • the same postgresql.conf is 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:

-- On the newly promoted node:
ALTER SYSTEM SET synchronized_standby_slots = '';
SELECT pg_reload_conf();

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:

-- On the old primary, once it is no longer needed:
SELECT pg_drop_replication_slot('spock_standby_slot');

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 for member_slots_ttl (default 30min). 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 every loop_wait seconds. 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 = true alone, with one exception on PostgreSQL 17 and later: on a replica it removes failover slots whose synced is 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:

ignore_slots:
  - plugin: spock_output
    type: logical

Required settings

SettingValueWhereRestart?Why
sync_replication_slotsondynamic configNo (reload)PostgreSQL’s slotsync worker copies flagged slots to every replica
hot_standby_feedbackondynamic configNo (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_levellogicaldynamic configYesRequired for logical decoding and for slot synchronization
output_plugin_librariesinclude spock_outputdynamic config, every memberNo (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_slotstruePatroni confign/aThe 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_senderssized to clusterdynamic configYesMember slots plus Spock’s logical slots on every node; see Sizing
synchronized_standby_slotsstandby member slot name(s)dynamic config or callbackNo (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.

bootstrap:
  dcs:
    postgresql:
      use_slots: true
      parameters:
        wal_level: logical
        hot_standby_feedback: "on"          # required by slot synchronization
        sync_replication_slots: "on"        # PG slotsync worker copies FAILOVER slots
        max_replication_slots: 10
        max_wal_senders: 10
        # Only on servers that have this parameter -- see the note below
        output_plugin_libraries: "pgoutput, test_decoding, spock_output"

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:

synchronized_standby_slots = 'r1'

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_change callback on promotion and demotion with the arguments on_role_change <role> <scope>; the role is primary or replica (master on releases before 4.0). On becoming leader the script sets synchronized_standby_slots to the slots of the other members that are up and reloads; on becoming a replica it clears it.

    postgresql:
      callbacks:
        on_role_change: /etc/patroni/set_synchronized_standby_slots.sh

    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 from patroni.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, with use_slots on and no hand-made primary_slot_name. Review and adapt it before production use.

  • Let Patroni manage it. Patroni’s development branch has a manage_synchronized_standby_slots option that keeps synchronized_standby_slots equal to the synchronous standbys of synchronous_standby_names; it needs synchronous_mode and 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

  1. patronictl switchover demotes the leader and promotes a replica.
  2. On the new leader the synchronized Spock slots become usable; the subscribers only need their DSN pointed at it, as described under After failover.
  3. The old leader rejoins as a replica. Its own Spock slots carry failover = true and synced = false; Patroni 4.1.0 and later drops them there, and the slotsync worker recreates them as synchronized copies from the new leader.
  4. Whatever manages synchronized_standby_slots has 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:

-- on each replica
SELECT slot_name, synced, failover, invalidation_reason
FROM pg_replication_slots
WHERE plugin = 'spock_output' AND NOT temporary;

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 = on on the standby (required before the worker will synchronize anything)
  • The standby must be able to connect to the primary

Configuration GUCs

GUCDefaultDescription
spock.synchronize_slot_namesname_like:%%Slot name patterns to sync (all by default)
spock.drop_extra_slotsonDrop 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-1How many slots from pg_standby_slot_names must confirm (-1 = all)
spock.failover_slots_naptime1000Worker sleep between slot-sync passes, in ms (SIGHUP; range 1–3600000)
spock.failover_slots_feedback_naptime10000Shorter retry, in ms, while waiting for standby WAL feedback (SIGHUP; range 1–3600000)
spock.failover_slots_recreate_invalidatedonDrop 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)

hot_standby_feedback = on
spock.synchronize_slot_names = 'name_like:%%'
spock.drop_extra_slots = on

# Optional: hold walsenders on primary until this standby confirms
# (set this on the PRIMARY, not the standby)
# spock.pg_standby_slot_names = 'physical_slot_name'

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

ALTER EXTENSION spock UPDATE TO '6.0.0';

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 = true on 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:

SELECT spock.slot_enable_failover();

3. Verify

On the primary, every Spock slot should now show failover as true:

SELECT slot_name, failover
FROM pg_replication_slots
WHERE plugin = 'spock_output';

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+)

SELECT slot_name,
       failover,
       synced,
       active,
       invalidation_reason,
       confirmed_flush_lsn
FROM pg_replication_slots
WHERE NOT temporary
ORDER BY slot_name;

Check if native slotsync worker is active (PG17+)

SELECT pid, wait_event_type, wait_event, state
FROM pg_stat_activity
WHERE backend_type = 'slot sync worker';

Check spock worker is running (PG15/16)

SELECT pid, application_name, state
FROM pg_stat_activity
WHERE application_name = 'spock_failover_slots worker';

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.

PG.CENTER edition

2.15 - Limitations and Restrictions

Spock has several limitations and restrictions that users should be aware of when designing and implementing replication scenarios.

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:

ERROR: spock doesn't support index rechecks needed for deferrable indexes
DETAIL: relation "public"."test_relation" has deferrable indexes: "index1",
"index2"

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:

ERROR: delta apply column can't operate NULL values

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.

PG.CENTER edition

2.16 - Internals

Internals: section index.

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.

PG.CENTER edition · Upstream source

2.16.1 - Design proposals

Design proposals: section index.

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.

PG.CENTER edition · Upstream source

2.16.1.1 - Eliminating the Spock checkpoint hook and per-commit WAL flush for spock.progress

Spock currently maintains the spock.progress view via three coupled mechanisms:

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:

  1. remote_commit_ts is recovered post-crash via a pg_commit_ts scan, not left NULL. The original design accepted NULL as a freshness regression; the implementation runs a backward scan of pg_commit_ts for the relevant origin and repopulates the field. Promoted from a “follow-up” to a goal so spock.progress shows an accurate timestamp after a crash. The recovered prev_remote_ts is also intended to be useful for the planned parallel-apply rework.
  2. 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 SpockGroupHash entry at each resource.dat dump call site (clean shutdown, add_node, table-sync). Each record carries the full SpockApplyProgress snapshot for that entry. The records are not required for state recovery; they exist so a pg_waldump trace shows the exact progress snapshot persisted at each event LSN — useful for incident reconstruction over time. A single XLogFlush at the end of each emit batch gives WAL durability symmetric with resource.dat’s durable_rename().

Sections below are updated to reflect what shipped.

Problem

Spock currently maintains the spock.progress view via three coupled mechanisms:

  1. A custom WAL RMGR (src/spock_rmgr.c) that emits a SPOCK_RMGR_APPLY_PROGRESS record on every applied remote-origin commit and calls XLogFlush synchronously (in addition to the XLogFlush that core’s CommitTransactionCommand already performs).
  2. A Checkpoint_hook (registered in src/spock.c:1248) that dumps the in-memory SpockGroupHash to PGDATA/spock/resource.dat at every Postgres checkpoint. This requires a patch to Postgres core (src/backend/access/transam/xlog.c and src/include/access/xlog.h) to add the hook callout.
  3. A load/redo path that seeds shmem from resource.dat during shmem_startup_hook and overwrites with WAL redo of APPLY_PROGRESS records 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 XLogFlush on 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.progress column 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 SpockGroupHash shmem layout or the SpockApplyProgress struct.
  • Recovering last_updated_ts precisely (apply-time timestamp). Post-crash, set to the recovered remote_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:

  1. 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. If resource.dat holds 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.
  2. A forced keepalive on apply-worker (re)connect. The subscriber sends a status-update message with replyRequested=true immediately after spock_start_replication returns. Postgres’s walsender responds with a ‘k’ keepalive carrying its current sentPtr. The apply worker’s existing keepalive handler populates remote_insert_lsn and received_lsn in shmem within milliseconds of reconnect, rather than waiting for wal_sender_timeout / 2 (default 30s) to elapse.
  3. A backward pg_commit_ts scan to recover remote_commit_ts per origin. When reconcile detects stale or absent state, a follow-on routine recover_progress_timestamps_from_commit_ts() walks pg_commit_ts backward 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_ts is set to the same recovered remote_commit_ts so the XOR invariant in progress_update_struct holds; 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:

FieldSourceWhen authoritative
remote_commit_lsnReplication origin (replorigin_session_get_progress)At apply-worker startup, always correct
remote_commit_tsresource.dat if validated against origin LSN; else pg_commit_ts scanPreserved across clean restart; recovered post-crash; NULL only on fresh first start (no commits yet)
remote_insert_lsnForced ‘k’ keepaliveWithin ~ms of apply worker connect
received_lsnSameSame
last_updated_tsGetCurrentTimestamp() at each update; post-crash set to the recovered remote_commit_tsAlways 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_tsSet 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:

  1. Create the empty SpockGroupHash HTAB.
  2. Call spock_group_resource_load() to load PGDATA/spock/resource.dat if present and valid (version and system_identifier match). Each record is upserted into the hash via spock_group_progress_update().
  3. 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 LOG line 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.

  1. Compute the shmem key: (MyDatabaseId, MySubscription->target->id, MySubscription->origin->id).
  2. Fetch origin_lsn = replorigin_session_get_progress(false).
  3. Acquire SpockCtx->apply_group_master_lock in 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. Keep remote_commit_ts and last_updated_ts as loaded. Result: RECONCILE_FILE_IN_SYNC.
    • Entry present, file_lsn < origin_lsn. File is stale for this entry. Overwrite remote_commit_lsn with origin_lsn; clear remote_commit_ts and last_updated_ts to 0; bump remote_insert_lsn and received_lsn up to at least origin_lsn to preserve the insert_lsn >= commit_lsn invariant (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 prefer origin_lsn (same body as STALE). Result: RECONCILE_FILE_ANOMALY.
  4. 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), or
  • total_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:

static void
request_initial_status_update(PGconn *conn, XLogRecPtr startpos);

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:

  1. Remove the per-entry spock_apply_progress_add_to_wal(sap) call.
  2. Per entry: acquire master lock → mutate shmem → release lock (no I/O under the lock).
  3. After the loop: call spock_group_resource_dump() once to persist all entries atomically via durable_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 in src/spock_group.c (no longer registered or referenced).
  • extern void spock_checkpoint_hook(...) declaration in include/spock_group.h.
  • The apply-progress recovery contents of src/spock_rmgr.c (the redo handler that replayed SPOCK_RMGR_APPLY_PROGRESS records 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" in include/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 type SPOCK_RMGR_RESOURCE_DUMP. New emit helper spock_rmgr_log_resource_dump(event, changed_entries) is called at each of the three resource.dat dump call sites. Each call emits one WAL record per progress entry, carrying the full SpockApplyProgress snapshot for that entry so a pg_waldump trace shows exactly what state was on disk at each event LSN — useful for incident reconstruction over time. A single XLogFlush at the end of each emit batch covers all records.
    • For SHUTDOWN and ADD_NODE: caller passes NULL for changed_entries; the helper walks SpockGroupHash and emits a record per entry. Both events reflect changes across all subscriptions.
    • For TABLE_SYNC: caller passes the same list of SpockApplyProgress * it just used to update shmem. Only the affected subscription’s entries are emitted, since table-sync is per-subscription.
    • Redo handler emits a LOG line per record showing event type, sequence in batch, key, LSNs, and commit_ts. Records are not used for state recovery.
  • include/spock_rmgr.h — replace declarations to match the trimmed contents (SPOCK_RMGR_ID = 144, SPOCK_RMGR_RESOURCE_DUMP = 0x10, SpockResourceDumpRec carrying event_type + entry_seq/entry_total + the embedded SpockApplyProgress, SpockResourceDumpEvent, the emit helper).
  • src/spock.c — spock_rmgr_init() call retained in _PG_init. Header include retained.

Modify

  • src/spock_progress_recovery.c and include/spock_progress_recovery.h (new module) — single public entry point spock_init_progress_state(XLogRecPtr origin_lsn). File-static internals: the ReconcileResult enum, reconcile_progress_with_origin(), recover_progress_timestamps_from_commit_ts(), and the SPOCK_TS_RECOVERY_* #defines.
  • src/spock_apply.c — add a new helper request_initial_status_update(PGconn *conn, XLogRecPtr startpos) that emits an ‘r’ message with replyRequested=true without touching send_feedback’s static state.
  • src/spock_apply.c:spock_apply_main — between replorigin_session_setup and spock_start_replication, call spock_init_progress_state(origin_lsn) once; this internally runs reconcile and (if reconcile detected staleness) the pg_commit_ts scan. After spock_start_replication returns, call request_initial_status_update.
  • src/spock_group.c:spock_group_progress_force_set_list — drop the WAL call; add a single spock_group_resource_dump() followed by spock_rmgr_log_resource_dump(SPOCK_DUMP_ADD_NODE, ...) after the loop.
  • src/spock_group.c:spock_group_progress_update_list — same with SPOCK_DUMP_TABLE_SYNC.
  • src/spock.c:spock_supervisor_main — register spock_supervisor_on_exit via before_shmem_exit. The callback poll-waits for apply/sync workers to detach via a new helper spock_any_apply_worker_running() (in src/spock_worker.c), then calls spock_group_resource_dump() followed by spock_rmgr_log_resource_dump(SPOCK_DUMP_SHUTDOWN, NULL). The previous postmaster-context spock_on_shmem_exit in src/spock_shmem.c is removed entirely; both file and WAL dumps now have a single owner that runs in the supervisor process where XLogInsert is permitted.

Keep unchanged

  • Clean-shutdown gating semantics (only dumps if code == 0) — preserved in spock_supervisor_on_exit.
  • spock_group_resource_load(), spock_group_resource_dump() — load/dump file-format code.
  • SpockApplyProgress and SpockGroupEntry struct layouts.
  • spock.progress SQL view and get_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-line if (Checkpoint_hook) Checkpoint_hook(...) invocation inside CreateCheckPoint.
  • postgresql/src/include/access/xlog.h:218-219 — typedef + extern PGDLLIMPORT declaration.

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 a CHECKPOINT before 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 detects file_lsn < origin_lsn after a crash, advances remote_commit_lsn from the replication origin, and (with the recovery scan) that remote_commit_ts is recovered non-NULL post-crash. Also asserts CHECKPOINT does NOT update resource.dat (regression guard against re-introducing the checkpoint hook).

New tests

  1. 023_forced_keepalive_timing.pl — set wal_sender_timeout=10min so the timer-driven path is disabled; assert remote_insert_lsn populates within 1 second (proves the forced keepalive, not the timer, drove the refresh).
  2. 026_no_double_wal_flush.pl — count pg_stat_wal.wal_sync delta over 30 applied commits; assert delta < N (no per-commit forced fsync on the apply hot path).
  3. 027_remote_commit_ts_recovery.pl — apply commits, clean restart, more commits, CHECKPOINT, SIGKILL, restart; assert remote_commit_ts is non-NULL post-crash (recovered via the pg_commit_ts scan).
  4. 029_remote_commit_ts_recovery_clean_shutdown.pl — clean restart only; assert the skip-path LOG line (“file in sync with origin, skipping scan”) fires and the run-path log does not, and remote_commit_ts is preserved.

Deferred / not implemented

  • track_commit_timestamp = off test. Cannot occur in practice because spock’s existing spock.conflict_resolution GUC 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_node interrupted mid-loop test. Out of scope for this design; covered by existing add_node integration tests.

Regression safety checks

  • spock.progress column 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_node lifecycle, subscription state transitions, sync start/end). Sketched separately in 2026-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.dat entries that reference subscriptions that no longer exist.
  • Removing the obsolete updated_by_decode field from the SpockApplyProgress struct layout. (prev_remote_ts is 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.

PG.CENTER edition

2.16.1.2 - Spock Node Monitoring: Design of the spock_monitor subsystem

A Word version of this document is kept next to it as spock-monitor-design.docx.

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.

LayerElementsOwner
Shared memoryEvent ring (SpockMonitorShmem), per-subscription counters (SpockMonitorStatsHash)spock_monitor.c, allocated by spock_shmem.c
ProducersWorker attach and detach, apply loop, sync worker, output plugin, node and subscription management functions, exception handler, extension manager, emit_log_hookOne call at each site
SQL functionsget_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_lsnspock_monitor.c
Viewssystem_status, node_status, subscription_status, subscription_stats, worker_status, slot_status, peer_status, replication_set_status, settings, table_sync_status, eventssql/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).

typedef struct SpockMonitorEvent
{
    uint64      event_id;      /* increases by one, never reused */
    TimestampTz event_time;
    SpockMonitorEventType event_type;
    Oid         dboid;         /* database of the reporting process */
    Oid         subid;         /* subscription, or InvalidOid */
    int         pid;
    int         sqlerrcode;    /* SQLSTATE of an error event, else 0 */
    XLogRecPtr  lsn;           /* origin LSN, if any */
    char        detail[512];
} SpockMonitorEvent;

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.

typedef struct SpockMonitorStatsEntry
{
    SpockMonitorStatsKey key;
    int64       counter[SPOCK_MONITOR_NUM_COUNTERS];
    TimestampTz counter_time[SPOCK_MONITOR_NUM_COUNTERS];
    XLogRecPtr  last_error_lsn;
    int         last_error_sqlerrcode;
    int         last_error_pid;
    char        last_error_message[512];
    TimestampTz stats_reset;
    slock_t     mutex;
} SpockMonitorStatsEntry;

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.

CounterIncremented when
worker_startsAn apply worker attaches to its shared memory slot.
worker_failuresAn apply worker detaches after an error exit.
sync_worker_starts, sync_worker_failuresThe same for sync workers, so a resync is told apart from an apply worker restart.
provider_connectsSTART_REPLICATION succeeded in the apply worker.
provider_disconnectsapply_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_timeoutsspock.apply_idle_timeout forced a reconnect.
messages_received, bytes_receivedA data message was read from the stream.
xacts_appliedA remote transaction committed locally.
xacts_skippedA transaction was skipped through sub_skip_lsn.
xacts_discardedA transaction was discarded under transdiscard.
apply_errors, sync_errorsAn ERROR was raised in an apply or sync worker (section 6).
deadlocks, lock_timeouts, constraint_violations, resource_errorsThe same errors classified by SQLSTATE.
tables_syncedA 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_monitor protects 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->lock is held, never the other way round.
  • The error reporting path uses LWLockConditionalAcquire and 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 typeCall site
node_created, node_droppedspock_create_node(), spock_drop_node() after the catalog change
subscription_created, subscription_droppedspock_create_subscription(), spock_drop_subscription()
subscription_enabled, subscription_disabledspock_alter_subscription_enable(), spock_alter_subscription_disable(), spock_disable_subscription() in the exception handler
subscription_alteredInterface change, replication set add and remove, skip_lsn, options, synchronize and resynchronize table
worker_started, worker_stopped, worker_failedspock_worker_attach() and spock_worker_detach(); the failure detail carries the last recorded error message
worker_erroremit_log_hook, for any ERROR or FATAL in a spock worker
provider_connected, provider_disconnectedspock_start_replication(); the connection loss branch of apply_work()
transaction_skipped, transaction_discardedstop_skipping_changes(); the transdiscard branch of handle_commit()
sync_started, sync_finished, sync_failedspock_sync_main() and spock_sync_worker_finish()
slot_created, stream_started, stream_stoppedpg_decode_startup() with and without is_init; pg_decode_shutdown()
apply_paused, apply_resumedspock_pause_apply_workers(), spock_resume_apply_workers()
repair_mode_enabled, repair_mode_disabledspock_repair_mode()
extension_upgradedspock_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:

  1. Ignore unless the process is a spock worker (MySpockWorker is set) or a walsender running the spock output plugin, and shared memory is attached.
  2. Ignore levels below ERROR and at or above PANIC; a PANIC path must not take locks.
  3. 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_disconnected with 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.
  4. In a walsender, record a stream_error event 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.
  5. For apply and sync workers, bump apply_errors or sync_errors and 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.
  6. Record a worker_error event 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.

FunctionReturns
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).

ViewRowsBuilt from
spock.system_statusExactly oneget_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_statusExactly oneget_monitor_summary(), local_node, pg_extension, aggregates over the other views, spock.wal_size_bytes()
spock.subscription_statusOne per subscriptionsubscription, node, node_interface, local_sync_status, get_worker_status() (lateral, running worker preferred), pg_stat_activity, progress, replication_origin_status(), subscription_stats
spock.subscription_statsOne per subscriptionget_apply_stats() and channel_summary_stats, counters coalesced to zero
spock.worker_statusOne per workerget_worker_status(), pg_stat_activity, pg_blocking_pids() for the session holding a lock the worker waits for
spock.slot_statusOne per spock slotpg_replication_slots, pg_stat_replication, get_slot_groups(), current or replay WAL position
spock.table_sync_statusOne per sync rowlocal_sync_status with readable kind and status
spock.peer_statusOne per node and subscriptionnode, node_interface, subscription_status
spock.replication_set_statusOne per replication setreplication_set with counts over its tables, sequences and subscriptions
spock.settingsOne per parameterpg_settings, spock parameters and the core replication parameters, DSNs redacted
spock.eventsOne per eventget_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.sql and to spock--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 over spock.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.c is removed. spock.wait_slot_confirm_lsn(), spock.get_channel_stats(), spock.reset_channel_stats() and spock.apply_group_progress() keep their SQL definitions and C symbols and now live in spock_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 >= 180000 and are NULL otherwise.
  • Shared memory grows by the ring plus the hash. SpockMonitorStatsEntry is 800 bytes, dominated by its 512-byte last_error_message and the two per-counter arrays, so the hash costs roughly that plus dynahash overhead for each subscription tracked, bounded by max(64, 4 * max_worker_processes) entries. SpockMonitorEvent is 560 bytes, dominated by its 512-byte detail, so the ring costs spock.event_history_size * 560 bytes: 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-only pg_replication_origin_status) are granted to pg_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_stats still 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_full reports 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_slots columns 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.

PG.CENTER edition

2.16.2 - Historical plans

Historical plans: section index.

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.

PG.CENTER edition · Upstream source

2.16.2.1 - remote_commit_ts Recovery via pg_commit_ts Scan — Implementation Plan

No header changes — ReconcileResult is file-static.

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:

export PATH="${PG17_BIN:?Set PG17_BIN to the PostgreSQL 17 bin directory}:$PATH"
cd "${SPOCK_SRC:?Set SPOCK_SRC to the Spock checkout}"
git status                           # working tree clean
make -j4 install                     # baseline build OK

File Structure

FileRoleChange
src/spock_apply.cApply worker main, reconcile, new recovery functionModify
tests/tap/t/027_remote_commit_ts_recovery.plHappy pathCreate
tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.plSkip-path verificationCreate
tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.plError-path verificationCreate

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 at src/spock_apply.c:2937-2938, update caller at src/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:

static void UpdateWorkerStats(XLogRecPtr last_received, XLogRecPtr last_inserted);
...
static void request_initial_status_update(PGconn *conn, XLogRecPtr startpos);
static void reconcile_progress_with_origin(XLogRecPtr origin_lsn);

Replace the last line with the enum and updated declaration:

typedef enum ReconcileResult
{
	RECONCILE_FILE_IN_SYNC,		/* file_lsn == origin_lsn; recovery scan can skip */
	RECONCILE_FILE_STALE,		/* file_lsn <  origin_lsn; recovery scan needed */
	RECONCILE_FILE_ANOMALY,		/* file_lsn >  origin_lsn; recovery scan needed */
	RECONCILE_FILE_ABSENT		/* no entry was loaded; recovery scan needed */
} ReconcileResult;

static ReconcileResult reconcile_progress_with_origin(XLogRecPtr origin_lsn);
  • Step 1.2: Update the function definition to return the enum

At src/spock_apply.c:2937, change:

static void
reconcile_progress_with_origin(XLogRecPtr origin_lsn)

to:

static ReconcileResult
reconcile_progress_with_origin(XLogRecPtr origin_lsn)

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 to return RECONCILE_FILE_ABSENT;. The hash isn’t set up; treat as absent.
  • The entry == NULL case (hash full) — change return; to return 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.

static ReconcileResult
reconcile_progress_with_origin(XLogRecPtr origin_lsn)
{
	SpockGroupKey	key;
	SpockGroupEntry *entry;
	bool			found;
	ReconcileResult	result;

	if (!SpockGroupHash || !SpockCtx)
	{
		elog(WARNING, "SPOCK %s: SpockGroupHash is not initialized; reconcile skipped",
			 MySubscription->name);
		return RECONCILE_FILE_ABSENT;
	}

	key.dbid = MyDatabaseId;
	key.node_id = MySubscription->target->id;
	key.remote_node_id = MySubscription->origin->id;

	LWLockAcquire(SpockCtx->apply_group_master_lock, LW_EXCLUSIVE);

	entry = (SpockGroupEntry *) hash_search(SpockGroupHash, &key,
											HASH_ENTER, &found);
	if (entry == NULL)
	{
		LWLockRelease(SpockCtx->apply_group_master_lock);
		elog(WARNING, "SpockGroupHash is full, cannot reconcile progress for "
			 "(dbid=%u, node_id=%u, remote_node_id=%u)",
			 key.dbid, key.node_id, key.remote_node_id);
		return RECONCILE_FILE_ABSENT;
	}

	if (!found)
	{
		/* ...existing init body unchanged... */
		result = RECONCILE_FILE_ABSENT;
	}
	else if (entry->progress.remote_commit_lsn == origin_lsn)
	{
		/* ...existing body unchanged... */
		result = RECONCILE_FILE_IN_SYNC;
	}
	else if (entry->progress.remote_commit_lsn < origin_lsn)
	{
		/* ...existing stale body unchanged... */
		result = RECONCILE_FILE_STALE;
	}
	else
	{
		/* ...existing anomaly body unchanged... */
		result = RECONCILE_FILE_ANOMALY;
	}

	LWLockRelease(SpockCtx->apply_group_master_lock);
	return result;
}
  • Step 1.3: Update the caller to receive the result

At src/spock_apply.c:4216, change:

reconcile_progress_with_origin(origin_startpos);

to:

ReconcileResult reconcile_result = reconcile_progress_with_origin(origin_startpos);

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
make -j4 install

Expected: clean build, no new warnings.

cd tests/tap && ./run_tests.sh t/022_rmgr_progress_post_checkpoint_crash.pl

Expected: all subtests pass (this test exercises the reconcile path most heavily).

  • Step 1.5: Commit
git add src/spock_apply.c
git commit -m "refactor: reconcile_progress_with_origin returns ReconcileResult

Threads a typed result back to the caller so a follow-up commit can
gate post-reconcile work on whether the loaded resource.dat was in
sync, stale, anomalous, or absent. Pure refactor -- no behavior
change."

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:

/*
 * Constants governing the post-crash scan of pg_commit_ts that recovers
 * remote_commit_ts per origin. Plain #defines for now; convert to GUCs
 * only if a deployment ever needs to tune them.
 */
#define SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN	1000
#define SPOCK_TS_RECOVERY_SCAN_LIMIT			1000000
#define SPOCK_TS_RECOVERY_BATCH_SIZE			1000
  • Step 2.2: Build to verify
make -j4 install

Expected: clean build (no use sites yet, but the macros exist).

  • Step 2.3: Commit
git add src/spock_apply.c
git commit -m "feat: add SPOCK_TS_RECOVERY_* constants for commit_ts scan

Adds the three tunables (min commits per origin, hard scan limit,
batch size) for the upcoming pg_commit_ts recovery scan. Defined as
plain #defines; conversion to GUCs is a follow-up if profiling
motivates tuning."

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.pl

  • Step 3.1: Create the test file

Write tests/tap/t/027_remote_commit_ts_recovery.pl with the following content:

#!/usr/bin/perl
# =============================================================================
# Test: 027_remote_commit_ts_recovery.pl
#       Verify that after a crash, remote_commit_ts is recovered from the
#       subscriber's pg_commit_ts SLRU rather than left NULL. The recovered
#       values are also intended to be useful for the planned parallel-apply
#       rework.
#
# Topology:  n1 (provider) -> n2 (subscriber)
#
# Sequence:
#   1. Apply commits, clean restart (writes resource.dat).
#   2. Apply more commits (origin advances; resource.dat stale).
#   3. SIGKILL subscriber.
#   4. Restart. Apply worker reconcile detects stale, calls the new
#      recover_progress_timestamps_from_commit_ts which scans pg_commit_ts
#      backward and populates remote_commit_ts.
#   5. Assert remote_commit_ts is NOT NULL.
# =============================================================================

use strict;
use warnings;
use Test::More;
use lib '.';
use SpockTest qw(
    create_cluster destroy_cluster system_or_bail
    command_ok get_test_config scalar_query psql_or_bail
    wait_for_sub_status wait_for_pg_ready
);

sub wait_until {
    my ($timeout_s, $probe) = @_;
    my $deadline = time() + $timeout_s;
    while (time() < $deadline) {
        return 1 if $probe->();
        select(undef, undef, undef, 0.25);
    }
    return 0;
}

create_cluster(2, 'Create 2-node cluster');

my $conf      = get_test_config();
my $host      = $conf->{host};
my $pg_bin    = $conf->{pg_bin};
my $ports     = $conf->{node_ports};
my $datadirs  = $conf->{node_datadirs};
my $dbname    = $conf->{db_name};
my $user      = $conf->{db_user};

my $prov_port = $ports->[0];
my $sub_port  = $ports->[1];
my $sub_dir   = $datadirs->[1];

my $prov_dsn = "host=$host port=$prov_port dbname=$dbname user=$user";

psql_or_bail(1, "CREATE TABLE public.ts_recovery (id int primary key, val text)");
psql_or_bail(2, "CREATE TABLE public.ts_recovery (id int primary key, val text)");

psql_or_bail(2, "SELECT spock.sub_create('test_sub', '$prov_dsn', ARRAY['default'], false, false)");
ok(wait_for_sub_status(2, 'test_sub', 'replicating', 30), 'subscription is replicating');

# --- Round 1: apply, clean restart so resource.dat is written. ---
psql_or_bail(1, "INSERT INTO public.ts_recovery SELECT g, 'r1_' || g FROM generate_series(1,50) g");
ok(wait_until(30, sub { scalar_query(2, "SELECT count(*) FROM public.ts_recovery") eq '50' }),
   'round-1 50 rows replicated');

system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-m', 'fast', 'stop';
ok(-f "$sub_dir/spock/resource.dat", 'resource.dat written on clean stop');

system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-o', "-p $sub_port", '-w', 'start';
ok(wait_for_pg_ready($host, $sub_port, $pg_bin, 30), 'subscriber back up');
ok(wait_for_sub_status(2, 'test_sub', 'replicating', 30), 'replicating after clean restart');

# --- Round 2: apply more so origin advances past resource.dat's snapshot. ---
psql_or_bail(1, "INSERT INTO public.ts_recovery SELECT g, 'r2_' || g FROM generate_series(51,100) g");
ok(wait_until(30, sub { scalar_query(2, "SELECT count(*) FROM public.ts_recovery") eq '100' }),
   'round-2 50 rows replicated');

# Confirm remote_commit_ts is non-NULL pre-crash (sanity).
my $pre_ts = scalar_query(2, "SELECT remote_commit_ts::text FROM spock.progress LIMIT 1");
ok($pre_ts ne '', "pre-crash remote_commit_ts populated: $pre_ts");

# --- SIGKILL subscriber. ---
my $pid_file = "$sub_dir/postmaster.pid";
open(my $fh, '<', $pid_file) or die "Cannot open $pid_file: $!";
my $sub_pid = <$fh>;
chomp($sub_pid);
close($fh);
kill 'KILL', $sub_pid;
pass('subscriber SIGKILLed');

select(undef, undef, undef, 2.0);

# --- Restart. Reconcile detects stale; recovery scan populates remote_commit_ts. ---
system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-o', "-p $sub_port", '-w', 'start';
ok(wait_for_pg_ready($host, $sub_port, $pg_bin, 30), 'subscriber accepting connections after crash');

# Wait for the apply worker to start, run reconcile, run recovery scan.
ok(wait_until(30, sub {
    my $ts = scalar_query(2, q{
        SELECT remote_commit_ts::text FROM spock.progress LIMIT 1
    });
    defined $ts && $ts ne '' && $ts ne '0/0'
}), 'spock.progress.remote_commit_ts populated by recovery scan');

# --- Assertions ---
my $post_ts = scalar_query(2, "SELECT remote_commit_ts::text FROM spock.progress LIMIT 1");
ok($post_ts ne '',
   "post-crash remote_commit_ts is NOT NULL (recovered via pg_commit_ts scan): $post_ts");

# remote_commit_ts must be a valid timestamp (parses as such).
my $ts_valid = scalar_query(2,
    "SELECT '$post_ts'::timestamptz IS NOT NULL");
is($ts_valid, 't', "post-crash remote_commit_ts parses as a valid timestamptz");

psql_or_bail(2, "SELECT spock.sub_drop('test_sub')");
destroy_cluster('Destroy 2-node cluster');
done_testing();

Make it executable:

chmod +x tests/tap/t/027_remote_commit_ts_recovery.pl
  • Step 3.2: Run the test — confirm it fails as expected
cd tests/tap && ./run_tests.sh t/027_remote_commit_ts_recovery.pl

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
git add tests/tap/t/027_remote_commit_ts_recovery.pl
git commit -m "test: add 027 (remote_commit_ts post-crash recovery, currently failing)

Asserts the regression target for the pg_commit_ts scan: after a crash
that leaves resource.dat stale relative to the replication origin,
remote_commit_ts must be recovered (non-NULL) rather than left blank.
Currently fails -- implementation lands in the next commit."

Task 4: Implement the scan and wire the call site

Files:

  • Modify: src/spock_apply.c — add recover_progress_timestamps_from_commit_ts function and call it from spock_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:

static void recover_progress_timestamps_from_commit_ts(SpockGroupEntry *entry,
													   RepOriginId target_origin);
  • Step 4.2: Add the include for commit_ts.h

Near the top of src/spock_apply.c (in the #include block), add:

#include "access/commit_ts.h"
  • 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):

/*
 * recover_progress_timestamps_from_commit_ts
 *
 * After reconcile detects that resource.dat is stale (or absent) for this
 * origin, scan pg_commit_ts backward from the latest xid to recover the
 * most-recent remote_commit_ts for this origin. The recovered values are
 * also intended to be useful for the planned parallel-apply rework.
 *
 * Termination: stop after observing SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN
 * commits for this origin (any older commit is guaranteed to have a smaller
 * commit_ts under realistic concurrency widths) or after scanning
 * SPOCK_TS_RECOVERY_SCAN_LIMIT total xids.
 *
 * Caller must have ensured the entry exists in SpockGroupHash (reconcile
 * does this).
 */
static void
recover_progress_timestamps_from_commit_ts(SpockGroupEntry *entry,
										   RepOriginId target_origin)
{
	TransactionId	xid_high;
	TimestampTz		running_max_ts = 0;
	int				seen_count = 0;
	int64			total_scanned = 0;

	xid_high = ReadNextTransactionId();
	if (TransactionIdPrecedes(xid_high, FirstNormalTransactionId + 1))
	{
		elog(LOG, "SPOCK %s: ts recovery: no normal transactions yet; skipping",
			 MySubscription->name);
		return;
	}
	xid_high = xid_high - 1;

	while (seen_count < SPOCK_TS_RECOVERY_MIN_SEEN_PER_ORIGIN
		   && total_scanned < SPOCK_TS_RECOVERY_SCAN_LIMIT)
	{
		TransactionId	xid_low;
		TransactionId	xid;
		int64			batch_count;

		CHECK_FOR_INTERRUPTS();

		/* Compute batch lower bound, clamped at FirstNormalTransactionId. */
		if (TransactionIdPrecedes(xid_high,
								  FirstNormalTransactionId + SPOCK_TS_RECOVERY_BATCH_SIZE))
			xid_low = FirstNormalTransactionId;
		else
			xid_low = xid_high - SPOCK_TS_RECOVERY_BATCH_SIZE + 1;

		batch_count = (int64) xid_high - (int64) xid_low + 1;

		for (xid = xid_low; TransactionIdPrecedes(xid, xid_high + 1); xid++)
		{
			TimestampTz		ts;
			RepOriginId		origin;

			if (!TransactionIdGetCommitTsData(xid, &ts, &origin))
				continue;					/* aborted, vacuumed, or no commit_ts */
			if (origin != target_origin)
				continue;					/* local writes / other origins */

			seen_count++;
			if (ts > running_max_ts)
				running_max_ts = ts;
		}

		total_scanned += batch_count;

		if (xid_low == FirstNormalTransactionId)
			break;						/* wraparound floor */

		xid_high = xid_low - 1;
	}

	if (running_max_ts > 0)
	{
		LWLockAcquire(SpockCtx->apply_group_master_lock, LW_EXCLUSIVE);
		if (entry->progress.remote_commit_ts < running_max_ts)
		{
			entry->progress.remote_commit_ts = running_max_ts;
			entry->progress.prev_remote_ts = running_max_ts;
		}
		LWLockRelease(SpockCtx->apply_group_master_lock);

		elog(INFO, "SPOCK %s: ts recovery: scanned %lld xids, found %d commits, "
			 "recovered remote_commit_ts",
			 MySubscription->name, (long long) total_scanned, seen_count);
	}
	else
	{
		elog(WARNING, "SPOCK %s: ts recovery: scanned %lld xids, no commits found "
			 "for origin %u; remote_commit_ts remains NULL until next applied commit",
			 MySubscription->name, (long long) total_scanned, target_origin);
	}
}
  • Step 4.4: Wire the call site in spock_apply_main

At src/spock_apply.c:4216 (where Task 1 introduced reconcile_result), replace:

ReconcileResult reconcile_result = reconcile_progress_with_origin(origin_startpos);
(void) reconcile_result;	/* used in Task 4 */

with:

ReconcileResult reconcile_result = reconcile_progress_with_origin(origin_startpos);

if (reconcile_result == RECONCILE_FILE_IN_SYNC)
{
	elog(INFO, "SPOCK %s: ts recovery: file in sync with origin, skipping scan",
		 MySubscription->name);
}
else
{
	SpockGroupKey		key;
	SpockGroupEntry	   *entry;
	bool				found;
	RepOriginId			target_origin = replorigin_session_origin;

	key.dbid = MyDatabaseId;
	key.node_id = MySubscription->target->id;
	key.remote_node_id = MySubscription->origin->id;

	LWLockAcquire(SpockCtx->apply_group_master_lock, LW_SHARED);
	entry = (SpockGroupEntry *) hash_search(SpockGroupHash, &key,
											HASH_FIND, &found);
	LWLockRelease(SpockCtx->apply_group_master_lock);

	if (entry != NULL)
		recover_progress_timestamps_from_commit_ts(entry, target_origin);
}

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
make -j4 install
cd tests/tap && ./run_tests.sh t/027_remote_commit_ts_recovery.pl

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
./run_tests.sh t/022_rmgr_progress_post_checkpoint_crash.pl t/008_rmgr.pl

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:

my $post_commit_ts = scalar_query(2, q{
    SELECT remote_commit_ts::text FROM spock.progress LIMIT 1
});
is($post_commit_ts, '',
   "remote_commit_ts is NULL post-crash (reconcile cleared stale ts)");

diag("post-crash: remote_commit_lsn=$post_commit_lsn remote_commit_ts='$post_commit_ts' (expected NULL)");

to:

my $post_commit_ts = scalar_query(2, q{
    SELECT remote_commit_ts::text FROM spock.progress LIMIT 1
});
ok($post_commit_ts ne '',
   "remote_commit_ts is NOT NULL post-crash (recovered via pg_commit_ts scan)");

diag("post-crash: remote_commit_lsn=$post_commit_lsn remote_commit_ts='$post_commit_ts'");

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
./run_tests.sh t/022_rmgr_progress_post_checkpoint_crash.pl

Expected: all subtests pass.

  • Step 4.9: Commit
git add src/spock_apply.c tests/tap/t/022_rmgr_progress_post_checkpoint_crash.pl
git commit -m "feat: recover remote_commit_ts via pg_commit_ts scan on crash restart

After reconcile_progress_with_origin detects that resource.dat is stale
or absent for an origin, scan pg_commit_ts backward from the latest xid
and populate remote_commit_ts with the max ts found for this origin.
The recovered values are also intended to be useful for the planned
parallel-apply rework.

Termination: 1000 commits seen for this origin (concurrency width is
bounded well below this by max_connections / poolers) or 1M xids total.
Logs INFO on completion (skip path or run path) so startup behavior is
grep-able.

Updates test 022 to reflect that remote_commit_ts is now recovered
rather than NULL after crash."

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.pl

  • Step 5.1: Create the test

Write tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl:

#!/usr/bin/perl
# =============================================================================
# Test: 030_remote_commit_ts_recovery_track_commit_ts_off.pl
#       Verify that the apply worker errors out at startup if
#       track_commit_timestamp is off and the recovery scan would otherwise
#       run (i.e., resource.dat is stale or absent). Spock requires
#       track_commit_timestamp = on for conflict resolution; making the
#       failure mode loud at apply-worker start is intentional.
# =============================================================================

use strict;
use warnings;
use Test::More;
use lib '.';
use SpockTest qw(
    create_cluster destroy_cluster system_or_bail
    command_ok get_test_config scalar_query psql_or_bail
    wait_for_sub_status wait_for_pg_ready
);

sub wait_until {
    my ($timeout_s, $probe) = @_;
    my $deadline = time() + $timeout_s;
    while (time() < $deadline) {
        return 1 if $probe->();
        select(undef, undef, undef, 0.25);
    }
    return 0;
}

sub log_contains {
    my ($logfile, $pattern) = @_;
    return 0 unless -f $logfile;
    open(my $fh, '<', $logfile) or return 0;
    while (my $line = <$fh>) {
        return 1 if $line =~ /$pattern/;
    }
    close($fh);
    return 0;
}

create_cluster(2, 'Create 2-node cluster');

my $conf      = get_test_config();
my $host      = $conf->{host};
my $pg_bin    = $conf->{pg_bin};
my $ports     = $conf->{node_ports};
my $datadirs  = $conf->{node_datadirs};
my $dbname    = $conf->{db_name};
my $user      = $conf->{db_user};

my $prov_port = $ports->[0];
my $sub_port  = $ports->[1];
my $sub_dir   = $datadirs->[1];

my $prov_dsn = "host=$host port=$prov_port dbname=$dbname user=$user";

psql_or_bail(1, "CREATE TABLE public.ts_off (id int primary key, val text)");
psql_or_bail(2, "CREATE TABLE public.ts_off (id int primary key, val text)");

psql_or_bail(2, "SELECT spock.sub_create('test_sub', '$prov_dsn', ARRAY['default'], false, false)");
ok(wait_for_sub_status(2, 'test_sub', 'replicating', 30), 'subscription is replicating');

psql_or_bail(1, "INSERT INTO public.ts_off SELECT g, 'r1_' || g FROM generate_series(1,50) g");
ok(wait_until(30, sub { scalar_query(2, "SELECT count(*) FROM public.ts_off") eq '50' }),
   '50 rows replicated');

# Clean restart so resource.dat is current.
system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-m', 'fast', 'stop';
system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-o', "-p $sub_port", '-w', 'start';
ok(wait_for_sub_status(2, 'test_sub', 'replicating', 30), 'replicating after clean restart');

# Apply more so resource.dat goes stale.
psql_or_bail(1, "INSERT INTO public.ts_off SELECT g, 'r2_' || g FROM generate_series(51,100) g");
ok(wait_until(30, sub { scalar_query(2, "SELECT count(*) FROM public.ts_off") eq '100' }),
   '100 rows replicated');

# Disable track_commit_timestamp -- requires a postmaster restart, but our
# next step is going to crash and restart anyway.
psql_or_bail(2, "ALTER SYSTEM SET track_commit_timestamp = off");

# SIGKILL.
my $pid_file = "$sub_dir/postmaster.pid";
open(my $fh, '<', $pid_file) or die "Cannot open $pid_file: $!";
my $sub_pid = <$fh>;
chomp($sub_pid);
close($fh);
kill 'KILL', $sub_pid;
pass('subscriber SIGKILLed');

select(undef, undef, undef, 2.0);

# Restart -- track_commit_timestamp is now off; reconcile sees stale file;
# recovery scan must error out.
system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-o', "-p $sub_port", '-w', 'start';
ok(wait_for_pg_ready($host, $sub_port, $pg_bin, 30), 'subscriber back up');

# Wait for the apply worker to attempt start, then check the log for the
# expected ERROR. The bgworker manager will respawn it; we just need to
# verify the message appears.
my $logfile = "$sub_dir/log/postgresql-1.log";
# SpockTest may put logs elsewhere; adjust path if needed by reading test
# config or scanning $sub_dir/log/.
ok(wait_until(30, sub {
    log_contains($logfile, qr/track_commit_timestamp.*on/i)
}), "apply worker logged ERROR about track_commit_timestamp being off");

# Restore for cleanup.
psql_or_bail(2, "ALTER SYSTEM SET track_commit_timestamp = on");
system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-m', 'fast', 'restart';

destroy_cluster('Destroy 2-node cluster');
done_testing();

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”).

chmod +x tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl
  • Step 5.2: Run the test — confirm it fails as expected
./run_tests.sh t/030_remote_commit_ts_recovery_track_commit_ts_off.pl

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
git add tests/tap/t/030_remote_commit_ts_recovery_track_commit_ts_off.pl
git commit -m "test: add 030 (track_commit_timestamp off, currently failing)

Asserts the apply worker errors at startup if track_commit_timestamp
is off when the recovery scan would otherwise run. Currently fails --
guard lands in the next commit."

Task 6: Add the track_commit_timestamp guard

Files:

  • Modify: src/spock_apply.c — add the guard at the top of recover_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:

if (!track_commit_timestamps)
	ereport(ERROR,
			(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			 errmsg("SPOCK %s: track_commit_timestamp must be on for spock.progress recovery",
					MySubscription->name),
			 errhint("Set track_commit_timestamp = on in postgresql.conf and restart.")));

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
make -j4 install

Expected: clean build.

  • Step 6.3: Run test 030 — should now pass
./run_tests.sh t/030_remote_commit_ts_recovery_track_commit_ts_off.pl

Expected: all subtests pass.

  • Step 6.4: Run test 027 to confirm no regression
./run_tests.sh t/027_remote_commit_ts_recovery.pl

Expected: all subtests pass.

  • Step 6.5: Commit
git add src/spock_apply.c
git commit -m "feat: error if track_commit_timestamp is off during ts recovery

Spock already requires track_commit_timestamp = on for conflict
resolution. Making the failure mode loud at apply-worker start (rather
than silently returning a degraded NULL state) is consistent with that
existing requirement and catches misconfiguration early."

Task 7: Add the clean-shutdown skip-path test (029)

Files:

  • Create: tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl

  • Step 7.1: Create the test

Write tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl:

#!/usr/bin/perl
# =============================================================================
# Test: 029_remote_commit_ts_recovery_clean_shutdown.pl
#       Verify that on a CLEAN restart (resource.dat in sync with origin),
#       the recovery scan is SKIPPED and the loaded remote_commit_ts is
#       preserved. Confirmed by checking the apply-worker INFO log for the
#       "file in sync, skipping scan" line.
# =============================================================================

use strict;
use warnings;
use Test::More;
use lib '.';
use SpockTest qw(
    create_cluster destroy_cluster system_or_bail
    command_ok get_test_config scalar_query psql_or_bail
    wait_for_sub_status wait_for_pg_ready
);

sub wait_until {
    my ($timeout_s, $probe) = @_;
    my $deadline = time() + $timeout_s;
    while (time() < $deadline) {
        return 1 if $probe->();
        select(undef, undef, undef, 0.25);
    }
    return 0;
}

sub log_grep_count {
    my ($logfile, $pattern) = @_;
    return 0 unless -f $logfile;
    open(my $fh, '<', $logfile) or return 0;
    my $count = 0;
    while (my $line = <$fh>) {
        $count++ if $line =~ /$pattern/;
    }
    close($fh);
    return $count;
}

create_cluster(2, 'Create 2-node cluster');

my $conf      = get_test_config();
my $host      = $conf->{host};
my $pg_bin    = $conf->{pg_bin};
my $ports     = $conf->{node_ports};
my $datadirs  = $conf->{node_datadirs};
my $dbname    = $conf->{db_name};
my $user      = $conf->{db_user};

my $prov_port = $ports->[0];
my $sub_port  = $ports->[1];
my $sub_dir   = $datadirs->[1];

my $prov_dsn = "host=$host port=$prov_port dbname=$dbname user=$user";

psql_or_bail(1, "CREATE TABLE public.ts_clean (id int primary key, val text)");
psql_or_bail(2, "CREATE TABLE public.ts_clean (id int primary key, val text)");

psql_or_bail(2, "SELECT spock.sub_create('test_sub', '$prov_dsn', ARRAY['default'], false, false)");
ok(wait_for_sub_status(2, 'test_sub', 'replicating', 30), 'subscription is replicating');

psql_or_bail(1, "INSERT INTO public.ts_clean SELECT g, 'r_' || g FROM generate_series(1,50) g");
ok(wait_until(30, sub { scalar_query(2, "SELECT count(*) FROM public.ts_clean") eq '50' }),
   '50 rows replicated');

# Capture pre-shutdown ts.
my $pre_ts = scalar_query(2, "SELECT remote_commit_ts::text FROM spock.progress LIMIT 1");
ok($pre_ts ne '', "pre-shutdown remote_commit_ts: $pre_ts");

# Establish baseline: count "skipping scan" log lines before restart.
my $logfile = "$sub_dir/log/postgresql-1.log";
my $skip_before = log_grep_count($logfile, qr/ts recovery: file in sync, skipping scan/);

# CLEAN shutdown + restart. resource.dat should match origin LSN.
system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-m', 'fast', 'stop';
ok(-f "$sub_dir/spock/resource.dat", 'resource.dat written on clean stop');

system_or_bail "$pg_bin/pg_ctl", '-D', $sub_dir, '-o', "-p $sub_port", '-w', 'start';
ok(wait_for_pg_ready($host, $sub_port, $pg_bin, 30), 'subscriber back up');
ok(wait_for_sub_status(2, 'test_sub', 'replicating', 30), 'replicating after clean restart');

# Wait for the new "skipping scan" log line.
ok(wait_until(15, sub {
    log_grep_count($logfile, qr/ts recovery: file in sync, skipping scan/) > $skip_before
}), 'apply worker logged "file in sync, skipping scan" on clean restart');

# Confirm scan was NOT run (no "scanned ... xids" line for this restart).
my $scan_run = log_grep_count($logfile, qr/ts recovery: scanned \d+ xids/);
# We only count NEW occurrences relative to baseline, but since baseline is 0
# for a fresh cluster, any positive count would indicate the scan ran.
# Capture before/after to be precise:
# (For simplicity, this test asserts the skip log appeared. A run log alongside
#  it would also appear, indicating the skip path was NOT taken; the assertion
#  below covers that case.)
is(log_grep_count($logfile, qr/ts recovery: scanned \d+ xids.*recovered remote_commit_ts/),
   0,
   'scan did NOT run on clean restart (no "recovered remote_commit_ts" log line)');

# remote_commit_ts should still match pre-shutdown.
my $post_ts = scalar_query(2, "SELECT remote_commit_ts::text FROM spock.progress LIMIT 1");
is($post_ts, $pre_ts, "remote_commit_ts preserved across clean restart");

psql_or_bail(2, "SELECT spock.sub_drop('test_sub')");
destroy_cluster('Destroy 2-node cluster');
done_testing();
chmod +x tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl
  • Step 7.2: Run the test
./run_tests.sh t/029_remote_commit_ts_recovery_clean_shutdown.pl

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
git add tests/tap/t/029_remote_commit_ts_recovery_clean_shutdown.pl
git commit -m "test: add 029 (clean-shutdown skip path for ts recovery)

Verifies that on a clean restart, when resource.dat matches the origin
LSN, the recovery scan is skipped and the loaded remote_commit_ts is
preserved. Asserted via the INFO log line and absence of any 'scanned
xids' line for the restart."

Task 8: Final regression sweep

  • Step 8.1: Run the full TAP suite
cd tests/tap && ./run_tests.sh

Expected: all tests pass, including 008, 022, 023, 026, and the three new tests (027, 029, 030).

  • Step 8.2: Verify the commit log
git log --oneline main..HEAD | head -20

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_timestamp guard (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: ReconcileResult enum (Task 1) is used in Task 4’s call site. target_origin is RepOriginId. running_max_ts is TimestampTz. Constants are int64-safe via the (int64) total_scanned cast.
  • 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.pm if 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.

PG.CENTER edition

2.16.3 - Design decisions

Explanations of why things are done the way they are.

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-upgrade support 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.

PG.CENTER edition

2.16.4 - spock Output Plugin

This is the logical decoding output plugin 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.

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=database and dbname=[...] parameters
    • The PostgreSQL client library can be libpq or 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
  • 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 spock message block encapsulated in a replication protocol CopyData message
    • Client receives and unwraps message, then decodes the spock message block
    • Client intermittently sends a standby status update message to server to confirm replay
  • … 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 RepOriginId that 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 Relation the 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.

PG.CENTER edition

2.16.5 - Spock Protocol

spockoutput defines a libpq subprotocol for streaming tuples, metadata, etc., from the decoding plugin to receivers.

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

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

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.

MessageType/SizeNotes
Message typesigned charLiteral B (0x42)
flagsuint80-3: Reserved, client must ERROR if set and not recognised.
lsnuint64“final_lsn” in decoding context - currently it means lsn of commit
commit timeuint64“commit_time” in decoding context
remote XIDuint32“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.

MessageType/SizeNotes
Message typesigned charLiteral O (0x4f)
flagsuint80-3: Reserved, application must ERROR if set and not recognised
origin_lsnuint64LSN (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_lengthuint8Length in bytes of origin_identifier
origin_identifiersigned 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.

MessageType/SizeNotes
Message typesigned charLiteral C (0x43)
Flagsuint80-3: Reserved, client must ERROR if set and not recognised
Commit LSNuint64commit_lsn in decoding commit decode callback. This is the same value as in the BEGIN message, and marks the end of the transaction.
End LSNuint64end_lsn in decoding transaction context
Commit timeuint64commit_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

MessageType/SizeNotes
Message typesigned charLiteral Insert (0x49), Update (0x55) or Delete (0x44)
flagsuint8Row flags (reserved)
relidentifieruint32relidentifier 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

MessageType/SizeNotes
Tuple typesigned charIdentifies the kind of tuple being sent.
tupleformatsigned charT (0x54)
nattsuint16Number 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:

MessageType/SizeNotes
kindsigned charnull (0x6e) field

Full tuple value fields have a length and datum:

MessageType/SizeNotes
kindsigned charinternal binary (0x62) field
lengthint4Only 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

MessageType/SizeNotes
Message typesigned charLiteral R (0x52)
flagsuint80-6: Reserved, client must ERROR if set and not recognised.
relidentifieruint32Arbitrary relation id, unique for this upstream. In practice this will probably be the upstream table’s oid, but the downstream can’t assume anything.
nspnamelengthuint8Length of namespace name (incl. terminating \0)
nspnamesigned char[nspnamelength]Relation namespace (null terminated)
relnamelengthuint8Length of relation name (incl. terminating \0)
relnamechar[relname]Relation name (null terminated)
attrs blocksigned charLiteral: A (0x41)
nattsuint16Number 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.

MessageType/SizeNotes
blocktypesigned charC (0x43) - column
flagsuint8Column info flags

Column Metadata Block Header

All column metadata blocks share the same header, which is the same length as a column delimiter:

MessageType/SizeNotes
blocktypesigned charIdentifies the kind of metadata block that follows.
blockbodylengthuint16Length 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.

MessageType/SizeNotes
[column metadata block header][composite]blocktype = N (0x4e)
colnamechar[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

MessageType/SizeNotes
Message typesigned charS (0x53) - startup
Startup message versionuint8Value is always “1”.
(parameters)null-terminated key/value pairsSee 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 nameValue typeDescription
max_proto_versionintegerNewest version of the protocol supported by output plugin. Currently 5.
min_proto_versionintegerOldest protocol version supported by server. Currently 4.
proto_versionintegerThe negotiated protocol version selected by the server based on the overlap between client and server ranges.
coltypesbooleanColumn types will be sent in table metadata. Currently always false.
pg_version_numintegerPostgreSQL server_version_num of server, if it’s PostgreSQL. e.g. 180000
pg_versionstringPostgreSQL server_version of server, if it’s PostgreSQL. e.g. “18.0”
pg_catversionuint32Version of the PostgreSQL system catalogs on the upstream server, if it’s PostgreSQL.
database_encodingstringThe native text encoding of the database the plugin is running in.
encodingstringField 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_originsboolTells the client that the server will send changeset origin information. See Changeset forwarding for details.
walsender_pidintegerPID of the walsender process on the upstream server.
spock_versionstringSpock version string of the upstream server. e.g. “4.0.11”
spock_version_numintegerSpock numeric version of the upstream server. e.g. 40011
no_txinfoboolEcho 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 nameValue typeDescription
binary.internal_basetypesbooleanIf 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_basetypesbooleanIf 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_versionuint16The PostgreSQL major version that internal binary format values are compatible with. Corresponds to PG_VERSION_NUM/100 on the upstream server.
binary.binary_pg_versionuint16The PostgreSQL major version that send/recv format values will be compatible with. This is not necessarily the actual upstream PostgreSQL version.
binary.sizeof_intuint8sizeof(int) on the upstream.
binary.sizeof_longuint8sizeof(long) on the upstream.
binary.sizeof_datumuint8sizeof(Datum) on the upstream (the PostgreSQL Datum typedef).
binary.maxalignuint8Upstream PostgreSQL server’s MAXIMUM_ALIGNOF value - platform dependent, determined at build time.
binary.bigendianboolTrue iff the upstream is big-endian.
binary.float4_byvalboolUpstream PostgreSQL’s float4_byval compile option.
binary.float8_byvalboolUpstream PostgreSQL’s float8_byval compile option.
binary.integer_datetimesboolWhether 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.

KeyTypeValue(s)Notes
startup_params_formatuint321The format version of this startup parameter set. Currently always 1. Required, ERROR if missing.
max_proto_versionuint324-5Newest version of the protocol supported by client. Output plugin must ERROR if supported version too old. Required, ERROR if missing.
min_proto_versionuint324-5Oldest version of the protocol supported by client. Output plugin must ERROR if supported version too old. Required, ERROR if missing.

Client Requirements and Capabilities

KeyTypeDefaultNotes
expected_encodingstringnullThe 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_formatstringnullProtocol format requested. “native” (documented here) or “json”. Default is native (binary).
no_txinfobooleanfalseWhen 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.

KeyTypeDefaultNotes
spock.forward_originsstringnullComma-separated list of replication origin names to forward. Currently only the special value “all” is accepted.
spock.replication_set_namesstringnullComma-separated list of replication set names to subscribe to. If specified, only changes in the named replication sets are sent.
spock.replicate_only_tablestringnullQualified table name (schema.table) to replicate. If specified, only changes to this single table are sent. Used during initial table synchronization.
hooks.setup_functionstringnullLegacy 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.

KeyTypeDefaultNotes
pg_versionuint32nullPostgreSQL 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_versionstringnullSpock version string of the downstream. e.g. “4.0.11”. Logged on the upstream if it differs from the server’s version.
spock_version_numuint32nullSpock 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 nameValue typeDefaultDescription
binary.want_binary_basetypesbooleanfalseTrue if the client accepts binary interchange (send/recv) format rows for PostgreSQL built-in base types.
binary.want_internal_basetypesbooleanfalseTrue if the client accepts PostgreSQL internal-format binary output for base PostgreSQL types not otherwise specified elsewhere.
binary.basetypes_major_versionuint32nullThe 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_intuint32nullsizeof(int) on the downstream.
binary.sizeof_longuint32nullsizeof(long) on the downstream.
binary.sizeof_datumuint32nullsizeof(Datum) on the downstream (the PostgreSQL Datum typedef).
binary.bigendianboolnullTrue iff the downstream is big-endian.
binary.float4_byvalboolnullDownstream PostgreSQL’s float4_byval compile option.
binary.float8_byvalboolnullDownstream PostgreSQL’s float8_byval compile option.
binary.integer_datetimesboolnullDownstream PostgreSQL’s integer_datetimes compile option.

Note: binary.maxalign is 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.

PG.CENTER edition

2.17 - Troubleshooting Spock

This document provides solutions to common issues encountered when using Spock for PostgreSQL logical 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.

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:

SELECT * FROM spock.node_status;
SELECT subscription_name, status, worker_status, last_error_message
  FROM spock.subscription_status;
SELECT event_time, event_type, severity, detail
  FROM spock.events WHERE severity <> 'info' ORDER BY event_id DESC LIMIT 20;

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.conf entries allow secure connections between nodes.

  • Test network connectivity between nodes with the following command:

    psql -h <remote_node_ip> -U postgres -d <database_name>
  • You can check the PostgreSQL logs for detailed error messages with this command:

    tail -f /var/lib/pgsql/18/data/log/postgresql-*.log
  • You can verify that the Spock extension is created on both nodes with this query:

    SELECT extname, extversion FROM pg_extension WHERE extname = 'spock';

Subscription Stuck in Initializing State

If a subscription remains in the initializing state, verify the following configuration parameters.

  • Check that max_replication_slots is set to a sufficient value:

    SHOW max_replication_slots;

    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 databases per node, plus any physical or failover slots. On PostgreSQL 15-17 this parameter also caps replication origins.

  • Verify that max_wal_senders is set to a sufficient value:

    SHOW max_wal_senders;

    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_origins setting:

    SHOW max_active_replication_origins;

    Ensure that the value is at least the number of subscriptions this node applies - (nodes - 1) x replicated databases in a full mesh - plus headroom.

  • If parameters were modified, restart PostgreSQL with this command:

    sudo systemctl restart postgresql-18
  • Check the subscription status with this query:

    SELECT * FROM spock.sub_show_status();

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:

    SHOW spock.enable_ddl_replication;

    The value should be on.

  • Check that the include_ddl_repset parameter is enabled:

    SHOW spock.include_ddl_repset;
  • 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:

    SHOW spock.allow_ddl_from_functions;
Warning

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:

    ALTER TABLE table_name ADD PRIMARY KEY (column_name);
  • Alternatively, set a replica identity using a unique index:

    ALTER TABLE table_name REPLICA IDENTITY USING INDEX index_name;

The unique index must be non-partial, non-deferrable, and use NOT NULL columns.

Note

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:

ERROR: spock doesn't support index rechecks needed for deferrable indexes
DETAIL: relation "public"."test_relation" has deferrable indexes: "index1"

To resolve this issue, convert deferrable constraints to non-deferrable:

ALTER TABLE table_name DROP CONSTRAINT constraint_name;
ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_name);

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.

ALTER TABLE table_name ALTER COLUMN column_name SET NOT NULL;

Then configure the Delta-Apply column with the following command:

ALTER TABLE table_name ALTER COLUMN column_name
  SET (log_old_value=true, delta_apply_function=spock.delta_apply);

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:

wal_level = logical
max_worker_processes = 20
max_replication_slots = 10
max_wal_senders = 10
shared_preload_libraries = 'spock'
track_commit_timestamp = on

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:

sudo systemctl restart postgresql-18

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:

ERROR:  library "spock_output" may not be used as an output plugin
HINT:   If it is safe for all REPLICATION users to use this library as an
        output plugin, add it to "output_plugin_libraries" and reload the
        server configuration.

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:

output_plugin_libraries = 'pgoutput, test_decoding, spock_output'

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:

SELECT current_setting('output_plugin_libraries', true);

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:

SHOW spock.conflict_resolution;

The only supported value is:

  • last_update_wins - Keep the version with the newest commit timestamp.

To change the setting, use the following command:

ALTER SYSTEM SET spock.conflict_resolution = 'last_update_wins';
SELECT pg_reload_conf();
Note

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:

SHOW spock.exception_behaviour;

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:

ALTER SYSTEM SET spock.exception_behaviour = 'discard';
SELECT pg_reload_conf();

You can check the exception log table for details with this query:

SELECT * FROM spock.exception_log ORDER BY timestamp DESC LIMIT 10;

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:

SELECT subscription_name, provider_node, replication_lag_bytes,
       replication_lag, worker_status
  FROM spock.subscription_status;

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:

  1. Assess damage by checking subscription status on surviving nodes.

  2. Clean up Spock metadata by dropping subscriptions to the failed node:

    SELECT spock.sub_drop(subscription_name := 'sub_to_failed_node');
    SELECT spock.node_drop(node_name := 'failed_node');
  3. Identify missing data using ACE table-diff with these flags:

    ./ace table-diff --nodes n2,n3,n4 --preserve-origin n1 \
      --until 2026-02-11T14:30:00Z --output json cluster public.table_name
  4. Repair affected tables using ACE table-repair:

    ./ace table-repair --diff-file=diff_file.json \
      --nodes n2,n3,n4 --recovery-mode --source-of-truth n3 \
      --preserve-origin cluster public.table_name
  5. Validate by re-running table-diff without flags to confirm tables match.

Warning

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:

    SELECT worker_status, worker_terminated_at, last_error_message
      FROM spock.subscription_status WHERE subscription_name = 'sub_name';
    SELECT event_time, event_type, detail FROM spock.events
     WHERE subscription_name = 'sub_name' ORDER BY event_id DESC LIMIT 20;

    A worker_status of restart pending means the worker failed and the manager will retry after worker_restart_delay milliseconds.

  • Verify the provider node is running and accessible.

  • Check replication slots on the provider with this query:

    SELECT slot_name, active, retained_wal_bytes FROM spock.slot_status;
  • Review PostgreSQL logs on both provider and subscriber nodes if the views do not explain the failure.

  • Restart the subscription with these commands:

    SELECT spock.sub_disable(subscription_name := 'sub_name');
    SELECT spock.sub_enable(subscription_name := 'sub_name');

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.

  1. Check that the extension matches the installed library and that the upgrade was recorded:

    SELECT spock_version, extension_version, extension_update_pending
      FROM spock.node_status;
    SELECT event_time, detail FROM spock.events
     WHERE event_type = 'extension_upgraded';
  2. Verify subscription status with this query:

    SELECT subscription_name, enabled, status, worker_status
      FROM spock.subscription_status;
  3. Check replication slots on each provider with this query:

    SELECT slot_name, active, state, retained_wal_bytes FROM spock.slot_status;
  4. Monitor replication lag with this query:

    SELECT subscription_name, replication_lag_bytes, replication_lag
      FROM spock.subscription_status;

DDL Replication After Upgrade

If DDL replication was disabled for the upgrade, re-enable it on all nodes with the following commands:

ALTER SYSTEM SET spock.enable_ddl_replication = on;
SELECT pg_reload_conf();

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:

SELECT spock.repset_alter_table(
    set_name := 'default',
    relation := 'public.table_name',
    columns := ARRAY['col1', 'col2', 'new_col']
);

Partitioned Table Replication

If new partitions are not replicating, add them manually with the following command:

SELECT spock.repset_add_partition(
    parent := 'public.parent_table',
    partition := 'public.new_partition'
);

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:

SHOW log_directory;
SHOW log_filename;

On RHEL/Rocky Linux, logs are typically located at:

/var/lib/pgsql/18/data/log/

Monitor logs in real-time with this command:

tail -f /var/lib/pgsql/18/data/log/postgresql-*.log

Filter for Spock-related messages with this command:

grep -i spock /var/lib/pgsql/18/data/log/postgresql-*.log

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:


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.

PG.CENTER edition

2.18 - Frequently Asked Questions

Column filters work fine on tables with OIDs, but spock cannot filter on system columns like oid or xmin.

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 oid or xmin.

  • 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_filter on a table with OIDS? Can I filter on xmin?

    Yes, row_filter behavior works fine for table with OIDs, but spock cannot filter on system columns (like xmin).

  • 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_filter on attributes of JSONB datatype works fine.

Using apply_delay with Time Changes

  • Does apply_delay accommodate time zone changes, for example Daylight Savings Time?

    Note: the physical replication parameter recovery_min_apply_delay behaves 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_delay is 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.

PG.CENTER edition

2.19 - Spock Release Notes

This section lists what changed since 6.0.0-beta.1, for those testing the beta.

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 plain ALTER EXTENSION spock UPDATE does nothing on a beta 1 node. Update a beta 1 node this way instead:

    1. Pause DDL on the cluster.

    2. Install the beta 2 binaries and restart the node.

    3. In every database where Spock is installed, run:

      ALTER EXTENSION spock UPDATE TO '6.0.0-beta1-to-beta2';
      ALTER EXTENSION spock UPDATE TO '6.0.0';
    4. Repeat for each node, then resume DDL.

    5. On each primary, check that every Spock slot has the failover flag:

      SELECT slot_name, failover
      FROM pg_replication_slots
      WHERE plugin = 'spock_output';

      For any slot still showing false, pause the subscriber that holds it and run SELECT spock.slot_enable_failover(); on the primary.

    The first command adds the objects beta 2 needs (the spock.reserved_object catalog and its functions, the node metadata functions and the trigger on spock.node, and the monitoring views and functions with their pg_monitor grants), removes spock.wait_for_apply_worker(), reimplements spock.get_apply_worker_status() over spock.get_worker_status(), marks spock.md5_agg parallel safe on a node upgraded from 5.x, and sets the failover flag on existing slots. The second only sets the version name back to 6.0.0.

    The failover flag 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, because spock.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_output must be listed in output_plugin_libraries. See Upgrading below.

  • On PostgreSQL 18, spock.pg_standby_slot_names did 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 default spock.standby_slots_min_confirmed of -1 a logical walsender waits for every named slot until wal_sender_timeout and 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, default 1024, range 16 to 1048576, POSTMASTER): how many recent events the spock.events view 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 by pg_monitor, since pg_replication_origin_status is 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() and spock.report_section(). get_system_info(), get_events(), get_apply_stats() and get_pending_exceptions() are executable by pg_monitor only, and reset_events() by superusers only.

Changed

  • spock.get_apply_worker_status() is now a SQL function over spock.get_worker_status(), with the same columns and rows as before. spock.get_worker_status() and the spock.worker_status view 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, default 0, USERSET): the time limit for a single wait in the node management routines. 0 keeps each routine’s built-in limit.
  • spock.non_conflicting_inserts (boolean, default off, POSTMASTER): asserts that a replicated INSERT can never collide with a local row, so the apply worker skips the conflict lookup and the speculative insertion.
  • spock.failover_slots_naptime (milliseconds, default 1000, SIGHUP) and spock.failover_slots_feedback_naptime (milliseconds, default 10000, SIGHUP): how often Spock’s failover-slots worker syncs slots. It used to wait a fixed 60 seconds.
  • spock.failover_slots_recreate_invalidated (boolean, default on, 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_exception and spock.output_delay are now declared in milliseconds, so they accept values with units such as '5s'.
  • spock.restart_delay_default now 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 a tiebreaker value.
  • 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() and spock.node_refresh_info_one(), and the node_info_broadcast_trigger trigger on spock.node. EXECUTE on the first two and on node_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_names with spock.standby_slots_min_confirmed is 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’s synchronized_standby_slots waits 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_invalidated above.
  • On PostgreSQL 16 and 17, with spock.failover_slots_database set and wal_level = logical on 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, with spock.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 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. The commit timestamp of a frozen row is now found.
  • A procedure that runs COMMIT or ROLLBACK, 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_logging on, 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) and REPACK (CONCURRENTLY) locally and does not replicate them, since neither can run inside the apply worker’s transaction.
  • spock.sub_wait_for_sync() and spock.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 spock and snowflake schemas is refused while DDL replication is on.
  • Large objects stored by lolor can be replicated, and Zodan add_node copies them to the new node.
  • Zodan add_node can 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_origins cannot 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_upgrade of a Spock node on PostgreSQL 17 and later no longer fails with resource 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 INSERT that collides with a row committed locally at the same moment goes to conflict resolution instead of failing with a duplicate key error. Each INSERT into a table with a unique index now takes a speculative insertion; see spock.non_conflicting_inserts above.
  • 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 tiebreaker pick 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. The CONFLICT: ... wins over ... by tiebreaker log 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 query when an extension such as pg_duckdb runs a query on SET.
  • 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() and spock.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 as Invalid argument; and table sync no longer fails against an origin older than 5.0.7, which lacks spock.pause_apply_workers(). From 5.0.14, besides the failover-slots, frozen-row and CALL fixes listed above: a slot named in spock.pg_standby_slot_names that does not exist is reported even when the other slots meet spock.standby_slots_min_confirmed, a slot named twice is counted once, AutoDDL no longer replicates CLUSTER without a table or CLUSTER on 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 after spock.restart_delay_default instead.
  • AutoDDL failed CREATE SCHEMA ... CREATE TABLE ... with relation "..." 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 attoptions server 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.progress is now a view backed by spock.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, and info (including its conflict-resolution tiebreaker) now propagate automatically to every direct subscriber on change, via the new spock.node_alter() function or a plain UPDATE; no more silently disagreeing tiebreakers from a forgotten spock.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_status and spock.events give the complete picture of a node without reading the server log.
  • Liveness and feedback refactor — TCP keepalive replaces the fragile wal_sender_timeout workaround; new spock.apply_idle_timeout GUC.
  • 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_object catalog controls which schemas and extensions are left out of structure sync, replication sets and DDL replication.
  • Mixed-version node addition — Zodan add_node can 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_node copies 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, CLUSTER folded into REPACK, the pgstat and recovery-conflict signalling changes, and the RepOriginId rename). 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:

  1. Identify which rows are missing on lagging survivors using table-diff --preserve-origin.
  2. 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.progress is now a view over the new spock.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. Use apply_group_progress() directly (or the view) for live data, and use the new spock.read_peer_progress(slot, provider_node_id, subscriber_node_id) function during slot snapshot import.
  • spock.lag_tracker view redefined. The old last_received_lsn column has been renamed to commit_lsn to reflect what it actually is, and a new received_lsn column reports the last LSN sent by the publisher (matching the pgoutput protocol convention).
  • remote_insert_lsn is 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_operation field 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 4 MB, unit MB). When the queue exceeds the cap, subsequent entries spill to a temporary file on disk. Set to 0 to disable spilling and allow unbounded memory use (improves throughput for very large transactions; allocation failure falls back to spock.exception_behaviour).

spock.exception_behaviour continues to control the action on unrecoverable errors:

ValueAction
discardSkip the failed transaction and continue replication.
transdiscardRoll back the failed transaction and continue.
sub_disableDisable the subscription and exit cleanly.

Logical Slot Failover

  • On PostgreSQL 17+, Spock creates all logical replication slots with the FAILOVER flag, 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_slots background worker is no longer registered. The native PostgreSQL slotsync worker fully replaces it. See the Logical Slot Failover section of the configuration guide for required postgresql.conf settings.
  • On PostgreSQL 17, Spock’s worker remains active but automatically yields to the native slotsync worker if sync_replication_slots = on is 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 = off leaves 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_database set and wal_level = logical on 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 as DROP DATABASE on it fail.

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 typev6.0 type(s)What changed
insert_existsinsert_existsNo change.
update_updateupdate_exists / update_origin_differsSpock 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_deleteupdate_missingRenamed for clarity.
delete_deletedelete_missing / delete_origin_differsSpock now logs whether the missing row was last modified by a different origin.
(new)delete_existsA 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_status and spock.settings for the known nodes, the replication sets and the parameters replication depends on.
  • spock.system_status for 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_error events. 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=0 on 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_USER renamed to READONLY_LOCAL (the old name is retained as a backward-compatible alias) to clarify that it restricts local (non-replication) connections.
  • In READONLY_ALL mode, the apply worker sends keepalive feedback but skips applying new transactions.
  • Read-only mode changes are detected before applying the next transaction (CHECK_FOR_INTERRUPTS moved 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 new spock.gen_sub_name() helper.
  • remove_node drops subscriptions from the spock.subscription catalog 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_node can 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_timeout GUC 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_timeout no longer has a 300-second maximum.
  • The old Python versions, zodan.py and zodremove.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 UPDATE are no longer replicated.

  • Transaction guards — AutoDDL hook no longer fails when utility commands (e.g., CLUSTER without a table name) execute outside a transaction context.

  • Filtered non-transactional DDL — commands that cannot execute inside transaction blocks on subscribers (e.g., CLUSTER on partitioned tables, VACUUM) are filtered on the publisher side before being queued.

  • Temporary-relation DDL not replicated — CREATE TABLE … (LIKE temp) and CREATE TABLE … AS SELECT … FROM temp are skipped, since the temporary relation does not exist on the subscriber.

  • Replication-set stickiness on ALTER TABLE — with spock.include_ddl_repset enabled, ALTER TABLE no longer evicts a table from a user-defined replication set unless it adds or drops a primary key / replica identity. Inline ADD COLUMN … PRIMARY KEY and REPLICA IDENTITY FULL tables are now classified correctly.

  • Safe search_path interpolation — replicated DDL ships a valid SET search_path even when the session path is empty.

  • Direct DDL against spock and snowflake is refused (behaviour change) — while spock.enable_ddl_replication is on, a statement whose target schema is one of the built-in extension-owned schemas now fails outright:

    ERROR:  cannot run DDL against schema snowflake while DDL replication is enabled
    DETAIL:  The schema is managed by an extension and its objects are not replicated.
    HINT:  For a deliberate node-local change, run the statement with spock.enable_ddl_replication = off.

    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 EXTENSION stays node-local — with spock.allow_ddl_from_functions on, DDL an extension ran while being dropped was queued for replication, even though every peer runs the same cleanup when it applies the DROP EXTENSION. For lolor this left peers unable to drop the extension and stalled apply. The DROP EXTENSION itself still replicates, except for a node-local extension (below).

  • CREATE, ALTER and DROP EXTENSION lolor are no longer replicated. lolor refuses to be created or dropped by an apply worker, so every peer logged the replicated statement in spock.exception_log and discarded it, while the node that ran it reported it as replicated. The lolor extension row in spock.reserved_object has replicate_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 lolor and SECURITY LABEL ON EXTENSION lolor stay local too. A DROP EXTENSION naming lolor together with another extension is refused while DDL replication is on, and so is CREATE EXTENSION ... CASCADE of 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: when false, CREATE, ALTER and DROP EXTENSION for 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 as GRANT, still replicate. See the list in Replication Set Management. The default is true.

The built-in rows cannot be changed or removed:

Objectexclude_from_dumpblock_in_repsetreplicate_ddl
spockyesyesyes
snowflakeyesyesyes
loloryesnoschema yes, extension no
coldfrontyesnoyes
pgedge_aceyesyesno

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.
    • remotetuple is now freed after use in the conflict reporting path.
  • Shared memory initialization centralized in spock_shmem.c with 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_lsn lost after crash recovery — the value was not included in WAL records and defaulted to 0 after crash recovery, breaking lag tracking in spock.lag_tracker.
  • Generated columns — tables containing GENERATED ALWAYS AS … STORED columns 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 calling RelationGetReplicaIndex(), 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_SIZE tables, and torn reads of 64-bit counters without spinlock protection.
  • Skip LSN mechanism — a successfully skipped transaction in SUB_DISABLE mode 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 after PQputCopyEnd() to detect failures, and a new SYNC_STATUS_FAILED state stops retry loops and surfaces clear error messages.
  • Un-appliable TRUNCATE loop — in discard mode 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_upgrade failed on PostgreSQL 17 and later — pg_upgrade decodes each logical slot’s remaining WAL to check it is drained, and Spock’s resource manager was not registered in the servers pg_upgrade starts. The check failed with resource manager with ID 144 not registered.
  • Apply idle timeout treated as a data exception — when spock.apply_idle_timeout fired 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_lsn now 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 DateStyle and TimeZone. 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 during add_node. Peer connections now request datestyle=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 called instead of the real error.
  • Replicated INSERT racing 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 each INSERT into a table with a unique index; spock.non_conflicting_inserts turns 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 unless spock.check_all_uc_indexes is 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 on SET made the snapshot import fail with SET 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 an UPDATE that found no row disabled the subscription under sub_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_wins against a frozen row — the commit timestamp of a local row was looked up through its xmin, which reads as frozen once VACUUM freezes the row, and the row then counted as older than any change. An older incoming UPDATE overwrote 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 normal VACUUM can too. The original xid is now used.
  • Crash after a procedure that ends its transaction — after a CALL that runs COMMIT or ROLLBACK over the extended query protocol with a bound parameter, AutoDDL read the statement from freed memory and the server crashed. spock.wait_for_sync_event() runs ROLLBACK, so a psycopg or JDBC client waiting for a sync event could crash a node.
  • spock.apply_change_logging with 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.dat writes — 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.
  • REPACK on PostgreSQL 19 — AutoDDL queued REPACK (ANALYZE) and REPACK (CONCURRENTLY), which cannot run inside the apply worker’s transaction. They now run locally only, as table-less and partitioned CLUSTER already 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() and spock.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/ and include/ directories.
  • Packaging — the repository now builds the spock60 RPM 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.md explaining how to report vulnerabilities, and the output_plugin_libraries requirement in the README and the configuration, installation and troubleshooting guides. The guide to running logical slot failover under Patroni, with the sample samples/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, default 300, 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 to 0 to disable and rely solely on TCP keepalive for liveness detection.
  • spock.output_delay (int milliseconds, default 0, 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, default 100, SIGHUP) — TTL for rows in spock.resolutions. Rows older than this are deleted periodically by the apply worker. Set to 0 to disable automatic cleanup. Complements spock.cleanup_resolutions(days) and the new index on resolutions(log_time).
  • spock.enable_quiet_mode (bool, default off, SIGHUP) — when enabled, downgrades DDL replication INFO/WARNING messages to LOG level and suppresses dependent-object reporting in DROP CASCADE operations. Intended for regression tests and production environments where less verbose output is desired.
  • spock.log_verbosity (enum normal/debug1/debug2, default normal, SUSET) — promotes Spock’s own DEBUG1/DEBUG2 messages to LOG so they survive a normal log_min_messages.
  • spock.apply_change_logging (enum none/key_only/verbose, default none, SUSET) — emits per-change JSON from the apply worker (action, table, key, origin, commit timestamp; plus row data in verbose).
  • spock.read_retry_count allows 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, default 0, 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. 0 keeps each routine’s built-in limit. It can be set for one operation, for example SET spock.sync_timeout = '2h'.
  • spock.failover_slots_naptime (int milliseconds, default 1000, 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, default 10000, 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 when sync_replication_slots is off.
  • spock.non_conflicting_inserts (bool, default off, POSTMASTER) — asserts that a replicated INSERT can 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 by spock.exception_behaviour rather than by conflict resolution.
  • spock.failover_slots_recreate_invalidated (bool, default on, SIGHUP) — whether Spock’s failover-slots worker drops and recreates a slot copy that was invalidated on the standby. off leaves 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: default 4194304 → 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_exception and spock.output_delay are now declared in milliseconds, so they accept values with units ('5s') and SHOW reports the unit. Their values do not change.
  • spock.restart_delay_default now 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_generator sequence (replaces inline oid-from-counter generation for subscription rows).
  • New: spock.reserved_object table, 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 support spock.cleanup_resolutions().
  • spock.resolutions.conflict_type values renamed during upgrade: update_update → update_exists, update_delete → update_missing, delete_delete → delete_missing. insert_exists is unchanged.
  • spock.subscription.sub_skip_schema is now correctly typed as text[] (the column was added as text in 5.0.2 but the C code always treated the bytes as text[]; 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 (backs spock.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 the failover flag 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 a tiebreaker patch); 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 returns false if any failed.
  • spock.node_info_emit() / spock.node_info_apply() / spock.node_info_broadcast() (trigger function, backing the new node_info_broadcast_trigger on spock.node) / spock.node_refresh_info_one() — internal plumbing behind node metadata propagation and refresh; not intended to be called directly (EXECUTE revoked from PUBLIC, 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, default 1024, range 16 to 1048576, POSTMASTER): how many recent events the spock.events view 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 by pg_monitor, since pg_replication_origin_status is 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() and spock.report_section(). get_system_info(), get_events(), get_apply_stats() and get_pending_exceptions() are executable by pg_monitor only, and reset_events() by superusers only.
  • spock.reset_subscription_stats(subid) also resets the activity counters behind spock.subscription_stats, on every supported PostgreSQL version, and only superusers can run it.
  • spock.get_apply_worker_status() is now a SQL function over spock.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() and spock.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 errno message such as Invalid argument. The error now gives the child’s exit code or signal. (5.0.13)
  • Table sync failed with function does not exist against an origin older than 5.0.7, which lacks spock.pause_apply_workers() and spock.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, with spock.exception_behaviour = transdiscard, its rows would land in spock.exception_log with error_message = unknown). The apply worker now PG_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_log when applying under transdiscard / sub_disable. The originally-failing row now carries the real error message; bystander rows in the same transaction are recorded as unavailable instead of unknown.
  • zodan: name slots and subscriptions consistently (sub_{provider}_{subscriber}) via the new spock.gen_sub_name() helper; remove_node drops subscriptions from the spock.subscription catalog 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 parameterise spock.sync_event() to avoid the Phase 9 handshake deadlock.
  • Prevent data loss on resync_table when the subscriber is read-only (SPOC-440).
  • Fix stale local_tuple pointer in the INSERT exception path for a missing relation; SUB_DISABLE now exits cleanly instead of dereferencing freed memory.
  • Suppress repeated hot_standby_feedback off ERROR 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_bytes int → uint64 overflow fix (b4ba9bdf)
  • A lost provider connection under SUB_DISABLE could 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 on SIGTERM.
  • An error between transactions left the apply worker in replay mode for the next transaction, which had never failed, so under TRANSDISCARD or SUB_DISABLE it could be discarded or disable the subscription.
  • Two subscriptions whose names share a prefix (such as sub and sub_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_dsn was 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.progress table and recreates it as a view,
  • replaces the spock.lag_tracker view definition,
  • migrates spock.resolutions.conflict_type values,
  • adds the new functions, the sub_id_generator sequence and the spock.reserved_object catalog,
  • drops spock.wait_for_apply_worker(),
  • replaces the C spock.get_apply_worker_status() with a SQL function over spock.get_worker_status(),
  • adds the node_info_broadcast_trigger trigger on spock.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_agg and spock.spock_gen_slot_name,
  • turns on the failover flag for existing logical slots by calling spock.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_lsn in place until the standby has received the WAL up to the intended position.
  • If spock.failover_slots_database is 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_database setting 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, so DROP DATABASE and ALTER DATABASE ... RENAME on it fail unless you use WITH (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_invalidated setting 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_database setting 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_names that does not exist was never reported when the other named slots already satisfied spock.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_names was counted twice, so with the default spock.standby_slots_min_confirmed of -1, 'sb1,sb1' needed two confirmations from one slot and held replication until wal_sender_timeout on every attempt. Repeated names are now ignored.

  • An apply worker could fail with unable to find an empty exception log slot while 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() and spock.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 after spock.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. spockctrl is no longer in the -dbgsym package.

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() and spock.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 errno message such as Invalid argument. The error now gives the child’s exit code or signal.

  • Sync failed with function does not exist against an origin older than 5.0.7, which lacks spock.pause_apply_workers() and spock.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_libraries parameter, and a library may no longer be used as an output plugin unless it is listed there. Its default excludes spock_output, so on a server carrying the fix logical decoding fails with library "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. Set output_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_timeout fired, 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 on spock.exception_behaviour the subscription was disabled or the transaction was written to spock.exception_log and 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 waits spock.restart_delay_default before starting again, so a problem that does not clear cannot turn into a tight restart loop.

  • Tables with GENERATED ALWAYS AS ... STORED columns 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 CLUSTER with 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. An add_node run 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 of pg_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’s restart_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_log and spock.exception_behaviour can 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 under TRANSDISCARD or SUB_DISABLE was 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 TRANSDISCARD and SUB_DISABLE every 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 with spock.sub_alter_skiplsn are exempt.

  • Two subscriptions whose names share a prefix (for example sub and sub_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_dsn the 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_messages said. 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_DISABLE that disabled the subscription for no real error. The marker is now cleared when the worker exits on SIGTERM.

  • 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_behaviour never 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 TYPE with 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 attoptions server patch for the heap_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/19 layer for the API changes in that beta (CLUSTER folded into REPACK, the recovery-conflict signalling changes, tuple-descriptor finalisation, and the flattened ReorderBufferTXN commit-time field). CREATE EXTENSION accepts 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_node and remove_node are 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_slots on a switchover. A sample Patroni on_role_change callback, samples/set_synchronized_standby_slots.sh, resets synchronized_standby_slots after a promotion. See Logical Slot Failover.

  • Documented the wait_if_disabled argument of spock.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 when sync_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-promotion synchronized_standby_slots runbook.

  • 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 via spock.failover_slots_feedback_naptime), both SIGHUP-settable in milliseconds

  • Never copy the pgedge_ace schema to a node joining via add_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 DISTINCT unique 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 relation error 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_log instead of the opaque placeholder unavailable. 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, so 5.0.10 sorted below 5.0.4 and 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_slots stalling 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 in spock.resolutions is unaffected.

Spock 5.0.8

Bug Fixes

  • Fix subscriber crash on transactions larger than 2 GB. apply_replay_bytes was declared as int, causing signed-integer overflow and a crash when a single replicated transaction exceeded 2 GB of WAL data. Changed to uint64.
  • 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-on error during exception handling per 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 FAILOVER flag, 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_slots background worker is no longer registered. The native PostgreSQL slotsync worker fully replaces it. See the Logical Slot Failover section in the configuration guide for required postgresql.conf settings.
  • On PostgreSQL 17, Spock’s worker remains active but automatically yields to the native slotsync worker if sync_replication_slots = on is set, preventing conflicts.

Bug Fixes

  • Preserve the original error message in spock.exception_log when applying in TRANSDISCARD or SUB_DISABLE mode. 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 with error_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_snapshot and adjust_progress_info could advance spock.progress past 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 in SpockContext for the duration of slot creation and resumed once adjust_progress_info completes.
  • Fix apply worker crash with epoll_ctl() failed: Invalid argument after a provider connection died. The socket fd captured before stream_replay: was never refreshed, so a stale fd was passed to WaitLatchOrSocket on re-entry. The fd is now refreshed at stream_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 of add_node) was generating subscription names as sub_{subscriber}_{provider} instead of the expected sub_{provider}_{subscriber} convention, causing remove_node to fail when looking up subscriptions by name. A new spock.gen_sub_name(provider_node, subscriber_node) helper is now used in place of inline name concatenations.
  • ZODAN: the remove_node cleanup loop tried to drop subscriptions by guessing names and nodes, which broke whenever cross_wire and add_node used different naming conventions. It now performs a per-node DROP of every subscription read directly from the spock.subscription catalog.
  • 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; revised upgrading_spock.md; fixed event-trigger syntax (EXECUTE FUNCTION instead of the deprecated EXECUTE PROCEDURE); standardized function-reference filenames to match function names exactly; removed obsolete batch_inserts.md
  • Test infrastructure aligned with main: run_tests.sh and SpockTest.pm now use absolute TESTLOGDIR paths, derive per-test log filenames, and isolate psql from a developer’s psqlrc/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_frequency GUC 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 every wal_sender_timeout / 2 seconds.
  • New spock.log_origin_change GUC to control logging of row origin changes to the PostgreSQL log. Origin changes caused by replication are no longer written to the spock.resolutions table, 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 publisher
    • since_sub_creation — Log origin changes for tuples modified after subscription creation (suppresses noise from pg_restored data)
  • New sub_created_at column on spock.subscription to 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.progress catalog 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_origin in spock.resolutions instead 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 in spock_conflict_row_to_json() that were overwriting the local_origin NULL flag.
  • Fix Zodan initialization issue: present_final_cluster_state now 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_node is 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.resolutions table, 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_behaviour setting (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() and spock.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 spockctrl command line utility and sample workflows simplify the management of a Spock multi-master replication setup for PostgreSQL. spockctrl provides a convenient interface for:
    • node management
    • replication set management
    • subscription management
    • ad-hoc SQL execution
    • workflow automation
  • Previously, replicated DELETE statements that attempted to delete a missing row were logged as exceptions. Since the purpose of a DELETE statement is to remove a row, we no longer log these as exceptions. Instead these are now logged in the Resolutions table.
  • INSERT conflicts resulting from a duplicate primary key or identity replica are now transformed into an UPDATE that updates all columns of the existing row, using Last-Write-Wins (LWW) logic. The transaction is then logged in the node’s Resolutions table, as either:
    • keep local if the local node’s INSERT has a later timestamp than the arriving INSERT
    • apply remote if the arriving INSERT from 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 COMMIT confirmation 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_indexes GUC is an experimental feature (disabled by default); use this feature at your own risk. If this GUC is enabled, 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 the spock.exception_log table.

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.

PG.CENTER edition

2.20 - pglogical to Spock function names

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.

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.4Spock 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.4Spock 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.4Spock 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.4Spock 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.4Spock 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.

PG.CENTER edition

3 - LOLOR

lolor is an extension that makes Postgres-style large objects compatible with logical Replication.

Upstream reference for LOLOR 1.3.0-dev. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of LOLOR with Mimus is unverified.

Source version

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.

Removal in the 1.3.0 development snapshot

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:

lolor.pg_largeobject
lolor.pg_largeobject_metadata
lolor.pg_largeobject_description

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.

CREATE EXTENSION lolor;
SELECT lolor.migrate_from_native();

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:

SELECT lolor.migrate_to_native();
DROP EXTENSION lolor;

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:

SELECT * FROM lolor.digest();         -- per-object checksum, compare 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:

SELECT * FROM lolor.check_orphans();  -- objects referring to a dropped role
SELECT lolor.fix_orphans('some_role');  -- reassign them and drop dead ACL entries

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:

  1. Stop creating and changing large objects on every node, and let replication drain. Then confirm the nodes agree:

    SELECT * FROM lolor.digest();   -- run on every node; the output must match
  2. Stop publishing the tables. With Spock, remove them from the replication set on every provider node that publishes them:

    SELECT spock.repset_remove_table('default', 'lolor.pg_largeobject');
    SELECT spock.repset_remove_table('default', 'lolor.pg_largeobject_metadata');
    SELECT spock.repset_remove_table('default', 'lolor.pg_largeobject_description');

    With native logical replication, drop them from the publication instead:

    ALTER PUBLICATION mypub DROP TABLE lolor.pg_largeobject, lolor.pg_largeobject_metadata,
        lolor.pg_largeobject_description;

    A publication created FOR TABLES IN SCHEMA lolor drops them with ALTER PUBLICATION mypub DROP TABLES IN SCHEMA lolor. A FOR ALL TABLES publication publishes them for as long as it exists: drop it, or recreate it with an explicit table list.

  3. 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:

    SELECT spock.sub_alter_sync('mysub');

    A native subscription is refreshed with:

    ALTER SUBSCRIPTION mysub REFRESH PUBLICATION;

    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.

  4. Migrate the data out on every node, connecting to each node directly; with spock the migration runs in repair mode and is not replicated:

    SELECT lolor.migrate_to_native();

    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.

  5. Drop the extension on each node, connecting to each node directly, with no other client session connected to the database:

    DROP EXTENSION lolor;

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, and REVOKE 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 as ALTER DATABASE ... RENAME: a renamed function keeps its OID, so a session that already resolved the lo_* functions keeps calling the previous implementation, and the row movement cannot be made atomic for other backends either. The calling session must reconnect after enable() or disable(). 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 the lo_* 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, run ALTER EXTENSION lolor UPDATE in 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 BY and REASSIGN OWNED BY do not see them: a role that owns them or appears in their ACL can be dropped without a warning, and REASSIGN OWNED / DROP OWNED leave them untouched. Before dropping a role, run REASSIGN OWNED BY or DROP OWNED BY in each database that has lolor, then DROP ROLE. For the role that owns the extension use REASSIGN OWNED BY: DROP OWNED BY would remove the extension too, and is refused while any object remains in lolor storage. Afterwards run lolor.check_orphans() in each such database and repair anything it reports with lolor.fix_orphans(new_owner); lolor.migrate_to_native() refuses while orphans exist.
  • Dropping lolor is refused while lolor.pg_largeobject, lolor.pg_largeobject_metadata or lolor.pg_largeobject_description is 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 and migrate_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 via lolor.node and checked against existing rows. To make that hazard an error rather than silent divergence, collect the other nodes’ OIDs with lolor.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, compare lolor.digest() across nodes to confirm they converged.

Continue reading


Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.

PG.CENTER edition

3.1 - Installing and Configuring lolor

lolor is supported on Postgres versions 16 and later.

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.

export PATH=/opt/pg16/bin:$PATH

# compile
make USE_PGXS=1
make USE_PGXS=1 install

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.

shared_preload_libraries = 'lolor'

Then connect to your Postgres database and create the extension with the command:

CREATE EXTENSION lolor;

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.

lolor.node = 1

You can also change the search_path to pick large object related tables from the lolor schema:

SET search_path=lolor,"$user",public,pg_catalog

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:

-- 'default' is Spock's built-in replication set; subscriptions consume it automatically.
SELECT spock.repset_add_table('default', 'lolor.pg_largeobject');
SELECT spock.repset_add_table('default', 'lolor.pg_largeobject_metadata');
SELECT spock.repset_add_table('default', 'lolor.pg_largeobject_description');

Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.

PG.CENTER edition

3.2 - lolor Release Notes

lolor Release Notes: LOLOR reference and usage.

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

Unreleased development version

These notes describe pinned main development. The latest stable tag checked on November 21, 2026 remains v1.2.3.

Removal in the 1.3.0 development snapshot

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 after CREATE 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_shdepend on the way back, so DROP ROLE, REASSIGN OWNED and DROP OWNED see the objects again. Comments are parked in lolor.pg_largeobject_description while an object is in lolor storage. Native objects are removed with the same bookkeeping as DROP (dependencies, comments and labels), but without the per-object locks DROP takes, so a database with more large objects than the lock table can hold is migrated without raising max_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 ShareRowExclusiveLock on both stores until commit. Ordinary large object access takes RowExclusiveLock, which does not conflict with itself, so a concurrent lo_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()) as peer_oids to turn a cross-node collision into a refusal, and compare lolor.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 with lo_unlink() and retry.
  • New helpers lolor.digest() and lolor.native_lo_oids() for cross-node checks after a node-local migration.
  • New helpers lolor.check_orphans() and lolor.fix_orphans(new_owner) for objects whose owner, grantee or grantor has been dropped. Objects in lolor storage cannot participate in pg_shdepend, so DROP ROLE does not notice them; check_orphans() lists them and which reference is dangling, and fix_orphans() reassigns dead owners, replacing them in the ACL as REASSIGN OWNED would 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 in pg_catalog for the whole database, which a non-superuser should not be able to do.
  • Fixed DROP ROLE failing with “unrecognized object class”. Creating a large object recorded a pg_shdepend row whose classId was the OID of lolor.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 because inv_drop() deleted with PERFORM_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 UPDATE must be run in every database that has lolor. Until it is, DROP ROLE anywhere in the cluster keeps reporting “owner of objects in database X”.
    • A database that ran DROP EXTENSION lolor on 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 with SELECT 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), then DELETE FROM pg_shdepend WHERE dbid = <that dbid> AND classid IN (<those OIDs>).
  • 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 with lolor must be loaded via "shared_preload_libraries"; the native pg_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 first lo_open(). Upgrade in this order: install the new library files, add lolor to shared_preload_libraries, restart, then run ALTER EXTENSION lolor UPDATE in 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 BY and 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: run lolor.migrate_to_native() first. The event trigger only puts the native pg_catalog.lo_* names back. The new superuser setting lolor.allow_unsafe_drop skips both checks and discards the contents of lolor storage. Because the drop renames the native functions back, it has the same requirements as lolor.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 TABLES or FOR 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 by DROP OWNED BY leaves 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() and lolor.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 lolor has the same requirements as lolor.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() and lolor.is_enabled() now probe exact function signatures in pg_catalog. They previously matched on proname across every schema, so any user with CREATE on any schema could define a function named lolor_lo_open and wedge lolor into a permanent “inconsistent state” that also blocked DROP 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 of pg_stat_activity and 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’s disable(), which still has the unqualified function lookups fixed in this release. Run ALTER EXTENSION lolor UPDATE first.
  • Fixed the lolor.node upper 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 have lolor.node = 16 configured, the server still starts but logs 16 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_shdepend restoration, 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 UPDATE for 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.

PG.CENTER edition

3.3 - Using lolor

The following command examples demonstrate 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:

-- Create a large object with no data and return the oid:
lolor_db=# SELECT lo_creat (-1);
 lo_creat 
----------
  1100433
(1 row)

-- Querying the lolor schema for related stats:
lolor_db=# SELECT * FROM lolor.pg_largeobject_metadata where oid = 1100433:
   oid   | lomowner | lomacl 
---------+----------+--------
 1100433 |       10 | 
(1 row)

-- Creating an empty large object with oid 200000:
lolor_db=# SELECT lo_create (200000);
 lo_create 
-----------
    200000
(1 row)

-- Get related stats
lolor_db=# SELECT * FROM lolor.pg_largeobject_metadata where oid = 200001:
  oid   | lomowner | lomacl 
--------+----------+--------
 200001 |       10 | 
(1 row)

-- Import an operating system file as a large object:
lolor_db=# SELECT lo_import ('/etc/os-release');
 lo_import
-----------
   1100449
(1 row)

-- Return information about the large object:
lolor_db=# SELECT * FROM
        lolor.pg_largeobject where loid = 1100449;
  loid   | pageno | data                                                                  
 1100449 |      0 | \x5052455454595f4e414d453d2244656269616e20474e552f4c696e75782031322028626f6f6b776f726d29220a4e414d453d2244656269616e20474e552f4c696e7578220a56455
253494f4e5f49443d223132220a56455253494f4e3d2231322028626f6f6b776f726d29220a56455253494f4e5f434f44454e414d453d626f6f6b776f726d0a49443d64656269616e0a484f4d455f55524c3d
2268747470733a2f2f7777772e64656269616e2e6f72672f220a535550504f52545f55524c3d2268747470733a2f2f7777772e64656269616e2e6f72672f737570706f7274220a4255475f5245504f52545f5
5524c3d2268747470733a2f2f627567732e64656269616e2e6f72672f220a
(1 row)

-- Unlink a large object:
lolor_db=# SELECT lo_unlink (1100449);
 lo_unlink 
-----------
         1
(1 row)

Upstream source · 1548836b0df0 · Copyright (c) 2024–2026, pgEdge, Inc. PostgreSQL License.

PG.CENTER edition

3.4 - Using pg_upgrade with lolor

The pgupgrade utility is used for upgrading Postgres versions.

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:

db1_17=# SELECT lolor.disable();

Next, execute the upgrade. A sample pg_upgrade command appears below:

# pg_upgrade --old-datadir=/data/db1_17 \
		--new-datadir=/data/db1_18 \
		--old-bindir=/usr/lib/postgresql/17/bin \
		--new-bindir=/usr/lib/postgresql/18/bin \
		--link

Then, use psql to enable lolor:

db1_18=# SELECT lolor.enable();

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.

PG.CENTER edition

4 - Snowflake

Using a Snowflake sequence allows you to take full advantage of the benefits offered by a distributed, multi-master replication solution.

Upstream reference for Snowflake 2.6.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of Snowflake with Mimus is unverified.

Source version

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.node GUC in the postgresql.conf file.

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


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.

PG.CENTER edition

4.1 - Changelog

All notable changes to the Snowflake extension are documented here.

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 now 2.5.0.

Fixed

  • Fixed dump/restore of snowflake-converted sequences. convert_sequence_to_snowflake() previously left MAXVALUE at (old last_value + 1), but snowflake.nextval() bypasses MAXVALUE and writes snowflake-sized values, so pg_dump could emit a setval() that failed to restore. Sequences are now converted with AS 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=True and shell-injection risks from test runner and helper subprocess calls; use shlex.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 ARG handling 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.

PG.CENTER edition

4.2 - Converting a PostgreSQL Sequence to a Snowflake Sequence

You cannot directly create a snowflake sequence; you must first create a sequence in Postgres and then convert it.

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:

    \ds

Another way is to query metadata catalog information directly in psql or another SQL editor.

    SELECT * FROM information_schema.sequences;

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:

acctg=# CREATE TABLE orders (customer VARCHAR, invoice VARCHAR, id bigserial PRIMARY KEY);
CREATE TABLE

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:

acctg=# INSERT INTO orders VALUES ('Chesterfield Schools', 'art_9338');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('Chesterfield Schools', 'math_9663');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('Albemarle Schools', 'sci_2009');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('King William Schools', 'sci_7399');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('King William Schools', 'art_9484');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('Hanover Schools', 'music_1849');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('Washington Schools', 'hist_2983');
INSERT 0 1

When we select the rows from our table, we can see the sequence numbers in the id column:

acctg=# SELECT * FROM orders;
       customer       |  invoice   | id 
----------------------+------------+----
 Chesterfield Schools | art_9338   |  1
 Chesterfield Schools | math_9663  |  2
 Albemarle Schools    | sci_2009   |  3
 King William Schools | sci_7399   |  4
 King William Schools | art_9484   |  5
 Hanover Schools      | music_1849 |  6
 Washington Schools   | hist_2983  |  7
(7 rows)

To convert the sequence definition for the orders table to use Snowflake sequences, invoke the following command in psql or another SQL editor:

SELECT snowflake.convert_sequence_to_snowflake('orders_id_seq'::regclass);

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:

acctg=# INSERT INTO orders VALUES ('Prince William Schools', 'math_8330');
INSERT 0 1
acctg=# INSERT INTO orders VALUES ('Fluvanna Schools', 'art_9447');
INSERT 0 1

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:

acctg=# SELECT id, snowflake.format(id), customer, invoice FROM orders;
         id         |                          format                           |        customer        |  invoice   
--------------------+-----------------------------------------------------------+------------------------+------------
                  1 | {"id": 1, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Chesterfield Schools   | art_9338
                  2 | {"id": 2, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Chesterfield Schools   | math_9663
                  3 | {"id": 3, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Albemarle Schools      | sci_2009
                  4 | {"id": 4, "ts": "2022-12-31 19:00:00-05", "count": 0}     | King William Schools   | sci_7399
                  5 | {"id": 5, "ts": "2022-12-31 19:00:00-05", "count": 0}     | King William Schools   | art_9484
                  6 | {"id": 6, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Hanover Schools        | music_1849
                  7 | {"id": 7, "ts": "2022-12-31 19:00:00-05", "count": 0}     | Washington Schools     | hist_2983
 135824181823537153 | {"id": 1, "ts": "2024-01-10 14:16:48.438-05", "count": 0} | Prince William Schools | math_8330
 135824609030176769 | {"id": 1, "ts": "2024-01-10 14:18:30.292-05", "count": 0} | Fluvanna Schools       | art_9447
(9 rows)

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.

PG.CENTER edition

4.3 - Creating a Snowflake Sequence in a New Cluster

Before you use Snowflake sequences, each node in your cluster must have a unique snowflake.node identifier.

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.node from the node ordinal.
  • pgEdge Helm charts derive snowflake.node from each node name.
  • pgEdge Ansible playbooks set snowflake.node from 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:

ALTER SYSTEM SET snowflake.node = 10;
SELECT pg_reload_conf();

You can also add the parameter to the postgresql.conf file directly. The following line identifies the host as node 11:

snowflake.node = 11

After you edit postgresql.conf, reload the server for the change to take effect. You can reload from psql:

SELECT pg_reload_conf();

You can also reload the server with pg_ctl:

pg_ctl reload -D "/path/to/your/data/directory"

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.

PG.CENTER edition

4.4 - Reviewing Sequence Definitions in your Table Meta-data

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:

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:

acctg=# \d+ orders;
                                                             Table "public.orders"
  Column  |       Type        | Collation | Nullable |              Default               | Storage  | Compression | Stats target | Description 
----------+-------------------+-----------+----------+------------------------------------+----------+-------------+--------------+-------------
 customer | character varying |           |          |                                    | extended |             |              | 
 invoice  | character varying |           |          |                                    | extended |             |              | 
 id       | bigint            |           | not null | nextval('orders_id_seq'::regclass) | plain    |             |              | 
Indexes:
    "orders_pkey" PRIMARY KEY, btree (id)
Access method: heap

After performing a conversion, the \d+ table_name command shows a Default value of snowflake.nextval('orders_id_seq'::regclass):

acctg=# \d+ orders
                                                                  Table "public.orders"
  Column  |       Type        | Collation | Nullable |                   Default                    | Storage  | Compression | Stats target | Descripti
on 
----------+-------------------+-----------+----------+----------------------------------------------+----------+-------------+--------------+----------
---
 customer | character varying |           |          |                                              | extended |             |              | 
 invoice  | character varying |           |          |                                              | extended |             |              | 
 id       | bigint            |           | not null | snowflake.nextval('orders_id_seq'::regclass) | plain    |             |              | 
Indexes:
    "orders_pkey" PRIMARY KEY, btree (id)
Access method: heap

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.

PG.CENTER edition

4.5 - Snowflake Functions

You can query the following Snowflake functions at the psql command line to return useful information about tables that use Snowflake sequences.

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:

acctg=# SELECT * FROM snowflake.nextval('orders_id_seq'::regclass);
      nextval       
--------------------
 136169504773242881
(1 row)

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:

acctg=# SELECT * FROM snowflake.currval('orders_id_seq'::regclass);
      currval       
--------------------
 136169504773242881
(1 row)

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:

acctg=# SELECT * FROM snowflake.get_epoch(136169504773242881);
   get_epoch    
----------------
 1704996539.845
(1 row)

You can use the to_timestamp(snowflake.get_epoch(<value>)) function to convert the epoch into a timestamp. For example:

acctg=# SELECT to_timestamp(snowflake.get_epoch(136169504773242881));
        to_timestamp        
----------------------------
 2024-01-11 13:08:59.845-05
(1 row)
Node and counter in the upstream transcript

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:

acctg=# SELECT snowflake.get_count(136169504773242881);
 get_count 
-----------
         3
(1 row)

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.

acctg=# SELECT * FROM snowflake.get_node(136169504773242881);
 get_node 
----------
        1
(1 row)

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:

acctg=# SELECT * FROM snowflake.format(136169504773242881);
                          format                           
-----------------------------------------------------------
 {"id": 1, "ts": "2024-01-11 13:08:59.845-05", "count": 0}
(1 row)

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.

PG.CENTER edition

5 - SafeSession

pgEdge SafeSession is a PostgreSQL extension that enforces read-only sessions for specified database roles.

Upstream reference for SafeSession 1.1. Mimus 19.0.1 integrates Spock 5.0.15. Compatibility of SafeSession with Mimus is unverified.

Source version

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

make
make install

Configure PostgreSQL

Add the extension to shared_preload_libraries in postgresql.conf:

shared_preload_libraries = 'pgedge_safesession'

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:

CREATE EXTENSION pgedge_safesession;

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.

ALTER SYSTEM SET pgedge_safesession.roles =
    'readonly_user, reporting_role';
SELECT pg_reload_conf();

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 ANALYZE forms
  • 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. A DO block or CALL in 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 a CALL argument, or passed as an EXECUTE parameter (including through EXPLAIN EXECUTE and CREATE TABLE AS ... EXECUTE). A function reached only indirectly, through a view body, a row-level security policy’s USING/WITH CHECK qual, or a domain CHECK constraint, 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’s RETURNS type.
  • 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_only or default_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_only or default_transaction_read_only to 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() and clock_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 AUTHORIZATION to 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_libraries is required, and the roles are normally set in postgresql.conf or with ALTER SYSTEM). Setting it only for a single session with SET would be undone by that session’s DISCARD ALL or RESET 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

-- As superuser: configure restrictions
ALTER SYSTEM SET pgedge_safesession.roles =
    'reporting_user';
SELECT pg_reload_conf();

-- Connect as reporting_user
-- Reads work normally:
SELECT * FROM sales;          -- OK
SELECT count(*) FROM sales;   -- OK
EXPLAIN SELECT * FROM sales;  -- OK
COPY sales TO '/tmp/out.csv'; -- OK

-- Writes are blocked:
INSERT INTO sales VALUES (1); -- ERROR
CREATE TABLE tmp (id int);    -- ERROR
COPY sales FROM '/tmp/in.csv'; -- ERROR

Licence

See the Licence page for details.

Continue reading


Upstream source · d66225fcceef · Copyright (c) 2025–2026, pgEdge, Inc. PostgreSQL License.

PG.CENTER edition

5.1 - Changelog

All notable changes to the pgEdge SafeSession will be documented in this file.

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 roles

  • ExecutorStart 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 = on for restricted sessions

  • SECURITY 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 = on to 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.

PG.CENTER edition

5.2 - LICENCE()

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.

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.

PG.CENTER edition

6 - About this site

Sources, licensing, versions, and maintenance.

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.

PG.CENTER edition · Upstream source

6.1 - Sources and attribution

Pinned sources, copyright notices, adaptations, and translation 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.

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.

ExtensionEnglish sourceChannel
spockd05e2e2b6a82v6.0.0-beta.2; pre-release
Spock 5.0 maintenance supplemente710faa6fe21v5.0.15-rc.2 release notes and configuration changes
lolor1548836b0df01.3.0 development; latest stable v1.2.3
safesessiond66225fcceefv1.1
snowflake9506e1bd5c1fv2.6.1

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.

PG.CENTER edition

6.2 - License texts

Verbatim upstream license and copyright notices.

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

LICENSE.md

The PostgreSQL License

Copyright (c) 2021 - 2026, pgEdge, Inc.

Portions Copyright (c) 1996-2019, The PostgreSQL Global Development Group

Portions Copyright (c) 1994, The Regents of the University of California

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.

COPYRIGHT

Copyright (c) 2021-2026, pgEdge, Inc.
Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California

lolor

LICENSE.md

The PostgreSQL License

Copyright (c) 2024 - 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.

safesession

LICENCE.md

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.

snowflake

LICENSE.md

The PostgreSQL License

Copyright (c) 2023 - 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.

COPYRIGHT

Snowflake ID Implementation for PostgreSQL

Copyright (c) 2021-2026, pgEdge, Inc.
Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California

PG.CENTER edition · Upstream source

6.3 - Maintenance and coverage

Reading features, translation coverage, and validation scope.

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 in postgresql.conf. Authentication rules belong in the instance’s actual pg_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.

PG.CENTER edition · Upstream source