Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(repair): only the CLI apply records a database refusal as a stop; the cycle and remediation keep the rethrow

garrytan4c5245618035
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 954eee5b65..b4ba7100c2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,9 +31,9 @@ identifiers and attribution are available in the pre-removal Git revision
- `src/core/persistence/sync-origin-evidence.ts`: `readDeletionProvenance` reads HEAD's full history in bounded batches (a side branch's own deleting commit first; a merge only when its resolution dropped the file).
- `src/core/repair/file-drift.ts`: per-page `provenance` and `details.provenance` counts; `--provenance` filter (`residuals.other_provenance`); the database-only keep (`managed_maintenance_file_drift_detach`, a database maintenance request whose preparer re-checks the page and its provenance and clears the hold).
-- `src/core/repair/core.ts`: database refusals and the CLI's termination signal stop an apply with a result; `src/commands/repair.ts` owns SIGTERM/SIGHUP during an apply.
+- `src/core/repair/core.ts`: database refusals (`recordDatabaseStops`, set by the CLI; the cycle and doctor remediation keep the rethrow their own stops rely on) and the CLI's termination signal stop an apply with a result; `src/commands/repair.ts` owns SIGTERM/SIGHUP during an apply.
- `docs/guides/repair.md` (provenance), `docs/ENGINES.md#pool-sizing` (sync workers and a derived direct route in the pooler sum).
-- Tests: `test/repair-file-drift-provenance-gbra133.test.ts`, `test/repair-database-stop-gbra133.test.ts` (PGLite and Postgres); `test/repair-apply-continue-6459.test.ts` now pins the stop-with-result contract for a lost connection.
+- Tests: `test/repair-file-drift-provenance-gbra133.test.ts`, `test/repair-database-stop-gbra133.test.ts` (PGLite and Postgres).
## [0.60.355.0] - 2026-10-21
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index edca031da9..3179abb5e3 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -437,7 +437,7 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
...(k === kind && keep ? { keep } : {}), ...(k === kind && requestId ? { requestId } : {}),
...(k === kind && k === 'receipt-compaction' ? { olderThan, includeFailures, force } : {}),
...(k === kind && k === 'rename-identity' ? { from, close } : {}), ...(k === kind && afterPage !== undefined ? { afterPage } : {}),
- ...(apply ? { stop: stop.signal } : {}) })).finally(() => releaseSignals?.());
+ ...(apply ? { stop: stop.signal, recordDatabaseStops: true } : {}) })).finally(() => releaseSignals?.());
if (apply) clearHealthMemo(engine);
const paidKinds = results.filter(r => r.paid).map(r => r.kind);
if (json) {
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 12b6890bdb..3bb0d36fac 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -322,6 +322,8 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
spec?: Pick<RepairKindSpec, 'explicit_only' | 'consent' | 'spends'>; maxLlmUsd?: number; deadline?: number; now?: () => number;
/** GBRA-133: the CLI's termination signal; the apply stops before the next item with a result instead of dying mid-run. */
stop?: AbortSignal;
+ /** GBRA-133: the CLI's apply records a database refusal as a stop with a result; other callers (cycle, remediation) keep the rethrow. */
+ recordDatabaseStops?: boolean;
/** Test seam: who publishes this run's admissions (default: this process's consumer, else a live full one on this host). */
publicationOwner?: () => Promise<{ alive: boolean; owner: string }> }): Promise<RepairResult> {
// #6696 (A5): an approved local repair is the operator's own write; a maintenance cycle's background scope still wins.
@@ -516,8 +518,8 @@ async function runRepairScoped(ctx: OperationContext, handler: RepairHandler, sc
}
// GBRA-133: a deadlock, a serialization failure or a lost database connection stops the run with what it applied and
// the resume command in the result (the cursor stays before this item), instead of ending the command with no record.
- const database = classifyItemFailure(error);
- if (database.scope === 'run' && (database.code === 'database_contention' || database.code === 'connection_lost')) {
+ const database = opts.recordDatabaseStops ? classifyItemFailure(error) : null;
+ if (database && database.scope === 'run' && (database.code === 'database_contention' || database.code === 'connection_lost')) {
const sqlstate = (error as { code?: unknown } | null)?.code;
return stopAfterSettle({ reason: database.code, message: redactConnectionInfo(`Stopped at ${item.source_id}:${item.slug}: the database refused this item`
+ `${typeof sqlstate === 'string' ? ` (${sqlstate})` : ''}: ${database.message.slice(0, 300)}. The items before it stay applied `
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index ce944b07b7..e2c1263869 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -585,7 +585,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
* `maxLlmUsd`: what this run may spend on a paid chat model (`spends: 'llm'` kinds; undefined = no run cap).
*/
async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean; only?: string[]; skip?: string[];
- slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal;
+ slugs?: string[]; noLlm?: boolean; maxLlmUsd?: number; deadline?: number; stop?: AbortSignal; recordDatabaseStops?: boolean;
prefer?: 'file' | 'database'; requests?: string[]; allDrifted?: boolean; driftClass?: string; since?: string; held?: boolean; side?: string; state?: string; provenance?: string; cursor?: string; progress?: ProgressReporter;
keep?: 'prior' | 'disk' | 'withdrawn'; requestId?: string; olderThan?: string; includeFailures?: boolean; force?: boolean; from?: string; close?: boolean; afterPage?: number } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0], writeWaitMs } as OperationContext;
@@ -595,7 +595,7 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
...(run.olderThan ? ['--older-than', run.olderThan] : []), ...(run.includeFailures ? ['--include-failures'] : []), ...(run.force ? ['--force'] : []),
...(run.afterPage !== undefined ? ['--after', String(run.afterPage)] : [])],
explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous, only: run.only, skip: run.skip, slugs: run.slugs, noLlm: run.noLlm,
- maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
+ maxLlmUsd: run.maxLlmUsd, deadline: run.deadline, ...(run.stop ? { stop: run.stop } : {}), ...(run.recordDatabaseStops ? { recordDatabaseStops: true } : {}), prefer: run.prefer, requests: run.requests, allDrifted: run.allDrifted, driftClass: run.driftClass, since: run.since,
held: run.held, side: run.side, state: run.state, provenance: run.provenance, cursor: run.cursor, progress: run.progress, keep: run.keep, requestId: run.requestId, olderThan: run.olderThan, includeFailures: run.includeFailures, force: run.force, from: run.from, close: run.close, afterPage: run.afterPage });
},
};
diff --git a/test/repair-apply-continue-6459.test.ts b/test/repair-apply-continue-6459.test.ts
index 2043597484..45d47b1f75 100644
--- a/test/repair-apply-continue-6459.test.ts
+++ b/test/repair-apply-continue-6459.test.ts
@@ -142,7 +142,7 @@ describe('repair --apply continues past a per-item invalid_params / source_chang
expect(stub.store.get(1)).toBe('repaired item 1');
});
- test('other refusals still stop the run as before (write_pending stops; a lost connection stops with a result, GBRA-133; an unexpected error is one item\'s failure, GBRA-130)', async () => {
+ test('other refusals still stop the run as before (write_pending stops; a lost connection rethrows; an unexpected error is one item\'s failure, GBRA-130)', async () => {
const stub = stubKind('timeline', 3, {});
stub.handler.apply = async (_c, it) => {
stub.attempts.push(it.cursor.id);
@@ -161,10 +161,7 @@ describe('repair --apply continues past a per-item invalid_params / source_chang
await resetPgliteState(engine);
const lost = stubKind('timeline', 3, {});
lost.handler.apply = async (_c, it) => { if (it.cursor.id === 0) throw Object.assign(new Error('Connection terminated unexpectedly'), { code: '08006' }); return { applied: true, outcome: 'repaired' }; };
- // GBRA-133: the run stops at the refused item with a result (reason, SQLSTATE, resume command) instead of rethrowing.
- const dropped = await runRepair(ctx(), lost.handler, await resolveRepairScope(engine), { apply: true, spec: lost.spec });
- expect(dropped).toMatchObject({ applied: 0, failed: [], complete: false, stopped: { reason: 'database_contention' } });
- expect(dropped.stopped!.message).toContain('(08006): Connection terminated unexpectedly');
+ await expect(runRepair(ctx(), lost.handler, await resolveRepairScope(engine), { apply: true, spec: lost.spec })).rejects.toThrow('Connection terminated');
});
test('the human output counts the failures, names the slug and the full-scan command; the command exits 1', async () => {
diff --git a/test/repair-database-stop-gbra133.test.ts b/test/repair-database-stop-gbra133.test.ts
index 89947d1157..049aad19e5 100644
--- a/test/repair-database-stop-gbra133.test.ts
+++ b/test/repair-database-stop-gbra133.test.ts
@@ -2,7 +2,8 @@
* GBRA-133: a repair apply that the database refuses mid-run (a deadlock, a serialization failure, a lost connection) stops
* with a result: what it applied, the stop reason with the SQLSTATE, and the resume command; the cursor stays before the
* refused item, so the same command resumes there. Before, the error ended the command and an `--apply --json` run left
- * no record of what it had applied. A termination signal (the CLI's SIGTERM or SIGHUP) stops the apply the same way before
+ * no record of what it had applied. The CLI's apply opts in (`recordDatabaseStops`); the cycle and doctor remediation keep
+ * the rethrow, which their own run-scoped stops rely on (pinned by the default case below). A termination signal (the CLI's SIGTERM or SIGHUP) stops the apply the same way before
* its next item. Real PGLite (and Postgres when DATABASE_URL is set) for the cursor; a stub kind.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
@@ -49,7 +50,7 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a databas
await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");
const { handler, applied } = stub(new Map([[2, error]]));
const scope = await resolveRepairScope(engine);
- const first = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true });
+ const first = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true, recordDatabaseStops: true });
expect(applied).toEqual([1]);
expect(first.applied).toBe(1);
expect(first.complete).toBe(false);
@@ -58,12 +59,18 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a databas
if (error.code !== 'CONNECTION_CLOSED') expect(first.stopped!.message).toContain(`(${error.code})`);
expect(first.stopped!.message).toContain(`Rerun \`${first.apply_command}\` to resume from this item.`);
expect(first.stopped!.fix?.argv).toEqual(['gbrain', 'repair', 'gbra133-stub', '--json']);
- const second = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true });
+ const second = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true, recordDatabaseStops: true });
expect(applied).toEqual([1, 2, 3]);
expect(second).toMatchObject({ applied: 2, complete: true, resumed_from: { phase: 0, id: 1 } });
expect(second.stopped).toBeUndefined();
}, 60_000);
+ test('without the CLI opt-in a run-scoped database error still rethrows (cycle and remediation callers)', async () => {
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");
+ const { handler } = stub(new Map([[2, Object.assign(new Error('deadlock detected'), { code: '40P01' })]]));
+ await expect(runRepair(ctx(), handler, await resolveRepairScope(engine), { apply: true, expect: 'stub-hash', explicit: true })).rejects.toThrow('deadlock detected');
+ }, 60_000);
+
test('a termination signal stops the apply before its next item with a result, and the same command resumes', async () => {
await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair'");
const stop = new AbortController();
@@ -75,7 +82,7 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: a databas
expect(applied).toEqual([1]);
expect(first).toMatchObject({ applied: 1, complete: false, stopped: { reason: 'interrupted' } });
expect(first.stopped!.message).toBe(`Stopped before default:notes/p2: this process received SIGTERM (2 item(s) still pending; the items before it stay applied). Rerun \`${first.apply_command}\` to resume.`);
- const second = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true });
+ const second = await runRepair(ctx(), handler, scope, { apply: true, expect: 'stub-hash', explicit: true, recordDatabaseStops: true });
expect(applied).toEqual([1, 2, 3]);
expect(second).toMatchObject({ applied: 2, complete: true });
}, 60_000);