Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a one-shot command's consumer takes the direct route; admission contention is retryable contention

garrytan1b008df8e26b
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 7792afac66..5f45cb296d 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3907,7 +3907,11 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Reading or writing durable storage failed. | Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path. | For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json. | host_admin | `gbrain doctor --json` | 1 | no |
+| Reading or writing durable storage failed. | Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `reason: database_contention`: a write admission that deadlocks, serialization failures, lock timeouts or statement timeouts kept refusing for its whole retry budget; no receipt was confirmed, so the same request_id is safe to retry once the contention clears. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path. | For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json. | host_admin | `gbrain doctor --json` | 1 | no |
+
+Reasons: `database_contention`.
+
+Override: reason `database_contention`: retryable, exit 1, retryable.
### sync_admission_restricted
diff --git a/src/core/direct-pool-profile.ts b/src/core/direct-pool-profile.ts
index a732ad525e..dbc091537e 100644
--- a/src/core/direct-pool-profile.ts
+++ b/src/core/direct-pool-profile.ts
@@ -5,7 +5,8 @@
* - short_lived: a command that owns a consumer or takes a lease gets one connection.
* - one_shot: a command that takes no lease routes nothing through the direct
* pool; schema DDL still uses one connection for its session advisory lock
- * and long statement timeout. Taking a lease makes it short_lived.
+ * and long statement timeout. Taking a lease or starting a persistence
+ * consumer makes it short_lived.
* GBRAIN_DIRECT_POOL_BY_COMMAND=0 restores the earlier behavior: resident everywhere.
*
* No imports: db-lock.ts reads this on PGLite too.
@@ -27,7 +28,7 @@ export function setDirectPoolProfile(profile: DirectPoolProfile): void {
processProfile = profile;
}
-/** A one-shot command that takes a lease renews it on the direct lane, so it becomes short-lived. */
+/** A one-shot command that takes a lease or starts a persistence consumer runs them on the direct lane, so it becomes short-lived. */
export function noteDirectPoolLease(): void {
if (processProfile === 'one_shot') processProfile = 'short_lived';
}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 5daa31a51a..dafb03de66 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -651,7 +651,8 @@ export const CODES = {
stale_unavailable: { class: 'unavailable', summary: "No complete, current authorized shared-skills view is available; cached shared skills stay unused.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },
state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },
storage_error: { class: 'server', summary: "Reading or writing durable storage failed.",
- why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",
+ reasons: ['database_contention'], reason_overrides: { database_contention: { class: 'retryable' } },
+ why: "Usually a dropped connection or a failed statement; the same error after a rerun is not transient. `reason: database_contention`: a write admission that deadlocks, serialization failures, lock timeouts or statement timeouts kept refusing for its whole retry budget; no receipt was confirmed, so the same request_id is safe to retry once the contention clears. `detail: persistence_mode_unknown` (#6482): the persistence_brain singleton is missing, duplicated or carries a non-boolean `enabled`, so gbrain cannot tell whether the brain is managed and refuses every write, sync, connector run and activation step that depends on it rather than route a managed brain through the unmanaged writer; only a well-formed `enabled: false` row selects the unmanaged path.",
suggestion: 'For persistence_mode_unknown: run gbrain sources writer status --probe --json on the brain host (it reports the malformed state instead of refusing), fix the persistence_brain row it names, then gbrain doctor --json.' },
sync_not_applicable: { class: 'caller', summary: "Sync does not apply to this source: its directory is not a Git checkout.", why: "Sync imports changes between Git commits. A gbrain-owned content directory (created by init) holds files gbrain manages itself and is not a Git repository, so there is nothing to sync; gbrain never initializes Git on its own.", reasons: ['content_directory'] },
// #6712 PR 1: the drain lease (src/core/persistence/sync-lease.ts).
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index 1a4dff618d..f38a6cf45e 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -121,7 +121,8 @@ function classifyOne(error: unknown): ClassifiedItemFailure | null {
if (error instanceof OperationError) {
const code = String(error.code === 'storage_error' && error.writeError ? error.writeError : error.canonicalCode);
const requestId = error.writeRequest?.request_id ?? null;
- if (RUN_SCOPED_CODES.has(code) || (code === 'storage_error' && error.detail === 'database_contention')) {
+ if (code === 'storage_error' && error.detail === 'database_contention') return { code: 'database_contention', scope: 'run', class: 'transient', message, requestId };
+ if (RUN_SCOPED_CODES.has(code)) {
return { code, scope: 'run', class: 'transient', message, requestId };
}
const registryClass = (CODES as Record<string, { class: string }>)[code]?.class;
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index 1e3e94e0a0..5f8f2c1fe9 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -56,6 +56,7 @@ export async function retryWriteAdmission<T>(requestId: string, attempt: (remain
`Retry the same operation, arguments, and request_id ${requestId}. No queued receipt has been confirmed.`);
unavailable.writeError = 'storage_error';
unavailable.detail = 'database_contention';
+ unavailable.reason = 'database_contention';
throw unavailable;
}
// The transaction has rolled back and released its connection before any
diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.ts
index b986685eb1..9e5bdd213f 100644
--- a/src/core/persistence/service.ts
+++ b/src/core/persistence/service.ts
@@ -7,6 +7,7 @@ import { WaiterOnlyConsumer, type ElectedOwner } from './consumer-election.ts';
import { RESIDENT_CONSUMER_KINDS, startConsumerHeartbeat, type ConsumerHeartbeat } from './consumer-heartbeat.ts';
import { enginePoolStats } from '../postgres-engine/pool-stats.ts';
import { claimOwnerKind, isOneShotCommand } from './claim-phase.ts';
+import { noteDirectPoolLease } from '../direct-pool-profile.ts';
import { preparePageMutation } from './page-prepare.ts';
import { prepareSemanticPageMutation } from './semantic-pages.ts';
import { getWriteRequestById, getWriteRequestProgress, receiptFor, type WriteRequestProgress } from './journal.ts';
@@ -123,6 +124,7 @@ export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConf
}
return prior.consumer;
}
+ noteDirectPoolLease();
const kind = claimOwnerKind();
const oneShot = isOneShotCommand() && kind !== 'serve' && !RESIDENT_CONSUMER_KINDS.includes(kind) ? { waiting: () => (settledWaiters.get(engine)?.size ?? 0) > 0 } : undefined;
const full = () => new PersistenceConsumer(engine, config, preparePersistedMutation,
diff --git a/test/oneshot-consumer-direct-route.test.ts b/test/oneshot-consumer-direct-route.test.ts
new file mode 100644
index 0000000000..26d7b3cfb4
--- /dev/null
+++ b/test/oneshot-consumer-direct-route.test.ts
@@ -0,0 +1,98 @@
+/**
+ * A one-shot command that starts a persistence consumer (`gbrain repair <kind> --apply`, `gbrain cli`, ...) takes the
+ * direct route when one is configured. Since the direct pool follows the command (#7312), a one-shot process routed
+ * nothing direct until it took a lease, so a consumer it started ran its claims and scans through the transaction-mode
+ * pooler even with GBRAIN_DIRECT_DATABASE_URL set, and printed the `reason=transaction_pooler` line. Starting a consumer
+ * now makes the process short-lived (one direct connection), as taking a lease does.
+ *
+ * And a write admission that database contention kept blocking (`storage_error`, detail `database_contention`) is
+ * contention, not a storage fault: the item classifier names it `database_contention`, so a repair apply stops with
+ * the resume command instead of failing the item, and the error envelope reads retryable.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { codeRetryable } from '../src/core/error-catalogue.ts';
+import { directPoolProfile, setDirectPoolProfile } from '../src/core/direct-pool-profile.ts';
+import { classifyItemFailure } from '../src/core/item-failure.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';
+import { consumerConnectionRoute, consumerStatementEngine } from '../src/core/persistence/consumer-lane.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const ROUTE = { GBRAIN_DIRECT_POOL_SIZE: undefined, GBRAIN_DIRECT_POOL_BY_COMMAND: undefined, GBRAIN_DISABLE_DIRECT_POOL: undefined, GBRAIN_CONSUMER_DIRECT_LANE: undefined };
+
+afterEach(() => setDirectPoolProfile('resident'));
+
+describe('a one-shot command that starts a persistence consumer', () => {
+ let pglite: PGLiteEngine | null = null;
+ beforeAll(async () => {
+ if (!testBackends().includes('pglite')) return;
+ pglite = new PGLiteEngine();
+ await pglite.connect({ database_url: '' });
+ await pglite.initSchema();
+ }, 60_000);
+ afterAll(async () => { if (pglite) { await disposePersistenceConsumer(pglite); await pglite.disconnect(); } });
+
+ test('becomes short-lived', async () => {
+ if (!pglite) return;
+ setDirectPoolProfile('one_shot');
+ startPersistenceConsumer(pglite, { engine: 'pglite', embedding_disabled: true } as never);
+ expect(directPoolProfile()).toBe('short_lived');
+ });
+
+ if (testBackends().includes('postgres')) {
+ test('postgres with a transaction-pooler URL and GBRAIN_DIRECT_DATABASE_URL: the consumer runs on the direct route', async () => {
+ const brain = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const engine = new PostgresEngine();
+ const pooler = new URL(brain.databaseUrl);
+ pooler.searchParams.set('prepare', 'false');
+ const lines: string[] = [];
+ const write = process.stderr.write.bind(process.stderr);
+ try {
+ await withEnv({ ...ROUTE, GBRAIN_DIRECT_DATABASE_URL: brain.databaseUrl }, async () => {
+ setDirectPoolProfile('one_shot');
+ await engine.connect({ database_url: pooler.toString(), poolSize: 2 });
+ expect(consumerConnectionRoute(engine)).toMatchObject({ lane: 'pool', pooler_mode: 'transaction' });
+ process.stderr.write = ((chunk: string | Uint8Array) => { lines.push(String(chunk)); return true; }) as typeof process.stderr.write;
+ try { startPersistenceConsumer(engine, { engine: 'postgres', embedding_disabled: true } as never); }
+ finally { process.stderr.write = write; }
+ expect(consumerConnectionRoute(engine)).toMatchObject({ lane: 'direct', pooler_mode: 'transaction' });
+ expect(lines.join('')).not.toContain('reason=transaction_pooler');
+ const timeout = await consumerStatementEngine(engine).executeRaw<{ statement_timeout: string }>('SHOW statement_timeout');
+ expect(timeout[0]!.statement_timeout).toBe('30min');
+ });
+ } finally {
+ process.stderr.write = write;
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+ await brain.close();
+ }
+ }, 120_000);
+ }
+});
+
+describe('write admission blocked by database contention', () => {
+ async function admissionContention(): Promise<OperationError> {
+ const error = await retryWriteAdmission('req-example', async () => { throw Object.assign(new Error('deadlock detected'), { code: '40P01' }); }, 30)
+ .then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ return error as OperationError;
+ }
+
+ test('is classified as database_contention for the run, not a storage fault', async () => {
+ const error = await admissionContention();
+ expect(error).toMatchObject({ code: 'storage_error', detail: 'database_contention' });
+ expect(classifyItemFailure(error)).toMatchObject({ code: 'database_contention', scope: 'run', class: 'transient' });
+ });
+
+ test('reads retryable', async () => {
+ const error = await admissionContention();
+ expect(error.reason).toBe('database_contention');
+ expect(codeRetryable(error.code, error.reason)).toBe(true);
+ expect(codeRetryable('storage_error')).toBe(false);
+ });
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 1dfa5e1c4c..c894dc01af 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -234,6 +234,7 @@ test/managed-sync-stale-group-head.test.ts
test/migration-persistence-request-id-index.test.ts
test/migration-persistence-request-slug-index.test.ts
test/on-commit-embedding.serial.test.ts
+test/oneshot-consumer-direct-route.test.ts
test/oneshot-housekeeping-cli.test.ts
test/origin-guard-6948.test.ts
test/origin-twin-sequence-7150.test.ts