Skip to content

Cancelling StartReplication before its startup reply can leave the logical slot active #6770

Open

Description

@thomhurst

Summary

Cancelling LogicalReplicationConnection.StartReplication while its START_REPLICATION command is in flight can leave the stream running with an active slot. The cancellation request reaches PostgreSQL before the command, and the client does not stop within the configured cancellation timeout after the command later reaches the server.

Reproduction

Use PostgreSQL 18.6 with wal_level=logical, Npgsql 11.0.0, .NET 11 and Python 3. Run the client against a disposable server. Send logical replication through a loopback proxy that holds the START_REPLICATION packet but forwards the separate CancelRequest connection. Cancel the stream token, then let the held packet reach PostgreSQL. The control forwards the packet first and waits for the first standby reply before cancelling. Neither case needs a publication write.

Runnable client and TCP proxy

Use a new net11.0 console project with NuGet package Npgsql 11.0.0. The PostgreSQL example uses port 5432 and password probe. Run python proxy.py 5432 early with an empty early directory. Read the proxy's listening port from early/port, then run dotnet run -- 5432 LISTENING_PORT early early. To run the control, use an empty directory named ready for both commands and pass ready as the final client argument.

Program.cs

using Npgsql;
using Npgsql.Replication;
using Npgsql.Replication.PgOutput;

var port = int.Parse(args[0]);
var proxyPort = int.Parse(args[1]);
var status = args[2];
var mode = args[3];
var slot = mode == "early" ? "early_probe" : "ready_probe";
var settings = $"Host=127.0.0.1;Port={port};Username=postgres;Password=probe;Database=postgres;Pooling=false;SSL Mode=Disable;GSS Encryption Mode=Disable";
await using var sql = new NpgsqlConnection(settings);
await sql.OpenAsync();
await using (var provision = new NpgsqlCommand($"""
    CREATE TABLE IF NOT EXISTS events (value int);
    DROP PUBLICATION IF EXISTS events;
    CREATE PUBLICATION events FOR TABLE events;
    """, sql))
{
    await provision.ExecuteNonQueryAsync();
    provision.CommandText = $"SELECT pg_create_logical_replication_slot('{slot}', 'pgoutput')";
    await provision.ExecuteNonQueryAsync();
}

var replicationSettings = new NpgsqlConnectionStringBuilder(settings) { Port = proxyPort };
await using var replication = new LogicalReplicationConnection(replicationSettings.ConnectionString)
{
    WalReceiverStatusInterval = TimeSpan.FromMilliseconds(25)
};
await replication.Open();
using var cancellation = new CancellationTokenSource();
var read = ReadAsync();

using var guard = new CancellationTokenSource(TimeSpan.FromSeconds(10));
while (!File.Exists(Path.Combine(status, "held")))
{
    await Task.Delay(10, guard.Token);
}
if (mode == "ready")
{
    File.WriteAllText(Path.Combine(status, "release"), "");
    await using var command = new NpgsqlCommand($"""
        SELECT EXISTS (
            SELECT FROM pg_replication_slots s
            JOIN pg_stat_replication r ON s.active_pid = r.pid
            WHERE s.slot_name = '{slot}' AND r.reply_time IS NOT NULL)
        """, sql);
    while (await command.ExecuteScalarAsync(guard.Token) is not true)
    {
        await Task.Delay(10, guard.Token);
    }
}

cancellation.Cancel();
if (mode == "early")
{
    File.WriteAllText(Path.Combine(status, "release"), "");
}
if (await Task.WhenAny(read, Task.Delay(TimeSpan.FromSeconds(35))) == read)
{
    await read;
    Console.WriteLine($"{mode}: stream stopped within 35 seconds");
}
else
{
    await using var command = new NpgsqlCommand($"SELECT active FROM pg_replication_slots WHERE slot_name = '{slot}'", sql);
    Console.WriteLine($"{mode}: stream still pending after 35 seconds, slot active={await command.ExecuteScalarAsync()}");
    command.CommandText = $"SELECT pg_terminate_backend(active_pid) FROM pg_replication_slots WHERE slot_name = '{slot}' AND active";
    await command.ExecuteNonQueryAsync();
    try
    {
        await read.WaitAsync(TimeSpan.FromSeconds(5));
    }
    catch (NpgsqlException)
    {
        // The simulated delayed-start connection is terminated for probe cleanup.
    }
}

async Task ReadAsync()
{
    try
    {
        await foreach (var _ in replication.StartReplication(new PgOutputReplicationSlot(slot), new("events", PgOutputProtocolVersion.V1), cancellation.Token))
        {
        }
    }
    catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
    {
    }
}

proxy.py

import asyncio
import struct
import sys
from pathlib import Path

port = int(sys.argv[1])
folder = Path(sys.argv[2])

async def pump(source, destination):
    while data := await source.read(65536):
        destination.write(data)
        await destination.drain()

async def handle(client, to_client):
    pg, to_pg = await asyncio.open_connection("127.0.0.1", port)
    tasks = []
    try:
        size = await client.readexactly(4)
        startup = await client.readexactly(struct.unpack("!I", size)[0] - 4)
        to_pg.write(size + startup)
        await to_pg.drain()
        if struct.unpack("!I", startup[:4])[0] == 80877102:
            await pump(pg, to_client)
            return
        tasks.append(asyncio.create_task(pump(pg, to_client)))
        while True:
            header = await client.readexactly(5)
            payload = await client.readexactly(struct.unpack("!I", header[1:])[0] - 4)
            if header[:1] == b"Q" and payload.startswith(b"START_REPLICATION"):
                (folder / "held").touch()
                while not (folder / "release").exists():
                    await asyncio.sleep(0.005)
                to_pg.write(header + payload)
                await to_pg.drain()
                break
            to_pg.write(header + payload)
            await to_pg.drain()
        tasks.append(asyncio.create_task(pump(client, to_pg)))
        await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    except (asyncio.IncompleteReadError, ConnectionError):
        pass
    finally:
        for task in tasks:
            task.cancel()
        await asyncio.gather(*tasks, return_exceptions=True)
        to_pg.close()
        to_client.close()

async def main():
    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    (folder / "port").write_text(str(server.sockets[0].getsockname()[1]))
    async with server:
        await server.serve_forever()

asyncio.run(main())

Expected and actual

Expected the enumerator to throw OperationCanceledException or otherwise stop within the default two-second cancellation timeout after the server misses the early cancel. It still owned the slot after 35 seconds. In a separate run with a four-second guard, the control stopped within the guard. The repro has no Relayer dependency.

The pinned cancellation callback installs a two-second read timeout. Replication startup changes the read timeout after receiving the initial response. That ordering looks capable of overwriting the cancellation fallback. Repository main has the same implementation. #5523 concerns leaving the enumeration without cancellation.

Could the replication startup path preserve the cancellation deadline when the startup response arrives after cancellation? Found while diagnosing Relayer CI.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions