# Copyright (c) 2026, PostgreSQL Global Development Group

# A non-transactional message followed by a remote transaction that keeps
# failing should reach the handler once, not once per apply-worker retry.
# Fails on v9-0002 (handler runs on every retry); passes if the commit in
# apply_handle_message() advances the replication origin to msg.lsn.
use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

my $pub = PostgreSQL::Test::Cluster->new('publisher');
$pub->init(allows_streaming => 'logical');
$pub->start;

my $sub = PostgreSQL::Test::Cluster->new('subscriber');
$sub->init;
$sub->append_conf('postgresql.conf', q{
shared_preload_libraries = 'test_logicalmsg_hooks'
wal_retrieve_retry_interval = 200ms
});
$sub->start;

$pub->safe_psql('postgres',
	'CREATE TABLE t (a int); CREATE PUBLICATION pub FOR ALL TABLES;');
$sub->safe_psql('postgres', 'CREATE TABLE t (a int PRIMARY KEY);');
my $connstr = $pub->connstr . ' dbname=postgres';
$sub->safe_psql('postgres',
	"CREATE SUBSCRIPTION sub CONNECTION '$connstr' PUBLICATION pub WITH (messages = true)");
$sub->wait_for_subscription_sync($pub, 'sub');

# Get the module's log table created.
$pub->safe_psql('postgres', q{SELECT pg_logical_emit_message(true, 'init', 'x')});
$pub->wait_for_catchup('sub');

# Local row that the next remote INSERT will conflict with.
$sub->safe_psql('postgres', 'INSERT INTO t VALUES (1)');

my $log_offset = -s $sub->logfile;
$pub->safe_psql('postgres', q{
SELECT pg_logical_emit_message(false, 'nontx', 'deliver once');
INSERT INTO t VALUES (1);
});

# Wait for several retries of the failing transaction.
$sub->wait_for_log(qr/conflict detected on relation "public.t"(?s:.*)conflict detected on relation "public.t"(?s:.*)conflict detected on relation "public.t"/,
	$log_offset);

is($sub->safe_psql('postgres',
		q{SELECT count(*) FROM test_logicalmsg_log WHERE prefix = 'nontx'}),
	'1', 'non-transactional message is not re-handled on each retry');

done_testing();
