Skip to content

decode: carry a slot drop on when only the connection close fails - #626

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd93-slot-drop-failed-close
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd93-slot-drop-failed-close

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

When the server drops a replication slot but closing the replication connection afterwards fails, pg-sprite reap now confirms the slot is gone, drops its publication, and reports the slot as dropped.

Why

pg-sprite reap cleans up replication slots that stopped runs left behind, each with a publication of the same name. It drops a slot over a replication connection, and if only the final close of that connection failed, it reported the slot as failed ("may be gone") and stopped before the publication, although the server had already dropped the slot. The operator was left a publication to clean by hand and a report that did not say what really happened.

What

  • pkg/decode: the drop returns the drop error and the close error separately. After an accepted drop, it reads pg_replication_slots by name on the pool (once more if that read fails); if no slot of that name remains, it drops the publication exactly as a clean drop does and returns the new ErrSlotDroppedConnectionNotClosed, wrapping the close error. A slot still in the catalog stays an ErrInvariantViolation and its publication is kept. A refused drop is unchanged. Applies to DropSlot, DropIdleSlot and both *OfGoneTable forms.
  • pkg/checkpoint: ReapOrphanSlots counts that sentinel as a drop; the slot goes in Dropped, a new Reaped.Unclosed records the close error, and the pass carries on. The CLI logs one warning per such slot; the JSON report and exit code are unchanged.
  • Other callers (the run after its swap, restart, discard) still treat the sentinel as an error, as before; only now the publication has been dropped too.
  • internal/testutil.SlotDropFault: a fault hook on the existing dbconn.Config.BeforeConnect that makes the close fail after the server has answered the drop. No production hook.
  • Docs: cli.md reap section, copy-and-swap design (reaper), invariants (ST-3), SAFETY.md.

Before / after

The same orphan slot reaped when the replication connection's close fails after the server has dropped it.

pg-sprite reap      orphan slot pgsprite_app_orders, publication pgsprite_app_orders

Before
  DROP_REPLICATION_SLOT pgsprite_app_orders   → server drops it
  close replication connection                → fails
  reap report                                 → failed: pgsprite_app_orders ("may be gone"), exit 1
  publication pgsprite_app_orders             → left for the operator

After
  DROP_REPLICATION_SLOT pgsprite_app_orders   → server drops it
  close replication connection                → fails
  pg_replication_slots, by name, on the pool  → no such slot
  DROP PUBLICATION pgsprite_app_orders        → dropped
  reap report                                 → dropped: pgsprite_app_orders, exit 0
                                                 (warning on stderr names the close error)

If the catalog still shows a slot of that name, the slot stays under failed and its publication is kept, as before.

The server had dropped the slot, but a failed close of the replication
connection made the reaper report it as failed and keep its publication.
The catalog now confirms the slot is gone and the publication follows.
@Kiran01bm
Kiran01bm marked this pull request as ready for review November 30, 2026 01:41
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-30T01:41:21.234096Z
We couldn’t complete this review. Comment @codex review to try again.
0358750 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@aparajon

Copy link
Copy Markdown
Collaborator

🤖 Review 1/2 (correctness) of 0358750: 0 blocking, 2 non-blocking.

Inspected the whole change at 03587507cb611f91867e8010f4d244d6ba47e8f5 against its merge base 3fc2fc1: the new drop plumbing in slot_drop.go#L158-L268, the ReplaceSlot caller (slot.go#L196-L209), the reaper branch (reap.go#L232-L270), the CLI warning (reap.go#L125-L132), the fault helper, the five new tests, the docs, and every other caller of DropSlot, DropIdleSlot and their gone-table forms. I read the pinned pglogrepl.DropReplicationSlot (conn.Exec(ctx, sql).ReadAll()) to settle what "the server accepted the drop" means on the client.

The drop is judged correctly, and the distinction the PR needs is drawn at the right place. "Only the close failed" is exactly dropErr == nil, read at slot_drop.go#L254 (or the server's own undefined_object at L256, where the slot was already gone). ReadAll returns an error for a connection that breaks mid-statement, a reply that never arrives, a cancelled or expired context (with WithServerSideCancel the wait is cancelled on the server, and endedByContext wraps the context's own error), and a server refusal, so every one of those lands in ErrSlotActive (L261) or the default arm (L265), which return nil for closeErr and carry the close's error only joined beside the failure, never behind the sentinel. The one outcome that stays "failed" although the server may have run the drop is a lost reply; the docs now say so in those words (failed row in docs/cli.md), and failing is the safe side for a slot that holds WAL. On top of that the sentinel does not rest on the classification alone: dropSlot reads the catalog on the pool after the drop (slot_drop.go#L199-L205) and confirmSlotGone (L214-L230) returns ErrInvariantViolation for any slot of the name still there, one made since included. ErrSlotDroppedConnectionNotClosed is built only at the last statement of dropSlotAndPublication (L166-L168), after the catalog showed no slot and the publication drop succeeded, so no failing path can reach it. A confirming read that fails is retried once on the pool and fails the drop only when both fail, which keeps the error surfaced and never converts uncertainty into "dropped".

What a resume does with the carried state. The reaper keeps no state across passes: a slot in Dropped is gone, and a failed pass leaves the slot to the next one. Runner.Run, which still treats the sentinel as a failure (finding 2), is safe on resume too: its row stays in the swapped phase, the rerun's DropSlot finds no slot (slot_drop.go#L189-L191) and goes on to the publication, which is already absent, and returns nil.

Invariants (docs/invariants.md): this upholds and extends ST-3. "Reports a drop only once the catalog no longer shows the slot" still holds, now also for a drop whose close failed, and the entry's text was updated in the same PR (invariants.md#L1336, #L1378-L1383); the five test names it cites exist. No *Enforced:* line moves. It does not touch CO-9 (the added catalog read reuses InspectSlot, which already spells its comparisons through pg_catalog).

Non-blocking

  1. No test pins the failed-drop-plus-failed-close case on the default arm, which is the half of the distinction the PR exists to keep. The two negative tests cover a held slot refused with ErrSlotActive (slot_drop_close_integration_test.go#L47-L66) and a slot recreated after an accepted drop (reap_close_integration_test.go#L55-L79). A wait the context ends, or a drop the server errors on, with a close that also fails goes through the default arm at L265 and is covered by neither, and the existing context test has no close fault. Because confirmSlotGone backs the classification, a regression there would most likely still fail closed, so this is a gap in proof rather than a live defect. Two smaller gaps sit beside it: ErrSlotDroppedPublicationLeft joined with a close failure (slot_drop.go#L164), whose joined shape the new doc comment promises, and both confirming reads failing. The fault helper can already write the first; it cannot kill the connection after the command is sent, so a mid-statement break is not reachable with it yet.
Test case (not run here: needs a live PostgreSQL through the fixture): a wait the context ends, with a failing close, is not a drop
func TestDropSlotEndedByItsContextWhoseConnectionFailsToCloseIsNotADrop(t *testing.T) {
	f := newSlotFixture(t)
	slot := f.createSlot(t)
	require.NoError(t, slot.Close(t.Context()))
	release := f.holdSlot(t, slot)
	defer release()
	fault := &testutil.SlotDropFault{FailClose: true}
	cfg := f.cfg
	cfg.BeforeConnect = fault.BeforeConnect

	dropCtx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond)
	defer cancel()
	err := decode.DropSlot(dropCtx, cfg, f.pool, slot.Name())

	require.ErrorIs(t, err, context.DeadlineExceeded)
	require.ErrorIs(t, err, testutil.ErrInjectedCloseFailure, "the close's error rides beside the failure")
	assert.NotErrorIs(t, err, decode.ErrSlotDroppedConnectionNotClosed)
	assert.NotErrorIs(t, err, decode.ErrSlotDroppedPublicationLeft)
	assert.Equal(t, int64(1), fault.ClosesFailed())
	_, found, err := decode.InspectSlot(t.Context(), f.pool, slot.Name())
	require.NoError(t, err)
	assert.True(t, found, "the holder keeps the slot")
	assert.True(t, f.publicationExists(t, slot.Name()))
}

Not run: the fixture starts a PostgreSQL container, which this review does not use. Expected to pass at 0358750 by reading the default arm; it would fail under a change that lets that arm return closeErr, nil once the slot is gone.

  1. Only the reaper carries a confirmed drop on; every other caller still turns the sentinel into a failure, and the docs read as if the sentinel were universally "not a failure". The sentinel's own comment says "it is not a failure of the drop" (slot_drop.go#L33-L44), but Runner.Run returns Result{}, err for a swap that has committed (runner.go#L523-L525), restart's discard stops (runner_restart.go#L134), and ReplaceSlot returns the bare close error, without the sentinel or any context, and does not create the new slot (slot.go#L201-L207); its doc comment still describes only the drop and the create. For a discard of an unrecorded slot (runner_discard.go#L317-L319) Discarded.Slot stays empty although slot and publication are gone, and discardFailure (discard.go#L239-L254) knows only the publication-left sentinel, so with nothing else dropped the CLI prints a plain error and no report. All of these fail on the safe side and a rerun finishes, so none is a defect; the PR just does not say which callers carry on and which stop. A sentence in the sentinel's comment (reaper carries on, the runner and ReplaceSlot stop and rerun) and a wrapped ReplaceSlot error would settle it.

Verified

  • Tests that run without a database are the only ones I ran, each anchored with a timeout: TestCaptureFailedCoversEveryCaptureSentinel passes at 0358750, and go vet is clean on pkg/decode, pkg/checkpoint, pkg/schemachange, the CLI package and the test-helper package. The five new tests, the fault helper and the reaper tests need a live PostgreSQL; I read them and did not run them.
  • Callers checked: DropSlot, DropIdleSlot and the gone-table forms at runner.go#L523, runner_restart.go#L134, runner_live_dispatch.go#L82, runner_discard.go#L274/#L317, runner_discard_gone.go#L147/#L208, reap.go#L245 and cli/discard.go; each treats a non-nil error as a stop, so none can read the new sentinel as success except the reaper branch.
  • Mutation (only the database-free test could run; the rest are by reading, labelled as such):
Mutant Caught by
M1 drop the ErrSlotDroppedConnectionNotClosed exemption in captureSentinelsNotRunFailures TestCaptureFailedCoversEveryCaptureSentinel (ran: --- FAIL, "decode.ErrSlotDroppedConnectionNotClosed is neither in captureFailed nor in captureSentinelsNotRunFailures")
M2 skip confirmSlotGone after a close failure (by reading) TestReapOrphanSlotsStopsAtASlotTheCatalogStillShowsAfterAFailedClose (needs PostgreSQL, not run)
M3 remove the second read in confirmSlotGone (by reading) TestDropSlotConfirmsOnAFreshReadWhenTheFirstConfirmingReadFails (not run)
M4 build the sentinel on the ErrSlotActive arm (by reading) TestDropIdleSlotOfAHeldSlotWhoseConnectionFailsToCloseLeavesBoth (not run)
M5 default arm returns closeErr, nil (by reading) survives every test in the PR; the test case in finding 1 is the specification
M6 drop the Unclosed loop in cli/reap.go (by reading) survives; no test reads the warning

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon

Copy link
Copy Markdown
Collaborator

🤖 Review 2/2 (OSS adoption and integration) of 0358750: 0 blocking, 2 non-blocking.

Read the change from two seats: an importer that calls decode.DropSlot or checkpoint.Store.ReapOrphanSlots from its own binary (SchemaBot is the obvious one), and an operator who runs pg-sprite reap from a cron job or a runbook and only meets the exit code, the report and stderr. The Go surface is additive and fits the package's shape: Reaped gains one field, Unclosed, that annotates Dropped rather than adding a list a consumer must reconcile with it, so a host that ignores it keeps a correct view of what is gone; UnclosedDrop.Err wraps both the new sentinel and the close's own error, so errors.Is works for either; the sentinel sits beside ErrSlotDroppedPublicationLeft and follows its join shape; and the design guide's reapOrphans example (copy-and-swap-design.md#L404-L408) was updated in the same PR, so an importer who copies it gets the warning.

Non-blocking

  1. DropSlot and DropIdleSlot now return a non-nil error for a drop that is complete, and nothing tells an importer except a doc comment. The sentinel's comment says a caller "counts both as gone and records the close's error; it is not a failure of the drop" (slot_drop.go#L33-L44), but the idiomatic if err := decode.DropSlot(...); err != nil { return err } still treats it as a failure, which is the safe default and what every caller in this repo other than the reaper does (see finding 2 of 1/2). An importer that wants the reaper's behavior has to write errors.Is(err, decode.ErrSlotDroppedConnectionNotClosed) and know that the slot and publication are gone when it matches; the one it already writes for ErrSlotDroppedPublicationLeft means the opposite for the publication. A one-line helper next to the sentinels (for example decode.SlotGone(err) bool, true for nil, the sentinel, and the publication-left case), or a short "outcomes of a drop" list in the guide beside the reaper section, would put the three outcomes in one place for the next importer instead of leaving each to read three comments.

  2. For an operator the close failure is a stderr line only, and the exit code changes from 1 to 0, so a cron job or alert keyed on either loses the signal. Before the PR a failed close stopped the pass: failed set, stopped: true, exit 1. Now the slot lands in dropped, the pass goes on and exits 0, and the only trace is the warning written at reap.go#L125-L132 and described in docs/cli.md. That is a defensible call, since nothing is left to act on, but it is a changed exit contract for a command whose docs say the report's format_version is bumped whenever a field "changes meaning" (it stays 3, and the failed row's text was narrowed rather than its shape changed). --json consumers cannot see which dropped entries had a close failure, and no test reads the warning, so deleting the loop leaves every test green. Either an unclosed list in the report (with the version bump the docs promise) or a sentence in the release note that a close failure no longer exits 1 and that stderr is where it shows would let an operator decide whether to alert on it; a small CLI test that the warning is written would pin the documented behavior.

What reads well for adopters

  • The doc comments on Reaped.Failed, the reap report's failed row and ST-3 now say plainly when a failed slot may already be gone (reply lost, or both confirming reads failed) and when it cannot be (the catalog confirmed it), which is the question an operator asks first when a pass stops.
  • The fault helper in the test-helper package is generic (a hook on the connection, a counter the test asserts so a connection it could not read fails the test instead of passing it), so an importer testing its own drop handling can reuse the technique.
  • Nothing in the added error text can carry a connection string or row data beyond what the close error from the driver already did, and the warning goes to stderr, not into the report that scripts parse.

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon aparajon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Stamping with comments: 0 blocking, 4 non-blocking (see the review comments above).

This stamp was left by Claude Code (claude-sonnet-5-5).

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