Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Carry a lane fault through the knock-on cancel (#6402 residual, fix wave 15 P4.3)
garrytand20f66be0124
diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex a83e5d9308..b9b2b7b636 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -113,6 +113,13 @@ Every hold and error has three fields, from one table| `invalid_params` | systemic | none | yes | always |<!-- sync-fault-table:end -->+A `cancelled` error whose group was released by a lane fault (`lock_timeout`+or `statement_timeout` on a parallel publish lane) also carries that fault as+`last_error.detail`, and the cancelled rows keep it as their `blocked_reason`+(`lane_lock_timeout`, `lane_statement_timeout`) and in the cancel message.+The verdict is the same retry; the detail says the database, not the page,+ended the group.+An unknown code is systemic and human: `gbrain errors <code>` explains itoffline, `gbrain doctor --json` says what the brain thinks.diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex c8d14f1cfe..8e12b9c250 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -35,10 +35,10 @@ import type { BrainEngine } from '../engine.ts';import { OperationError } from '../ops/contract.ts';import { authorizeStoredRequest, storedAuthorizationReads } from './authority.ts';import { localHostId } from './identity.ts';-import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership, joinWorktreeLease } from './ownership.ts';+import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership, joinWorktreeLease, MANAGED_MODE_SQL } from './ownership.ts';import { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, lanePolicy, stepDownLanes, type LaneState } from './sync-lanes.ts';-import { cancelRows, windowPredecessor } from './sync-window.ts';+import { cancelRows, laneFaultBlockedReason, laneFaultCancelMessage, windowPredecessor } from './sync-window.ts';import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,foregroundPriority, independentGroup, publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';import { principalKey, requestPrincipal, type FileRecoveryRecord, type WriteRequest } from './model.ts';@@ -147,7 +147,7 @@ const STABLE_IN_PREPARATION = new Set(['SELECT lane,revoked_at,grant_ceiling FROM persistence_local_writers WHERE id=$1::uuid','SELECT s.source_id,s.source_incarnation,s.worktree_id,s.relative_path, s.topology_generation::text AS topology_generation,w.owner_host_id,w.owner_epoch::text AS owner_epoch,w.state, h.local_path,h.coordination_path FROM persistence_source_bindings s JOIN persistence_worktrees w ON w.id=s.worktree_id LEFT JOIN persistence_host_bindings h ON h.worktree_id=w.id AND h.host_id=$2::uuid WHERE s.source_id=$1','SELECT local_path FROM sources WHERE id=$1',- 'SELECT enabled FROM persistence_brain WHERE singleton=1',+ MANAGED_MODE_SQL,"SELECT to_regclass('shared_skill_packs') IS NOT NULL AS present",'SELECT p.source_id,p.source_incarnation,s.local_path AS source_root, h.local_path AS worktree_root,b.relative_path FROM shared_skill_packs p JOIN sources s ON s.id=p.source_id AND s.incarnation=p.source_incarnation LEFT JOIN persistence_source_bindings b ON b.source_id=p.source_id AND b.source_incarnation=p.source_incarnation LEFT JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuid','SELECT id, name, local_path, last_commit, last_sync_at, config, created_at, contextual_retrieval_mode, trust_frontmatter_overrides FROM sources WHERE id = $1',@@ -440,7 +440,10 @@ function groupFailure(error: unknown): GroupFailure {*/async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution): Promise<boolean | null> {if (run.lane) run.lane.fallbacks++;- if (reason === 'lock_timeout' || reason === 'statement_timeout') stepDownLanes(rows[0]!.worktree_id!, `${reason} on a lane group`);+ // #6402 residual (P4.3): a server fault on the lane group is kept on the rows it releases or cancels (`blocked_reason`+ // `lane_<fault>`, the cancel message), so the ledger and `claimedHeadOrder` name it instead of a generic wait.+ const laneFault = reason === 'lock_timeout' || reason === 'statement_timeout' ? reason : null;+ if (laneFault) stepDownLanes(rows[0]!.worktree_id!, `${reason} on a lane group`);const after = windowPredecessor(rows[0]!);const prior = after ? await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=$3::uuid',[rows[0]!.principal_kind, rows[0]!.principal_id, after]).then(found => found[0]?.state ?? null) : 'committed';@@ -448,10 +451,10 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G// claimed again as a lane head; publishing its members one at a time would hold the lanes back.if (prior === 'committed' && reason !== 'busy') return null;if (prior !== null && ['failed', 'conflict', 'cancelled'].includes(prior)) {- for (const done of await cancelRows(engine, rows)) run.settled(done);+ for (const done of await cancelRows(engine, rows, laneFault ? laneFaultCancelMessage(laneFault) : undefined)) run.settled(done);return true;}- for (const row of rows) await releaseUnpublishedClaim(engine, row, 'group_member_waiting');+ for (const row of rows) await releaseUnpublishedClaim(engine, row, laneFault ? laneFaultBlockedReason(laneFault) : 'group_member_waiting');return false;}diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex 8ae53d8317..1e46d87864 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -34,6 +34,7 @@ import { CONTENT_REPAIR_KINDS, contentHoldDisposition, runContentLane, type Contimport { resolveRepairScope, type RepairKind, type RepairResult } from '../repair/core.ts';import type { RepairKindSpec } from '../repair/registry.ts';import { headCommittedBytes } from './sync-page-fault.ts';+import { laneFaultInMessage } from './sync-window.ts';import { drainEstimate } from './sync-drain.ts';import { resolveManagedSyncContext } from './sync-discovery.ts';@@ -50,6 +51,7 @@ export interface SyncStatusHold extends SyncFaultVerdict {export interface SyncStatusError extends SyncFaultVerdict {code: string;+ detail?: string;message: string;slug?: string;path?: string;@@ -126,8 +128,9 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proconst repairable = records.filter(record => contentHoldDisposition(record, auto).action === 'repair').length;const failures = (await readManagedSyncFailures(engine, [sourceId])).filter(failure => failure.code !== 'sync_incomplete');const failure = failures[0];- const lastError: SyncStatusError | null = failure ? { code: failure.code, message: failure.message, path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,- ...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, message: failure.message }) } : null;+ const laneFault = failure?.code === 'cancelled' ? laneFaultInMessage(failure.message) : null;+ const lastError: SyncStatusError | null = failure ? { code: failure.code, ...(laneFault ? { detail: laneFault } : {}), message: failure.message, path: failure.path, phase: failure.phase, first_seen: failure.first_seen, attempts: failure.attempts,+ ...(failure.request_id ? { request_id: failure.request_id } : {}), ...classifySyncFault({ code: failure.code, detail: laneFault, message: failure.message }) } : null;const unfinished = !!header && !header.done;const remaining = header ? Math.max(0, Number(header.total) - Number(header.index)) : null;const p = header?.progress;diff --git a/src/core/persistence/sync-window.ts b/src/core/persistence/sync-window.tsindex 9d1add0c79..ef0865c54e 100644--- a/src/core/persistence/sync-window.ts+++ b/src/core/persistence/sync-window.ts@@ -15,6 +15,16 @@ import { completeWrite, lockCounters } from './journal.ts';import { isTerminal, principalKey, requestPrincipal, type Principal, type WriteRequest } from './model.ts';export const WINDOW_CANCEL_MESSAGE = 'An earlier page of the same sync did not commit; this page was not published and is re-frozen after that failure is resolved.';+/** #6402 residual (P4.3): the lane fault a group released or cancelled under, kept on its rows as `blocked_reason` / the cancel message. */+export type LaneFault = 'lock_timeout' | 'statement_timeout';+export const laneFaultBlockedReason = (fault: LaneFault) => `lane_${fault}` as const;+export const laneFaultOf = (blockedReason: string | null | undefined): LaneFault | null =>+ blockedReason === 'lane_lock_timeout' ? 'lock_timeout' : blockedReason === 'lane_statement_timeout' ? 'statement_timeout' : null;+export const laneFaultCancelMessage = (fault: LaneFault) =>+ `An earlier page of the same sync did not commit after ${fault} on its lane group; this page was not published and is re-frozen on the next sync pass.`;+/** The lane fault a recorded cancel names, so `sync status --json` carries it as the failure's detail (#6402 residual). */+export const laneFaultInMessage = (message: string | null | undefined): LaneFault | null =>+ message?.includes(' after lock_timeout on its lane group') ? 'lock_timeout' : message?.includes(' after statement_timeout on its lane group') ? 'statement_timeout' : null;/** The request a window group waits for, or null for any other request. */export function windowPredecessor(row: Pick<WriteRequest, 'intent'>): string | null {@@ -111,7 +121,10 @@ export async function claimedHeadOrder(engine: BrainEngine, head: WriteRequest,const members = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'group'=$2AND state='queued' AND id<>$3::uuid ORDER BY sequence`, [head.worktree_id, group, head.id]);const missing = prior === 'missing' ? windowPredecessor(head) : null;- if (!missing) return cancelRows(engine, [head, ...members]);+ // #6402 (P4.3): a group released after a lane fault names that fault when its predecessor then ended uncommitted. The+ // claim cleared the head's own `blocked_reason`; its still-queued members keep the one the release stamped.+ const fault = laneFaultOf(head.blocked_reason) ?? members.map(member => laneFaultOf(member.blocked_reason)).find(Boolean) ?? null;+ if (!missing) return fault ? cancelRows(engine, [head, ...members], laneFaultCancelMessage(fault)) : cancelRows(engine, [head, ...members]);// #6402: a predecessor that was never admitted is named, never reported as "an earlier page did not commit".return [...await cancelRows(engine, [head], `Its predecessor request ${missing} was never admitted; this page was not published and is re-frozen on the next sync pass.`),...await cancelRows(engine, members, `The first page of its group (request ${head.request_id}) was cancelled because its predecessor request ${missing} was never admitted; this page was not published and is re-frozen on the next sync pass.`)];diff --git a/src/core/persistence/sync-write-diagnostic.ts b/src/core/persistence/sync-write-diagnostic.tsindex a15de27a45..901390f102 100644--- a/src/core/persistence/sync-write-diagnostic.ts+++ b/src/core/persistence/sync-write-diagnostic.ts@@ -20,7 +20,7 @@ export function managedSyncWriteDiagnostic(cursor: { sourceId: string; root: strconst code = terminal ? row.error_code ?? (row.state === 'cancelled' ? 'cancelled' : 'storage_error') : 'write_pending';const blockedReason = ['writer_busy', 'writer_pool_capacity', 'owner_unavailable', 'recovery_required', 'writer_lock_unavailable','database_contention', 'consumer_stopping', 'revision_changed_repreparing', 'unexpected_file_bytes', 'unexpected_staging_bytes',- 'preparation_deadline', 'group_member_waiting'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';+ 'preparation_deadline', 'group_member_waiting', 'lane_lock_timeout', 'lane_statement_timeout'].includes(row.blocked_reason ?? '') ? row.blocked_reason! : 'write_pending';const detail = terminal ? writeFailureDiagnostic(code, row.error_message) : {reason: blockedReason, message: 'The write is accepted but not committed; the sync checkpoint has not advanced.',suggestion: 'Re-run the same sync options to resume this request. Do not submit a replacement request or skip the pending write.',diff --git a/test/sync-cancelled-knock-on.test.ts b/test/sync-cancelled-knock-on.test.tsindex fe8a83a7db..7a49cc4ee4 100644--- a/test/sync-cancelled-knock-on.test.ts+++ b/test/sync-cancelled-knock-on.test.ts@@ -22,7 +22,7 @@ import { performManagedSync } from '../src/core/persistence/sync-run.ts';import { readSyncStatus } from '../src/core/persistence/sync-status.ts';import { classifySyncFault } from '../src/core/persistence/sync-fault-class.ts';import { managedSyncRetryCommand, readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';-import { claimedHeadOrder, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';+import { claimedHeadOrder, laneFaultBlockedReason, laneFaultCancelMessage, laneFaultInMessage, laneFaultOf, WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';import { submissionAuthority } from '../src/core/persistence/authority.ts';import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';@@ -123,3 +123,56 @@ test('a head whose window predecessor was never admitted is cancelled naming thaexpect(row!.error_message).toContain(missing);expect(row!.error_message).not.toBe(WINDOW_CANCEL_MESSAGE);}));++test('#6402 residual (P4.3): a lane group released after a lock timeout keeps the fault on its rows, and its cancel names it', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ expect(laneFaultBlockedReason('lock_timeout')).toBe('lane_lock_timeout');+ expect(laneFaultOf('lane_statement_timeout')).toBe('statement_timeout');+ expect(laneFaultOf('group_member_waiting')).toBeNull();+ await registerLocalWriter(engine, 'cli');+ const f = await fixture({ 'seed.md': note('Seed.') });+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [f.id]);+ const ctx: OperationContext = { engine, config: { engine: 'pglite' }, dryRun: false, remote: false, sourceId: f.id, logger: { info() {}, warn() {}, error() {} } } as OperationContext;+ // A predecessor that ended uncommitted, then a two-member lane group behind it (a claimed worktree, so the group is scoped like a sync's).+ const failedId = randomUUID();+ const authority = await submissionAuthority(ctx, 'put_page', f.id, source!.incarnation, 'notes/lane-prior');+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: f.id, sourceIncarnation: source!.incarnation,+ slug: 'notes/lane-prior', pageId: null, requestId: failedId, callerIntent: { content: note('Prior.') }, intent: { content: note('Prior.') } });+ await engine.executeRaw("UPDATE persistence_requests SET state='failed',completed_at=now(),error_code='storage_error' WHERE request_id=$1::uuid", [failedId]);+ const headId = randomUUID();+ for (const [slug, requestId] of [['notes/lane-head', headId], ['notes/lane-member', randomUUID()]] as const) {+ const a = await submissionAuthority(ctx, 'put_page', f.id, source!.incarnation, slug);+ const intent = { content: note(slug), after: failedId, group: headId };+ await admitWrite(engine, { principal: a.principal, authority: a, operation: 'put_page', sourceId: f.id, sourceIncarnation: source!.incarnation,+ slug, pageId: null, requestId, callerIntent: intent, intent });+ }+ // The group's publish hit a lock timeout: laneFallback released every member with the lane fault as its blocked reason.+ await engine.executeRaw("UPDATE persistence_requests SET blocked_reason=$2 WHERE intent->>'group'=$1", [headId, laneFaultBlockedReason('lock_timeout')]);+ // Scoped to the source's claimed worktree, as a managed sync's group rows are.+ await engine.executeRaw('UPDATE persistence_requests SET worktree_id=(SELECT worktree_id FROM persistence_source_bindings WHERE source_id=$1 LIMIT 1) WHERE source_id=$1', [f.id]);+ const head = (await claimNextWrite(engine, localHostId()))!;+ expect(head.request_id).toBe(headId);+ expect(head.blocked_reason).toBeNull();+ // Claimed as a window head (a lane head re-runs through laneFallback, which names the fault itself).+ const settled = await claimedHeadOrder(engine, head, false);+ expect(Array.isArray(settled)).toBe(true);+ const rows = settled as Awaited<ReturnType<typeof claimNextWrite>>[];+ expect(rows.map(row => row!.state)).toEqual(['cancelled', 'cancelled']);+ for (const row of rows) {+ expect(row!.error_code).toBe('cancelled');+ expect(row!.error_message).toBe(laneFaultCancelMessage('lock_timeout'));+ expect(row!.error_message).toContain('after lock_timeout on its lane group');+ }+ expect(classifySyncFault({ code: 'cancelled' })).toMatchObject({ class: 'page', safe_actions: ['retry'], needs_human: false });+}));++test('#6402 residual (P4.3): sync status carries the lane fault as the cancelled failure\'s detail', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ expect(laneFaultInMessage(laneFaultCancelMessage('statement_timeout'))).toBe('statement_timeout');+ expect(laneFaultInMessage(WINDOW_CANCEL_MESSAGE)).toBeNull();+ const f = await blockedRun();+ await engine.executeRaw(`UPDATE op_checkpoints SET completed_keys=jsonb_set(jsonb_set(completed_keys,'{0,code}','"cancelled"'),'{0,message}',to_jsonb($1::text))+ WHERE op='managed-sync-failure' AND completed_keys->0->>'source_id'=$2`, [laneFaultCancelMessage('lock_timeout'), f.id]);+ const status = await readSyncStatus(engine, f.id);+ expect(status.last_error).toMatchObject({ code: 'cancelled', detail: 'lock_timeout', class: 'page', safe_actions: ['retry'], needs_human: false });+ expect(status.last_error!.message).toContain('after lock_timeout on its lane group');+ expect(status.needs_human).toBe(false);+}), 120_000);