Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Reserve the consumer's idle lane once (#6352 residual, fix wave 15 P4.6)

garrytan5693e6ef9e78
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index ffc6ca52df..4de9695b6c 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -149,6 +149,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
private nextDelayMs: number | undefined;
private topologyRetryAfter = new Map<string, number>();
private idleLane: { conn: ReservedConnection; release: () => Promise<void> } | undefined;
+ /** #6352 (P4.6): the one lane reservation in flight; concurrent callers await it instead of reserving again. */
+ private idleLanePending: Promise<ReservedConnection | undefined> | undefined;
private idleLaneRetryAt = 0;
/** Phase 4.4: a single write is publishing or admitting on the idle lane's connection. */
private laneInUse = false;
@@ -325,34 +327,45 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
*/
private async acquireIdleLane(signal?: AbortSignal, forPublication = false): Promise<ReservedConnection | undefined> {
if (this.idleLane) return this.idleLane.conn;
- if (this.engine.kind !== 'postgres' || this.stopping || Date.now() < this.idleLaneRetryAt) return undefined;
- const pool = (this.engine as { getPoolDiagnostics?: () => { poolMax: number | null; tracked: Record<string, number> } | null }).getPoolDiagnostics?.();
- // Only reserve from an otherwise idle pool: a saturated pool falls back to a cancellable pooled probe.
- // A single write's publication (Phase 4.4) also reserves it while at least two other connections stay free.
- const inUse = Object.values(pool?.tracked ?? {}).reduce((sum, count) => sum + Math.max(0, count), 0);
- if (!pool?.poolMax || pool.poolMax < 3 || (forPublication ? pool.poolMax - inUse < 3 : inUse > 0)) return undefined;
+ if (!this.idleLanePending) {
+ if (this.engine.kind !== 'postgres' || this.stopping || Date.now() < this.idleLaneRetryAt) return undefined;
+ const pool = (this.engine as { getPoolDiagnostics?: () => { poolMax: number | null; tracked: Record<string, number> } | null }).getPoolDiagnostics?.();
+ // Only reserve from an otherwise idle pool: a saturated pool falls back to a cancellable pooled probe.
+ // A single write's publication (Phase 4.4) also reserves it while at least two other connections stay free.
+ const inUse = Object.values(pool?.tracked ?? {}).reduce((sum, count) => sum + Math.max(0, count), 0);
+ if (!pool?.poolMax || pool.poolMax < 3 || (forPublication ? pool.poolMax - inUse < 3 : inUse > 0)) return undefined;
+ // #6352 (P4.6) single flight: a second caller (the probe beside a single write's publication) joins the one
+ // reservation in flight instead of reserving a second connection nobody would track or release.
+ this.idleLanePending = this.reserveIdleLane().finally(() => { this.idleLanePending = undefined; });
+ }
+ const aborted = Promise.withResolvers<undefined>();
+ const onAbort = () => aborted.resolve(undefined);
+ if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
+ // An aborted caller falls back to a pooled probe; the reservation stays tracked as the lane and is released by
+ // releaseIdleLane (or stop), never left to a resolver nobody holds.
+ try { return await Promise.race([this.idleLanePending, aborted.promise]); }
+ finally { signal?.removeEventListener('abort', onAbort); }
+ }
+ /** Reserves the lane; the lane is tracked the moment the connection arrives, or released at once when the consumer is stopping. */
+ private async reserveIdleLane(): Promise<ReservedConnection | undefined> {
const held = Promise.withResolvers<void>();
const reserved = Promise.withResolvers<ReservedConnection>();
const done = this.engine.withReservedConnection(async conn => { reserved.resolve(conn); await held.promise; }, { route: 'ordinary' })
.catch(error => { reserved.reject(error); });
- const aborted = Promise.withResolvers<undefined>();
- const onAbort = () => aborted.resolve(undefined);
- if (signal?.aborted) onAbort(); else signal?.addEventListener('abort', onAbort, { once: true });
try {
- const conn = await Promise.race([reserved.promise, aborted.promise]);
- if (!conn) {
- reserved.promise.then(() => held.resolve(), () => {});
- return undefined;
- }
- this.idleLane = { conn, release: async () => { held.resolve(); await done; } };
+ const conn = await reserved.promise;
+ const lane = { conn, release: async () => { held.resolve(); await done; } };
+ if (this.stopping) { await lane.release(); return undefined; }
+ this.idleLane = lane;
return conn;
} catch {
this.idleLaneRetryAt = Date.now() + 60_000;
return undefined;
- } finally { signal?.removeEventListener('abort', onAbort); }
+ }
}
private async releaseIdleLane(): Promise<void> {
if (this.laneInUse) return;
+ await this.idleLanePending;
const lane = this.idleLane;
this.idleLane = undefined;
await lane?.release();
diff --git a/test/e2e/consumer-idle-lane-single-flight-postgres.test.ts b/test/e2e/consumer-idle-lane-single-flight-postgres.test.ts
new file mode 100644
index 0000000000..2e84388820
--- /dev/null
+++ b/test/e2e/consumer-idle-lane-single-flight-postgres.test.ts
@@ -0,0 +1,94 @@
+/**
+ * #6352 residual (fix wave 15 P4.6): `acquireIdleLane` had no single-flight guard. Two concurrent first callers (the
+ * idle probe and a single write's `forPublication` acquisition) both reserved a connection; only the last assignment to
+ * `idleLane` was tracked, and the other reservation waited on a resolver nobody held, so a reserved connection and its
+ * long-hold permit leaked until process exit. The consumer now keeps the one reservation in flight and later callers
+ * join it; a caller that aborts falls back to a pooled probe while the lane stays tracked; stop() and an acquisition
+ * failure leave no reservation behind. Postgres only (the lane exists only there); PgBouncer CI runs the same file.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';
+import type { ReservedConnection } from '../../src/core/engine.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { hasDatabase } from './helpers.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-idle-lane-'));
+let engine: PostgresEngine;
+let close: (() => Promise<void>) | undefined;
+
+type LaneSeam = { acquireIdleLane(signal?: AbortSignal, forPublication?: boolean): Promise<ReservedConnection | undefined>; idleLane: unknown; idleLanePending: unknown };
+const reserved = () => engine.getPoolDiagnostics()!.tracked.reserved;
+const consumer = () => new PersistenceConsumer(engine, { engine: 'postgres' }, async () => { throw new Error('no preparation in this test'); }, { hostId: randomUUID() });
+
+describe.skipIf(!hasDatabase())('acquireIdleLane single flight (#6352 residual)', () => {
+ beforeAll(async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!, 'instance', 4);
+ engine = pg.engine; close = pg.close;
+ }, 120_000);
+ afterAll(async () => { await close?.(); rmSync(home, { recursive: true, force: true }); });
+
+ test('two concurrent first callers (probe and publication) share one reservation; stop() releases it', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const c = consumer();
+ const seam = c as unknown as LaneSeam;
+ expect(reserved()).toBe(0);
+ const [probe, publication] = await Promise.all([seam.acquireIdleLane(undefined, false), seam.acquireIdleLane(undefined, true)]);
+ expect(probe).toBeDefined();
+ expect(publication).toBe(probe);
+ expect(reserved()).toBe(1);
+ expect(seam.idleLanePending).toBeUndefined();
+ // A later caller gets the tracked lane without a new reservation.
+ expect(await seam.acquireIdleLane()).toBe(probe);
+ expect(reserved()).toBe(1);
+ await c.stop();
+ expect(reserved()).toBe(0);
+ expect(seam.idleLane).toBeUndefined();
+ }), 60_000);
+
+ test('a caller that aborts while the reservation is in flight falls back, the lane stays tracked for the next caller, and stop() releases it', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const c = consumer();
+ const seam = c as unknown as LaneSeam;
+ const abort = new AbortController();
+ const first = seam.acquireIdleLane(abort.signal, false);
+ abort.abort();
+ expect(await first).toBeUndefined();
+ const next = await seam.acquireIdleLane();
+ expect(next).toBeDefined();
+ expect(reserved()).toBe(1);
+ await c.stop();
+ expect(reserved()).toBe(0);
+ }), 60_000);
+
+ test('stop() during an in-flight reservation releases the connection the moment it arrives', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const c = consumer();
+ const seam = c as unknown as LaneSeam;
+ const pending = seam.acquireIdleLane(undefined, false);
+ const stopped = c.stop();
+ await Promise.all([pending, stopped]);
+ expect(reserved()).toBe(0);
+ expect(seam.idleLane).toBeUndefined();
+ expect(seam.idleLanePending).toBeUndefined();
+ }), 60_000);
+
+ test('an acquisition failure leaves no reservation, no pending flight, and backs the lane off for a minute', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const c = consumer();
+ const seam = c as unknown as LaneSeam & { idleLaneRetryAt: number };
+ const real = engine.withReservedConnection.bind(engine);
+ (engine as { withReservedConnection: unknown }).withReservedConnection = async () => { throw new Error('synthetic reservation failure'); };
+ try {
+ const [a, b] = await Promise.all([seam.acquireIdleLane(undefined, false), seam.acquireIdleLane(undefined, true)]);
+ expect([a, b]).toEqual([undefined, undefined]);
+ } finally { (engine as { withReservedConnection: unknown }).withReservedConnection = real; }
+ expect(reserved()).toBe(0);
+ expect(seam.idleLanePending).toBeUndefined();
+ expect(seam.idleLaneRetryAt).toBeGreaterThan(Date.now() + 50_000);
+ expect(await seam.acquireIdleLane()).toBeUndefined();
+ await c.stop();
+ expect(reserved()).toBe(0);
+ }), 60_000);
+});