Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#7630): a reconcile or managed write's fault fix and group follow its intent kind; notice names what keeps the sync retry

garrytan316b1d82423c
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 675bcfb044..63803462cc 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1304,7 +1304,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.460.0', text: 'Dream consolidation on a managed brain now closes a fenced fact in its page: the closing `valid_until` is written into the fact\'s row in the entity page\'s `## Facts` fence, published with the take, and the database row takes its value from that cell, so a later sync or re-import keeps the fact closed. Before, only the database row was closed and the next re-import of the page reopened it. A fact with no fence row is still closed in the database. A fenced fact whose fence row is on another page is left open. Facts an earlier release closed in the database only are not changed (GBRA-190).' },
// GBRA-207 (#7630). `since` is stamped at the merge slot.
{ since: 'TBD', id: 'sync_refuses_relative_anchor', text: 'A sync whose source directory (`sources.local_path`) or legacy `sync.repo_path` is a relative path such as `.` now refuses `sync_anchor_relative` (exit 3) before any Git probe or import, instead of treating whatever folder it ran from as the brain repo (Git init, a baseline commit of the whole folder, an import of its markdown). `gbrain sources set-path <id> <absolute-directory>` sets the path, `gbrain sources set-path <id> --clear` now also clears a relative path on any source, and doctor\'s `default_source_local_path` warns on any source with a relative path, and `gbrain config set sync.repo_path` refuses one. Until the path is set, page and fact writes skip the file (database only), matching a folder to its source ignores it, the dream, autopilot and maintenance cycles run only database phases, fence repair edits stored pages instead of files, managed activation refuses it, `autopilot --install` needs `--repo`, a remote `submit_job` is refused and a managed brain records no managed root there. A few other local commands may still read it from the folder they run in, so set the path before relying on them.' },
- { since: 'TBD', text: 'A foreground write (`remember`, `put_page`, `add_tag`, `takes_add` and the other caller-submitted page mutations) that ends with a retryable fault such as `preparation_stalled` now carries a diagnosis that inspects the writer read-only (`gbrain sources writer status --source <id> --json`) and says to resubmit the same write with a new request_id, instead of telling the user to run `gbrain sync`. A maintenance or administration operation gets the read-only inspect alone. Recorded sync faults keep their sync retry.' },
+ { since: 'TBD', text: 'A foreground write (`remember`, `put_page`, `add_tag`, `takes_add` and the other caller-submitted page mutations) that ends with a retryable fault such as `preparation_stalled` now carries a diagnosis that inspects the writer read-only (`gbrain sources writer status --source <id> --json`) and says to resubmit the same write with a new request_id, instead of telling the user to run `gbrain sync`. A managed write (an import, repair, quarantine clear or grandfather) says to rerun its command, an operation such as `extract_facts` or writer administration gets the read-only inspect alone, and a canonical reconcile, a maintenance job (stored as `submit_job`) and a recorded sync fault keep their sync retry. `gbrain sources writer failures --group-by category` splits these by operation, and `--operation` narrows a listing to one.' },
// GBRA-95 RLS backfill. `since` is stamped at the merge slot.
{ since: '0.60.463.0', id: 'rls_backfill_unguarded_tables', text: 'On Postgres, a schema migration now enables row-level security on every gbrain table still without it. A table could be left without RLS because its RLS came only from a full schema replay, which `gbrain apply-migrations --yes` does not run (the four incremental-derivation tables, `page_segment_derivations`, `page_derivation_spend` and the two purge tables), or only from the auto-RLS event trigger, which needs a superuser and is absent on many managed brains. Supabase gives public tables anon and authenticated grants, so with the Data API on such a table was reachable with the anon key. Only a table still without RLS changes; one with a `GBRAIN:RLS_EXEMPT` comment is left alone; no row is read or written. Under a role that does not bypass RLS or does not own a table, the migration names the table on stderr and leaves it, and `gbrain doctor` (rls) keeps naming it with the fix. `gbrain repair missing-tables` now recreates a cache table with RLS on. A role that neither owns a table nor bypasses RLS reads no rows from it and cannot insert or update it once RLS is on (a read-only reporting role or a scoped write role, for example): give that role policies before upgrading (docs/ENGINES.md has the source-scope recipe), or, to keep a table open to it on purpose, add the `GBRAIN:RLS_EXEMPT reason=...` comment to that table. A write role set up with an earlier copy of that recipe also needs its new policies on `page_derivation_spend` and the two purge tables: without them its segmented derivation writes are refused, and the derivation purge triggers its writes fire read no purge, so they do not hold back a purged claim.' },
{ since: '0.60.464.0', text: 'On Postgres, `gbrain serve --access read-only` (stdio) no longer acts as a resident owner: it holds no session-lane (direct pool) connection, starts no persistence consumer, takes no on-commit notifier lease, runs no startup or idle sweep or facts drain, and refuses delegated sync and sweep requests (the CLI then runs them itself). Resolve, turn_context and context_pack still answer. A read-write serve, `gbrain jobs work` or the autopilot owns those duties; `gbrain doctor` reports when no process on the host holds the notifier (`commit_notifier`) or a consumer (`two_consumers_on_host`). Read-write and HTTP serves, and any serve on PGLite (the process that owns the database file), are unchanged.' },
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index 30ec7531be..31b12ca863 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -112,7 +112,7 @@ function writerFailuresQuery(sourceId: string, params: Record<string, unknown>):
if (bad('before', /^\d{1,19}$/)) throw invalid('Invalid --before value.', 'Pass --before exactly as the previous page\'s next_cursor.');
if (bad('code', /^[a-z][a-z0-9_]{0,63}$/)) throw invalid('Invalid --code value.', 'Pass --code as a snake_case code a group names, e.g. --code storage_error.');
if (bad('origin', /^[a-z][a-z0-9_]{0,63}$/)) throw invalid('Invalid --origin value.', 'Pass --origin as an origin a group names, or none for receipts with no recorded origin.');
- if (bad('operation', /^[a-z][a-z0-9_]{0,63}$/)) throw invalid('Invalid --operation value.', 'Pass --operation as the operation a group names, e.g. --operation put_page.');
+ if (bad('operation', /^[a-z][a-z0-9_]{0,63}$/)) throw invalid('Invalid --operation value.', 'Pass --operation as the operation a group names, e.g. --operation put_page or --operation canonical_reconcile.');
if (bad('category', /^[a-z][a-z_]{0,63}$/)) throw invalid('Invalid --category value.', 'Pass --category as a category a group names, e.g. --category knock_on.');
if (params.limit !== undefined && !(typeof params.limit === 'number' && Number.isInteger(params.limit) && params.limit >= 1 && params.limit <= 100)) {
throw invalid('Invalid --limit value.', 'Pass --limit as a whole number from 1 to 100 (default 20).');
diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.ts
index 0a66935838..b8fd2dc798 100644
--- a/src/core/persistence/terminal-classify.ts
+++ b/src/core/persistence/terminal-classify.ts
@@ -343,13 +343,27 @@ const RESUBMITTED_WRITES = new Set(['put_page', 'put_pages', 'capture', 'delete_
'add_tag', 'remove_tag', 'add_link', 'remove_link', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove']);
/**
- * #7630: a sync write (and a recorded sync fault, read as one) is stored as `submit_job`; its retry is the sync. A
- * foreground write (`remember`, `put_page`, ...) is resubmitted by its caller. Any other operation (maintenance,
- * administration) is neither: writer status names what holds it.
+ * #7630: the operation a fault's fix depends on. A reconcile or managed write (import, repair, quarantine clear,
+ * grandfather) is stored as `put_page` under its own intent kind, which names it while the intent survives.
+ */
+export function faultOperation(operation: string, intentKind: string | null | undefined): string {
+ return operation !== 'submit_job' && intentKind && (intentKind === 'canonical_reconcile' || intentKind.startsWith('managed_')) ? intentKind : operation;
+}
+
+/**
+ * #7630: a sync write, a maintenance job and a recorded sync fault (read as one) are stored as `submit_job`; their
+ * retry is the sync. A foreground write (`remember`, `put_page`, ...) is resubmitted by its caller, and a managed write
+ * by rerunning the command that wrote it. Any other operation (`extract_facts`, writer administration) is neither:
+ * writer status names what holds it.
*/
function faultAction(code: string, input: TerminalInput): Action {
const v = classifySyncFault({ code });
- if (v.safe_actions[0] === 'retry' && input.intent_kind === 'canonical_reconcile') {
+ const operation = faultOperation(input.operation, input.intent_kind);
+ if (v.safe_actions[0] === 'retry' && operation.startsWith('managed_')) {
+ return inspect(input.source_id, `The ${operation} write ended ${code}; it was not part of a sync, so a sync does not retry it. `
+ + 'Writer status names the step it stopped at and what held it, read-only. Once that clears, rerun the command that wrote it (an import, repair, quarantine clear or grandfather).');
+ }
+ if (v.safe_actions[0] === 'retry' && operation === 'canonical_reconcile') {
return syncRetry(input.source_id, `The canonical reconcile recorded ${code} (${v.class}); the next sync re-admits a keep_db reconcile, and a \`gbrain sources reconcile\` run is retried by running it again.`);
}
if (v.safe_actions[0] === 'retry' && input.operation !== 'submit_job' && !RESUBMITTED_WRITES.has(input.operation)) {
diff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.ts
index 060e29c8d7..e8f30947e6 100644
--- a/src/core/persistence/terminal-failures.ts
+++ b/src/core/persistence/terminal-failures.ts
@@ -28,7 +28,7 @@ import { readReceiptRetentionDays, DEFAULT_RECEIPT_RETENTION_DAYS } from './limi
import { MANAGED_SYNC_PASS_OP } from './sync-pass-row.ts';
import { SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';
import type { PublicCategory } from './public-category.ts';
-import { classifyTerminal, dispositionOf, driftSinceAction, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
+import { classifyTerminal, dispositionOf, driftSinceAction, faultOperation, TERMINAL_FIXED_IN, supersessionOrderSql, supersessionSql, terminalInspectArgv, terminalKnockOnSql, type TerminalCategory,
type TerminalDisposition, type TerminalVerdict, CONNECTION_MESSAGE_PATTERN, LEGACY_PUBLICATION_PREFIX } from './terminal-classify.ts';
export const TERMINAL_WINDOW_KEY = 'persistence.terminal_failures.window_days';
@@ -326,6 +326,7 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
const out: TerminalFailureRow[] = [];
// #6712 PR 2: the oldest admission per drift group, so the group's file-drift fix selects every page in it with one concrete --since.
const driftSince = new Map<string, string>();
+ const faultOperationOf = new Map<string, string>();
let cursor = q.before ?? null, scanned = 0, exhausted = false;
const want = q.groupBy ? MAX_SCAN : limit + 1;
while (out.length < want && scanned < MAX_SCAN && !exhausted) {
@@ -351,7 +352,8 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
const disposition = row.error_code === SYNC_PASS_SUPERSEDED ? 'superseded' : dispositionOf(row.later_state ? { state: row.later_state, same_intent: row.same_intent === true } : null);
const historical = !row.has_recovery && (disposition !== 'unknown' || v.historical);
const matches = (!q.category || v.category === q.category) && (!q.code || v.code === q.code)
- && (q.origin === undefined || (v.origin ?? NO_ORIGIN) === q.origin) && (!q.operation || row.operation === q.operation) && (state === 'all' || !historical);
+ && (q.origin === undefined || (v.origin ?? NO_ORIGIN) === q.origin) && (!q.operation || faultOperation(row.operation, row.intent_kind) === q.operation) && (state === 'all' || !historical);
+ if (matches) faultOperationOf.set(row.request_id, faultOperation(row.operation, row.intent_kind));
if (matches) out.push({ request_id: row.request_id, slug: row.slug, operation: row.operation, state: row.state, code: v.code, origin: v.origin, category: v.category, public_category: v.public_category, class: v.class,
safe_actions: v.safe_actions, needs_human: v.needs_human, ...(v.human_reason ? { human_reason: v.human_reason } : {}), disposition, blocking: row.has_recovery, historical,
compacted: row.compacted, ended_at: row.ended_at, cursor: row.sequence, ...(v.root_request_id ? { root_request_id: v.root_request_id } : {}),
@@ -373,7 +375,7 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailu
}
const groups = new Map<string, TerminalFailureGroup>();
for (const row of out) {
- const operation = row.category === 'sync_fault' ? row.operation : undefined;
+ const operation = row.category === 'sync_fault' ? faultOperationOf.get(row.request_id) : undefined;
const key = `${row.code}\0${row.origin ?? ''}\0${row.category}${operation === undefined ? '' : `\0${operation}`}`;
let g = groups.get(key);
if (!g) {
diff --git a/test/terminal-failures-6650.test.ts b/test/terminal-failures-6650.test.ts
index 80943dcb7a..583d70fb41 100644
--- a/test/terminal-failures-6650.test.ts
+++ b/test/terminal-failures-6650.test.ts
@@ -405,11 +405,19 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drill
await seed({ slug: 'notes/r', operation: 'remember', state: 'failed', code: 'preparation_stalled' });
await seed({ slug: 'notes/t1', operation: 'takes_supersede', state: 'failed', code: 'preparation_stalled' });
await seed({ slug: 'notes/t2', operation: 'takes_resolve', state: 'failed', code: 'preparation_stalled' });
+ await seed({ slug: 'notes/rc', operation: 'put_page', state: 'failed', code: 'preparation_stalled', kind: 'canonical_reconcile' });
+ await seed({ slug: 'notes/mi', operation: 'put_page', state: 'failed', code: 'preparation_stalled', kind: 'managed_file_import' });
+ await seed({ slug: 'notes/ef', operation: 'extract_facts', state: 'failed', code: 'preparation_stalled' });
const grouped = await readTerminalFailures(engine, { sourceId: SOURCE, groupBy: 'category' });
if (grouped.status !== 'ok') throw new Error('unknown');
const stalled = grouped.groups!.filter(g => g.code === 'preparation_stalled');
- expect(stalled.map(g => g.operation ?? '').sort()).toEqual(['put_page', 'remember', 'submit_job', 'takes_resolve', 'takes_supersede']);
- expect(stalled.find(g => g.operation === 'submit_job')!.fix.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);
+ expect(stalled.map(g => g.operation ?? '').sort()).toEqual(['canonical_reconcile', 'extract_facts', 'managed_file_import', 'put_page', 'remember', 'submit_job', 'takes_resolve', 'takes_supersede']);
+ for (const op of ['submit_job', 'canonical_reconcile']) expect(stalled.find(g => g.operation === op)!.fix.argv?.slice(0, 2)).toEqual(['gbrain', 'sync']);
+ expect(stalled.find(g => g.operation === 'managed_file_import')!.fix.why).toContain('rerun the command that wrote it');
+ expect(stalled.find(g => g.operation === 'extract_facts')!.fix.why).not.toContain('request_id');
+ const flat = await readTerminalFailures(engine, { sourceId: SOURCE, limit: 50 });
+ if (flat.status !== 'ok') throw new Error('unknown');
+ for (const g of stalled) for (const s of g.samples) expect(flat.rows!.find(r => r.request_id === s.request_id)!.fix).toEqual(g.fix);
for (const op of ['put_page', 'remember', 'takes_supersede', 'takes_resolve']) {
const g = stalled.find(x => x.operation === op)!;
expect(g.rows).toBe(1);
@@ -422,7 +430,7 @@ for (const kind of testBackends()) describe(`the aggregate, doctor and the drill
expect(parsed.params.operation).toBe(g.operation);
const rows = await runPersistenceAdministration(engine, parsed.operation, parsed.params) as TerminalFailureListing;
if (rows.status !== 'ok') throw new Error('unknown');
- expect(rows.rows!.map(r => r.operation)).toEqual([g.operation ?? '']);
+ expect(rows.rows!.map(r => r.request_id)).toEqual(g.samples.map(s => s.request_id));
}
const table = renderWriterFailures(grouped, false).split('\n');
for (const op of ['submit_job', 'takes_supersede', 'takes_resolve']) expect(table.some(l => /^\s+\d+\s/.test(l) && l.includes(' preparation_stalled ') && l.includes(` ${op} `))).toBe(true);