Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(deactivate): only live effects block; report terminal failures as history; retry-effects covers failed effects (GBRA-130 A-15)

garrytan4d715d93b344
diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.ts
index 1c31428ca3..6fa778d9f4 100644
--- a/src/commands/doctor/checks/parked-effects.ts
+++ b/src/commands/doctor/checks/parked-effects.ts
@@ -46,7 +46,7 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string
const listed = effects.map(effect => `${effect.kind} ${effect.source_id}: ${effect.parked.map(target =>
`${target.slug ?? '(whole effect)'} (${target.error_code})`).join(', ')}; ${'exit' in effect ? effect.exit : effect.command}`);
return { name: 'parked_effects', status: 'warn', details,
- message: `${count} Git or withdrawal effect(s) have parked targets after five consecutive failures; their withdrawal or Git backup is incomplete. ` +
+ message: `${count} Git, withdrawal or embedding effect(s) have parked targets after repeated failures; their withdrawal, Git backup or vectors are incomplete. ` +
`Inspect \`gbrain sources writer status <source>\`, fix the cause, preview with the command shown, then rerun it without --dry-run to authorize one more attempt: ${listed.join(' | ')}` +
(count > rows.length ? ` (first ${rows.length} of ${count} shown)` : '') +
(effects.some(effect => effect.parked.some(target => target.error_code === 'git_target_pending'))
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index 9622d2710b..2e724fca1f 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -7,8 +7,10 @@
* transaction locks `persistence_brain FOR UPDATE` first, checks the expected
* admin state and the writer admin lock, locks worktrees then sources (the
* order admission uses) and rechecks quiescence: no request queued, running or
- * recovering, no request or topology change with a recovery record, no
- * uncommitted effect, no live connector or maintenance lease. It then sets
+ * recovering, no request or topology change with a recovery record, no queued,
+ * running or recovering effect, no live connector or maintenance lease. A
+ * terminally failed effect can no longer change, so it does not block: the
+ * report lists it in `failed_effects` with its code and exit. It then sets
* `enabled=false`, increments `mode_epoch`, marks every worktree `retired`
* (rows kept for receipt and effect foreign keys), deletes source and host
* bindings, and records a committed `writer_deactivate` topology change naming
@@ -42,6 +44,8 @@ import { canonicalFilesystemPath } from './root-registry.ts';
import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
import { assertPhysicalRoot, assertPhysicalRootReservation, PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
import { preActivationClaims, releasePreActivationClaims, type PreActivationClaim } from './pre-activation-release.ts';
+import { PARK_AFTER_FAILURES } from './effect-model.ts';
+import { EMBEDDING_ZERO_NORM } from '../ai/embedding-guard.ts';
export const DEACTIVATE_DOCS = 'docs/architecture/topologies.md#deactivate-runbook';
@@ -54,6 +58,13 @@ export interface DeactivationBlocker {
exit: string;
}
+/** GBRA-130 A-15: a terminally failed effect, reported as history; `exit` is the command that retries it, or null when nothing can. */
+export interface FailedEffectEntry {
+ effect_id: string; kind: string; source_id: string; request_id: string; code: string | null;
+ exit: string | null;
+ detail: string;
+}
+
export interface LocalMarkerReport {
state: 'cleared' | 'pending';
removed: string[];
@@ -73,6 +84,8 @@ export interface DeactivationReport {
blockers: DeactivationBlocker[];
/** Held connector items copied (or, on a dry run, to be copied) into each source's classic state file. */
carried_holds?: HoldCarry[];
+ /** Terminally failed effects (history, never blockers), at most 50, each with its code and exit. */
+ failed_effects?: FailedEffectEntry[];
/** #6122: on a never-activated brain, the claimed sources a deactivation releases (dry run) or released. */
pre_activation_claims?: PreActivationClaim[];
local_markers?: LocalMarkerReport;
@@ -104,16 +117,14 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
"SELECT id::text AS id, operation, source_id FROM persistence_topology_changes WHERE state='recovering' OR recovery IS NOT NULL ORDER BY created_at LIMIT 20");
for (const t of topology) blockers.push({ kind: 'topology_recovery', id: t.id, source_id: t.source_id, detail: `${t.operation} for ${t.source_id} is recovering`,
exit: `gbrain sources writer status ${t.source_id} --json, then let the owner finish recovery` });
- const effects = await engine.executeRaw<{ effect_id: string; kind: string; state: string; source_id: string; request_id: string; error_code: string | null; recovering: boolean; source_live: boolean }>(
- `SELECT e.id::text AS effect_id, e.kind, e.state, COALESCE(e.source_id, r.source_id) AS source_id, r.request_id::text AS request_id, e.error_code,
- e.recovery IS NOT NULL AS recovering,
- EXISTS (SELECT 1 FROM sources s WHERE s.id = r.source_id AND s.incarnation = r.source_incarnation) AS source_live
- FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
- WHERE e.state<>'committed' OR e.recovery IS NOT NULL ORDER BY e.id LIMIT 50`);
+ // GBRA-130 A-15: only work that can still change blocks, as activation checks; terminal failures are failedEffectHistory's.
+ const effects = await engine.executeRaw<EffectRow>(`${EFFECT_ROWS} WHERE e.state IN ('queued','running') OR e.recovery IS NOT NULL ORDER BY e.id LIMIT 50`);
for (const e of effects) {
- blockers.push({ kind: 'effect', id: e.effect_id, source_id: e.source_id, detail: `${e.kind} effect ${e.state}${e.error_code ? ` (${e.error_code})` : ''} for request ${e.request_id}`,
- exit: e.kind === 'embedding' ? (e.source_live ? `gbrain repair embedding-effects --source ${e.source_id}` : 'gbrain repair embedding-effects (its source was removed; run it brain-wide)')
- : e.state === 'failed' ? `gbrain sources writer retry-effects ${e.source_id} --request-id ${e.request_id} --dry-run`
+ blockers.push({ kind: 'effect', id: e.effect_id, source_id: e.source_id, detail: `${e.kind} effect ${e.state}${e.recovering ? ', recovering' : ''}${e.error_code ? ` (${e.error_code})` : ''} for request ${e.request_id}`,
+ exit: e.kind === 'links' || e.kind === 'facts-backstop'
+ ? `wait for the owner to drain it (a ${e.kind} effect that keeps failing settles after ${PARK_AFTER_FAILURES} attempts), then rerun deactivate`
+ : e.kind === 'embedding' && !e.recovering
+ ? `wait for the owner to drain it, then rerun deactivate; one still queued after an hour is re-queued by gbrain repair embedding-effects --source ${e.source_id}`
: 'wait for the owner to drain it, then rerun deactivate' });
}
// Managed connector holds live in the managed checkpoint, which classic mode does not read. Deactivation copies
@@ -138,6 +149,31 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
return blockers;
}
+type EffectRow = { effect_id: string; kind: string; state: string; source_id: string; request_id: string; error_code: string | null; recovering: boolean; source_live: boolean };
+const EFFECT_ROWS = `SELECT e.id::text AS effect_id, e.kind, e.state, COALESCE(e.source_id, r.source_id) AS source_id, r.request_id::text AS request_id, e.error_code,
+ e.recovery IS NOT NULL AS recovering,
+ EXISTS (SELECT 1 FROM sources s WHERE s.id = r.source_id AND s.incarnation = r.source_incarnation AND NOT s.archived) AS source_live
+ FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id`;
+
+/**
+ * GBRA-130 A-15: terminally failed effects, oldest first (at most 50). They block nothing; each carries the exit that
+ * retries it: retry-effects for parked targets and failed Git, withdrawal, links and facts-backstop effects,
+ * `repair embedding-effects` for a failed embedding effect, and none for a zero-norm refusal (the same input returns
+ * the same vector) or an effect whose source was archived, replaced or removed.
+ */
+export async function failedEffectHistory(engine: BrainEngine): Promise<FailedEffectEntry[]> {
+ const rows = await engine.executeRaw<EffectRow>(`${EFFECT_ROWS} WHERE e.state='failed' AND e.recovery IS NULL ORDER BY e.id LIMIT 50`);
+ return rows.map(e => {
+ const retry = `gbrain sources writer retry-effects ${e.source_id} --request-id ${e.request_id} --dry-run`;
+ const [exit, why] = !e.source_live ? [null, 'its source was archived, replaced or removed, so nothing can run it']
+ : e.kind !== 'embedding' || e.error_code === 'targets_parked' ? [retry, 'preview it, fix the recorded cause, then run the command without --dry-run']
+ : e.error_code === EMBEDDING_ZERO_NORM ? [null, 'the provider returns a zero vector for this text, so a retry fails the same way; the page keeps no signature, so gbrain embed --stale retries it under another model']
+ : [`gbrain repair embedding-effects --source ${e.source_id}`, 'preview the bounded retry, then apply it with --apply after the user approves the cost'];
+ return { effect_id: e.effect_id, kind: e.kind, source_id: e.source_id, request_id: e.request_id, code: e.error_code, exit,
+ detail: `${e.kind} effect failed${e.error_code ? ` (${e.error_code})` : ''} for request ${e.request_id}: ${why}` };
+ });
+}
+
/**
* #5914 [R9a]: the `physical_root` blockers of this host's owned checkouts, probed
* exactly as the real operation of each mode will: the managed run takes the
@@ -221,7 +257,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
const blockers = [...await deactivationBlockers(engine), ...await physicalRootBlockers(engine, 'managed')];
if (opts.dryRun) {
const carried_holds = (await planHoldCarry(engine, existingLocalHostId())).filter(c => c.items > 0 && !holdCarryBlocked(c));
- return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds };
+ return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds, failed_effects: await failedEffectHistory(engine) };
}
if (blockers.length) throw blockedError(blockers);
const principal = await topologyPrincipal(engine);
@@ -260,6 +296,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
if (inside.length) throw blockedError(inside);
// Written before commit: if the transaction then fails, the brain stays managed and ignores these files.
const carried_holds = await carryHoldsToClassicState(tx, hostId);
+ const failed_effects = await failedEffectHistory(tx);
const retired = await retiredTopology(tx);
const [epoch] = await tx.executeRaw<{ mode_epoch: string }>(
'UPDATE persistence_brain SET enabled=false, mode_epoch=mode_epoch+1 WHERE singleton=1 RETURNING mode_epoch::text');
@@ -275,7 +312,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
incarnation: null, worktrees: retired.worktrees.map(w => w.id) }, outcome);
await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
return { ...base, mode: 'classic' as const, deactivated: true, mode_epoch: Number(epoch.mode_epoch), retired_mode_epoch: Number(current.mode_epoch),
- retired_worktrees: retired.worktrees, source_bindings: retired.bindings, blockers: [], carried_holds };
+ retired_worktrees: retired.worktrees, source_bindings: retired.bindings, blockers: [], carried_holds, failed_effects };
});
} finally { for (const lock of locks.reverse()) await lock.release(); }
return { ...report, local_markers: await cleanupRetiredManagedMarkers(engine) };
diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.ts
index 0d4854592f..556876d7ab 100644
--- a/src/core/persistence/effect-retry.ts
+++ b/src/core/persistence/effect-retry.ts
@@ -101,20 +101,27 @@ async function ownerRevokedError(tx: BrainEngine, sourceId: string, request: Wri
}
/**
- * #5612: parked Git and withdrawal effects of one committed request. Returns
- * null when the request has none, so the caller falls through to embedding
- * retry. Each invocation authorizes exactly one more attempt per parked target.
- * `internalId` selects one journal row when several principals share the public
- * receipt id; `ownerHost` is the owner's admin-intent approval for #6697 (D6).
+ * #5612: parked Git and withdrawal effects of one committed request, plus
+ * (GBRA-130) parked embedding targets and failed Git, withdrawal-mirror, links
+ * and facts-backstop effects without parked targets (a mirror that failed
+ * `source_changed` while its source was archived, a facts-backstop effect that
+ * used up its attempts), and an embedding effect that failed `source_changed`. Returns null when the request has none, so the caller
+ * falls through to embedding retry. Each invocation authorizes exactly one more
+ * attempt per parked target or failed effect. `internalId` selects one journal
+ * row when several principals share the public receipt id; `ownerHost` is the
+ * owner's admin-intent approval for #6697 (D6); `parkedOnly` keeps to parked
+ * Git and withdrawal effects (the credential-change retry).
*/
export async function retryParkedEffects(engine: BrainEngine, sourceId: string, requestId: string, dryRun: boolean,
- options: { internalId?: string; ownerHost?: boolean } = {}): Promise<Record<string, unknown> | null> {
+ options: { internalId?: string; ownerHost?: boolean; parkedOnly?: boolean } = {}): Promise<Record<string, unknown> | null> {
const [request, ambiguous] = options.internalId
? await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND id=$2::uuid', [sourceId, options.internalId])
: await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE source_id=$1 AND request_id=$2::uuid LIMIT 2', [sourceId, requestId]);
if (!request || ambiguous) return null;
const tracked = await engine.executeRaw<PersistenceEffect>(`SELECT * FROM persistence_effects WHERE request_id=$1::uuid
- AND kind IN ('git','withdrawal-mirror') AND (data ? 'parked' OR data ? 'retried') ORDER BY kind`, [request.id]);
+ AND ((kind IN ('git','withdrawal-mirror') AND (data ? 'parked' OR data ? 'retried'))
+ OR (NOT $2::boolean AND (state='failed' AND (kind<>'embedding' OR error_code='source_changed') OR kind='embedding' AND data ? 'parked'))) ORDER BY kind`,
+ [request.id, options.parkedOnly === true]);
if (!tracked.length) return null;
const hostId = existingLocalHostId();
if (!hostId) throw unregisteredHost(sourceId, requestId);
@@ -127,8 +134,9 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
await guardEffectSource(tx, selected, hostId);
const [effect] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [selected.id]);
const parked = effect.data.parked ?? [];
- const summary = { kind: effect.kind, parked_targets: parked.length, targets: parked.slice(0, 20), retried: effect.data.retried ?? 0 };
- if (effect.state !== 'failed' || effect.error_code !== 'targets_parked') {
+ const summary = { kind: effect.kind, error_code: effect.error_code, parked_targets: parked.length, targets: parked.slice(0, 20), retried: effect.data.retried ?? 0 };
+ const parkedState = effect.error_code === 'targets_parked' ? 'parked' : 'failed';
+ if (effect.state !== 'failed' || (parkedState === 'failed' && options.parkedOnly)) {
effects.push({ ...summary, state: effect.state, terminal: effect.state === 'committed', action: 'unchanged' });
continue;
}
@@ -138,21 +146,22 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
const underOwner = denied !== null && options.ownerHost === true && effect.kind === 'git';
if (denied && !underOwner) {
if (!dryRun && !options.ownerHost) throw denied;
- effects.push({ ...summary, state: 'parked', terminal: true, action: 'owner_revoked' });
+ effects.push({ ...summary, state: parkedState, terminal: true, action: 'owner_revoked' });
continue;
}
const retriedUnder = underOwner ? { retried_under: 'owner_host' } : {};
- if (dryRun) { effects.push({ ...summary, state: 'parked', terminal: true, action: 'would_retry', ...retriedUnder }); continue; }
+ if (dryRun) { effects.push({ ...summary, state: parkedState, terminal: true, action: 'would_retry', ...retriedUnder }); continue; }
const { parked: _parked, retry_slugs: retrying = [], failing_target: _target, ...data } = effect.data;
const scanning = targetedWithdrawalEffect(effect) || effect.data.source_scan === true;
const slugs = scanning ? [...new Set([...retrying, ...parked.flatMap(entry => entry.slug ? [entry.slug] : [])])] : [];
const [updated] = await tx.executeRaw<{ state: string }>(`UPDATE persistence_effects SET state='queued',data=$2::text::jsonb,error_code=NULL,
- next_attempt_at=now(),claim_expires_at=NULL,updated_at=now() WHERE id=$1 AND state='failed' AND error_code='targets_parked'
+ next_attempt_at=now(),claim_expires_at=NULL,updated_at=now() WHERE id=$1 AND state='failed' AND error_code IS NOT DISTINCT FROM $3
AND execution_token IS NULL AND recovery IS NULL RETURNING state`,
[effect.id, JSON.stringify({ ...data, ...(slugs.length ? { retry_slugs: slugs } : {}), target_failures: PARK_AFTER_FAILURES - 1,
...(!scanning && (effect.data.slug ?? effect.data.relative_path) ? { failing_target: effect.data.slug ?? effect.data.relative_path } : {}),
...(underOwner ? { retried_under: 'owner_host', retried_by_host: hostId } : {}),
- retried: (effect.data.retried ?? 0) + 1 })]);
+ ...(effect.kind === 'embedding' ? { embedding_attempt_base: effect.attempts } : {}),
+ retried: (effect.data.retried ?? 0) + 1 }), effect.error_code]);
if (!updated) throw opError('write_claim_lost', 'The parked effect changed during retry approval.',
`The ${effect.kind} effect of request ${requestId} changed (claimed, retried or settled by the worker) while this approval ran, so the transaction rolled back and nothing was queued. Preview its current state before deciding again.`,
{ fix: previewFix(sourceId, requestId) });
@@ -164,8 +173,8 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,
...(denied ? { authority: { ok: false, code: refusal!.code, message: refusal!.message } } : {}),
...(revoked ? { action: 'owner_revoked', refusal: refusalEnvelope(denied!), fix: denied!.fix } : {}),
next_action: revoked && !queued ? denied!.suggestion
- : dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target.'
- : queued ? 'The resident owner makes one more attempt per parked target. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'
+ : dryRun ? 'Fix the recorded cause, then run the same command without --dry-run to authorize one more attempt per parked target or failed effect.'
+ : queued ? 'The resident owner makes one more attempt per parked target or failed effect. Rerun this command with --dry-run to read the terminal state; a target that fails again parks again.'
: 'No parked target remains for this request.' };
});
}
diff --git a/src/core/persistence/embedding-settlement.ts b/src/core/persistence/embedding-settlement.ts
index f71cb7c373..28908a1fda 100644
--- a/src/core/persistence/embedding-settlement.ts
+++ b/src/core/persistence/embedding-settlement.ts
@@ -24,8 +24,12 @@
*
* Every state change is a compare-and-set on state, attempts, execution token
* and recovery. A candidate that changed since planning is `changed_since_preview`.
+ * Two failed effects are not candidates (GBRA-130 A-15): one with parked targets
+ * (`targets_parked`; `gbrain sources writer retry-effects` retries those) and a
+ * zero-norm refusal, which a retry repeats by design.
*/
import { trueUpRequests } from './receipt-true-up.ts';
+import { EMBEDDING_ZERO_NORM } from '../ai/embedding-guard.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { opError, OperationError } from '../ops/contract.ts';
@@ -55,7 +59,8 @@ export interface EmbeddingCandidate {
/** Stale queued (over an hour, or re-queued by this repair and not yet settled) and failed embedding effects of committed writes. */
export const EMBEDDING_CANDIDATE_WHERE = `e.kind='embedding' AND r.state='committed' AND e.recovery IS NULL AND e.execution_token IS NULL
- AND (e.state='failed' OR e.state='queued' AND (e.updated_at < now() - interval '1 hour' OR e.data ? 'repair_requeued_at'))`;
+ AND (e.state='failed' OR e.state='queued' AND (e.updated_at < now() - interval '1 hour' OR e.data ? 'repair_requeued_at'))
+ AND NOT (e.state='failed' AND e.error_code IN ('targets_parked','${EMBEDDING_ZERO_NORM}'))`;
export async function listEmbeddingCandidates(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: string[]): Promise<EmbeddingCandidate[]> {
const rows = await engine.executeRaw<EmbeddingCandidate>(`SELECT e.id::text AS effect_id, r.source_id, r.slug, r.request_id::text AS request_id,
diff --git a/src/core/persistence/git-durability-administration.ts b/src/core/persistence/git-durability-administration.ts
index a43dabbf6b..7a74b2e6ec 100644
--- a/src/core/persistence/git-durability-administration.ts
+++ b/src/core/persistence/git-durability-administration.ts
@@ -190,7 +190,7 @@ export async function retryParkedPushes(engine: BrainEngine, worktreeId: string,
const target = { source_id: row.source_id, request_id: row.request_id };
let result: Record<string, unknown> | null;
try {
- result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun, { internalId: row.id });
+ result = await retryParkedEffects(engine, row.source_id, row.request_id, dryRun, { internalId: row.id, parkedOnly: true });
} catch (error) {
if (!(error instanceof OperationError) || !REQUEST_REFUSALS.has(error.code)) throw error;
refused.push({ ...target, ...refusalEnvelope(error) });
diff --git a/test/persistence-deactivate.test.ts b/test/persistence-deactivate.test.ts
index 24a6aa29c0..7201b745ae 100644
--- a/test/persistence-deactivate.test.ts
+++ b/test/persistence-deactivate.test.ts
@@ -58,7 +58,8 @@ for (const databaseUrl of process.env.DATABASE_URL ? [undefined, process.env.DAT
expect(dry.mode).toBe('managed');
expect(dry.dry_run).toBe(true);
expect(dry.blockers.map((b: { kind: string }) => b.kind)).toEqual(['writer_admin_lock', 'effect']);
- expect(dry.blockers.find((b: { kind: string }) => b.kind === 'effect').exit).toBe('gbrain repair embedding-effects --source default');
+ expect(dry.blockers.find((b: { kind: string }) => b.kind === 'effect').exit)
+ .toBe('wait for the owner to drain it, then rerun deactivate; one still queued after an hour is re-queued by gbrain repair embedding-effects --source default');
expect(dry.retired_worktrees.length).toBe(1);
expect(dry.kept).toMatchObject({ skill_bundles_enabled: true, writer_protocol_floor: 2 });
expect(await writerAdminState(engine)).toBe(before);