Skip to content

Commit 810e781

Browse files
fix(replication): add inbound stream watchdog for silent stalls (#5148)
1 parent 17de59a commit 810e781

3 files changed

Lines changed: 257 additions & 2 deletions

File tree

‎apps/webapp/app/services/runsReplicationService.server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,7 @@ export class RunsReplicationService {
488488
const client = new LogicalReplicationClient({
489489
pgConfig: {
490490
connectionString: source.pgConnectionUrl,
491+
connectionTimeoutMillis: 10_000,
491492
},
492493
name: `${options.serviceName}:${source.id}`,
493494
slotName: source.slotName,
@@ -497,6 +498,7 @@ export class RunsReplicationService {
497498
redisOptions: options.redisOptions,
498499
autoAcknowledge: false,
499500
resubscribeOnFailure: true,
501+
streamHeartbeatTimeoutMs: 90_000,
500502
maxResubscribeAttempts: options.maxResubscribeAttempts,
501503
publicationActions: ["insert", "update", "delete"],
502504
logger:

‎internal-packages/replication/src/client.test.ts‎

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Redis, type RedisOptions } from "@internal/redis";
22
import { createPostgresContainer, postgresAndRedisTest } from "@internal/testcontainers";
3+
import net from "node:net";
34
import { Client } from "pg";
45
import { LogicalReplicationClient } from "./client.js";
56
import type { MessageRelation, PgoutputMessage } from "./pgoutput.js";
@@ -1307,4 +1308,193 @@ describe("Replication Client", () => {
13071308
}
13081309
}
13091310
);
1311+
1312+
postgresAndRedisTest(
1313+
"streamHeartbeatTimeoutMs reconnects when a replication stream silently stalls",
1314+
async ({ postgresContainer, prisma, redisOptions }) => {
1315+
await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`);
1316+
1317+
const pgHost = postgresContainer.getHost();
1318+
const pgPort = postgresContainer.getPort();
1319+
const pgUrl = new URL(postgresContainer.getConnectionUri());
1320+
1321+
let blackholeActive = false;
1322+
const upstreamSockets = new Set<net.Socket>();
1323+
const clientSockets = new Set<net.Socket>();
1324+
let connectionCount = 0;
1325+
1326+
const proxy = net.createServer((clientSocket) => {
1327+
connectionCount++;
1328+
const connIndex = connectionCount;
1329+
clientSockets.add(clientSocket);
1330+
1331+
const upstreamSocket = net.createConnection({ host: pgHost, port: pgPort });
1332+
upstreamSockets.add(upstreamSocket);
1333+
1334+
clientSocket.on("data", (chunk) => {
1335+
if (blackholeActive && connIndex === 1) return;
1336+
if (!upstreamSocket.destroyed) upstreamSocket.write(chunk);
1337+
});
1338+
upstreamSocket.on("data", (chunk) => {
1339+
if (blackholeActive && connIndex === 1) return;
1340+
if (!clientSocket.destroyed) clientSocket.write(chunk);
1341+
});
1342+
1343+
const cleanup = () => {
1344+
clientSockets.delete(clientSocket);
1345+
upstreamSockets.delete(upstreamSocket);
1346+
if (!clientSocket.destroyed) clientSocket.destroy();
1347+
if (!upstreamSocket.destroyed) upstreamSocket.destroy();
1348+
};
1349+
clientSocket.on("error", cleanup);
1350+
upstreamSocket.on("error", cleanup);
1351+
clientSocket.on("close", cleanup);
1352+
upstreamSocket.on("close", cleanup);
1353+
});
1354+
1355+
await new Promise<void>((resolve) => proxy.listen(0, "127.0.0.1", resolve));
1356+
const proxyAddress = proxy.address() as net.AddressInfo;
1357+
pgUrl.hostname = "127.0.0.1";
1358+
pgUrl.port = String(proxyAddress.port);
1359+
1360+
const client = new LogicalReplicationClient({
1361+
name: "watchdog-stall-test",
1362+
slotName: "watchdog_stall_slot",
1363+
publicationName: "watchdog_stall_pub",
1364+
redisOptions,
1365+
table: "TaskRun",
1366+
pgConfig: { connectionString: pgUrl.toString() },
1367+
resubscribeOnFailure: true,
1368+
resubscribeMinDelayMs: 50,
1369+
resubscribeMaxDelayMs: 100,
1370+
streamHeartbeatTimeoutMs: 150,
1371+
});
1372+
1373+
const errors: Error[] = [];
1374+
const starts: number[] = [];
1375+
const logs: Array<{ lsn: string; log: PgoutputMessage }> = [];
1376+
1377+
client.events.on("error", (err) => errors.push(err));
1378+
client.events.on("start", () => starts.push(Date.now()));
1379+
client.events.on("data", (data) => logs.push(data));
1380+
1381+
try {
1382+
await client.subscribe();
1383+
for (let i = 0; i < 40 && starts.length < 1; i++) {
1384+
await setTimeout(50);
1385+
}
1386+
expect(starts).toHaveLength(1);
1387+
1388+
// Silently blackhole the first TCP connection: no frames, no socket error/close.
1389+
blackholeActive = true;
1390+
1391+
// Wait for watchdog to trip, destroy the stalled socket, and resubscribe on a fresh one.
1392+
for (let i = 0; i < 60 && starts.length < 2; i++) {
1393+
await setTimeout(50);
1394+
}
1395+
1396+
expect(errors.some((e) => e.message.includes("Replication stream stalled"))).toBe(true);
1397+
expect(starts.length).toBeGreaterThanOrEqual(2);
1398+
1399+
// Verify the reconnected stream actually receives new changes.
1400+
const org = await prisma.organization.create({ data: { title: "t", slug: "t-stall" } });
1401+
const proj = await prisma.project.create({
1402+
data: {
1403+
name: "t",
1404+
slug: "t-stall",
1405+
organizationId: org.id,
1406+
externalRef: "t-stall",
1407+
},
1408+
});
1409+
const env = await prisma.runtimeEnvironment.create({
1410+
data: {
1411+
slug: "t-stall",
1412+
type: "DEVELOPMENT",
1413+
projectId: proj.id,
1414+
organizationId: org.id,
1415+
apiKey: "t-stall",
1416+
pkApiKey: "t-stall",
1417+
shortcode: "t-stall",
1418+
},
1419+
});
1420+
await prisma.taskRun.create({
1421+
data: {
1422+
friendlyId: "run_after_stall",
1423+
taskIdentifier: "my-task",
1424+
payload: "{}",
1425+
traceId: "t1",
1426+
spanId: "s1",
1427+
queue: "test",
1428+
runtimeEnvironmentId: env.id,
1429+
projectId: proj.id,
1430+
},
1431+
});
1432+
1433+
const found = await waitForLogs(logs, 0, (f) => f.some((m) => m.tag === "insert"));
1434+
expect(found.some((m) => m.tag === "insert")).toBe(true);
1435+
} finally {
1436+
await client.shutdown();
1437+
for (const s of clientSockets) s.destroy();
1438+
for (const s of upstreamSockets) s.destroy();
1439+
await new Promise<void>((resolve) => proxy.close(() => resolve()));
1440+
}
1441+
}
1442+
);
1443+
1444+
postgresAndRedisTest(
1445+
"periodic keepalive (0x6b) frames reset the stream watchdog and prevent disconnects",
1446+
async ({ postgresContainer, prisma, redisOptions }) => {
1447+
await prisma.$executeRawUnsafe(`ALTER TABLE public."TaskRun" REPLICA IDENTITY FULL;`);
1448+
1449+
const client = new LogicalReplicationClient({
1450+
name: "watchdog-keepalive-test",
1451+
slotName: "watchdog_keepalive_slot",
1452+
publicationName: "watchdog_keepalive_pub",
1453+
redisOptions,
1454+
table: "TaskRun",
1455+
pgConfig: { connectionString: postgresContainer.getConnectionUri() },
1456+
resubscribeOnFailure: true,
1457+
resubscribeMinDelayMs: 50,
1458+
resubscribeMaxDelayMs: 100,
1459+
streamHeartbeatTimeoutMs: 200,
1460+
});
1461+
1462+
const errors: Error[] = [];
1463+
const starts: number[] = [];
1464+
const heartbeats: number[] = [];
1465+
1466+
client.events.on("error", (err) => errors.push(err));
1467+
client.events.on("start", () => starts.push(Date.now()));
1468+
client.events.on("heartbeat", () => heartbeats.push(Date.now()));
1469+
1470+
try {
1471+
await client.subscribe();
1472+
for (let i = 0; i < 40 && starts.length < 1; i++) {
1473+
await setTimeout(50);
1474+
}
1475+
expect(starts).toHaveLength(1);
1476+
1477+
// Send valid 0x6b Primary keepalive frames every 75ms for 450ms (> 200ms timeout).
1478+
const keepalive = Buffer.alloc(18);
1479+
keepalive[0] = 0x6b;
1480+
keepalive.writeUInt32BE(1, 5); // LSN 0/1
1481+
1482+
for (let i = 0; i < 6; i++) {
1483+
await setTimeout(75);
1484+
// @ts-expect-error accessing private connection to simulate inbound keepalive frames
1485+
client.connection?.emit("copyData", {
1486+
length: keepalive.length,
1487+
chunk: keepalive,
1488+
name: "copyData",
1489+
});
1490+
}
1491+
1492+
expect(heartbeats.length).toBeGreaterThanOrEqual(6);
1493+
expect(errors).toHaveLength(0);
1494+
expect(starts).toHaveLength(1);
1495+
} finally {
1496+
await client.shutdown();
1497+
}
1498+
}
1499+
);
13101500
});

‎internal-packages/replication/src/client.ts‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,13 @@ export interface LogicalReplicationClientOptions {
115115
*/
116116
ackIntervalSeconds?: number;
117117

118+
/**
119+
* Watchdog timeout in ms for inbound replication stream traffic (`0x77` XLogData or `0x6b`
120+
* Primary keepalive). When exceeded, the stalled socket is destroyed with an error so the
121+
* client reconnects. Off by default when omitted or `<= 0`.
122+
*/
123+
streamHeartbeatTimeoutMs?: number;
124+
118125
/**
119126
* The actions to publish to the publication.
120127
*/
@@ -166,6 +173,8 @@ export class LogicalReplicationClient {
166173
private ackIntervalSeconds: number;
167174
private lastAckTimestamp: number = 0;
168175
private ackIntervalTimer: NodeJS.Timeout | null = null;
176+
private streamHeartbeatTimeoutMs: number;
177+
private streamWatchdogTimer: NodeJS.Timeout | null = null;
169178
private _isStopped: boolean = false;
170179
private _tracer: Tracer;
171180
private resubscribeOnFailure: boolean;
@@ -207,6 +216,7 @@ export class LogicalReplicationClient {
207216
this.leaderLockAcquireAdditionalTimeMs = options.leaderLockAcquireAdditionalTimeMs ?? 1000;
208217
this.leaderLockRetryIntervalMs = options.leaderLockRetryIntervalMs ?? 500;
209218
this.ackIntervalSeconds = options.ackIntervalSeconds ?? 10;
219+
this.streamHeartbeatTimeoutMs = options.streamHeartbeatTimeoutMs ?? 0;
210220
this.resubscribeOnFailure = options.resubscribeOnFailure ?? false;
211221
this.resubscribeMinDelayMs = options.resubscribeMinDelayMs ?? 1000;
212222
this.resubscribeMaxDelayMs = options.resubscribeMaxDelayMs ?? 30000;
@@ -258,6 +268,7 @@ export class LogicalReplicationClient {
258268
clearInterval(this.ackIntervalTimer);
259269
this.ackIntervalTimer = null;
260270
}
271+
this.#clearStreamWatchdog();
261272
// Release leader lock if held
262273
await this.#releaseLeaderLock();
263274

@@ -292,6 +303,7 @@ export class LogicalReplicationClient {
292303
clearInterval(this.ackIntervalTimer);
293304
this.ackIntervalTimer = null;
294305
}
306+
this.#clearStreamWatchdog();
295307

296308
return this;
297309
});
@@ -349,6 +361,8 @@ export class LogicalReplicationClient {
349361
this.ackIntervalTimer = null;
350362
}
351363

364+
this.#clearStreamWatchdog();
365+
352366
this.connection?.removeAllListeners();
353367
this.connection = null;
354368

@@ -602,7 +616,8 @@ export class LogicalReplicationClient {
602616
return this;
603617
}
604618

605-
this.connection.once("replicationStart", () => {
619+
const connection = this.connection;
620+
connection.once("replicationStart", () => {
606621
if (this._intentionalStop) {
607622
// shutdown() raced the stream start — tear this attempt down.
608623
void this.#cleanupAttempt();
@@ -612,17 +627,19 @@ export class LogicalReplicationClient {
612627
this.resubscribeAttempts = 0;
613628
this.recoveryFailures = 0;
614629
this.resubscribeGaveUp = false;
630+
this.#armStreamWatchdog(attemptEpoch, connection);
615631
this.events.emit("start");
616632
});
617633

618-
this.connection.on(
634+
connection.on(
619635
"copyData",
620636
async ({ chunk: buffer }: { length: number; chunk: Buffer; name: string }) => {
621637
// pgoutput protocol: 0x77 = XLogData, 0x6b = Primary keepalive
622638
if (buffer[0] !== 0x77 && buffer[0] !== 0x6b) {
623639
this.logger.warn("Unknown replication message type", { byte: buffer[0] });
624640
return;
625641
}
642+
this.#armStreamWatchdog(attemptEpoch, connection);
626643
const lsn =
627644
buffer.readUInt32BE(1).toString(16).toUpperCase() +
628645
"/" +
@@ -1372,4 +1389,50 @@ export class LogicalReplicationClient {
13721389
}
13731390
}, 1000);
13741391
}
1392+
1393+
#clearStreamWatchdog(): void {
1394+
if (this.streamWatchdogTimer) {
1395+
clearTimeout(this.streamWatchdogTimer);
1396+
this.streamWatchdogTimer = null;
1397+
}
1398+
}
1399+
1400+
#armStreamWatchdog(attemptEpoch: number, connection: Connection): void {
1401+
this.#clearStreamWatchdog();
1402+
if (this.streamHeartbeatTimeoutMs <= 0) return;
1403+
if (
1404+
this._intentionalStop ||
1405+
attemptEpoch !== this.subscribeEpoch ||
1406+
this.connection !== connection
1407+
) {
1408+
return;
1409+
}
1410+
1411+
this.streamWatchdogTimer = setTimeout(() => {
1412+
this.streamWatchdogTimer = null;
1413+
if (
1414+
this._intentionalStop ||
1415+
attemptEpoch !== this.subscribeEpoch ||
1416+
this.connection !== connection
1417+
) {
1418+
return;
1419+
}
1420+
1421+
this.logger.error("Replication stream stalled", {
1422+
name: this.options.name,
1423+
slotName: this.options.slotName,
1424+
publicationName: this.options.publicationName,
1425+
streamHeartbeatTimeoutMs: this.streamHeartbeatTimeoutMs,
1426+
});
1427+
1428+
// @ts-ignore pg does not type the client's connection stream
1429+
const stream: { destroy(error?: Error): void } | undefined = connection.stream;
1430+
const stalledError = new Error("Replication stream stalled");
1431+
if (stream) {
1432+
stream.destroy(stalledError);
1433+
} else {
1434+
connection.emit("error", stalledError);
1435+
}
1436+
}, this.streamHeartbeatTimeoutMs);
1437+
}
13751438
}

0 commit comments

Comments
 (0)