Skip to content

[WIP] Physical to logical replica support - #521

Draft
rasifr wants to merge 53 commits into
mainfrom
task/SPOC-601/physical-to-logical-replica
Draft

rasifr wants to merge 53 commits into
mainfrom
task/SPOC-601/physical-to-logical-replica

Conversation

@rasifr

@rasifr rasifr commented Jul 9, 2026

Copy link
Copy Markdown
Member

No description provided.

@rasifr rasifr self-assigned this Jul 9, 2026
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

This PR adds the spock_create_subscriber utility with build and documentation updates, and changes forwarded-origin caching and advancement in spock_apply.c. The TAP test expands cascade replication coverage, gap handling, and direct subscription behavior.

Changes: spock_create_subscriber Utility

Layer / File(s) Summary
Build wiring and documentation
Makefile, utils/spock_create_subscriber/Makefile, .gitignore, docs/creating_subscriber_nodes.md
Adds recursive build wiring, PGXS build setup, removes the ignore entry, and documents subscriber creation and supported CLI options.
CLI and subscriber setup flow
utils/spock_create_subscriber/spock_create_subscriber.c
Adds option parsing, validation, provider checks, data-directory initialization, restore-point recovery, process control, and subscription orchestration.
Replication and subscription initialization
utils/spock_create_subscriber/spock_create_subscriber.c
Adds provider metadata validation, logical slot creation, extension cleanup, replication-origin setup, and Spock node and subscription creation.
Connection, configuration, and filesystem helpers
utils/spock_create_subscriber/spock_create_subscriber.c
Adds conninfo construction, configuration copying, system-identifier checks, process polling, filesystem utilities, executable discovery, and database-list parsing.

Forward-origin caching in spock_apply

Layer / File(s) Summary
Forward-origin cache population and advancement
src/spock_apply.c
handle_origin() resolves and caches forwarded-origin mappings on decode, and maybe_advance_forwarded_origin() advances only from the cached local origin id.
Forward-origin cascade validation
tests/tap/t/015_forward_origin_advance.pl
Extends the three-node cascade test with forwarding-origin setup, gap recovery, and duplicate checks after direct subscription enablement.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive No pull request description was provided, so the intent can't be assessed from author text. Add a brief description summarizing the new subscriber creation flow and related test/docs changes.
✅ Passed checks (4 passed)

Check name Status Explanation
Title check ✅ Passed The title matches the main change: adding physical-to-logical replica support.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Finishing Touches

🧪 Generate unit tests (beta)

  • Create PR with unit tests
  • Commit unit tests in branch task/SPOC-601/physical-to-logical-replica
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@codacy-production

codacy-production Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 21 critical · 17 high · 27 medium

Alerts:
⚠ 21 issues (≤ 0 issues of at least critical severity)
⚠ 23 issues (≤ 0 issues of at least minor severity)

Results:
65 new issues

Category Results
ErrorProne 1 critical (1 false positive)
14 high (14 false positives)
Security 20 critical (18 false positives)
3 high (2 false positives)
Complexity 27 medium

View in Codacy

🟢 Metrics 388 complexity · 6 duplication

Metric Results
Complexity 388
Duplication 6

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (3)
tests/tap/t/015_forward_origin_advance.pl (1)

88-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer wait_for_sub_status over fixed sleep for subscription readiness.

The sleep '5' + immediate is(..., 'replicating') checks are timing-dependent and will flake on slow CI. SpockTest.pm already exposes wait_for_sub_status($node, $sub, 'replicating', $timeout); using it (and similarly for data-arrival polling elsewhere) makes the test deterministic.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/tap/t/015_forward_origin_advance.pl` around lines 88 - 96, Replace the
fixed readiness delay in the subscription replication test with polling via
wait_for_sub_status from SpockTest.pm, using the subscription identifiers
sub_n2_n1 and sub_n3_n2 in the existing replication checks. Update the test flow
so it waits for each subscription to reach replicating before asserting, instead
of relying on system_or_bail 'sleep', '5'. If there are other data-arrival waits
in this test, switch those to the same polling helper as well to keep the test
deterministic.
utils/spock_create_subscriber/spock_create_subscriber.c (2)

1100-1106: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Address the TODO: unqualified UPDATE on spock.local_sync_status.

The UPDATE spock.local_sync_status SET sync_status = 'r' has no WHERE clause, affecting all rows. For a freshly created extension this is likely safe, but the /* TODO */ suggests the developer intended further work. Should this be scoped to the current subscription only?

Do you want me to generate a scoped version that filters by sync_subid?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@utils/spock_create_subscriber/spock_create_subscriber.c` around lines 1100 -
1106, The UPDATE in spock_create_subscriber currently changes every row in
spock.local_sync_status, so scope it to the current subscription instead of
updating the whole table. Use the existing subscription identifier in this flow
(for example, the sync_subid associated with the current subscription setup in
spock_create_subscriber) and add the appropriate WHERE clause so only the
intended row is modified. Keep the existing error handling around PQexec and
PQresultStatus unchanged.

283-284: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Replace atoi with strtol for apply_delay parsing.

atoi silently returns 0 for non-numeric input, making typos indistinguishable from the default. Use strtol with errno and endptr checks to reject malformed values.

♻️ Proposed refactor
-			apply_delay = atoi(optarg);
+			{
+				char *endptr;
+				long val;
+				errno = 0;
+				val = strtol(optarg, &endptr, 10);
+				if (errno != 0 || *endptr != '\0' || optarg == endptr)
+					die(_("Invalid apply delay value: %s\n"), optarg);
+				apply_delay = (int) val;
+			}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@utils/spock_create_subscriber/spock_create_subscriber.c` around lines 283 -
284, Replace the `atoi` parsing for `apply_delay` in the `case 8` branch with
`strtol` so malformed input can be detected. In the option-handling code that
sets `apply_delay`, validate the conversion using both `errno` and the `endptr`
result, and reject values that are non-numeric or partially parsed instead of
silently accepting them as 0.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/creating_subscriber_nodes.md`:
- Line 5: The document has a heading level jump and a wording issue in the
subscriber nodes guide. In the section marked by the Synopsis heading, change
the heading level to stay consistent with the surrounding structure, and in the
text describing comma separated values, hyphenate the phrase as used elsewhere
in the docs. Use the Synopsis heading and the comma separated wording as the
identifiers to locate the edits.
- Around line 9-25: The `--text-types` CLI option is missing from both the
subscriber creation documentation and the CLI help output, so users cannot
discover it. Add a new row for `--text-types` in the options table in the
subscriber docs, and add a matching `printf` entry in `usage()` in
`spock_create_subscriber.c` alongside the existing option descriptions,
referencing the `force_text_transfer` behavior.

In `@src/spock_apply.c`:
- Around line 1185-1205: Invalidate and refresh the forwarded-origin cache
inside maybe_advance_forwarded_origin() whenever subscription state changes, not
just when remote_origin_id changes. Update the
cached_forward_remote_id/cached_forward_local_id logic so Step 16b
create/drop/recreate events can’t leave the worker stuck with InvalidRepOriginId
or a stale replorigin_by_name result, and consider resetting the cache when the
relevant subscription lookup yields no active forwarded subscription. Keep the
existing remote_origin_id checks, but add cache invalidation tied to
subscription changes so alternating forwarded peers don’t repeatedly reuse
outdated entries.

In `@utils/spock_create_subscriber/spock_create_subscriber.c`:
- Around line 1554-1570: The is_pg_dir helper is incorrectly building the
PG_VERSION path from the global data_dir instead of its path argument. Update
is_pg_dir to use the passed-in path when composing version_file so the check
works for any caller, and keep the existing stat/errno logic intact. Verify the
behavior around is_pg_dir and its callers in spock_create_subscriber.c still
returns false only when the target directory truly lacks PG_VERSION.
- Around line 1701-1718: The get_pgpid() helper leaks the pidf file handle when
fscanf() does not read a valid PID. Update the error path in get_pgpid() so that
pidf is always closed before returning, including the fscanf failure branch,
while keeping the existing success and fopen failure behavior unchanged.
- Around line 1745-1751: `generate_restore_point_name` currently assumes
`malloc(NAMEDATALEN)` succeeds before calling `snprintf`, which can crash on
allocation failure. Update this function to check the `malloc` result before
using `rpn`; if allocation fails, handle it safely by returning a null/empty
failure value or propagating the error in the same style used elsewhere in
`spock_create_subscriber.c`. Keep the existing restore-point naming logic intact
for the success path.
- Around line 1314-1346: The path formatting in WriteRecoveryConf and
CopyConfFile uses sprintf into fixed-size filename buffers, which can overflow
when data_dir is long. Replace each sprintf call with snprintf, passing
MAXPGPATH as the buffer limit, and handle truncation/failure consistently before
using the resulting path. Use the existing filename buffer and the
WriteRecoveryConf/CopyConfFile helpers to locate all affected calls.
- Around line 406-412: The subscriber setup check leaks the string returned by
read_sysid() in the dbnum/use_existing_data_dir path because it is compared with
strcmp and then discarded. Update the logic around check_data_dir() in
spock_create_subscriber.c to store the read_sysid(data_dir) result in a
temporary variable, use it for the strcmp against remote_info->sysid, and free
it after the comparison before any die() or return path.
- Around line 688-718: The run_basebackup() helper appends extra_basebackup_args
verbatim into the system() command, so it must reject anything outside the
documented safe pg_basebackup options. Update run_basebackup() to
validate/whitelist only the allowed flags (-T, -c, and --xlogdir/--waldir)
before appending, or refactor it to use an argv-based exec path instead of shell
command construction. Ensure the fix is localized around run_basebackup() and
the extra_basebackup_args handling.

---

Nitpick comments:
In `@tests/tap/t/015_forward_origin_advance.pl`:
- Around line 88-96: Replace the fixed readiness delay in the subscription
replication test with polling via wait_for_sub_status from SpockTest.pm, using
the subscription identifiers sub_n2_n1 and sub_n3_n2 in the existing replication
checks. Update the test flow so it waits for each subscription to reach
replicating before asserting, instead of relying on system_or_bail 'sleep', '5'.
If there are other data-arrival waits in this test, switch those to the same
polling helper as well to keep the test deterministic.

In `@utils/spock_create_subscriber/spock_create_subscriber.c`:
- Around line 1100-1106: The UPDATE in spock_create_subscriber currently changes
every row in spock.local_sync_status, so scope it to the current subscription
instead of updating the whole table. Use the existing subscription identifier in
this flow (for example, the sync_subid associated with the current subscription
setup in spock_create_subscriber) and add the appropriate WHERE clause so only
the intended row is modified. Keep the existing error handling around PQexec and
PQresultStatus unchanged.
- Around line 283-284: Replace the `atoi` parsing for `apply_delay` in the `case
8` branch with `strtol` so malformed input can be detected. In the
option-handling code that sets `apply_delay`, validate the conversion using both
`errno` and the `endptr` result, and reject values that are non-numeric or
partially parsed instead of silently accepting them as 0.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d2d28024-a6d4-48fb-ab59-05568339e7c2

📥 Commits

Reviewing files that changed from the base of the PR and between a11ae76 and be3d868.

📒 Files selected for processing (7)
  • .gitignore
  • Makefile
  • docs/creating_subscriber_nodes.md
  • src/spock_apply.c
  • tests/tap/t/015_forward_origin_advance.pl
  • utils/spock_create_subscriber/Makefile
  • utils/spock_create_subscriber/spock_create_subscriber.c
💤 Files with no reviewable changes (1)
  • .gitignore

