Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): name the OS error and the drain stop for an unopenable worktree lock (#6305)
time-attack903a091de8bb
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 7e6acd7f51..72b4307071 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -31,6 +31,7 @@ import { readWriteSwitchSnapshot, writeSwitchOn } from './switches.ts';import { consumerConnectionRoute, consumerStatementEngine, poolerExposureLine } from './consumer-lane.ts';import { isConnectionLoss } from '../retry-matcher.ts';import { INSPECT_OWNER_RETRY_MS } from './health.ts';+import { lockOpenOsError } from './native-lock.ts';type PhaseObservation = { name: string; started_at: string; deadline_exceeded: boolean; attempt: number; first_conn_ms?: number };/** #5373: set by a task that abandons a still-running preparation after losing its claim; its root is freed only once `until` settles. */@@ -851,7 +852,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', failureLogText(done));if (done.state === 'queued' && done.blocked_reason === 'writer_lock_unavailable') {root.retryAfterMs = INSPECT_OWNER_RETRY_MS;- this.log('publication', 'writer_lock_unavailable', `request ${row.request_id}: this process cannot open source ${row.source_id}'s worktree lock; left for an owner process`);+ this.log('publication', 'writer_lock_unavailable', `request ${row.request_id}: this process cannot open source ${row.source_id}'s worktree lock${lockOpenOsError(row.worktree_id) ? ` (${lockOpenOsError(row.worktree_id)})` : ''}; left for an owner process`);}if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex e61d399980..0819a04fcb 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -17,7 +17,7 @@ import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWritimport type { WaitingOn } from './claim-phase.ts';import { preparationKind } from './preparation-budget.ts';import { isTerminal, principalKey, requestPrincipal, recoveryFiles, type FileRecoveryRecord, type RecoveryRecord, type WriteRequest } from './model.ts';-import { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';+import { isLockOpenFailure, noteLockOpenFailure, type NativeLockHandle } from './native-lock.ts';import { withCoordinatedWrite } from './context.ts';import { lockCoreSources } from './core-guard.ts';import { publicationAttribution } from './attribution.ts';@@ -282,6 +282,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prcatch (error) {// #6305: this process cannot open the lock file (sandbox, unwritable lock directory): like a busy lock, publish nothing.if (!isLockOpenFailure(error)) throw error;+ noteLockOpenFailure(row.worktree_id, error);await releaseUnpublishedClaim(engine, row, 'writer_lock_unavailable');return (await getWriteRequestById(engine, row.id))!;}diff --git a/src/core/persistence/native-lock.ts b/src/core/persistence/native-lock.tsindex 62a5681bdb..b53968b21b 100644--- a/src/core/persistence/native-lock.ts+++ b/src/core/persistence/native-lock.ts@@ -37,6 +37,13 @@ export class NativeLockUnavailableError extends Error {}/** #6305: this process could not create or open the lock file; a busy lock returns null instead. */+/** #6305: the OS error of the last lock-open failure per worktree, so the consumer's release line names it (the request's blocked_reason cannot). */+const openFailures = new Map<string, string>();+export function noteLockOpenFailure(worktreeId: string, error: unknown): void {+ const os = error instanceof NativeLockUnavailableError ? error.osError : undefined;+ if (os) openFailures.set(worktreeId, os); else openFailures.delete(worktreeId);+}+export function lockOpenOsError(worktreeId: string | null | undefined): string | null { return worktreeId ? openFailures.get(worktreeId) ?? null : null; }export function isLockOpenFailure(error: unknown): error is NativeLockUnavailableError {return error instanceof NativeLockUnavailableError && error.stage === 'open';}diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex d9e665ea46..c9bf9cb953 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -878,6 +878,14 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: swhy: 'Status names the request, its step and the owner process, read-only.', user_message: `Restart ${owner} on this host, then run: ${resumeCommand}`,verify: { argv: ['gbrain', 'sources', 'writer', 'movement', sourceId, '--json'] } }, cliRenderContext()), ...(docs ? { docs } : {}) };}+ // #6305: the head stays queued as writer_lock_unavailable: no process that reached it could open the source's worktree lock.+ if (d?.stop_reason === 'drain_stalled' && (d.stall?.blocked_reason === 'writer_lock_unavailable')) {+ return { command: `gbrain sources writer status --source ${sourceId} --json`, safe_to_loop: false, retry_after_ms: 0, ...estimate, code: 'drain_stalled', cause: d.stall.cause,+ why: `The write ${d.stall.request_id} stayed queued for ${d.stall.stalled_seconds}s with blocked_reason=writer_lock_unavailable: the processes that claimed it could not open source ${sourceId}'s worktree lock `+ + '(a sandbox, or a lock directory this user cannot write; the consumer log line names the OS error), so they left it for an owner and none took it. Nothing failed and the cursor is intact. '+ + `Run the sync from a process that can write the source's lock directory (the owner's gbrain serve, or this command outside the sandbox), then rerun: ${resumeCommand}`,+ ...(docs ? { docs } : {}) };+ }// #6423: the pass admitted nothing for the whole window; the step and statement name where it waited.if (d?.stop_reason === 'drain_stalled' && d.stall?.cause === 'no_admission') {const stall = d.stall;diff --git a/test/persistence-lock-open-failure.test.ts b/test/persistence-lock-open-failure.test.tsindex acc8419dd7..47bcabc23d 100644--- a/test/persistence-lock-open-failure.test.ts+++ b/test/persistence-lock-open-failure.test.ts@@ -25,6 +25,9 @@ import { localHostId } from '../src/core/persistence/identity.ts';import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { lockOpenOsError } from '../src/core/persistence/native-lock.ts';+import { drainNext, runDrain } from '../src/core/persistence/sync-drain.ts';+import type { SyncResult } from '../src/commands/sync.ts';import { publishSingleWrite } from '../src/core/persistence/group-publish.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';@@ -56,6 +59,17 @@ describe('native lock open failures are typed and carry the OS error', () => {expect(nativeLockOsError(new Error('Native lock open failed (OS error 13)'))).toBe(process.platform === 'win32' ? 'os_error_13' : 'EACCES');expect(nativeLockOsError(new Error('Native lock open failed (OS error 0)'))).toBeUndefined();});+ test('a managed drain whose head stays queued as writer_lock_unavailable stops drain_stalled with a next that names it', async () => {+ const pending = { status: 'partial', reason: 'writer_pending', fromCommit: null, toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [],+ managedCursor: { index: 1, total: 3 } } as SyncResult;+ const stall = { request_id: 'req-1', state: 'queued', blocked_reason: 'writer_lock_unavailable', head_request_id: 'req-1', head_state: 'queued', claimable_here: false, owner_is_this_host: true };+ const result = await runDrain({ pass: async () => pending, pauseMs: 1, stallMs: 20, probe: { blockedHead: async () => null, fingerprint: async () => ({ key: 'same', stall, claim: null }) } });+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { blocked_reason: 'writer_lock_unavailable', cause: 'no_progress' } });+ const next = drainNext(result, 'gbrain sync --source default --no-pull', 'default')!;+ expect(next).toMatchObject({ command: 'gbrain sources writer status --source default --json', code: 'drain_stalled', safe_to_loop: false });+ expect(next.why).toContain('blocked_reason=writer_lock_unavailable');+ expect(next.why).toContain('names the OS error');+ });test('ownerExceptionFailure reports the OS error, not the gbrain code', () => {const error = new NativeLockUnavailableError('The OS could not acquire the writer lock', Object.assign(new Error('x'), { code: 'EACCES' }));expect(ownerExceptionFailure(error).detail).toMatchObject({ origin: 'owner_exception', errno: 'EACCES' });@@ -121,6 +135,16 @@ for (const kind of testBackends()) {expect(await engine.getPage('notes/locked-out', { sourceId: 'default' })).not.toBeNull();}), 120_000);+ test('the release keeps the OS error for the consumer log line (lockOpenOsError)', async () => withEnv({ GBRAIN_HOME: home }, async () => {+ const { row, binding, prepared } = await claimedPut('notes/locked-out-errno');+ rmSync(binding.coordination_path!, { force: true }); mkdirSync(binding.coordination_path!);+ expect(await publish(engine, row, prepared)).toMatchObject({ state: 'queued', blocked_reason: 'writer_lock_unavailable' });+ expect(lockOpenOsError(binding.worktree_id)).toBe('EISDIR');+ rmSync(binding.coordination_path!, { recursive: true, force: true });+ const again = (await claimNextWrite(engine, localHostId()))!;+ expect((await publish(engine, again, await preparePageMutation(engine, again, context().config))).state).toBe('committed');+ }), 120_000);+test('an EISDIR on the page file itself (the brain path) still fails terminally', async () => withEnv({ GBRAIN_HOME: home }, async () => {const { row, prepared } = await claimedPut('notes/blocked-file');mkdirSync(join(root, 'notes', 'blocked-file.md'), { recursive: true });