Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a pooler client cap is released as contention, not a terminal storage_error; the consumer log names pool_exhausted (GBRA-133 PR 3a)

garrytand87041f4e3f7
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 21b120b367..356097a7f0 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1083,6 +1083,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'A sync pass\'s checkpoint that its pass can no longer publish (the pass ended, or another pass started) is now refused `sync_pass_superseded` instead of `revision_conflict`: it records no managed-sync failure, reads `superseded` in `gbrain sources writer failures` and does not count as an unresolved terminal failure, and a pass that stops with its checkpoint still pending reports `managedWrite.disposition: superseded` instead of "Re-run the same sync options to resume this request".' },
{ since: 'TBD', text: '`gbrain sync status` also reports `last_sync_at` (when the source last converged: every path of its target imported, deleted or held) and `last_committed_at` (when a managed sync write of the source last committed), and the human line says when the source is still importing since it last converged, so a long catch-up no longer reads as a day stale. Its `freshness` block adds `waiting_commits`, the commits on HEAD not synced yet; `unresolved_commits` still counts only synced commits that git cannot date on this host.' },
{ since: 'TBD', text: 'A serve sync pass that stops short now names why on its `[serve-sync] done` line: `stop=<reason>`, the write that stopped it (`write_error`, `write_reason`, `request`), the failed files by code, or `cause=unrecorded` when the pass recorded none, followed by a `next` line with the command to run. Before, a blocked pass printed only `status=blocked_by_failures`.' },
+ { since: 'TBD', text: 'A managed write that meets a pooler\'s client cap (Supavisor `EMAXCONNSESSION` in session mode, "too many clients already") is now released as contention and retried, like SQLSTATE 53300, instead of failing terminally as `storage_error` and stopping the sync drain `blocked_by_failures`. The persistence log names it `reason=pool_exhausted`, with the pool-sizing fix in place of the generic writer-status pointer.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 605d2ffa27..124f75df86 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,7 +1,7 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues, independentGroup, sweepSegmentStorage, yieldToEventLoop } from './journal.ts';
-import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';
+import { connectionCapFailure, finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';
import { preparationConfigView } from './config-snapshot.ts';
@@ -872,7 +872,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
return;
}
const code = (error as { code?: unknown })?.code;
- this.lastError = { code: typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),
+ // GBRA-133: a pooler's client cap names itself (and its fix) instead of the pooler's generic code.
+ this.lastError = { code: connectionCapFailure(error) ? 'pool_exhausted' : typeof code === 'string' && (/^[A-Z0-9]{5}$/.test(code) || isWriteErrorCode(code)) ? code : 'storage_error', at: new Date().toISOString(),
...(this.lastPhaseError ? { phase: this.lastPhaseError } : {}) };
if (this.opts.onError) this.opts.onError(error);
else this.log(this.lastPhaseError ?? 'execution', this.lastError.code, errorDetail(error), this.lastPhaseError ? this.lastPhaseTiming : undefined, row);
@@ -893,7 +894,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
this.lastLog = { key, at };
}
if (!this.opts.onError) process.stderr.write(`[persistence] phase=${phase} reason=${code}${detail ? ` message="${detail}"` : ''}${timing}${row ? requestLogFields(row) : ''}`
- + '; unfinished work remains tracked; fix: gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log\n');
+ + `; unfinished work remains tracked; fix: ${code === 'pool_exhausted' ? 'every gbrain process on this database shares the pooler\'s client limit: run fewer long-running processes (share one gbrain serve --http) or raise the limit; docs: docs/ENGINES.md#pool-sizing'
+ : 'gbrain sources writer status --json; docs: docs/ENGINES.md#persistence-consumer-log'}\n`);
}
/** #5373: tracks work that outlived its claim until it settles; the returned promise never rejects. */
/**
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index b51ae26ef3..875ef6adaf 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -52,6 +52,7 @@ import { recordPublicationFenceTrend } from '../fence-repair/census-store.ts';
import { segmentWriteScope } from '../page-body/ingest.ts';
import { publicationBeliefOptions, withBeliefBatch } from '../belief/ledger.ts';
import { markBeliefCommits } from '../belief/append.ts';
+import { classifyPgAccessError } from '../pg-access-classify.ts';
interface PreparedMutationBase {
sourceExclusive?: boolean;
@@ -218,7 +219,14 @@ function conflictCode(code: string): boolean { return ['revision_required','revi
function failureState(code: string): 'conflict' | 'failed' | 'cancelled' { return code === 'admission_paused' ? 'cancelled' : conflictCode(code) ? 'conflict' : 'failed'; }
export function transientDatabaseFailure(error: unknown): boolean {
return ['40001','40P01','55P03','57014','53300','57P01','57P02','57P03','08000','08003','08006','08001','08004',
- 'ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code));
+ 'ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code)) || connectionCapFailure(error);
+}
+/**
+ * GBRA-133: a pooler's client cap (Supavisor `EMAXCONNSESSION`, "too many clients already") is the same contention as
+ * SQLSTATE 53300 whatever code the pooler sends with it, so a write that meets it is released, never failed terminally.
+ */
+export function connectionCapFailure(error: unknown): boolean {
+ return classifyPgAccessError(error).reason === 'pool_exhausted';
}
/**
* Flip lane C: the shared-read failures (`sharedReadFailure`) already charged. A group's memoized read the database cancelled
diff --git a/test/connection-cap-transient-gbra133.test.ts b/test/connection-cap-transient-gbra133.test.ts
new file mode 100644
index 0000000000..b209730fe8
--- /dev/null
+++ b/test/connection-cap-transient-gbra133.test.ts
@@ -0,0 +1,29 @@
+/**
+ * GBRA-133: a pooler's client cap is contention, not a failed write.
+ * Supavisor answers a session-mode client over its cap with `(EMAXCONNSESSION) max clients reached in session mode` under its
+ * own error code, not SQLSTATE 53300, so a managed write that met it was failed terminally (storage_error) and the sync drain
+ * stopped blocked_by_failures. It is released like 53300 now; a write's own errors still fail.
+ */
+import { expect, test } from 'bun:test';
+import { connectionCapFailure, transientDatabaseFailure } from '../src/core/persistence/coordinator.ts';
+
+const poolerError = (message: string, code: string) => Object.assign(new Error(message), { code });
+
+test('a pooler client cap under any code is transient contention', () => {
+ const capped = [
+ poolerError('(EMAXCONNSESSION) max clients reached in session mode - max clients are limited to pool_size: 25', 'XX000'),
+ poolerError('sorry, too many clients already', '53300'),
+ poolerError('remaining connection slots are reserved for non-replication superuser connections', '53300'),
+ ];
+ for (const error of capped) {
+ expect(connectionCapFailure(error)).toBe(true);
+ expect(transientDatabaseFailure(error)).toBe(true);
+ }
+});
+
+test("a write's own error is not a connection cap", () => {
+ for (const error of [poolerError('duplicate key value violates unique constraint', '23505'), poolerError('internal error', 'XX000'), new Error('boom')]) {
+ expect(connectionCapFailure(error)).toBe(false);
+ expect(transientDatabaseFailure(error)).toBe(false);
+ }
+});