diff --git a/.gitignore b/.gitignore index b792ef5ad..1f98aec2a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ results regression_output tmp_check -spock_create_subscriber +/utils/spock_create_subscriber/spock_create_subscriber +/utils/spock_create_subscriber/.deps/ +/utils/spock_create_subscriber/spock_fe.c .vimrc *.o *.so diff --git a/Makefile b/Makefile index 3fd256ccc..43e019bf1 100644 --- a/Makefile +++ b/Makefile @@ -9,6 +9,7 @@ EXTENSION = spock PGFILEDESC = "spock - multi-master replication" MODULES = spock_output +SUBDIRS = utils/spock_create_subscriber # Lookup source directory vpath % src src/compat/$(PGVER) diff --git a/docs/creating_subscriber_nodes.md b/docs/creating_subscriber_nodes.md new file mode 100644 index 000000000..164744f6a --- /dev/null +++ b/docs/creating_subscriber_nodes.md @@ -0,0 +1,141 @@ +## Creating a Subscriber Node with pg_basebackup + +Spock supports creating a subscriber node by cloning the provider with [`pg_basebackup`](https://www.postgresql.org/docs/current/app-pgbasebackup.html) and starting it as a Spock subscriber. Use the `spock_create_subscriber` utility (located in the `bin` directory of your pgEdge platform installation) to register the node. + +### Synopsis: + + `spock_create_subscriber [OPTION]...` + +**Options** + +Specify the following options as needed. + +| Option | Description +|----------|------------- +| `-D`, `--pgdata=DIRECTORY` | The `data` directory to be used for new node. This can be either an empty/non-existing directory, or a directory populated using the `pg_basebackup -X stream` command. A directory in which a PostgreSQL server is running, such as a standby of the source, is refused and left running. +| `--databases` | An optional list of databases to replicate. +| `-n`, `--subscriber-name=NAME` | The name of the newly created subscriber. +| `--subscriber-dsn=CONNSTR` | A connection string to the newly created subscriber. +| `--provider-dsn=CONNSTR` | A connection string to the provider. +| `--replication-sets=SETS` | A comma-separated list of replication set names. +| `--apply-delay=DELAY` | The apply delay in seconds (by default 0). +| `--drop-slot-if-exists` | Drop replication slot of conflicting name. +| `-s`, `--stop` | Stop the server once the initialization is done. +| `-v` | Increase logging verbosity. +| `--extra-basebackup-args` | Additional arguments to pass to `pg_basebackup`. Safe options are: `-T`, `-c`, `--xlogdir`/`--waldir` +| `--text-types` | Transfer all column values as text rather than binary during initial sync. Use this when provider and subscriber differ in endianness or type representation. + +**Configuration files overrides** + +You can use the following options to override the location of the configuration files. + +| Option | Description +|----------|------------- +|`--hba-conf` | path to the new `pg_hba.conf` +| `--postgresql-conf` | path to the new `postgresql.conf` +| `--postgresql-auto-conf` | settings to override in `postgresql.auto.conf` +| `--recovery-conf` | path to the template recovery configuration + +Unlike `spock.sub_create`'s other data sync options, this method of cloning ignores replication sets and copies all tables on all databases. However, it's often much faster, especially over high-bandwidth connections. + +**New node configuration** + +After the configuration overrides are applied, the utility checks the new node's configuration and stops if `wal_level` is not `logical` or `shared_preload_libraries` does not include `spock`. With `--bidirectional`, `track_commit_timestamp` must also be `on`. + +### Joining a multi-master cluster + +With `--bidirectional`, the utility joins the new node to an existing multi-master cluster: the new node subscribes to every existing node, and every existing node subscribes to it. The provider named by `--provider-dsn` is the source node; the other nodes are discovered from its subscriptions. The replication sets are taken from the source's subscriptions, so `--replication-sets`, `--apply-delay` and `--text-types` cannot be combined with `--bidirectional`. + +| Option | Description +|----------|------------- +| `--bidirectional` | Join an existing multi-master cluster. +| `--stall-timeout=SECS` | Once PostgreSQL accepts connections, the number of seconds without replay progress before giving up (default 1800). A single large transaction is sent only at commit, so while the provider decodes it the join shows no progress; raise this value when the source has bulk writers. It does not bound PostgreSQL's own startup. Use `--max-wait` for a hard ceiling. +| `--max-wait=SECS` | A hard ceiling, in seconds, on the catchup wait after the connection is made (default: unbounded). It does not bound PostgreSQL's own startup. The utility's connections use TCP keepalives, so a peer that disappears from the network while a check is in flight ends the run with a connection error within about a minute. That does not apply to a connection over a Unix-domain socket, nor to a server that is still reachable but has stopped answering; the ceiling is checked between checks, not inside one. It also bounds the creation of the replication slots on the source and the peers, which waits for the write transactions that were running when it started; the wait ends with a message that says so. +| `--cleanup` | Remove the partial state of a failed or interrupted join and exit. Stops PostgreSQL if it is running in `--pgdata`, and keeps the data directory: remove it yourself afterwards. It refuses a manifest that records a completed join; see below. +| `--skip-disk-space-check` | Before the base backup, the utility compares the free space in the `--pgdata` filesystem with an estimate of the copy: the total size of the source's databases plus 10% for the WAL streamed during the copy. This is an early warning, not an exact figure: it assumes an uncompressed copy that lands entirely on the `--pgdata` filesystem. If the check fails, free up space or choose another `--pgdata`; when the backup or the filesystem compresses it, or tablespaces are copied to other filesystems, check the space yourself and use this option to proceed. If the check cannot be made, the utility says so and goes on. | + +`--subscriber-dsn` must be an address the existing nodes can use to connect back to the new node. The join requires: + +- Spock 6.0.0 or later on every node. +- `track_commit_timestamp = on` on the source and on every peer. +- Every node in the cluster subscribed to every other node, with all those subscriptions replicating. +- Every change committed on the source when the check starts has been confirmed by each of the source's existing outbound Spock slots. The utility waits for them to catch up, and stops if no outbound slot makes progress for 30 seconds. +- Room for the join on the existing nodes: on the source, a free replication slot for the logical slot and one for the base backup (none for the backup with `--no-slot` in `--extra-basebackup-args`) and two free WAL senders; on each peer, one free slot and one free WAL sender. `wal_level = logical` on all of them. +- A new-node configuration that fits: the new node gets one replication slot and one WAL sender for the source and each peer, so `max_replication_slots` and `max_wal_senders` must be at least the number of existing nodes. The utility reads both from the source and from `--postgresql-conf` and `--postgresql-auto-conf`. The port of `--subscriber-dsn` must be the port the new node will listen on, which is the source's unless an override file sets `port`. A value the source took from its own command line or environment is not inherited, so the new node uses the built-in default for it. The utility reads these files line by line and does not follow `include`, `include_dir` or `include_if_exists`: a setting made in an included file is not seen, and the check uses the source's value or the default instead. Set `max_replication_slots`, `max_wal_senders` and `port` directly in the file you pass if the check is to see them. +- No server listening at `--subscriber-dsn`, no slot of the join's name on the source (unless `--drop-slot-if-exists`), and no leftover subscription, slot or node entry of the new node's name from an earlier attempt on the source or a peer. +- Exactly one Spock database on the source. To check this, the utility connects to every non-template database of the source with the same credentials as for the join, so that account must be allowed to connect to each of them. A database it cannot check stops the join. +- The same replication sets, with the same tables, row filters and table schemas, on the source and on each peer. Replication set names must not contain commas. + +Whatever `spock.exception_behaviour` the cluster uses, the new node runs with `sub_disable` from the moment Spock starts on it until the forwarding through the source has been cleared, and then returns to its configured value. Until then it applies exactly what the source committed, on a copy of the source, so a failed apply means the new node is not a faithful copy; under `discard` or `transdiscard` the failed transaction would be dropped and the join would still report success. Any apply failure in that stretch is a hard join failure: run `--cleanup`, fix the cause and retry. The configured value is recorded in the manifest before it is changed. If the utility dies after the override and before the restore, `--cleanup` puts the recorded value back on the node, whose data directory it keeps. + +Until the join completes, keep the new node unreachable by other clients, for example with a private address or a restrictive `pg_hba.conf` set through `--hba-conf` or `--postgresql-conf`; the utility does not do this. + +With or without `--bidirectional`, the source instance must have no enabled native (non-spock) logical subscriptions: the backup would copy them, and on the new node they would compete with the source for their upstream slots. The utility stops if it finds one. Transactions that were prepared on the source when the restore point was taken are rolled back on the new node, in the database it is joining; they reach the new node by replication when the source commits them. + +The utility records the objects it creates on the other nodes in `spock_bidirectional_manifest.json` in `--pgdata`, and in `.spock_bidir_pending.json` until the base backup is complete. If a join fails or is interrupted, run the utility with `--bidirectional --cleanup --pgdata=DIRECTORY` to remove the subscriptions and replication slots it created. `--cleanup` removes only what the join created on the nodes and the records in `--pgdata`. It never removes the data directory, or the tablespace and `--waldir` directories the base backup placed outside it: remove them yourself once it has finished, and before you run the join again in the same place. A manifest that records a completed join belongs to a live cluster member: `--cleanup` refuses it, and leaves the node, its data directory and the other nodes' subscriptions and slots untouched. To remove such a node, drop its subscriptions with `spock.sub_drop()`, drop the reverse subscriptions on the other nodes the same way, drop the node with `spock.node_drop()`, then stop it and remove its data directory. If you are sure the manifest is stale, delete it and run `--cleanup` again. `--cleanup` refuses a manifest that belongs to another node when `--subscriber-name` names a different one. A join does not start in a `--pgdata` that already holds a manifest, or next to a pending record from an earlier attempt: the utility stops and names the file and the node. If the file is the record of an interrupted join into that directory, run `--cleanup` first. If it was copied from another node's data directory, for example in a backup you took yourself, delete it once you are sure, and run the join again. A manifest that a base backup taken by the utility itself brings along from the source is removed automatically. + +### Required privileges and access + +The utility connects with the role named in each connection string and runs superuser-only operations with it, so each of these roles must be a superuser: + +| Connection string | What the utility does with the role | +|-------------------|-------------------------------------| +| `--provider-dsn` (the source) | Creates the logical replication slot and the restore point; reads `pg_replication_slots` and `pg_replication_origin_status`; runs Spock functions. `pg_basebackup` uses the same role over a replication connection. | +| `--subscriber-dsn` (the new node) | Changes the node's configuration with `ALTER SYSTEM`; drops the Spock catalog it inherited in the backup, and the replication origins; creates the node and its subscriptions. | +| The address of each peer, as recorded in the source's `spock.node_interface` (with `--bidirectional`) | Creates a replication slot and sync events on the peer, and the peer's reverse subscription. | + +With `--bidirectional`, the utility checks that the role is a superuser on the source and on every peer before it creates anything there, and stops with a message that names the role and the node. A replication-only role fails that check. + +The base backup needs a `replication` entry in the source's `pg_hba.conf` that lets the role connect from the new node. For the join, every existing node must be able to connect to `--subscriber-dsn`, and the new node must be able to connect to every existing node; set `--hba-conf` for the new node accordingly. + +The utility creates these objects, and `--cleanup` removes the ones a failed join leaves behind: + +- On the source: a logical replication slot (named by `spock.spock_gen_slot_name()`), and with `--bidirectional` the source's reverse subscription to the new node and sync events. +- On each peer, with `--bidirectional`: a replication slot for the new node's direct subscription, sync events, and the peer's reverse subscription to the new node. +- On the new node: the Spock node, and its subscriptions to the source and to each peer. + +### What the join does not guard against + +The utility checks the cluster at the start of the join and verifies the dataflow at the end. It does not watch the cluster in between, so keep these three points in mind: + +- **Membership changes.** The utility reads the list of the cluster's nodes once, before the base backup. It does not detect a node that another join or an administrator adds or removes while the join runs, and the new node can end up without a subscription to a node that was added meanwhile. Run joins one at a time, and do not add or remove nodes while one runs. If it happened anyway, compare `spock.sub_show_status()` on the new node with the list of nodes, create the missing subscription, or run `--cleanup` and start the join again. +- **A peer's slot invalidated or dropped during the join.** The utility creates one replication slot on each peer for the new node's direct subscription. If the slot is dropped, or invalidated because it fell more than the peer's `max_slot_wal_keep_size` behind, the subscription never streams. The join does not notice this when it enables the subscription. It fails at the final verification, because a marker written on that peer does not reach the new node, and reports a stalled wait. Run `--cleanup` to remove what the join created, fix the peer, and start again. Keep `max_slot_wal_keep_size` on the peers large enough for the whole join. +- **The forwarding clear.** After the catchup, the utility stops the source from forwarding the peers' changes and waits until the source accepts a new connection for the catchup subscription. If the source cannot report the previous connection, the utility accepts the first connection it sees. The window is narrow. If a join is interrupted around this step, run `--cleanup` and start it again from scratch. + +### Examples + +Convert a physical copy of a provider into a logical subscriber. The utility takes the base backup itself, so `--pgdata` is a new or empty directory: + +```bash +spock_create_subscriber \ + --pgdata=/var/lib/postgresql/data_n2 \ + --subscriber-name=n2 \ + --subscriber-dsn="host=n2.example.com port=5432 dbname=app user=spock_admin" \ + --provider-dsn="host=n1.example.com port=5432 dbname=app user=spock_admin" \ + --postgresql-conf=/etc/postgresql/n2/postgresql.conf \ + --hba-conf=/etc/postgresql/n2/pg_hba.conf +``` + +Join a new node to an existing multi-master cluster through `n1`. The other nodes are discovered from `n1`: + +```bash +spock_create_subscriber --bidirectional \ + --pgdata=/var/lib/postgresql/data_n3 \ + --subscriber-name=n3 \ + --subscriber-dsn="host=n3.example.com port=5432 dbname=app user=spock_admin" \ + --provider-dsn="host=n1.example.com port=5432 dbname=app user=spock_admin" \ + --postgresql-conf=/etc/postgresql/n3/postgresql.conf \ + --hba-conf=/etc/postgresql/n3/pg_hba.conf \ + --stall-timeout=1800 +``` + +Remove what a failed or interrupted join left behind. The utility keeps the data directory, so remove it yourself afterwards: + +```bash +spock_create_subscriber --bidirectional --cleanup \ + --pgdata=/var/lib/postgresql/data_n3 + +rm -rf /var/lib/postgresql/data_n3 +``` + +The existing nodes use `--subscriber-dsn` to connect back to the new node, so it must work from their hosts: include the password in the string, or provide it through a password file on those hosts. For the utility's own connections, a password file or the `PGPASSWORD` environment variable also works. diff --git a/docs/modify/index.md b/docs/modify/index.md index d04d53cb5..6ecfe6879 100644 --- a/docs/modify/index.md +++ b/docs/modify/index.md @@ -10,3 +10,7 @@ There are several tools and scripts you can use to add a node to a cluster; the [pgBackRest](add_node_pgbackrest.md) is an open-source tool that you can use to add a node to a replicating cluster with minimal interruption. +* **Use spock_create_subscriber to Clone a Provider or Join a Multi-Master Cluster** + +[`spock_create_subscriber`](../creating_subscriber_nodes.md) clones a node with `pg_basebackup` and starts the copy as a Spock subscriber; with `--bidirectional` it joins the new node to an existing multi-master cluster, subscribing it to every existing node and every existing node to it. + diff --git a/include/spock_injection.h b/include/spock_injection.h index 405841dfb..6a78d0bd6 100644 --- a/include/spock_injection.h +++ b/include/spock_injection.h @@ -3,7 +3,7 @@ * spock_injection.h * Injection point support for the Spock extension. * - * Two named injection points are defined, one per side of the wire: + * Four named injection points are defined: * * SPOCK_WORKER_DELAY() – subscriber side, at apply-worker * start/finish sites ('spock-worker-delay'). @@ -26,6 +26,18 @@ * insertion exists to survive, and the one * a concurrent local writer produces for * real. + * SPOCK_FORWARDED_APPLY_ERROR() – subscriber side, right before a + * forwarded-origin row change is applied + * to the heap ('spock-forwarded-apply- + * error'). Lets a test attach an + * 'error'-mode injection point (core's + * injection_points extension) to force + * an error-class exception on a + * forwarded transaction, e.g. during a + * bidirectional-join catchup, to verify + * the transaction aborts rather than + * silently committing with a missing + * row. * * SPOCK_RANDOM_DELAYS defined – the worker and output-plugin points call * spock_random_delay() directly; fires @@ -35,7 +47,10 @@ * a worker or transaction boundary, and a * sleep averaging 50 ms on every applied * row puts the regression suite hours past - * any sensible timeout. + * any sensible timeout. The same goes for + * SPOCK_FORWARDED_APPLY_ERROR(), which is + * also a no-op: a random sleep does not + * serve an error-injection point. * USE_INJECTION_POINTS defined – all expand to INJECTION_POINT(); the * core injection_points module can * attach to any name when needed. @@ -83,6 +98,7 @@ extern void spock_random_delay(void); /* Per-row: delaying here would take the suite hours. See above. */ #define SPOCK_INSERT_CONFLICT_STALL() ((void) 0) #define SPOCK_APPLY_UPDATE_STALL() ((void) 0) +#define SPOCK_FORWARDED_APPLY_ERROR() ((void) 0) #elif defined(USE_INJECTION_POINTS) @@ -94,12 +110,14 @@ extern void spock_random_delay(void); #define SPOCK_INSERT_CONFLICT_STALL() \ INJECTION_POINT("spock-insert-conflict-stall", NULL) #define SPOCK_APPLY_UPDATE_STALL() INJECTION_POINT("spock-apply-update-stall", NULL) +#define SPOCK_FORWARDED_APPLY_ERROR() INJECTION_POINT("spock-forwarded-apply-error", NULL) #else #define SPOCK_WORKER_DELAY() INJECTION_POINT("spock-worker-delay") #define SPOCK_OUTPUT_TXN_STALL() INJECTION_POINT("spock-output-txn-stall") #define SPOCK_INSERT_CONFLICT_STALL() \ INJECTION_POINT("spock-insert-conflict-stall") #define SPOCK_APPLY_UPDATE_STALL() INJECTION_POINT("spock-apply-update-stall") +#define SPOCK_FORWARDED_APPLY_ERROR() INJECTION_POINT("spock-forwarded-apply-error") #endif #else @@ -108,6 +126,7 @@ extern void spock_random_delay(void); #define SPOCK_OUTPUT_TXN_STALL() ((void) 0) #define SPOCK_INSERT_CONFLICT_STALL() ((void) 0) #define SPOCK_APPLY_UPDATE_STALL() ((void) 0) +#define SPOCK_FORWARDED_APPLY_ERROR() ((void) 0) #endif /* SPOCK_RANDOM_DELAYS / USE_INJECTION_POINTS */ diff --git a/mkdocs.yml b/mkdocs.yml index 57baa66b1..d98588cd3 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -77,6 +77,7 @@ nav: - Updating the Postgres Version with a Rolling Update: modify/zodan/zodan_rolling_pg_version_tutorial.md - Upgrading the Postgres Version In Place with pg_upgrade: modify/pg_upgrade_rolling_tutorial.md - Adding a Node with Minimal Downtime with pgBackRest: modify/add_node_pgbackrest.md + - Creating a Subscriber Node with spock_create_subscriber: creating_subscriber_nodes.md - Recovering from Catastrophic Node Failure: recovery/catastrophic_node_failure.md - Monitoring a Cluster: - Monitoring the Configuration and Health of a Cluster: monitoring/index.md diff --git a/src/spock_apply_heap.c b/src/spock_apply_heap.c index 4052d31ae..38037e439 100644 --- a/src/spock_apply_heap.c +++ b/src/spock_apply_heap.c @@ -84,6 +84,7 @@ #include "spock_apply_heap.h" #include "spock_apply.h" #include "spock_exception_handler.h" +#include "spock_injection.h" #include "spock.h" typedef struct ApplyExecutionData @@ -111,6 +112,23 @@ static void build_delta_tuple(SpockRelation *rel, SpockTupleData *oldtup, #endif static bool physatt_in_attmap(SpockRelation *rel, int attid); +/* + * Is the row currently being applied part of a transaction whose origin is + * not this apply worker's direct provider -- i.e. a forwarded-origin + * change (cascade or bidirectional-join forwarding)? + * + * replorigin_session_origin mirrors handle_origin()'s remote_origin_id for + * the duration of the transaction (spock_apply.c), so this is the same + * first-order test handle_origin() itself uses, without needing any of + * spock_apply.c's file-static transaction state visible here. + */ +static inline bool +is_forwarded_origin_apply(void) +{ + return replorigin_session_origin != InvalidRepOriginId && + replorigin_session_origin != (RepOriginId) MySubscription->origin->id; +} + /* * Executor state preparation for evaluation of constraint expressions, * indexes and triggers for the specified relation. @@ -1239,6 +1257,9 @@ spock_apply_heap_insert(SpockRelation *rel, SpockTupleData *newtup) slot_fill_defaults(rel, estate, remoteslot); MemoryContextSwitchTo(oldctx); + if (is_forwarded_origin_apply()) + SPOCK_FORWARDED_APPLY_ERROR(); + EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL); /* @@ -1463,6 +1484,9 @@ spock_apply_heap_update(SpockRelation *rel, SpockTupleData *oldtup, MemoryContextSwitchTo(oldctx); + if (is_forwarded_origin_apply()) + SPOCK_FORWARDED_APPLY_ERROR(); + /* Find the current local tuple */ EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL); ExecOpenIndices(edata->targetRelInfo, false); @@ -1586,6 +1610,9 @@ spock_apply_heap_delete(SpockRelation *rel, SpockTupleData *oldtup) MemoryContextSwitchTo(oldctx); + if (is_forwarded_origin_apply()) + SPOCK_FORWARDED_APPLY_ERROR(); + /* Find the current local tuple */ EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL); ExecOpenIndices(edata->targetRelInfo, false); diff --git a/src/spock_fe.c b/src/spock_fe.c index ebe62a825..7635914c3 100644 --- a/src/spock_fe.c +++ b/src/spock_fe.c @@ -41,7 +41,7 @@ int find_other_exec_version(const char *argv0, const char *target, uint32 *version, char *retpath) { - char cmd[MAXPGPATH]; + char cmd[4 * MAXPGPATH + 32]; /* retpath, every quote escaped */ char cmd_output[1024]; FILE *output; int pre_dot = 0, @@ -59,7 +59,31 @@ find_other_exec_version(const char *argv0, const char *target, "/%s%s", target, EXE); /* And request the version from the program */ +#ifndef WIN32 + { + /* quote retpath as one shell word, whatever characters it holds */ + size_t n = 0; + const char *q; + + cmd[n++] = '\''; + for (q = retpath; *q && n < sizeof(cmd) - 16; q++) + { + if (*q == '\'') + { + cmd[n++] = '\''; + cmd[n++] = '\\'; + cmd[n++] = '\''; + cmd[n++] = '\''; + } + else + cmd[n++] = *q; + } + cmd[n] = '\0'; + strlcat(cmd, "' --version", sizeof(cmd)); + } +#else snprintf(cmd, sizeof(cmd), "\"%s\" --version", retpath); +#endif if ((output = popen(cmd, "r")) == NULL) { @@ -226,10 +250,12 @@ appendPQExpBufferConnstrValue(PQExpBuffer buf, const char *str) bool needquotes; /* - * If the string consists entirely of plain ASCII characters, no need to - * quote it. This is quite conservative, but better safe than sorry. + * If the string is one or more plain ASCII characters, no need to quote + * it. An empty string must default to needing quotes -- an unquoted + * empty value doesn't parse as empty, it swallows the entire next + * "keyword=value" token. */ - needquotes = false; + needquotes = true; for (s = str; *s; s++) { if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || @@ -238,6 +264,7 @@ appendPQExpBufferConnstrValue(PQExpBuffer buf, const char *str) needquotes = true; break; } + needquotes = false; } if (needquotes) diff --git a/tests/docker/Dockerfile-step-1.el9 b/tests/docker/Dockerfile-step-1.el9 index f207fb926..feff1cbe8 100644 --- a/tests/docker/Dockerfile-step-1.el9 +++ b/tests/docker/Dockerfile-step-1.el9 @@ -61,7 +61,9 @@ ARG PG_REF= ARG SPOCK_RANDOM_DELAYS= # When set to any non-empty value, PostgreSQL is configured with # --enable-injection-points, so spock_injection.h's USE_INJECTION_POINTS -# branch is compiled. Must be combined with an empty SPOCK_RANDOM_DELAYS. +# branch is compiled, and the injection_points test module (PostgreSQL 17 and +# later) is installed, which the TAP tests that attach injection points load. +# Must be combined with an empty SPOCK_RANDOM_DELAYS. ARG ENABLE_INJECTION_POINTS= # Export as environment variables for build-time and runtime @@ -214,6 +216,10 @@ RUN set -eux && \ echo "========================================" && \ make install > /dev/null && \ make -C contrib install > /dev/null && \ + if [ -n "${ENABLE_INJECTION_POINTS}" ] && \ + [ -d src/test/modules/injection_points ]; then \ + make -C src/test/modules/injection_points install > /dev/null; \ + fi && \ echo "PostgreSQL installation complete" # ============================================================================== diff --git a/tests/regress/expected/conflict_stat.out b/tests/regress/expected/conflict_stat.out index b46c8b26b..654bf5860 100644 --- a/tests/regress/expected/conflict_stat.out +++ b/tests/regress/expected/conflict_stat.out @@ -310,6 +310,45 @@ SELECT spock.reset_subscription_stats(:test_sub_id); (1 row) TRUNCATE spock.exception_log; +-- ============================================================ +-- Test spock.get_subscription_stats() against a disabled subscription +-- whose apply worker has never run (PG18 stats hooks guard, read side). +-- The pgstat entry is created at CREATE SUBSCRIPTION time regardless of +-- "enabled", so this must return a well-defined all-zero row, not crash. +-- ============================================================ +BEGIN; +SELECT 1 FROM spock.sub_create( + subscription_name := 'test_subscription_disabled', + provider_dsn := (SELECT provider_dsn FROM spock_regress_variables()) || ' user=super', + replication_sets := '{}', + synchronize_structure := false, + synchronize_data := false, + forward_origins := '{}', + enabled := false); + ?column? +---------- + 1 +(1 row) + +COMMIT; +SELECT sub_id AS disabled_sub_id FROM spock.subscription + WHERE sub_name = 'test_subscription_disabled' \gset +SELECT confl_update_missing, + confl_insert_exists,confl_update_origin_differs,confl_update_exists, + confl_delete_origin_differs,confl_delete_missing,confl_delete_exists, + stats_reset +FROM spock.get_subscription_stats(:disabled_sub_id); + confl_update_missing | confl_insert_exists | confl_update_origin_differs | confl_update_exists | confl_delete_origin_differs | confl_delete_missing | confl_delete_exists | stats_reset +----------------------+---------------------+-----------------------------+---------------------+-----------------------------+----------------------+---------------------+------------- + 0 | 0 | 0 | 0 | 0 | 0 | 0 | +(1 row) + +SELECT spock.sub_drop('test_subscription_disabled'); + sub_drop +---------- + 1 +(1 row) + -- Cleanup \c :provider_dsn SELECT spock.replicate_ddl($$ DROP TABLE public.conflict_ue_test CASCADE; $$); diff --git a/tests/regress/sql/conflict_stat.sql b/tests/regress/sql/conflict_stat.sql index 8f8959a78..7988ac4fa 100644 --- a/tests/regress/sql/conflict_stat.sql +++ b/tests/regress/sql/conflict_stat.sql @@ -203,6 +203,35 @@ FROM spock.get_subscription_stats(:test_sub_id); SELECT spock.reset_subscription_stats(:test_sub_id); TRUNCATE spock.exception_log; +-- ============================================================ +-- Test spock.get_subscription_stats() against a disabled subscription +-- whose apply worker has never run (PG18 stats hooks guard, read side). +-- The pgstat entry is created at CREATE SUBSCRIPTION time regardless of +-- "enabled", so this must return a well-defined all-zero row, not crash. +-- ============================================================ + +BEGIN; +SELECT 1 FROM spock.sub_create( + subscription_name := 'test_subscription_disabled', + provider_dsn := (SELECT provider_dsn FROM spock_regress_variables()) || ' user=super', + replication_sets := '{}', + synchronize_structure := false, + synchronize_data := false, + forward_origins := '{}', + enabled := false); +COMMIT; + +SELECT sub_id AS disabled_sub_id FROM spock.subscription + WHERE sub_name = 'test_subscription_disabled' \gset + +SELECT confl_update_missing, + confl_insert_exists,confl_update_origin_differs,confl_update_exists, + confl_delete_origin_differs,confl_delete_missing,confl_delete_exists, + stats_reset +FROM spock.get_subscription_stats(:disabled_sub_id); + +SELECT spock.sub_drop('test_subscription_disabled'); + -- Cleanup \c :provider_dsn SELECT spock.replicate_ddl($$ DROP TABLE public.conflict_ue_test CASCADE; $$); diff --git a/tests/tap/schedule b/tests/tap/schedule index b44cee616..322d57a1d 100644 --- a/tests/tap/schedule +++ b/tests/tap/schedule @@ -57,6 +57,17 @@ test: 046_apply_worker_exception_misclassification test: 048_insert_conflict_race test: 049_wait_for_sync_dropped test: 052_change_log_attmap +test: 070_bidir_plumbing +test: 073_bidir_join_multipeer_lag +test: 074_bidir_join_big_txn_liveness +test: 075_bidir_join_unbounded_peer_slot_wal +test: 077_bidir_join_lww_conflict +test: 078_bidir_join_concurrent_load +test: 081_bidir_join_forwarded_discard_abort +test: 082_create_subscriber_basebackup +test: 083_create_subscriber_enable_order +test: 084_create_subscriber_exception_modes +test: 085_create_subscriber_rmgr_replay # Upgrade schema match test (builds from source, slow): #test: 018_upgrade_schema_match # diff --git a/tests/tap/schedule-nightly b/tests/tap/schedule-nightly index b1c3c69f2..62aaa5b93 100644 --- a/tests/tap/schedule-nightly +++ b/tests/tap/schedule-nightly @@ -45,3 +45,21 @@ test: 103_manager_worker_dboid_race test: 110_resync_node_info_warning test: 120_standby_holdback_quorum test: 121_exception_slot_exhausted + +# --bidirectional join failure paths, kept off the per-PR schedule to stay +# inside the 30 minute TAP step limit in spockbench.yml. 076 and 080 are +# matrices in which every case is a full join (~110s apiece); 072, 079 and 086 +# (~43s each) cover the utility being killed mid-catchup, the stall watchdog +# aborting, and the source slot creation being cancelled. +test: 072_bidir_join_crash_midcatchup +test: 076_bidir_join_precondition_negatives +test: 079_bidir_join_stall_abort +test: 080_bidir_join_failure_matrix +test: 086_create_subscriber_slot_cancel + +# --bidirectional join under sustained OLTP write load (pgedge-loadgen). +# Not yet enabled here: needs its real-world runtime at +# SPOCK_BIDIR_LOAD_LEVEL=medium/heavy characterized on CI hardware first, +# and CI needs a pgedge-loadgen checkout (PGEDGE_LOADGEN_BIN) available -- +# it skip_alls cleanly without one. ~161s locally at the light default. +#test: 071_bidir_join_under_load diff --git a/tests/tap/t/046_apply_worker_exception_misclassification.pl b/tests/tap/t/046_apply_worker_exception_misclassification.pl index fd5eded3f..12ee4797f 100644 --- a/tests/tap/t/046_apply_worker_exception_misclassification.pl +++ b/tests/tap/t/046_apply_worker_exception_misclassification.pl @@ -143,7 +143,7 @@ # Restart the apply worker repeatedly while the writer is running, via # sub_alter_options() toggling apply_delay -- the same mechanism that -# uncovered this bug in 049_bidir_join_under_load.pl's lag-injection +# uncovered this bug in 071_bidir_join_under_load.pl's lag-injection # scenario. for my $i (1 .. 40) { system_or_bail("$pg_bin/psql", '-X', '-p', $p2, '-d', $dbname, '-c', diff --git a/tests/tap/t/070_bidir_plumbing.pl b/tests/tap/t/070_bidir_plumbing.pl new file mode 100644 index 000000000..7f92b4de9 --- /dev/null +++ b/tests/tap/t/070_bidir_plumbing.pl @@ -0,0 +1,1122 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 070_bidir_plumbing.pl - spock_create_subscriber --bidirectional +# ============================================================================= +# Validates the bidirectional node-join procedure end to end: physical +# backup, recovery to a restore point, catalog strip (capture + origin drop +# + guarded DROP EXTENSION), replication-set/table/sequence restore, and +# catchup (disabled-first subscription to the source, disabled placeholder +# subscriptions to every peer, and a wait for n3 to reach a target LSN +# captured on the source) -- stopping short of enabling any direct peer +# subscription (a later step). +# +# Topology: +# n1 <-> n2 (full bidirectional Spock subscriptions, existing 2-node +# cluster from create_cluster/cross_wire) +# n3 a real third PostgreSQL instance built via +# `spock_create_subscriber --bidirectional`, physically backed +# up from n1. +# +# Test count breakdown: +# 1 binary found +# 5 create_cluster(2) +# 1 cross_wire n1<->n2 +# 1 custom replication set created on n1 +# 1 table with row_filter added to custom set on n1 +# 1 table with explicit column list added to custom set on n1 +# 1 sequence added to custom set on n1 +# 1 sequence advanced past its initial value on n1 (setval fidelity check) +# 1 partitioned table (parent + 2 children) added to custom set on n1 +# 1 sequence with apostrophe in name added to custom set on n1 +# 1 peer-forwarding test table created on n1 +# 1 peer-forwarding test table replicated to n2 +# 1 --bidirectional exits 0 +# 1 n3 postgres is running +# 1 spock extension installed cleanly on n3 (exactly one row) +# 1 n3 has exactly the catchup and peer origins, none leftover from the basebackup +# 1 n3 was given its own system identifier (pg_resetwal), distinct from n1 +# 1 spock.readonly is lifted on n3 once the join is fully verified +# 1 custom replication set restored on n3 with correct flags +# 1 table membership restored with correct row_filter +# 1 table membership restored with correct explicit column list +# 1 sequence value restored exactly (last_value) +# 1 sequence is_called restored exactly +# 1 sequence pr3_test_seq is a member of pr3_test_repset on n3 +# 1 partitioned table parent + 2 children all present in repset on n3 +# 1 apostrophe-named sequence value restored on n3 +# 1 apostrophe-named sequence is_called restored on n3 +# 1 apostrophe-named sequence is a member of pr3_test_repset on n3 +# 1 manifest: source_slot_name populated +# 1 manifest: source_restore_lsn populated +# 1 manifest: node_dsn populated +# 1 source slot exists on n1 +# 1 catchup subscription sub_n3_n1 is replicating on n3 +# 1 forwarding cleared on sub_n3_n1 after cutover +# 1 direct peer subscription sub_n3_n2 is replicating on n3 after cutover +# 1 peer slot created on n2 during the coverage barrier +# 1 n2's post-cutover write reached n3 via the direct sub_n3_n2 path +# 1 n3's origin for peer n2 advanced via the direct subscription +# 1 reverse subscription sub_n2_n3 is replicating on n2 +# 1 reverse subscription sub_n1_n3 is replicating on n1 +# 1 n3's post-join write reached the source via sub_n1_n3 +# 1 n3's post-join write reached the peer via sub_n2_n3 +# 1 manifest has version 2 and status complete after the join +# 9 --cleanup refuses a completed join: names the manifest, says how to remove a live +# node by hand, and leaves the manifest, directory and subscriptions untouched +# 3 --force is not an option, and the rejected run touches nothing +# 1 the manifest is put back to in_progress to test cleanup of an interrupted join +# 1 pending-cleanup sidecar has status in_progress +# 4 --cleanup with the source unreachable keeps the manifest and data directory +# 1 --cleanup exits 0 +# 1 source slot removed from n1 after cleanup +# 1 n3 data directory kept after cleanup, postmaster stopped +# 1 manifest removed after cleanup +# 1 a second --cleanup exits 0 +# 1 the operator removes the directory +# 1 --cleanup exits 0 when run again on an already-clean target (idempotent) +# 1 no source slot reappears from a redundant cleanup call +# 1 --bidirectional rejects a multi-database request +# 1 --max-wait rejects a value that overflows int +# 1 --stall-timeout rejects a non-numeric value +# 1 --apply-delay rejects a value that overflows int +# 1 --bidirectional aborts when another database on the source has spock configured +# 1 --bidirectional rejects a broken full-mesh topology (disabled subscription) +# 1 --bidirectional rejects mismatched replication-set flags between source and peer +# 1 a broken --extra-basebackup-args makes the base backup fail +# 1 pending-cleanup sidecar written before the failed backup +# 1 pending-cleanup sidecar is mode 0600 +# 1 source slot still exists on n1 after the failed backup (orphaned) +# 1 --cleanup recovers via the pending sidecar +# 1 source slot removed from n1 via sidecar-based cleanup +# 1 pending-cleanup sidecar removed after cleanup +# 1 a broken backup orphans a slot for the retry-cleanup test +# 1 pending sidecar written for the retry-cleanup test +# 1 --cleanup exits non-zero when the source is unreachable +# 1 pending sidecar retained after an incomplete cleanup +# 1 n1 postgres is running again +# 1 --cleanup succeeds once the source is reachable again +# 1 pending sidecar removed once cleanup actually completed +# 10 --cleanup with no manifest/sidecar touches nothing +# 6 an unwritable sidecar location is rejected before the source slot is created +# 1 destroy_cluster +# --- +# 102 total +# ============================================================================= + +use strict; +use warnings; +use Test::More tests => 134; +use File::Path qw(remove_tree); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready output_plugin_libraries_conf + track_child track_datadir); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); + +# The tool's stderr lands in the shared log file (SpockTest.pm redirects every +# child's stderr there). Read it back after a negative case to check *why* +# the run was rejected, not only that it exited nonzero. +sub log_size { return -s $config->{log_file} // 0; } +sub log_tail_has { + my ($pattern, $since_bytes) = @_; + open(my $fh, '<', $config->{log_file}) or return ''; + seek($fh, $since_bytes, 0); + local $/; + my $tail = <$fh> // ''; + close $fh; + return $tail =~ $pattern; +} +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +my $n1_sysid = scalar_query(1, "SELECT system_identifier FROM pg_control_system()"); + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +# ============================================================================= +# Seed n1 with a custom replication set, a table with a row_filter, and a +# sequence, to exercise the catalog capture/restore with non-default state +# rather than just the three built-in sets. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT spock.repset_create('pr3_test_repset', true, true, true, false)"; +pass('custom replication set created on n1'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pr3_test_tbl (id serial primary key, region text, value integer)"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT spock.repset_add_table(set_name := 'pr3_test_repset', " . + "relation := 'pr3_test_tbl', synchronize_data := false, " . + "row_filter := 'region = ''east''')"; +pass('table with row_filter added to custom set on n1'); + +# Table with an explicit, non-default column list, to exercise the +# columns := restore path (captured/restored as a bare array- +# literal string relying on implicit text[] coercion) -- previously +# untested, so a round-trip regression here could pass silently. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pr3_test_cols (id serial primary key, region text, " . + "value integer, secret text)"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT spock.repset_add_table(set_name := 'pr3_test_repset', " . + "relation := 'pr3_test_cols', synchronize_data := false, " . + "columns := ARRAY['id', 'region', 'value'])"; +pass('table with explicit column list added to custom set on n1'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE SEQUENCE pr3_test_seq"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT spock.repset_add_seq('pr3_test_repset', 'pr3_test_seq')"; +pass('sequence added to custom set on n1'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT setval('pr3_test_seq', 42, true)"; +my $seq_before = scalar_query(1, "SELECT last_value FROM pr3_test_seq"); +is($seq_before, '42', 'sequence advanced past its initial value on n1'); + +# Partitioned table: parent + 2 children get separate captured membership +# rows (that's how include_partitions => true populated them here); restore +# must not try to re-add children a second time via the parent's own +# include_partitions => true call. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pr3_test_part (id int, region text, PRIMARY KEY (id, region)) PARTITION BY LIST (region)"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pr3_test_part_east PARTITION OF pr3_test_part FOR VALUES IN ('east')"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pr3_test_part_west PARTITION OF pr3_test_part FOR VALUES IN ('west')"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT spock.repset_add_table(set_name := 'pr3_test_repset', " . + "relation := 'pr3_test_part', synchronize_data := false, " . + "include_partitions := true)"; +pass('partitioned table (parent + 2 children) added to custom set on n1'); + +# Sequence with an apostrophe in its name, to exercise setval() quoting. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + q(CREATE SEQUENCE "weird's_seq"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + q(SELECT spock.repset_add_seq('pr3_test_repset', '"weird''s_seq"')); +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + q(SELECT setval('"weird''s_seq"', 7, true)); +pass('sequence with apostrophe in name added to custom set on n1'); + +# Table used later to verify n3's origin for peer n2 advances via forwarding. +# Created on n1 only and left to arrive on n2 via DDL replication (creating +# it directly on both sides races the already-established cross-wire DDL +# replay); spock.include_ddl_repset=on adds it to 'default' on each node +# once it lands there. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pr4_peer_tbl (id serial primary key, val text)"; +pass('peer-forwarding test table created on n1'); + +my $tbl_on_n2 = '0'; +for (1 .. 15) { + $tbl_on_n2 = scalar_query(2, + "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'pr4_peer_tbl'"); + last if $tbl_on_n2 eq '1'; + sleep(1); +} +is($tbl_on_n2, '1', 'peer-forwarding test table replicated to n2'); + +# check_preconditions() requires all of n1's outbound replication to have +# caught up (no unreplicated DDL/data still in flight to n2); wait for the +# setup above to drain. +for (1 .. 15) { + my $lag = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + last if defined $lag && $lag eq '0'; + sleep(1); +} + +# ============================================================================= +# TEST: --bidirectional continues through physical backup / catalog strip / +# repset restore, stopping before the catchup subscription. +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3'; +track_datadir($n3_datadir); +my $manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; + +# n3's WAL lives outside its data directory, so cleanup has a link to follow. +my $n3_waldir = '/tmp/tmp_spock_node_2_waldir_bidir_pr3'; +remove_tree($n3_waldir) if -d $n3_waldir; + +# n3's postgresql.conf is copied verbatim from n1 by the basebackup, port and +# all -- since all nodes run on the same host in this test, n3 must be given +# an override with its own port (a real cross-host join wouldn't need this). +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='" . $config->{log_dir} . "'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +command_ok( + [ $SCS_BIN, + '--bidirectional', + # trailing slash: the pending sidecar must still land next to the + # directory, not inside it (pg_basebackup needs it empty) + '--pgdata', "$n3_datadir/", + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--extra-basebackup-args', "--waldir=$n3_waldir", + ], + '--bidirectional exits 0 (trailing slash on --pgdata, separate WAL directory)' +); +ok(-l "$n3_datadir/pg_wal", 'n3 WAL directory is outside its data directory'); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); + +my $ext_count = `$pg_bin/psql -p $n3_port -d $dbname -t -c "SELECT COUNT(*) FROM pg_extension WHERE extname = 'spock'"`; +$ext_count =~ s/\s+//g; +is($ext_count, '1', 'spock extension installed cleanly on n3 (exactly one row)'); + +# By this point the catchup subscription and the one disabled peer +# subscription (n2) have each created their own origin -- exactly 2, not +# more. Anything beyond that would mean an origin survived from the +# basebackup instead of being dropped by the catalog strip. +my $origin_count = `$pg_bin/psql -p $n3_port -d $dbname -t -c "SELECT COUNT(*) FROM pg_replication_origin"`; +$origin_count =~ s/\s+//g; +is($origin_count, '2', + 'n3 has exactly the catchup and peer origins, none leftover from the basebackup'); + +my $n3_sysid = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT system_identifier FROM pg_control_system()"`; +$n3_sysid =~ s/\s+//g; +isnt($n3_sysid, $n1_sysid, + 'n3 was given its own system identifier (pg_resetwal), distinct from n1'); + +my $readonly = `$pg_bin/psql -p $n3_port -d $dbname -t -c "SHOW spock.readonly"`; +$readonly =~ s/\s+//g; +is($readonly, 'off', + "spock.readonly is lifted on n3 once the join is fully verified"); + +my $repset_flags = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT replicate_insert, replicate_update, replicate_delete, replicate_truncate FROM spock.replication_set WHERE set_name = 'pr3_test_repset'"`; +$repset_flags =~ s/\s+//g; +is($repset_flags, 't|t|t|f', 'custom replication set restored on n3 with correct flags'); + +my $row_filter = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT pg_get_expr(rts.set_row_filter, rts.set_reloid) FROM spock.replication_set_table rts JOIN spock.replication_set rs ON rts.set_id = rs.set_id WHERE rs.set_name = 'pr3_test_repset'"`; +$row_filter =~ s/^\s+|\s+$//g; +like($row_filter, qr/region\s*=\s*'east'/, 'table membership restored with correct row_filter'); + +my $columns = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT rts.set_att_list FROM spock.replication_set_table rts JOIN spock.replication_set rs ON rts.set_id = rs.set_id WHERE rs.set_name = 'pr3_test_repset' AND rts.set_reloid::regclass::text = 'pr3_test_cols'"`; +$columns =~ s/^\s+|\s+$//g; +is($columns, '{id,region,value}', + 'table membership restored with correct explicit column list'); + +my $seq_last_value = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT last_value FROM pr3_test_seq"`; +$seq_last_value =~ s/\s+//g; +is($seq_last_value, '42', 'sequence value restored exactly (last_value)'); + +my $seq_is_called = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT is_called FROM pr3_test_seq"`; +$seq_is_called =~ s/\s+//g; +is($seq_is_called, 't', 'sequence is_called restored exactly'); + +# pr3_test_seq must be an actual member of pr3_test_repset on n3, not just +# have its value restored (a regression here is the sequence-membership bug: +# setval() alone leaves the sequence unpublished). +my $seq_member = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT COUNT(*) FROM spock.replication_set_seq rss JOIN spock.replication_set rs ON rss.set_id = rs.set_id WHERE rs.set_name = 'pr3_test_repset' AND rss.set_seqoid::regclass::text = 'pr3_test_seq'"`; +$seq_member =~ s/\s+//g; +is($seq_member, '1', 'sequence pr3_test_seq is a member of pr3_test_repset on n3'); + +# Partitioned table: parent + 2 children must all be present as distinct +# memberships (a regression here is include_partitions => true re-adding +# already-captured children and violating the (set_id, set_reloid) PK, +# which would have aborted the join above rather than just miscounting). +my $part_member_count = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT COUNT(*) FROM spock.replication_set_table rts JOIN spock.replication_set rs ON rts.set_id = rs.set_id WHERE rs.set_name = 'pr3_test_repset' AND rts.set_reloid::regclass::text LIKE 'pr3_test_part%'"`; +$part_member_count =~ s/\s+//g; +is($part_member_count, '3', 'partitioned table parent + 2 children all present in repset on n3'); + +# Sequence with an apostrophe in its name: value/is_called restored and +# membership present, without a SQL syntax error breaking the whole run. +sub psql_capture { + my (@args) = @_; + open(my $fh, '-|', "$pg_bin/psql", @args) or die "cannot run psql: $!"; + local $/; + my $out = <$fh>; + close $fh; + $out =~ s/^\s+|\s+$//g if defined $out; + return $out; +} + +my $weird_seq_value = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', 'SELECT last_value FROM "weird\'s_seq"'); +is($weird_seq_value, '7', "apostrophe-named sequence value restored on n3"); + +my $weird_seq_called = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', 'SELECT is_called FROM "weird\'s_seq"'); +is($weird_seq_called, 't', "apostrophe-named sequence is_called restored on n3"); + +my $weird_seq_member = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT COUNT(*) FROM spock.replication_set_seq rss JOIN spock.replication_set rs ON rss.set_id = rs.set_id WHERE rs.set_name = 'pr3_test_repset' AND rss.set_seqoid::regclass::text = '\"weird''s_seq\"'"); +is($weird_seq_member, '1', "apostrophe-named sequence is a member of pr3_test_repset on n3"); + +# ============================================================================= +# Manifest content checks +# ============================================================================= +my $manifest_content = ''; +if (-f $manifest) { + open my $fh, '<', $manifest or die "Cannot read manifest: $!"; + local $/; + $manifest_content = <$fh>; + close $fh; +} + +ok($manifest_content =~ /"source_slot_name":\s*"[^"]+"/, + 'manifest: source_slot_name populated'); +ok($manifest_content =~ /"source_restore_lsn":\s*"[0-9A-Fa-f]+\/[0-9A-Fa-f]+"/, + 'manifest: source_restore_lsn populated'); +ok($manifest_content =~ /"node_dsn":\s*"[^"]+"/, + 'manifest: node_dsn populated'); +ok($manifest_content =~ /"version":\s*2\b/ && + $manifest_content =~ /"status":\s*"complete"/, + 'manifest: version 2, status complete after the join'); + +# --cleanup trusts the manifest in the data directory, so it must refuse one +# that belongs to another node (e.g. copied from a source joined by this tool). +my $ls_owner = log_size(); +ok(!system_maybe($SCS_BIN, '--bidirectional', '--cleanup', + '--subscriber-name', 'not_n3', '--pgdata', $n3_datadir), + '--cleanup refuses a manifest that belongs to another node'); +ok(log_tail_has(qr/belongs to node "n3", not "not_n3"/, $ls_owner), + 'the refusal names both nodes'); +ok(-f $manifest, 'manifest kept after the refused --cleanup (wrong node)'); + +# A manifest and a pending record that name different nodes mean the manifest +# was copied from the source by an interrupted backup; --cleanup must not pick +# one of them. +{ + my $pending = "$n3_datadir.spock_bidir_pending.json"; + my $mtext = do { local $/; open my $mf, '<', $manifest or die $!; <$mf> }; + + # Repeat the first peer so both records list more peers than the parser's + # initial array size; reading the second record after the first used to + # run past the end of the peer array. + (my $padded = $mtext) =~ + s/( \{\n "node_name".*?\n \})(,?\n)/("$1,\n" x 5) . "$1$2"/se; + (my $ptext = $padded) =~ s/("subscriber_name":\s*)"n3"/$1"other_node"/; + open my $pf, '>', $pending or die "Cannot write $pending: $!"; + print $pf $ptext; + close $pf; + open my $mf2, '>', $manifest or die "Cannot write $manifest: $!"; + print $mf2 $padded; + close $mf2; + + my $ls_mix = log_size(); + ok(!system_maybe($SCS_BIN, '--bidirectional', '--cleanup', + '--pgdata', $n3_datadir), + '--cleanup refuses a manifest and a pending record of different nodes'); + ok(log_tail_has(qr/belongs to node "n3" but the pending record .* belongs to "other_node"/, + $ls_mix), + 'the refusal names both records'); + ok(-f $manifest, 'manifest kept after the refused --cleanup (mixed records)'); + unlink $pending; + open my $mf3, '>', $manifest or die "Cannot write $manifest: $!"; + print $mf3 $mtext; + close $mf3; +} + +# A completed join is a live cluster member: --cleanup refuses it and removes +# nothing; the way to take such a node out is by hand. +my $ls_21538 = log_size(); +ok(!system_maybe($SCS_BIN, '--bidirectional', '--cleanup', + '--pgdata', $n3_datadir), + '--cleanup refuses a completed join'); +ok(log_tail_has(qr/Manifest \Q$manifest\E records a completed join/, $ls_21538), + 'rejected for the expected reason, naming the manifest'); +ok(log_tail_has(qr/spock\.sub_drop\(\).*spock\.node_drop\(\).*delete it and run --cleanup again/s, + $ls_21538), + 'the refusal says how to remove a live node by hand and what to do about a stale manifest'); +ok(-f $manifest, 'manifest kept after the refused --cleanup'); +ok(-d $n3_datadir, 'data directory kept after the refused --cleanup'); +is(scalar_query(1, "SELECT count(*) FROM spock.subscription WHERE sub_name = 'sub_n1_n3'"), + '1', "the source's reverse subscription survives the refused --cleanup"); +is(scalar_query(2, "SELECT count(*) FROM spock.subscription WHERE sub_name = 'sub_n2_n3'"), + '1', "the peer's reverse subscription survives the refused --cleanup"); +is(`$pg_bin/psql -X -p $n3_port -d $dbname -t -A -c "SELECT count(*) > 0 FROM spock.subscription"`, + "t\n", 'subscriptions on the joined node survive the refused --cleanup'); + +# --force is gone: there is no way to ask --cleanup to remove a node or its +# data directory. +my $ls_force = log_size(); +ok(!system_maybe($SCS_BIN, '--bidirectional', '--cleanup', '--force', + '--pgdata', $n3_datadir), + '--force is not an option'); +ok(log_tail_has(qr/unrecognized option.*force/, $ls_force), + 'the rejection names the option'); +ok(-f $manifest && -d $n3_datadir, 'nothing was touched by the rejected --force'); + +my $source_slot_exists = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +ok($source_slot_exists >= 1, 'source slot exists on n1'); + +# ============================================================================= +# TEST: catchup subscription and, after cutover, the direct peer +# subscription are both replicating; a post-cutover write on n2 reaches n3 +# via the direct path, advancing n3's origin for n2. +# ============================================================================= +my $sub_status = ''; +for (1 .. 30) { + $sub_status = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT status FROM spock.sub_show_status('sub_n3_n1')"); + last if $sub_status eq 'replicating'; + sleep(1); +} +is($sub_status, 'replicating', 'catchup subscription sub_n3_n1 is replicating on n3'); + +is(psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT forward_origins FROM spock.sub_show_status('sub_n3_n1')"), + '', "forwarding cleared on sub_n3_n1 after cutover"); + +my $peer_sub_status = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT status FROM spock.sub_show_status('sub_n3_n2')"); +is($peer_sub_status, 'replicating', + 'direct peer subscription sub_n3_n2 is replicating on n3 after cutover'); + +# Origin name matches what create_disabled_peer_subscriptions() computed for +# sub_n3_n2 (spock_gen_slot_name(dbname, 'n2', 'sub_n3_n2')) -- the same +# value is also the slot name create_peer_slot() created on n2 during the +# coverage barrier. +my $n2_origin_name = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT spock.spock_gen_slot_name('$dbname', 'n2', 'sub_n3_n2')"); + +is(psql_capture('-p', $node_ports->[1], '-d', $dbname, '-t', '-A', + '-c', "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name = '$n2_origin_name'"), + '1', 'peer slot created on n2 during the coverage barrier'); + +my $n2_origin_query = + "SELECT COALESCE(s.remote_lsn::text, '0/0') FROM pg_replication_origin o " . + "LEFT JOIN pg_replication_origin_status s ON o.roident = s.local_id " . + "WHERE o.roname = '$n2_origin_name'"; + +# Write on n2 after cutover; forwarding is off and the direct sub_n3_n2 is +# enabled, so this reaches n3 directly from n2, not via n1. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "INSERT INTO pr4_peer_tbl (val) VALUES ('from_n2_post_join')"; + +my $row_on_n3 = '0'; +for (1 .. 30) { + $row_on_n3 = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT COUNT(*) FROM pr4_peer_tbl WHERE val = 'from_n2_post_join'"); + last if $row_on_n3 eq '1'; + sleep(1); +} +is($row_on_n3, '1', "n2's post-cutover write reached n3 via the direct sub_n3_n2 path"); + +my $n2_origin_lsn = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', $n2_origin_query); +isnt($n2_origin_lsn, '0/0', "n3's origin for peer n2 advanced via the direct subscription"); + +# ============================================================================= +# TEST: reverse subscriptions are replicating, and a write on n3 reaches +# both the source and the peer through them -- an external proof, +# independent of the utility's own internal verify_bidirectional_dataflow() +# check. +# ============================================================================= +is(psql_capture('-p', $node_ports->[1], '-d', $dbname, '-t', '-A', + '-c', "SELECT status FROM spock.sub_show_status('sub_n2_n3')"), + 'replicating', 'reverse subscription sub_n2_n3 is replicating on n2'); + +is(psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', + '-c', "SELECT status FROM spock.sub_show_status('sub_n1_n3')"), + 'replicating', 'reverse subscription sub_n1_n3 is replicating on n1'); + +# Explicit id: pr4_peer_tbl's serial sequence isn't part of the custom +# repset that gets its value round-tripped onto n3 (only pr3_test_seq and +# the apostrophe-named sequence are), so n3's own local copy of the +# sequence is still at its basebackup-time value and would collide with +# the id the n2-post-join row already claimed via replication. +system_or_bail "$pg_bin/psql", '-p', $n3_port, '-d', $dbname, '-c', + "INSERT INTO pr4_peer_tbl (id, val) VALUES (1000, 'from_n3_post_join')"; + +my $row_on_n1 = '0'; +for (1 .. 30) { + $row_on_n1 = scalar_query(1, + "SELECT COUNT(*) FROM pr4_peer_tbl WHERE val = 'from_n3_post_join'"); + last if $row_on_n1 eq '1'; + sleep(1); +} +is($row_on_n1, '1', "n3's post-join write reached the source via sub_n1_n3"); + +my $row_on_n2_from_n3 = '0'; +for (1 .. 30) { + $row_on_n2_from_n3 = scalar_query(2, + "SELECT COUNT(*) FROM pr4_peer_tbl WHERE val = 'from_n3_post_join'"); + last if $row_on_n2_from_n3 eq '1'; + sleep(1); +} +is($row_on_n2_from_n3, '1', "n3's post-join write reached the peer via sub_n2_n3"); + +# ============================================================================= +# From here on --cleanup is tried on what an interrupted join leaves behind: +# the manifest goes back to in_progress, as if the run had died right after it +# created everything. (A completed join is never cleaned up; see above.) +# ============================================================================= +{ + my $mtext_done = do { local $/; open my $mf, '<', $manifest or die $!; <$mf> }; + (my $mtext_open = $mtext_done) =~ s/("status":\s*)"complete"/$1"in_progress"/; + isnt($mtext_open, $mtext_done, 'the manifest is put back to in_progress'); + open my $mfo, '>', $manifest or die "Cannot write $manifest: $!"; + print $mfo $mtext_open; + close $mfo; +} + +# ============================================================================= +# TEST: --cleanup with the source unreachable must not delete the manifest +# (it lives in the data directory and is the only drop list). +# ============================================================================= +{ + my $n1_dd = $config->{node_datadirs}->[0]; + system_or_bail "$pg_bin/pg_ctl", 'stop', '-D', $n1_dd, '-m', 'fast'; + + my $ls_27374 = log_size(); +ok(!system_maybe($SCS_BIN, '--bidirectional', '--cleanup', + '--pgdata', $n3_datadir), + '--cleanup exits non-zero when the source is unreachable'); +ok(log_tail_has(qr/cannot connect to source node/, $ls_27374), + 'rejected for the expected reason: cannot connect to source node'); + ok(-d $n3_datadir, + 'data directory kept after an incomplete --cleanup'); + ok(-f $manifest, + 'manifest kept after an incomplete --cleanup'); + + system_or_bail "$pg_bin/pg_ctl", 'start', '-D', $n1_dd, + '-l', "$config->{log_dir}/n1_force_restart.log"; + ok(wait_for_pg_ready($host, $node_ports->[0], $pg_bin, 30), + 'n1 postgres is running again'); +} + +# ============================================================================= +# TEST: --cleanup removes the source slot and the manifest, and leaves the +# data directory to the operator +# ============================================================================= +command_ok( + [ $SCS_BIN, + '--bidirectional', + '--cleanup', + '--pgdata', $n3_datadir, + ], + '--cleanup exits 0' +); + +my $source_slot_after = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($source_slot_after, '0', 'source slot removed from n1 after cleanup'); + +ok(-d $n3_datadir, 'n3 data directory kept after cleanup'); +ok(!-f $manifest, 'manifest removed after cleanup'); +ok(!-e "$n3_datadir/postmaster.pid", 'postmaster of n3 stopped by cleanup'); +command_ok( + [ $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $n3_datadir ], + 'a second --cleanup of the same directory exits 0' +); + +# The operator removes the data directory, and the separate WAL directory it +# links to, which a later join needs empty. +remove_tree($n3_datadir); +remove_tree($n3_waldir, { keep_root => 1 }); +ok(!-d $n3_datadir, 'n3 data directory removed by the operator'); + +# ============================================================================= +# TEST: a slot already on a peer under the name this join would use is not +# ours: the join must refuse it, and --cleanup must leave it alone. +# ============================================================================= +{ + my $peer_slot = scalar_query(1, + "SELECT spock.spock_gen_slot_name('$dbname', 'n2', 'sub_n3_n2')"); + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, + '-c', "SELECT pg_create_logical_replication_slot('$peer_slot', 'spock_output')"; + + my $ls_29440 = log_size(); +ok(!system_maybe($SCS_BIN, '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf), + 'join refuses a pre-existing slot of the peer slot name'); +ok(log_tail_has(qr/replication slot ".*" already exists on "n2"/, $ls_29440), + 'rejected for the expected reason: already exists on peer'); + system_maybe($SCS_BIN, '--bidirectional', '--cleanup', + '--pgdata', $n3_datadir); + is(scalar_query(2, + "SELECT count(*) FROM pg_replication_slots WHERE slot_name = '$peer_slot'"), + '1', '--cleanup leaves the pre-existing peer slot alone'); + + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, + '-c', "SELECT pg_drop_replication_slot('$peer_slot')"; + remove_tree($n3_datadir) if -d $n3_datadir; +} + +# ============================================================================= +# TEST: --cleanup is a safe no-op when the target is already fully +# clean -- no manifest, no pending sidecar, no data directory, nothing left +# on the source to drop. This existed in the old 070_bidir_plumbing.pl and +# was never carried forward when 070 superseded it. +# ============================================================================= +command_ok( + [ $SCS_BIN, + '--bidirectional', + '--cleanup', + '--pgdata', $n3_datadir, + ], + '--cleanup exits 0 when run again on an already-clean target (idempotent)' +); + +my $source_slot_after_idempotent_cleanup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($source_slot_after_idempotent_cleanup, '0', + 'no source slot reappears from a redundant cleanup call'); + +# ============================================================================= +# TEST: --bidirectional hard-rejects a multi-database request outright, +# rather than silently joining only the first-named database -- all join +# state is per-database. +# ============================================================================= +my $multidb_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_multidb'; +track_datadir($multidb_datadir); +remove_tree($multidb_datadir) if -d $multidb_datadir; +my $ls_31783 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $multidb_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--databases', "$dbname,postgres"), + '--bidirectional rejects a multi-database request'); +ok(log_tail_has(qr/supports a single database only/, $ls_31783), + 'rejected for the expected reason: supports a single database only'); +remove_tree($multidb_datadir) if -d $multidb_datadir; + +# An empty entry in --databases is rejected, not left as an unset array slot. +{ + my $ls_empty = log_size(); + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $multidb_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--databases', "$dbname,"), + '--databases with an empty entry is rejected'); + ok(log_tail_has(qr/--databases contains an empty database name/, $ls_empty), + 'the rejection names the empty entry'); +} + +# A provider DSN without a dbname gets the intended message, not a crash. +{ + my $ls_nodb = log_size(); + my $rc_nodb = system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $multidb_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', "host=$host port=$node_ports->[0] user=$db_user password=$db_password", + '--subscriber-dsn', $n3_dsn); + ok(!$rc_nodb, 'a provider DSN without a database name is rejected'); + ok(log_tail_has(qr/provider connection string must contain database name/, $ls_nodb), + 'the rejection asks for a database name'); +} +remove_tree($multidb_datadir) if -d $multidb_datadir; + +# ============================================================================= +# TEST: option parsing rejects malformed/out-of-range integer arguments +# instead of silently truncating them -- e.g. a value like 4294967296 +# wraps to 0 when cast to int after strtol(), which would otherwise turn +# --max-wait=4294967296 into an accepted, effectively-unbounded wait. +# ============================================================================= +my $intcheck_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_intcheck'; +track_datadir($intcheck_datadir); +remove_tree($intcheck_datadir) if -d $intcheck_datadir; +my $ls_32929 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $intcheck_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--max-wait', '4294967296'), + '--max-wait rejects a value that overflows int'); +ok(log_tail_has(qr/--max-wait value is out of range/, $ls_32929), + 'rejected for the expected reason: --max-wait value is out of range'); + +my $ls_33405 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $intcheck_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--stall-timeout', 'abc'), + '--stall-timeout rejects a non-numeric value'); +ok(log_tail_has(qr/--stall-timeout requires an integer value/, $ls_33405), + 'rejected for the expected reason: --stall-timeout requires an integer valu'); + +my $ls_33889 = log_size(); +ok(!system_maybe($SCS_BIN, + '--pgdata', $intcheck_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--apply-delay', '99999999999999999999'), + '--apply-delay rejects a value that overflows int'); +ok(log_tail_has(qr/--apply-delay value is out of range/, $ls_33889), + 'rejected for the expected reason: --apply-delay value is out of range'); +remove_tree($intcheck_datadir) if -d $intcheck_datadir; + +# ============================================================================= +# TEST: --bidirectional aborts if the source instance has spock configured +# on another database too, even though that database was never named via +# --databases (check_single_spock_database() must fail closed). +# ============================================================================= +system_or_bail "$pg_bin/createdb", '-p', $node_ports->[0], 'pr3_other_db'; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', 'pr3_other_db', '-c', + "CREATE EXTENSION spock"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', 'pr3_other_db', '-c', + "SELECT spock.node_create('pr3_other_node', 'dbname=pr3_other_db')"; + +my $otherdb_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_otherdb'; +track_datadir($otherdb_datadir); +remove_tree($otherdb_datadir) if -d $otherdb_datadir; +my $ls_35292 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $otherdb_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn), + '--bidirectional aborts when another database on the source has spock configured'); +ok(log_tail_has(qr/exactly one spock-configured database/, $ls_35292), + 'rejected for the expected reason: exactly one spock-configured database'); +remove_tree($otherdb_datadir) if -d $otherdb_datadir; + +system_maybe "$pg_bin/psql", '-p', $node_ports->[0], '-d', 'pr3_other_db', '-c', + "SELECT spock.node_drop('pr3_other_node')"; +system_maybe "$pg_bin/dropdb", '-p', $node_ports->[0], 'pr3_other_db'; + +# ============================================================================= +# TEST: --bidirectional rejects a broken full-mesh topology -- a disabled +# subscription is not a valid mesh edge, even though it still exists. A +# plain subscription COUNT would not catch this. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT spock.sub_disable('sub_n2_n1', true)"; +for (1 .. 15) { + my $enabled = scalar_query(2, + "SELECT sub_enabled FROM spock.subscription WHERE sub_name = 'sub_n2_n1'"); + last if defined $enabled && $enabled eq 'f'; + sleep(1); +} + +my $mesh_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_mesh'; +track_datadir($mesh_datadir); +remove_tree($mesh_datadir) if -d $mesh_datadir; +my $ls_36856 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $mesh_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn), + '--bidirectional rejects a broken full-mesh topology (disabled subscription)'); +ok(log_tail_has(qr/no healthy \(status = 'replicating'\) subscription/, $ls_36856), + 'rejected for the expected reason: no healthy (status = replicating) subscr'); +remove_tree($mesh_datadir) if -d $mesh_datadir; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT spock.sub_enable('sub_n2_n1', true)"; +for (1 .. 15) { + my $enabled = scalar_query(2, + "SELECT sub_enabled FROM spock.subscription WHERE sub_name = 'sub_n2_n1'"); + last if defined $enabled && $enabled eq 't'; + sleep(1); +} + +# ============================================================================= +# TEST: --bidirectional rejects mismatched replication-set definitions for a +# selected (subscription-referenced) set between source and peer -- a +# repset the forwarding path and a future direct-peer path disagree on can +# permanently drop changes on cutover. DDL replication is disabled for the +# ALTER itself so the mismatch is real and local to n2. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_alter('default', replicate_truncate := false)"; + +my $repset_mismatch_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_repset_mismatch'; +track_datadir($repset_mismatch_datadir); +remove_tree($repset_mismatch_datadir) if -d $repset_mismatch_datadir; +my $ls_38641 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $repset_mismatch_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn), + '--bidirectional rejects mismatched replication-set flags between source and peer'); +ok(log_tail_has(qr/replication set "default" differs between the source and peer/, $ls_38641), + 'rejected for the expected reason: replication set "default" differs betwee'); +remove_tree($repset_mismatch_datadir) if -d $repset_mismatch_datadir; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_alter('default', replicate_truncate := true)"; + +# ============================================================================= +# TEST: a failed base backup leaves the source slot recoverable via +# --cleanup, even though the real manifest was never written -- a +# pending-cleanup sidecar is persisted right after source slot creation, +# before the backup even starts, since data_dir must stay empty until +# pg_basebackup runs. +# ============================================================================= +my $failed_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_failed'; +track_datadir($failed_datadir); +my $pending_sidecar = "${failed_datadir}.spock_bidir_pending.json"; +remove_tree($failed_datadir) if -d $failed_datadir; +unlink($pending_sidecar) if -f $pending_sidecar; + +my $ls_40159 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $failed_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--extra-basebackup-args', '--waldir=/nonexistent_pr3_test_waldir_xyz'), + 'a broken --extra-basebackup-args makes the base backup fail'); +ok(log_tail_has(qr/pg_basebackup failed/, $ls_40159), + 'rejected for the expected reason: pg_basebackup failed'); + +ok(-f $pending_sidecar, 'pending-cleanup sidecar written before the failed backup'); +{ + open my $sfh, '<', $pending_sidecar or die "Cannot read sidecar: $!"; + local $/; + my $sidecar_content = <$sfh>; + close $sfh; + ok($sidecar_content =~ /"status":\s*"in_progress"/, + 'pending-cleanup sidecar has status in_progress'); +} + +my $sidecar_mode = (stat($pending_sidecar))[2] & 07777; +is(sprintf('%04o', $sidecar_mode), '0600', + 'pending-cleanup sidecar is mode 0600 (may carry a DSN password)'); + +my $slot_after_failed_backup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +ok($slot_after_failed_backup >= 1, + 'source slot still exists on n1 after the failed backup (orphaned)'); + +command_ok( + [ $SCS_BIN, + '--bidirectional', + '--cleanup', + '--pgdata', $failed_datadir, + ], + '--cleanup recovers via the pending sidecar (no real manifest exists)' +); + +my $slot_after_sidecar_cleanup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($slot_after_sidecar_cleanup, '0', + 'source slot removed from n1 via sidecar-based cleanup'); + +ok(!-f $pending_sidecar, 'pending-cleanup sidecar removed after cleanup'); +remove_tree($failed_datadir) if -d $failed_datadir; + +# ============================================================================= +# TEST: an incomplete cleanup (source unreachable) exits non-zero and keeps +# the pending sidecar so it can be retried, instead of unconditionally +# deleting the only retry record. +# ============================================================================= +my $retry_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_pr3_retry'; +track_datadir($retry_datadir); +my $retry_sidecar = "${retry_datadir}.spock_bidir_pending.json"; +remove_tree($retry_datadir) if -d $retry_datadir; +unlink($retry_sidecar) if -f $retry_sidecar; + +my $ls_42626 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $retry_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--extra-basebackup-args', '--waldir=/nonexistent_pr3_test_waldir_retry'), + 'a broken backup orphans a slot for the retry-cleanup test'); +ok(log_tail_has(qr/pg_basebackup failed/, $ls_42626), + 'rejected for the expected reason: pg_basebackup failed'); +ok(-f $retry_sidecar, 'pending sidecar written for the retry-cleanup test'); + +my $n1_datadir = $config->{node_datadirs}->[0]; +system_or_bail "$pg_bin/pg_ctl", 'stop', '-D', $n1_datadir, '-m', 'fast'; + +my $ls_43363 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--cleanup', + '--pgdata', $retry_datadir), + '--cleanup exits non-zero when the source is unreachable'); +ok(log_tail_has(qr/cannot connect to source node/, $ls_43363), + 'rejected for the expected reason: cannot connect to source node'); +ok(-f $retry_sidecar, + 'pending sidecar retained after an incomplete cleanup (retryable)'); + +system_or_bail "$pg_bin/pg_ctl", 'start', '-D', $n1_datadir, + '-l', "$config->{log_dir}/n1_retry_restart.log"; +ok(wait_for_pg_ready($host, $node_ports->[0], $pg_bin, 30), + 'n1 postgres is running again'); + +command_ok( + [ $SCS_BIN, + '--bidirectional', + '--cleanup', + '--pgdata', $retry_datadir, + ], + '--cleanup succeeds once the source is reachable again' +); +ok(!-f $retry_sidecar, + 'pending sidecar removed once cleanup actually completed'); +remove_tree($retry_datadir) if -d $retry_datadir; + +# ============================================================================= +# TEST: --cleanup with neither a manifest nor a sidecar has nothing to do and +# touches nothing: not a non-empty directory (e.g. another node's data +# directory given by mistake), not an empty one. +# ============================================================================= +sub cleanup_only { + my ($pgdata) = @_; + my $out = qx{"$SCS_BIN" --bidirectional --cleanup --pgdata "$pgdata" 2>&1}; + return ($? >> 8, $out); +} + +my $stray_dir = '/tmp/tmp_spock_048_stray_dir'; +remove_tree($stray_dir) if -d $stray_dir; +mkdir($stray_dir) or die "cannot create $stray_dir: $!"; +open(my $stray_fh, '>', "$stray_dir/important.txt") or die "cannot write: $!"; +print $stray_fh "keep me\n"; +close($stray_fh); + +my ($cf_rc, $cf_out) = cleanup_only($stray_dir); +is($cf_rc, 0, '--cleanup of a directory with no records exits 0'); +like($cf_out, qr/nothing to clean up/, 'it says there is nothing to clean up'); +ok(-f "$stray_dir/important.txt", 'the directory content is left in place'); +remove_tree($stray_dir); + +($cf_rc, $cf_out) = cleanup_only($n1_datadir); +is($cf_rc, 0, "--cleanup of another node's data directory (no records) exits 0"); +ok(-f "$n1_datadir/PG_VERSION", "the running node's data directory is still present"); +is(system("$pg_bin/pg_isready -h $host -p $node_ports->[0] -q"), 0, + 'the running node is still accepting connections'); +like($cf_out, qr/nothing to clean up/, + "it says there is nothing to clean up for the running node's directory"); + +my $empty_dir = '/tmp/tmp_spock_048_empty_dir'; +remove_tree($empty_dir) if -d $empty_dir; +mkdir($empty_dir) or die "cannot create $empty_dir: $!"; +($cf_rc, $cf_out) = cleanup_only($empty_dir); +is($cf_rc, 0, '--cleanup of an empty directory exits 0'); +ok(-d $empty_dir, 'the empty directory is left in place'); +rmdir($empty_dir); + +($cf_rc, $cf_out) = cleanup_only('/tmp/tmp_spock_048_does_not_exist'); +is($cf_rc, 0, '--cleanup of a nonexistent directory exits 0'); +ok(!-e '/tmp/tmp_spock_048_does_not_exist', 'nothing was created'); + +# ============================================================================= +# TEST: the sidecar is the only record of the source slot, so its location is +# checked before the slot is created: a --pgdata whose parent directory does +# not exist is rejected +# without leaving a slot on the source. +# ============================================================================= +# (A trailing slash is dropped from --pgdata, so a missing directory named +# with one is an ordinary new directory, not an unwritable sidecar location.) +for my $bad ('/tmp/tmp_spock_048_missing_parent/sub/n3') { + for (1 .. 15) { + my $lag = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + last if defined $lag && $lag eq '0'; + sleep(1); + } + my $join_cmd = qq{"$SCS_BIN" --bidirectional --pgdata "$bad" } + . qq{--subscriber-name n3 --provider-dsn "$n1_dsn" } + . qq{--subscriber-dsn "$n3_dsn" 2>&1}; + my $join_out = qx{$join_cmd}; + isnt($? >> 8, 0, "join with an unwritable sidecar location ($bad) is rejected"); + like($join_out, qr/cannot write the pending-cleanup record/, + 'the rejection names the sidecar'); + is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots " . + "WHERE slot_name LIKE 'spk_%n3%'"), + '0', 'no source slot was left on n1'); +} + +# ============================================================================= +# CLEANUP +# ============================================================================= +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE IF EXISTS pr3_test_tbl"; +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE IF EXISTS pr3_test_part"; +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE IF EXISTS pr3_test_cols"; +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP SEQUENCE IF EXISTS pr3_test_seq"; +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + q(DROP SEQUENCE IF EXISTS "weird's_seq"); +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT spock.repset_drop('pr3_test_repset')"; +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Cleanup'); diff --git a/tests/tap/t/071_bidir_join_under_load.pl b/tests/tap/t/071_bidir_join_under_load.pl new file mode 100644 index 000000000..0f54b101f --- /dev/null +++ b/tests/tap/t/071_bidir_join_under_load.pl @@ -0,0 +1,807 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 071_bidir_join_under_load.pl - spock_create_subscriber --bidirectional +# under sustained OLTP write load +# ============================================================================= +# 070_bidir_plumbing.pl proves the --bidirectional pipeline (physical backup, +# catalog strip, catchup, coverage barrier, cutover, reverse subscriptions) +# is correct against a quiescent source. It does not prove the pipeline +# survives a source that is actively, continuously being written to for the +# whole multi-minute duration of the join -- which is the realistic +# production scenario this utility exists for. +# +# This test drives a TPC-C-like OLTP workload against n1 (via the +# pgedge-loadgen tool, https://github.com/pgEdge/pgedge-loadgen -- see +# PGEDGE_LOADGEN_BIN below) throughout a --bidirectional join, at a +# configurable intensity (SPOCK_BIDIR_LOAD_LEVEL=light|medium|heavy), and +# verifies: the join completes and reports success; n3's final data matches +# both n1's and n2's exactly -- row count AND full content hash, every +# wholesale table, not just one -- once replication drains; fresh +# bidirectional writes still flow correctly afterward; and --cleanup +# correctly recovers an orphaned join attempt while the source remains +# under load. Along the way it exercises --stall-timeout, +# --max-wait, --extra-basebackup-args (both a valid and a deliberately +# broken value), and a deliberately injected catchup-subscription +# apply_delay -- coverage 070 only ever exercises against a quiescent +# cluster, if at all. +# +# check_preconditions() (spock_create_subscriber.c) requires the source's +# outbound replication to have zero lag at the instant it runs, so the load +# generator cannot simply run continuously across the whole test: it is +# stopped and drained before each --bidirectional invocation, then resumed +# the moment that invocation's pending-cleanup sidecar file appears on disk +# (written immediately after the source slot is created, i.e. immediately +# after check_preconditions() has already passed) -- so the actual +# multi-minute body of the join (basebackup transfer, catchup replay, +# coverage barrier, cutover) runs with the source under active write load, +# exactly as intended. +# +# NOT added to tests/tap/schedule or schedule-nightly (see the commented-out +# entry there): this is meant to be run individually for now +# (PROVE_TESTS=t/071_bidir_join_under_load.pl make check_prove) and promoted +# to a nightly/weekly CI schedule later, once its real-world runtime at +# medium/heavy load is characterized. +# +# Requires the pgedge-loadgen binary. Resolved via, in order: the +# PGEDGE_LOADGEN_BIN environment variable; ../../../pgedge-loadgen/bin/ +# pgedge-loadgen (a sibling checkout of https://github.com/pgEdge/ +# pgedge-loadgen next to this spock checkout); PATH. skip_all (not fail) if +# none is found, matching ensure_lolor()'s precedent for an optional +# external dependency (SpockTest.pm) -- the test count is therefore not +# known up front (see 032_lolor_largeobject_repset.pl for the same +# plan-skip_all-then-done_testing() shape), and is settled by +# done_testing() at the end instead of a fixed Test::More tests => N plan. +# +# Flow: seed n1 with the wholesale schema+data, then run three scenarios, +# each under active pgedge-loadgen write load against n1 throughout the +# multi-minute body of the join: +# 1. a full --bidirectional join with --stall-timeout/--max-wait/ +# --extra-basebackup-args set, verified by exit code, subscription +# status, an exact row-count+content-hash match between n1/n3 and +# n1/n2 once replication drains, and a fresh two-way write proof -- +# then --cleanup torn down. +# 2. a join that fails part-way (broken --extra-basebackup-args, same +# trick as 070_bidir_plumbing.pl) orphaning a source slot, recovered via +# --cleanup while n1 is still under load. +# 3. a full join like (1), but with a deliberate apply_delay injected +# onto the catchup subscription partway through, proving the coverage +# barrier's stall-timeout logic tolerates steady, bounded replication +# lag rather than mistaking it for a stall. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +# ============================================================================= +# Locate pgedge-loadgen binary; skip_all (not fail) if unavailable +# ============================================================================= +my $LOADGEN_BIN = $ENV{PGEDGE_LOADGEN_BIN}; +$LOADGEN_BIN = undef if defined $LOADGEN_BIN && !-x $LOADGEN_BIN; +unless (defined $LOADGEN_BIN) { + my $sibling = '../../../pgedge-loadgen/bin/pgedge-loadgen'; + $LOADGEN_BIN = $sibling if -x $sibling; +} +unless (defined $LOADGEN_BIN) { + for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/pgedge-loadgen"; + if (-x $c) { $LOADGEN_BIN = $c; last; } + } +} +unless (defined $LOADGEN_BIN) { + plan skip_all => 'pgedge-loadgen not found (set PGEDGE_LOADGEN_BIN, ' . + 'or check out https://github.com/pgEdge/pgedge-loadgen next to ' . + 'this spock checkout and run "make build" there)'; +} + +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# Load level: light (default), medium, or heavy -- controls the number of +# concurrent pgedge-loadgen connections hammering n1 during each join. +# ============================================================================= +my %LOAD_CONNECTIONS = (light => 2, medium => 10, heavy => 25); +my $load_level = lc($ENV{SPOCK_BIDIR_LOAD_LEVEL} // 'light'); +BAIL_OUT("SPOCK_BIDIR_LOAD_LEVEL must be light, medium, or heavy (got '$load_level')") + unless exists $LOAD_CONNECTIONS{$load_level}; +my $load_connections = $LOAD_CONNECTIONS{$load_level}; +diag("load level: $load_level ($load_connections connections)"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; +my $n3_provider_uri = + "postgres://$db_user:$db_password\@$host:$node_ports->[0]/$dbname?sslmode=disable"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub psql_capture { + my (@args) = @_; + open(my $fh, '-|', "$pg_bin/psql", @args) or die "cannot run psql: $!"; + local $/; + my $out = <$fh>; + close $fh; + $out //= ''; + $out =~ s/^\s+|\s+$//g; + return $out; +} + +# ============================================================================= +# Fork cmd into the background, redirecting its output to $logfile. Returns +# the child PID immediately without waiting for it to finish. +# ============================================================================= +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so terminate_child() reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +# Stop a child started by spawn_background() and its own children (the +# utility runs pg_basebackup and pg_ctl through system()): TERM the process +# group, allow a grace period, then KILL it, and always reap. A bare +# waitpid() after TERM can block for as long as the backup takes to finish. +sub terminate_child { + my ($pid) = @_; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +# Block (with a bound) until $pid exits; returns its exit code, or undef if +# it did not exit within $timeout seconds. +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +# Send SIGTERM and wait (with a bound) for a clean exit -- pgedge-loadgen's +# run command drains in-flight queries and closes connections on SIGTERM, +# then exits 0 (confirmed empirically: no forced-kill path needed here). +sub stop_loadgen { + my ($pid, $logfile) = @_; + return unless defined $pid; + + # run only ends on SIGTERM, so one that has already exited stopped early + # (bad arguments, lost connection) and the join ran against idle data. + if (waitpid($pid, WNOHANG) == $pid) { + fail("the workload was still running when the join finished " + . "(it exited with " . ($? >> 8) . ")"); + if (defined $logfile && open(my $lfh, '<', $logfile)) { + local $/; + diag("workload log $logfile:\n" . (<$lfh> // '')); + close($lfh); + } + return; + } + pass("the workload was still running when the join finished"); + kill('TERM', $pid); + my $rc = wait_for_pid($pid, 30); + unless (defined $rc) { + diag("loadgen pid $pid did not exit after SIGTERM+30s; sending KILL"); + kill('KILL', $pid); + waitpid($pid, 0); + } +} + +# The pending-cleanup sidecar is deliberately ephemeral: it exists only +# between source-slot creation and the real manifest being written (which +# immediately unlinks it, superseded) -- run_basebackup_and_write_manifest() +# always writes the real manifest before removing the sidecar, so there is +# no gap where neither exists. On fast local disks that whole window can +# be well under a second (a small basebackup finishing before the next +# 1-second poll even runs), so polling for the sidecar alone can miss it +# entirely on a successful join even though the slot really was created; +# checking for either file closes that race. (A failed backup, e.g. +# scenario 2 below, never reaches the manifest write, so the sidecar +# alone stays present there for as long as it takes for this to notice.) +sub wait_for_slot_created { + my ($pending_path, $manifest_path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $pending_path || -f $manifest_path; + sleep(1); + } + return 0; +} + +# check_preconditions()'s own zero-lag requirement, polled from here so we +# never launch --bidirectional while it would be doomed to fail on it. +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +# The wholesale (TPC-C-like) schema's 9 tables and their primary-key +# columns, used both to pick a drain signal and to build an ORDER BY for +# the content-hash check below (string_agg's row order is otherwise +# undefined, which would make two nodes with identical data hash +# differently). +my @wholesale_tables = qw(warehouse district customer history item stock + orders new_orders order_line); +my %TABLE_PK = ( + warehouse => 'w_id', + district => 'd_w_id, d_id', + customer => 'c_w_id, c_d_id, c_id', + history => 'h_id', + item => 'i_id', + stock => 's_w_id, s_i_id', + orders => 'o_w_id, o_d_id, o_id', + new_orders => 'no_w_id, no_d_id, no_o_id', + order_line => 'ol_w_id, ol_d_id, ol_o_id, ol_number', +); + +# Poll $table's row count on $node_b until it matches $node_a's (bounded); +# used to let replication drain before a data comparison, since while a +# load generator is active a node's row counts are a moving target. +sub wait_for_table_drain { + my ($node_a, $node_b, $table, $timeout) = @_; + $timeout //= 120; + my $count_a = scalar_query($node_a, "SELECT COUNT(*) FROM $table"); + for (1 .. $timeout) { + my $count_b = scalar_query($node_b, "SELECT COUNT(*) FROM $table"); + return 1 if defined $count_b && $count_b eq $count_a; + sleep(1); + } + return 0; +} + +# Compare every wholesale table between two nodes: row count, and a full +# content hash (md5 of every row's text representation, concatenated in +# primary-key order) -- two assertions per table. Row count alone would +# miss a bug that swapped or corrupted row content without changing the +# row total; hashing every table (not just one) closes that gap. +sub verify_data_consistency { + my ($node_a, $label_a, $node_b, $label_b) = @_; + for my $t (@wholesale_tables) { + my $count_a = scalar_query($node_a, "SELECT COUNT(*) FROM $t"); + my $count_b = scalar_query($node_b, "SELECT COUNT(*) FROM $t"); + is($count_b, $count_a, "row count matches between $label_a and $label_b: $t"); + + my $pk = $TABLE_PK{$t}; + my $hash_query = "SELECT md5(COALESCE(string_agg(x::text, ',' " . + "ORDER BY $pk), '')) FROM $t x"; + my $hash_a = scalar_query($node_a, $hash_query); + my $hash_b = scalar_query($node_b, $hash_query); + is($hash_b, $hash_a, + "content hash matches between $label_a and $label_b: $t"); + } +} + +# ============================================================================= +# SETUP: seed n1 with the wholesale (TPC-C-like) schema+data via +# pgedge-loadgen -- 9 tables, every one with an explicit primary key (so +# every table gets a usable REPLICA IDENTITY), ~600k rows, ~120MB. The +# --size floor for this app does not shrink below that regardless of the +# value passed, so a fixed small value is used for every load level; only +# the concurrency of the later `run` phase varies by level. +# ============================================================================= +my $loadgen_log = "$log_dir/pgedge_loadgen.log"; +unlink($loadgen_log) if -f $loadgen_log; + +command_ok( + [ $LOADGEN_BIN, 'init', '--app', 'wholesale', '--size', '20MB', + '--drop-existing', '--connection', $n3_provider_uri, + '--log-level', 'warn' ], + 'loadgen schema+data initialized on n1' +); + +# Marker table for the final bidirectional-dataflow proof below, kept +# separate from the loadgen tables so that check does not depend on any of +# pgedge-loadgen's own FK/PK shapes. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE load_test_marker (id serial primary key, val text)"; +pass('marker table created on n1'); + +# Wait for the full initial bulk load (schema DDL + ~600k rows) to drain to +# n2 before touching anything else -- item is untouched by the `run` +# workload later, so its count is a clean, stable proxy for "the bulk load +# has fully replicated". +my $item_count_n1 = scalar_query(1, "SELECT COUNT(*) FROM item"); +my $item_on_n2 = '-1'; +for (1 .. 180) { + $item_on_n2 = scalar_query(2, "SELECT COUNT(*) FROM item"); + last if $item_on_n2 eq $item_count_n1; + sleep(1); +} +is($item_on_n2, $item_count_n1, 'loadgen tables replicated to n2'); + +my $marker_on_n2 = '-1'; +for (1 .. 30) { + $marker_on_n2 = scalar_query(2, + "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'load_test_marker'"); + last if $marker_on_n2 eq '1'; + sleep(1); +} +is($marker_on_n2, '1', 'marker table replicated to n2'); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting scenario 1') + or BAIL_OUT('n1->n2 replication never drained after the initial bulk load; ' . + 'cannot proceed to --bidirectional under load'); + +# ============================================================================= +# SCENARIO 1: join under load, with a handful of non-default options +# (--stall-timeout, --max-wait, and a valid --extra-basebackup-args) that +# 070_bidir_plumbing.pl only ever exercises against a quiescent cluster. +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_load_s1'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +# n3's postgresql.conf is copied verbatim from n1 by the basebackup, port and +# all; override it with n3's own port, same as 070_bidir_plumbing.pl. +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.load'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log_1 = "$log_dir/scs_scenario1.log"; +unlink($scs_log_1) if -f $scs_log_1; + +my $scs_pid = spawn_background($scs_log_1, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '600', + '--extra-basebackup-args', '--label=spock_bidir_load_test', + '-v', +); + +ok(wait_for_slot_created($n3_pending, $n3_manifest, 30), + 'source slot created (safe to resume load)') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log_1); + +my $loadgen_run_log_1 = "$log_dir/pgedge_loadgen_run_s1.log"; +unlink($loadgen_run_log_1) if -f $loadgen_run_log_1; +my $loadgen_pid = spawn_background($loadgen_run_log_1, + $LOADGEN_BIN, 'run', '--app', 'wholesale', + '--connections', $load_connections, + '--profile', 'global', + '--report-interval', '30', + '--connection', $n3_provider_uri, + '--log-level', 'info', +); + +my $scs_rc_1 = wait_for_pid($scs_pid, 780); +unless (defined $scs_rc_1) { + diag("spock_create_subscriber (scenario 1) did not exit within 780s; killing it"); + terminate_child($scs_pid); + $scs_rc_1 = -1; +} +is($scs_rc_1, 0, "--bidirectional (under $load_level load) exits 0") + or diag("see $scs_log_1 and $loadgen_run_log_1"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); + +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription sub_n3_n2 is replicating on n3'); +ok(wait_for_sub_status(2, 'sub_n2_n3', 'replicating', 30), + 'reverse subscription sub_n2_n3 is replicating on n2'); +ok(wait_for_sub_status(1, 'sub_n1_n3', 'replicating', 30), + 'reverse subscription sub_n1_n3 is replicating on n1'); + +my $readonly = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SHOW spock.readonly"); +is($readonly, 'off', 'spock.readonly is lifted on n3'); + +# Stop the load generator and let replication fully drain -- to both n3 +# (the node that just joined) and n2 (the pre-existing peer, which has +# been receiving the same load-driven writes the whole time) -- before +# comparing data; while `run` is active, row counts are a moving target. +# order_line sees the heaviest per-transaction churn (new_order inserts +# several rows per order), so it is used as the drain signal for the +# whole batch on each node. +stop_loadgen($loadgen_pid, $loadgen_run_log_1); + +diag('replication did not fully drain to n3 within 120s after stopping the load generator') + unless wait_for_table_drain(1, 3, 'order_line'); +diag('replication did not fully drain to n2 within 120s after stopping the load generator') + unless wait_for_table_drain(1, 2, 'order_line'); + +verify_data_consistency(1, 'n1', 3, 'n3'); +verify_data_consistency(1, 'n1', 2, 'n2'); + +# Fresh bidirectional dataflow, now that the join is fully settled and load +# has stopped -- proves the mesh is genuinely live, not just "exited 0". +# Explicit, non-colliding ids: load_test_marker's serial sequence is local +# to each node (its value isn't part of what a join round-trips), so an +# id-less insert on n3 and then on n1 would both independently produce +# id=1 and collide once the n3-side row replicates back -- the same pitfall +# 070_bidir_plumbing.pl documents and works around for pr4_peer_tbl. +system_or_bail "$pg_bin/psql", '-p', $n3_port, '-d', $dbname, '-c', + "INSERT INTO load_test_marker (id, val) VALUES (2000, 'from_n3_after_load_join')"; +my $marker_on_n1 = '0'; +for (1 .. 30) { + $marker_on_n1 = scalar_query(1, + "SELECT COUNT(*) FROM load_test_marker WHERE val = 'from_n3_after_load_join'"); + last if $marker_on_n1 eq '1'; + sleep(1); +} +is($marker_on_n1, '1', 'fresh write on n3 reaches n1 (marker table)'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "INSERT INTO load_test_marker (id, val) VALUES (3000, 'from_n1_after_load_join')"; +my $marker_on_n3 = '0'; +for (1 .. 30) { + $marker_on_n3 = scalar_query(3, + "SELECT COUNT(*) FROM load_test_marker WHERE val = 'from_n1_after_load_join'"); + last if $marker_on_n3 eq '1'; + sleep(1); +} +is($marker_on_n3, '1', 'fresh write on n1 reaches n3 (marker table)'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster (scenario 1 teardown)'); +ok(!-d $n3_datadir, 'n3 data directory removed after scenario 1 cleanup'); + +# ============================================================================= +# SCENARIO 2: a join that fails part-way (deliberately broken +# --extra-basebackup-args, same trick as 070_bidir_plumbing.pl) while n1 is +# under load, orphaning a source slot -- then --cleanup must +# recover it while that load is still running, not just once it has +# stopped. +# ============================================================================= +ok(wait_for_zero_lag(1, 60), 'replication drained before starting scenario 2') + or BAIL_OUT('n1->n2 replication never drained after scenario 1; ' . + 'cannot proceed to scenario 2'); + +my $n3_datadir_2 = '/tmp/tmp_spock_node_2_datadir_bidir_load_s2'; +my $n3_pending_2 = "${n3_datadir_2}.spock_bidir_pending.json"; +# The broken --extra-basebackup-args below means the backup never succeeds +# and the real manifest is never written, so this path never comes into +# existence for this scenario -- present here only for symmetry with +# wait_for_slot_created()'s signature. +my $n3_manifest_2 = "$n3_datadir_2/spock_bidirectional_manifest.json"; +remove_tree($n3_datadir_2) if -d $n3_datadir_2; +unlink($n3_pending_2) if -f $n3_pending_2; + +my $scs_log_2 = "$log_dir/scs_scenario2.log"; +unlink($scs_log_2) if -f $scs_log_2; + +my $scs_pid_2 = spawn_background($scs_log_2, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir_2, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--extra-basebackup-args', '--waldir=/nonexistent_pr3_load_test_waldir', +); + +ok(wait_for_slot_created($n3_pending_2, $n3_manifest_2, 30), + 'source slot created for scenario 2 (safe to resume load)') + or BAIL_OUT('spock_create_subscriber never created the source slot for ' . + "scenario 2; see $scs_log_2"); + +my $loadgen_run_log_2 = "$log_dir/pgedge_loadgen_run_s2.log"; +unlink($loadgen_run_log_2) if -f $loadgen_run_log_2; +my $loadgen_pid_2 = spawn_background($loadgen_run_log_2, + $LOADGEN_BIN, 'run', '--app', 'wholesale', + '--connections', $load_connections, + '--profile', 'global', + '--report-interval', '30', + '--connection', $n3_provider_uri, + '--log-level', 'info', +); + +my $scs_rc_2 = wait_for_pid($scs_pid_2, 120); +my $scs_2_timed_out = !defined $scs_rc_2; +if ($scs_2_timed_out) { + diag("spock_create_subscriber (scenario 2) did not exit within 120s; killing it"); + terminate_child($scs_pid_2); +} +# A hang is not the expected failure: it must not count as a nonzero exit. +ok(!$scs_2_timed_out && $scs_rc_2 > 0 && $scs_rc_2 < 128, + 'a broken --extra-basebackup-args makes the utility exit with an error ' + . '(under load), not hang or die by signal'); +{ + my $log_2 = do { local $/; open my $lf, '<', $scs_log_2 or die "$scs_log_2: $!"; <$lf> }; + like($log_2, qr/pg_basebackup failed with exit status/, + 'the failure is the injected pg_basebackup error'); +} + +my $slot_after_failed_backup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +ok($slot_after_failed_backup >= 1, + 'source slot orphaned on n1 after the failed backup (under load)'); + +# The whole point of this scenario: --cleanup must work while n1 is +# still under active write load, not just once it has quiesced. +command_ok( + [ $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $n3_datadir_2 ], + '--cleanup recovers the orphaned slot while n1 is under load' +); + +stop_loadgen($loadgen_pid_2, $loadgen_run_log_2); + +my $slot_after_cleanup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($slot_after_cleanup, '0', 'source slot removed from n1 after cleanup'); + +remove_tree($n3_datadir_2) if -d $n3_datadir_2; +unlink($n3_pending_2) if -f $n3_pending_2; + +# ============================================================================= +# SCENARIO 3: join with deliberately injected replication lag on the +# catchup subscription (sub_n3_n1), on top of the same write load as +# scenario 1 -- proving wait_for_catchup()/the coverage barrier's +# stall-timeout logic correctly tolerates a steady, bounded lag (a +# continuous trickle of small LSN advances) rather than mistaking it for a +# stall, and that --max-wait is honored as an upper bound rather than +# fired early. +# +# apply_delay (spock_apply.c) holds each transaction back until +# apply_delay has elapsed past its own origin commit timestamp; the value +# is read from the subscription row only when the apply worker (re)starts +# (spock_apply.c ApplyWorkerMain), so it has no effect until then. +# spock.sub_alter_options(..., '{"apply_delay": "..."}'::jsonb) +# (spock_functions.c) updates the row and forces exactly that reconnect, +# so the delay takes effect from the point of the ALTER forward -- there +# is no CLI flag for this in --bidirectional (--apply-delay only wires +# into the plain, non-bidirectional path), so it is injected here +# directly against n3's catalog once the row exists, polling rather than +# guessing the timing since the row exists (disabled, then enabled) partway +# through the join and there is no external signal for exactly when. +# ============================================================================= +ok(wait_for_zero_lag(1, 60), 'replication drained before starting scenario 3') + or BAIL_OUT('n1->n2 replication never drained after scenario 2; ' . + 'cannot proceed to scenario 3'); + +my $n3_datadir_3 = '/tmp/tmp_spock_node_2_datadir_bidir_load_s3'; +my $n3_pending_3 = "${n3_datadir_3}.spock_bidir_pending.json"; +my $n3_manifest_3 = "$n3_datadir_3/spock_bidirectional_manifest.json"; +remove_tree($n3_datadir_3) if -d $n3_datadir_3; +unlink($n3_pending_3) if -f $n3_pending_3; + +my $scs_log_3 = "$log_dir/scs_scenario3.log"; +unlink($scs_log_3) if -f $scs_log_3; + +my $apply_delay_seconds = 5; +my $scenario3_start = time(); + +my $scs_pid_3 = spawn_background($scs_log_3, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir_3, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '600', +); + +ok(wait_for_slot_created($n3_pending_3, $n3_manifest_3, 30), + 'source slot created for scenario 3 (safe to resume load)') + or BAIL_OUT('spock_create_subscriber never created the source slot for ' . + "scenario 3; see $scs_log_3"); + +my $loadgen_run_log_3 = "$log_dir/pgedge_loadgen_run_s3.log"; +unlink($loadgen_run_log_3) if -f $loadgen_run_log_3; +my $loadgen_pid_3 = spawn_background($loadgen_run_log_3, + $LOADGEN_BIN, 'run', '--app', 'wholesale', + '--connections', $load_connections, + '--profile', 'global', + '--report-interval', '30', + '--connection', $n3_provider_uri, + '--log-level', 'info', +); + +# n3's postgres comes up partway through the join (after the basebackup, +# system-identifier reset, and restart); sub_n3_n1's catalog row exists +# from create_catchup_subscription()'s first (disabled) sub_create call +# onward, well before catchup actually begins, so polling for it and +# firing the ALTER as soon as it appears lands the delay before or very +# early into the catchup wait either way. +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 120), + 'n3 postgres is running (scenario 3)'); + +sub set_sub_n3_n1_apply_delay { + my ($interval_text) = @_; + my $alter_sql = "SELECT spock.sub_alter_options('sub_n3_n1', " . + "'{\"apply_delay\": \"${interval_text}\"}'::jsonb)"; + system_or_bail "$pg_bin/psql", '-p', $n3_port, '-d', $dbname, '-c', $alter_sql; +} + +my $apply_delay_injected = 0; +for (1 .. 60) { + my $sub_exists = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT COUNT(*) FROM spock.subscription WHERE sub_name = 'sub_n3_n1'"); + if (defined $sub_exists && $sub_exists eq '1') { + set_sub_n3_n1_apply_delay("${apply_delay_seconds} seconds"); + $apply_delay_injected = 1; + last; + } + sleep(1); +} +ok($apply_delay_injected, + "injected a ${apply_delay_seconds}s apply_delay onto the catchup subscription") + or BAIL_OUT('sub_n3_n1 never appeared in spock.subscription; see ' . $scs_log_3); + +# Hold the delay for a bounded window -- long enough to prove catchup makes +# steady, delayed-but-not-stalled progress under it -- then clear it before +# clear_forwarding() does its own independent sub_alter_options()-triggered +# reconnect on this same subscription. Both apply_delay and the delay's +# 5-second-per-transaction hold-back persist across a reconnect (it is +# read from the subscription row at apply-worker startup, not reset by +# it), so leaving it set would still be in effect when that second, +# independent reconnect happens; clearing it first keeps this scenario a +# clean test of steady-lag tolerance rather than of two independent, +# uncoordinated reconnect triggers landing on the same subscription close +# together, which is a real but different (and separately worth testing) +# scenario. +my $apply_delay_hold_seconds = 15; +diag("holding the ${apply_delay_seconds}s apply_delay for " . + "${apply_delay_hold_seconds}s before clearing it"); +sleep($apply_delay_hold_seconds); +set_sub_n3_n1_apply_delay('0'); + +# Poll (rather than a single blocking wait_for_pid()) so spock.exception_log +# can be sampled every second while n3 is still reachable -- if the join +# fails, spock_create_subscriber's own die() path may or may not manage to +# stop postgres afterward before this script regains control, so querying +# only after the wait is an unreliable way to see error_message; sampling +# throughout the wait is not. +my $scs_rc_3; +my $last_exception = ''; +for (1 .. 780) { + my $r = waitpid($scs_pid_3, WNOHANG); + if ($r == $scs_pid_3) { + $scs_rc_3 = ($? >> 8); + last; + } + # A failing transaction can touch several rows/tables; only one of the + # resulting exception_log entries carries the real error, the rest are + # "discarded due to exception" collateral pointing at it via + # command_counter -- fetch every entry for the latest failing + # transaction (not just the single most recent row) so the real one is + # actually visible here rather than possibly being one of the + # collateral entries. + my $exc = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', '-F', ' | ', + '-c', "SELECT table_name, operation, command_counter, error_message " . + "FROM spock.exception_log WHERE remote_commit_ts = " . + "(SELECT max(remote_commit_ts) FROM spock.exception_log) " . + "ORDER BY command_counter"); + $last_exception = $exc if $exc ne ''; + sleep(1); +} +unless (defined $scs_rc_3) { + diag("spock_create_subscriber (scenario 3) did not exit within 780s; killing it"); + terminate_child($scs_pid_3); + $scs_rc_3 = -1; +} +is($scs_rc_3, 0, + "--bidirectional (under $load_level load, with a ${apply_delay_seconds}s catchup apply_delay) exits 0") + or diag("see $scs_log_3 and $loadgen_run_log_3 -- most recent n3 " . + "spock.exception_log entry seen during the wait: " . + ($last_exception ne '' ? $last_exception : '(none captured)')); + +# Sanity check that the delay actually had an effect rather than being +# silently ignored (e.g. a typo'd JSON key that sub_alter_options rejected +# without this script noticing) -- the join must have taken at least +# apply_delay_seconds, since the last transaction it needed to catch up to +# is held back by that much from its own commit time. +my $scenario3_elapsed = time() - $scenario3_start; +ok($scenario3_elapsed >= $apply_delay_seconds, + "scenario 3 took at least ${apply_delay_seconds}s (${scenario3_elapsed}s elapsed), " . + "confirming the injected apply_delay actually took effect"); + +stop_loadgen($loadgen_pid_3, $loadgen_run_log_3); + +diag('replication did not fully drain to n3 within 120s after stopping the load generator') + unless wait_for_table_drain(1, 3, 'order_line'); +verify_data_consistency(1, 'n1', 3, 'n3'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir_3, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster (scenario 3 teardown)'); +ok(!-d $n3_datadir_3, 'n3 data directory removed after scenario 3 cleanup'); + +# ============================================================================= +# Final sanity: n1 <-> n2 (the pre-existing bidirectional pair) must still be +# healthy after everything above -- proves the load + three join/cleanup +# cycles did not leave the original mesh in a bad state. +# ============================================================================= +my $n1n2_ok = wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30); +ok($n1n2_ok, 'n1 <-> n2 subscriptions are still replicating after the load run'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Cleanup'); + +done_testing(); diff --git a/tests/tap/t/072_bidir_join_crash_midcatchup.pl b/tests/tap/t/072_bidir_join_crash_midcatchup.pl new file mode 100644 index 000000000..0f77c0fdc --- /dev/null +++ b/tests/tap/t/072_bidir_join_crash_midcatchup.pl @@ -0,0 +1,427 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 072_bidir_join_crash_midcatchup.pl - spock_create_subscriber +# --bidirectional survives the +# utility process itself being +# killed mid-catchup +# ============================================================================= +# 070_bidir_plumbing.pl and 071_bidir_join_under_load.pl both prove --cleanup +# recovers a join that failed during the *base backup* phase (a +# deliberately broken --extra-basebackup-args). Neither kills the utility +# process itself once it is past that point and into the catchup replay -- +# the phase this session's investigation (spurious SUB_DISABLE / apply-idle- +# timeout misclassification, PR 607) was all about. The design doc's own +# resumability contract for a mid-catchup crash is "not a resumable journal": +# the practical recovery is --cleanup + a fresh basebackup, same as +# for a backup failure -- but that path was never actually exercised for a +# crash landing *after* the source slot exists and the catchup subscription +# is already replicating, only for one landing *before* the backup completes. +# +# This test seeds n1 with enough rows that the catchup replay is guaranteed +# to still be in progress a few seconds in, starts --bidirectional in the +# background, waits until n3's catchup subscription (sub_n3_n1) is +# genuinely mid-replay (present, replicating, and only partially caught up), +# then SIGKILLs the utility process outright -- no SIGTERM, no chance for +# graceful shutdown -- and verifies: --cleanup still recovers +# cleanly (source slot removed, data directory removed); the pre-existing +# n1<->n2 mesh is unaffected; and a fresh --bidirectional retry against the +# same source afterward succeeds end-to-end with correct data, proving the +# cluster is genuinely left in a rejoinable state, not just "cleaned up". +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub psql_capture { + my (@args) = @_; + open(my $fh, '-|', "$pg_bin/psql", @args) or die "cannot run psql: $!"; + local $/; + my $out = <$fh>; + close $fh; + $out //= ''; + $out =~ s/^\s+|\s+$//g; + return $out; +} + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so terminate_child() reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +# Stop a child started by spawn_background() and its own children (the +# utility runs pg_basebackup and pg_ctl through system()): TERM the process +# group, allow a grace period, then KILL it, and always reap. A bare +# waitpid() after TERM can block for as long as the backup takes to finish. +sub terminate_child { + my ($pid) = @_; + + # kill(sig, 0) signals this process's own group, which must never happen + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +# Poll a log file's content for a pattern (rather than a fixed offset read) +# since the file may not exist yet when polling starts. +sub wait_for_log_pattern { + my ($logfile, $pattern, $timeout) = @_; + for (1 .. $timeout) { + if (-f $logfile) { + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return 1 if defined $content && $content =~ $pattern; + } + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP: a continuous writer on n1, so catchup always has a growing WAL +# delta to replay. --bidirectional does a *physical* basebackup first -- +# a one-time seed inserted before the join is already present in that +# backup, leaving nothing for the logical catchup subscription to actually +# replay (confirmed empirically: a 400k-row one-time seed made catchup +# resolve instantly, giving no window to interrupt at all). Only rows +# written *during* the join, after the backup's start LSN, are real +# catchup work. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE crash_test_tbl (id bigint PRIMARY KEY, val text)"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE SEQUENCE crash_test_id_seq"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', q{ + CREATE PROCEDURE crash_test_load(n_batches int, batch_rows int) + LANGUAGE plpgsql AS $$ + DECLARE i int; + BEGIN + FOR i IN 1..n_batches LOOP + INSERT INTO crash_test_tbl + SELECT nextval('crash_test_id_seq'), 'x' || g + FROM generate_series(1, batch_rows) g; + COMMIT; + PERFORM pg_sleep(0.02); + END LOOP; + END $$; +}; +pass('crash_test_tbl and writer procedure created on n1'); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1->n2 replication never drained after setup; cannot proceed'); + +# The writer is started only after --bidirectional's own +# check_preconditions() has already passed (see wait_for_slot_created() +# below) -- it hard-rejects up front if the source has *any* unreplicated +# changes pending to an existing peer, so starting it any earlier makes +# every run fail before n3's postgres even comes up (confirmed +# empirically). Kept running through the rest of the physical backup and +# into catchup, then stopped (server-side) once the kill has landed. Same +# technique as 046_apply_worker_exception_misclassification.pl and +# 073_bidir_join_multipeer_lag.pl: killing the client process alone does +# not reliably stop a backend mid-CALL. +my $writer_pid; + +sub start_writer { + $writer_pid = spawn_background("$log_dir/crash_test_writer.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, + '-c', "CALL crash_test_load(100000, 3000)"); +} + +sub stop_writer { + system_or_bail "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity " . + "WHERE query LIKE 'CALL crash_test_load%' AND pid <> pg_backend_pid()"; + for (1 .. 30) { + my $still_running = scalar_query(1, + "SELECT count(*) FROM pg_stat_activity WHERE query LIKE 'CALL crash_test_load%'"); + last if defined $still_running && $still_running eq '0'; + sleep(1); + } + terminate_child($writer_pid); +} + +# ============================================================================= +# TEST: start --bidirectional, kill it mid-catchup, confirm --cleanup +# recovers cleanly +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_crash'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +# The pending-cleanup sidecar is written immediately after the source slot +# is created, i.e. immediately after check_preconditions() has already +# passed -- polling for it (or the real manifest, in case it lands between +# polls) is the same technique 071_bidir_join_under_load.pl uses to know +# it is now safe to resume write load against the source. +sub wait_for_slot_created { + my ($timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $n3_pending || -f $n3_manifest; + sleep(1); + } + return 0; +} + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.crash'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_crash_midcatchup.log"; +unlink($scs_log) if -f $scs_log; + +my $scs_pid = spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '600', +); + +# On a failed wait, stop everything this test started before bailing out: the +# join (and its children), the server-side writer, and the join's own +# slot/subscriptions via --cleanup. Otherwise they outlive the test +# and break the next run. +sub abort_run { + my ($msg) = @_; + terminate_child($scs_pid); + eval { stop_writer(); 1 } if defined $writer_pid; + system_maybe($SCS_BIN, '--bidirectional', '--cleanup', + '--pgdata', $n3_datadir); + BAIL_OUT($msg); +} + +ok(wait_for_slot_created(30), 'source slot created (safe to start the writer)') + or abort_run('spock_create_subscriber never created the source slot; see ' . $scs_log); +start_writer(); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 60), + 'n3 postgres is running (pre-kill)') + or abort_run('n3 postgres never came up; see ' . $scs_log); + +# Wait until spock_create_subscriber's own log shows it has entered the +# catchup wait -- sub_n3_n1 exists, is enabled, and wait_for_catchup() is +# now polling its progress against a fixed target LSN captured moments +# earlier. The writer has been running since the source slot was created +# (well before this point: the physical backup transfer, restore-point +# dance, and n3 postgres restart all happen in between), so the target +# captured is already a large, real backlog -- no margin sleep here on +# purpose: with an idle peer (n2) the coverage barrier and clear_forwarding +# phases that follow catchup are fast, so killing as early as possible +# (the instant this line appears) rather than after any extra delay is +# what keeps this test inside the catchup wait specifically, rather than +# racing into later phases. +ok(wait_for_log_pattern($scs_log, qr/Waiting for catchup to the source/, 120), + 'spock_create_subscriber reached the catchup wait phase') + or abort_run('never reached the catchup wait phase; see ' . $scs_log); + +# The harshest interruption: no SIGTERM, no chance to run any cleanup path +# at all -- a genuine crash, not a graceful stop. +kill('KILL', $scs_pid); +waitpid($scs_pid, 0); +pass('spock_create_subscriber process killed (SIGKILL) mid-catchup'); + +stop_writer(); + +my $final_count = scalar_query(1, "SELECT COUNT(*) FROM crash_test_tbl"); +ok(defined $final_count && $final_count > 0, + "writer produced $final_count rows on n1 before being stopped"); + +my $source_slot_after_kill = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +ok($source_slot_after_kill >= 1, + 'source slot on n1 survives the kill (orphaned, as expected)'); + +command_ok( + [ $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $n3_datadir ], + '--cleanup exits 0 after a mid-catchup kill' +); + +my $source_slot_after_cleanup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($source_slot_after_cleanup, '0', 'source slot removed from n1 after cleanup'); + +ok(-d $n3_datadir, 'n3 data directory kept by --cleanup'); +remove_tree($n3_datadir); + +ok(!wait_for_pg_ready($host, $n3_port, $pg_bin, 5), + 'n3 postgres is no longer reachable after cleanup'); + +my $n1n2_ok_after_kill = wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30); +ok($n1n2_ok_after_kill, + 'pre-existing n1 <-> n2 mesh is unaffected by the crash + cleanup cycle'); + +# ============================================================================= +# TEST: a fresh --bidirectional retry against the same source succeeds -- +# the cluster is genuinely rejoinable, not just "cleaned up". +# ============================================================================= +ok(wait_for_zero_lag(1, 60), 'replication drained before the retry') + or BAIL_OUT('n1->n2 replication never drained after cleanup; cannot retry'); + +my $scs_log_retry = "$log_dir/scs_crash_midcatchup_retry.log"; +unlink($scs_log_retry) if -f $scs_log_retry; + +my $scs_pid_retry = spawn_background($scs_log_retry, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '600', +); + +my $scs_rc_retry = wait_for_pid($scs_pid_retry, 300); +unless (defined $scs_rc_retry) { + diag("spock_create_subscriber (retry) did not exit within 300s; killing it"); + terminate_child($scs_pid_retry); + $scs_rc_retry = -1; +} +is($scs_rc_retry, 0, 'fresh --bidirectional retry after the crash exits 0') + or diag("see $scs_log_retry"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running (retry)'); +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3 (retry)'); + +my $n3_count_retry = '-1'; +for (1 .. 60) { + $n3_count_retry = scalar_query(3, "SELECT COUNT(*) FROM crash_test_tbl"); + last if $n3_count_retry eq $final_count; + sleep(1); +} +is($n3_count_retry, $final_count, 'all rows present on n3 after the retry'); + +my $hash_n1 = scalar_query(1, + "SELECT md5(COALESCE(string_agg(x::text, ',' ORDER BY id), '')) FROM crash_test_tbl x"); +my $hash_n3 = scalar_query(3, + "SELECT md5(COALESCE(string_agg(x::text, ',' ORDER BY id), '')) FROM crash_test_tbl x"); +is($hash_n3, $hash_n1, 'content hash matches between n1 and n3 after the retry'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster (final teardown)'); +ok(!-d $n3_datadir, 'n3 data directory removed after final cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/073_bidir_join_multipeer_lag.pl b/tests/tap/t/073_bidir_join_multipeer_lag.pl new file mode 100644 index 000000000..867cfc258 --- /dev/null +++ b/tests/tap/t/073_bidir_join_multipeer_lag.pl @@ -0,0 +1,483 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 073_bidir_join_multipeer_lag.pl - spock_create_subscriber +# --bidirectional's coverage barrier +# genuinely waits for EVERY existing +# peer, not just the fastest one +# ============================================================================= +# establish_peer_coverage_barrier() (spock_create_subscriber.c) has two +# steps: Hop 1, per peer P, waits for a sync_event emitted on P to land on +# the source (n1); Hop 2, once, fires only after every peer's Hop 1 has +# landed, and cuts the new node over to direct replication. Both +# 070_bidir_plumbing.pl and 071_bidir_join_under_load.pl only ever join a new +# node into a 2-node mesh (n1 + one peer, n2) -- with exactly one peer, the +# "wait for EVERY peer" condition in Hop 2 is vacuously true on every run. A +# bug that fired Hop 2 as soon as *any* single peer's Hop 1 landed, instead +# of *all* of them, would not be caught by either test. +# +# This test builds a genuine 3-node pre-existing mesh (n1, n2, n3, fully +# cross-wired) and keeps n3 under sustained write load throughout the join +# of a 4th node (n4, via n1 as source) -- so n1's replay of n3's changes is +# backlogged right at the moment the coverage barrier runs, while n2 (idle) +# clears its Hop 1 almost immediately. If Hop 2 fired as soon as n2's Hop 1 +# landed, n4 would be cut over to direct replication from n1/n2/n3 before +# n3's backlog had fully passed through n1's forwarding path -- a real, +# permanent gap: n4 would end up missing some of n3's rows relative to n3 +# itself, even though n4 matches n1 and n2 exactly. Comparing n4 to n3 +# specifically (not just to n1/n2, which 070/071 already do) is therefore +# the correctness assertion that actually exercises this: it fails if the +# barrier raced ahead, and passes only if it genuinely waited for n3. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 3-node cluster, fully cross-wired (n1 <-> n2 <-> n3 <-> n1) +# ============================================================================= +create_cluster(3, 'Create 3-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(3, ['n1', 'n2', 'n3'], 'Cross-wire n1 <-> n2 <-> n3'); + +sub psql_capture { + my (@args) = @_; + open(my $fh, '-|', "$pg_bin/psql", @args) or die "cannot run psql: $!"; + local $/; + my $out = <$fh>; + close $fh; + $out //= ''; + $out =~ s/^\s+|\s+$//g; + return $out; +} + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so terminate_child() reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +# Stop a child started by spawn_background() and its own children (the +# utility runs pg_basebackup and pg_ctl through system()): TERM the process +# group, allow a grace period, then KILL it, and always reap. A bare +# waitpid() after TERM can block for as long as the backup takes to finish. +sub terminate_child { + my ($pid) = @_; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_table_drain { + my ($node_a, $node_b, $table, $timeout) = @_; + $timeout //= 180; + my $count_a = scalar_query($node_a, "SELECT COUNT(*) FROM $table"); + for (1 .. $timeout) { + my $count_b = scalar_query($node_b, "SELECT COUNT(*) FROM $table"); + return 1 if defined $count_b && $count_b eq $count_a; + sleep(1); + } + return 0; +} + +# Poll a log file's content for a pattern (rather than a fixed offset read) +# since the file may not exist yet when polling starts. +sub wait_for_log_pattern { + my ($logfile, $pattern, $timeout) = @_; + for (1 .. $timeout) { + if (-f $logfile) { + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return time() if defined $content && $content =~ $pattern; + } + sleep(1); + } + return undef; +} + +# ============================================================================= +# SETUP: a table replicated across the existing 3-node mesh via DDL +# replication, to be under sustained write load on n3 throughout n4's join. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE lag_peer_tbl (id bigint PRIMARY KEY, val text)"; +pass('lag_peer_tbl created on n1'); + +for my $peer_node (2, 3) { + my $on_peer = '0'; + for (1 .. 30) { + $on_peer = scalar_query($peer_node, + "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'lag_peer_tbl'"); + last if $on_peer eq '1'; + sleep(1); + } + is($on_peer, '1', "lag_peer_tbl replicated to n$peer_node"); +} + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[2], '-d', $dbname, '-c', + "CREATE SEQUENCE lag_peer_id_seq"; + +# A PROCEDURE (not a DO block) can issue its own internal COMMITs, so a +# single long-lived connection on n3 produces a continuous stream of +# separately committed transactions for as long as this test needs a +# backlog to exist -- same technique as 046_apply_worker_exception_ +# misclassification.pl's mid-transaction-restart repro. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[2], '-d', $dbname, '-c', q{ + CREATE PROCEDURE lag_peer_load(n_batches int, batch_rows int) + LANGUAGE plpgsql AS $$ + DECLARE i int; + BEGIN + FOR i IN 1..n_batches LOOP + INSERT INTO lag_peer_tbl + SELECT nextval('lag_peer_id_seq'), 'x' || g + FROM generate_series(1, batch_rows) g; + COMMIT; + -- Throttled deliberately: n3 is in a full mesh, so n2 also + -- applies every one of these rows via its own subscription, + -- inflating n2's own WAL and hence n1's (idle-peer) lag to + -- n2 as a side effect. An unthrottled writer here overwhelms + -- the whole cluster, not just n3 (confirmed empirically: without + -- this sleep, the pre-flight lag gate below tripped on n2, not + -- the intended target n3). + PERFORM pg_sleep(0.02); + END LOOP; + END $$; +}; + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1 outbound replication never drained after setup; cannot proceed'); + +# Started only after --bidirectional's own check_preconditions() has +# already passed (see wait_for_slot_created() below) -- it hard-rejects up +# front if the *source* (n1) has any unreplicated changes pending to an +# existing peer. This writer targets n3, not n1, so it may not actually +# trip that specific check, but 072_bidir_join_crash_midcatchup.pl hit +# exactly this failure mode empirically for a same-node case, and starting +# late here costs nothing (n1's replication is already drained above) -- +# not worth relitigating precisely which lag check_preconditions() looks +# at. Kept running through the rest of the join; stopped server-side +# afterward (pg_terminate_backend), same as 072 and 046 -- killing the +# client process alone does not reliably stop a backend mid-CALL. +my $writer_pid; + +sub start_writer { + $writer_pid = spawn_background("$log_dir/lag_peer_writer.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[2], '-d', $dbname, + '-c', "CALL lag_peer_load(100000, 500)"); +} + +# ============================================================================= +# TEST: join n4 via n1 while n3 is lagging behind on its own writes +# ============================================================================= +my $n4_port = $node_ports->[2] + 1; +my $n4_datadir = '/tmp/tmp_spock_node_3_datadir_bidir_multipeer'; +track_datadir($n4_datadir); +my $n4_pending = "${n4_datadir}.spock_bidir_pending.json"; +my $n4_manifest = "$n4_datadir/spock_bidirectional_manifest.json"; +my $n4_dsn = "host=$host port=$n4_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n4_datadir) if -d $n4_datadir; +unlink($n4_pending) if -f $n4_pending; + +sub wait_for_slot_created { + my ($timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $n4_pending || -f $n4_manifest; + sleep(1); + } + return 0; +} + +my $n4_conf = '/tmp/tmp_spock_node_3_postgresql.conf.override.multipeer'; +open my $conf_fh, '>', $n4_conf or die "Cannot write $n4_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n4_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n4_port}.log'\n"; +close $conf_fh; + +# The source's subscriptions must all select the same replication sets; +# otherwise the forwarded and direct paths could select different changes. +{ + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE spock.subscription SET sub_replication_sets = ARRAY['default','default_insert_only']" + . " WHERE sub_name = 'sub_n1_n2'"; + my $out = `"$SCS_BIN" --bidirectional --pgdata "$n4_datadir" --subscriber-name n4 --provider-dsn "$n1_dsn" --subscriber-dsn "$n4_dsn" --postgresql-conf "$n4_conf" 2>&1`; + isnt($? >> 8, 0, 'a source whose subscriptions select different replication sets is rejected'); + like($out, qr/do not all select the same replication sets \(\{ddl_sql,default,default_insert_only\}, \{default,default_insert_only\}\)/, + 'the rejection lists the differing selections'); + is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n4%'"), + '0', 'no source slot was created'); + ok(!-d $n4_datadir, 'no data directory was created'); + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE spock.subscription SET sub_replication_sets = ARRAY['default','default_insert_only','ddl_sql']" + . " WHERE sub_name = 'sub_n1_n2'"; +} + +my $scs_log = "$log_dir/scs_multipeer.log"; +unlink($scs_log) if -f $scs_log; + +my $scs_pid = spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n4_datadir, + '--subscriber-name', 'n4', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n4_dsn, + '--postgresql-conf', $n4_conf, + '--stall-timeout', '120', + '--max-wait', '600', +); + +ok(wait_for_slot_created(30), 'source slot created (safe to start the n3 writer)') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log); + +# Hold n3's changes back from n1 so the barrier has a known, pending peer +# transaction to wait for, instead of relying on the load happening to +# outrun n1's apply. An open transaction holding an exclusive lock on the +# table blocks sub_n1_n3's apply worker at its first row (the subscription +# stays enabled; the utility refuses a disabled one), so Hop 1 for n3 cannot +# land until the lock is released. +my $lock_pid = spawn_background("$log_dir/lag_peer_lock.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, '-c', + "BEGIN; LOCK TABLE lag_peer_tbl IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(3600)"); +my $locked = 0; +for (1 .. 30) { + $locked = scalar_query(1, + "SELECT count(*) FROM pg_locks l JOIN pg_class c ON c.oid = l.relation " . + "WHERE c.relname = 'lag_peer_tbl' AND l.mode = 'AccessExclusiveLock' AND l.granted"); + last if $locked ne '0'; + sleep(1); +} +isnt($locked, '0', 'n1 holds an exclusive lock on lag_peer_tbl (n3 held back from n1)'); +start_writer(); + +my $barrier_start = wait_for_log_pattern($scs_log, + qr/Establishing peer coverage barrier/, 120); +ok(defined $barrier_start, 'coverage barrier phase started') + or diag("see $scs_log"); + +# The utility handles the peers in turn. Reaching n3's Hop 1 means n2's has +# already landed, so what is left blocking the join is n3 alone. +ok(wait_for_log_pattern($scs_log, + qr/catch up to peer "n2"\.\.\.\n.*Waiting for the source to catch up to peer "n3"/s, 120), + "n2's Hop 1 landed on n1; the join is now waiting on n3") + or diag("see $scs_log"); + +# The barrier is now running against a peer whose writes n1 does not have. +# It must not cut over while that is so. +sleep(15); +is(waitpid($scs_pid, WNOHANG), 0, + 'the join is still waiting while n3 is held back from n1'); +ok(!wait_for_log_pattern($scs_log, qr/Clearing forwarding on the catchup subscription/, 1), + 'the join did not cut over while n3 was held back from n1'); +# (n1's own copy of the table cannot be counted while it is locked.) n3 has +# committed rows, and n1's apply of them is blocked on the lock. +my $held_n3 = scalar_query(3, "SELECT COUNT(*) FROM lag_peer_tbl"); +cmp_ok($held_n3, '>', 0, "n3 has committed $held_n3 rows that n1 cannot apply yet") + or diag("see $log_dir/lag_peer_writer.log"); + +system_or_bail "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity " . + "WHERE query LIKE '%pg_sleep(3600)%' AND pid <> pg_backend_pid()"; +terminate_child($lock_pid); +pass('n1 resumes applying n3 (lock released)'); + +my $scs_rc = wait_for_pid($scs_pid, 780); +unless (defined $scs_rc) { + diag("spock_create_subscriber (multipeer) did not exit within 780s; killing it"); + terminate_child($scs_pid); + $scs_rc = -1; +} +is($scs_rc, 0, '--bidirectional (3-peer mesh, one peer lagging) exits 0') + or diag("see $scs_log and $log_dir/lag_peer_writer.log"); + +# The join waited (asserted above, while n1 held the lock) and then went on +# to cut over once n1 could apply n3's writes again. +ok(wait_for_log_pattern($scs_log, qr/Clearing forwarding on the catchup subscription/, 5), + 'the join cut over after n1 could apply n3 again'); + +ok(wait_for_pg_ready($host, $n4_port, $pg_bin, 30), 'n4 postgres is running'); +ok(wait_for_sub_status(4, 'sub_n4_n1', 'replicating', 30), + 'catchup subscription sub_n4_n1 is replicating on n4'); +ok(wait_for_sub_status(4, 'sub_n4_n2', 'replicating', 30), + 'direct peer subscription sub_n4_n2 is replicating on n4'); +ok(wait_for_sub_status(4, 'sub_n4_n3', 'replicating', 30), + 'direct peer subscription sub_n4_n3 is replicating on n4'); +ok(wait_for_sub_status(3, 'sub_n3_n4', 'replicating', 30), + 'reverse subscription sub_n3_n4 is replicating on n3'); + +# ============================================================================= +# Stop the writer (server-side) and let everything drain before comparing. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-X', '-p', $node_ports->[2], '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity " . + "WHERE query LIKE 'CALL lag_peer_load%' AND pid <> pg_backend_pid()"; +for (1 .. 30) { + my $still_running = scalar_query(3, + "SELECT count(*) FROM pg_stat_activity WHERE query LIKE 'CALL lag_peer_load%'"); + last if defined $still_running && $still_running eq '0'; + sleep(1); +} +kill('TERM', $writer_pid); +waitpid($writer_pid, 0); +pass('n3 writer stopped'); + +diag('lag_peer_tbl did not fully drain to n1 within 180s') + unless wait_for_table_drain(3, 1, 'lag_peer_tbl'); +diag('lag_peer_tbl did not fully drain to n4 within 180s') + unless wait_for_table_drain(3, 4, 'lag_peer_tbl'); +diag('lag_peer_tbl did not fully drain to n2 within 180s') + unless wait_for_table_drain(3, 2, 'lag_peer_tbl'); + +# ============================================================================= +# THE assertion: n4 must match n3 exactly, not just n1/n2 -- this is the +# pair that only fails if the coverage barrier raced ahead of n3's backlog. +# ============================================================================= +my $hash_query = "SELECT md5(COALESCE(string_agg(x::text, ',' ORDER BY id), '')) " . + "FROM lag_peer_tbl x"; +my $count_n3 = scalar_query(3, "SELECT COUNT(*) FROM lag_peer_tbl"); +my $count_n4 = scalar_query(4, "SELECT COUNT(*) FROM lag_peer_tbl"); +is($count_n4, $count_n3, 'row count matches between n3 (lagging peer) and n4'); +my $hash_n3 = scalar_query(3, $hash_query); +my $hash_n4 = scalar_query(4, $hash_query); +is($hash_n4, $hash_n3, 'content hash matches between n3 (lagging peer) and n4'); + +my $count_n1 = scalar_query(1, "SELECT COUNT(*) FROM lag_peer_tbl"); +is($count_n4, $count_n1, 'row count matches between n1 and n4'); +my $hash_n1 = scalar_query(1, $hash_query); +is($hash_n4, $hash_n1, 'content hash matches between n1 and n4'); + +my $count_n2 = scalar_query(2, "SELECT COUNT(*) FROM lag_peer_tbl"); +is($count_n4, $count_n2, 'row count matches between n2 and n4'); +my $hash_n2 = scalar_query(2, $hash_query); +is($hash_n4, $hash_n2, 'content hash matches between n2 and n4'); + +# ============================================================================= +# Prove the n3 <-> n4 pair is a genuinely live DIRECT subscription, not just +# correct inherited catchup data -- a fresh two-way write test. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $n4_port, '-d', $dbname, '-c', + "INSERT INTO lag_peer_tbl (id, val) VALUES (900000001, 'from_n4_direct')"; +my $on_n3_direct = '0'; +for (1 .. 30) { + $on_n3_direct = scalar_query(3, + "SELECT COUNT(*) FROM lag_peer_tbl WHERE val = 'from_n4_direct'"); + last if $on_n3_direct eq '1'; + sleep(1); +} +is($on_n3_direct, '1', 'fresh write on n4 reaches n3 via the direct subscription'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[2], '-d', $dbname, '-c', + "INSERT INTO lag_peer_tbl (id, val) VALUES (900000002, 'from_n3_direct')"; +my $on_n4_direct = '0'; +for (1 .. 30) { + $on_n4_direct = scalar_query(4, + "SELECT COUNT(*) FROM lag_peer_tbl WHERE val = 'from_n3_direct'"); + last if $on_n4_direct eq '1'; + sleep(1); +} +is($on_n4_direct, '1', 'fresh write on n3 reaches n4 via the direct subscription'); + +ok(teardown_joined_node($n4_port, 'n4', $n4_datadir, + $node_ports->[0], $node_ports->[1], $node_ports->[2]), + 'n4 is taken out of the cluster'); +ok(!-d $n4_datadir, 'n4 data directory removed after cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n4_conf) if -f $n4_conf; +destroy_cluster('Destroy 3-node cluster'); + +done_testing(); diff --git a/tests/tap/t/074_bidir_join_big_txn_liveness.pl b/tests/tap/t/074_bidir_join_big_txn_liveness.pl new file mode 100644 index 000000000..bc03f4c55 --- /dev/null +++ b/tests/tap/t/074_bidir_join_big_txn_liveness.pl @@ -0,0 +1,312 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 074_bidir_join_big_txn_liveness.pl - the catchup stall watchdog must +# not fire on a healthy, merely +# slow-to-apply transaction +# ============================================================================= +# Design doc (spock_bidirectional_final.md) section 11: the Spock output +# plugin registers no streaming (in-progress-transaction) callbacks, so a +# large transaction is decoded and sent, and its origin advanced, only at +# its COMMIT. Every LSN signal wait_for_catchup()/wait_for_origin_progress() +# watches therefore freezes for as long as that one transaction is still +# being applied -- even though the apply worker is healthy and busy, not +# stalled. Before this fix, --stall-timeout was a pure LSN-progress +# watchdog and would die() on exactly this pattern; section 16 calls out a +# "big-transaction liveness" regression test for it explicitly, and it did +# not exist. +# +# This reproduces it directly: a REPLICA-only trigger with pg_sleep() on a +# table, present on n1 before the physical backup (so n3 inherits it too), +# fires only when a row is *applied* via replication -- not when n1's own +# origin transaction inserts it -- so a single, fast-committing transaction +# on n1 takes many seconds to fully apply on n3, freezing n3's catchup +# origin for that whole window. --stall-timeout is set far shorter than +# that window: without the liveness check, catchup dies well before the +# transaction finishes applying; with it, the apply worker's own +# pg_stat_activity state proves it is still busy, and the wait continues +# through to a correct, complete result. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so terminate_child() reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +# Stop a child started by spawn_background() and its own children (the +# utility runs pg_basebackup and pg_ctl through system()): TERM the process +# group, allow a grace period, then KILL it, and always reap. A bare +# waitpid() after TERM can block for as long as the backup takes to finish. +sub terminate_child { + my ($pid) = @_; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_log_pattern { + my ($logfile, $pattern, $timeout) = @_; + for (1 .. $timeout) { + if (-f $logfile) { + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return 1 if defined $content && $content =~ $pattern; + } + sleep(1); + } + return 0; +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_slot_created { + my ($pending_path, $manifest_path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $pending_path || -f $manifest_path; + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP: a table with a REPLICA-only slow trigger, present on n1 before the +# physical backup so n3 inherits it too. ENABLE REPLICA TRIGGER means it +# fires only on rows applied via replication, not on n1's own origin +# inserts -- so inserting into this table on n1 is fast, but n3 takes a +# long time to apply each row. +# ============================================================================= +my $rows = 200; +my $sleep_per_row = 0.15; +my $expected_min_seconds = int($rows * $sleep_per_row * 0.8); # generous margin + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE slow_apply_tbl (id serial primary key, val text)"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', qq{ + CREATE FUNCTION slow_apply_trigger() RETURNS trigger LANGUAGE plpgsql AS \$\$ + BEGIN + PERFORM pg_sleep($sleep_per_row); + RETURN NEW; + END \$\$; + CREATE TRIGGER slow_apply_trg BEFORE INSERT ON slow_apply_tbl + FOR EACH ROW EXECUTE FUNCTION slow_apply_trigger(); + ALTER TABLE slow_apply_tbl ENABLE REPLICA TRIGGER slow_apply_trg; +}; +pass("slow_apply_tbl with a replica-only ${sleep_per_row}s-per-row trigger created on n1"); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1->n2 replication never drained after setup; cannot proceed'); + +# ============================================================================= +# TEST: join with a --stall-timeout far shorter than the time this one +# transaction will take to apply on n3 +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_liveness'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; +# 5s used to be enough locally, but PR CI (pgEdge/spock#521) showed this +# specific file intermittently failing on the PG15 job only -- the gap +# between n1's commit and n3's handle_begin() (connection/decode startup, +# not the slow-apply loop itself) can exceed a razor-thin 5s under +# contended CI runners. 15s keeps a comfortable ~2x margin below +# $expected_min_seconds (~24s) while giving that startup gap real headroom. +my $stall_timeout = 15; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.liveness'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_liveness.log"; +unlink($scs_log) if -f $scs_log; + +my $scs_pid = spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', "$stall_timeout", + '--max-wait', '300', +); + +ok(wait_for_slot_created($n3_pending, $n3_manifest, 30), + 'source slot created (safe to insert the slow transaction)') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log); + +# The slot existing does not fix the physical recovery point: a row committed +# before the restore point is created arrives with the backup and never goes +# through the slow apply on n3. Wait for the utility to report that the +# restore point exists, so the insert lands after it and before the catchup +# target is taken. +ok(wait_for_log_pattern($scs_log, qr/Bringing subscriber node to the restore point/, 120), + 'the restore point exists (safe to insert the slow transaction)') + or do { terminate_child($scs_pid); BAIL_OUT('the join never reached its restore point; see ' . $scs_log) }; + +# Fast on n1 (the replica-only trigger does not fire for n1's own origin +# insert): a single transaction, all $rows rows, so its origin only +# advances on n3 once every row has been applied there. +my $insert_start = time(); +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "INSERT INTO slow_apply_tbl (val) SELECT 'row ' || g FROM generate_series(1, $rows) g"; +my $insert_elapsed = time() - $insert_start; +ok($insert_elapsed < $expected_min_seconds, + "the insert on n1 itself was fast (${insert_elapsed}s) -- the replica " . + "trigger did not fire for n1's own origin transaction"); + +my $join_start = time(); +my $scs_rc = wait_for_pid($scs_pid, 300); +unless (defined $scs_rc) { + diag("spock_create_subscriber did not exit within 300s; killing it"); + terminate_child($scs_pid); + $scs_rc = -1; +} +my $join_elapsed = time() - $join_start; +is($scs_rc, 0, + "--bidirectional exits 0 despite a single transaction frozen on n3 for " . + "longer than --stall-timeout=${stall_timeout}s") + or diag("see $scs_log"); + +ok($join_elapsed >= $expected_min_seconds, + "the join took at least ${expected_min_seconds}s (${join_elapsed}s elapsed), " . + "confirming the slow-apply transaction was genuinely still in flight " . + "when the join reached it, not skipped or already caught up"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3'); + +my $n1_count = scalar_query(1, "SELECT COUNT(*) FROM slow_apply_tbl"); +is($n1_count, "$rows", 'all rows present on n1'); +my $n3_count = '-1'; +for (1 .. 30) { + $n3_count = scalar_query(3, "SELECT COUNT(*) FROM slow_apply_tbl"); + last if $n3_count eq $n1_count; + sleep(1); +} +is($n3_count, $n1_count, + 'every row of the slow transaction was applied on n3, none skipped or discarded'); + +is(scalar_query(3, "SELECT COUNT(*) FROM spock.exception_log"), + '0', 'no exceptions were logged (the wait genuinely continued, not replayed/discarded)'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster'); +ok(!-d $n3_datadir, 'n3 data directory removed after cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/075_bidir_join_unbounded_peer_slot_wal.pl b/tests/tap/t/075_bidir_join_unbounded_peer_slot_wal.pl new file mode 100644 index 000000000..82f27d0fc --- /dev/null +++ b/tests/tap/t/075_bidir_join_unbounded_peer_slot_wal.pl @@ -0,0 +1,348 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 075_bidir_join_unbounded_peer_slot_wal.pl - demonstrates the +# WAL-retention exposure +# a peer slot has during +# the coverage barrier, +# currently unprotected +# ============================================================================= +# Design doc (spock_bidirectional_final.md) section 13: a peer slot created +# in Step 20 Phase A sits unconsumed -- pinning WAL and catalog_xmin on that +# peer -- until the direct subscription is enabled in Step 20.6. Section 13 +# promotes a pre-flight lag gate and a --max-slot-wal budget/abort valve to +# a v1 requirement to bound that exposure. Both were implemented, tested, +# and then deliberately reverted (see the revert commit for the "how +# necessary is this" discussion): the existing --stall-timeout + manual +# --cleanup path already bounds the exposure in the common case, just less +# precisely (by elapsed time, not actual WAL bytes) than a dedicated guard +# would, and no test had ever actually hit the gap the guard closes. +# +# This test is that missing evidence, kept independently of whether the +# guard exists: it demonstrates the exposure is real, not hypothetical, by +# measuring it directly -- keeping a peer (n2) under continuous write load +# throughout a new node's (n3's) join, and sampling n2's own peer +# replication slot's retained WAL (pg_wal_lsn_diff(pg_current_wal_lsn(), +# restart_lsn), the exact signal section 13 names) throughout the coverage +# barrier. It asserts retention grows past a threshold that would matter in +# production, and that the join still succeeds correctly despite that +# growth -- this is a resource-exposure characterization, not a +# correctness bug: nothing here should ever fail the join itself. +# +# Re-run this same test once --max-slot-wal is reintroduced (a dedicated +# follow-up per the revert commit): with the guard in place and a --max- +# slot-wal budget set below what this test currently observes, the join +# should instead abort with every peer slot dropped -- the assertions +# below would need inverting at that point, which is exactly the point of +# keeping this test around. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so terminate_child() reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +# Stop a child started by spawn_background() and its own children (the +# utility runs pg_basebackup and pg_ctl through system()): TERM the process +# group, allow a grace period, then KILL it, and always reap. A bare +# waitpid() after TERM can block for as long as the backup takes to finish. +sub terminate_child { + my ($pid) = @_; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_slot_created { + my ($pending_path, $manifest_path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $pending_path || -f $manifest_path; + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP: a table on n2, replicated to n1 via the existing mesh, kept under +# continuous write load throughout n3's join. batch-committed via a +# PROCEDURE so a single long-lived connection produces a steady stream +# rather than one huge transaction -- the exposure this test measures +# accrues across many small transactions the peer slot sits behind, not +# from any one of them being unusually large. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "CREATE TABLE peer_wal_tbl (id bigint PRIMARY KEY, val text)"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "CREATE SEQUENCE peer_wal_id_seq"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', q{ + CREATE PROCEDURE peer_wal_load(n_batches int, batch_rows int) + LANGUAGE plpgsql AS $$ + DECLARE i int; + BEGIN + FOR i IN 1..n_batches LOOP + INSERT INTO peer_wal_tbl + SELECT nextval('peer_wal_id_seq'), 'x' || g + FROM generate_series(1, batch_rows) g; + COMMIT; + PERFORM pg_sleep(0.02); + END LOOP; + END $$; +}; +pass('peer_wal_tbl and writer procedure created on n2'); + +# The peer slot spock_create_subscriber will create on n2 for n3's future +# direct subscription is a pure, deterministic function of (dbname, +# provider_node_name, sub_name) -- spock.spock_gen_slot_name() -- so its +# name is knowable before the join even starts (n3's sub-to-n2 always +# follows the sub__ convention). +my $n2_peer_slot_name = scalar_query(2, + "SELECT spock.spock_gen_slot_name('$dbname', 'n2', 'sub_n3_n2')"); +ok(length($n2_peer_slot_name) > 0, 'resolved n2 peer slot name in advance'); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1->n2 replication never drained after setup; cannot proceed'); + +# ============================================================================= +# TEST: join n3 via n1 while n2 is under continuous write load; sample the +# peer slot's own retained WAL throughout the coverage barrier. +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_unbounded_wal'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.unbounded_wal'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_unbounded_wal.log"; +unlink($scs_log) if -f $scs_log; + +my $scs_pid = spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '300', +); + +ok(wait_for_slot_created($n3_pending, $n3_manifest, 30), + 'source slot created (safe to start the n2 writer)') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log); + +my $writer_pid = spawn_background("$log_dir/peer_wal_writer.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[1], '-d', $dbname, + '-c', "CALL peer_wal_load(100000, 500)"); + +# Sample the peer slot's own retention on n2 (the exact query design doc +# section 13 names: pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) +# from the moment it appears until the join finishes. WNOHANG so this +# loop and the join proceed concurrently rather than sampling only once +# after the fact, when the slot may already be gone (consumed at cutover) +# or the window already closed. +my $max_retained_bytes = 0; +my $samples = 0; +my $join_deadline = time() + 1800; # the utility's own --max-wait does not bound this loop +my $timed_out = 0; +for (;;) { + my $r = waitpid($scs_pid, WNOHANG); + last if $r == $scs_pid; + + if (time() > $join_deadline) { + # Unresponsive utility: stop it and its children and reap it; the + # assertions and cleanup below report the failure. + $timed_out = 1; + terminate_child($scs_pid); + last; + } + + my $retained = scalar_query(2, + "SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) " . + "FROM pg_replication_slots WHERE slot_name = '$n2_peer_slot_name'"); + if (defined $retained && $retained =~ /^\d+$/) { + $samples++; + $max_retained_bytes = $retained if $retained > $max_retained_bytes; + } + sleep(1); +} +my $scs_rc = $timed_out ? q(timed out) : (($? & 127) ? 128 + ($? & 127) : ($? >> 8)); + +diag("sampled the peer slot's retained WAL $samples time(s); " . + "max observed: $max_retained_bytes byte(s)"); + +is($scs_rc, 0, '--bidirectional exits 0 despite n2 being under continuous load') + or diag("see $scs_log"); + +# The actual demonstration: without a budget guard, retention on the peer +# slot grows to a size that would matter in production while it sits +# unconsumed -- not just a few stray bytes from normal replication +# bookkeeping. 1MB is comfortably below what this test's writer produces +# over even a short barrier window (empirically tens of MB), while being +# far above any incidental noise -- a threshold this loose only fails if +# the exposure genuinely stopped growing, not from ordinary run-to-run +# timing variance. +ok($max_retained_bytes > 1024 * 1024, + "peer slot retention exceeded 1MB during the barrier " . + "(max observed: $max_retained_bytes byte(s)) -- the WAL-retention " . + "exposure design doc section 13 describes is real, not hypothetical"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription sub_n3_n2 is replicating on n3'); + +# Correctness is unaffected by the exposure -- this is a resource cost, +# not a data-safety bug. Stop the writer (server-side: killing the client +# alone does not reliably stop a backend mid-CALL) and confirm the data +# converges exactly once it drains. +system_or_bail "$pg_bin/psql", '-X', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity " . + "WHERE query LIKE 'CALL peer_wal_load%' AND pid <> pg_backend_pid()"; +for (1 .. 30) { + my $still_running = scalar_query(2, + "SELECT count(*) FROM pg_stat_activity WHERE query LIKE 'CALL peer_wal_load%'"); + last if defined $still_running && $still_running eq '0'; + sleep(1); +} +terminate_child($writer_pid); + +my $count_n2 = scalar_query(2, "SELECT COUNT(*) FROM peer_wal_tbl"); +my $count_n3 = '-1'; +for (1 .. 60) { + $count_n3 = scalar_query(3, "SELECT COUNT(*) FROM peer_wal_tbl"); + last if $count_n3 eq $count_n2; + sleep(1); +} +is($count_n3, $count_n2, + 'n3 eventually receives every row despite the unbounded retention window'); + +# n3 keeps its direct subscription to n2, so the peer slot the join created +# must still exist once the join is over. +my $peer_slot = scalar_query(2, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name = '$n2_peer_slot_name'"); +is($peer_slot, '1', "n3's direct slot on n2 ($n2_peer_slot_name) exists after cutover"); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster'); +ok(!-d $n3_datadir, 'n3 data directory removed after cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/076_bidir_join_precondition_negatives.pl b/tests/tap/t/076_bidir_join_precondition_negatives.pl new file mode 100644 index 000000000..f82d6dc1b --- /dev/null +++ b/tests/tap/t/076_bidir_join_precondition_negatives.pl @@ -0,0 +1,1423 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 076_bidir_join_precondition_negatives.pl +# spock_create_subscriber --bidirectional -- cheap pre-flight rejections +# ============================================================================= +# Design doc spock_bidirectional_final.md section 16 "Negative paths" lists a +# set of preconditions --bidirectional must reject before touching a peer's +# replication slot or the source's data directory. 070_bidir_plumbing.pl already +# covers a broken full-mesh topology and one replication-set flag mismatch; +# this file rounds out the rest of that list with scenarios that don't need +# any pause/injection machinery -- each sets up exactly one bad precondition, +# attempts the join, and asserts a clean, specific rejection, then repairs the +# precondition before moving on so later scenarios start from a known-good +# state. The final scenario is the one exception: it needs one real +# completed join, to test that a second, colliding join attempt fails clean. +# +# Topology: n1 <-> n2, the same cross-wired 2-node cluster 070 uses. +# +# Test count breakdown: +# 1 binary found +# 5 create_cluster(2) +# 1 cross_wire n1<->n2 +# -- Scenario 1: peer unreachable at discovery +# 1 --bidirectional rejects an unreachable peer +# 1 rejection reports the mesh edge to the down peer as unhealthy +# 1 n2 postgres is running again +# -- Scenario 2: track_commit_timestamp=off on the source (SKIPPED -- see +# comment at the scenario: no legal spock.conflict_resolution value +# permits track_commit_timestamp=off in this build, so no live node +# exists to test this precondition against) +# 2 skip +# -- Scenario 3: track_commit_timestamp=off on a peer (SKIPPED, same reason) +# 2 skip +# -- Scenario 4: Spock version too old +# 1 --bidirectional rejects a too-old Spock version on the source +# 1 --bidirectional rejects a too-old Spock version on a peer +# -- Scenario 5: source has unreplicated changes pending to an existing peer +# 1 --bidirectional rejects source with undrained outbound lag to a peer +# -- Scenario 6: P0.5 filter-equivalence, remaining sub-cases +# 1 --bidirectional rejects a repset table-membership mismatch +# 1 --bidirectional rejects a repset row_filter mismatch +# 1 --bidirectional rejects a repset sequence-membership mismatch +# -- Scenario 7: idempotent double-invocation +# 1 first --bidirectional join (minimal, no custom repset seeding) exits 0 +# 1 n3a postgres is running +# 1 second --bidirectional join reusing the subscriber name "n3" is rejected +# 1 the first n3's own subscription to the source is still replicating +# 1 no duplicate "n3" node row was left behind on the source +# 1 --cleanup removes the first join's state +# 1 destroy_cluster +# --- +# (new scenarios 7 (--drop-slot-if-exists), 8, 9, 10 are not counted here; +# the test uses done_testing()) +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + wait_for_sub_status + psql_or_bail wait_for_pg_ready output_plugin_libraries_conf teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_file = $config->{log_file}; +my $n1_datadir = $config->{node_datadirs}->[0]; +my $n2_datadir = $config->{node_datadirs}->[1]; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; +my $n2_dsn = "host=$host port=$node_ports->[1] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub psql_capture { + my (@args) = @_; + open(my $fh, '-|', "$pg_bin/psql", @args) or die "cannot run psql: $!"; + local $/; + my $out = <$fh>; + close $fh; + $out =~ s/^\s+|\s+$//g if defined $out; + return $out; +} + +# The die() message for every rejection below lands in this test's own log +# file (SpockTest.pm redirects every child process's stderr there), not on +# the console -- read it back after each system_maybe() to verify *why* the +# join was rejected, not just that it was. +sub log_tail_has { + my ($pattern, $since_bytes) = @_; + open(my $fh, '<', $log_file) or return ''; + seek($fh, $since_bytes, 0); + local $/; + my $tail = <$fh> // ''; + close $fh; + return $tail =~ $pattern; +} +sub log_size { + return -s $log_file // 0; +} + +# Wait for n1's outbound replication to n2 to fully drain (the same +# precondition check() itself performs) before attempting a join, so an +# earlier scenario's DDL/data doesn't leak into a later one's rejection. +sub wait_for_n1_drained { + for (1 .. 15) { + my $lag = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return if defined $lag && $lag eq '0'; + sleep(1); + } +} +wait_for_n1_drained(); + +my $port_ctr = 0; +sub fresh_datadir { + $port_ctr++; + my $dir = "/tmp/tmp_spock_node_2_datadir_bidir_pn_$port_ctr"; + remove_tree($dir) if -d $dir; + return $dir; +} + +# A rejection by the pre-flight phase must leave no trace: no slot on the +# source (counted before/after, so it does not depend on slot naming), no +# pending-cleanup sidecar, and no data directory content (pg_basebackup needs +# the directory empty, and the base backup is the expensive step to repeat). +sub slot_count { + return scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots"); +} + +sub assert_no_side_effects { + my ($dir, $slots_before, $label) = @_; + is(slot_count(), $slots_before, "$label: no slot was created on the source"); + ok(!-e "${dir}.spock_bidir_pending.json", + "$label: no pending-cleanup sidecar was written"); + my @left = -d $dir ? glob("$dir/*") : (); + ok(!@left, "$label: the data directory was left untouched"); +} + +# ============================================================================= +# Scenario 1: peer unreachable at discovery. A fully-down peer is caught by +# check_mesh_edges() -- which reads sub_n1_n2's *local* status on n1, not a +# live connection to n2 -- before check_preconditions()'s later per-peer +# connect loop is ever reached, so the actual rejection is the mesh-health +# message, not a distinct "cannot connect" one. (The narrower race this +# file cannot construct -- n1 still believes sub_n1_n2 is replicating while +# a direct TCP attempt to n2 independently fails -- is what "cannot connect +# to peer" in check_preconditions()/check_replication_set_equivalence() +# actually guards.) +# ============================================================================= +note("Scenario 1: peer unreachable at discovery"); +system_or_bail "$pg_bin/pg_ctl", 'stop', '-D', $n2_datadir, '-m', 'fast'; + +my $before = log_size(); +my $dir1 = fresh_datadir(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir1, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 100) . " dbname=$dbname"), + '--bidirectional rejects an unreachable peer'); +ok(log_tail_has(qr/no healthy \(status = 'replicating'\) subscription from "n2"/, $before), + 'rejection reports the mesh edge to the down peer as unhealthy'); +remove_tree($dir1) if -d $dir1; + +system_or_bail "$pg_bin/pg_ctl", 'start', '-D', $n2_datadir, + '-l', "$config->{log_dir}/n2_scenario1_restart.log"; +ok(wait_for_pg_ready($host, $node_ports->[1], $pg_bin, 30), 'n2 postgres is running again') + or BAIL_OUT('cannot continue without n2 back up'); +wait_for_n1_drained(); + +# ============================================================================= +# Scenario 2/3: track_commit_timestamp=off, source then peer. SKIPPED -- +# confirmed genuinely unreachable in this build, not a test-construction +# problem. spock.conflict_resolution's only enabled enum string is +# "last_update_wins" (SpockConflictResolvers[], spock.c:83-93 -- apply_remote/ +# error/keep_local/first_update_wins are all commented out pending upstream +# design work: "Disabled until we can clearly define their desired behavior. +# Jan Wieck 2024-08-12"). spock_conflict_resolver_check_hook() +# (spock_conflict.c:799) rejects last_update_wins whenever +# track_commit_timestamp is off and accepts only apply_remote/error instead +# -- neither of which is a legal GUC value right now. So no spock-loaded +# postmaster can boot at all with track_commit_timestamp=off in this build +# (confirmed directly: ALTER SYSTEM SET spock.conflict_resolution = +# 'apply_remote' itself fails with "invalid value for parameter +# ... HINT: Available values: last_update_wins.", before the intended +# restart-and-observe-FATAL path is even reached) -- there is no live node +# check_preconditions()'s track_commit_timestamp check can ever be exercised +# against. Revisit once apply_remote/error are re-enabled. +# ============================================================================= +note("Scenario 2: track_commit_timestamp=off on the source"); +SKIP: { + skip 'no legal spock.conflict_resolution value permits track_commit_timestamp' + . '=off in this build (apply_remote/error are commented out of' + . ' SpockConflictResolvers[], spock.c:83-93) -- a spock-loaded postmaster' + . ' cannot boot with it off at all, so this precondition path has no live' + . ' node to test against', 2; +} + +note("Scenario 3: track_commit_timestamp=off on a peer"); +SKIP: { + skip 'same as Scenario 2 -- see comment above', 2; +} + +# ============================================================================= +# Scenario 4: Spock version too old. Faked by editing the catalog metadata +# row check_spock_version_at_least_6() reads (pg_extension.extversion) -- +# this does not touch the loaded shared library, only the version string the +# precondition check itself trusts, which is exactly the surface being +# tested. Restored immediately after each attempt. +# ============================================================================= +note("Scenario 4: Spock version too old"); +my $real_extversion = scalar_query(1, "SELECT extversion FROM pg_extension WHERE extname = 'spock'"); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE pg_extension SET extversion = '5.0.11' WHERE extname = 'spock'"; +my $dir4a = fresh_datadir(); +my $ls_11881 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir4a, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 103) . " dbname=$dbname"), + '--bidirectional rejects a too-old Spock version on the source'); +ok(log_tail_has(qr/Spock version 5\.0\.11 on "source" is too old/, $ls_11881), + "--bidirectional rejects a too-old Spock version on the source: rejected for the expected reason"); +remove_tree($dir4a) if -d $dir4a; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE pg_extension SET extversion = '$real_extversion' WHERE extname = 'spock'"; + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "UPDATE pg_extension SET extversion = '5.0.11' WHERE extname = 'spock'"; +my $dir4b = fresh_datadir(); +my $ls_12798 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir4b, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 104) . " dbname=$dbname"), + '--bidirectional rejects a too-old Spock version on a peer'); +ok(log_tail_has(qr/no healthy \(status = 'replicating'\) subscription from "n2"/, $ls_12798), + "a peer reporting a too-old version is rejected (by the mesh health check, which runs before the peer version check and which the faked version already trips)"); +remove_tree($dir4b) if -d $dir4b; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "UPDATE pg_extension SET extversion = '$real_extversion' WHERE extname = 'spock'"; + +# ============================================================================= +# Scenario 5: source has unreplicated changes pending to an existing peer. +# Disabling sub_n2_n1 stops n2 consuming, without needing a full restart; +# a write on n1 then leaves n1's outbound slot to n2 behind. +# ============================================================================= +note("Scenario 5: source has undrained outbound lag to an existing peer"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT spock.sub_disable('sub_n2_n1', true)"; +for (1 .. 15) { + my $enabled = scalar_query(2, + "SELECT sub_enabled FROM spock.subscription WHERE sub_name = 'sub_n2_n1'"); + last if defined $enabled && $enabled eq 'f'; + sleep(1); +} +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pn_lag_probe (id int)"; + +$before = log_size(); +my $dir5 = fresh_datadir(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir5, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 105) . " dbname=$dbname"), + '--bidirectional rejects source with undrained outbound lag to a peer'); +ok(log_tail_has(qr/unreplicated changes pending to an existing peer: no progress for \d+ seconds on spk_\w*n2\w* \((?:in)?active\)/, $before), + 'rejection names the stalled outbound slot and says there was no progress'); +remove_tree($dir5) if -d $dir5; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT spock.sub_enable('sub_n2_n1', true)"; +for (1 .. 15) { + my $enabled = scalar_query(2, + "SELECT sub_enabled FROM spock.subscription WHERE sub_name = 'sub_n2_n1'"); + last if defined $enabled && $enabled eq 't'; + sleep(1); +} +wait_for_n1_drained(); +system_maybe "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE IF EXISTS pn_lag_probe"; +wait_for_n1_drained(); + +# ============================================================================= +# Scenario 6: P0.5 filter-equivalence, remaining sub-cases. 070_bidir_plumbing.pl +# already proves the flags sub-case (replicate_truncate mismatch on +# 'default'); these three exercise the other independent segments of +# compute_repset_fingerprints()'s per-table string (tbl=...|cols=...| +# filter=...|schema=(...)) and the separate seq=... segment. Column-list and +# partition-inclusion mismatches are not separately tested here -- they +# differ from the row_filter case only in which substring of the same +# per-table fingerprint changes, not in which code path fires or which die() +# message is reached, so table-membership + row_filter + sequence-membership +# already exercise every independent branch of check_replication_set_ +# equivalence() (found on source only, found on peer only, and same-name- +# different-fingerprint). Only 'default' is checked here because +# build_selected_set_name_filter() restricts comparison to sets an existing +# subscription actually references -- an unreferenced custom set (as seeded +# in 070) is invisible to this check. DDL replication is turned off for +# each mutating ALTER so the mismatch is real and local to n2, exactly as +# 070's flags test does. +# ============================================================================= +note("Scenario 6: repset table-membership mismatch"); +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; CREATE TABLE pn_extra_tbl (id int PRIMARY KEY)"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_add_table('default', 'pn_extra_tbl', synchronize_data := false)"; + +my $dir6a = fresh_datadir(); +my $ls_17390 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir6a, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 106) . " dbname=$dbname"), + '--bidirectional rejects a repset table-membership mismatch'); +ok(log_tail_has(qr/replication set "default" differs between the source and peer "n2"/, $ls_17390), + "--bidirectional rejects a repset table-membership mismatch: rejected for the expected reason"); +remove_tree($dir6a) if -d $dir6a; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_remove_table('default', 'pn_extra_tbl')"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; DROP TABLE pn_extra_tbl"; + +note("Scenario 6: repset row_filter mismatch"); +# CREATE TABLE runs with DDL replication ON (unlike the table-membership +# case above), specifically so it reaches n2 -- but autoddl capture +# (spock_autoddl.c) auto-adds a newly created table to 'default' on BOTH +# nodes as part of applying that same DDL, with no filter on either side. +# An explicit repset_add_table() on n1 here would just collide with that +# auto-membership (duplicate key on replication_set_table_pkey) -- so skip +# it and let auto-membership do the (filter-less, matching) add on n1; +# the wait loop below confirms n2 got the same auto-add. The actual +# mismatch is then made by remove+re-add *on n2 only*, DDL replication off. +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pn_filter_tbl (id int PRIMARY KEY, region text)"; +for (1 .. 15) { + my $present = scalar_query(2, + "SELECT COUNT(*) FROM spock.replication_set_table rts" . + " JOIN spock.replication_set rs ON rts.set_id = rs.set_id" . + " WHERE rs.set_name = 'default' AND rts.set_reloid::regclass::text = 'pn_filter_tbl'"); + last if defined $present && $present eq '1'; + sleep(1); +} +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_remove_table('default', 'pn_filter_tbl')"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_add_table('default', 'pn_filter_tbl', synchronize_data := false, " . + "row_filter := 'id > 0')"; + +my $dir6b = fresh_datadir(); +my $ls_19997 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir6b, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 107) . " dbname=$dbname"), + '--bidirectional rejects a repset row_filter mismatch'); +ok(log_tail_has(qr/replication set "default" differs between the source and peer "n2"/, $ls_19997), + "--bidirectional rejects a repset row_filter mismatch: rejected for the expected reason"); +remove_tree($dir6b) if -d $dir6b; + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE pn_filter_tbl"; +for (1 .. 15) { + my $gone = scalar_query(2, "SELECT to_regclass('pn_filter_tbl') IS NULL"); + last if defined $gone && $gone eq 't'; + sleep(1); +} + +note("Scenario 6: repset sequence-membership mismatch"); +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; CREATE SEQUENCE pn_extra_seq"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_add_seq('default', 'pn_extra_seq')"; + +my $dir6c = fresh_datadir(); +my $ls_21267 = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir6c, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 108) . " dbname=$dbname"), + '--bidirectional rejects a repset sequence-membership mismatch'); +ok(log_tail_has(qr/replication set "default" differs between the source and peer "n2"/, $ls_21267), + "--bidirectional rejects a repset sequence-membership mismatch: rejected for the expected reason"); +remove_tree($dir6c) if -d $dir6c; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_remove_seq('default', 'pn_extra_seq')"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; DROP SEQUENCE pn_extra_seq"; +wait_for_n1_drained(); +# wait_for_n1_drained() only confirms LSN lag has drained, not that +# sub_show_status() itself has settled -- the DROP SEQUENCE/repset_remove_seq +# cycle just above can leave a brief window where a worker is still +# restarting from the DDL and check_mesh_edges() sees a transient non- +# 'replicating' status on one side, which would spuriously fail Scenario 7's +# very first join for a reason that has nothing to do with idempotency. +# Confirmed happening in practice once -- wait for both directions to be +# genuinely settled before relying on the mesh being healthy. +wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + or BAIL_OUT('mesh did not restabilize after Scenario 6 cleanup'); +wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30) + or BAIL_OUT('mesh did not restabilize after Scenario 6 cleanup'); + +# ============================================================================= +# Scenario 7: idempotent double-invocation. One real join, left live (no +# --cleanup), then a second attempt reusing the same --subscriber-name "n3" +# against a fresh, empty pgdata. Whichever check trips it, the join must +# fail rather than leave a duplicate "n3" node or disturb the first n3. +# ============================================================================= +note("Scenario 7: idempotent double-invocation"); +my $n3a_datadir = fresh_datadir(); +my $n3a_port = $node_ports->[1] + 150; +my $n3a_dsn = "host=$host port=$n3a_port dbname=$dbname" + . " user=$db_user password=$db_password"; +my $n3a_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.n3a'; +open my $conf_fh_a, '>', $n3a_conf or die "Cannot write $n3a_conf: $!"; +print $conf_fh_a "shared_buffers=1GB\n"; +print $conf_fh_a "shared_preload_libraries='spock'\n"; +print $conf_fh_a output_plugin_libraries_conf($pg_bin); +print $conf_fh_a "wal_level=logical\n"; +print $conf_fh_a "spock.enable_ddl_replication=on\n"; +print $conf_fh_a "spock.include_ddl_repset=on\n"; +print $conf_fh_a "spock.allow_ddl_from_functions=on\n"; +print $conf_fh_a "spock.exception_behaviour=sub_disable\n"; +print $conf_fh_a "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh_a "track_commit_timestamp=on\n"; +print $conf_fh_a "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh_a "spock.enable_spill=on\n"; +print $conf_fh_a "port=$n3a_port\n"; +print $conf_fh_a "listen_addresses='*'\n"; +print $conf_fh_a "logging_collector=on\n"; +print $conf_fh_a "log_directory='" . $config->{log_dir} . "'\n"; +print $conf_fh_a "log_filename='00${n3a_port}.log'\n"; +close $conf_fh_a; + +# --drop-slot-if-exists: a leftover source slot of the same name is refused +# without the flag and replaced with it. A physical slot stands in for the +# leftover: the tool matches on name only, and it does not count toward the +# outbound-lag precondition. +my $src_slot = scalar_query(1, + "SELECT spock.spock_gen_slot_name('$dbname', 'n1', 'sub_n3_n1')"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT pg_create_physical_replication_slot('$src_slot')"; +wait_for_n1_drained(); + +my @n3a_join = ( + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3a_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3a_dsn, + '--postgresql-conf', $n3a_conf, +); + +$before = log_size(); +ok(!system_maybe(@n3a_join), + 'a leftover source slot is refused without --drop-slot-if-exists'); +ok(log_tail_has(qr/replication slot "\Q$src_slot\E" already exists/, $before), + 'the refusal names the existing slot'); +is(scalar_query(1, "SELECT slot_type FROM pg_replication_slots " . + "WHERE slot_name = '$src_slot'"), + 'physical', 'the leftover slot is untouched'); + +command_ok( + [ @n3a_join, '--drop-slot-if-exists' ], + 'first --bidirectional join (replacing a leftover slot with --drop-slot-if-exists) exits 0' +); +is(scalar_query(1, "SELECT slot_type FROM pg_replication_slots " . + "WHERE slot_name = '$src_slot'"), + 'logical', 'the leftover slot was replaced by the join\'s logical slot'); +ok(wait_for_pg_ready($host, $n3a_port, $pg_bin, 30), 'n3a postgres is running'); + +my $n3b_datadir = fresh_datadir(); +my $n3b_port = $node_ports->[1] + 151; +my $n3b_dsn = "host=$host port=$n3b_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +# n3a's own postgres is still running on $n3a_port -- reusing $n3a_conf here +# (which hardcodes that port) would make n3b's postgres either fail to bind +# it (n3a already holds it) or, if it somehow started anyway, listen on a +# port --subscriber-dsn never points at, so --bidirectional's own +# wait_postmaster_connection() polls a port nothing answers on forever. +# n3b needs its own override, identical to n3a's but for its own port. +my $n3b_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.n3b'; +open my $conf_fh_b, '>', $n3b_conf or die "Cannot write $n3b_conf: $!"; +print $conf_fh_b "shared_buffers=1GB\n"; +print $conf_fh_b "shared_preload_libraries='spock'\n"; +print $conf_fh_b output_plugin_libraries_conf($pg_bin); +print $conf_fh_b "wal_level=logical\n"; +print $conf_fh_b "spock.enable_ddl_replication=on\n"; +print $conf_fh_b "spock.include_ddl_repset=on\n"; +print $conf_fh_b "spock.allow_ddl_from_functions=on\n"; +print $conf_fh_b "spock.exception_behaviour=sub_disable\n"; +print $conf_fh_b "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh_b "track_commit_timestamp=on\n"; +print $conf_fh_b "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh_b "spock.enable_spill=on\n"; +print $conf_fh_b "port=$n3b_port\n"; +print $conf_fh_b "listen_addresses='*'\n"; +print $conf_fh_b "logging_collector=on\n"; +print $conf_fh_b "log_directory='" . $config->{log_dir} . "'\n"; +print $conf_fh_b "log_filename='00${n3b_port}.log'\n"; +close $conf_fh_b; + +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $n3b_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3b_dsn, + '--postgresql-conf', $n3b_conf), + 'second --bidirectional join reusing the subscriber name "n3" is rejected'); +remove_tree($n3b_datadir) if -d $n3b_datadir; +unlink($n3b_conf) if -f $n3b_conf; + +# --drop-slot-if-exists must not destroy the live slot of the completed join. +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $n3b_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=$n3b_port dbname=$dbname", + '--drop-slot-if-exists'), + 'a repeat join with --drop-slot-if-exists is also rejected'); +is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots " . + "WHERE slot_name = '$src_slot' AND active"), + '1', 'the live source slot is still present and active'); +remove_tree($n3b_datadir) if -d $n3b_datadir; + +is(psql_capture('-p', $n3a_port, '-d', $dbname, '-t', '-A', + '-c', "SELECT status FROM spock.sub_show_status('sub_n3_n1')"), + 'replicating', "the first n3's own subscription to the source is still replicating"); + +my $node_name_count = scalar_query(1, + "SELECT COUNT(*) FROM spock.node WHERE node_name = 'n3'"); +is($node_name_count, '1', 'no duplicate "n3" node row was left behind on the source'); + +ok(teardown_joined_node($n3a_port, 'n3', $n3a_datadir, $node_ports->[0], $node_ports->[1]), + q(the first join's node is taken out of the cluster)); +unlink($n3a_conf) if -f $n3a_conf; +remove_tree($n3a_datadir) if -d $n3a_datadir; + +wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + or BAIL_OUT('mesh did not restabilize after Scenario 7 cleanup'); +wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30) + or BAIL_OUT('mesh did not restabilize after Scenario 7 cleanup'); +wait_for_n1_drained(); + +# ============================================================================= +# Scenario 8: an enabled native (non-spock) logical subscription on the +# source is rejected before anything is created. +# ============================================================================= +note("Scenario 8: enabled native logical subscription on the source"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "CREATE PUBLICATION pn_native_pub"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE SUBSCRIPTION pn_native_sub CONNECTION '$n2_dsn' " . + "PUBLICATION pn_native_pub WITH (copy_data = false)"; +wait_for_n1_drained(); + +$before = log_size(); +my $dir8 = fresh_datadir(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir8, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 160) . " dbname=$dbname"), + '--bidirectional rejects an enabled native subscription on the source'); +ok(log_tail_has(qr/no enabled native \(non-spock\) logical subscriptions.*pn_native_sub/s, $before), + 'rejection names the native subscription'); +is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"), + '0', 'no source slot was created'); +ok(!-e "${dir8}.spock_bidir_pending.json", 'no pending-cleanup sidecar was created'); +remove_tree($dir8) if -d $dir8; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP SUBSCRIPTION pn_native_sub"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "DROP PUBLICATION pn_native_pub"; +wait_for_n1_drained(); + +# ============================================================================= +# Scenario 9: a peer whose recorded DSN reaches a differently named node is +# rejected as an identity mismatch. n1's record of n2's DSN is pointed at n1 +# itself, so the node reached as "n2" identifies itself as "n1". +# ============================================================================= +note("Scenario 9: peer identity mismatch"); +my $n2_if_dsn_sql = "SELECT if_dsn FROM spock.node_interface WHERE if_nodeid = " . + "(SELECT node_id FROM spock.node WHERE node_name = 'n2')"; +my $orig_n2_dsn = psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', + '-c', $n2_if_dsn_sql); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE spock.node_interface SET if_dsn = \$\$$n1_dsn\$\$ " . + "WHERE if_nodeid = (SELECT node_id FROM spock.node WHERE node_name = 'n2')"; + +$before = log_size(); +my $dir9 = fresh_datadir(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir9, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 161) . " dbname=$dbname"), + '--bidirectional rejects a peer DSN that reaches a differently named node'); +ok(log_tail_has(qr/identifies itself as "n1" once connected/, $before), + 'rejection reports the node-name/identity mismatch'); +is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"), + '0', 'no source slot was created'); +remove_tree($dir9) if -d $dir9; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE spock.node_interface SET if_dsn = \$\$$orig_n2_dsn\$\$ " . + "WHERE if_nodeid = (SELECT node_id FROM spock.node WHERE node_name = 'n2')"; +is(psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', '-c', $n2_if_dsn_sql), + $orig_n2_dsn, "n2's recorded DSN is restored on n1"); + +# ============================================================================= +# Scenario 9b: a peer reached with a role that is not a superuser. The join +# reads pg_replication_origin_status and creates slots on the peers, so it +# must stop before the first side effect instead of failing during the +# cutover. n1's record of n2's DSN is pointed at a plain login role. +# ============================================================================= +note("Scenario 9b: peer reached as a non-superuser"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "CREATE ROLE pn_nosuper LOGIN PASSWORD 'pn_nosuper_pw'"; +my $nosuper_dsn = "host=$host port=" . $node_ports->[1] . + " dbname=$dbname user=pn_nosuper password=pn_nosuper_pw"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE spock.node_interface SET if_dsn = \$\$$nosuper_dsn\$\$ " . + "WHERE if_nodeid = (SELECT node_id FROM spock.node WHERE node_name = 'n2')"; + +$before = log_size(); +my $dir9b = fresh_datadir(); +my $slots9b = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir9b, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 164) . " dbname=$dbname"), + '--bidirectional rejects a peer reached as a non-superuser'); +ok(log_tail_has(qr/role "pn_nosuper" on "n2" is not a superuser/, $before), + 'rejection names the role and the peer'); +assert_no_side_effects($dir9b, $slots9b, 'non-superuser peer'); + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "UPDATE spock.node_interface SET if_dsn = \$\$$orig_n2_dsn\$\$ " . + "WHERE if_nodeid = (SELECT node_id FROM spock.node WHERE node_name = 'n2')"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "DROP ROLE pn_nosuper"; +remove_tree($dir9b) if -d $dir9b; + +# ============================================================================= +# Scenario 10: a user object depending on the spock extension is rejected by +# the DROP EXTENSION guard instead of being dropped by CASCADE. The pre-flight +# phase runs the same guard against the source's catalogs, which are identical +# to what the copy will hold, so the join stops before any slot or backup. +# ============================================================================= +note("Scenario 10: user view depending on the spock extension"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "CREATE VIEW pn_dep_view AS SELECT node_id FROM spock.node"; +wait_for_n1_drained(); + +my $dir10 = fresh_datadir(); +my $n3c_port = $node_ports->[1] + 162; +my $n3c_dsn = "host=$host port=$n3c_port dbname=$dbname" + . " user=$db_user password=$db_password"; +my $n3c_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.n3c'; +open my $conf_fh_c, '>', $n3c_conf or die "Cannot write $n3c_conf: $!"; +print $conf_fh_c "shared_preload_libraries='spock'\n"; +print $conf_fh_c output_plugin_libraries_conf($pg_bin); +print $conf_fh_c "wal_level=logical\n"; +print $conf_fh_c "track_commit_timestamp=on\n"; +print $conf_fh_c "port=$n3c_port\n"; +print $conf_fh_c "listen_addresses='*'\n"; +close $conf_fh_c; + +$before = log_size(); +my $slots10 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir10, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3c_dsn, + '--postgresql-conf', $n3c_conf), + '--bidirectional rejects a user view depending on the spock extension'); +ok(log_tail_has(qr/cannot drop the spock extension.*pn_dep_view/s, $before), + 'rejection names the dependent view'); +assert_no_side_effects($dir10, $slots10, 'dependent view'); + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; DROP VIEW pn_dep_view"; +remove_tree($dir10) if -d $dir10; + +# ============================================================================= +# Scenario 11: the new node's own configuration lacks track_commit_timestamp. +# The base backup inherits "on" from the source; the override turns it off, so +# the join must stop once the overrides are applied. +# ============================================================================= +note("Scenario 11: track_commit_timestamp off in the new node's configuration"); +my $dir11 = fresh_datadir(); +my $n3c_auto = '/tmp/tmp_spock_node_2_postgresql.auto.conf.override.n3c'; +open my $auto_fh, '>', $n3c_auto or die "Cannot write $n3c_auto: $!"; +print $auto_fh "track_commit_timestamp=off\n"; +close $auto_fh; + +$before = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir11, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3c_dsn, + '--postgresql-conf', $n3c_conf, + '--postgresql-auto-conf', $n3c_auto), + '--bidirectional rejects a new node configured with track_commit_timestamp=off'); +ok(log_tail_has(qr/track_commit_timestamp is "off" in the configuration of/, $before), + 'rejection names track_commit_timestamp'); + +command_ok( + [ $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $dir11 ], + '--cleanup removes the rejected join\'s state' +); +is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"), + '0', 'no source slot remains after cleanup'); +remove_tree($dir11) if -d $dir11; +unlink($n3c_auto) if -f $n3c_auto; +unlink($n3c_conf) if -f $n3c_conf; + +# ============================================================================= +# Scenarios 12-16: rejections by the pre-flight phase. Each is something that +# used to surface only after the base backup (or never until the node was +# already half built); each must now stop the join before any slot, sidecar or +# data-directory content exists. +# ============================================================================= + +# Scenario 12: the new node's name collides with a node of the mesh. +note("Scenario 12: subscriber name already used by a mesh node"); +my $dir12 = fresh_datadir(); +$before = log_size(); +my $slots12 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir12, + '--subscriber-name', 'n2', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 163) . " dbname=$dbname"), + '--bidirectional rejects a subscriber name used by a mesh node'); +ok(log_tail_has(qr/subscriber name "n2" is already used by a node/, $before), + 'rejection names the colliding node'); +assert_no_side_effects($dir12, $slots12, 'name collision'); +remove_tree($dir12) if -d $dir12; + +# Scenario 13: the slot the join would create on a peer already exists there. +note("Scenario 13: peer slot already exists"); +my $peer_slot = psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', '-c', + "SELECT spock.spock_gen_slot_name('$dbname', 'n2', 'sub_n3_n2')"); +ok($peer_slot =~ /^spk_/, "computed the peer slot name ($peer_slot)"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT pg_create_logical_replication_slot('$peer_slot', 'spock_output')"; +wait_for_n1_drained(); + +my $dir13 = fresh_datadir(); +$before = log_size(); +my $slots13 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir13, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 164) . " dbname=$dbname"), + '--bidirectional rejects a peer slot that already exists'); +ok(log_tail_has(qr/replication slot "\Q$peer_slot\E" already exists on "n2"/, $before), + 'rejection names the slot and the peer'); +assert_no_side_effects($dir13, $slots13, 'existing peer slot'); +remove_tree($dir13) if -d $dir13; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT pg_drop_replication_slot('$peer_slot')"; + +# Scenario 14: a reverse subscription from an earlier attempt is still on a peer. +note("Scenario 14: leftover reverse subscription on a peer"); +# sub_create() insists on the DSN n2 already has recorded for n1. +my $n1_if_dsn = psql_capture('-p', $node_ports->[1], '-d', $dbname, '-t', '-A', '-c', + "SELECT if_dsn FROM spock.node_interface WHERE if_nodeid = " . + "(SELECT node_id FROM spock.node WHERE node_name = 'n1')"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT spock.sub_create(subscription_name := 'sub_n2_n3', " . + "provider_dsn := \$\$$n1_if_dsn\$\$, synchronize_structure := false, " . + "synchronize_data := false, enabled := false)"; +my $dir14 = fresh_datadir(); +$before = log_size(); +my $slots14 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir14, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 165) . " dbname=$dbname"), + '--bidirectional rejects a leftover reverse subscription on a peer'); +ok(log_tail_has(qr/subscription "sub_n2_n3" already exists on "n2"/, $before), + 'rejection names the subscription and the peer'); +assert_no_side_effects($dir14, $slots14, 'leftover reverse subscription'); +remove_tree($dir14) if -d $dir14; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SELECT spock.sub_drop('sub_n2_n3')"; +wait_for_n1_drained(); + +# Scenario 15: a server is already listening at --subscriber-dsn (here +# the peer itself), so it cannot be the address of the not-yet-existing node. +note("Scenario 15: --subscriber-dsn already reachable"); +my $dir15 = fresh_datadir(); +$before = log_size(); +my $slots15 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir15, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn), + '--bidirectional rejects a --subscriber-dsn where a server is listening'); +ok(log_tail_has(qr/a server is already listening at --subscriber-dsn/, $before), + 'rejection explains the DSN must be the new node\'s'); +assert_no_side_effects($dir15, $slots15, 'subscriber DSN in use'); +remove_tree($dir15) if -d $dir15; + +# The same, but the server would refuse our login (unknown role). It is +# still a server in the way, which only a ping, not a real connection, sees. +wait_for_n1_drained(); +my $dir15b = fresh_datadir(); +$before = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir15b, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=$node_ports->[1] dbname=$dbname" + . " user=pn_no_such_role password=wrong"), + '--bidirectional rejects a --subscriber-dsn whose server would refuse the login'); +ok(log_tail_has(qr/a server is already listening at --subscriber-dsn/, $before), + 'a refused login still counts as a server listening'); +assert_no_side_effects($dir15b, $slots15, 'subscriber DSN in use, login refused'); +remove_tree($dir15b) if -d $dir15b; + +# Scenario 15c: a source that is being written to must not trip the outbound +# drain check. Every outbound slot is always a little behind the end of WAL +# while writes continue, so a check that compares slots with the live WAL +# position rejects such a source nearly every time (measured: 2494 of 2500 +# samples at ten small inserts a second). The join is pointed at a live server +# as --subscriber-dsn so that it stops right after the pre-flight checks; what +# matters is that the stop is for that reason and not for the drain check. +note("Scenario 15c: outbound drain check under steady writes on the source"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pn_steady_load (id serial PRIMARY KEY, v text)"; +wait_for_n1_drained(); + +my $writer = fork(); +die "fork failed: $!" unless defined $writer; +if ($writer == 0) { + exec("$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DO \$\$ BEGIN FOR i IN 1..200 LOOP " . + "INSERT INTO pn_steady_load(v) VALUES (md5(i::text)); COMMIT; " . + "PERFORM pg_sleep(0.1); END LOOP; END \$\$;") + or die "exec failed: $!"; +} +sleep(2); # let the writer get going + +my $dir15c = fresh_datadir(); +$before = log_size(); +my $slots15c = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir15c, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn), + 'the join stops at the pre-flight checks while the source is under write load'); +ok(log_tail_has(qr/a server is already listening at --subscriber-dsn/, $before), + 'it got past the outbound drain check and stopped at the --subscriber-dsn check'); +ok(!log_tail_has(qr/unreplicated changes pending/, $before), + 'steady writes did not make the outbound drain check reject the source'); +assert_no_side_effects($dir15c, $slots15c, 'drain check under load'); +remove_tree($dir15c) if -d $dir15c; + +waitpid($writer, 0); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE pn_steady_load"; +wait_for_n1_drained(); + +# Scenario 16: a peer with no free replication slot. max_replication_slots is +# lowered to exactly the number of slots in use (a restart is needed), so the +# one slot the join must create there cannot exist. +note("Scenario 16: peer without a free replication slot"); +my $n2_slots = psql_capture('-p', $node_ports->[1], '-d', $dbname, '-t', '-A', '-c', + "SELECT count(*) FROM pg_replication_slots"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "ALTER SYSTEM SET max_replication_slots = $n2_slots"; +system_or_bail "$pg_bin/pg_ctl", 'restart', '-w', '-D', $n2_datadir, '-m', 'fast', + '-l', "$config->{log_dir}/n2_scenario16_restart.log"; +ok(wait_for_pg_ready($host, $node_ports->[1], $pg_bin, 30), 'n2 restarted with a full slot table') + or BAIL_OUT('cannot continue without n2 back up'); +ok(wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 60) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 60), + 'the n1 <-> n2 subscriptions are replicating again') + or BAIL_OUT('mesh did not recover after the n2 restart'); +wait_for_n1_drained(); + +my $dir16 = fresh_datadir(); +$before = log_size(); +my $slots16 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir16, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 166) . " dbname=$dbname"), + '--bidirectional rejects a peer with no free replication slot'); +ok(log_tail_has(qr/"n2" has 0 free replication slot\(s\) but the join needs 1/, $before), + 'rejection names the peer and max_replication_slots'); +assert_no_side_effects($dir16, $slots16, 'full peer slot table'); +remove_tree($dir16) if -d $dir16; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "ALTER SYSTEM RESET max_replication_slots"; +system_or_bail "$pg_bin/pg_ctl", 'restart', '-w', '-D', $n2_datadir, '-m', 'fast', + '-l', "$config->{log_dir}/n2_scenario16_restore.log"; +ok(wait_for_pg_ready($host, $node_ports->[1], $pg_bin, 30), 'n2 restarted with its normal slot limit') + or BAIL_OUT('cannot continue without n2 back up'); +ok(wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 60) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 60), + 'the n1 <-> n2 subscriptions are replicating again') + or BAIL_OUT('mesh did not recover after the n2 restart'); +wait_for_n1_drained(); + +# Scenario 17: not enough free disk space for the base backup, and the +# dedicated option that turns that check off. Needs a small filesystem, which +# is only built here on macOS (hdiutil RAM disk), so elsewhere the scenario is +# skipped loudly rather than passing with fewer tests. +note("Scenario 17: free disk space for the base backup"); +SKIP: { + skip "needs a small RAM disk, built with hdiutil on macOS only", 13 + unless $^O eq 'darwin' && -x '/usr/bin/hdiutil'; + + my $ramdev = `hdiutil attach -nomount ram://65536 2>/dev/null`; + $ramdev =~ s/\s+//g; + skip "could not create a RAM disk", 13 unless $ramdev =~ m{^/dev/disk\d+$}; + my $mnt = '/tmp/spock_pn_tiny_mnt'; + mkdir $mnt unless -d $mnt; + if (system("newfs_hfs -v spocktiny $ramdev >/dev/null 2>&1") != 0 + || system("diskutil mount -mountPoint $mnt $ramdev >/dev/null 2>&1") != 0) + { + system("hdiutil detach $ramdev >/dev/null 2>&1"); + skip "could not format and mount the RAM disk", 13; + } + + my $dir17 = "$mnt/n3"; + $before = log_size(); + my $slots17 = slot_count(); + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir17, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 167) . " dbname=$dbname"), + '--bidirectional rejects a target filesystem too small for the backup'); + ok(log_tail_has(qr/not enough free disk space for the base backup.*--skip-disk-space-check/s, $before), + 'rejection reports the shortfall and names --skip-disk-space-check'); + assert_no_side_effects($dir17, $slots17, 'too little disk space'); + + # A relative --pgdata that does not exist yet used to skip the check + # silently (no directory part to walk up to). + { + use Cwd qw(getcwd); + my $cwd = getcwd(); + chdir($mnt) or BAIL_OUT("cannot chdir to $mnt"); + $before = log_size(); + my $slots17r = slot_count(); + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', 'n3rel', + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 167) . " dbname=$dbname"), + 'a relative --pgdata on a too-small filesystem is rejected'); + ok(log_tail_has(qr/not enough free disk space for the base backup/, $before), + 'the relative path was measured, not skipped'); + assert_no_side_effects("$mnt/n3rel", $slots17r, 'relative --pgdata, too little disk space'); + chdir($cwd); + } + + # With the check off the join gets as far as the copy and then runs out of + # space; what matters is that the estimate no longer stops it first. + $before = log_size(); + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--skip-disk-space-check', + '--pgdata', $dir17, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 167) . " dbname=$dbname"), + 'with --skip-disk-space-check the join proceeds to the copy and fails there'); + ok(!log_tail_has(qr/not enough free disk space/, $before), + 'the disk-space estimate was not applied'); + + command_ok( + [ $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $dir17 ], + '--cleanup removes the failed copy\'s state' + ); + system("diskutil unmount force $mnt >/dev/null 2>&1; hdiutil detach $ramdev >/dev/null 2>&1"); +} + +# Scenario 18: the source needs a free slot for the base backup's temporary +# physical slot as well as for the logical source slot. With exactly one free +# the join must be rejected up front; --extra-basebackup-args '--no-slot' removes +# the need for the second one. +note("Scenario 18: source slot for the base backup"); +my $n1_slots = psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', '-c', + "SELECT count(*) FROM pg_replication_slots"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "ALTER SYSTEM SET max_replication_slots = " . ($n1_slots + 1); +system_or_bail "$pg_bin/pg_ctl", 'restart', '-w', '-D', $n1_datadir, '-m', 'fast', + '-l', "$config->{log_dir}/n1_scenario18_restart.log"; +ok(wait_for_pg_ready($host, $node_ports->[0], $pg_bin, 30), 'n1 restarted with one free slot') + or BAIL_OUT('cannot continue without n1 back up'); +ok(wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 60) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 60), + 'the n1 <-> n2 subscriptions are replicating again') + or BAIL_OUT('mesh did not recover after the n1 restart'); +wait_for_n1_drained(); + +my $dir18 = fresh_datadir(); +$before = log_size(); +my $slots18 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir18, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 168) . " dbname=$dbname"), + '--bidirectional rejects a source that cannot also hold the backup slot'); +ok(log_tail_has(qr/"source" has 1 free replication slot\(s\) but the join needs 2/, $before), + 'rejection names the source and the two slots needed'); +assert_no_side_effects($dir18, $slots18, 'source without a backup slot'); + +$before = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--extra-basebackup-args', '--no-slot', + '--pgdata', $dir18, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 168) . " dbname=$dbname"), + 'with --no-slot the slot check passes and a later check rejects the join'); +ok(!log_tail_has(qr/free replication slot\(s\)/, $before), + 'one free slot is enough once the backup uses no slot of its own'); +assert_no_side_effects($dir18, $slots18, 'source with --no-slot'); +remove_tree($dir18) if -d $dir18; + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "ALTER SYSTEM RESET max_replication_slots"; +system_or_bail "$pg_bin/pg_ctl", 'restart', '-w', '-D', $n1_datadir, '-m', 'fast', + '-l', "$config->{log_dir}/n1_scenario18_restore.log"; +ok(wait_for_pg_ready($host, $node_ports->[0], $pg_bin, 30), 'n1 restarted with its normal slot limit') + or BAIL_OUT('cannot continue without n1 back up'); +ok(wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 60) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 60), + 'the n1 <-> n2 subscriptions are replicating again') + or BAIL_OUT('mesh did not recover after the n1 restart'); +wait_for_n1_drained(); + +# Scenario 19: a slot left on the source by an earlier attempt. Without +# --drop-slot-if-exists the join is rejected up front. With it, the stale +# slot (inactive, never advancing) must not be mistaken for unreplicated work +# by the drain wait: the run gets past it, and is stopped later by the port +# check because no port override is given. +note("Scenario 19: stale source slot and --drop-slot-if-exists"); +my $stale = psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', '-c', + "SELECT spock.spock_gen_slot_name('$dbname', 'n1', 'sub_n3_n1')"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT pg_create_logical_replication_slot('$stale', 'spock_output')"; +my $dir19 = fresh_datadir(); +$before = log_size(); +my $slots19 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir19, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 169) . " dbname=$dbname"), + '--bidirectional rejects a stale source slot'); +ok(log_tail_has(qr/replication slot "\Q$stale\E" already exists on the source.*--drop-slot-if-exists/s, $before), + 'rejection names the slot and --drop-slot-if-exists'); +assert_no_side_effects($dir19, $slots19, 'stale source slot'); + +$before = log_size(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--drop-slot-if-exists', + '--pgdata', $dir19, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 169) . " dbname=$dbname"), + 'with --drop-slot-if-exists the join is stopped by a later check'); +ok(!log_tail_has(qr/unreplicated changes pending/, $before), + 'the stale slot was not counted as unreplicated work'); +ok(log_tail_has(qr/--subscriber-dsn uses port \d+ but the new node would listen/, $before), + 'the run got past the drain wait to the new-node port check'); +assert_no_side_effects($dir19, $slots19, 'stale source slot with --drop-slot-if-exists'); +remove_tree($dir19) if -d $dir19; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT pg_drop_replication_slot('$stale')"; + +# Scenario 20: what the new node will be allowed to do. It starts from a copy +# of the source's configuration (plus the override files), and needs a slot +# and a WAL sender for each existing node, and must listen on the port of +# --subscriber-dsn. These only fail after promotion if not checked now. +note("Scenario 20: the new node's own configuration"); +my $dsn_port20 = $node_ports->[1] + 170; +my @checks20 = ( + [ 'max_replication_slots = 1', + qr/would get max_replication_slots = 1 but needs 2/ ], + [ 'max_wal_senders = 1', + qr/would get max_wal_senders = 1 but needs 2/ ], + [ 'port = ' . ($dsn_port20 + 1), + qr/--subscriber-dsn uses port $dsn_port20 but the new node would listen on port ${\($dsn_port20 + 1)}/ ], +); +my $c20 = 0; +for my $chk (@checks20) { + $c20++; + my ($line, $re) = @$chk; + my $conf = "/tmp/tmp_spock_pn_conf_$c20.conf"; + open(my $cf, '>', $conf) or BAIL_OUT("cannot write $conf"); + print $cf "$line\n"; + close $cf; + + my $dir20 = fresh_datadir(); + $before = log_size(); + my $slots20 = slot_count(); + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--postgresql-auto-conf', $conf, + '--pgdata', $dir20, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=$dsn_port20 dbname=$dbname"), + "--bidirectional rejects a new-node configuration with \"$line\""); + ok(log_tail_has($re, $before), "rejection explains \"$line\""); + assert_no_side_effects($dir20, $slots20, "new-node config \"$line\""); + remove_tree($dir20) if -d $dir20; + unlink $conf; +} + +sub log_tail_capture { + my ($pattern, $since_bytes) = @_; + open(my $fh, '<', $log_file) or return; + seek($fh, $since_bytes, 0); + local $/; + my $tail = <$fh> // ''; + close $fh; + return $tail =~ $pattern ? ($1, $2) : (); +} + +# Scenario 21: the free-space check on any platform. The environment variable +# replaces the measured free space (a test hook, inert unless set), so the +# estimate itself is exercised: it must cover at least the source's database, +# and a filesystem with plenty of room must pass it. +note("Scenario 21: free-space estimate"); +my $db_mb = int(psql_capture('-p', $node_ports->[0], '-d', $dbname, '-t', '-A', '-c', + "SELECT pg_database_size('$dbname')") / (1024 * 1024)); +my $dir21 = fresh_datadir(); +$before = log_size(); +my $slots21 = slot_count(); +{ + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_FREE_BYTES} = 1048576; + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir21, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 171) . " dbname=$dbname"), + '--bidirectional rejects a filesystem with 1 MB free'); +} +my ($avail21, $need21) = log_tail_capture( + qr/not enough free disk space for the base backup in "[^"]+": (\d+) MB available, about (\d+) MB needed/, + $before); +is($avail21, 1, 'the shortfall report shows the free space'); +ok(defined $need21 && $need21 >= $db_mb, + "the estimate (" . ($need21 // 'none') . " MB) covers the database ($db_mb MB)"); +ok(log_tail_has(qr/--skip-disk-space-check to proceed/, $before), + 'the shortfall report names the way past it'); +assert_no_side_effects($dir21, $slots21, 'free-space estimate'); + +$before = log_size(); +{ + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_FREE_BYTES} = 1099511627776; + ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir21, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 171) . " dbname=$dbname"), + 'with plenty of free space a later check rejects the join'); +} +ok(!log_tail_has(qr/not enough free disk space/, $before), + 'a filesystem with room passes the estimate'); +ok(log_tail_has(qr/--subscriber-dsn uses port/, $before), + 'the run got past the free-space check'); +remove_tree($dir21) if -d $dir21; + +# Scenario 22: a spock node row for the new node's name on a peer. Creating +# the reverse subscription there would fail after promotion if its address +# differs from the new node's, so it must be rejected before the backup. +note("Scenario 22: leftover node row on a peer"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "INSERT INTO spock.node (node_id, node_name) VALUES (424242, 'n3')"; +my $dir22 = fresh_datadir(); +$before = log_size(); +my $slots22 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir22, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 172) . " dbname=$dbname"), + '--bidirectional rejects a leftover node row on a peer'); +ok(log_tail_has(qr/a spock node named "n3" is already known on "n2"/, $before), + 'rejection names the node and the peer'); +assert_no_side_effects($dir22, $slots22, 'leftover node row'); +remove_tree($dir22) if -d $dir22; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "DELETE FROM spock.node WHERE node_id = 424242"; + +# Scenario 23: a live postmaster in --pgdata. A standby of the source passes +# the version, system identifier and timeline checks, so the run must refuse it +# for the running server, leave it running and write nothing into it. +note("Scenario 23: live standby in --pgdata"); +my $dir23 = fresh_datadir(); +my $port23 = $node_ports->[1] + 173; +{ + local $ENV{PGPASSWORD} = $db_password; + ok(system_maybe("$pg_bin/pg_basebackup", '-D', $dir23, '-d', $n1_dsn, + '-X', 'stream', '-R', '-c', 'fast'), + 'base backup of the source taken for the standby'); +} +ok(system_maybe("$pg_bin/pg_ctl", '-D', $dir23, '-w', '-o', + "-p $port23 -c shared_preload_libraries= -c logging_collector=off", + '-l', '/dev/null', 'start'), + 'the copy runs as a standby'); +my $auto_before = `cat '$dir23/postgresql.auto.conf'`; +my $conf23 = '/tmp/tmp_spock_pn_conf_23.conf'; +open(my $cf23, '>', $conf23) or BAIL_OUT("cannot write $conf23"); +print $cf23 "port = $port23\n"; +close $cf23; +$before = log_size(); +my $slots23 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--postgresql-auto-conf', $conf23, + '--pgdata', $dir23, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=$port23 dbname=$dbname"), + '--bidirectional rejects a --pgdata with a running standby'); +ok(log_tail_has(qr/a postmaster \(pid \d+\) is running from data directory/, $before), + 'rejection names the running postmaster'); +ok(system_maybe("$pg_bin/pg_ctl", '-D', $dir23, 'status'), + 'the standby is still running'); +is(`cat '$dir23/postgresql.auto.conf'`, $auto_before, + "the standby's configuration is untouched"); +ok(!-e "$dir23/spock_bidirectional_manifest.json" && !-e "$dir23.spock_bidir_pending.json", + 'no manifest or pending record was written'); +is(slot_count(), $slots23, 'no slot was created on the source'); +system_maybe("$pg_bin/pg_ctl", '-D', $dir23, '-m', 'fast', '-w', 'stop'); +remove_tree($dir23) if -d $dir23; +unlink $conf23; + +# Scenario 24: nodes whose sessions have different search_paths. The +# replication-set comparison prints each table as regclass::text, which omits +# the schema when it is on the session's search_path, so a peer whose role has +# another search_path used to print the same table under a different name and +# be refused. The tool's connections use an empty search_path, so the nodes +# agree and the run gets past the comparison (to the unrelated port check). +note("Scenario 24: different search_path on a peer"); +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE pn_sp_tbl (id int PRIMARY KEY)"; +for (1 .. 15) { + my $present = scalar_query(2, + "SELECT COUNT(*) FROM spock.replication_set_table rts" . + " JOIN spock.replication_set rs ON rts.set_id = rs.set_id" . + " WHERE rs.set_name = 'default' AND rts.set_reloid::regclass::text LIKE '%pn_sp_tbl'"); + last if defined $present && $present eq '1'; + sleep(1); +} +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "ALTER ROLE $db_user IN DATABASE $dbname SET search_path = pg_catalog"; +my $dir24 = fresh_datadir(); +$before = log_size(); +my $slots24 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir24, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 174) . " dbname=$dbname"), + '--bidirectional rejects the join at a later check'); +ok(!log_tail_has(qr/replication set "default" differs between the source and peer/, $before), + 'a peer with another search_path is not reported as having a different replication set'); +ok(log_tail_has(qr/--subscriber-dsn uses port/, $before), + 'the run got past the replication-set comparison'); +assert_no_side_effects($dir24, $slots24, 'search_path'); +remove_tree($dir24) if -d $dir24; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "ALTER ROLE $db_user IN DATABASE $dbname RESET search_path"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "DROP TABLE pn_sp_tbl"; + +# Scenario 25: the same table name in different schemas. The source has +# sp_a.sp_t and the peer public.sp_t in the "default" set, and the source's role +# has search_path = sp_a. regclass::text prints both as sp_t when the session's +# search_path says so, so the comparison used to call the two sets equal. The +# nodes really differ: the join must be refused for the replication set. +note("Scenario 25: same table name, different schemas, on source and peer"); +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "CREATE SCHEMA sp_a; CREATE TABLE sp_a.sp_t (id int PRIMARY KEY); " . + "SELECT spock.repset_add_table('default', 'sp_a.sp_t')"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "CREATE TABLE public.sp_t (id int PRIMARY KEY); " . + "SELECT spock.repset_add_table('default', 'public.sp_t')"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "ALTER ROLE $db_user IN DATABASE $dbname SET search_path = sp_a"; +my $dir25 = fresh_datadir(); +$before = log_size(); +my $slots25 = slot_count(); +ok(!system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $dir25, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', "host=$host port=" . ($node_ports->[1] + 175) . " dbname=$dbname"), + '--bidirectional rejects the join'); +ok(log_tail_has(qr/replication set "default" differs between the source and peer/, $before), + 'the same table name in different schemas is a different replication set'); +assert_no_side_effects($dir25, $slots25, 'search_path false match'); +remove_tree($dir25) if -d $dir25; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "ALTER ROLE $db_user IN DATABASE $dbname RESET search_path"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_remove_table('default', 'sp_a.sp_t'); " . + "DROP TABLE sp_a.sp_t; DROP SCHEMA sp_a"; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "SET spock.enable_ddl_replication = off; " . + "SELECT spock.repset_remove_table('default', 'public.sp_t'); " . + "DROP TABLE public.sp_t"; + +# ============================================================================= +# CLEANUP +# ============================================================================= +destroy_cluster('Cleanup'); +done_testing(); diff --git a/tests/tap/t/077_bidir_join_lww_conflict.pl b/tests/tap/t/077_bidir_join_lww_conflict.pl new file mode 100644 index 000000000..cae6ea4c3 --- /dev/null +++ b/tests/tap/t/077_bidir_join_lww_conflict.pl @@ -0,0 +1,383 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 077_bidir_join_lww_conflict.pl - conflicting concurrent writes on two +# existing peers during a new node's +# --bidirectional catchup resolve to +# the SAME value on the new node as on +# the existing peers +# ============================================================================= +# Design doc spock_bidirectional_final.md section 16 lists, as a required +# positive-path scenario: "LWW conflict: concurrent conflicting writes on two +# peers during catchup; assert LWW resolves identically on source and n3." +# No existing bidirectional test exercises a genuine same-row conflict; every +# other bidir test (070/071/072/073/074/075) only ever writes NEW, non- +# colliding rows. +# +# n3 does not live through the conflict itself: it is not yet directly +# subscribed to n2 while catching up (that direct subscription stays +# disabled -- see spock_bidirectional_implementation.md's "Step 16b" -- +# until Step 20.6, well after this test's conflicting writes land). n3 only +# ever sees n2's write forwarded through n1's catchup subscription +# (forward_origins := '{all}'), tagged with n2's own origin so n3's apply +# worker resolves the conflict independently, against n1's own write, using +# the SAME origin/commit-timestamp inputs n1 itself used. If forwarding +# dropped a change, reordered it, or lost the origin tag, n3 would converge +# on a different winner than n1/n2 despite the join reporting success -- +# exactly the failure this test is positioned to catch that no other bidir +# test can (they never create a same-row conflict in the first place). +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, bidirectionally cross-wired (n1 <-> n2) +# ============================================================================= +create_cluster(2, 'Create 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2'); + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so the END cleanup reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub terminate_child { + my ($pid) = @_; + + # kill(sig, 0) signals this process's own group, which must never happen + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +# Poll a log file's content for a pattern (rather than a fixed offset read) +# since the file may not exist yet when polling starts. +sub wait_for_log_pattern { + my ($logfile, $pattern, $timeout) = @_; + for (1 .. $timeout) { + if (-f $logfile) { + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return 1 if defined $content && $content =~ $pattern; + } + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP: a table on the existing mesh, one seed row both n1 and n2 will race +# to update once n3's join is underway. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE lww_conflict_tbl (id int PRIMARY KEY, val text, writer text)"; +pass('lww_conflict_tbl created on n1'); + +my $on_n2 = '0'; +for (1 .. 30) { + $on_n2 = scalar_query(2, + "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'lww_conflict_tbl'"); + last if $on_n2 eq '1'; + sleep(1); +} +is($on_n2, '1', 'lww_conflict_tbl replicated to n2'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "INSERT INTO lww_conflict_tbl (id, val, writer) VALUES (1, 'seed', 'n1')"; + +my $seed_on_n2 = ''; +for (1 .. 30) { + $seed_on_n2 = scalar_query(2, + "SELECT val FROM lww_conflict_tbl WHERE id = 1"); + last if $seed_on_n2 eq 'seed'; + sleep(1); +} +is($seed_on_n2, 'seed', 'seed row replicated to n2 before the join starts'); + +# check_preconditions() rejects the join outright if n1's outbound slot to +# an existing peer (n2) has not fully drained -- the DDL/data that set up +# lww_conflict_tbl and its seed row just above leaves exactly that kind of +# residual lag for a moment. Wait for it to clear before launching, or the +# join dies immediately with "source has unreplicated changes pending to an +# existing peer" (confirmed happening in practice). +for (1 .. 15) { + my $lag = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + last if defined $lag && $lag eq '0'; + sleep(1); +} + +# Log every conflict resolution spock makes to spock.resolutions on n1/n2, +# so the LWW decision can be inspected directly rather than only inferred +# from the converged value. PGC_SIGHUP -- ALTER SYSTEM + reload is enough, +# no restart needed. +for my $port (@$node_ports) { + system_or_bail "$pg_bin/psql", '-p', $port, '-d', $dbname, '-c', + "ALTER SYSTEM SET spock.save_resolutions = on"; + system_or_bail "$pg_bin/psql", '-p', $port, '-d', $dbname, '-c', + "SELECT pg_reload_conf()"; +} + +# ============================================================================= +# TEST: join n3 via n1 while conflicting writes race on n1 and n2 +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_lww'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.lww'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "spock.save_resolutions=on\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_lww.log"; +unlink($scs_log) if -f $scs_log; + +# Hold the join right before the coverage barrier: forwarding is certainly +# still live there, and nothing has been cleared or enabled yet. +my $paused = "${n3_datadir}.spock_bidir_test_paused"; +my $resume = "${n3_datadir}.spock_bidir_test_resume"; +unlink($paused, $resume); + +my $scs_pid = do { + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'coverage_barrier'; + spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '600', + ); +}; + +# Forwarding (forward_origins := '{all}' on the catchup subscription) is +# live from "Creating catchup subscription" (Step 14/15) through the end of +# the coverage barrier (Step 20), cleared only by clear_forwarding() just +# before Step 20.6 enables the direct peer subscription -- see +# spock_bidirectional_implementation.md. Waiting for the catchup wait-loop +# log line guarantees we are somewhere inside that whole window, not +# necessarily "still waiting" specifically (with only one seed row, Step 18 +# may already be satisfied): either way, both conflicting writes below are +# still guaranteed to reach n3 via forwarding, not via a live direct +# subscription to n2 (which does not exist yet). +my $reached = 0; +for (1 .. 120) { + if (-e $paused) { $reached = 1; last; } + last if waitpid($scs_pid, WNOHANG) == $scs_pid; + sleep(1); +} +ok($reached, 'join paused before the coverage barrier (forwarding is live)') + or BAIL_OUT('spock_create_subscriber never reached the barrier; see ' . $scs_log); + +# Fire both conflicting UPDATEs as near-simultaneously as two forked OS +# processes allow, and keep both transactions open for two seconds so that +# neither commits before the other has made its change, so neither is sequenced through the other via the +# existing n1<->n2 mesh subscription before the second one commits. +my $writer1_log = "$log_dir/lww_writer_n1.log"; +my $writer2_log = "$log_dir/lww_writer_n2.log"; +my $w1_pid = spawn_background($writer1_log, + "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, '-c', + "BEGIN; UPDATE lww_conflict_tbl SET val = 'from_n1', writer = 'n1' WHERE id = 1; " . + "SELECT pg_sleep(2); COMMIT"); +my $w2_pid = spawn_background($writer2_log, + "$pg_bin/psql", '-X', '-p', $node_ports->[1], '-d', $dbname, '-c', + "BEGIN; UPDATE lww_conflict_tbl SET val = 'from_n2', writer = 'n2' WHERE id = 1; " . + "SELECT pg_sleep(2); COMMIT"); + +my $w1_rc = wait_for_pid($w1_pid, 30); +my $w2_rc = wait_for_pid($w2_pid, 30); +is($w1_rc, 0, 'conflicting UPDATE from n1 committed') + or diag("see $writer1_log"); +is($w2_rc, 0, 'conflicting UPDATE from n2 committed') + or diag("see $writer2_log"); + +# While the join is held, n3 has no direct subscription to n2, so n2's +# write can reach it only through n1's catchup subscription. Prove that the +# forwarding path carried both writes before letting the join continue. +is(scalar_query(3, + "SELECT count(*) FROM spock.subscription " . + "WHERE sub_name = 'sub_n3_n2' AND sub_enabled"), + '0', 'sub_n3_n2 is not enabled while the join is held'); +system_or_bail "$pg_bin/psql", '-X', '-q', '-p', $node_ports->[1], '-d', $dbname, '-c', + "INSERT INTO lww_conflict_tbl (id, val, writer) VALUES (2, 'n2_only', 'n2')"; +my $fwd = ''; +for (1 .. 60) { + $fwd = scalar_query(3, "SELECT val FROM lww_conflict_tbl WHERE id = 2"); + last if $fwd eq 'n2_only'; + sleep(1); +} +is($fwd, 'n2_only', "n2's write reached n3 through n1 while sub_n3_n2 was off"); +my $held_val = ''; +for (1 .. 60) { + $held_val = scalar_query(3, "SELECT val FROM lww_conflict_tbl WHERE id = 1"); + last if $held_val =~ /^from_n[12]$/; + sleep(1); +} +like($held_val, qr/^from_n[12]$/, + 'a conflicting write reached n3 through the forwarding path'); + +open(my $rfh, '>', $resume) or die "cannot create $resume: $!"; +close($rfh); + +my $scs_rc = wait_for_pid($scs_pid, 780); +unless (defined $scs_rc) { + diag("spock_create_subscriber (lww) did not exit within 780s; killing it"); + terminate_child($scs_pid); + $scs_rc = -1; +} +is($scs_rc, 0, '--bidirectional exits 0 despite a same-row conflict during catchup') + or diag("see $scs_log"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription sub_n3_n2 is replicating on n3'); + +# ============================================================================= +# THE assertion: all three nodes converge on the SAME LWW winner. n1 and n2 +# resolve the conflict live, in real time, via their existing mesh +# subscription; n3 only ever sees it via forwarding through n1's catchup +# subscription. If forwarding lost the origin tag or reordered the two +# writes, n3 would independently resolve to a different winner than n1/n2 +# even though row counts and the rest of the join look perfectly healthy. +# ============================================================================= +my $val_n1 = ''; +my $val_n2 = ''; +my $val_n3 = ''; +for (1 .. 60) { + $val_n1 = scalar_query(1, "SELECT val FROM lww_conflict_tbl WHERE id = 1"); + $val_n2 = scalar_query(2, "SELECT val FROM lww_conflict_tbl WHERE id = 1"); + $val_n3 = scalar_query(3, "SELECT val FROM lww_conflict_tbl WHERE id = 1"); + last if $val_n1 eq $val_n2 && $val_n2 eq $val_n3; + sleep(1); +} +diag("final values -- n1: '$val_n1', n2: '$val_n2', n3: '$val_n3'"); + +ok($val_n1 eq 'from_n1' || $val_n1 eq 'from_n2', + 'n1 resolved the conflict to one of the two contending writers, not a third value'); +is($val_n2, $val_n1, 'n2 agrees with n1 on the LWW winner (both saw the conflict live)'); +is($val_n3, $val_n1, + 'n3 agrees with n1/n2 on the LWW winner despite only seeing it forwarded'); + +my $exc_count_n3 = scalar_query(3, "SELECT count(*) FROM spock.exception_log"); +is($exc_count_n3, '0', 'no exceptions logged on n3 for the resolved conflict'); + +# ============================================================================= +# spock.resolutions is not usable as evidence here: with save_resolutions on, +# it stays empty on both n1 and n2 for this same-row UPDATE/UPDATE case, so +# a check on it can only ever fail or be skipped. The evidence of a real +# conflict is the overlap above instead: both transactions stay open for two +# seconds and commit together, so each node receives the other's change over +# a row it just updated itself. Without resolution the two nodes would swap +# values and stay different; all three ending on one value is what shows the +# conflict was resolved. + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster'); +ok(!-d $n3_datadir, 'n3 data directory removed after cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/078_bidir_join_concurrent_load.pl b/tests/tap/t/078_bidir_join_concurrent_load.pl new file mode 100644 index 000000000..5584503cf --- /dev/null +++ b/tests/tap/t/078_bidir_join_concurrent_load.pl @@ -0,0 +1,469 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 078_bidir_join_concurrent_load.pl - spock_create_subscriber +# --bidirectional under simultaneous +# write load on the SOURCE and a +# non-source PEER at once +# ============================================================================= +# Design doc (spock_bidirectional_final.md) section 16 lists, as a required +# positive-path scenario: "Concurrent writes on source AND a non-source peer +# throughout catchup; assert row-level convergence on all nodes (no missing +# rows, no duplicates)." Two existing tests each cover half of this: +# 071_bidir_join_under_load.pl loads only the source (n1); 073_bidir_join_ +# multipeer_lag.pl loads only a peer (n3, in a 3-node mesh). Neither loads +# both at once, which is what the design scenario actually calls for -- a +# bug specific to two independent write streams converging through the +# forwarding path simultaneously (e.g. an interleaving that the barrier or +# forwarded-origin resolution handles correctly when only one side is active) +# would not be caught by either. +# +# This test keeps the topology as simple as the scenario allows: a 2-node +# pre-existing mesh (n1, n2), joining n3 via n1 as the source -- n1 is "the +# source", n2 is "a non-source peer", matching the design wording exactly +# with no extra nodes needed. Uses the same dependency-free write-load +# mechanism as 073 (a PROCEDURE issuing its own COMMITs per batch, driven by +# a backgrounded psql -c "CALL ...", throttled with pg_sleep) rather than +# 071's pgedge-loadgen dependency -- keeping this test self-contained and +# suitable for the per-push schedule, not gated behind external tooling. +# +# Each writer inserts into disjoint id ranges (n1: 1..4999999, n2: 50000000+) +# so a real bug that produced a genuine duplicate row (not just a benign +# conflict-resolution replay) is distinguishable from two writers legitimately +# both succeeding. The writers run until the utility has finished, so both are +# certainly still writing when the cutover happens: the utility is paused +# right after the coverage barrier and the forwarding clear, and the rows +# written from then on must reach n3 too. Convergence is checked with the row +# counts of both writers on every node, a full content hash, and n3's +# spock.resolutions: a row delivered twice (forwarded through the source AND +# directly from the peer) is an insert conflict on a primary key, which a +# COUNT(DISTINCT id) cannot see, and with spock.save_resolutions on it is +# recorded there. A deliberate insert conflict at the end proves that +# recording works, so the empty result above means something. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok get_test_config scalar_query + wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally (n1 <-> n2) +# ============================================================================= +create_cluster(2, 'Create 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2'); + +sub psql_capture { + my (@args) = @_; + open(my $fh, '-|', "$pg_bin/psql", @args) or die "cannot run psql: $!"; + local $/; + my $out = <$fh>; + close $fh; + $out //= ''; + $out =~ s/^\s+|\s+$//g; + return $out; +} + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so the END cleanup reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub terminate_child { + my ($pid) = @_; + + # kill(sig, 0) signals this process's own group, which must never happen + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_table_drain { + my ($node_a, $node_b, $table, $timeout) = @_; + $timeout //= 180; + my $count_a = scalar_query($node_a, "SELECT COUNT(*) FROM $table"); + for (1 .. $timeout) { + my $count_b = scalar_query($node_b, "SELECT COUNT(*) FROM $table"); + return 1 if defined $count_b && $count_b eq $count_a; + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP: a table + PROCEDURE replicated across n1/n2 via DDL replication, +# used by both concurrent writers below. Disjoint id ranges per writer (a +# large offset for n2) rather than a shared sequence -- two independent +# writers sharing one sequence would themselves need to replicate sequence +# state through the very path being tested, entangling the setup with the +# thing under test. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE concurrent_load_tbl (id bigint PRIMARY KEY, val text, src text)"; +pass('concurrent_load_tbl created on n1'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', q{ + CREATE PROCEDURE concurrent_load(id_base bigint, n_batches int, + batch_rows int, node_label text) + LANGUAGE plpgsql AS $$ + DECLARE i int; + BEGIN + FOR i IN 1..n_batches LOOP + INSERT INTO concurrent_load_tbl (id, val, src) + SELECT id_base + (i - 1) * batch_rows + g, 'x' || g, node_label + FROM generate_series(1, batch_rows) g; + COMMIT; + -- Throttled for the same reason as 073_bidir_join_multipeer_ + -- lag.pl's writer: both n1 and n2 apply each other's rows via + -- their pre-existing cross-wired subscription, so an unthrottled + -- writer on either side inflates both nodes' outbound WAL, not + -- just its own. + PERFORM pg_sleep(0.1); + END LOOP; + END $$; +}; +pass('concurrent_load procedure created on n1'); + +my $table_on_n2 = '0'; +for (1 .. 30) { + $table_on_n2 = scalar_query(2, + "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'concurrent_load_tbl'"); + last if $table_on_n2 eq '1'; + sleep(1); +} +is($table_on_n2, '1', 'concurrent_load_tbl replicated to n2'); + +my $proc_on_n2 = '0'; +for (1 .. 30) { + $proc_on_n2 = scalar_query(2, + "SELECT COUNT(*) FROM pg_proc WHERE proname = 'concurrent_load'"); + last if $proc_on_n2 eq '1'; + sleep(1); +} +is($proc_on_n2, '1', 'concurrent_load procedure replicated to n2'); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1 outbound replication never drained after setup; cannot proceed'); + +# ============================================================================= +# TEST: join n3 via n1 while BOTH n1 (the source) and n2 (a non-source peer) +# are under concurrent, independent write load throughout catchup and the +# coverage barrier. +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_concurrent'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +sub wait_for_slot_created { + my ($timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $n3_pending || -f $n3_manifest; + sleep(1); + } + return 0; +} + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.concurrent'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "spock.save_resolutions=on\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_concurrent.log"; +unlink($scs_log) if -f $scs_log; + +my $n3_paused = "${n3_datadir}.spock_bidir_test_paused"; +my $n3_resume = "${n3_datadir}.spock_bidir_test_resume"; +unlink($n3_paused, $n3_resume); + +# Paused right after the barrier and the forwarding clear: from there on the +# writers' rows can only reach n3 through the direct peer subscription and the +# source's own stream. +my $scs_pid = do { + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'enable_peer_subs'; + spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '600', + ); +}; + +ok(wait_for_slot_created(30), + 'source slot created (safe to start both writers)') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log); + +# Two independent writers, started together: one against the source (n1), +# one against a non-source peer (n2), both left running until the utility has +# finished (the test stops them). +my $n1_writer_pid = spawn_background("$log_dir/concurrent_load_n1.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, + '-c', "CALL concurrent_load(1, 100000, 50, 'n1')"); +my $n2_writer_pid = spawn_background("$log_dir/concurrent_load_n2.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[1], '-d', $dbname, + '-c', "CALL concurrent_load(50000000, 100000, 50, 'n2')"); +pass('concurrent writers started on n1 (source) and n2 (peer)'); + +my $paused_ok = 0; +for (1 .. 600) { + if (-e $n3_paused) { $paused_ok = 1; last; } + last if waitpid($scs_pid, WNOHANG) == $scs_pid; + sleep(1); +} +ok($paused_ok, 'the utility reached the pause after the coverage barrier') + or BAIL_OUT('no pause reached; see ' . $scs_log); + +# Row counts of each writer at the pause: whatever is written after this +# moment must still arrive on n3. +my %at_pause = ( + n1 => scalar_query(1, "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = 'n1'"), + n2 => scalar_query(2, "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = 'n2'"), +); +sleep(2); +for my $w ([1, 'n1'], [2, 'n2']) { + my ($node, $label) = @$w; + my $now = scalar_query($node, + "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = '$label'"); + cmp_ok($now, '>', $at_pause{$label}, + "writer $label is still writing after the coverage barrier"); +} +open(my $resume_fh, '>', $n3_resume) or die $!; +close($resume_fh); + +my $scs_rc = wait_for_pid($scs_pid, 780); +unless (defined $scs_rc) { + diag("spock_create_subscriber did not exit within 780s; killing it"); + terminate_child($scs_pid); + $scs_rc = -1; +} +is($scs_rc, 0, + '--bidirectional exits 0 with concurrent source+peer write load throughout') + or diag("see $scs_log"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription sub_n3_n2 is replicating on n3'); +ok(wait_for_sub_status(2, 'sub_n2_n3', 'replicating', 30), + 'reverse subscription sub_n2_n3 is replicating on n2'); +ok(wait_for_sub_status(1, 'sub_n1_n3', 'replicating', 30), + 'reverse subscription sub_n1_n3 is replicating on n1'); + +my $readonly = psql_capture('-p', $n3_port, '-d', $dbname, '-t', '-A', + '-c', "SHOW spock.readonly"); +is($readonly, 'off', 'spock.readonly is lifted on n3'); + +# ============================================================================= +# Stop both writers (they run until told to), then let replication fully drain +# everywhere before comparing. A backend in pg_sleep() does not notice that +# its client went away, so the writers' sessions are terminated on the servers. +# ============================================================================= +sleep(2); # keep writing for a moment after the join, too +for my $node_num (1, 2) { + system_or_bail "$pg_bin/psql", '-X', '-q', '-p', $node_ports->[$node_num - 1], + '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity" + . " WHERE query LIKE 'CALL concurrent_load(%' AND pid <> pg_backend_pid()"; +} +sub stop_writer { + my ($pid, $timeout) = @_; + return unless defined $pid; + my $rc = wait_for_pid($pid, $timeout); + unless (defined $rc) { + diag("writer pid $pid did not finish within ${timeout}s; killing it"); + terminate_child($pid); + } +} +stop_writer($n1_writer_pid, 60); +stop_writer($n2_writer_pid, 60); +pass('both writers stopped'); + +diag('concurrent_load_tbl did not fully drain to n3 within 180s') + unless wait_for_table_drain(1, 3, 'concurrent_load_tbl'); +diag('concurrent_load_tbl did not fully drain to n2 within 180s') + unless wait_for_table_drain(1, 2, 'concurrent_load_tbl'); + +# ============================================================================= +# THE assertions: every node must agree exactly -- no missing rows (either +# writer's), no duplicates -- on the combined output of both simultaneous +# writers. +# ============================================================================= +my $n1_rows = scalar_query(1, "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = 'n1'"); +my $n2_rows = scalar_query(2, "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = 'n2'"); +my $hash_query = "SELECT md5(COALESCE(string_agg(x::text, ',' ORDER BY id), '')) " . + "FROM concurrent_load_tbl x"; + +cmp_ok($n1_rows, '>', $at_pause{n1}, 'n1 wrote rows after the coverage barrier'); +cmp_ok($n2_rows, '>', $at_pause{n2}, 'n2 wrote rows after the coverage barrier'); + +for my $pair ([1, 'n1'], [2, 'n2'], [3, 'n3']) { + my ($node_num, $label) = @$pair; + is(scalar_query($node_num, "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = 'n1'"), + $n1_rows, "$label has all of the source's (n1) rows, including those after the barrier"); + is(scalar_query($node_num, "SELECT COUNT(*) FROM concurrent_load_tbl WHERE src = 'n2'"), + $n2_rows, "$label has all of the peer's (n2) rows, including those after the barrier"); +} + +# A row delivered twice (forwarded by the source and sent directly by the +# peer) is an insert conflict on the primary key. +is(scalar_query(3, "SELECT COUNT(*) FROM spock.resolutions" + . " WHERE node_name = 'n3' AND relname LIKE '%concurrent_load_tbl'"), + '0', 'n3 recorded no conflict on concurrent_load_tbl: no row was delivered twice'); + +my $hash_n1 = scalar_query(1, $hash_query); +my $hash_n2 = scalar_query(2, $hash_query); +my $hash_n3 = scalar_query(3, $hash_query); +is($hash_n2, $hash_n1, 'content hash matches between n1 and n2'); +is($hash_n3, $hash_n1, 'content hash matches between n1 (source) and n3 (joined)'); +is($hash_n3, $hash_n2, 'content hash matches between n2 (peer) and n3 (joined)'); + + +# ============================================================================= +# Fresh bidirectional dataflow, proving the mesh is genuinely live after +# both simultaneous write streams and the join itself have settled. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $n3_port, '-d', $dbname, '-c', + "INSERT INTO concurrent_load_tbl (id, val, src) " . + "VALUES (999999999, 'post_join', 'n3')"; +my $marker_on_n1 = '0'; +for (1 .. 30) { + $marker_on_n1 = scalar_query(1, + "SELECT COUNT(*) FROM concurrent_load_tbl WHERE val = 'post_join'"); + last if $marker_on_n1 eq '1'; + sleep(1); +} +is($marker_on_n1, '1', 'fresh write on n3 reaches n1 after the join'); + +# Positive control for the conflict check above: a row that exists on n3 only +# (inserted in repair mode, so it is not replicated) and then arrives from n1 +# is an insert conflict on n3, which must show up in spock.resolutions. +system_or_bail "$pg_bin/psql", '-X', '-q', '-p', $n3_port, '-d', $dbname, '-c', + "SELECT spock.repair_mode(true); " + . "INSERT INTO concurrent_load_tbl (id, val, src) VALUES (888888888, 'control', 'n3')"; +system_or_bail "$pg_bin/psql", '-X', '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "INSERT INTO concurrent_load_tbl (id, val, src) VALUES (888888888, 'control', 'n1')"; +my $control = '0'; +for (1 .. 30) { + $control = scalar_query(3, "SELECT COUNT(*) FROM spock.resolutions" + . " WHERE node_name = 'n3' AND conflict_type = 'insert_exists'" + . " AND relname LIKE '%concurrent_load_tbl'"); + last if $control ne '0'; + sleep(1); +} +isnt($control, '0', 'a deliberate insert conflict on n3 is recorded in spock.resolutions'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster'); +ok(!-d $n3_datadir, 'n3 data directory removed after cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/079_bidir_join_stall_abort.pl b/tests/tap/t/079_bidir_join_stall_abort.pl new file mode 100644 index 000000000..361949bae --- /dev/null +++ b/tests/tap/t/079_bidir_join_stall_abort.pl @@ -0,0 +1,451 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 079_bidir_join_stall_abort.pl - the catchup stall watchdog must +# actually fire, cleanly, when +# progress genuinely stops +# ============================================================================= +# Design doc (spock_bidirectional_final.md) section 16, progress-watchdog +# scenarios: "Stall a wait (freeze *all* progress signals) past +# --stall-timeout -> clean abort with an attributed bottleneck message; +# state preserved; --cleanup recovers; retry resumes." 073_bidir_join_ +# multipeer_lag.pl and 074_bidir_join_big_txn_liveness.pl already prove the +# two "must NOT abort" halves of the same watchdog (slow-but-progressing, +# and a healthy worker busy on one large transaction) -- but nothing +# exercised the abort path itself actually firing. Confirmed by reading +# wait_for_origin_progress() in spock_create_subscriber.c: a stall is only +# declared when BOTH origin LSN progress is frozen AND (for a caller with a +# watch_sub_name) apply_worker_is_busy() reports the apply worker is not +# active -- so to hit this deterministically, both signals need to freeze +# at once, not just one. +# +# This freezes both signals the same way a real network partition or dead +# link would: rather than manufacturing a scenario through extra load or +# timing, it SIGSTOPs the actual walsender backend on n1 serving n3's +# catchup subscription. Found precisely, not "most recently connected" (to +# avoid any ambiguity with the pre-existing n1<->n2 mesh's own apply +# connections): spock_connect_replica() (spock.c) passes the subscription's +# own slot_name as the outbound connection's application_name, so on n1 +# that walsender's pg_stat_replication.application_name is exactly +# sub_n3_n1's sub_slot_name. (This is a different application_name than +# the "spock apply :" convention apply_worker_is_busy() uses +# -- that one is set locally on n3's own backend via SetConfigOption() in +# spock_worker.c, for n3's own pg_stat_activity; it is never sent to n1.) +# A stopped walsender sends nothing further, so n3's origin LSN stops +# advancing, and once the apply worker finishes whatever was already in +# flight it goes idle -- both conditions the watchdog requires, +# deterministically and without touching any implementation code. +# +# After the abort: SIGCONT is required before --cleanup, since DROP +# ... REPLICATION SLOT waits for its walsender to detach, which a stopped +# backend never does. --cleanup must then recover cleanly, the +# pre-existing n1<->n2 mesh must be unaffected, and a fresh retry (against +# the now-unstalled source) must succeed end-to-end -- the same "genuinely +# rejoinable, not just cleaned up" bar 072_bidir_join_crash_midcatchup.pl +# sets for its own crash scenario. +# +# Unix-only (SIGSTOP/SIGCONT process control), consistent with the rest of +# this test family's existing fork()/exec()/kill() use for spawning and +# killing spock_create_subscriber itself. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + psql_or_bail wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so the END cleanup reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub terminate_child { + my ($pid) = @_; + + # kill(sig, 0) signals this process's own group, which must never happen + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_slot_created { + my ($pending_path, $manifest_path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $pending_path || -f $manifest_path; + sleep(1); + } + return 0; +} + +# Poll a log file's content for a pattern (rather than a fixed offset read) +# since the file may not exist yet when polling starts. +sub wait_for_log_pattern { + my ($logfile, $pattern, $timeout) = @_; + for (1 .. $timeout) { + if (-f $logfile) { + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return 1 if defined $content && $content =~ $pattern; + } + sleep(1); + } + return 0; +} + +sub slurp_log { + my ($logfile) = @_; + return '' unless -f $logfile; + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return $content // ''; +} + +# ============================================================================= +# SETUP: a continuous writer on n1, so catchup always has a real, moving +# backlog right up until the freeze -- same rationale as +# 072_bidir_join_crash_midcatchup.pl: a one-time seed already present in +# the physical backup leaves nothing for the logical catchup subscription +# to replay, so only rows written *during* the join are real catchup work. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE TABLE stall_test_tbl (id bigint PRIMARY KEY, val text)"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', + "CREATE SEQUENCE stall_test_id_seq"; +system_or_bail "$pg_bin/psql", '-p', $node_ports->[0], '-d', $dbname, '-c', q{ + CREATE PROCEDURE stall_test_load(n_batches int, batch_rows int) + LANGUAGE plpgsql AS $$ + DECLARE i int; + BEGIN + FOR i IN 1..n_batches LOOP + INSERT INTO stall_test_tbl + SELECT nextval('stall_test_id_seq'), 'x' || g + FROM generate_series(1, batch_rows) g; + COMMIT; + PERFORM pg_sleep(0.02); + END LOOP; + END $$; +}; +pass('stall_test_tbl and writer procedure created on n1'); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1->n2 replication never drained after setup; cannot proceed'); + +my $writer_pid; + +sub start_writer { + $writer_pid = spawn_background("$log_dir/stall_test_writer.log", + "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, + '-c', "CALL stall_test_load(100000, 500)"); +} + +sub stop_writer { + system_or_bail "$pg_bin/psql", '-X', '-p', $node_ports->[0], '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity " . + "WHERE query LIKE 'CALL stall_test_load%' AND pid <> pg_backend_pid()"; + for (1 .. 30) { + my $still_running = scalar_query(1, + "SELECT count(*) FROM pg_stat_activity WHERE query LIKE 'CALL stall_test_load%'"); + last if defined $still_running && $still_running eq '0'; + sleep(1); + } + terminate_child($writer_pid); +} + +# ============================================================================= +# TEST: start --bidirectional, freeze the source walsender partway through +# the join (both LSN progress and apply-worker liveness at once -- this +# lands during catchup or, if catchup finishes first against this test's +# small backlog, the immediately-following coverage barrier's Hop 2, since +# both poll the same sub_n3_n1 connection), and confirm the watchdog +# aborts cleanly with an attributed message. +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_stall'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; +my $stall_timeout = 5; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.stall'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_stall_abort.log"; +unlink($scs_log) if -f $scs_log; + +my $scs_pid = spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', "$stall_timeout", + '--max-wait', '300', +); + +ok(wait_for_slot_created($n3_pending, $n3_manifest, 30), + 'source slot created (safe to start the writer)') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log); +start_writer(); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 60), + 'n3 postgres is running (pre-freeze)') + or BAIL_OUT('n3 postgres never came up; see ' . $scs_log); + +ok(wait_for_log_pattern($scs_log, qr/Waiting for catchup to the source/, 120), + 'spock_create_subscriber reached the catchup wait phase') + or BAIL_OUT('never reached the catchup wait phase; see ' . $scs_log); + +stop_writer(); + +# Precisely identify n3's own catchup-subscription apply connection on n1 +# -- not "most recently connected" -- via the slot name spock_connect_ +# replica() uses as that connection's application_name, so there is no +# ambiguity with the pre-existing n1<->n2 mesh's own apply connections. +my $n3_slot_name = scalar_query(3, + "SELECT sub_slot_name FROM spock.subscription WHERE sub_name = 'sub_n3_n1'"); +ok(defined $n3_slot_name && length($n3_slot_name), 'read sub_n3_n1 slot name') + or BAIL_OUT('could not read sub_n3_n1 slot name; see ' . $scs_log); + +my $walsender_pid = scalar_query(1, + "SELECT pid FROM pg_stat_replication WHERE application_name = '$n3_slot_name'"); +ok(defined $walsender_pid && $walsender_pid =~ /^\d+$/, + "found n1's walsender backend for sub_n3_n1 (pid $walsender_pid)") + or BAIL_OUT("could not find walsender for application_name '$n3_slot_name'"); + +ok(kill('STOP', $walsender_pid), "SIGSTOPped n1's walsender for sub_n3_n1") + or BAIL_OUT("could not SIGSTOP walsender pid $walsender_pid: $!"); + +my $scs_rc = wait_for_pid($scs_pid, 30); + +# Always resume the frozen backend before doing anything else, regardless +# of how the assertions below turn out -- a stopped walsender left behind +# would otherwise wedge every later step in this test (including +# --cleanup's own slot drop, and Test::More's own teardown). +ok(kill('CONT', $walsender_pid), "SIGCONTed n1's walsender for sub_n3_n1"); + +ok(defined $scs_rc, 'spock_create_subscriber exited on its own (watchdog fired)') + or diag("spock_create_subscriber did not exit within 30s after the freeze; see $scs_log"); +if (!defined $scs_rc) { + terminate_child($scs_pid); + $scs_rc = -1; +} +isnt($scs_rc, 0, + 'spock_create_subscriber exits non-zero once the stall watchdog fires'); + +my $scs_output = slurp_log($scs_log); +like($scs_output, + qr/\S[^\n]*? appears stalled: no origin progress for \d+ second\(s\) and the apply worker is not active; .*rerun with a larger --stall-timeout/, + 'abort message attributes the stall to a specific phase, not a generic wait'); + +# ============================================================================= +# TEST: --cleanup recovers cleanly after the aborted join +# ============================================================================= +# die() stops n3's postgres before exiting, and --cleanup starts it again +# itself (ensure_subscriber_running_for_cleanup) to drop what the join left +# there, so the first --cleanup must succeed. +sub run_scs_capture { + my ($logfile, @args) = @_; + unlink($logfile) if -f $logfile; + my $pid = spawn_background($logfile, $SCS_BIN, @args); + my $rc = wait_for_pid($pid, 60); + unless (defined $rc) { + terminate_child($pid); + $rc = -1; + } + return $rc; +} + +my $cleanup_log1 = "$log_dir/scs_stall_abort_cleanup1.log"; +my $cleanup_rc1 = run_scs_capture($cleanup_log1, + '--bidirectional', '--cleanup', '--pgdata', $n3_datadir); + +is($cleanup_rc1, 0, '--cleanup exits 0 after the stall abort (first attempt)') + or diag("see $cleanup_log1"); + +my $source_slot_after_cleanup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($source_slot_after_cleanup, '0', 'source slot removed from n1 after cleanup'); + +ok(-d $n3_datadir, 'n3 data directory kept by --cleanup'); +remove_tree($n3_datadir); + +my $n1n2_ok_after_stall = wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30); +ok($n1n2_ok_after_stall, + 'pre-existing n1 <-> n2 mesh is unaffected by the stall + abort + cleanup cycle'); + +# ============================================================================= +# TEST: a fresh --bidirectional retry against the now-unstalled source +# succeeds end-to-end -- the cluster is genuinely rejoinable, not just +# "cleaned up". +# ============================================================================= +my $final_count = scalar_query(1, "SELECT COUNT(*) FROM stall_test_tbl"); +ok(defined $final_count && $final_count > 0, + "writer produced $final_count rows on n1 before it was stopped"); + +ok(wait_for_zero_lag(1, 60), 'replication drained before the retry') + or BAIL_OUT('n1->n2 replication never drained after cleanup; cannot retry'); + +my $scs_log_retry = "$log_dir/scs_stall_abort_retry.log"; +unlink($scs_log_retry) if -f $scs_log_retry; + +my $scs_pid_retry = spawn_background($scs_log_retry, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '120', + '--max-wait', '300', +); + +my $scs_rc_retry = wait_for_pid($scs_pid_retry, 300); +unless (defined $scs_rc_retry) { + diag("spock_create_subscriber (retry) did not exit within 300s; killing it"); + terminate_child($scs_pid_retry); + $scs_rc_retry = -1; +} +is($scs_rc_retry, 0, 'fresh --bidirectional retry after the stall abort exits 0') + or diag("see $scs_log_retry"); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running (retry)'); +ok(wait_for_sub_status(3, 'sub_n3_n1', 'replicating', 30), + 'catchup subscription sub_n3_n1 is replicating on n3 (retry)'); + +my $n3_count_retry = '-1'; +for (1 .. 60) { + $n3_count_retry = scalar_query(3, "SELECT COUNT(*) FROM stall_test_tbl"); + last if $n3_count_retry eq $final_count; + sleep(1); +} +is($n3_count_retry, $final_count, 'all rows present on n3 after the retry'); + +my $hash_n1 = scalar_query(1, + "SELECT md5(COALESCE(string_agg(x::text, ',' ORDER BY id), '')) FROM stall_test_tbl x"); +my $hash_n3 = scalar_query(3, + "SELECT md5(COALESCE(string_agg(x::text, ',' ORDER BY id), '')) FROM stall_test_tbl x"); +is($hash_n3, $hash_n1, 'content hash matches between n1 and n3 after the retry'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster (final teardown)'); +ok(!-d $n3_datadir, 'n3 data directory removed after final cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/080_bidir_join_failure_matrix.pl b/tests/tap/t/080_bidir_join_failure_matrix.pl new file mode 100644 index 000000000..1cc2926e3 --- /dev/null +++ b/tests/tap/t/080_bidir_join_failure_matrix.pl @@ -0,0 +1,297 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 080_bidir_join_failure_matrix.pl - spock_create_subscriber +# --bidirectional: --cleanup +# recovers from a failure at each +# Phase 3 cutover step +# ============================================================================= +# SPOC-607 hardening review flagged a gap: 070_bidir_plumbing.pl and +# 072_bidir_join_crash_midcatchup.pl both prove --cleanup recovers a +# join that failed during the *base backup* phase or mid-*catchup*, but +# nothing exercises a failure landing after catchup completes -- inside the +# Phase 3 cutover sequence itself (coverage barrier, forwarding teardown, +# peer subscription enable, reverse subscription creation, the post-reverse +# readiness wait, and the final dataflow verification). The design doc's own +# testing-strategy section calls this out explicitly ("kill n3 between Step +# 20 and Step 21"). +# +# There is no reliable external timing signal for these steps -- unlike +# catchup, which can run arbitrarily long under write load, each of these +# steps normally completes in well under a second against an idle peer, so a +# SIGKILL race from the test side would be too flaky to trust. Instead this +# test uses a small test-only hook in spock_create_subscriber itself: +# SPOCK_CREATE_SUBSCRIBER_TEST_FAIL_AFTER= makes the utility die() +# immediately after that named step completes, going through the exact same +# failure path (process exits non-zero, whatever manifest state was +# persisted up to that point stays on disk) a genuine crash there would. +# +# For each of the 8 named steps: run the join to a deliberate death at that +# step, confirm --cleanup fully recovers (source slot, peer slot, +# data directory, manifest/sidecar, and any reverse subscriptions already +# created are all gone; the pre-existing n1<->n2 mesh is untouched), then +# move on to the next step. After the last (latest-possible) step, prove a +# fresh retry succeeds end-to-end -- the cluster is genuinely rejoinable, +# not just "cleaned up". +# +# die() stops n3's postgres before exiting, and --cleanup starts it again +# itself (ensure_subscriber_running_for_cleanup) to drop what the join left +# there, so the first --cleanup after every injected failure must +# succeed. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf track_child track_datadir teardown_joined_node); + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_failmatrix'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.failmatrix'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so the END cleanup reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub slurp_log { + my ($logfile) = @_; + return '' unless -f $logfile; + open(my $fh, '<', $logfile) or die "Cannot open $logfile: $!"; + local $/; + my $content = <$fh>; + close($fh); + return $content // ''; +} + +# Runs one --cleanup attempt with its own log file, returning its +# exit code (0 = success). +sub run_cleanup_once { + my ($logfile) = @_; + unlink($logfile) if -f $logfile; + my $pid = spawn_background($logfile, + $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $n3_datadir); + my $rc = wait_for_pid($pid, 60); + unless (defined $rc) { + kill('TERM', $pid); + waitpid($pid, 0); + $rc = -1; + } + return $rc; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +# Runs the join to completion (or to its test-injected death). $fail_after +# undef means a real, unhindered join. Returns true (like system_maybe) iff +# the process exited 0. +sub run_join { + my ($fail_after) = @_; + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_FAIL_AFTER} = $fail_after + if defined $fail_after; + return system_maybe($SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '60', + '--max-wait', '300', + ); +} + +# The peer slot name is a pure hash of (dbname, peer_node_name, +# subscription_name) -- deterministic and computable without n3 being up, +# from either half of the pre-existing n1<->n2 mesh. +my $n2_peer_slot_name = scalar_query(1, + "SELECT spock.spock_gen_slot_name('$dbname', 'n2', 'sub_n3_n2')"); + +# peer_slot_created and reverse_sub_created fire between creating a peer-side +# resource (the peer's slot, a reverse subscription) and the following manifest +# write, so a death there must still be recoverable by --cleanup. +my @steps = qw(peer_slot_created coverage_barrier clear_forwarding + enable_peer_subs reverse_sub_created reverse_subs + reverse_subs_ready verify); + +for my $step (@steps) { + ok(wait_for_zero_lag(1, 60), "replication drained before the '$step' attempt") + or BAIL_OUT("n1->n2 replication never drained; cannot proceed"); + + remove_tree($n3_datadir) if -d $n3_datadir; + unlink($n3_pending) if -f $n3_pending; + + my $log_before = -s $config->{log_file} // 0; + ok(!run_join($step), "join fails after step '$step' (test-injected)"); + + # die() stops the postgres it started on n3; stopping succeeds, so it must + # not warn that the node could not be stopped. + open(my $lfh, '<', $config->{log_file}) or die "cannot read log: $!"; + seek($lfh, $log_before, 0); + my $join_log = do { local $/; <$lfh> } // ''; + close($lfh); + like($join_log, qr/test-injected failure after step "\Q$step\E"/, + "the attempt failed at the injected step '$step', not earlier"); + unlike($join_log, qr/could not be stopped/, + "die() after '$step' reports no failed postgres stop"); + isnt(system("$pg_bin/pg_isready -h $host -p $n3_port -q"), 0, + "n3 postgres is stopped after die() at '$step'"); + + my $cleanup_log1 = "$log_dir/scs_failmatrix_cleanup_${step}_1.log"; + my $cleanup_rc1 = run_cleanup_once($cleanup_log1); + + is($cleanup_rc1, 0, + "--cleanup exits 0 after failing at '$step' (first attempt)") + or diag("see $cleanup_log1"); + + is(scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"), + '0', "source slot removed from n1 after '$step' cleanup"); + + is(scalar_query(2, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name = '$n2_peer_slot_name'"), + '0', "peer slot removed from n2 after '$step' cleanup"); + + ok(-d $n3_datadir, "n3 data directory kept by the '$step' cleanup"); + remove_tree($n3_datadir); + ok(!-f $n3_manifest, "manifest removed after '$step' cleanup"); + ok(!-f $n3_pending, "pending sidecar removed after '$step' cleanup"); + + is(scalar_query(1, + "SELECT COUNT(*) FROM spock.subscription WHERE sub_name LIKE '%n3%'"), + '0', "no orphaned n3-related subscription remains on n1 after '$step'"); + + is(scalar_query(2, + "SELECT COUNT(*) FROM spock.subscription WHERE sub_name LIKE '%n3%'"), + '0', "no orphaned n3-related subscription remains on n2 after '$step'"); + + ok((wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30)), + "pre-existing n1 <-> n2 mesh unaffected after '$step' cleanup"); +} + +# ============================================================================= +# TEST: after the last (latest-possible) failure point, a fresh retry +# succeeds end-to-end -- the cluster is genuinely rejoinable, not just +# "cleaned up". +# ============================================================================= +ok(wait_for_zero_lag(1, 60), 'replication drained before the retry') + or BAIL_OUT('n1->n2 replication never drained; cannot retry'); + +ok(run_join(undef), 'fresh --bidirectional retry after the failure matrix exits 0'); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running (retry)'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription sub_n3_n2 is replicating on n3 (retry)'); + +is(scalar_query(3, "SHOW spock.readonly"), 'off', + 'spock.readonly is lifted on n3 once the retried join is fully verified'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, $node_ports->[0], $node_ports->[1]), + 'n3 is taken out of the cluster (final teardown)'); +ok(!-d $n3_datadir, 'n3 data directory removed after final cleanup'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/081_bidir_join_forwarded_discard_abort.pl b/tests/tap/t/081_bidir_join_forwarded_discard_abort.pl new file mode 100644 index 000000000..8450fbdf1 --- /dev/null +++ b/tests/tap/t/081_bidir_join_forwarded_discard_abort.pl @@ -0,0 +1,396 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 081_bidir_join_forwarded_discard_abort.pl - an error-class exception +# on a forwarded txn +# during catchup must +# abort the join, not +# silently drop the row +# ============================================================================= +# SPOC-607 hardening review flagged this as a design-doc scenario (§16, +# "Abort-on-discard") with zero coverage, needing new injection-point +# infrastructure -- there was no way to force an apply failure specifically +# on a *forwarded*-origin change (as opposed to any ordinary apply error). +# +# New infra added alongside this test: SPOCK_FORWARDED_APPLY_ERROR(), a +# named injection point (include/spock_injection.h, same three-way +# SPOCK_RANDOM_DELAYS / USE_INJECTION_POINTS / no-op pattern already used by +# SPOCK_WORKER_DELAY()/SPOCK_OUTPUT_TXN_STALL()) fired from +# spock_apply_heap_insert/update/delete() right before the heap write, but +# only when the row being applied belongs to a forwarded-origin transaction +# (src/spock_apply_heap.c: is_forwarded_origin_apply(), mirroring the same +# replorigin_session_origin vs. MySubscription->origin->id test +# handle_origin() itself uses). +# +# Timing: the poisoned peer write must land, and forward_origins must still +# be active, at the moment the apply worker processes it -- both of which +# stop being true once establish_peer_coverage_barrier() finishes and +# clear_forwarding() runs, which (per 072/079's own findings) can happen +# well under a second after catchup completes against an idle peer. Polling +# an external log line for "reached the catchup wait phase" and then racing +# to attach the injection point and write the poisoned row is not a safe +# margin against that. Instead this uses a second test-only hook, +# SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE=coverage_barrier (spock_create_ +# subscriber.c: maybe_test_pause_before()), which blocks the join right +# after wait_for_catchup() returns and before establish_peer_coverage_ +# barrier() starts -- a point that deterministically guarantees forwarding +# is still active and nothing has been torn down -- until this test creates +# a resume marker file. The injection point is armed and the poisoned row +# is written on the peer while the join is provably frozen there, so +# forwarding it through the source is not a race against anything. +# +# n3 uses spock.exception_behaviour=sub_disable (the same setting every +# other bidir-join test in this family uses; 'error' is not a real value -- +# the only ones the GUC accepts are discard/transdiscard/sub_disable). A +# first-attempt apply failure is not yet retried with a subtransaction +# wrapper (MyApplyWorker->use_try_block is false until a worker restart has +# already seen this same commit LSN fail once), so it propagates straight +# out of apply_work()'s outer PG_TRY: no partial commit, and +# maybe_advance_forwarded_origin() never runs for this transaction. The +# manager restarts the apply worker, which retries the same transaction -- +# this time with use_try_block=true, so the poisoned action is logged and +# skipped rather than applied, but per spock_apply.c's own SUB_DISABLE +# handling the origin LSN is deliberately NOT advanced even though the +# retry "succeeded", and the worker throws once more to disable sub_n3_n1 +# outright. Either way, progress on sub_n3_n1 freezes permanently at the +# poisoned LSN and the subscription ends up disabled -- exactly the signal +# the existing catchup stall watchdog (079_bidir_join_stall_abort.pl) and +# --max-wait ceiling are built to catch, and a world away from "the row +# quietly vanished but the join reported success". This test proves that +# combination actually aborts the *join*: the poisoned row's transaction is +# written on n2 (the peer, not the provider) so it only ever reaches n3 by +# being *forwarded* through n1 -- an ordinary own-origin write from n1 would +# not exercise the forwarded-apply guard at all. +# +# Requires a server built with --enable-injection-points; skips cleanly +# (like 046_apply_worker_exception_misclassification.pl) when that support +# is not present. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(:sys_wait_h); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + command_ok system_maybe get_test_config scalar_query + wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf + track_child track_datadir); + +# ============================================================================= +# Locate spock_create_subscriber binary and check for injection_points +# support before doing any cluster setup. +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +# ============================================================================= +# Check for injection_points support; skip_all (not fail) if unavailable. +# Must run before any test assertion (plan skip_all requires it). +# ============================================================================= +my $config_probe = get_test_config(); +my $pg_bin_probe = $config_probe->{pg_bin}; +my $pkglibdir = `"$pg_bin_probe/pg_config" --pkglibdir`; +chomp $pkglibdir; +my $has_injection_points = (-e "$pkglibdir/injection_points.so") + || (-e "$pkglibdir/injection_points.dylib"); + +unless ($has_injection_points) { + plan skip_all => + "server not built with --enable-injection-points; " . + "cannot force a forwarded-apply error deterministically"; +} + +pass("spock_create_subscriber binary found"); + +# ============================================================================= +# SETUP: 2-node cluster, cross-wired bidirectionally +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so the END cleanup reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_slot_created { + my ($pending_path, $manifest_path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $pending_path || -f $manifest_path; + sleep(1); + } + return 0; +} + +sub wait_for_file { + my ($path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $path; + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP: the peer's own table -- the row that will be forwarded through n1 +# to n3 and trip the injection point. Created directly on n2 (not +# replicated from n1) so it is unambiguously n2-origin. +# ============================================================================= +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "CREATE TABLE discard_peer_tbl (id serial PRIMARY KEY, val text)"; +pass('peer test table created'); + +ok(wait_for_zero_lag(1, 60), 'replication drained before starting the join') + or BAIL_OUT('n1->n2 replication never drained after setup; cannot proceed'); + +# The CREATE TABLE above travels n2 -> n1 through a slot on n2; the join's +# replication-set comparison fails if n1 has not applied it yet. +ok(wait_for_zero_lag(2, 60), "n2's outbound replication drained before starting the join") + or BAIL_OUT('n2->n1 replication never drained after setup; cannot proceed'); + +# ============================================================================= +# TEST: start --bidirectional, arm the forwarded-apply injection point on +# n3, write a row on the peer (n2) so it is forwarded through n1 while +# forward_origins is still active, and confirm the join aborts rather than +# completing with that row silently missing. +# ============================================================================= +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_discard'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $n3_pause_marker = "${n3_datadir}.spock_bidir_test_paused"; +my $n3_resume_marker = "${n3_datadir}.spock_bidir_test_resume"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; +# A stale marker from an interrupted prior run would otherwise desync the +# rendezvous: a leftover resume marker lets maybe_test_pause_before() sail +# through before this run's own arm-injection/write-poison/release sequence +# ever happens; a leftover pause marker would make wait_for_file() below +# report "paused" before this run's join has actually gotten there. +unlink($n3_pause_marker) if -f $n3_pause_marker; +unlink($n3_resume_marker) if -f $n3_resume_marker; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.discard'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_buffers=1GB\n"; +print $conf_fh "shared_preload_libraries='spock,injection_points'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "spock.exception_replay_queue_size='1MB'\n"; +print $conf_fh "spock.enable_spill=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my $scs_log = "$log_dir/scs_discard_abort.log"; +unlink($scs_log) if -f $scs_log; + +my $scs_pid; +{ + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'coverage_barrier'; + $scs_pid = spawn_background($scs_log, + $SCS_BIN, + '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '20', + '--max-wait', '90', + ); +} + +ok(wait_for_slot_created($n3_pending, $n3_manifest, 30), + 'source slot created') + or BAIL_OUT('spock_create_subscriber never created the source slot; see ' . $scs_log); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 60), + 'n3 postgres is running') + or BAIL_OUT('n3 postgres never came up; see ' . $scs_log); + +# Deterministic rendezvous: catchup has completed and the join is blocked +# immediately before establish_peer_coverage_barrier(), so forward_origins +# is still active and nothing has been torn down yet -- see +# maybe_test_pause_before() in spock_create_subscriber.c. +ok(wait_for_file($n3_pause_marker, 60), + 'join paused before the coverage barrier (forwarding still active)') + or BAIL_OUT('never reached the pre-coverage-barrier pause; see ' . $scs_log); + +system_or_bail "$pg_bin/psql", '-X', '-p', $n3_port, '-d', $dbname, '-c', + "CREATE EXTENSION IF NOT EXISTS injection_points"; +ok(system_maybe("$pg_bin/psql", '-X', '-p', $n3_port, '-d', $dbname, '-c', + "SELECT injection_points_attach('spock-forwarded-apply-error', 'error')"), + 'armed the forwarded-apply-error injection point on n3'); + +system_or_bail "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "INSERT INTO discard_peer_tbl (val) VALUES ('poison')"; +pass('wrote the poisoned row on the peer (n2), to be forwarded through n1'); + +# Release the pause: forwarding was guaranteed active for both the arm and +# the write above, so the poisoned row can only reach n3 by being forwarded +# through n1, whatever pace the rest of the join now runs at. +open(my $resume_fh, '>', $n3_resume_marker) or die "Cannot write $n3_resume_marker: $!"; +close($resume_fh); +pass('released the join to proceed past the coverage barrier'); + +my $scs_rc = wait_for_pid($scs_pid, 150); + +system_maybe("$pg_bin/psql", '-X', '-p', $n3_port, '-d', $dbname, '-c', + "SELECT injection_points_detach('spock-forwarded-apply-error')"); + +ok(defined $scs_rc, 'spock_create_subscriber exited on its own (join aborted)') + or diag("spock_create_subscriber did not exit within 150s; see $scs_log"); +if (!defined $scs_rc) { + kill('TERM', $scs_pid); + waitpid($scs_pid, 0); + $scs_rc = -1; +} +isnt($scs_rc, 0, + 'spock_create_subscriber exits non-zero: the forwarded-txn error aborts the join'); + +# ============================================================================= +# TEST: n3 never reached cutover -- read-only was never lifted, sub_n3_n1 +# ended up disabled rather than silently completing, and the poisoned row +# was never durably visible. die()'s own handler already stopped n3's +# postgres as part of aborting, so it must be restarted (independently of +# spock_create_subscriber's own machinery) to inspect it, then stopped +# again before --cleanup runs. +# ============================================================================= +system_or_bail "$pg_bin/pg_ctl", 'start', '-D', $n3_datadir, + '-l', "$log_dir/n3_discard_inspect.log"; +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), + 'n3 postgres restarted for post-abort inspection'); + +my $readonly_after_abort = scalar_query(3, "SHOW spock.readonly"); +isnt($readonly_after_abort, 'off', + 'n3 never lifted read-only (join did not reach cutover)'); + +my $sub_n3_n1_enabled = scalar_query(3, + "SELECT sub_enabled FROM spock.subscription WHERE sub_name = 'sub_n3_n1'"); +is($sub_n3_n1_enabled, 'f', + 'sub_n3_n1 ended up disabled by the forwarded-apply error, not silently caught up'); + +my $poison_on_n3 = scalar_query(3, + "SELECT COUNT(*) FROM discard_peer_tbl WHERE val = 'poison'"); +is($poison_on_n3, '0', + 'the poisoned row is not durably present on n3 after the abort'); + +system_or_bail "$pg_bin/pg_ctl", 'stop', '-D', $n3_datadir, '-m', 'fast'; + +# ============================================================================= +# TEST: --cleanup recovers cleanly after the aborted join, and the +# pre-existing n1<->n2 mesh is unaffected. die() stopped n3's postgres once +# (and this test stopped it again above after inspecting it); --cleanup starts +# it again itself (ensure_subscriber_running_for_cleanup) to drop what the +# join left there, so the first --cleanup must succeed. +# ============================================================================= +my $cleanup_log1 = "$log_dir/scs_discard_cleanup1.log"; +unlink($cleanup_log1) if -f $cleanup_log1; +my $cleanup_pid1 = spawn_background($cleanup_log1, + $SCS_BIN, '--bidirectional', '--cleanup', '--pgdata', $n3_datadir); +my $cleanup_rc1 = wait_for_pid($cleanup_pid1, 60); +unless (defined $cleanup_rc1) { + kill('TERM', $cleanup_pid1); + waitpid($cleanup_pid1, 0); + $cleanup_rc1 = -1; +} + +is($cleanup_rc1, 0, + '--cleanup exits 0 after the forwarded-apply-error abort (first attempt)') + or diag("see $cleanup_log1"); + +my $source_slot_after_cleanup = scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +is($source_slot_after_cleanup, '0', 'source slot removed from n1 after cleanup'); + +ok(-d $n3_datadir, 'n3 data directory kept by --cleanup'); +remove_tree($n3_datadir); + +ok((wait_for_sub_status(1, 'sub_n1_n2', 'replicating', 30) + && wait_for_sub_status(2, 'sub_n2_n1', 'replicating', 30)), + 'pre-existing n1 <-> n2 mesh is unaffected by the abort + cleanup cycle'); + +system_maybe "$pg_bin/psql", '-p', $node_ports->[1], '-d', $dbname, '-c', + "DROP TABLE IF EXISTS discard_peer_tbl"; + +# ============================================================================= +# CLEANUP +# ============================================================================= +unlink($n3_conf) if -f $n3_conf; +unlink($n3_pause_marker) if -f $n3_pause_marker; +unlink($n3_resume_marker) if -f $n3_resume_marker; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/082_create_subscriber_basebackup.pl b/tests/tap/t/082_create_subscriber_basebackup.pl new file mode 100644 index 000000000..69e1cda05 --- /dev/null +++ b/tests/tap/t/082_create_subscriber_basebackup.pl @@ -0,0 +1,726 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 082_create_subscriber_basebackup.pl - spock_create_subscriber command +# line, base backup, and data directory reuse +# ============================================================================= +# 1 command-line validation: missing/conflicting options and out-of-range +# values are rejected with a specific message (no cluster needed) +# 2 --extra-basebackup-args containing shell metacharacters is rejected +# before any state is created, and the injected command never runs +# 3 the pg_basebackup command line requests streamed WAL and a fast +# checkpoint (-X s -c fast) +# 4 with checkpoint_timeout = 1h and write load on the source, the join +# completes promptly: a spread checkpoint would pace itself against +# checkpoint_timeout, so completion proves the checkpoint is immediate +# 5 the WAL carried in the new node's pg_wal is bounded by the WAL the +# source generated during the join plus recycling slack -- WAL that +# pre-dates the backup is not copied +# 6 replication slots on the source are not carried into the new node +# 7 an existing non-empty --pgdata is accepted only if it is a base backup +# of the source that has not been promoted; otherwise it is rejected +# before any slot, sidecar, or change to the directory +# 8 the node left behind is a plain primary: no standby/recovery signal +# files, not in recovery, stays one across a restart, and the catchup +# recovery settings (primary_conninfo, recovery_target_*) are not left +# in postgresql.auto.conf +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree make_path); +use Time::HiRes qw(time); +use POSIX qw(WNOHANG); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + system_maybe get_test_config scalar_query + wait_for_pg_ready wait_for_sub_status + output_plugin_libraries_conf track_datadir + teardown_joined_node); + +# Source WAL pre-generated before the join, and the allowance on top of the +# WAL generated during the join: segments recycled by n3's own startup and +# the partially filled segment at each end. +my $PREFILL_ROWS = 1_000_000; +my $WAL_SLACK_SEGS = 6; +my $JOIN_TIMEOUT_SEC = 300; + +# ============================================================================= +# Locate spock_create_subscriber binary +# ============================================================================= +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +# ============================================================================= +# 1. Command-line validation. Every case is rejected while parsing arguments, +# before any connection is attempted, so no cluster is needed. +# ============================================================================= +{ + # Unreachable on purpose: a case that wrongly gets past validation fails to + # connect instead of touching a real server. + my $PROV = 'host=127.0.0.1 port=1 dbname=x'; + my $SUB = 'host=127.0.0.1 port=2 dbname=x'; + my $DIR = '/tmp/tmp_spock_061_cli_pgdata'; + remove_tree($DIR) if -d $DIR; + + # Run with the given argument list; returns (exit status, combined output). + sub scs { + my @args = @_; + my $cmd = join(' ', map { "'$_'" } ($SCS_BIN, @args)) . ' 2>&1'; + my $out = qx{$cmd}; + return ($? >> 8, $out); + } + + my @base = ('--pgdata', $DIR, '--subscriber-name', 'n3', + '--provider-dsn', $PROV, '--subscriber-dsn', $SUB); + + # [ description, [args], expected exit, message pattern ] + my @cases = ( + [ 'no --pgdata', + [ '--subscriber-name', 'n3', '--provider-dsn', $PROV, + '--subscriber-dsn', $SUB ], + 1, qr/No data directory specified/ ], + [ 'no --subscriber-name', + [ '--pgdata', $DIR, '--provider-dsn', $PROV, '--subscriber-dsn', $SUB ], + 1, qr/No subscriber name specified/ ], + [ 'no --provider-dsn', + [ '--pgdata', $DIR, '--subscriber-name', 'n3', + '--subscriber-dsn', $SUB ], + 1, qr/Provider connection string must be specified/ ], + [ 'no --subscriber-dsn', + [ '--pgdata', $DIR, '--subscriber-name', 'n3', + '--provider-dsn', $PROV ], + 1, qr/Subscriber connection string must be specified/ ], + [ '--cleanup without --bidirectional', + [ '--pgdata', $DIR, '--cleanup' ], + 1, qr/--cleanup requires --bidirectional/ ], + [ '--force is not an option', + [ @base, '--bidirectional', '--force' ], + 1, qr/unrecognized option.*force/ ], + [ '--replication-sets combined with --bidirectional', + [ @base, '--bidirectional', '--replication-sets', 'default' ], + 1, qr/--replication-sets cannot be combined with --bidirectional/ ], + [ '--apply-delay combined with --bidirectional', + [ @base, '--bidirectional', '--apply-delay', '5' ], + 1, qr/--apply-delay cannot be combined with --bidirectional/ ], + [ '--text-types combined with --bidirectional', + [ @base, '--bidirectional', '--text-types' ], + 1, qr/--text-types cannot be combined with --bidirectional/ ], + [ '--apply-delay negative', + [ @base, '--apply-delay', '-1' ], + 1, qr/Apply delay cannot be negative/ ], + [ '--apply-delay above the maximum', + [ @base, '--apply-delay', '86401' ], + 1, qr/Apply delay cannot be more than 86400/ ], + [ '--apply-delay not an integer', + [ @base, '--apply-delay', 'soon' ], + 1, qr/--apply-delay requires an integer value/ ], + [ '--stall-timeout zero', + [ @base, '--bidirectional', '--stall-timeout', '0' ], + 1, qr/--stall-timeout must be a positive integer/ ], + [ '--stall-timeout negative', + [ @base, '--bidirectional', '--stall-timeout', '-5' ], + 1, qr/--stall-timeout must be a positive integer/ ], + [ '--max-wait negative', + [ @base, '--bidirectional', '--max-wait', '-1' ], + 1, qr/--max-wait must be a non-negative integer/ ], + [ '--postgresql-conf naming a missing file', + [ @base, '--postgresql-conf', '/nonexistent_061/postgresql.conf' ], + 1, qr/postgresql\.conf file does not exist/ ], + [ '--hba-conf naming a missing file', + [ @base, '--hba-conf', '/nonexistent_061/pg_hba.conf' ], + 1, qr/pg_hba\.conf file does not exist/ ], + [ '--postgresql-auto-conf naming a missing file', + [ @base, '--postgresql-auto-conf', '/nonexistent_061/auto.conf' ], + 1, qr/postgresql\.auto\.conf file does not exist/ ], + [ 'unknown option', + [ @base, '--no-such-option' ], + 1, qr/(Unknown option|unrecognized option)/ ], + ); + + for my $c (@cases) { + my ($desc, $args, $want_rc, $want_msg) = @$c; + note("Testing: $desc"); + my ($rc, $out) = scs(@$args); + is($rc, $want_rc, "$desc: exit status"); + like($out, $want_msg, "$desc: message"); + } + + # --cleanup needs neither a subscriber name nor DSNs + note('Testing: --cleanup --bidirectional needs only --pgdata'); + my ($rc, $out) = scs('--bidirectional', '--cleanup', '--pgdata', $DIR); + is($rc, 0, '--cleanup of a nonexistent directory exits 0'); + like($out, qr/nothing to clean up/, '--cleanup reports there is nothing to do'); + + ok(!-e $DIR, 'no data directory was created by any rejected invocation'); + ok(!-e "$DIR.spock_bidir_pending.json", + 'no sidecar was created by any rejected invocation'); + +} + +# Total size of WAL segment files in a data directory's pg_wal. +sub wal_segments_bytes { + my ($datadir) = @_; + my $total = 0; + opendir(my $dh, "$datadir/pg_wal") or die "cannot open $datadir/pg_wal: $!"; + for my $f (readdir $dh) { + next unless $f =~ /^[0-9A-F]{24}$/; + $total += -s "$datadir/pg_wal/$f"; + } + closedir $dh; + return $total; +} + +# check_preconditions() requires zero outbound replication lag on the source. +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL" . + " OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +# ============================================================================= +# SETUP +# ============================================================================= +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $n1_datadir = $config->{node_datadirs}->[0]; +my $n1_port = $node_ports->[0]; + +my $n1_dsn = "host=$host port=$n1_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_061_basebackup'; +my $n3_sidecar = "${n3_datadir}.spock_bidir_pending.json"; +# The joins below start n3 themselves; make sure END stops it if a check dies. +track_datadir($n3_datadir); +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_sidecar) if -f $n3_sidecar; + +# n3's postgresql.conf is copied from n1 by the backup, port included; all +# nodes share a host here, so n3 gets its own port. +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override_061'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "min_wal_size=32MB\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='" . $config->{log_dir} . "'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +my @scs_join = ( + $SCS_BIN, '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, +); + +# ============================================================================= +# 2. Shell metacharacters in --extra-basebackup-args are rejected up front +# ============================================================================= +note('Testing: unsafe --extra-basebackup-args are rejected before any state exists'); + +my $marker = '/tmp/tmp_spock_061_injected_marker'; +unlink($marker) if -e $marker; + +my @unsafe = ( + "--label=x;touch $marker", + "--label=x|touch $marker", + "--label=x&touch $marker", + "--label=x`touch $marker`", + "--label=\$(touch $marker)", + "--label=x>$marker", + "--label=x<$marker", +); + +for my $bad (@unsafe) { + my $cmd = qq{"$SCS_BIN" --bidirectional --pgdata "$n3_datadir" } + . qq{--subscriber-name n3 --provider-dsn "$n1_dsn" } + . qq{--subscriber-dsn "$n3_dsn" } + . qq{--extra-basebackup-args '$bad' 2>&1}; + my $out = qx{$cmd}; + my $rc = $? >> 8; + isnt($rc, 0, "rejected with non-zero exit: $bad"); + like($out, qr/unsafe shell characters/, + "rejection names the cause: $bad"); +} + +ok(!-e $marker, 'no injected command ran'); +ok(!-e $n3_datadir, 'no data directory created by rejected invocations'); +ok(!-e $n3_sidecar, 'no pending-cleanup sidecar left by rejected invocations'); +is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots " . + "WHERE slot_name LIKE 'spk_%n3%'"), + '0', 'no source slot created by rejected invocations'); + +# ============================================================================= +# 3. pg_basebackup command line: streamed WAL, fast checkpoint +# ============================================================================= +note('Testing: pg_basebackup is invoked with -X s -c fast'); + +# A backup that fails immediately keeps this cheap; -v -v prints the command +# before it runs. +my $bb_cmd = qq{"$SCS_BIN" -v -v --bidirectional --pgdata "$n3_datadir" } + . qq{--subscriber-name n3 } + . qq{--provider-dsn "$n1_dsn sslpassword=ssl_secret_061" } + . qq{--subscriber-dsn "$n3_dsn" --postgresql-conf "$n3_conf" } + . qq{--extra-basebackup-args '--waldir=/nonexistent_061_waldir' 2>&1}; +my $cmd_out = qx{$bb_cmd}; +isnt($? >> 8, 0, 'backup with an unusable --waldir fails'); +like($cmd_out, qr/Running pg_basebackup: .*-X s -c fast/, + 'pg_basebackup requested with streamed WAL and fast checkpoint'); +unlike($cmd_out, qr/(?&1}; + my $out = qx{$unreachable}; + isnt($? >> 8, 0, 'join against an unreachable provider fails'); + like($out, qr/Connection to database failed.*connection string was:/s, + 'the connection failure is reported with the connection string'); + unlike($out, qr/\Q$secret\E/, 'the password is not in the error output'); + unlike($out, qr/\Q$ssl_secret\E/, 'sslpassword is not in the error output'); + ok(!-e $n3_datadir, 'no data directory created'); +} + +# ============================================================================= +# 4-6. Join under write load with a long checkpoint_timeout +# ============================================================================= +note('Testing: join with checkpoint_timeout=1h and write load on the source'); + +# A stray slot on the source; slots must not be carried into the new node. +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "SELECT pg_create_physical_replication_slot('bb_probe_slot')"; + +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "CREATE TABLE bb_load (id bigserial PRIMARY KEY, pad text)"; + +# Pre-existing WAL on the source, kept in n1's pg_wal, that a correct backup +# must not copy. +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM SET wal_keep_size = '2GB'"; +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM SET max_wal_size = '4GB'"; +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM SET checkpoint_timeout = '1h'"; +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "SELECT pg_reload_conf()"; +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO bb_load (pad) SELECT repeat('x', 200) " . + "FROM generate_series(1, $PREFILL_ROWS)"; + +ok(wait_for_zero_lag(1, 120), 'source outbound replication drained before the join'); + +my $n1_wal_before = wal_segments_bytes($n1_datadir); +my $seg_size = scalar_query(1, + "SELECT setting::bigint FROM pg_settings " . + "WHERE name = 'wal_segment_size'"); +$seg_size = 16 * 1024 * 1024 unless $seg_size =~ /^\d+$/ && $seg_size > 0; +my $slack = $WAL_SLACK_SEGS * $seg_size; + +# The join runs as a child; write load starts once the source slot exists +# (check_preconditions() has passed by then), so the backup itself runs +# against a busy source. +my $start_lsn = scalar_query(1, "SELECT pg_current_wal_lsn()"); +my $t0 = time(); + +my $join_pid = fork(); +die "fork failed: $!" unless defined $join_pid; +if ($join_pid == 0) { + exec(@scs_join) or die "exec failed: $!"; +} + +my $manifest = "$n3_datadir/spock_bidirectional_manifest.json"; +my $slot_seen = 0; +my $join_rc; +for (1 .. 60) { + if (-f $n3_sidecar || -f $manifest) { $slot_seen = 1; last; } + if (waitpid($join_pid, WNOHANG) == $join_pid) { + # Keep the status: it cannot be collected a second time. + $join_rc = ($? & 127) ? 128 + ($? & 127) : ($? >> 8); + last; + } + sleep(1); +} + +# A join that already exited never created the slot; there is nothing to load. +my $writer_pid; +unless (defined $join_rc) { + $writer_pid = fork(); + die "fork failed: $!" unless defined $writer_pid; + if ($writer_pid == 0) { + setpgrp(0, 0); + exec('sh', '-c', + "while :; do $pg_bin/psql -q -p $n1_port -d $dbname -c " . + "\"INSERT INTO bb_load (pad) SELECT repeat('y', 200) " . + "FROM generate_series(1, 5000)\" || exit 1; sleep 1; done") + or die "exec failed: $!"; + } +} + +unless (defined $join_rc) { + for (1 .. $JOIN_TIMEOUT_SEC) { + my $w = waitpid($join_pid, WNOHANG); + if ($w == $join_pid) { + $join_rc = ($? & 127) ? 128 + ($? & 127) : ($? >> 8); + last; + } + sleep(1); + } +} +my $elapsed = time() - $t0; + +if (defined $writer_pid) { + kill('TERM', -$writer_pid); + waitpid($writer_pid, 0); +} + +unless (defined $join_rc) { + kill('KILL', $join_pid); + waitpid($join_pid, 0); +} + +ok($slot_seen, 'source slot created (join passed its preconditions)'); +is($join_rc, 0, 'join exits 0 with write load and checkpoint_timeout=1h'); +cmp_ok($elapsed, '<', $JOIN_TIMEOUT_SEC, + sprintf('join completed in %.0fs, not paced by checkpoint_timeout', $elapsed)); + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); + +# 5. WAL volume +note('Testing: new node pg_wal does not carry WAL older than the backup'); + +my $generated = scalar_query(1, + "SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), '$start_lsn')"); +my $n3_wal = wal_segments_bytes($n3_datadir); +my $bound = $generated + $slack; + +note(sprintf('n1 pg_wal before join: %d MB; WAL generated during join: %d MB; ' . + 'n3 pg_wal: %d MB; bound: %d MB', + $n1_wal_before / 1048576, $generated / 1048576, + $n3_wal / 1048576, $bound / 1048576)); + +cmp_ok($n3_wal, '<=', $bound, + 'n3 pg_wal bounded by WAL generated during the join plus slack'); +cmp_ok($n1_wal_before, '>', $bound > $n3_wal ? $n3_wal : $bound, + 'source held more pre-existing WAL than n3 carries (check is discriminating)'); + +# 6. Slots are not carried over +note('Testing: source replication slots are not carried into the new node'); + +is(scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name = 'bb_probe_slot'"), + '1', 'probe slot exists on n1'); +my $n3_slots = `$pg_bin/psql -p $n3_port -d $dbname -t -A -c "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name = 'bb_probe_slot'"`; +$n3_slots =~ s/\s+//g; +is($n3_slots, '0', 'probe slot absent from n3'); +ok(!-e "$n3_datadir/pg_replslot/bb_probe_slot", + 'probe slot directory absent from n3 pg_replslot'); + +# ============================================================================= +# 7-8. Reuse of an existing --pgdata, and the state the new node is left in. +# The join above is torn down first so n3 can be joined again. +# ============================================================================= +# The join completed, so n3 is a live member that --cleanup would refuse: +# take it out of the cluster by hand. +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, + $node_ports->[0], $node_ports->[1]), + 'the first join is torn down before the reuse cases') + or BAIL_OUT("teardown of $n3_datadir failed"); +unlink($n3_sidecar) if -f $n3_sidecar; + +sub slurp { + my ($path) = @_; + return '' unless -f $path; + open my $fh, '<', $path or die "cannot read $path: $!"; + local $/; + my $c = <$fh>; + close $fh; + return $c // ''; +} + +# Run the join; returns (exit status, combined output). Output goes to a file +# because a successful join leaves a running postmaster that would hold a pipe +# open. +sub join_n3 { + my ($pgdata, @extra) = @_; + my $cmd = join(' ', map { "'$_'" } ( + $SCS_BIN, '--bidirectional', + '--pgdata', $pgdata, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + @extra)); + my $log = '/tmp/tmp_spock_061_join.out'; + my $rc = system("$cmd > '$log' 2>&1 < /dev/null") >> 8; + return ($rc, slurp($log)); +} + +sub n3_slots_on_n1 { + return scalar_query(1, + "SELECT COUNT(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +} + +sub backup_of_n1 { + my ($dir) = @_; + remove_tree($dir) if -d $dir; + local $ENV{PGPASSWORD} = $db_password; + return system("$pg_bin/pg_basebackup -D '$dir' -d '$n1_dsn' -X stream " . + "-c fast > /dev/null 2>&1"); +} + +# Assert a rejected attempt changed nothing outside the directory it was given. +sub assert_nothing_created { + my ($what) = @_; + is(n3_slots_on_n1(), '0', "$what: no source slot created"); + ok(!-e $n3_sidecar, "$what: no pending-cleanup sidecar created"); +} + +my @tmp_dirs = ('/tmp/tmp_spock_061_notpg', '/tmp/tmp_spock_061_othercluster', + '/tmp/tmp_spock_061_promoted'); + + +remove_tree($_) for @tmp_dirs; +ok(wait_for_zero_lag(1, 120), 'source outbound replication drained'); + +# ============================================================================= +# 7a. Not a postgres data directory +# ============================================================================= +note('Testing: a non-empty directory that is not a data directory is rejected'); + +my $notpg = '/tmp/tmp_spock_061_notpg'; +make_path($notpg); +open my $fh, '>', "$notpg/keep.txt" or die $!; +print $fh "keep me\n"; +close $fh; + +{ + my ($rc, $out) = join_n3($notpg); + isnt($rc, 0, 'non-data directory: join rejected'); + like($out, qr/exists but is not valid postgres data directory/, + 'non-data directory: rejection names the cause'); + ok(-f "$notpg/keep.txt", 'non-data directory: content left in place'); + assert_nothing_created('non-data directory'); +} + +# ============================================================================= +# 7b. Another cluster's data directory +# ============================================================================= +note("Testing: another cluster's data directory is rejected (system identifier)"); + +my $other = '/tmp/tmp_spock_061_othercluster'; +is(system("$pg_bin/initdb -D '$other' -U postgres > /dev/null 2>&1"), 0, + 'initdb of an unrelated cluster'); +my $other_ctl_before = `$pg_bin/pg_controldata '$other'`; + +{ + my ($rc, $out) = join_n3($other); + isnt($rc, 0, 'other cluster: join rejected'); + like($out, qr/not basebackup of remote node/, + 'other cluster: rejection names the system identifier mismatch'); + is(`$pg_bin/pg_controldata '$other'`, $other_ctl_before, + 'other cluster: control file unchanged'); + ok(!-e "$other/postmaster.pid", 'other cluster: not started'); + assert_nothing_created('other cluster'); +} + +# ============================================================================= +# 7c. A copy already past the source's timeline +# ============================================================================= +note("Testing: a copy of the source already on a later timeline is rejected"); + +my $promoted = '/tmp/tmp_spock_061_promoted'; +is(backup_of_n1($promoted), 0, 'base backup of n1 taken'); +is(system("$pg_bin/pg_resetwal -f -l 000000020000000100000000 '$promoted' " . + "> /dev/null 2>&1"), 0, + 'timeline of the copy advanced with pg_resetwal'); +like(`$pg_bin/pg_controldata '$promoted'`, + qr/Latest checkpoint's TimeLineID:\s+2\b/, + 'the copy is on timeline 2'); + +{ + my ($rc, $out) = join_n3($promoted); + isnt($rc, 0, 'promoted copy: join rejected'); + like($out, qr/already on timeline 2, past the source's current timeline 1/, + 'promoted copy: rejection names the timelines'); + like($out, qr/run --cleanup, then remove the data directory and retry with a fresh base backup/, + 'promoted copy: the hint is --cleanup, then removing the directory'); + ok(!-e "$promoted/postmaster.pid", 'promoted copy: not started'); + assert_nothing_created('promoted copy'); +} + +# ============================================================================= +# 7d. A valid base backup: the join resumes from it +# ============================================================================= +note('Testing: a valid base backup of the source is reused'); + +is(backup_of_n1($n3_datadir), 0, 'base backup of n1 taken as the n3 data directory'); +ok(wait_for_zero_lag(1, 60), 'source outbound replication drained'); + +# A backup the user took from a node joined with this tool carries that +# node's manifest. The join must not start on it, and must leave it alone for +# the user to judge; once the user has removed it the join goes ahead. +my $foreign = "$n3_datadir/spock_bidirectional_manifest.json"; +my $foreign_json = <<"JSON"; +{ + "version": 2, + "status": "in_progress", + "subscriber_name": "some_other_node", + "dbname": "$dbname", + "source_dsn": "$n1_dsn", + "source_slot_name": "spk_some_other_node", + "source_restore_lsn": "0/1000000", + "node_dsn": "", + "node_sysid": "", + "source_reverse_sub_created": false, + "peers": [] +} +JSON +{ + open my $mf, '>', $foreign or die "cannot write $foreign: $!"; + print $mf $foreign_json; + close $mf; + + my ($rc, $out) = join_n3($n3_datadir); + isnt($rc, 0, "another node's manifest in the directory: join refused"); + like($out, qr/"\Q$foreign\E" is a join record of node "some_other_node".*run --cleanup first.*copied from another node's data directory/s, + 'the refusal names the file and the node, and both ways out'); + ok(-f $foreign, 'the manifest is left in place'); + unlike($out, qr/Running pg_basebackup|Reusing existing data directory/, + 'nothing was started'); + assert_nothing_created('foreign manifest'); +} + +# A pending record left by an earlier attempt is refused the same way. +{ + open my $pf, '>', $n3_sidecar or die "cannot write $n3_sidecar: $!"; + print $pf $foreign_json; + close $pf; + unlink($foreign); + + my ($rc, $out) = join_n3($n3_datadir); + isnt($rc, 0, 'a pending record from an earlier attempt: join refused'); + like($out, qr/"\Q$n3_sidecar\E" is a join record of node "some_other_node"/, + 'the refusal names the pending record'); + ok(-f $n3_sidecar, 'the pending record is left in place'); + unlink($n3_sidecar); +} + +{ + my ($rc, $out) = join_n3($n3_datadir, '-v', '-v'); + is($rc, 0, 'join from an existing base backup exits 0') + or diag("output:\n$out"); + like($out, qr/Reusing existing data directory/, + 'the existing directory was reused, not re-backed-up'); + unlike($out, qr/Running pg_basebackup/, 'pg_basebackup was not run'); +} + +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 postgres is running'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription is replicating on n3'); +is(scalar_query(3, 'SHOW spock.readonly'), 'off', 'spock.readonly lifted on n3'); + +# ============================================================================= +# 8. State the new node is left in +# ============================================================================= +note('Testing: the new node is a plain primary with no recovery leftovers'); + +ok(!-e "$n3_datadir/standby.signal", 'no standby.signal'); +ok(!-e "$n3_datadir/recovery.signal", 'no recovery.signal'); +is(scalar_query(3, 'SELECT pg_is_in_recovery()'), 'f', 'n3 is not in recovery'); + +my $auto = slurp("$n3_datadir/postgresql.auto.conf"); +unlike($auto, qr/^\s*primary_conninfo\s*=/m, + 'primary_conninfo is not left in postgresql.auto.conf'); +unlike($auto, qr/^\s*recovery_target/m, + 'recovery_target_* settings are not left in postgresql.auto.conf'); +unlike($auto, qr/\Q$db_password\E/, + 'the source password is not left in postgresql.auto.conf'); + +note('Testing: n3 stays a primary and keeps replicating across a restart'); + +is(system("$pg_bin/pg_ctl restart -D '$n3_datadir' -m fast -s " . + "-l '$config->{log_dir}/n3_065_restart.log' > /dev/null 2>&1"), 0, + 'n3 restarted'); +ok(wait_for_pg_ready($host, $n3_port, $pg_bin, 30), 'n3 accepts connections after the restart'); +is(scalar_query(3, 'SELECT pg_is_in_recovery()'), 'f', + 'n3 is still not in recovery after the restart'); +ok(wait_for_sub_status(3, 'sub_n3_n2', 'replicating', 30), + 'direct peer subscription still replicating after the restart'); + +# ============================================================================= +# CLEANUP +# ============================================================================= +system_maybe "$pg_bin/pg_ctl", 'stop', '-D', $n3_datadir, '-m', 'immediate'; +system_maybe "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "SELECT pg_drop_replication_slot('bb_probe_slot')"; +system_maybe "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM RESET wal_keep_size"; +system_maybe "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM RESET max_wal_size"; +system_maybe "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM RESET checkpoint_timeout"; +system_maybe "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "DROP TABLE IF EXISTS bb_load"; +remove_tree($_) for $n3_datadir, @tmp_dirs; +unlink($n3_conf) if -f $n3_conf; +unlink($marker) if -e $marker; +destroy_cluster('Cleanup'); + +done_testing(); diff --git a/tests/tap/t/083_create_subscriber_enable_order.pl b/tests/tap/t/083_create_subscriber_enable_order.pl new file mode 100644 index 000000000..0a4968099 --- /dev/null +++ b/tests/tap/t/083_create_subscriber_enable_order.pl @@ -0,0 +1,668 @@ +# ============================================================================= +# Test: 083_create_subscriber_enable_order.pl +# +# spock_create_subscriber must not let a sync worker touch the provider slot +# or the replication origin between sub_create() and the point where the +# origin is positioned at the base backup's restore point. Creating the +# subscription enabled leaves it in sync status INIT, and the INIT path drops +# and recreates the slot and advances the origin on its own. +# +# SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE=subscribe_enable freezes the +# utility after the subscription is created and its origin positioned, and +# before it is enabled. While frozen, the subscription must be disabled with +# local sync status READY and its origin must exist. After the resume it must +# replicate. +# +# Also covers the plain (non-bidirectional) path's failure handling: a failed +# base backup must not leave its provider slot behind, and DROP EXTENSION must +# not run while a non-spock object depends on spock. The restore point name +# must carry a per-run suffix. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(WNOHANG); +use lib '.'; +use SpockTest qw(create_cluster destroy_cluster system_or_bail + get_test_config scalar_query wait_for_pg_ready + output_plugin_libraries_conf node_logfile + track_child track_datadir); + +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +create_cluster(1, 'Create provider cluster'); + +my $config = get_test_config(); +my $host = $config->{host}; +my $dbname = $config->{db_name}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; +my $n1_port = $config->{node_ports}->[0]; + +my $n1_dsn = "host=$host port=$n1_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +my $n2_port = $n1_port + 1; +my $n2_datadir = '/tmp/tmp_spock_node_1_datadir_083_enable_order'; +track_datadir($n2_datadir); +my $n2_dsn = "host=$host port=$n2_port dbname=$dbname" + . " user=$db_user password=$db_password"; +remove_tree($n2_datadir) if -d $n2_datadir; + +my $n2_conf = '/tmp/tmp_spock_node_1_postgresql.conf.override_083'; +open my $conf_fh, '>', $n2_conf or die "Cannot write $n2_conf: $!"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "port=$n2_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n2_port}.log'\n"; +close $conf_fh; + +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'CREATE TABLE t083 (id int PRIMARY KEY, v text)'; +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO t083 SELECT g, 'pre' FROM generate_series(1, 100) g"; + +sub n2_query { + my ($sql) = @_; + my $out = `$pg_bin/psql -X -p $n2_port -d $dbname -t -A -c "$sql" 2>&1`; + chomp $out; + return $out; +} + +sub run_scs { + my (@extra) = @_; + my $out = `"$SCS_BIN" --pgdata "$n2_datadir" --subscriber-name n2 --provider-dsn "$n1_dsn" --subscriber-dsn "$n2_dsn" --postgresql-conf "$n2_conf" @extra 2>&1`; + return ($? >> 8, $out); +} + +sub terminate_child { + my ($pid) = @_; + + # kill(sig, 0) signals this process's own group, which must never happen + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub provider_slots { + return scalar_query(1, "SELECT count(*) FROM pg_replication_slots" + . " WHERE slot_type = 'logical' AND plugin = 'spock_output'"); +} + +# A failed base backup must not leave its slot pinning WAL on the provider. +{ + my ($rc, $out) = run_scs("--extra-basebackup-args '--waldir=/nonexistent_083_waldir'"); + isnt($rc, 0, 'a failed base backup makes the utility fail'); + is(provider_slots(), '0', 'the failed run left no slot on the provider'); + remove_tree($n2_datadir) if -d $n2_datadir; +} + +# A configuration that cannot host spock must stop the run, with the slot dropped. +for my $case ( + [ 'wal_level=replica', qr/wal_level is "replica" .* must be "logical"/ ], + [ "shared_preload_libraries=''", qr/shared_preload_libraries .* does not include "spock"/ ], +) { + my ($setting, $re) = @$case; + my $auto = '/tmp/tmp_spock_node_1_auto.conf.override_083'; + open my $af, '>', $auto or die $!; + print $af "$setting\n"; + close $af; + my ($rc, $out) = run_scs("--postgresql-auto-conf '$auto'"); + isnt($rc, 0, "$setting makes the utility fail"); + like($out, $re, "the rejection names the setting for $setting"); + is(provider_slots(), '0', "the run left no slot on the provider for $setting"); + remove_tree($n2_datadir) if -d $n2_datadir; + unlink($auto); +} + +# A copy already past the source's timeline is refused; --cleanup does not +# apply to the plain path, so the hint must say to remove the directory. +{ + local $ENV{PGPASSWORD} = $db_password; + is(system("$pg_bin/pg_basebackup -D '$n2_datadir' -d '$n1_dsn' -X stream " + . "-c fast > /dev/null 2>&1"), 0, 'base backup of the provider taken'); + is(system("$pg_bin/pg_resetwal -f -l 000000020000000100000000 '$n2_datadir' " + . "> /dev/null 2>&1"), 0, 'timeline of the copy advanced'); + my ($rc, $out) = run_scs(); + isnt($rc, 0, 'a copy on a later timeline makes the utility fail'); + like($out, qr/already on timeline 2, past the source's current timeline 1.*remove the data directory and retry/s, + 'the hint is to remove the data directory'); + is(provider_slots(), '0', 'the failed run left no slot on the provider'); + remove_tree($n2_datadir) if -d $n2_datadir; +} + +# A directory with a live postmaster is refused before anything is written, and +# the server is left running: it is a standby of the provider, not ours to stop. +{ + local $ENV{PGPASSWORD} = $db_password; + is(system("$pg_bin/pg_basebackup -D '$n2_datadir' -d '$n1_dsn' -X stream " + . "-R -c fast > /dev/null 2>&1"), 0, + 'base backup of the provider taken for the standby'); + is(system("$pg_bin/pg_ctl -D '$n2_datadir' -w " + . "-o \"-p $n2_port -c shared_preload_libraries= " + . "-c logging_collector=off\" -l /dev/null start > /dev/null 2>&1"), + 0, 'the copy runs as a standby'); + my $before = `md5 -q '$n2_datadir/postgresql.auto.conf' 2>/dev/null` + || `md5sum '$n2_datadir/postgresql.auto.conf'`; + for my $mode ('') { + my $label = 'plain path'; + my ($rc, $out) = run_scs($mode); + isnt($rc, 0, "a running standby makes the utility fail ($label)"); + like($out, qr/a postmaster \(pid \d+\) is running from data directory/, + "the refusal names the running postmaster ($label)"); + is(system("$pg_bin/pg_ctl -D '$n2_datadir' status > /dev/null 2>&1"), 0, + "the standby is still running ($label)"); + my $after = `md5 -q '$n2_datadir/postgresql.auto.conf' 2>/dev/null` + || `md5sum '$n2_datadir/postgresql.auto.conf'`; + is($after, $before, "the standby's configuration is untouched ($label)"); + ok(!-e "$n2_datadir/spock_bidirectional_manifest.json", + "no manifest written into the standby's directory ($label)"); + is(provider_slots(), '0', "the refused run left no slot on the provider ($label)"); + } + system("$pg_bin/pg_ctl -D '$n2_datadir' -m fast -w stop >/dev/null 2>&1"); + remove_tree($n2_datadir) if -d $n2_datadir; +} + +# A non-spock object depending on spock must stop the run before anything is dropped. +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'CREATE VIEW v083 AS SELECT * FROM spock.node'; +{ + my ($rc, $out) = run_scs(); + isnt($rc, 0, 'a dependent object makes the utility fail'); + like($out, qr/depend on it and would be collaterally dropped.*v083/s, + 'the dependent object is named'); + is(provider_slots(), '0', 'the failed run left no slot on the provider'); + remove_tree($n2_datadir) if -d $n2_datadir; +} +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'DROP VIEW v083'; + +# The clone of a source with an enabled native subscription would start +# consuming from that subscription's upstream once promoted. The plain path +# must refuse it, as --bidirectional does, before it creates a slot. +{ + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'CREATE PUBLICATION p083'; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "SELECT pg_create_logical_replication_slot('native083', 'pgoutput')"; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "CREATE SUBSCRIPTION s083 CONNECTION '$n1_dsn' PUBLICATION p083 " + . "WITH (create_slot = false, slot_name = 'native083', copy_data = false)"; + + my ($rc, $out) = run_scs(); + isnt($rc, 0, 'an enabled native subscription on the provider makes the utility fail'); + like($out, qr/no enabled native \(non-spock\) logical subscriptions.*s083/s, + 'the native subscription is named'); + is(provider_slots(), '0', 'the failed run left no slot on the provider'); + remove_tree($n2_datadir) if -d $n2_datadir; + + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'ALTER SUBSCRIPTION s083 DISABLE'; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'ALTER SUBSCRIPTION s083 SET (slot_name = NONE)'; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'DROP SUBSCRIPTION s083'; + for (1 .. 20) { + last if system("$pg_bin/psql -q -X -p $n1_port -d $dbname -c " + . "\"SELECT pg_drop_replication_slot('native083')\" " + . ">/dev/null 2>&1") == 0; + sleep(1); + } + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'DROP PUBLICATION p083'; +} + +# SIGTERM while the utility waits: it must clean up from the main flow, +# drop the provider slot and stop the new node. +{ + my $cpaused = "${n2_datadir}.spock_bidir_test_paused"; + my $clog = "$log_dir/scs_cancel.log"; + unlink($clog, $cpaused); + + my $cpid = fork(); + die "fork() failed: $!" unless defined $cpid; + if ($cpid == 0) { + open(my $fh, '>>', $clog) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'subscribe_enable'; + setpgrp(0, 0); # own group, so END can stop it if a check dies + exec($SCS_BIN, + '--pgdata', $n2_datadir, + '--subscriber-name', 'n2', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn, + '--postgresql-conf', $n2_conf) or POSIX::_exit(127); + } + track_child($cpid); + + my $creached = 0; + for (1 .. 120) { + if (-e $cpaused) { $creached = 1; last; } + last if waitpid($cpid, WNOHANG) == $cpid; + sleep(1); + } + ok($creached, 'utility reached the pause') + or do { diag(`tail -30 $clog`); done_testing(); exit 1; }; + is(provider_slots(), '1', 'the plain path holds a provider slot while paused'); + + kill('TERM', $cpid); + my $crc; + for (1 .. 60) { + if (waitpid($cpid, WNOHANG) == $cpid) { $crc = $? >> 8; last; } + sleep(1); + } + terminate_child($cpid) unless defined $crc; + is($crc, 1, 'SIGTERM makes the utility exit with status 1'); + open my $lf, '<', $clog or die $!; + local $/; + my $log = <$lf>; + close $lf; + like($log, qr/Canceling\.\.\./, 'the cancellation is reported'); + is(provider_slots(), '0', 'the cancelled run dropped its provider slot'); + ok(!-e "$n2_datadir/postmaster.pid", 'the new node was stopped'); + unlink($cpaused); + remove_tree($n2_datadir) if -d $n2_datadir; +} + +# SIGTERM, or SIGHUP from a dropped ssh session, while pg_basebackup is running: +# the utility must not wait for the backup to finish (hours, on a large +# provider). The backup is throttled to the minimum rate so that it is +# certainly still running. +for my $sig (qw(TERM HUP)) { + my $blog = "$log_dir/scs_cancel_backup_$sig.log"; + unlink($blog); + + my $bpid = fork(); + die "fork() failed: $!" unless defined $bpid; + if ($bpid == 0) { + open(my $fh, '>>', $blog) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + $SIG{HUP} = 'DEFAULT'; # the tool keeps SIGHUP ignored when started under nohup + setpgrp(0, 0); # own group, so END can stop it if a check dies + exec($SCS_BIN, + '--pgdata', $n2_datadir, + '--subscriber-name', 'n2', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn, + '--postgresql-conf', $n2_conf, + '--extra-basebackup-args', '--max-rate=32') or POSIX::_exit(127); + } + track_child($bpid); + + my $copying = 0; + for (1 .. 120) { + if (-d "$n2_datadir/base") { $copying = 1; last; } + last if waitpid($bpid, WNOHANG) == $bpid; + sleep(1); + } + ok($copying, "the base backup is copying data (SIG$sig)") + or do { diag(`tail -30 $blog`); terminate_child($bpid); done_testing(); exit 1; }; + sleep(2); + is(waitpid($bpid, WNOHANG), 0, "the throttled backup is still running (SIG$sig)"); + is(provider_slots(), '1', "the provider slot exists during the backup (SIG$sig)"); + + my $t0 = time(); + kill($sig, $bpid); + my $brc; + for (1 .. 60) { + if (waitpid($bpid, WNOHANG) == $bpid) { $brc = $? >> 8; last; } + sleep(1); + } + my $took = time() - $t0; + terminate_child($bpid) unless defined $brc; + is($brc, 1, "SIG$sig during the base backup makes the utility exit with status 1"); + cmp_ok($took, '<', 20, "the utility stopped within ${took}s, not at the end of the backup (SIG$sig)"); + + open my $blf, '<', $blog or die $!; + my $blogtext = do { local $/; <$blf> }; + close $blf; + like($blogtext, qr/Canceling\.\.\./, "the cancellation is reported (SIG$sig)"); + is(provider_slots(), '0', "the cancelled run dropped its provider slot (SIG$sig)"); + my $left = `ps -axo command | grep -c '[m]ax-rate=32'`; + chomp $left; + is($left, '0', "no pg_basebackup is left running (SIG$sig)"); + remove_tree($n2_datadir) if -d $n2_datadir; +} + +# A provider slot that max_slot_wal_keep_size invalidated while the base backup +# was taken is still listed; the run must stop with that reason before it +# enables the subscription, not report success and leave an apply worker that +# fails in START_REPLICATION for ever. +{ + my $ipaused = "${n2_datadir}.spock_bidir_test_paused"; + my $iresume = "${n2_datadir}.spock_bidir_test_resume"; + my $ilog = "$log_dir/scs_invalidated_slot.log"; + unlink($ilog, $ipaused, $iresume); + + my $ipid = fork(); + die "fork() failed: $!" unless defined $ipid; + if ($ipid == 0) { + open(my $fh, '>>', $ilog) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'subscribe_enable'; + setpgrp(0, 0); + exec($SCS_BIN, + '--pgdata', $n2_datadir, + '--subscriber-name', 'n2', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn, + '--postgresql-conf', $n2_conf) or POSIX::_exit(127); + } + track_child($ipid); + + my $ireached = 0; + for (1 .. 120) { + if (-e $ipaused) { $ireached = 1; last; } + last if waitpid($ipid, WNOHANG) == $ipid; + sleep(1); + } + ok($ireached, 'utility reached the pause before enabling the subscription') + or do { diag(`tail -30 $ilog`); terminate_child($ipid); done_testing(); exit 1; }; + + # Let the provider remove the WAL the slot holds. + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "ALTER SYSTEM SET max_slot_wal_keep_size = '16MB'"; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'SELECT pg_reload_conf()'; + my $status = ''; + my $batch = 0; + for my $round (1 .. 10) { + for (1 .. 4) { + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO t083 SELECT g + 1000000 + 10000 * " . $batch++ . ", 'wal' FROM generate_series(1, 2000) g"; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'SELECT pg_switch_wal()'; + } + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'CHECKPOINT'; + $status = scalar_query(1, "SELECT wal_status FROM pg_replication_slots" + . " WHERE slot_type = 'logical' AND plugin = 'spock_output'"); + last if $status eq 'lost'; + } + is($status, 'lost', 'the provider invalidated the slot while the utility was paused'); + + open(my $irf, '>', $iresume) or die $!; + close($irf); + my $irc; + for (1 .. 120) { + my $r = waitpid($ipid, WNOHANG); + if ($r == $ipid) { $irc = $? >> 8; last; } + sleep(1); + } + terminate_child($ipid) unless defined $irc; + isnt($irc, 0, 'an invalidated provider slot makes the utility fail'); + { + open my $lf, '<', $ilog or die $!; + local $/; + my $log = <$lf>; + close $lf; + like($log, qr/replication slot ".*" on the provider was invalidated \(wal_status is "lost"\).*max_slot_wal_keep_size/s, + 'the failure names the invalidated slot and its likely cause'); + } + is(provider_slots(), '0', 'the failed run dropped its provider slot'); + + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'ALTER SYSTEM RESET max_slot_wal_keep_size'; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'SELECT pg_reload_conf()'; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "DELETE FROM t083 WHERE id > 100"; + unlink($ipaused, $iresume); + remove_tree($n2_datadir) if -d $n2_datadir; +} + +my $paused = "${n2_datadir}.spock_bidir_test_paused"; +my $resume = "${n2_datadir}.spock_bidir_test_resume"; +my $scs_log = "$log_dir/scs_enable_order.log"; +unlink($scs_log, $paused, $resume); + +my $pid = fork(); +die "fork() failed: $!" unless defined $pid; +if ($pid == 0) { + open(my $fh, '>>', $scs_log) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'subscribe_enable'; + setpgrp(0, 0); # own group, so END can stop it if a check dies + exec($SCS_BIN, + '--pgdata', $n2_datadir, + '--subscriber-name', 'n2', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn, + '--postgresql-conf', $n2_conf) or POSIX::_exit(127); +} +track_child($pid); + +my $reached = 0; +for (1 .. 120) { + if (-e $paused) { $reached = 1; last; } + last if waitpid($pid, WNOHANG) == $pid; + sleep(1); +} +ok($reached, 'utility reached the pause before enabling the subscription') + or do { diag(`tail -30 $scs_log`); done_testing(); exit 1; }; + +# The restore point the utility created: the provider logs its LSN, and the +# utility names it in its own output. +my $restore_lsn; +{ + open my $lf, '<', $scs_log or die $!; + my $out = do { local $/; <$lf> }; + close $lf; + my ($name) = $out =~ /restore point "(spock_create_subscriber_[0-9a-f]+_[0-9a-f]+_[0-9a-f]+)"/; + ok(defined $name, 'the utility named its restore point'); + open my $pl, '<', node_logfile(1) or die $!; + my $plog = do { local $/; <$pl> }; + close $pl; + ($restore_lsn) = $plog =~ /restore point "\Q$name\E" created at ([0-9A-F]+\/[0-9A-F]+)/ if defined $name; + ok(defined $restore_lsn, 'the provider logged the LSN of that restore point'); +} + +# A row committed on the provider after the restore point: the paused +# utility holds the subscription disabled, so it must not have reached the +# new node yet, and it must arrive exactly once after the resume. +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO t083 VALUES (500, 'paused')"; + +is(n2_query("SELECT sub_enabled FROM spock.subscription"), 'f', + 'subscription is disabled while the origin is being positioned'); +is(n2_query("SELECT sync_status FROM spock.local_sync_status"), 'r', + 'local sync status is READY, not INIT'); +is(n2_query("SELECT count(*) FROM pg_replication_origin"), '1', + 'replication origin exists'); +is(n2_query("SELECT remote_lsn FROM pg_replication_origin_status" + . " WHERE remote_lsn <> '0/0'"), $restore_lsn // 'no restore LSN', + 'origin is positioned exactly at the restore point'); +is(scalar_query(1, "SELECT count(*) FROM pg_replication_slots" + . " WHERE slot_type = 'logical' AND NOT active" + . " AND plugin = 'spock_output'"), '1', + 'provider slot is still there and inactive'); +is(scalar_query(1, "SELECT confirmed_flush_lsn < '" . ($restore_lsn // '0/0') + . "'::pg_lsn FROM pg_replication_slots" + . " WHERE plugin = 'spock_output'"), 't', + 'provider slot predates the restore point: it was not dropped and recreated'); +is(n2_query("SELECT count(*) FROM t083 WHERE id = 500"), '0', + 'the row committed after the restore point is not on the new node yet'); + +open(my $rf, '>', $resume) or die $!; +close($rf); + +my $deadline = time() + 120; +my $rc; +while (time() < $deadline) { + my $r = waitpid($pid, WNOHANG); + if ($r == $pid) { $rc = $? >> 8; last; } + sleep(1); +} +terminate_child($pid) unless defined $rc; +is($rc, 0, 'utility finished successfully') or diag(`tail -30 $scs_log`); + +{ + open my $lf, '<', $scs_log or die $!; + local $/; + my $log = <$lf>; + close $lf; + like($log, qr/restore point "spock_create_subscriber_[0-9a-f]{13}_[0-9a-f]+_[0-9a-f]+"/, + 'the restore point name carries a per-run suffix'); +} + +is(n2_query("SELECT sub_enabled FROM spock.subscription"), 't', + 'subscription is enabled after the resume'); +is(n2_query("SELECT count(*) FROM t083 WHERE v = 'pre'"), '100', + 'pre-existing rows are present exactly once'); +my $paused_row = '0'; +for (1 .. 30) { + $paused_row = n2_query("SELECT count(*) FROM t083 WHERE id = 500"); + last if $paused_row eq '1'; + sleep(1); +} +is($paused_row, '1', 'the row committed while the utility was paused arrives, once'); + +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO t083 VALUES (1000, 'post')"; +my $got = '0'; +for (1 .. 30) { + $got = n2_query("SELECT count(*) FROM t083 WHERE id = 1000"); + last if $got eq '1'; + sleep(1); +} +is($got, '1', 'a row written after the join replicates to the new node'); +is(n2_query("SELECT count(*) FROM t083"), '102', + 'no row was replayed twice'); + +system("$pg_bin/pg_ctl -D $n2_datadir -m fast stop >/dev/null 2>&1"); +remove_tree($n2_datadir); + +# A transaction prepared on the provider before the restore point and +# committed after it must not leave a stale prepared copy on the clone: the +# copy would hold locks the apply worker then blocks behind. Also runs with a +# --recovery-conf whose last line has no newline (the recovery target lines +# are appended after it, and would otherwise be swallowed by its comment). +{ + my $n1_dd = $config->{node_datadirs}->[0]; + + for (1 .. 20) { + last if scalar_query(1, "SELECT count(*) FROM pg_replication_slots " + . "WHERE plugin = 'spock_output' AND active") eq '0'; + sleep(1); + } + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots " + . "WHERE plugin = 'spock_output'"; + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'ALTER SYSTEM SET max_prepared_transactions = 5'; + system_or_bail "$pg_bin/pg_ctl", 'restart', '-D', $n1_dd, '-m', 'fast', '-w', + '-l', "$log_dir/n1_083_restart.log"; + ok(wait_for_pg_ready($host, $n1_port, $pg_bin, 30), 'provider restarted with prepared transactions enabled'); + + my $rconf = '/tmp/tmp_spock_node_1_recovery.conf.override_083'; + open my $rf2, '>', $rconf or die $!; + print $rf2 "primary_conninfo = '$n1_dsn'\n# last line, no trailing newline"; + close $rf2; + + my $p2paused = "${n2_datadir}.spock_bidir_test_paused"; + my $p2resume = "${n2_datadir}.spock_bidir_test_resume"; + my $p2log = "$log_dir/scs_prepared.log"; + unlink($p2log, $p2paused, $p2resume); + + my $p2pid = fork(); + die "fork() failed: $!" unless defined $p2pid; + if ($p2pid == 0) { + open(my $fh, '>>', $p2log) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'restore_point'; + setpgrp(0, 0); # own process group, so the END cleanup reaches its children + exec($SCS_BIN, '-v', + '--pgdata', $n2_datadir, + '--subscriber-name', 'n2', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n2_dsn, + '--postgresql-conf', $n2_conf, + '--recovery-conf', $rconf) or POSIX::_exit(127); + } + track_child($p2pid); + + my $p2reached = 0; + for (1 .. 180) { + if (-e $p2paused) { $p2reached = 1; last; } + last if waitpid($p2pid, WNOHANG) == $p2pid; + sleep(1); + } + ok($p2reached, 'utility reached the pause before the restore point') + or do { diag(`tail -30 $p2log`); done_testing(); exit 1; }; + + # Prepared after the slot exists and before the restore point; committed + # only after the clone is up. + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "BEGIN; INSERT INTO t083 VALUES (2000, 'prepared'); PREPARE TRANSACTION 'px083'"; + is(scalar_query(1, "SELECT count(*) FROM pg_prepared_xacts"), '1', + 'a transaction is prepared on the provider'); + + open(my $p2rf, '>', $p2resume) or die $!; + close($p2rf); + + my $p2rc; + for (1 .. 180) { + my $r = waitpid($p2pid, WNOHANG); + if ($r == $p2pid) { $p2rc = ($? & 127) ? 128 + ($? & 127) : ($? >> 8); last; } + sleep(1); + } + terminate_child($p2pid) unless defined $p2rc; + is($p2rc, 0, 'utility finished (the recovery-conf without a final newline did not stop recovery)') + or diag(`tail -30 $p2log`); + + open my $p2lf, '<', $p2log or die $!; + my $p2out = do { local $/; <$p2lf> }; + close $p2lf; + like($p2out, qr/Rolling back prepared transaction 'px083' carried in the backup/, + 'the prepared copy on the clone was rolled back'); + is(n2_query("SELECT count(*) FROM pg_prepared_xacts"), '0', + 'the clone holds no prepared transaction'); + + system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "COMMIT PREPARED 'px083'"; + my $got2 = '0'; + for (1 .. 60) { + $got2 = n2_query("SELECT count(*) FROM t083 WHERE id = 2000"); + last if $got2 eq '1'; + sleep(1); + } + is($got2, '1', 'the transaction committed after the restore point reaches the clone by replication'); + + system("$pg_bin/pg_ctl -D $n2_datadir -m fast stop >/dev/null 2>&1"); + remove_tree($n2_datadir); + unlink($rconf, $p2paused, $p2resume); +} + +unlink($n2_conf); +destroy_cluster('Destroy provider cluster'); +done_testing(); diff --git a/tests/tap/t/084_create_subscriber_exception_modes.pl b/tests/tap/t/084_create_subscriber_exception_modes.pl new file mode 100644 index 000000000..cf088340b --- /dev/null +++ b/tests/tap/t/084_create_subscriber_exception_modes.pl @@ -0,0 +1,464 @@ +# ============================================================================= +# Test: 084_create_subscriber_exception_modes.pl +# +# Until the forwarding through the source is cleared, the new node applies +# exactly what the source committed, on a copy of the source, so any apply +# failure there means it is not a faithful copy. Under +# spock.exception_behaviour = discard or transdiscard the failed transaction +# would be dropped and the origin would move on, and the join, which looks +# for a disabled subscription, would report a verified member with rows +# missing. spock_create_subscriber therefore runs the new node with +# sub_disable from the start of the catchup until clear_forwarding() is done, +# and then restores the configured value. +# +# For each of transdiscard and discard (configured on the new node): +# failure case A CHECK constraint exists on the new node only. The join +# is frozen right before the catchup subscription is enabled +# (SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE=catchup_enable), +# the override must already be in effect, a row that violates +# the constraint is written on the source, and the join must +# abort; --cleanup then leaves nothing behind. +# control case The source and the peer already hold rows in their +# spock.exception_log. The join must succeed, and the new +# node must end with its configured value, no leftover line +# in postgresql.auto.conf, no override record left in the +# manifest, and writable. +# crash case The join dies right after the coverage barrier with the +# override in effect. The in-progress manifest records the +# configured value, and --cleanup, which keeps the data +# directory, puts it back (twice in a row is fine). +# auto.conf The configured value comes from postgresql.auto.conf: it is +# restored with SET, so that exact line is there afterwards. +# With sub_disable configured nothing is overridden and the join succeeds. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(WNOHANG); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + system_maybe get_test_config scalar_query + wait_for_pg_ready + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +create_cluster(2, 'Create bidirectional 2-node cluster'); + +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; + +my $n1_dsn = "host=$host port=$node_ports->[0] dbname=$dbname" + . " user=$db_user password=$db_password"; + +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +sub spawn_background { + my ($logfile, @cmd) = @_; + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $logfile) or die "Cannot open $logfile: $!"; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + close($fh); + setpgrp(0, 0); # own process group, so the END cleanup reaches pg_basebackup too + exec(@cmd) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub wait_for_pid { + my ($pid, $timeout) = @_; + for (1 .. $timeout) { + my $r = waitpid($pid, WNOHANG); + return (($? & 127) ? 128 + ($? & 127) : ($? >> 8)) if $r == $pid; + sleep(1); + } + return undef; +} + +sub wait_for_zero_lag { + my ($node_num, $timeout) = @_; + for (1 .. $timeout) { + my $lag = scalar_query($node_num, + "SELECT COUNT(*) FROM pg_replication_slots" . + " WHERE slot_type = 'logical' AND plugin = 'spock_output'" . + " AND (confirmed_flush_lsn IS NULL OR confirmed_flush_lsn < pg_current_wal_lsn())"); + return 1 if defined $lag && $lag eq '0'; + sleep(1); + } + return 0; +} + +sub wait_for_file { + my ($path, $timeout) = @_; + for (1 .. $timeout) { + return 1 if -f $path; + sleep(1); + } + return 0; +} + +sub slurp { + my ($path) = @_; + return '' unless -f $path; + open my $fh, '<', $path or die "cannot read $path: $!"; + local $/; + my $t = <$fh>; + close $fh; + return $t; +} + +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + 'CREATE TABLE t084 (id serial PRIMARY KEY, val text)'; +system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, '-c', + "INSERT INTO t084 (val) SELECT 'pre' || g FROM generate_series(1, 50) g"; +ok(wait_for_zero_lag(1, 60), 'n1 -> n2 drained before the joins') + or BAIL_OUT('replication never drained'); +ok(wait_for_zero_lag(2, 60), 'n2 -> n1 drained before the joins') + or BAIL_OUT('replication never drained'); + +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_084_modes'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_paused = "${n3_datadir}.spock_bidir_test_paused"; +my $n3_resume = "${n3_datadir}.spock_bidir_test_resume"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override_084'; + +sub n3_query { + my ($sql) = @_; + my $out = `$pg_bin/psql -X -p $n3_port -d $dbname -t -A -c "$sql" 2>&1`; + chomp $out; + return $out; +} + +sub write_n3_conf { + my ($mode) = @_; + open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; + print $conf_fh "shared_preload_libraries='spock'\n"; + print $conf_fh output_plugin_libraries_conf($pg_bin); + print $conf_fh "wal_level=logical\n"; + print $conf_fh "spock.exception_behaviour=$mode\n"; + print $conf_fh "spock.conflict_resolution=last_update_wins\n"; + print $conf_fh "track_commit_timestamp=on\n"; + print $conf_fh "port=$n3_port\n"; + print $conf_fh "listen_addresses='*'\n"; + print $conf_fh "logging_collector=on\n"; + print $conf_fh "log_directory='$log_dir'\n"; + print $conf_fh "log_filename='00${n3_port}.log'\n"; + close $conf_fh; +} + +sub fresh_n3 { + remove_tree($n3_datadir) if -d $n3_datadir; + unlink($n3_pending, $n3_paused, $n3_resume); +} + +# Start the join in the background; $pause_at and $fail_after are step names +# or undef. +sub start_join { + my ($tag, $pause_at, $fail_after, @extra) = @_; + my $log = "$log_dir/scs_084_$tag.log"; + unlink($log); + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = $pause_at + if defined $pause_at; + local $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_FAIL_AFTER} = $fail_after + if defined $fail_after; + my $pid = spawn_background($log, + $SCS_BIN, '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + '--stall-timeout', '30', + '--max-wait', '180', + @extra); + return ($pid, $log); +} + +sub terminate_child { + my ($pid) = @_; + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { return if waitpid($pid, WNOHANG) == $pid; sleep(1); } + kill('KILL', -$pid); + waitpid($pid, 0); +} + +# --------------------------------------------------------------------------- +# failure case: a row that cannot be applied on the new node, written while +# the override is in effect +# --------------------------------------------------------------------------- +sub failure_case { + my ($mode) = @_; + + write_n3_conf($mode); + fresh_n3(); + my ($pid, $log) = start_join("fail_$mode", 'catchup_enable', undef); + + ok(wait_for_file($n3_paused, 240), + "[$mode] join paused right before the catchup subscription is enabled") + or do { diag(slurp($log)); terminate_child($pid); return; }; + + is(n3_query("SHOW spock.exception_behaviour"), 'sub_disable', + "[$mode] the new node runs with sub_disable although $mode is configured"); + like(slurp("$n3_datadir/postgresql.auto.conf"), + qr/^spock\.exception_behaviour\s*=\s*'sub_disable'/m, + "[$mode] the override is in postgresql.auto.conf"); + + ok(system_maybe("$pg_bin/psql", '-X', '-q', '-p', $n3_port, '-d', $dbname, + '-c', "ALTER TABLE t084 ADD CONSTRAINT t084_no_poison CHECK (val <> 'poison')"), + "[$mode] CHECK constraint added on the new node only"); + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, + '-c', "INSERT INTO t084 (val) VALUES ('before_$mode'), ('poison'), ('after_$mode')"; + + open(my $rf, '>', $n3_resume) or die $!; + close($rf); + + my $rc = wait_for_pid($pid, 300); + ok(defined $rc, "[$mode] the utility exited on its own") + or do { diag(slurp($log)); terminate_child($pid); $rc = -1; }; + isnt($rc, 0, "[$mode] the join fails instead of reporting a verified member"); + like(slurp($log), qr/was disabled/, + "[$mode] it fails because the catchup subscription was disabled"); + + my $clog = "$log_dir/scs_084_cleanup_$mode.log"; + unlink($clog); + my $cpid = spawn_background($clog, $SCS_BIN, '--bidirectional', + '--cleanup', '--pgdata', $n3_datadir); + my $crc = wait_for_pid($cpid, 120); + is($crc, 0, "[$mode] --cleanup exits 0 at the first attempt") + or diag(slurp($clog)); + ok(-d $n3_datadir, "[$mode] --cleanup keeps the new node's data directory"); + remove_tree($n3_datadir); + is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots" + . " WHERE slot_name LIKE 'spk_%n3%'"), + '0', "[$mode] no slot for the new node is left on n1"); + + # rows written for this case must not leak into the next one + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, + '-c', "DELETE FROM t084 WHERE val IN ('before_$mode', 'poison', 'after_$mode')"; + ok(wait_for_zero_lag(1, 60), "[$mode] n1 -> n2 drained after the failed join"); +} + +# --------------------------------------------------------------------------- +# control case: existing exception_log rows on the source and the peer +# --------------------------------------------------------------------------- +sub control_case { + my ($mode) = @_; + + write_n3_conf($mode); + fresh_n3(); + + for my $n (1, 2) { + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[$n - 1], + '-d', $dbname, '-c', + "INSERT INTO spock.exception_log (remote_origin, remote_commit_ts," + . " command_counter, retry_errored_at, remote_xid, error_message)" + . " VALUES (1, now(), 1, now(), 1, 'pre-existing exception $mode')"; + } + + my ($pid, $log) = start_join("ctl_$mode", undef, undef); + my $rc = wait_for_pid($pid, 400); + ok(defined $rc, "[$mode control] the utility exited on its own") + or do { diag(slurp($log)); terminate_child($pid); $rc = -1; }; + is($rc, 0, "[$mode control] the join succeeds with exceptions already logged" + . " on the source and the peer") + or diag(slurp($log)); + + is(n3_query("SHOW spock.exception_behaviour"), $mode, + "[$mode control] the new node ends with its configured value"); + unlike(slurp("$n3_datadir/postgresql.auto.conf"), + qr/spock\.exception_behaviour/, + "[$mode control] no spock.exception_behaviour line is left in postgresql.auto.conf"); + is(n3_query("SHOW spock.readonly"), 'off', + "[$mode control] the new node is writable"); + like(slurp("$n3_datadir/spock_bidirectional_manifest.json"), + qr/"status":\s*"complete"/, "[$mode control] the manifest says complete"); + unlike(slurp("$n3_datadir/spock_bidirectional_manifest.json"), + qr/exception_behaviour_orig/, + "[$mode control] the completed manifest holds no override record"); + + system_or_bail "$pg_bin/psql", '-q', '-p', $node_ports->[0], '-d', $dbname, + '-c', "INSERT INTO t084 (val) VALUES ('post_join_$mode')"; + my $got = 0; + for (1 .. 30) { + $got = n3_query("SELECT COUNT(*) FROM t084 WHERE val = 'post_join_$mode'"); + last if $got eq '1'; + sleep(1); + } + is($got, '1', "[$mode control] a post-join write on n1 reaches the new node"); + + ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, + $node_ports->[0], $node_ports->[1]), + "[$mode control] the new node is taken out of the cluster again") + or BAIL_OUT("teardown of $n3_datadir failed"); + ok(wait_for_zero_lag(1, 60), "[$mode control] n1 -> n2 drained after the teardown"); +} + +# --------------------------------------------------------------------------- +# crash case: the join dies with the override in effect; --cleanup restores +# --------------------------------------------------------------------------- +sub crash_case { + my ($mode) = @_; + + write_n3_conf($mode); + fresh_n3(); + my ($pid, $log) = start_join("crash_$mode", undef, 'coverage_barrier'); + my $rc = wait_for_pid($pid, 400); + ok(defined $rc, "[$mode crash] the utility exited on its own") + or do { diag(slurp($log)); terminate_child($pid); $rc = -1; }; + isnt($rc, 0, "[$mode crash] the join died after the coverage barrier"); + like(slurp($log), qr/test-injected failure after step "coverage_barrier"/, + "[$mode crash] it died where the test injected the failure"); + + my $manifest = "$n3_datadir/spock_bidirectional_manifest.json"; + like(slurp($manifest), qr/"status":\s*"in_progress"/, + "[$mode crash] the manifest is in progress"); + like(slurp($manifest), qr/"exception_behaviour_orig":\s*"$mode"/, + "[$mode crash] the manifest records the configured value"); + like(slurp($manifest), qr/"exception_behaviour_orig_in_auto_conf":\s*false/, + "[$mode crash] ... and that it did not come from postgresql.auto.conf"); + like(slurp("$n3_datadir/postgresql.auto.conf"), + qr/^spock\.exception_behaviour\s*=\s*'sub_disable'/m, + "[$mode crash] the override is still in postgresql.auto.conf"); + + my $clog = "$log_dir/scs_084_crash_cleanup_$mode.log"; + unlink($clog); + my $cpid = spawn_background($clog, $SCS_BIN, '--bidirectional', + '--cleanup', '--pgdata', $n3_datadir); + my $crc = wait_for_pid($cpid, 120); + is($crc, 0, "[$mode crash] --cleanup exits 0") or diag(slurp($clog)); + like(slurp($clog), qr/Restoring spock\.exception_behaviour = '$mode'/, + "[$mode crash] --cleanup restores the recorded value"); + ok(-d $n3_datadir, "[$mode crash] the data directory is kept"); + unlike(slurp("$n3_datadir/postgresql.auto.conf"), + qr/spock\.exception_behaviour/, + "[$mode crash] no override is left in postgresql.auto.conf"); + ok(!-f $manifest, "[$mode crash] the manifest is gone after a complete cleanup"); + + my $clog2 = "$log_dir/scs_084_crash_cleanup2_$mode.log"; + unlink($clog2); + $cpid = spawn_background($clog2, $SCS_BIN, '--bidirectional', + '--cleanup', '--pgdata', $n3_datadir); + is(wait_for_pid($cpid, 120), 0, "[$mode crash] a second --cleanup is fine") + or diag(slurp($clog2)); + unlike(slurp("$n3_datadir/postgresql.auto.conf"), + qr/spock\.exception_behaviour/, + "[$mode crash] still no override after the second --cleanup"); + is(scalar_query(1, "SELECT COUNT(*) FROM pg_replication_slots" + . " WHERE slot_name LIKE 'spk_%n3%'"), + '0', "[$mode crash] no slot for the new node is left on n1"); + remove_tree($n3_datadir); + unlink($n3_pending); + ok(wait_for_zero_lag(1, 60), "[$mode crash] n1 -> n2 drained after the cleanup"); +} + +# --------------------------------------------------------------------------- +# auto.conf case: the configured value comes from postgresql.auto.conf +# --------------------------------------------------------------------------- +sub auto_conf_case { + my $orig = 'transdiscard'; + + write_n3_conf('discard'); # postgresql.conf says discard ... + my $auto = '/tmp/tmp_spock_node_2_postgresql.auto.conf.override_084'; + open my $afh, '>', $auto or die "Cannot write $auto: $!"; + print $afh "spock.exception_behaviour = '$orig'\n"; # ... auto.conf wins + close $afh; + fresh_n3(); + + my ($pid, $log) = start_join("auto", 'catchup_enable', undef, + '--postgresql-auto-conf', $auto); + ok(wait_for_file($n3_paused, 240), + "[auto.conf] join paused right before the catchup subscription is enabled") + or do { diag(slurp($log)); terminate_child($pid); unlink($auto); return; }; + like(slurp("$n3_datadir/spock_bidirectional_manifest.json"), + qr/"exception_behaviour_orig":\s*"$orig"/, + "[auto.conf] the manifest records the value from postgresql.auto.conf"); + like(slurp("$n3_datadir/spock_bidirectional_manifest.json"), + qr/"exception_behaviour_orig_in_auto_conf":\s*true/, + "[auto.conf] ... and that it came from there"); + is(n3_query("SHOW spock.exception_behaviour"), 'sub_disable', + "[auto.conf] the override is in effect"); + open(my $rf, '>', $n3_resume) or die $!; + close($rf); + + my $rc = wait_for_pid($pid, 400); + is($rc, 0, "[auto.conf] the join succeeds") or diag(slurp($log)); + is(n3_query("SHOW spock.exception_behaviour"), $orig, + "[auto.conf] the new node ends with the value from postgresql.auto.conf"); + my @lines = grep { /^spock\.exception_behaviour\s*=/ } + split(/\n/, slurp("$n3_datadir/postgresql.auto.conf")); + is(scalar(@lines), 1, "[auto.conf] exactly one spock.exception_behaviour line is left"); + like($lines[0] // '', qr/^spock\.exception_behaviour\s*=\s*'$orig'$/, + "[auto.conf] ... and it is the original one"); + unlike(slurp("$n3_datadir/spock_bidirectional_manifest.json"), + qr/exception_behaviour_orig/, + "[auto.conf] the completed manifest holds no override record"); + ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, + $node_ports->[0], $node_ports->[1]), + "[auto.conf] the new node is taken out of the cluster again"); + unlink($auto); +} + +failure_case('transdiscard'); +control_case('transdiscard'); +failure_case('discard'); +control_case('discard'); +crash_case('transdiscard'); +auto_conf_case(); + +# sub_disable configured: nothing is overridden +{ + my $mode = 'sub_disable'; + write_n3_conf($mode); + fresh_n3(); + my ($pid, $log) = start_join("ctl_$mode", 'catchup_enable', undef); + ok(wait_for_file($n3_paused, 240), + "[$mode] join paused right before the catchup subscription is enabled") + or do { diag(slurp($log)); terminate_child($pid); }; + unlike(slurp("$n3_datadir/postgresql.auto.conf"), + qr/spock\.exception_behaviour/, + "[$mode] nothing was written to postgresql.auto.conf"); + open(my $rf, '>', $n3_resume) or die $!; + close($rf); + my $rc = wait_for_pid($pid, 400); + is($rc, 0, "[$mode] the join succeeds") or diag(slurp($log)); + is(n3_query("SHOW spock.exception_behaviour"), $mode, + "[$mode] the new node still runs with sub_disable"); + unlike(slurp("$n3_datadir/postgresql.auto.conf"), + qr/spock\.exception_behaviour/, + "[$mode] postgresql.auto.conf has no spock.exception_behaviour line"); + ok(teardown_joined_node($n3_port, 'n3', $n3_datadir, + $node_ports->[0], $node_ports->[1]), + "[$mode] the new node is taken out of the cluster again"); +} + +unlink($n3_conf, $n3_paused, $n3_resume); +destroy_cluster('Destroy 2-node cluster'); +done_testing(); diff --git a/tests/tap/t/085_create_subscriber_rmgr_replay.pl b/tests/tap/t/085_create_subscriber_rmgr_replay.pl new file mode 100644 index 000000000..e71182992 --- /dev/null +++ b/tests/tap/t/085_create_subscriber_rmgr_replay.pl @@ -0,0 +1,177 @@ +# ============================================================================= +# Test: 085_create_subscriber_rmgr_replay.pl +# +# The clone is started without spock until the source's spock catalog is +# stripped, but the WAL it replays up to the restore point can contain records +# of spock's own resource manager (resource.dat dumps, written at a table +# sync, at ADD_NODE and when the provider shuts down). Redo of such a record +# with the resource manager unregistered stops with "resource manager with ID +# ... not registered", and every retry on that backup stops at the same +# record. +# +# SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE=restore_point freezes the utility +# after the base backup; restarting the provider then writes the shutdown +# dump into the window between the backup and the restore point. After the +# resume the join must succeed and the clone must have replayed the record. +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(WNOHANG); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + get_test_config scalar_query wait_for_pg_ready + output_plugin_libraries_conf + track_child track_datadir teardown_joined_node); + +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +create_cluster(2, 'Create provider cluster'); +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 so the provider has progress entries to dump'); + +my $config = get_test_config(); +my $host = $config->{host}; +my $dbname = $config->{db_name}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; +my $n1_port = $config->{node_ports}->[0]; +my $n1_datadir = $config->{node_datadirs}->[0]; + +my $n1_dsn = "host=$host port=$n1_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +my $n3_port = $n1_port + 2; +my $n3_datadir = '/tmp/tmp_spock_node_1_datadir_085_rmgr_replay'; +track_datadir($n3_datadir); +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; +remove_tree($n3_datadir) if -d $n3_datadir; + +my $n3_conf = '/tmp/tmp_spock_node_1_postgresql.conf.override_085'; +my $n3_log = "$log_dir/00${n3_port}.log"; +unlink($n3_log); +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + 'CREATE TABLE t085 (id int PRIMARY KEY, v text)'; +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO t085 SELECT g, 'pre' FROM generate_series(1, 100) g"; + +sub terminate_child { + my ($pid) = @_; + + # kill(sig, 0) signals this process's own group, which must never happen + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { + return if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + diag("child $pid ignored SIGTERM for 30s; sending KILL to its process group"); + kill('KILL', -$pid); + waitpid($pid, 0); +} + +my $paused = "${n3_datadir}.spock_bidir_test_paused"; +my $resume = "${n3_datadir}.spock_bidir_test_resume"; +my $scs_log = "$log_dir/scs_rmgr_replay.log"; +unlink($scs_log, $paused, $resume); + +my $pid = fork(); +die "fork() failed: $!" unless defined $pid; +if ($pid == 0) { + open(my $fh, '>>', $scs_log) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + $ENV{SPOCK_CREATE_SUBSCRIBER_TEST_PAUSE_BEFORE} = 'restore_point'; + setpgrp(0, 0); # own group, so END can stop it if a check dies + exec($SCS_BIN, + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf) or POSIX::_exit(127); +} +track_child($pid); + +my $reached = 0; +for (1 .. 120) { + if (-e $paused) { $reached = 1; last; } + last if waitpid($pid, WNOHANG) == $pid; + sleep(1); +} +ok($reached, 'utility reached the pause after the base backup') + or do { diag(`tail -30 $scs_log`); terminate_child($pid); done_testing(); exit 1; }; + +# The shutdown of the provider writes one resource.dat dump record per +# progress entry; they land after the backup started and before the restore +# point the utility creates once it is resumed. +is(system("$pg_bin/pg_ctl -D '$n1_datadir' -m fast -w restart >/dev/null 2>&1"), 0, + 'the provider was restarted while the utility was paused'); +ok(wait_for_pg_ready($host, $n1_port, $pg_bin, 60), 'the provider accepts connections again'); +system_or_bail "$pg_bin/psql", '-q', '-p', $n1_port, '-d', $dbname, '-c', + "INSERT INTO t085 SELECT g, 'during' FROM generate_series(101, 150) g"; + +open(my $rf, '>', $resume) or die $!; +close($rf); + +my $rc; +for (1 .. 300) { + if (waitpid($pid, WNOHANG) == $pid) { $rc = $? >> 8; last; } + sleep(1); +} +terminate_child($pid) unless defined $rc; +is($rc, 0, 'the join succeeds although the replayed WAL holds spock resource-manager records') + or diag(`tail -40 $scs_log`); + +open my $lf, '<', $n3_log or die "cannot read $n3_log: $!"; +my $n3_text = do { local $/; <$lf> }; +close $lf; +unlike($n3_text, qr/resource manager with ID \d+ not registered/, + 'redo did not stop at an unregistered resource manager'); +like($n3_text, qr/SPOCK rmgr: resource\.dat dump replayed \(event=shutdown/, + 'the clone replayed the provider\'s shutdown dump with the resource manager registered'); + +is(scalar(`$pg_bin/psql -X -p $n3_port -d $dbname -t -A -c "SELECT pg_is_in_recovery()"`), + "f\n", 'the new node is promoted'); +is(scalar(`$pg_bin/psql -X -p $n3_port -d $dbname -t -A -c "SELECT count(*) FROM spock.subscription"`), + "1\n", 'the new node has its subscription'); +my $rows = 0; +for (1 .. 60) { + $rows = `$pg_bin/psql -X -p $n3_port -d $dbname -t -A -c "SELECT count(*) FROM t085"`; + chomp $rows; + last if $rows eq '150'; + sleep(1); +} +is($rows, '150', 'the rows from before and during the pause are on the new node'); + +ok(teardown_joined_node($n3_port, 'n3', $n3_datadir), + 'the new node is torn down'); +unlink($paused, $resume); + +destroy_cluster('Destroy test cluster'); +done_testing(); diff --git a/tests/tap/t/086_create_subscriber_slot_cancel.pl b/tests/tap/t/086_create_subscriber_slot_cancel.pl new file mode 100644 index 000000000..13a83cc72 --- /dev/null +++ b/tests/tap/t/086_create_subscriber_slot_cancel.pl @@ -0,0 +1,257 @@ +#!/usr/bin/perl +# ============================================================================= +# Test: 086_create_subscriber_slot_cancel.pl - the source slot creation of a +# --bidirectional join must be stoppable +# ============================================================================= +# pg_create_logical_replication_slot() waits for every write transaction that +# was running when it started. With one held open on the source, the utility +# must still stop (a) on SIGTERM, (b) at --max-wait, and (c) a killed utility +# must not leave a slot behind once the transaction ends -- the source backend +# notices the lost client (client_connection_check_interval) and gives up. +# +# (a) SIGTERM during the slot creation -> exit 1 within seconds, "Canceling", +# no slot +# (b) --max-wait 8 -> exit 1 after about 8 seconds with the timeout message, +# no slot +# (c) SIGKILL of the utility -> the waiting backend on the source goes away +# within seconds; no slot once the writer ends +# ============================================================================= + +use strict; +use warnings; +use Test::More; +use File::Path qw(remove_tree); +use POSIX qw(WNOHANG); +use Time::HiRes qw(time); +use lib '.'; +use SpockTest qw(create_cluster cross_wire destroy_cluster system_or_bail + get_test_config scalar_query output_plugin_libraries_conf + track_child track_datadir); + +my $SCS_BIN; +for my $dir (split(':', $ENV{PATH} // '')) { + my $c = "$dir/spock_create_subscriber"; + if (-x $c) { $SCS_BIN = $c; last; } +} +unless (defined $SCS_BIN) { + my $bt = '../../utils/spock_create_subscriber/spock_create_subscriber'; + $SCS_BIN = $bt if -x $bt; +} +BAIL_OUT("spock_create_subscriber binary not found; run 'make install' first") + unless defined $SCS_BIN; + +create_cluster(2, 'Create bidirectional 2-node cluster'); +my $config = get_test_config(); +my $node_ports = $config->{node_ports}; +my $dbname = $config->{db_name}; +my $host = $config->{host}; +my $db_user = $config->{db_user}; +my $db_password = $config->{db_password}; +my $pg_bin = $config->{pg_bin}; +my $log_dir = $config->{log_dir}; +cross_wire(2, ['n1', 'n2'], 'Cross-wire n1 <-> n2 bidirectionally'); + +my $n1_port = $node_ports->[0]; +my $n1_dsn = "host=$host port=$n1_port dbname=$dbname" + . " user=$db_user password=$db_password"; +my $n3_port = $node_ports->[1] + 1; +my $n3_datadir = '/tmp/tmp_spock_node_2_datadir_bidir_slotcancel'; +track_datadir($n3_datadir); +my $n3_pending = "${n3_datadir}.spock_bidir_pending.json"; +my $n3_dsn = "host=$host port=$n3_port dbname=$dbname" + . " user=$db_user password=$db_password"; + +my $n3_conf = '/tmp/tmp_spock_node_2_postgresql.conf.override.slotcancel'; +open my $conf_fh, '>', $n3_conf or die "Cannot write $n3_conf: $!"; +print $conf_fh "shared_preload_libraries='spock'\n"; +print $conf_fh output_plugin_libraries_conf($pg_bin); +print $conf_fh "wal_level=logical\n"; +print $conf_fh "spock.enable_ddl_replication=on\n"; +print $conf_fh "spock.include_ddl_repset=on\n"; +print $conf_fh "spock.allow_ddl_from_functions=on\n"; +print $conf_fh "spock.exception_behaviour=sub_disable\n"; +print $conf_fh "spock.conflict_resolution=last_update_wins\n"; +print $conf_fh "track_commit_timestamp=on\n"; +print $conf_fh "port=$n3_port\n"; +print $conf_fh "listen_addresses='*'\n"; +print $conf_fh "logging_collector=on\n"; +print $conf_fh "log_directory='$log_dir'\n"; +print $conf_fh "log_filename='00${n3_port}.log'\n"; +close $conf_fh; + +system_or_bail "$pg_bin/psql", '-X', '-q', '-p', $n1_port, '-d', $dbname, '-c', + "CREATE TABLE slotcancel_t (a int)"; + +sub terminate_child { + my ($pid) = @_; + return unless defined $pid && $pid > 0; + kill('TERM', -$pid); + for (1 .. 30) { return if waitpid($pid, WNOHANG) == $pid; sleep(1); } + kill('KILL', -$pid); + waitpid($pid, 0); +} + +sub n3_slots { + return scalar_query(1, + "SELECT count(*) FROM pg_replication_slots WHERE slot_name LIKE 'spk_%n3%'"); +} + +sub creating_backends { + return scalar_query(1, "SELECT count(*) FROM pg_stat_activity" + . " WHERE query LIKE '%pg_create_logical_replication_slot%'" + . " AND pid <> pg_backend_pid()"); +} + +sub start_join { + my ($log, @extra) = @_; + remove_tree($n3_datadir) if -d $n3_datadir; + unlink($n3_pending) if -f $n3_pending; + unlink($log); + my $pid = fork(); + die "fork() failed: $!" unless defined $pid; + if ($pid == 0) { + open(my $fh, '>>', $log) or die $!; + open(STDOUT, '>&', $fh) or die $!; + open(STDERR, '>&', $fh) or die $!; + setpgrp(0, 0); + exec($SCS_BIN, '--bidirectional', + '--pgdata', $n3_datadir, + '--subscriber-name', 'n3', + '--provider-dsn', $n1_dsn, + '--subscriber-dsn', $n3_dsn, + '--postgresql-conf', $n3_conf, + @extra) or POSIX::_exit(127); + } + track_child($pid); + return $pid; +} + +sub wait_creating { + my ($pid) = @_; + my $n = 0; + for (1 .. 60) { + $n = creating_backends(); + last if $n ne '0'; + last if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + return $n; +} + +sub wait_exit { + my ($pid, $secs) = @_; + for (1 .. $secs) { + return ($? >> 8) if waitpid($pid, WNOHANG) == $pid; + sleep(1); + } + return undef; +} + +sub slurp { + my ($f) = @_; + open my $fh, '<', $f or return ''; + local $/; + my $t = <$fh>; + close $fh; + return $t // ''; +} + +# A write transaction held open on the source for the whole test. +my $wpid = fork(); +die "fork() failed: $!" unless defined $wpid; +if ($wpid == 0) { + open(STDOUT, '>', '/dev/null') or die $!; + open(STDERR, '>', '/dev/null') or die $!; + setpgrp(0, 0); + exec("$pg_bin/psql", '-X', '-q', '-p', $n1_port, '-d', $dbname, '-c', + "BEGIN; INSERT INTO slotcancel_t VALUES (1); SELECT pg_sleep(600);") + or POSIX::_exit(127); +} +track_child($wpid); +my $holding = 0; +for (1 .. 30) { + $holding = scalar_query(1, "SELECT count(*) FROM pg_stat_activity" + . " WHERE query LIKE '%slotcancel_t%' AND state = 'active'" + . " AND pid <> pg_backend_pid()"); + last if $holding ne '0'; + sleep(1); +} +isnt($holding, '0', 'a write transaction is open on the source') + or BAIL_OUT('could not hold a transaction open'); + +# (a) SIGTERM +{ + my $log = "$log_dir/scs_slotcancel_term.log"; + my $pid = start_join($log); + isnt(wait_creating($pid), '0', '(a) the utility waits in the slot creation') + or do { diag(slurp($log)); terminate_child($pid); terminate_child($wpid); done_testing(); exit 1 }; + sleep(2); + my $t0 = time(); + kill('TERM', $pid); + my $rc = wait_exit($pid, 30); + my $took = time() - $t0; + terminate_child($pid) unless defined $rc; + is($rc, 1, '(a) SIGTERM makes the utility exit with status 1'); + cmp_ok($took, '<', 20, sprintf('(a) it stopped within %.1fs', $took)); + like(slurp($log), qr/Canceling\.\.\./, '(a) the cancellation is reported'); + is(n3_slots(), '0', '(a) no slot is left on the source'); + is(creating_backends(), '0', '(a) the slot creation was cancelled on the source'); +} + +# (b) --max-wait +{ + my $log = "$log_dir/scs_slotcancel_maxwait.log"; + my $pid = start_join($log, '--max-wait', '8'); + isnt(wait_creating($pid), '0', '(b) the utility waits in the slot creation') + or do { diag(slurp($log)); terminate_child($pid); terminate_child($wpid); done_testing(); exit 1 }; + my $t0 = time(); + my $rc = wait_exit($pid, 60); + my $took = time() - $t0; + terminate_child($pid) unless defined $rc; + is($rc, 1, '(b) --max-wait makes the utility exit with status 1'); + cmp_ok($took, '<', 30, sprintf('(b) it stopped after %.1fs', $took)); + like(slurp($log), qr/timed out after 8 second\(s\) waiting to create replication slot/, + '(b) the timeout is reported'); + is(n3_slots(), '0', '(b) no slot is left on the source'); + is(creating_backends(), '0', '(b) the slot creation was cancelled on the source'); +} + +# (c) SIGKILL. Needs client_connection_check_interval, which not every +# platform has; skip loudly where the server rejects it. +my $check_supported = system("$pg_bin/psql", '-X', '-q', '-p', $n1_port, + '-d', $dbname, '-c', "SET client_connection_check_interval = '1s'") == 0; +SKIP: { + skip('client_connection_check_interval is not available on this platform', 2) + unless $check_supported; + + my $log = "$log_dir/scs_slotcancel_kill.log"; + my $pid = start_join($log); + isnt(wait_creating($pid), '0', '(c) the utility waits in the slot creation') + or do { diag(slurp($log)); terminate_child($pid); terminate_child($wpid); done_testing(); exit 1 }; + sleep(1); + kill('KILL', $pid); + waitpid($pid, 0); + my $gone = 0; + my $t0 = time(); + for (1 .. 30) { + if (creating_backends() eq '0') { $gone = 1; last } + sleep(1); + } + my $took = time() - $t0; + ok($gone, sprintf('(c) the source backend gave up %.1fs after the utility was killed', $took)); +} + +# Release the writer; only now could a surviving backend finish its slot. +system_or_bail "$pg_bin/psql", '-X', '-q', '-p', $n1_port, '-d', $dbname, '-c', + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity" + . " WHERE query LIKE '%slotcancel_t%' AND pid <> pg_backend_pid()"; +terminate_child($wpid); +sleep(3); +is(n3_slots(), '0', '(c) no slot appeared on the source once the transaction ended'); + +remove_tree($n3_datadir) if -d $n3_datadir; +unlink($n3_pending) if -f $n3_pending; +unlink($n3_conf) if -f $n3_conf; +destroy_cluster('Destroy 2-node cluster'); + +done_testing(); diff --git a/tests/tap/t/SpockTest.pm b/tests/tap/t/SpockTest.pm index 9a1a3b29e..e9fe35d95 100644 --- a/tests/tap/t/SpockTest.pm +++ b/tests/tap/t/SpockTest.pm @@ -6,7 +6,7 @@ use Exporter 'import'; use Test::More; use TAP::Formatter::Color; use TAP::Harness; -use File::Path qw(make_path); +use File::Path qw(make_path remove_tree); use File::Basename; use File::Spec; use Time::HiRes qw(usleep); @@ -34,6 +34,9 @@ our @EXPORT_OK = qw( poll_query_until sync_nodes apply_worker_pid + track_child + track_datadir + teardown_joined_node ); # Test configuration @@ -697,8 +700,78 @@ sub apply_worker_pid { return ''; } +# Background children (process-group leaders) and extra postmasters a test +# started itself, so the END block can stop them when the test leaves early +# (BAIL_OUT, die). Without it a surviving child or node keeps its port and +# makes the next test in the run fail. +my $OWNER_PID = $$; +my @tracked_children; +my @tracked_datadirs; + +sub track_child { push @tracked_children, @_; return; } +sub track_datadir { push @tracked_datadirs, @_; return; } + +sub _stop_tracked { + return unless $$ == $OWNER_PID; + + # kill(0, ...) is true only while the group still has members, so a child + # the test already reaped is left alone. + for my $pid (@tracked_children) { + next unless kill(0, -$pid); + kill('TERM', -$pid); + } + for (1 .. 20) { + last unless grep { kill(0, -$_) } @tracked_children; + usleep(250_000); + } + for my $pid (@tracked_children) { + next unless kill(0, -$pid); + kill('KILL', -$pid); + waitpid($pid, 0); + } + for my $dir (@tracked_datadirs) { + next unless -f "$dir/postmaster.pid"; + system("$PG_BIN/pg_ctl -D '$dir' -m immediate -w stop >/dev/null 2>&1"); + } +} + +# Take a node whose join completed out of the cluster, the way a person has +# to: spock_create_subscriber --cleanup refuses a live cluster member. Drops +# the reverse subscriptions on the other nodes (their slots live on the node, +# so it must still be running), then the node's own subscriptions, then stops +# it and removes its data directory and the pending-cleanup record. Nodes +# are given by port. Returns true if every drop worked and the directory is +# gone. +sub teardown_joined_node { + my ($node_port, $node_name, $datadir, @peer_ports) = @_; + + my $failed = 0; + my $on_port = sub { + my ($port, $sql) = @_; + system("$PG_BIN/psql", '-X', '-q', '-v', 'ON_ERROR_STOP=1', + '-p', $port, '-d', $DB_NAME, '-c', $sql) == 0 + or do { $failed++; + diag("teardown of $node_name: failed on port $port: $sql"); }; + }; + + for my $peer (@peer_ports) { + $on_port->($peer, + "SELECT spock.sub_drop(s.sub_name, true) FROM spock.subscription s " + . "JOIN spock.node n ON n.node_id = s.sub_origin " + . "WHERE n.node_name = '$node_name'"); + } + $on_port->($node_port, + "SELECT spock.sub_drop(sub_name, true) FROM spock.subscription"); + system("$PG_BIN/pg_ctl -D '$datadir' -m fast -w stop >/dev/null 2>&1") + if -f "$datadir/postmaster.pid"; + remove_tree($datadir) if -d $datadir; + unlink("$datadir.spock_bidir_pending.json"); + return !$failed && !-d $datadir; +} + # Ensure cleanup on module destruction END { + _stop_tracked(); destroy_cluster() if $nodes_created; } diff --git a/utils/pgindent/typedefs.list b/utils/pgindent/typedefs.list index 8c546cc11..4b16df9f7 100644 --- a/utils/pgindent/typedefs.list +++ b/utils/pgindent/typedefs.list @@ -1,3 +1,17 @@ +BidirectionalState +CatalogCapture +CleanupDropOutcome +ManifestParseState +PeerNodeInfo +RemoteInfo +RepsetCapture +RepsetFingerprintEntry +RepsetTableCapture +ReverseSubTarget +SequenceCapture +SubscriberCreateContext +VerbosityLevelEnum +WaitTracker __m128i __m512i __mmask64 diff --git a/utils/spock_create_subscriber/Makefile b/utils/spock_create_subscriber/Makefile new file mode 100644 index 000000000..ebbef3180 --- /dev/null +++ b/utils/spock_create_subscriber/Makefile @@ -0,0 +1,19 @@ +# Makefile for spock_create_subscriber utility +PG_CONFIG ?= pg_config +PROGRAM = spock_create_subscriber + +PG_CPPFLAGS = -I../../include -I$(shell $(PG_CONFIG) --includedir) +PG_LDFLAGS = -lpq -L$(shell $(PG_CONFIG) --libdir) + +# the symlink rule below must not become the default goal +.DEFAULT_GOAL := all + +# create symlink to spock_fe.c here +spock_fe.c: ../../src/spock_fe.c + ln -sf $< $@ +EXTRA_CLEAN = spock_fe.c +OBJS = spock_create_subscriber.o common.o manifest.o preflight.o spock_fe.o + +# PGXS +PGXS := $(shell $(PG_CONFIG) --pgxs) +include $(PGXS) diff --git a/utils/spock_create_subscriber/common.c b/utils/spock_create_subscriber/common.c new file mode 100644 index 000000000..f591ff8a6 --- /dev/null +++ b/utils/spock_create_subscriber/common.c @@ -0,0 +1,873 @@ +/*------------------------------------------------------------------------- + * + * common.c + * Helpers shared by spock_create_subscriber.c and manifest.c: output, + * connection strings, files and paths. Nothing here depends on the + * state of a join. + * + *------------------------------------------------------------------------- + */ +#include "postgres_fe.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common/file_utils.h" +#include "libpq-fe.h" +#include "port.h" +#include "pqexpbuffer.h" + +#include "spock_create_subscriber.h" + +VerbosityLevelEnum verbosity = VERBOSITY_NORMAL; + +static char *PQconninfoParamsToConnstr(const char *const *keywords, const char *const *values); +static void appendPQExpBufferConnstrValue(PQExpBuffer buf, const char *str); + +/* + * Print message to stdout and flush + */ +void +print_msg(VerbosityLevelEnum level, const char *fmt,...) +{ + if (verbosity >= level) + { + va_list argptr; + + va_start(argptr, fmt); + vfprintf(stdout, fmt, argptr); + va_end(argptr); + fflush(stdout); + } +} + +/* + * PQexec() wrapper that logs the query text at VERBOSITY_DEBUG (-v -v) + * before running it, and the resulting status/row count after -- a + * drop-in replacement so every query this tool issues is traceable + * without a separate print_msg() call at each site. Callers still do + * their own PQresultStatus()/die() handling on the result exactly as + * with a plain PQexec() call. + */ +PGresult * +debug_exec(PGconn *conn, const char *query) +{ + PGresult *res; + + print_msg(VERBOSITY_DEBUG, _(" > %s\n"), query); + res = PQexec(conn, query); + if (verbosity >= VERBOSITY_DEBUG) + { + if (PQresultStatus(res) == PGRES_TUPLES_OK) + print_msg(VERBOSITY_DEBUG, _(" < %s (%d row(s))\n"), + PQresStatus(PQresultStatus(res)), PQntuples(res)); + else + print_msg(VERBOSITY_DEBUG, _(" < %s\n"), + PQresStatus(PQresultStatus(res))); + } + + return res; +} + +/* + * Like debug_exec(), for a statement that carries a connection string and so + * possibly a password: the debug trace names the statement but does not show + * it. + */ +PGresult * +debug_exec_sensitive(PGconn *conn, const char *query, const char *what) +{ + PGresult *res; + + print_msg(VERBOSITY_DEBUG, _(" > %s (statement not shown: it contains a " + "connection string)\n"), what); + res = PQexec(conn, query); + if (verbosity >= VERBOSITY_DEBUG) + print_msg(VERBOSITY_DEBUG, _(" < %s\n"), + PQresStatus(PQresultStatus(res))); + return res; +} + +/* + * Append str to buf as one shell word, so that a path or connection string + * reaches the child process unchanged whatever characters it holds. (libpq + * escaping of a connection string is not shell escaping.) + */ +void +append_shell_arg(PQExpBuffer buf, const char *str) +{ +#ifndef WIN32 + const char *p; + + appendPQExpBufferChar(buf, '\''); + for (p = str; *p; p++) + { + if (*p == '\'') + appendPQExpBufferStr(buf, "'\\''"); + else + appendPQExpBufferChar(buf, *p); + } + appendPQExpBufferChar(buf, '\''); +#else + if (strchr(str, '"') != NULL) + die(_("a path or connection string containing a double quote cannot " + "be passed to a child process on this platform\n")); + appendPQExpBuffer(buf, "\"%s\"", str); +#endif +} + +/* + * Parse optarg as a base-10 integer, dying with a message naming + * opt_name if any part of it isn't numeric or the value doesn't fit in + * an int -- shared by every --