Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a committed connector retry resolves the refusal it replaced (#6824)
time-attack293538c18bae
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 0bce6ff77f..17f55ea803 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -911,6 +911,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', id: 'auth_rescope_client_print_only', text: '`gbrain auth rescope --client <id>` (and `gbrain auth rescope-client <id>`) with no grant flag and no `--profile` now prints the client\'s stored grants and writes nothing (`--json`: `changed: false`, `written: false`), as the help always said, instead of refusing with `invalid_grant`. An unknown client id refuses with `client_not_found`, whose fix is `gbrain auth clients --json`. `--repair` alone still refuses.' },{ since: '0.60.307.0', id: 'file_drift_unknown_listed', text: '`gbrain repair file-drift --all-drifted` previews and the bare `gbrain repair file-drift` survey now list a conflicted page the live check cannot classify (canonical file missing, page gone, not the owner host, a refused or failed check) as `unknown`, counted under `unknown_<reason>` with the next step for that reason. They used to drop it silently, so a preview could read as empty. Unknown pages are never repaired and get no `--class` preview command.' },{ since: '0.60.307.0', id: 'source_lifecycle_dry_run_physical_root', text: 'On a managed brain, `gbrain sources remove --dry-run` and `gbrain sources set-path --dry-run` now run the read-only physical-root check their real runs make, so a checkout deleted and recreated at its recorded path refuses the dry run with `recovery_required` (detail `physical_root_directory_changed`, naming the relocated-root self-transfer) instead of exiting 0 and then refusing the real command. The dry run still writes nothing.' },+ { since: '0.60.307.0', id: 'connector_retry_supersedes_refusal', text: 'A refused managed connector write (kinds `connector_v2_import`, `connector_v2_delete`, `connector_v2_checkpoint`) that a later connector retry replaced and committed now counts as resolved (`disposition: superseded`) in doctor `persistence_terminal_failures`, `gbrain sources writer failures` and `gbrain sync status`, instead of staying unresolved forever. Only a retry whose recorded `retryOf` chain reaches the refusal (same principal, source incarnation, operation, slug and kind, at most 32 hops) counts; a sibling refusal with no link stays unresolved. The receipts themselves are kept.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex 9602dcd357..60ead2ad4b 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -368,8 +368,9 @@ export const PAGE_REMOVAL_OPERATIONS: readonly string[] = ['delete_page', 'purge* failed request `r` (both `persistence_requests` aliases): the same intent committed, failed or still pending; a later* page removal committed or pending; for a `put_page`, any later write committed or pending, or a later caller* `put_page` that failed (the newer content); #6834: for a refused sync checkpoint, any later committed checkpoint of the- * source (both read by kind; a compacted row, which keeps no kind, by its operation). `r` must expose `id`.- * Literal strings only; NULL-safe for a compacted `c` (no intent).+ * source (both read by kind; a compacted row, which keeps no kind, by its operation); #6824: for a refused connector+ * write, a later committed connector retry whose recorded `retryOf` lineage reaches it (connectorRetrySql). `r` must+ * expose `id`. Literal strings only; NULL-safe for a compacted `c` (no intent).*/export function supersessionSql(r: string, c: string): string {const removals = PAGE_REMOVAL_OPERATIONS.map(op => `'${op}'`).join(',');@@ -379,7 +380,36 @@ export function supersessionSql(r: string, c: string): string {OR (${r}.slug='__managed_sync_checkpoint__' AND ${r}.operation='submit_job' AND ${c}.state='committed' AND ${c}.operation='submit_job'AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=${r}.id),'managed_sync_checkpoint')='managed_sync_checkpoint'AND COALESCE(${c}.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint')- OR (${r}.operation='put_page' AND ${c}.state='failed' AND ${c}.operation='put_page' AND COALESCE(NOT (${c}.intent ? 'kind'), false))))`;+ OR (${r}.operation='put_page' AND ${c}.state='failed' AND ${c}.operation='put_page' AND COALESCE(NOT (${c}.intent ? 'kind'), false))+ OR ${connectorRetrySql(r, c)}))`;+}++/** Hops a connector retry's `retryOf` lineage is followed back; a longer chain leaves the refusal unresolved (fail closed). */+export const CONNECTOR_RETRY_LINEAGE_MAX_DEPTH = 32;+const CONNECTOR_WRITE_KINDS = `'connector_v2_import','connector_v2_delete','connector_v2_checkpoint'`;+const UUID_TEXT = `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'`;++/**+ * #6824: a connector retry records `retryBase`/`retryOf`/`retryAttempt` in its intent, so its digest never equals the+ * refusal it replaces. A committed retry `c` supersedes the refused `r` (read whole as `k`) only when every hop of its+ * recorded `retryOf` chain, back to `r`, has the same principal, source and incarnation, operation, slug and connector+ * intent kind, at a lower sequence, within CONNECTOR_RETRY_LINEAGE_MAX_DEPTH hops. Another refusal of the same item with+ * no recorded link is not proof. Each hop is one lookup on the (principal_kind, principal_id, request_id) unique index.+ */+function connectorRetrySql(r: string, c: string): string {+ return `(${r}.operation='submit_job' AND ${c}.operation='submit_job' AND ${c}.state='committed' AND COALESCE(${c}.intent ? 'retryOf', false)+ AND EXISTS (SELECT 1 FROM persistence_requests k WHERE k.id=${r}.id AND k.intent->>'kind' IN (${CONNECTOR_WRITE_KINDS})+ AND ${c}.intent->>'kind'=k.intent->>'kind' AND ${c}.principal_kind=k.principal_kind AND ${c}.principal_id=k.principal_id+ AND ${c}.source_incarnation=k.source_incarnation+ AND EXISTS (WITH RECURSIVE lineage(request_id, sequence, intent, depth) AS (+ SELECT ${c}.request_id, ${c}.sequence, ${c}.intent, 0+ UNION ALL+ SELECT p.request_id, p.sequence, p.intent, l.depth+1 FROM lineage l JOIN persistence_requests p+ ON p.principal_kind=k.principal_kind AND p.principal_id=k.principal_id+ AND p.request_id=CASE WHEN l.intent->>'retryOf' ~ ${UUID_TEXT} THEN (l.intent->>'retryOf')::uuid END+ WHERE l.depth<${CONNECTOR_RETRY_LINEAGE_MAX_DEPTH} AND p.sequence<l.sequence AND p.source_id=k.source_id+ AND p.source_incarnation=k.source_incarnation AND p.operation=k.operation AND p.slug=k.slug AND p.intent->>'kind'=k.intent->>'kind')+ SELECT 1 FROM lineage WHERE request_id=k.request_id)))`;}/** The order that picks the most telling superseding request: the same intent committed, then the same intent, then the oldest later write. */diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.tsindex ba476a4770..c2d32cd995 100644--- a/test/terminal-failures-6650.test.ts+++ b/test/terminal-failures-6650.test.ts@@ -14,7 +14,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:tesimport { randomUUID } from 'node:crypto';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import type { BrainEngine } from '../src/core/engine.ts';-import { classifyTerminal, terminalKnockOnSql, supersessionSql, type TerminalInput } from '../src/core/persistence/terminal-classify.ts';+import { classifyTerminal, CONNECTOR_RETRY_LINEAGE_MAX_DEPTH, terminalKnockOnSql, supersessionSql, type TerminalInput } from '../src/core/persistence/terminal-classify.ts';import { isSyncKnockOn, knockOnDetail } from '../src/core/persistence/sync-knock-on.ts';import { WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';import { readTerminalFailureSummary, readTerminalFailures, readTerminalThresholds, sevenDayMedian, validateTerminalConfigValue, TERMINAL_HISTORICAL_SQL,@@ -88,7 +88,7 @@ describe('classifyTerminal', () => {const SOURCE = 'tf-a';const OTHER = 'tf-archived';async function seed(o: { source?: string; slug: string; operation?: string; state: string; code?: string | null; message?: string | null; detail?: unknown; recovery?: unknown;- compacted?: boolean; digest?: string; hoursAgo?: number; build?: string; kind?: string; blocked?: string }): Promise<string> {+ compacted?: boolean; digest?: string; hoursAgo?: number; build?: string; kind?: string; blocked?: string; intent?: object }): Promise<string> {const requestId = randomUUID();await engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent_bytes,terminal_reservation,state,error_code,error_message,error_detail,recovery,compacted,intent,completed_at,updated_at,admitter_version,blocked_reason)@@ -96,7 +96,7 @@ async function seed(o: { source?: string; slug: string; operation?: string; statnow()-($13::double precision*interval '1 hour'),now()-($13::double precision*interval '1 hour'),$14,$15)`,[requestId, o.operation ?? 'put_page', o.source ?? SOURCE, o.slug, o.digest ?? randomUUID(), o.state, o.code ?? null, o.compacted ? null : o.message ?? null,o.detail === undefined ? null : JSON.stringify(o.detail), o.recovery === undefined ? null : JSON.stringify(o.recovery), o.compacted === true,- o.compacted ? null : JSON.stringify(o.kind ? { kind: o.kind } : { content: 'x' }), o.hoursAgo ?? 1, o.build ?? '0.60.216.0', o.blocked ?? null]);+ o.compacted ? null : JSON.stringify(o.intent ?? (o.kind ? { kind: o.kind } : { content: 'x' })), o.hoursAgo ?? 1, o.build ?? '0.60.216.0', o.blocked ?? null]);return requestId;}@@ -173,6 +173,87 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drillexpect(defect.message).toContain('owner_exception/storage_error ×1');});+ // #6824: the old tests only replace page writes or repeat an identical digest. Connector retries+ // change the digest by recording retryOf, so exercise the real readers, without a new test seam.+ test('a committed connector retry resolves only its linked refusal, retaining the audit rows', async () => {+ const intent = { kind: 'connector_v2_checkpoint', connector: 'google', configHash: 'unchanged' };+ const slug = '__managed_connector_checkpoint__';+ const failed = await seed({ slug, operation: 'submit_job', state: 'conflict', code: 'source_changed', intent });+ const unlinked = await seed({ slug, operation: 'submit_job', state: 'conflict', code: 'source_changed', intent });+ await seed({ slug, operation: 'submit_job', state: 'committed', intent: { ...intent, retryOf: failed, retryBase: failed, retryAttempt: 1 } });+ const summary = await readTerminalFailureSummary(engine);+ expect(summary.status).toBe('ok');+ if (summary.status !== 'ok') throw new Error('unknown');+ expect(summary.sources[0]).toMatchObject({ historical_rows: 1, unresolved: { rows: 1 } });+ const listing = await readTerminalFailures(engine, { sourceId: SOURCE, state: 'all' });+ if (listing.status !== 'ok') throw new Error('unknown');+ expect(listing.rows!.find(r => r.request_id === failed)).toMatchObject({ disposition: 'superseded', historical: true });+ expect(listing.rows!.find(r => r.request_id === unlinked)).toMatchObject({ disposition: 'unknown', historical: false });+ expect(await engine.executeRaw('SELECT state,error_code FROM persistence_requests WHERE request_id=$1::uuid', [failed]))+ .toEqual([{ state: 'conflict', error_code: 'source_changed' }]);+ });++ test('committed connector retry chains resolve their ancestors but not a sibling refusal', async () => {+ for (const kind of ['connector_v2_import', 'connector_v2_delete', 'connector_v2_checkpoint']) {+ const intent = { kind, connector: 'google', configHash: 'same' };+ const slug = `notes/${kind}`;+ const base = await seed({ slug, operation: 'submit_job', state: 'conflict', code: 'source_changed', intent });+ const retry = await seed({ slug, operation: 'submit_job', state: 'failed', code: 'storage_error', intent: { ...intent, retryOf: base, retryBase: base } });+ const sibling = await seed({ slug, operation: 'submit_job', state: 'conflict', code: 'source_changed', intent: { ...intent, retryOf: base, retryBase: base } });+ await seed({ slug, operation: 'submit_job', state: 'committed', intent: { ...intent, retryOf: retry, retryBase: base } });+ const listing = await readTerminalFailures(engine, { sourceId: SOURCE, state: 'all' });+ if (listing.status !== 'ok') throw new Error('unknown');+ for (const request of [base, retry]) expect(listing.rows!.find(r => r.request_id === request)).toMatchObject({ disposition: 'superseded', historical: true });+ expect(listing.rows!.find(r => r.request_id === sibling)).toMatchObject({ disposition: 'unknown', historical: false });+ }+ });++ test(`a connector retry lineage is followed back at most CONNECTOR_RETRY_LINEAGE_MAX_DEPTH (${CONNECTOR_RETRY_LINEAGE_MAX_DEPTH}) hops`, async () => {+ const chain = async (hops: number) => {+ const intent = { kind: 'connector_v2_import', connector: 'google', configHash: 'deep' };+ const slug = `notes/depth-${hops}`;+ const base = await seed({ slug, operation: 'submit_job', state: 'conflict', code: 'source_changed', intent });+ let previous = base;+ for (let i = 1; i < hops; i++) previous = await seed({ slug, operation: 'submit_job', state: 'failed', code: 'storage_error', intent: { ...intent, retryOf: previous, retryBase: base, retryAttempt: i } });+ await seed({ slug, operation: 'submit_job', state: 'committed', intent: { ...intent, retryOf: previous, retryBase: base, retryAttempt: hops } });+ return base;+ };+ const superseded = async (requestId: string) => (await engine.executeRaw<{ superseded: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests c+ WHERE ${supersessionSql('r', 'c')}) AS superseded FROM persistence_requests r WHERE r.request_id=$1::uuid`, [requestId]))[0]!.superseded;+ expect(await superseded(await chain(CONNECTOR_RETRY_LINEAGE_MAX_DEPTH))).toBe(true);+ expect(await superseded(await chain(CONNECTOR_RETRY_LINEAGE_MAX_DEPTH + 1))).toBe(false);+ });++ test('connector replacement proof excludes noncommits, mismatched identities and missing lineage', async () => {+ const intent = { kind: 'connector_v2_import', connector: 'google', configHash: 'same' };+ const failed = await seed({ slug: 'notes/retry', operation: 'submit_job', state: 'conflict', code: 'source_changed', intent });+ const replacement = async (state: string, overrides: object = {}) => seed({ slug: 'notes/retry', operation: 'submit_job', state,+ intent: { ...intent, retryBase: failed, retryOf: failed, retryAttempt: 1 }, ...overrides });+ const candidates = [];+ for (const state of ['queued', 'running', 'recovering', 'failed', 'conflict', 'cancelled']) candidates.push(await replacement(state));+ candidates.push(await replacement('committed', { source: OTHER }));+ candidates.push(await replacement('committed', { slug: 'notes/other' }));+ candidates.push(await replacement('committed', { operation: 'extract_facts' }));+ candidates.push(await replacement('committed', { intent: { ...intent, retryOf: randomUUID() } }));+ candidates.push(await replacement('committed', { intent: { ...intent, retryBase: failed } }));+ candidates.push(await replacement('committed', { intent: { ...intent, retryOf: 'invalid-uuid' } }));+ candidates.push(await replacement('committed', { intent: { ...intent, kind: 'facts_extract', retryOf: failed } }));+ candidates.push(await replacement('committed', { compacted: true }));+ const otherPrincipal = await replacement('committed');+ await engine.executeRaw("UPDATE persistence_requests SET principal_id='someone-else' WHERE request_id=$1::uuid", [otherPrincipal]);+ candidates.push(otherPrincipal);+ const otherPrincipalKind = await replacement('committed');+ await engine.executeRaw("UPDATE persistence_requests SET principal_kind='oauth_client' WHERE request_id=$1::uuid", [otherPrincipalKind]);+ candidates.push(otherPrincipalKind);+ const otherIncarnation = await replacement('committed');+ await engine.executeRaw('UPDATE persistence_requests SET source_incarnation=$2::uuid WHERE request_id=$1::uuid', [otherIncarnation, randomUUID()]);+ candidates.push(otherIncarnation);+ const rows = await engine.executeRaw<{ request_id: string; matches: boolean }>(`SELECT c.request_id::text, ${supersessionSql('r', 'c')} AS matches+ FROM persistence_requests r CROSS JOIN persistence_requests c WHERE r.request_id=$1::uuid AND c.request_id=ANY($2::uuid[])`, [failed, candidates]);+ expect(rows).toHaveLength(candidates.length);+ expect(rows.filter(r => r.matches)).toEqual([]);+ });+test('a spike warns secondarily, against the zero-filled 7-day median, with its thresholds named as config keys', async () => {expect(sevenDayMedian([0, 0, 1])).toBe(0);await engine.setConfig('persistence.terminal_failures.spike_min', '3');