Comment thread docs/creating_subscriber_nodes.md Resolved
Comment thread docs/creating_subscriber_nodes.md Resolved
Comment thread src/spock_apply.c Resolved
@rasifr rasifr changed the title Task/spoc 601/physical to logical replica [WIP] Physical to logical replica support Jul 9, 2026
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from cd962d4 to 7d7c4a9 Compare July 9, 2026 13:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@utils/spock_create_subscriber/spock_create_subscriber.c`:
- Around line 285-286: The --apply-delay parsing in the option handling path is
too permissive because strtol(optarg, NULL, 10) accepts trailing junk and may
overflow before the later int bounds check. Update the parsing around the
apply_delay assignment to validate the entire optarg string was consumed and
that the value is within range before casting to int, using the existing option
handling logic in spock_create_subscriber.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bd133fc0-e83c-463f-824c-f6a80a5955a5

📥 Commits

Reviewing files that changed from the base of the PR and between cd962d4 and 7d7c4a9.

📒 Files selected for processing (4)
  • docs/creating_subscriber_nodes.md
  • src/spock_apply.c
  • tests/tap/t/015_forward_origin_advance.pl
  • utils/spock_create_subscriber/spock_create_subscriber.c
✅ Files skipped from review due to trivial changes (1)
  • docs/creating_subscriber_nodes.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/tap/t/015_forward_origin_advance.pl
  • src/spock_apply.c

@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from f17f6ff to 2556ade Compare July 13, 2026 07:02

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
utils/spock_create_subscriber/spock_create_subscriber.c (1)

700-718: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Consider allowlisting safe pg_basebackup options instead of denylisting shell metacharacters.

The denylist mitigates command injection, but doesn't enforce the documented safe options (-T, -c, --xlogdir/--waldir). A user could pass conflicting pg_basebackup flags (e.g., --slot, -r) that interfere with the replication slot being created. An allowlist would be more robust and align with the help text at line 611.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@utils/spock_create_subscriber/spock_create_subscriber.c` around lines 700 -
718, Replace the character-based validation in validate_extra_basebackup_args
with parsing that allowlists only the documented pg_basebackup options: -T, -c,
--xlogdir, and --waldir, including their expected argument forms. Reject every
other option or malformed value so callers cannot override replication-slot or
related settings, while retaining the existing unsafe-input failure behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@utils/spock_create_subscriber/spock_create_subscriber.c`:
- Around line 285-290: Update the --apply-delay parsing block in
spock_create_subscriber to check errno for strtol range errors before converting
the result to int, and validate the parsed long against the int range before
assigning apply_delay. Preserve the existing trailing-junk and missing-value
checks, rejecting overflow and out-of-range values through the same
invalid-integer error path.

---

Nitpick comments:
In `@utils/spock_create_subscriber/spock_create_subscriber.c`:
- Around line 700-718: Replace the character-based validation in
validate_extra_basebackup_args with parsing that allowlists only the documented
pg_basebackup options: -T, -c, --xlogdir, and --waldir, including their expected
argument forms. Reject every other option or malformed value so callers cannot
override replication-slot or related settings, while retaining the existing
unsafe-input failure behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 294e2feb-2612-435f-949f-589d425ab352

📥 Commits

Reviewing files that changed from the base of the PR and between f17f6ff and 2556ade.

📒 Files selected for processing (4)
  • docs/creating_subscriber_nodes.md
  • src/spock_apply.c
  • tests/tap/t/015_forward_origin_advance.pl
  • utils/spock_create_subscriber/spock_create_subscriber.c
🚧 Files skipped from review as they are similar to previous changes (3)
  • docs/creating_subscriber_nodes.md
  • src/spock_apply.c
  • tests/tap/t/015_forward_origin_advance.pl

@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch 2 times, most recently from a0313b2 to 4946512 Compare July 13, 2026 14:03
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from 4946512 to 401476f Compare July 22, 2026 10:50
@rasifr

rasifr commented Jul 22, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review commit 051450c

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

git show --no-ext-diff --format=fuller --stat 051450c
printf '\n--- changed files ---\n'
git diff-tree --no-commit-id --name-status -r 051450c
printf '\n--- parent(s) ---\n'
git rev-list --parents -n 1 051450c
printf '\n--- diff check ---\n'
git diff --check 051450c^ 051450c

printf '\n--- outlines of changed source files ---\n'
git diff-tree --no-commit-id --name-only -r 051450c \
  | while IFS= read -r f; do
      case "$f" in
        *.c) ast-grep outline "$f" --items all --type function --view expanded || true ;;
        *.pl) ast-grep outline "$f" --items all --view expanded || true ;;
      esac
    done

Length of output: 5351


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- changed function names and nearby declarations ---'
rg -n -C 5 'track_forward_peer_origin|maybe_advance_forwarded_origin|handle_origin|forward.*origin|Forward.*Origin|XactLastCommitEnd' src/spock_apply.c

printf '%s\n' '--- targeted commit diff: apply code ---'
git diff --no-ext-diff --unified=80 051450c^ 051450c -- src/spock_apply.c

printf '%s\n' '--- targeted commit diff: TAP test ---'
git diff --no-ext-diff --unified=40 051450c^ 051450c -- tests/tap/t/015_forward_origin_advance.pl

printf '%s\n' '--- related subscription lookup API and origin-cache usage ---'
rg -n -C 6 'get_node_subscriptions\s*\(|remote_origin_id|cached_forward|forward_origin' src tests -g '*.[ch]' -g '*.pl'

Length of output: 130262


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- subscription model and lookup implementation ---'
ast-grep outline src/spock_node.c --items all --view expanded
sed -n '1270,1345p' src/spock_node.c
rg -n -C 6 'typedef struct SpockSubscription|struct SpockSubscription|bool[[:space:]]+enabled|enabled;' src -g '*.[ch]'

printf '%s\n' '--- apply worker startup and replication-origin resume lookup ---'
rg -n -C 10 'replorigin_session_get_progress|replorigin_by_name|replorigin_session_setup|MySubscription->slot_name|spock_start_replication' src/spock_apply.c src -g '*.[ch]'

printf '%s\n' '--- subscription enable and apply-worker lifecycle ---'
rg -n -C 8 'spock_sub_enable|sub_enable|subscription.*enable|enabled[[:space:]]*=[[:space:]]*true' src/spock_functions.c src/spock_worker.c src -g '*.[ch]'

printf '%s\n' '--- exact changed lines ---'
git diff --no-ext-diff --unified=5 051450c^ 051450c -- src/spock_apply.c | nl -ba | sed -n '250,390p'
git show 051450c:src/spock_apply.c | nl -ba | sed -n '1234,1355p;5035,5075p'

Length of output: 57517


@rasifr I found one blocking issue in commit 051450c:

  • P1 — Do not advance origins belonging to enabled subscriptions — resolve_forward_peer_origin() selects every subscription whose provider matches the forwarded peer, including enabled ones, and maybe_advance_forwarded_origin() advances that origin from the cascade worker. However, an enabled subscription’s worker uses this same origin progress as its START_REPLICATION position. Consequently, a forwarded transaction can move an active direct subscription past changes that its own worker has not applied. This becomes data loss when the cascade and direct paths have different replication-set coverage: for example, a transaction excluded by the n2 → n1 → n3 path can be skipped by the direct n2 → n3 worker after it restarts, because a later forwarded transaction advanced its origin past it. Restrict the lookup to disabled/pre-created subscriptions (and retain the ambiguity check among those), or otherwise ensure the origin is not owned by an active worker. The TAP test should also cover an enabled direct subscription and assert its origin is untouched by forwarded traffic.

    Relevant locations: src/spock_apply.c, Lines 1241–1250 and Lines 1323–1351.

@rasifr

rasifr commented Jul 22, 2026 •

Copy link
Copy Markdown
Member Author

@coderabbitai

When an enabled subscription's apply worker starts, it calls replorigin_session_setup(originid) once, which sets replication_state->acquired_by = MyProcPid and holds it for the worker's entire lifetime (spock_apply.c:4647, no per-transaction release). Critically, replorigin_advance() — the same function maybe_advance_forwarded_origin() calls — checks that ownership first:

if (replication_state->acquired_by != 0)
ereport(ERROR, (errcode(ERRCODE_OBJECT_IN_USE),
errmsg("replication origin with ID %d is already active for PID %d", ...)));

So if sub_n3_n2's own worker is alive and owns that origin, a forwarding-path call to advance the same origin doesn't silently succeed or race on "latest LSN wins" — it throws ERRCODE_OBJECT_IN_USE immediately.

Besides, whichever path apply's the LSN, and advances, at most it could duplicate/resend same or older transaction, there will be no data loss.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- forwarding origin resolution and advancement ---'
rg -n -C 18 'resolve_forward_peer_origin|maybe_advance_forwarded_origin|replorigin_advance\s*\(|get_node_subscriptions\s*\(' src/spock_apply.c

printf '%s\n' '--- replication origin session setup, progress lookup, and error handling ---'
rg -n -C 14 'replorigin_session_setup\s*\(|replorigin_session_get_progress\s*\(|replorigin_session_reset\s*\(|PG_TRY|PG_CATCH|ERROR' src/spock_apply.c

printf '%s\n' '--- subscription lookup implementation and enabled predicate ---'
rg -n -C 18 'get_node_subscriptions\s*\(' src -g '*.[ch]'

printf '%s\n' '--- replication start LSN derived from origin progress ---'
rg -n -C 14 'replorigin_session_get_progress\s*\(|startpos|start_lsn|START_REPLICATION' src -g '*.[ch]'

printf '%s\n' '--- PostgreSQL replication-origin ownership checks in available source ---'
rg -n -C 10 'replication origin with ID %d is already active|acquired_by|replorigin_advance\s*\(' . \
  -g 'replorigin*.c' -g 'origin*.c' -g '*.h' || true

Length of output: 143119


@rasifr You are correct about the active-worker case. replorigin_session_setup() owns the origin, so the forwarded replorigin_advance() does not silently race or overwrite that worker’s progress. I withdraw that part of my prior explanation.

However, the unfiltered lookup still needs protection for two separate reasons:

  1. Active direct subscription: cascade worker failure.
    resolve_forward_peer_origin() selects enabled subscriptions too, and maybe_advance_forwarded_origin() does not catch ERRCODE_OBJECT_IN_USE. Once the direct worker owns the origin, subsequent forwarded traffic causes the cascade apply worker to error/exit rather than being a harmless duplicate. The test should insert another forwarded transaction after enabling sub_n3_n1 and assert that sub_n3_n2 remains replicating.

  2. Enabled but inactive direct subscription: replication-set coverage can still skip data.
    Before its worker has acquired the origin (including the pre-start window), forwarded traffic can advance it. The worker then reads that value at src/spock_apply.c Lines 4610 and uses it as its START_REPLICATION position at Lines 4627–4629. If the cascade subscription carries only replication set B, but the direct subscription includes A and B, then a direct-only A transaction followed by a forwarded B transaction advances the direct origin beyond A. Starting the direct subscription from the forwarded B position skips A.

Restricting the forwarding-origin resolution to disabled/pre-created subscriptions matches the intended handoff model and avoids both cases. The current test’s direct subscription is initially disabled, so filtering by !sub->enabled should preserve its intended setup.


✏️ Learnings added
Learnt from: rasifr
URL: https://github.com/pgEdge/spock/pull/521

Timestamp: 2026-07-22T12:19:00.978Z
Learning: In `src/spock_apply.c`, an apply worker calls `replorigin_session_setup(originid)` before reading its replication-origin progress and starting logical replication. PostgreSQL replication origins are exclusively owned while that worker is active; another `replorigin_advance()` on the same origin raises `ERRCODE_OBJECT_IN_USE` rather than silently updating the position.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch 3 times, most recently from 12070c3 to f6ada31 Compare August 5, 2026 15:32
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from f6ada31 to 9f2a788 Compare August 12, 2026 13:15
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch 2 times, most recently from 1a2e274 to 51c047d Compare September 2, 2026 16:43
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from 55f9992 to 399e363 Compare September 15, 2026 17:15
rasifr added a commit that referenced this pull request Sep 21, 2026
…scard abort, disabled-sub stats

Covers the remaining SPOC-607 hardening gaps against
spock_create_subscriber --bidirectional:

- --cleanup idempotency: a second --cleanup --force on an already-clean
  target is a safe no-op (048_bidir_join.pl).

- Phase-3 failure matrix: a new test-only hook,
  SPOCK_CREATE_SUBSCRIBER_TEST_FAIL_AFTER=<step>, aborts the join right
  after each of the 6 post-catchup cutover steps (coverage barrier, clear
  forwarding, enable peer subs, reverse subs, reverse-subs-ready, verify)
  so --cleanup recovery can be exercised deterministically at each one,
  instead of relying on racy external SIGKILL timing
  (058_bidir_join_failure_matrix.pl). Follows the same accept-either-
  outcome-then-verify-physical-state contract 057_bidir_join_stall_abort.pl
  already established for a --cleanup call that can't reach n3 to confirm
  local state after die() has already stopped its postgres.

- Discard injection: a new named injection point,
  SPOCK_FORWARDED_APPLY_ERROR() (same three-way SPOCK_RANDOM_DELAYS /
  USE_INJECTION_POINTS / no-op pattern as the existing
  SPOCK_WORKER_DELAY()/SPOCK_OUTPUT_TXN_STALL()), fires from
  spock_apply_heap_insert/update/delete() only when applying a
  forwarded-origin change. Lets a test force an error-class exception on a
  forwarded transaction during catchup and verify the join aborts --
  sub_n3_n1 ends up disabled, origin frozen, read-only never lifted, the
  poisoned row never durably applied -- rather than silently completing
  (060_bidir_join_forwarded_discard_abort.pl; skips cleanly without
  --enable-injection-points).

- PG18 stats hooks guard, read side: spock.get_subscription_stats() against
  a disabled subscription whose apply worker has never run returns a
  well-defined all-zero row rather than crashing (confirmed already
  crash-safe; added the regression scenario that was missing).

PG17 failover slot option for peer slots (the other open SPOC-607 item)
remains an unresolved design decision, not a coverage gap, and is left
for a separate decision.

Also widens 052_bidir_join_big_txn_liveness.pl's stall_timeout from 5s to
15s: PR CI (#521) showed it intermittently failing on the PG15
job only, since the gap between n1's commit and n3's handle_begin()
(connection/decode startup, not the slow-apply loop under test) can exceed
a razor-thin 5s under contended CI runners. 15s keeps a comfortable ~2x
margin below the ~24s minimum apply time while giving that startup gap
real headroom; the liveness detection it exercises is unchanged.

Verified: full regress + TAP suites pass on both PG15 and PG18.
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from ca964d1 to 61f038b Compare September 21, 2026 13:39
rasifr added a commit that referenced this pull request Oct 7, 2026
…scard abort, disabled-sub stats

Covers the remaining SPOC-607 hardening gaps against
spock_create_subscriber --bidirectional:

- --cleanup idempotency: a second --cleanup --force on an already-clean
  target is a safe no-op (070_bidir_plumbing.pl).

- Phase-3 failure matrix: a new test-only hook,
  SPOCK_CREATE_SUBSCRIBER_TEST_FAIL_AFTER=<step>, aborts the join right
  after each of the 6 post-catchup cutover steps (coverage barrier, clear
  forwarding, enable peer subs, reverse subs, reverse-subs-ready, verify)
  so --cleanup recovery can be exercised deterministically at each one,
  instead of relying on racy external SIGKILL timing
  (080_bidir_join_failure_matrix.pl). Follows the same accept-either-
  outcome-then-verify-physical-state contract 079_bidir_join_stall_abort.pl
  already established for a --cleanup call that can't reach n3 to confirm
  local state after die() has already stopped its postgres.

- Discard injection: a new named injection point,
  SPOCK_FORWARDED_APPLY_ERROR() (same three-way SPOCK_RANDOM_DELAYS /
  USE_INJECTION_POINTS / no-op pattern as the existing
  SPOCK_WORKER_DELAY()/SPOCK_OUTPUT_TXN_STALL()), fires from
  spock_apply_heap_insert/update/delete() only when applying a
  forwarded-origin change. Lets a test force an error-class exception on a
  forwarded transaction during catchup and verify the join aborts --
  sub_n3_n1 ends up disabled, origin frozen, read-only never lifted, the
  poisoned row never durably applied -- rather than silently completing
  (081_bidir_join_forwarded_discard_abort.pl; skips cleanly without
  --enable-injection-points).

- PG18 stats hooks guard, read side: spock.get_subscription_stats() against
  a disabled subscription whose apply worker has never run returns a
  well-defined all-zero row rather than crashing (confirmed already
  crash-safe; added the regression scenario that was missing).

PG17 failover slot option for peer slots (the other open SPOC-607 item)
remains an unresolved design decision, not a coverage gap, and is left
for a separate decision.

Also widens 074_bidir_join_big_txn_liveness.pl's stall_timeout from 5s to
15s: PR CI (#521) showed it intermittently failing on the PG15
job only, since the gap between n1's commit and n3's handle_begin()
(connection/decode startup, not the slow-apply loop under test) can exceed
a razor-thin 5s under contended CI runners. 15s keeps a comfortable ~2x
margin below the ~24s minimum apply time while giving that startup gap
real headroom; the liveness detection it exercises is unchanged.

Verified: full regress + TAP suites pass on both PG15 and PG18.
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from 89a105d to cf1e93a Compare October 7, 2026 15:56
Comment thread docs/creating_subscriber_nodes.md Resolved
After the configuration overrides are applied, read wal_level,
shared_preload_libraries and, with --bidirectional,
track_commit_timestamp from the new node's data directory and fail unless
they are "logical", include "spock" and "on".  A node that cannot host
spock otherwise fails only after the catchup, and one without commit
timestamps joins with last_update_wins unable to work.
…-bidirectional

The bidirectional subscriptions are created without either setting, so
the options were accepted and silently ignored.
…rectory

The error for a reused data directory already past the source's timeline
told every caller to run --cleanup --force, which requires
--bidirectional.  Without it, say to remove the data directory.
Document --bidirectional, --stall-timeout, --max-wait, --cleanup and
--force, the join preconditions, the manifest, and --postgresql-auto-conf.
Also state the configuration the new node must have.
Joins a node with spock_create_subscriber --bidirectional while
pgedge-loadgen writes to the source, and compares the data on all nodes
afterwards.  Skipped when pgedge-loadgen is not found.  Not scheduled;
run it individually.
… the same replication sets

The joining node uses the union of the sets selected by the source's
subscriptions for all of its own subscriptions.  When the source's
subscriptions differ, the direct path from a peer can select different
changes than the path forwarded through the source.  Reject such a
source.
A single large transaction is sent only at commit, so the origin LSN
stays frozen while the provider decodes it and the apply worker is idle.
Raise the default and name this case in the stall error and the docs.
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from 70f4fe1 to 7dea0f9 Compare November 24, 2026 08:36
The base backup can be very large and cannot be reused once the copy is
promoted, yet several checks that need no changes to anything ran only
after it, or never ran at all.  A rejection then cost a full re-copy and
a manual --cleanup.

Move every read-only check of --bidirectional into a bidir_preflight()
phase that runs before the startup log, the source slot, the sidecar and
the base backup.  Add the checks that were missing:

  - the subscriber name must not collide with a node of the mesh
  - the source and each peer need wal_level = logical and free WAL
    senders; a peer also needs a free replication slot
  - the slot the join will create on a peer must not already exist
  - no reverse subscription from an earlier attempt may be left on the
    source or a peer
  - spock extension dependents are checked on the source, whose catalogs
    match the copy, instead of after promotion
  - the target filesystem must have room for the backup
  - no server may be listening at --subscriber-dsn; this uses PQping(),
    so a server that would refuse the login still counts

The disk-space figure assumes an uncompressed copy, so it can reject a
backup that would fit when the backup or the filesystem compresses.  Add
--skip-disk-space-check to turn it off, and document it.

The new node's own configuration limits and its reachability of the
peers still cannot be checked before it exists.

Extend 076 with a case for each new check, asserting that a rejection
leaves no slot, no sidecar and an untouched data directory, and make the
dependent-view case assert the same instead of relying on --cleanup.
The disk-space case builds a small RAM disk with hdiutil and is skipped
elsewhere.
The inline go-live sequence of a --bidirectional join mixed steps that
only make the new node catch up with steps that change the existing
cluster.  Separate them so the second kind cannot start before the first
has fully succeeded, and so a later change can run each pass over several
databases.

Move the catchup subscription, the peer subscriptions, the coverage
barrier and the forwarding clear into bidir_catchup_phase().  Move the
reverse subscriptions and the dataflow verification, the first steps that
make an existing node replicate to the new one, into
bidir_publish_phase().  Lifting read-only mode and marking the join
complete become bidir_finish_join().

The statements run in the same order as before, including each failure
injection point, so behavior is unchanged and the existing 070 to 081
tests cover it.
The precondition that nothing is still in flight to an existing peer
compared each outbound slot's confirmed_flush_lsn with the current WAL
position, at one instant.  While the source is written to, every slot is
a little behind the end of WAL, so the check rejected such a source
almost every time: with ten small inserts a second it reported lag in
2494 of 2500 samples, against 0 of 4000 on an idle source.  Even an idle
source could fail it, when one background record landed between the
caller's own drain wait and the check.  Callers had to pause every writer
of the cluster first, which hid the problem from any test of a join under
load.

Read the WAL position once and wait until every outbound spock slot has
confirmed it.  Later WAL cannot matter, so a loaded source passes as soon
as its peers catch up with the target.  A slot that stops advancing, such
as a disabled peer subscription or a slot left by an earlier attempt, is
still rejected after 30 seconds without progress, and the message names
the stalled slots.  This runs before the base backup, so waiting costs
nothing.

Add a 076 case that joins against a source under steady writes and must
get past the check, which the old check fails, and make the stalled-slot
case assert the new message.  Describe the precondition in the docs.
Comment thread utils/spock_create_subscriber/Makefile Resolved
@ibrarahmad
ibrarahmad self-requested a review November 27, 2026 07:19

@ibrarahmad ibrarahmad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added more review comments.

Several conditions that fail only after the base backup was promoted, where
the copy cannot be reused, are now rejected before any slot or backup:

- Room for the base backup: the total size of the source's databases plus
  10% is compared with the free space in the --pgdata filesystem, measured
  on the nearest existing parent when the directory does not exist yet.  It
  is an early warning; --skip-disk-space-check bypasses it, and a check that
  cannot be made is reported instead of skipped silently.
- The source needs a free slot for the temporary physical slot of
  pg_basebackup -X s as well as for the logical slot (none for the backup
  with --no-slot or a named slot).
- A slot left on the source by an earlier attempt blocked
  --drop-slot-if-exists through the drain wait, because it never advances.
  It is now excluded from the wait, and rejected up front without the option.
- The new node gets its configuration from the source plus the override files,
  so max_replication_slots and max_wal_senders must cover the source and every
  peer, and the port of --subscriber-dsn must be the port it will listen on.
- A spock.node row for the new node's name on the source or a peer makes
  sub_create fail after promotion; it is rejected up front.
- The programs used after the backup (pg_resetwal in particular) are located
  and version-checked in the preflight.

A subscriber name taken by a mesh node is reported before slot checks. The
drain wait is announced at normal verbosity, and escaped literals are freed.
Tests 076 and 070 cover each new rejection; 070's deliberately failing
backups now set the new node's port as a real join must.
Utility:
- Fall back to the built-in default for a setting the source took from
  its own config file when --postgresql-conf does not set it.
- Treat only a missing manifest as "nothing to clean up"; any other
  stat() error is fatal.
- Do not print statements carrying a connection string at -v -v, and
  redact the peer connection string in traces.
- Quote paths and connection strings passed to the shell, including the
  version probe in spock_fe.c (POSIX only).
- Use TCP keepalives on the utility's connections so a vanished peer
  ends the run within about a minute; document how --max-wait applies.
- Abort the peer coverage barrier if the replication sets selected by
  the source's subscriptions changed since they were captured.
- Start the physical catchup --max-wait and stall clocks after the
  first successful connection.
- On the non-bidirectional path, verify that --subscriber-dsn reaches
  the postmaster running from the local data directory before any
  catalog change, by comparing the postmaster start time (floor(), with
  one second of slack, as the pid file holds truncated seconds).
- Remove the join manifest a base backup copies from a source that was
  itself joined with this tool, and make --cleanup refuse a manifest
  that belongs to another node when --subscriber-name names one.
- Store the source connection string with the database name in the
  manifest, so cleanup connects to the right database when
  --provider-dsn has no dbname.
- Canonicalize --pgdata, so a trailing slash cannot put the pending
  sidecar inside the data directory.
- Report the JSON error detail before freeing the lexer (PG17+).
- --cleanup --force also empties tablespace and --waldir directories
  that the backup placed outside the data directory.
- Refuse enabled native logical subscriptions on the ordinary path too.
- Roll back transactions that were prepared at the restore point on the
  new node; they reach it by replication once committed on the source.
- Make sure the recovery configuration ends with a newline before the
  recovery target lines are appended.
- Do not pass a NULL dbname to pstrdup() when the DSN has none.
- Bound the wait for a started postmaster to appear, so a postmaster
  that died during replay no longer hangs the tool.
- Reject empty entries in --databases.
- Add a restore_point pause hook for tests.

Build: ignore and clean the spock_fe.c link in the utility directory.

Tests:
- Require the specific diagnostic in the 076 and 080 failure cases.
- Fail 071 if the load generator exited before the join finished.
- Bound waits after SIGTERM (TERM, then KILL on the process group) and
  add a deadline to the 075 sampling loop.
- Clean up the join and writer before BAIL_OUT in 072.
- Hold a table lock on n1 in 073 so the barrier has a known pending
  transaction; replace its vacuous barrier timing check.
- Wait for the restore point before the slow insert in 074.
- SpockTest.pm tracks background children and extra data directories
  and stops them in END, so a BAIL_OUT no longer leaves a child or a
  node holding its port; 070-075, 077-079, 081 and 083 register theirs.
- 070: match the specific message in the exit-only negative cases; cover
  the trailing slash, a separate WAL directory emptied by cleanup, a
  manifest owned by another node, empty --databases and a DSN without a
  dbname.
- 075: assert the peer slot exists after cutover instead of count >= 0.
- 082: give the failing-backup case a port override.
- 083: cover native subscriptions on the ordinary path, and a
  transaction prepared before the restore point and committed after it,
  with a --recovery-conf that lacks a final newline.

Docs: describe the native subscription and prepared transaction
handling and the wider --cleanup --force.
Serialization, parsing and the durable write of the bidirectional join's
manifest are about 600 lines that depend only on the join state structs.
They now live in manifest.c, with the structs they share with the rest of
the utility in spock_create_subscriber.h.  die() and get_connstr() lose
their static so the new file can use them.

A move only: no line of code changed, apart from the includes and the
declarations the split needs.
Output (print_msg, debug_exec), connection-string handling, input
validation (validate_extra_basebackup_args, validate_replication_set_input,
get_database_list), connectdb(), generate_restore_point_name(), the test
hook maybe_test_fail_after(), and file and path helpers do not depend on
the state of a join.  They now live in common.c, declared in
spock_create_subscriber.h, which leaves the main file with the join logic.
The verbosity level moves with print_msg.  discard_inherited_manifest()
goes to manifest.c, next to the code that names the manifest file.

Helpers that only common.c calls (is_symlink, absolute_link_target,
remove_tablespace_data and the connection-string quoting routines) stay
static there.  CopyConfFile() and WriteRecoveryConf() stay in the main file
because they use data_dir and progname.

A move only: no line of code changed, apart from the includes, the
declarations and the removal of static.
The checks of the source and its peers (replication-set fingerprints, mesh
health, node readiness, the single-database and native-subscription checks,
the Spock version check and the outbound drain wait) need nothing from the
join context beyond what they are passed.  They now live in preflight.c.

replication_slot_exists() and die_if_time_to_stop() lose their static, and
RepsetFingerprintEntry and OUTBOUND_DRAIN_STALL_SECS move with the code that
uses them.  The comment that described compute_repset_fingerprints() had
ended up above the struct; it now sits on the function.

Otherwise a move only: no line of code changed, apart from the includes and
the declarations.
…ility.

Fixes:
- read_manifest() freed the manifest text before json_errdetail() used it;
  check_single_spock_database() and compute_repset_fingerprints() passed
  strings that live in cleared results to die().
- --cleanup --force removed the data directory, and with it the links to
  the tablespace and WAL directories, even when emptying those had failed.
  It now stops and keeps the manifest.  remove_tablespace_data() reports
  a directory it cannot list instead of treating it as gone.
- A setting that the source took from its command line or environment is
  no longer assumed to carry over to the new node.
- check_connected_to_local_postmaster() also compares data_directory.
- --cleanup checks the pending record's node name like the manifest's, and
  refuses a manifest and a pending record that name different nodes (the
  manifest was copied from the source by an interrupted backup).  A peer
  record that lists resources but no address makes the cleanup incomplete.
- The native-subscription check is repeated right before the restore
  point, and the prepared-transaction rollback of the ordinary path comes
  after the dependency check.
- The debug line for pg_basebackup shows a redacted connection string.
- WriteRecoveryConf() checks fclose().  Replication set names with a comma
  are rejected, as the list is passed on comma-separated.
- The utility Makefile builds "all" by default, and find_other_exec_version()
  no longer truncates a long program path.

Tests: the wait helpers report a child killed by a signal as a failure;
072 does not signal its own process group when no writer was started; 080
and 083 register their children for cleanup; 081 also waits for n2's
outbound slots; 070 covers the manifest and pending record mismatch; 082
checks that an sslpassword is not echoed.

Docs: --max-wait keepalive wording, that postgresql.conf include
directives are not followed, that the join account must reach every
database of the source, and the comma restriction.

Fourth round: read_manifest() sized the peer array from a per-call
capacity that starts at zero, while num_peers lives in the caller's
state.  The --cleanup mismatch check read the manifest and the pending
record into one scratch state, so the second read shrank the array to
four entries and wrote past its end for a mesh of four or more peers.
The capacity now follows the index being written, and each record has
its own scratch state; 070 pads both records with extra peers.

Tests: 071 requires the pg_basebackup error in the log instead of
accepting a hang; 073 waits for n2's Hop 1 before checking that n3 holds
the join up; 077 holds the join before the coverage barrier, shows n2's
write reaching n3 through n1 while sub_n3_n2 is off, and keeps both
conflicting transactions open until both have made their change; 078,
079 and 083 bound the wait after cancelling a child and 083 puts its
children in their own process groups; 082 stops n3 on exit, keeps the
join's exit status when the first poll reaps it, and stops if the first
join cannot be cleaned up.  spock.resolutions stays out of 077: it is
empty on both nodes for this UPDATE/UPDATE case.
Comments written after the last indent run were not re-wrapped, the
PendingSlot typedef was unknown to pgindent, and get_database_list(),
no longer static, takes the declaration form pgindent uses for a
non-static function returning char **.  Formatting only.
@rasifr
rasifr force-pushed the task/SPOC-601/physical-to-logical-replica branch from d65d66b to 2ad093e Compare November 30, 2026 15:36
@ibrarahmad
ibrarahmad self-requested a review December 1, 2026 08:57

@ibrarahmad ibrarahmad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another pass over the current head. These are new points, not repeats of the earlier comments. All from reading the code, nothing was run.

Comment thread docs/creating_subscriber_nodes.md Resolved

@ibrarahmad ibrarahmad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second part, on the catchup, barrier and cutover code. The cutover order itself (slot before restore point, the two-hop barrier, the forwarded-origin handoff) holds when I trace it against the apply code. These five are what I found around it.

Run safety
- Refuse a data directory that a postmaster is running from, before
  anything is written to it.  A live standby of the source passed the
  version, system identifier and timeline checks, was rewritten, and then
  stopped by die(); die() now leaves a postmaster this run did not start
  alone.
- Stop the join when the provider's slot was invalidated while the base
  backup ran (wal_status "lost", e.g. max_slot_wal_keep_size), on both the
  bidirectional and the plain path, with the reason and what to do, instead
  of waiting out --stall-timeout or ending with "All done" and an apply
  worker that fails for ever.
- Handle SIGHUP like SIGTERM (unless nohup ignored it) and ignore SIGPIPE, so
  a dropped ssh session no longer kills the tool without going through
  die(); SIGHUP is blocked around the pg_control rewrite.  pg_basebackup
  runs in its own process group and a stop request ends it promptly, drops
  the provider slot and leaves no pg_basebackup behind.
- Let the catchup start wait on the join's own limits (pg_ctl start -W),
  not on pg_ctl's 60 seconds; a recovery after a long backup is no longer
  thrown away.
- Register spock's resource manager while the clone replays the provider's
  WAL (the first start loads spock in binary-upgrade mode, -b): redo of
  a spock resource.dat record with the manager unregistered stopped the
  postmaster and every retry on that backup stopped at the same record.
- Make the slot creation interruptible.  pg_create_logical_replication_slot()
  waits for every write transaction that was running when it started; the
  statement is now a plain blocking PQexec() that sigexit_handler() cancels
  with PQcancel() on a registered PGcancel, as psql and pgbench do
  (fe_utils/cancel.c).  --max-wait becomes a statement_timeout and
  client_connection_check_interval makes the backend give up when the
  utility is killed, both sent as SET LOCALs in the same PQexec() as the
  command; a platform that cannot do the connection check gets the command
  without it.  --max-wait reaches create_logical_slot(),
  initialize_replication_slot() and create_peer_slot() as a parameter.
- Fingerprint the replication sets under an empty search_path (one
  transaction with SET LOCAL), so the regclass/regtype/pg_get_expr names the
  pre-flight compares are schema qualified: nodes whose role or database
  search_path differ no longer print the same table differently (a refusal),
  and a.t and public.t no longer compare equal (a missed mismatch).

Earlier findings
- drop_logical_slot_if_exists() quotes the slot name, which comes from the
  editable manifest; wait_postmaster_shutdown() waits as long as
  --stall-timeout (at least 60 seconds) and die() no longer stops a postmaster
  that is already stopping; "postgres -C" keeps its standard error;
  '$libdir/spock' and a full path are accepted in shared_preload_libraries.
- The pre-flight checks verify that the join's role is a superuser on the
  new node, the source and every peer, naming the role and the node.
- The final manifest is written, fatally, before the read-only mode is
  lifted, so a failed write cannot leave a live, writable member under a
  manifest that lets --cleanup remove it.
- --cleanup refuses a manifest that records a completed join.

Documentation
- The page on spock_create_subscriber is in the navigation, linked from the
  page on modifying a cluster, with a privileges section and examples for the
  plain conversion, the join and the cleanup.
- A section says what the join does not guard against: the node list is read
  once (run joins one at a time, leave the membership alone), a peer slot that
  dies during the join shows at the final verification (keep
  max_slot_wal_keep_size large enough), and a join interrupted around the
  forwarding clear is retried from scratch after --cleanup; clear_forwarding()
  carries a comment for the last.

Tests
- 083: a live standby is refused (plain path); an invalidated slot stops the
  plain run; SIGTERM and SIGHUP during the base backup; the enable-order check
  now compares the origin and the slot's confirmed_flush_lsn with the restore
  point and a row written during the pause must arrive exactly once.
- 076: a live standby is refused with --bidirectional, a non-superuser peer is
  refused, and the search_path scenarios (a one-node setting no longer refuses
  the join; a same-named table in another schema is no longer taken for the
  same).
- 085: a spock shutdown record written between the base backup and the
  restore point is replayed; it fails on the previous binary.
- 086: with a write transaction held open on the source, SIGTERM, --max-wait
  and SIGKILL of the utility each end with no slot left and, for the kill,
  the waiting backend gone.
- 078: the convergence checks can fail (spock.save_resolutions on n3, writers
  that run until the join ends).
- 079, 080, 081: the first --cleanup after an aborted join must exit 0.
- 070-083 use SpockTest::teardown_joined_node() for completed joins; 071's
  header no longer talks about --force.
- The test image installs src/test/modules/injection_points when
  ENABLE_INJECTION_POINTS is set, so 081 can run in it.
Under spock.exception_behaviour = discard or transdiscard, a transaction
that fails to apply on the new node is dropped and its origin moves on.
The join's waits only look for a disabled subscription, so they saw the
target LSN reached and reported a verified member with rows missing.

Until clear_forwarding() 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: it must be a hard join failure whatever the
cluster's setting.  From the direct peer subscriptions on, the node
applies peers' transactions and cross-origin races are the cluster's
normal behaviour, so it must then run under the cluster's own policy.

The join now sets spock.exception_behaviour = 'sub_disable' on the new
node (ALTER SYSTEM, reload, wait until the session sees it) before the
catchup subscription is created, and puts the configured value back
right after clear_forwarding(), before the peer subscriptions are
enabled: ALTER SYSTEM SET if the value came from postgresql.auto.conf,
RESET otherwise.  Nothing is changed when the node already runs
sub_disable.

The configured value is kept in the manifest (two optional keys, no
version bump) and is written before it is changed, so a join that dies
in between is recoverable: --cleanup restores the recorded value on the
node it keeps, best effort, and a value already recorded is never
replaced by one read back from a node still carrying the override.  The
value is checked against the three valid ones before it reaches SQL.

Tests: 084 covers transdiscard and discard.  A row that violates a
constraint present on the new node only makes the join fail (the old tool
completed it), a join with rows already in the source's and the peer's
exception logs succeeds and leaves the configured value, no override in
postgresql.auto.conf and none in the manifest, a join killed after the
coverage barrier is repaired by --cleanup (twice in a row), a value from
postgresql.auto.conf is restored exactly, and a node configured with
sub_disable is left alone.  A test pause point, catchup_enable, is added
before the catchup subscription is enabled.
One rule for records this run did not write.  A join record in --pgdata that
the run did not create (the manifest a backup copies from a source that was
itself joined, the one in a base backup the user took, a pending record an
earlier attempt left next to the directory) is trusted by --cleanup, and a new
run would silently overwrite a pending record whose remote objects only
--cleanup knows how to remove.  A join (the --pgdata reuse path and the
base-backup path alike) now stops before it creates anything when the manifest
or the pending record already exists, names the file, and says which way out
there is: run --cleanup first if it belongs to an interrupted join into this
directory, delete it if it was copied from another node's data directory.
The base-backup path still deletes a manifest inherited from the source's own
backup.  This replaces the removal of another node's manifest on the reuse
path.  --cleanup still refuses a manifest or pending record that names
another node when --subscriber-name names this one, and a manifest and a
pending record that name different nodes, because each guards a case the new
rule does not reach.

--cleanup no longer deletes anything on disk.  It had two jobs: undoing a
failed join's work on the nodes and, with --force, deleting the data
directory together with the tablespace and --waldir directories the base
backup had placed outside it.  The second job is the destructive one: a wrong
--pgdata plus --force removed a directory the tool had no business deleting,
it needed its own emptying code, and a failure half-way kept the directory and
the manifest for a retry.  Deleting a directory is what rm -rf is for.
--cleanup now removes only the remote state (drops, slots, reverse
subscriptions), puts back the recorded spock.exception_behaviour, stops the
postmaster, and removes the manifest and the pending record when every
recorded resource was confirmed gone.  It keeps the manifest when the cleanup
was incomplete, and still refuses a completed join.  With no manifest and no
pending record there is nothing to do, whatever the directory holds.

Migration: --force is now an unrecognized option, so a script that runs
--cleanup --force fails; run --cleanup and then remove the data directory
(and any --waldir and tablespace directories) before joining again in the same
place.  The hint for a data directory past the source's timeline says so.

Removed: the --force option and BidirectionalState.force_cleanup,
remove_data_dir_if_forced(), remove_external_dirs() with its tablespace and
WAL-link helpers, discard_manifest_of_other_node(), and the empty-directory
special case.  Docs, usage text and examples describe the single behaviour.

Tests: every --cleanup --force becomes --cleanup, and where a test needs the
directory gone it removes it itself.  070 asserts that --force is rejected as
an unrecognized option and touches nothing, that a completed join is refused
(manifest, directory and subscriptions untouched), that --cleanup keeps the
directory and stops the postmaster, that a second --cleanup is fine, and that
a directory with no records is left alone with exit 0; 082 plants another
node's manifest and then a pending record in the reused base backup and
checks that the join is refused, names the file, starts nothing and goes ahead
once the file is gone, and covers the rejected option and the hint; 072, 076,
079-081 and 084 remove the directory after --cleanup.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants