Skip to content

Fix TIMELINE_HISTORY, SHOW ALL and CommandTimeout on replication connections - #6709

Merged
Brar merged 2 commits into
npgsql:mainfrom
Brar:repl/command-fixes
Nov 7, 2026
Merged

Brar merged 2 commits into
npgsql:mainfrom
Brar:repl/command-fixes

Conversation

@Brar

@Brar Brar commented Oct 25, 2026 •

Copy link
Copy Markdown
Member
  • TimelineHistory threw InvalidCastException ("Unable to cast object of type 'System.String' to type 'System.Byte[]'") for every history file on PostgreSQL 14 and later, which declare the content column as text instead of bytea. The column carries the raw bytes of the history file either way, so it is now read as raw bytes. The rarer DecoderFallbackException, for a history file that isn't valid UTF-8, also left the connection out of sync, and on older servers the bytea unescaping mangled or failed on backslashes in the file; both are gone with it, and the bytea parsing, now unused, is removed.
  • Show("all") returns many rows, which made the command helper expect CommandComplete, get another DataRow and break the connection. Now any replication command whose result has more than one row throws NotSupportedException once the rest of the result has been read, which leaves the connection usable.
  • ReplicationConnection.CommandTimeout was ignored by replication commands, since every command reset the timeouts to the connection string's Command Timeout, and setting it before Open threw InvalidOperationException. Replication commands now pass it to StartUserAction, which takes an optional timeout for this, so it applies to all of them and can be set before Open. Timeouts that don't fit into an int of milliseconds (e.g. TimeSpan.MaxValue) mean no timeout.
  • StartReplication(PhysicalReplicationSlot, CancellationToken) throws ArgumentNullException for a null slot instead of a NullReferenceException.

How a real server gets there

Each case ran against main and this PR, most of them also against the released 10.0.3, which behaved like main.

  • TIMELINE_HISTORY: a timeline above 1 exists after any promotion or point-in-time recovery, e.g. for a failover-aware client that looks up the switch point. On 14.24 after a plain promotion and on 18.6 after a recovery to a restore point, main threw the InvalidCastException; this PR returned the server's file byte for byte. The mock test's 0xFF byte stands for the rare variant: a history line quotes the restore point's name, so on 18.6 with a LATIN1 database and a restore point named with an é, main threw DecoderFallbackException before the row was consumed, and the next IDENTIFY_SYSTEM failed after 32 s. On 13.23 after a recovery to a restore point named rsa5\probe, main failed with "Could not parse data as bytea in field content" and broke the connection.
  • SHOW all: Show("all") gave 399 rows on 18.6. Main threw "Received backend message DataRow while expecting CommandCompleteMessage" and broke the connection; this PR throws NotSupportedException, and IDENTIFY_SYSTEM works afterwards. None of the other commands Npgsql reads this way returns more than one row; the mock test More_than_one_row covers one that would.
  • CommandTimeout: DropReplicationSlot(name, wait: true) while another session still streams from the slot waits on the server until the slot is released. With CommandTimeout = 3 s and Command Timeout=30 in the connection string, main waited 12 s, until the other session stopped; this PR timed out after 3 s, its cancellation ended the server's wait, and the connection stayed usable. A logical CREATE_REPLICATION_SLOT, which shares the read path of IDENTIFY_SYSTEM, waits for every running transaction that holds an xid: 12.2 s on main against 3.0 s with this PR. START_REPLICATION only waits on a stalled host or network, which was shown with a suspended walsender: 25 s on main, 13 s with this PR (about 10 s of each is the cancellation attempt). Setting the property before Open threw on main, and the following command ignored it.
  • The null slot: e.g. the null that ReadReplicationSlot returns for a missing slot, passed on unchecked. NullReferenceException on main, ArgumentNullException (slot) with this PR.

Tests

ReplicationCommandMockTests (12 cases, mock). On main 11 of them fail; CommandTimeout_too_large_for_a_socket passes there and guards the new handling of huge timeouts.

For the reviewer

  • No public API change. A core change: NpgsqlConnector.StartUserAction takes an optional timeout, which only the replication commands pass; without it, it applies the command's or the connection string's command timeout as before.
  • Behavior changes, also in the 11.0 release notes: CommandTimeout applies to replication commands, and Show("all") throws NotSupportedException.
  • Every release since 5.0 has the TimelineHistory bug (the released 8.0.9, 9.0.5 and 10.0.3 fail the same way on 14.24 and 18.6), and no CI test reads the content (CommonReplicationTests.TimelineHistory is [Explicit]). The TimelineHistory fix is meant to go to the 10.0 hotfix branch once this is merged.

Dependencies and merge order

It depends on no other PR.

Fixes #6695

@roji roji left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Recommendation

Proceed with this direction after #6689. I found no correctness issue requiring a revision in the command-fix layer. These are observable bugs in existing APIs, and the implementation is appropriately small.

Problem

On an open physical replication connection, these calls independently reproduce two failures:

await rc.TimelineHistory(2); // On a server promoted to timeline 2.
await rc.Show("all");

The original history reader decodes the content according to its declared PostgreSQL type, although the replication protocol sends file bytes directly. PostgreSQL 14+ declares that column as text, causing an InvalidCastException; the older bytea parser can instead corrupt backslashes. Show("all") receives multiple rows, but the original reader expects command completion after the first row and breaks the connection.

Separately, this property does not govern the wait on the original code:

rc.CommandTimeout = TimeSpan.FromSeconds(1);
await rc.DropReplicationSlot("busy_slot", wait: true);

Command startup resets the buffers to the connection-string timeout. Setting the property before Open() also throws.

Expected approach and alignment

I would preserve the public API: read history content as bytes regardless of its declared OID, consume unsupported multi-row results before rejecting them, and apply the replication timeout immediately after each user-action startup. This calls for tens of lines of production logic, removal of obsolete parsing, and focused regression tests, not another abstraction.

That is what the PR does: history and SHOW handling, raw-byte reading and row draining, and timeout application on all three command entry paths. The null-slot guard is a reasonable one-line companion fix. The large mock-support portion belongs to dependency #6689; this PR's own commit changes only two production files and adds one regression-test file.

Gaps and scope

No must-fix findings. Rejecting SHOW ALL is appropriate for an API returning one string; adding a new result-set API would be unnecessary scope. The tests cover both history column OIDs with invalid UTF-8 and a backslash, connection reuse after SHOW ALL, all three timeout entry paths before/after opening, oversized timeouts, and the null argument. The timeout/SHOW behavior corrections merit release-note coverage, not a public API redesign.

Manual validation

I built the pre-PR commit and PR HEAD and ran a separate console client against an isolated PostgreSQL 18.4 cluster, taking a base backup and promoting it to create a real timeline-2 history file. On HEAD, history matched that file byte-for-byte; the original build threw InvalidCastException. HEAD rejected SHOW ALL with NotSupportedException and successfully executed IDENTIFY_SYSTEM afterward; the original build broke the connection.

With another connection actively streaming from a slot, DROP_REPLICATION_SLOT WAIT timed out after 1.03 seconds on HEAD and left the connection usable. The original build ignored the one-second property and completed only when I released the slot after 4.01 seconds. Setting the timeout before opening succeeded only on HEAD. The 13 focused mock tests also passed. Live validation was on PostgreSQL 18.4; the pre-14 column declaration and stalled START_REPLICATION path were covered by mocks, not additional live servers.

Posted by copilot

roji
roji previously requested changes Oct 29, 2026
@roji
roji requested a balanced review from Copilot October 29, 2026 07:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the replication command-handling changes.

No open issues 🎉

What changed in this PR

Fixes replication command handling in Npgsql without changing the public API, addressing #6695. The PR also includes the replication mock infrastructure from prerequisite #6689.

Changes:

  • Reads timeline history content as raw bytes and safely consumes SHOW ALL results before throwing NotSupportedException.
  • Honors replication CommandTimeout, supports setting it before opening, treats oversized timeouts as infinite, and validates null physical replication slots.
  • Adds mock protocol support and regression tests for command handling, streaming, cancellation, and connection reuse.
File Description
test/​Npgsql.Tests/​Support/​ReplicationMock.cs Adds replication connection helpers and response builders.
test/​Npgsql.Tests/​Support/​PgServerMock.cs Adds replication messages, startup parsing, and null columns; corrects message lengths.
test/​Npgsql.Tests/​Support/​PgPostmasterMock.cs Makes the mock server version configurable.
test/​Npgsql.Tests/​Replication/​ReplicationMockTests.cs Tests replication startup, streaming, cancellation, and connection reuse.
test/​Npgsql.Tests/​Replication/​ReplicationCommandMockTests.cs Adds regression coverage for history bytes, SHOW ALL, timeouts, and null slots.
src/​Npgsql/​Replication/​ReplicationConnection.cs Fixes history decoding, result draining, and command timeout handling.
src/​Npgsql/​Replication/​PhysicalReplicationConnection.cs Rejects null slots with ArgumentNullException.

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The mock calculates message lengths using UTF-8 but writes fields as ASCII, corrupting non-ASCII text and potentially leaving readers waiting for bytes that are never sent.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Error field length mismatches its ASCII-encoded payload

test/​Npgsql.Tests/​Support/​PgServerMock.cs:547

The length is calculated as UTF-8, but the field writes below use WriteNullTerminatedString(string), which encodes as ASCII (NpgsqlWriteBuffer.cs:429–434). A non-ASCII error or notice such as Café therefore loses characters and declares more bytes than it sends, potentially leaving the reader waiting for missing bytes. Write these fields as UTF-8 bytes followed by NUL so the payload matches the declared length.

Review effort: Balanced

Brar and others added 2 commits November 1, 2026 13:28
…ections

- TimelineHistory threw an InvalidCastException on PostgreSQL 14 and
  later, which declare the content column as text instead of bytea. The
  column carries the raw bytes of the history file either way, so it is
  now read as raw bytes. That also stops bytea unescaping from mangling
  backslashes in the content on older servers, and leaves the bytea
  parsing without a use, so it is removed.
- Show("all") returns many rows, which made the command helper expect
  CommandComplete, get another DataRow and break the connection. Further
  rows are now skipped, and Show throws NotSupportedException for results
  that aren't a single value, leaving the connection usable.
- The ReplicationConnection.CommandTimeout property was ignored for
  replication commands, since every command reset the timeouts to the
  connection string's command timeout. It now applies to all commands,
  and setting it before Open no longer throws. Timeouts that don't fit
  into an int of milliseconds (e.g. TimeSpan.MaxValue) mean no timeout.
- StartReplication(PhysicalReplicationSlot, CancellationToken) throws
  ArgumentNullException for a null slot instead of a
  NullReferenceException.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- StartUserAction takes an optional timeout, which replication commands use
  for ReplicationConnection.CommandTimeout instead of overwriting the
  connection string's timeout that StartUserAction had just set. So the
  CommandTimeout setter no longer touches the buffers either.
- A replication command that returns more than one row throws
  NotSupportedException once the rest of its result has been read, instead of
  dropping the other rows. That covers SHOW ALL, so Show no longer checks for
  it itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brar
Brar force-pushed the repl/command-fixes branch from 0dc2337 to ec0ea97 Compare November 1, 2026 12:41
Copilot AI balanced review requested due to automatic review settings November 1, 2026 12:41

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues block approval of the replication connection fixes.

No open issues 🎉

Review effort: Balanced

@Brar
Brar requested a review from roji November 7, 2026 16:54
@Brar
Brar dismissed roji’s stale review November 7, 2026 17:11

Outdated. The problems are fixed.

@Brar
Brar merged commit 3bc0641 into npgsql:main Nov 7, 2026
13 checks passed
@Brar
Brar deleted the repl/command-fixes branch November 7, 2026 17:46
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.

TimelineHistory throws InvalidCastException on PostgreSQL 14+, Show("all") breaks the connection, ReplicationConnection.CommandTimeout is ignored

4 participants