Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): a process that cannot open the worktree lock leaves its write for an owner (#6305)

time-attackef9b6e6e6f87
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index c024308c82..5844f004a1 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -47,7 +47,7 @@ Managed connector ingestion, connector item holds, sync checkpoint validation an
- `src/core/persistence/graduation-copy.ts` — engine graduation copier (in process). `copyTable` reads source rows through the digest's own plan (`digestPlan` with inventory transforms, `rowFilter`, `::text` values, COLLATE "C" keyset batches) and writes them in one target transaction per table that sets `gbrain.graduation_run`, bypasses user triggers (`session_replication_role = replica`, or DISABLE/ENABLE TRIGGER by name in the same transaction, never the `gbrain_graduation_fence` triggers), deletes the target's rows (seed rows included) and inserts byte-sized batches as one `$1::text::jsonb` array cast back per column type. The per-column contract (`columnContract`) refuses missing, retyped, target-only or differently generated columns outside the entry's `columnAllowlist`; generated columns are never inserted. Self-FKs take a second update pass under DISABLE TRIGGER. `copySequences` applies each source sequence's exact position, raised to the target column maximum. `deferIndexes`/`buildDeferredIndexes` drop and rebuild HNSW (through `buildDeferredAnnIndexes`) and GIN indexes, keeping the pending list in the target-owned `graduation.deferred_indexes` config row. Tests: `test/graduation-copy.test.ts`, `test/e2e/graduation-copy.test.ts`.
- `src/core/persistence/root-metadata.ts` — engine-free physical-root ownership metadata names. `isPhysicalRootMetadata` matches exactly `.gbrain-owner.json`, its `.gbrain-owner-<sha256>.json` reservation and its `.gbrain-owner.json.<uuid>.tmp` temp file (`physical-root-record.ts` re-exports it and `PHYSICAL_ROOT_MARKER`). `withoutPhysicalRootMetadata` drops `git status --porcelain` entries whose every path is such metadata, for the doctor `bootstrap_push_health` and stop-hook dirty probes: a stamp-only tree is clean, a real change beside the stamp, a rename onto or away from it and a quoted path still count. Pinned by `test/persistence-root-metadata.test.ts`.
- `src/core/persistence/automatic-sync-policy.ts` — `automaticSyncPull(engine, source)`: whether an automatic sync (autopilot freshness `sync` job, per-source fanout cycle) may request a Git pull. It needs a parsed `remote_url`, exactly one boolean `persistence_brain` state that is off, and no worktree binding; a managed brain or claimed source syncs local HEAD with `pull: false`. Missing, duplicated or non-boolean persistence metadata throws `storage_error` (why, read-only `gbrain sources writer status --probe --json` fix) instead of granting a pull, so the caller queues nothing. Clone, immutable and federation flags grant nothing. Pinned by `test/automatic-sync-pull-policy.test.ts`.
-- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.4.0 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`. `native/locks/package.json` (private, no entry points, outside `buildInputs` and `prebuilds/`) is a package boundary so plugin hosts that namespace native addons by the nearest package.json do not treat the whole checkout as one package (#6026; guard `test/native-locks-package-boundary.test.ts`).
+- `src/core/persistence/native-lock.ts` + `native/locks/` — lazy portable Node-API v3 kernel locks (`flock` / `LockFileEx`) with opaque handles, retained stable lock files, cancellable asynchronous waiting and fail-closed capability errors. Eight vendored prebuilds support script-disabled source installs; pinned Zig recipes and source/artifact hashes live in `scripts/native/`. Actual competing-process, crash-handoff and compiled-executable tests run across eight platform/architecture targets and Bun 1.4.0 / 1.4.2. The compiled smoke waits for child exit before cleanup; `scripts/native/compiled-smoke-cleanup.ts` bounds retries to transient Windows `EBUSY` errors, with persistent and permission failures pinned by `test/scripts/native-compiled-cleanup.test.ts`. Windows-only `windows-ipc.h` supplies opaque Global mutex claims (same-thread recursion refused, abandoned owner handoff) and exact-handle stale AF_UNIX deletion after a verified reparse tag under a retained binding claim. CNG hashing and native casing make pipe identities independent of homes and logon sessions. Build and ownership contract: `native/locks/README.md`. `native/locks/package.json` (private, no entry points, outside `buildInputs` and `prebuilds/`) is a package boundary so plugin hosts that namespace native addons by the nearest package.json do not treat the whole checkout as one package (#6026; guard `test/native-locks-package-boundary.test.ts`). #6305: a failure to create or open the lock file is a `NativeLockUnavailableError` with `stage: 'open'` and `osError` (node:fs code, or the addon's `(OS error N)` as its errno name); `isLockOpenFailure` matches only that typed shape, never message text. `publishMutation` (`coordinator.ts`) and the Postgres single-write group path (`group-publish.ts` `publishGroup`, falling through to `publishMutation`) release such a write as `queued` / `writer_lock_unavailable` instead of the terminal owner-exception path; the consumer holds that root for `INSPECT_OWNER_RETRY_MS` (30 s, `health.ts`) so it doesn't re-prepare every poll; `ownerExceptionFailure` reports `osError` as the owner-only errno; a Git effect counts it as a dependency wait and never parks on it. An EISDIR or EACCES on the brain path itself stays terminal (`persistence-lock-open-failure.test.ts`, both engines).
- `src/core/persistence/switches.ts` + `preadmit-cache.ts` + `config-snapshot.ts` — the single-write fast path for foreground page writes on Postgres. `switches.ts` reads every write-path kill switch (`persistence.single_write_group` / `GBRAIN_SINGLE_WRITE_GROUP`, `persistence.preadmit_cache` / `GBRAIN_PREADMIT_CACHE`, `sync.waive_batch` / `GBRAIN_SYNC_WAIVE_BATCH`, `sync.foreground_priority` / `GBRAIN_SYNC_FOREGROUND_PRIORITY`, and `persistence.preparation_deadlines` / `GBRAIN_PREPARATION_DEADLINES` (#6278: off restores the old preparation predicate, see persistence-stalls.md); on by default, `0`/`false` off, env over config) in one `SELECT key,value FROM config WHERE key = ANY(...)` per engine, kept 5 s (the consumer tick reads it under its phase deadline), together with the four preparation budget keys (`readWriteSwitchSnapshot` returns `{ switches, preparation }`; `readPreparationPolicy` is the budgets alone); read-through views register their engine (`registerEngineView`) to share it. With `single_write_group` on: the consumer publishes an eligible single page write (put_page, capture, edit/delete/restore/revert without an internal `intent.kind` or group key) as a group of one through `publishGroup` (`publishSingleWrite`; its intent carries no group marker, its effects queue without `deferBatchReconcile`, and a group that does not commit falls back to `publishMutation`, reclaiming a claim its file restoration released); PGLite and refused shapes keep `publishMutation`. The waiter's own wake (`wake(true)`) claims without the periodic scans (recovery records still block the claim through `claimableWriteSql`); preparation reads the config table once (`config-snapshot.ts`) and sends its independent reads together; the coordinated (`coordinated: true`) put_page apply reuses the publisher's locked read as the import base, pipelines its follow-up statements and reads the page once after its last write for the read-back check, seal, core notice and receipt. Publication, the own admission and the recovery transactions run on the consumer's reserved lane (`onLane`: the idle-probe connection, taken while two other pool connections stay free and kept across writes; never lent while an idle probe runs on it, and probes skip it while lent), so their prepared statements stay warm; the waiter is told of the commit before the recovery record is cleared. `preadmit-cache.ts` (with `preadmit_cache` on, Postgres) answers the brain id, source row, worktree binding and local-writer reads of `submitPageMutation` from a per-engine cache (30 s, keyed by brain id; absences never cached); admission rechecks each under lock and the brain id against its protocol statement, and a refusal the cache could explain (`source_changed`, `permission_denied`, a changed brain) drops the cache and runs the whole preparation once more uncached. Pinned by `test/e2e/single-write-fast-path-postgres.test.ts` (switches, cache rechecks, replay, restoration after a failure past the file rename, the recovery-blocked direct claim) and `test/single-write-group-parity.test.ts` + `test/e2e/single-write-group-parity-postgres.test.ts` (row-for-row parity with the switches off); measured by `scripts/bench/foreground-put-page.ts`.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index 239d4ff492..ce5cd209fb 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -371,7 +371,12 @@ The admin health indicators count it as `accepted_pending`, outside the error
rate, with `pending_writes`, `oldest_pending_write_age_seconds` and
`pending_writes_later_failed`. `owner_unavailable`
and `writer_lock_unavailable` do not authorize a competing owner or a fresh
-request ID. `queue_capacity` refuses additional admission without evicting
+request ID. A process that cannot open the worktree lock file at all (a sandbox,
+an unwritable lock directory) leaves its write `queued` with
+`blocked_reason: writer_lock_unavailable` (receipt `next_action:
+inspect_owner`) for an owner process that can take the lock; retrying from the
+same process fails the same way, and the OS error stays in the owner-only
+detail. `queue_capacity` refuses additional admission without evicting
existing requests. `revision_required`, `revision_conflict`,
`idempotency_conflict`, and `source_changed` require correcting the caller's
intent or authority. `recovery_required` names unresolved publication state.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 277a65361a..3634fcc101 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -442,7 +442,7 @@ export const CODES = {
writer_coordinator_required: { class: 'host_only', summary: "The operation needs managed persistence (a writer coordinator) on the brain host." },
writer_identity_invalid: { class: 'host_only', summary: "The local writer identity is invalid." },
writer_identity_publish_failed: { class: 'host_only', summary: "The replacement writer is durable but its credential file could not be published." },
- writer_lock_unavailable: { class: 'retryable', summary: "Another activation probe is running." },
+ writer_lock_unavailable: { class: 'retryable', summary: "A writer lock could not be taken: another process holds it (busy), or this process cannot open the lock file at all.", why: "Busy clears when the holder finishes. A process that cannot open the lock file (a sandbox, an unwritable lock directory) fails the same way on every retry, so its write stays queued with blocked_reason writer_lock_unavailable until an owner process that can take the lock publishes it; the OS error is kept in the owner-only detail.", suggestion: 'For a queued write, wait for the owner (gbrain sources writer status --json names it) or run the write from a process that can open the lock directory; retrying from the same sandboxed process changes nothing.' },
writer_manifest_mismatch: { class: 'caller', summary: "Successor checkout differs from the recorded canonical manifest." },
writer_manifest_rescope_required: { class: 'host_only', summary: "A writer transfer prepared by an older release covers every file of the old checkout, ignored files included, so a clean Git clone cannot match it.", why: "Transfer manifests now cover the files Git tracks, so ignored secrets such as .env files are never read, hashed or required on the successor; a manifest recorded before that change is prepared again instead of asking the user to copy ignored files.", docs: 'docs/architecture/topologies.md#transfer-manifest-scope', suggestion: 'On the owner host, run gbrain sources writer transfer prepare <source> again with its admin intent and state, then accept with the new epoch and manifest.' },
writer_manifest_unsafe: { class: 'caller', summary: "The canonical worktree manifest cannot be recorded safely: the checkout holds a symlink or a Git submodule, a Git-scoped comparison ran on a directory Git cannot list, or Git cannot read a directory that holds .git." },
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 630491242f..7e6acd7f51 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -30,10 +30,11 @@ import { releaseAbandonedClaims } from './effect-journal.ts';
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';
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. */
-type RootHold = { until?: Promise<void> };
+type RootHold = { until?: Promise<void>; retryAfterMs?: number };
/** #6278: the budgets and switch in effect for this tick's claims; a test may pin them through `opts.preparationBudgets`. */
export type EffectivePreparationPolicy = PreparationPolicy & { deadlines: boolean };
/** #6278: an abandoned preparation that outlived the hard ceiling; it pins whatever its await holds until it settles. */
@@ -593,7 +594,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
let progressed = false;
const root: RootHold = {};
const task = this.executeOrGroup(row, root).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
- if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
+ if (!progressed) this.rootRetryAfter.set(key, Date.now() + (root.retryAfterMs ?? this.opts.pollMs ?? 250));
else { this.progressWake = true; this.publishedSinceMaintenance++; }
this.active.delete(task);
// The slot is free now; the root (or lane slot) waits for an abandoned preparation so nothing on it overtakes that work.
@@ -848,6 +849,10 @@ export class PersistenceConsumer implements PersistenceConsumerLike {
await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });
const { done, settled } = await this.publishSingle(row, prepared);
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`);
+ }
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.ts
index a025fe63a2..e61d399980 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -17,7 +17,7 @@ import { chargePreparationAttempt, clearResolvedRecovery, completeWrite, getWrit
import 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 type { NativeLockHandle } from './native-lock.ts';
+import { isLockOpenFailure, type NativeLockHandle } from './native-lock.ts';
import { withCoordinatedWrite } from './context.ts';
import { lockCoreSources } from './core-guard.ts';
import { publicationAttribution } from './attribution.ts';
@@ -278,7 +278,13 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
await releaseUnpublishedClaim(engine, row, 'owner_unavailable');
return (await getWriteRequestById(engine, row.id))!;
}
- lock = await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true });
+ try { lock = await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true }); }
+ catch (error) {
+ // #6305: this process cannot open the lock file (sandbox, unwritable lock directory): like a busy lock, publish nothing.
+ if (!isLockOpenFailure(error)) throw error;
+ await releaseUnpublishedClaim(engine, row, 'writer_lock_unavailable');
+ return (await getWriteRequestById(engine, row.id))!;
+ }
if (!lock) {
await releaseUnpublishedClaim(engine, row, 'writer_busy');
return (await getWriteRequestById(engine, row.id))!;
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 6114876c1a..039ecc88b2 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -41,6 +41,7 @@ import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
+import { isLockOpenFailure } from './native-lock.ts';
const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(
`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,
@@ -403,7 +404,7 @@ function embeddingStorageFailure(error: unknown): unknown {
}
async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, error: unknown, signal?: AbortSignal, target?: string): Promise<void> {
- const code = error instanceof OperationError ? error.code : 'effect_unavailable';
+ const code = error instanceof OperationError ? error.code : isLockOpenFailure(error) ? error.code : 'effect_unavailable';
// Source replacement is final only without recovery. Unknown physical bytes
// retain their record and continue to block this root for explicit repair.
if (code === 'source_changed' && !effect.recovery) {
@@ -453,7 +454,8 @@ async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, err
/** Waits that say nothing about the target never count toward parking. */
const CONTENTION_CODES = ['projection_pending', 'revision_conflict', 'writer_busy', 'writer_pool_capacity', 'git_index_locked'];
-const DEPENDENCY_CODES = ['recovery_required', 'owner_unavailable', 'write_claim_lost', 'queue_capacity'];
+// #6305: writer_lock_unavailable is this process failing to open the lock file, not the effect failing; it never parks the effect.
+const DEPENDENCY_CODES = ['recovery_required', 'owner_unavailable', 'write_claim_lost', 'queue_capacity', 'writer_lock_unavailable'];
/**
* A scan sets its failing target aside and moves on; a single-target effect,
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index b33a388941..a5d1477ad6 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -36,6 +36,7 @@ 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 { 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 { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markDispatched, markRecovering, prepareRecoveries,
@@ -213,8 +214,16 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
// lease and publishes beside them; everything else takes it exclusively.
// With this process's lanes open on the worktree but none publishing, it opens the lease for them to join.
const beside = !lane && rows.length === 1 && singleWrite(head) && await foregroundPriority(engine);
- const joined = beside ? joinWorktreeLease(binding) ?? ((lanePolicy(head.worktree_id)?.effective ?? 1) > 1 ? await acquireWorktreeShared(binding, engine) : null) : null;
- const lock = lane ? await acquireWorktreeShared(binding, engine) : joined ?? await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true });
+ let joined: NativeLockHandle | null, lock: NativeLockHandle | null;
+ try {
+ joined = beside ? joinWorktreeLease(binding) ?? ((lanePolicy(head.worktree_id)?.effective ?? 1) > 1 ? await acquireWorktreeShared(binding, engine) : null) : null;
+ lock = lane ? await acquireWorktreeShared(binding, engine) : joined ?? await acquireWorktree(binding, 0, undefined, engine, { yieldLanes: true });
+ } catch (error) {
+ // #6305: this process cannot open the lock file. A lane group retries as busy; a single write falls through to
+ // publishMutation (row still running, same token), which releases it for an owner as writer_lock_unavailable.
+ if (!isLockOpenFailure(error)) throw error;
+ return lane ? { ...none, reason: 'busy' } : none;
+ }
if (!lock) return { ...none, reason: 'busy' };
if (joined) publishingBeside.add(head.id);
if (lane) lane.coordinationPath ??= binding.coordination_path;
diff --git a/src/core/persistence/health.ts b/src/core/persistence/health.ts
index 5678c96b99..3a8d212352 100644
--- a/src/core/persistence/health.ts
+++ b/src/core/persistence/health.ts
@@ -7,6 +7,9 @@ export interface WriteHealthFacts {
owner_unavailable?: boolean;
inspect_owner?: boolean;
}
+/** How long a receipt that needs an owner's inspection asks callers to wait; #6305: also how long a consumer holds a root it cannot lock. */
+export const INSPECT_OWNER_RETRY_MS = 30_000;
+
export function writeHealth(row: { state: WriteRequestState; created_at: Date | string; blocked_reason?: string | null },
facts: WriteHealthFacts = {}, now = Date.now()): { retry_after_ms: number | null; diagnostic?: WriteDiagnostic } {
if (isTerminalWriteState(row.state)) return { retry_after_ms: null };
@@ -21,7 +24,7 @@ export function writeHealth(row: { state: WriteRequestState; created_at: Date |
const unknown = reason === 'pending' || reason === 'cause_unknown';
if (aged && unknown) reason = 'cause_unknown';
const inspect = aged || unexpected || facts.inspect_owner || ['writer_pool_capacity', 'owner_unavailable', 'writer_lock_unavailable'].includes(reason);
- return { retry_after_ms: inspect ? 30_000 : !unknown || age >= 30_000 ? 5000 : 1000,
+ return { retry_after_ms: inspect ? INSPECT_OWNER_RETRY_MS : !unknown || age >= 30_000 ? 5000 : 1000,
diagnostic: { age_ms: age, assessment: unknown ? aged ? 'stalled' : 'pending' : 'blocked', reason,
next_action: inspect ? 'inspect_owner' : 'poll', ...(facts.observed_at ? { observed_at: facts.observed_at } : {}) } };
}
diff --git a/src/core/persistence/native-lock.ts b/src/core/persistence/native-lock.ts
index 0748843616..62a5681bdb 100644
--- a/src/core/persistence/native-lock.ts
+++ b/src/core/persistence/native-lock.ts
@@ -2,6 +2,7 @@
import { mkdir } from 'node:fs/promises';
import { dirname, isAbsolute } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
+import { constants as osConstants } from 'node:os';
import { family, GLIBC, MUSL } from 'detect-libc';
export interface NativeExportPublisher {
@@ -22,12 +23,35 @@ interface NativeBinding extends NativeExportPublisher {
export class NativeLockUnavailableError extends Error {
readonly code = 'writer_lock_unavailable';
- constructor(message = 'Native writer locking is unavailable on this host', cause?: unknown) {
- super(message, { cause });
+ /** #6305: 'open' when this process could not create or open the lock file itself (its directory or the file), as opposed to an addon, close or IPC failure. */
+ readonly stage?: 'open';
+ /** #6305: the OS error behind the failure (`EACCES`, `EISDIR`, `os_error_5`), when the cause names one. */
+ readonly osError?: string;
+ constructor(message = 'Native writer locking is unavailable on this host', cause?: unknown, stage?: 'open') {
+ const osError = nativeLockOsError(cause);
+ super(osError ? `${message} (${osError})` : message, { cause });
this.name = 'NativeLockUnavailableError';
+ if (stage) this.stage = stage;
+ if (osError) this.osError = osError;
}
}
+/** #6305: this process could not create or open the lock file; a busy lock returns null instead. */
+export function isLockOpenFailure(error: unknown): error is NativeLockUnavailableError {
+ return error instanceof NativeLockUnavailableError && error.stage === 'open';
+}
+
+/** A node:fs error code, or the native addon's `(OS error N)` as its errno name (`os_error_N` when the platform has no name). */
+export function nativeLockOsError(cause: unknown): string | undefined {
+ const code = (cause as { code?: unknown } | null)?.code;
+ if (typeof code === 'string' && /^E[A-Z0-9]+$/.test(code)) return code;
+ const match = /\(OS error (\d+)\)/.exec(cause instanceof Error ? cause.message : '');
+ if (!match || match[1] === '0') return undefined;
+ const errno = Number(match[1]);
+ if (process.platform === 'win32') return `os_error_${errno}`;
+ return Object.entries(osConstants.errno).find(([, value]) => value === errno)?.[0] ?? `os_error_${errno}`;
+}
+
export interface NativeLockHandle {
/** True after release. A released handle must not authorize further work. */
readonly released: boolean;
@@ -124,7 +148,7 @@ export async function acquireNativeLock(path: string, options: NativeLockOptions
handle = binding.openLock(path);
} catch (cause) {
if (signal?.aborted) throw signal.reason;
- throw new NativeLockUnavailableError('Cannot open the stable writer lock file', cause);
+ throw new NativeLockUnavailableError('Cannot open the stable writer lock file', cause, 'open');
}
let released = false;
const release = async () => {
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 7597ac9433..6f00f803e2 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -112,9 +112,10 @@ export const OWNER_EXCEPTION_MESSAGE = 'Publication failed on an unexpected owne
/** #5929: the bounded identity of an unexpected owner exception (class, errno, frame), kept owner-only. */
export function ownerExceptionFailure(error: unknown): PublicationFailure {
- const e = (error && typeof error === 'object' ? error : {}) as { constructor?: { name?: unknown }; code?: unknown; errno?: unknown; stack?: unknown };
+ const e = (error && typeof error === 'object' ? error : {}) as { constructor?: { name?: unknown }; code?: unknown; errno?: unknown; stack?: unknown; osError?: unknown };
const errorClass = ident(e.constructor?.name);
- const raw = typeof e.code === 'string' ? e.code : typeof e.errno === 'number' ? String(e.errno) : undefined;
+ // #6305: an error that names the OS error behind it (a native lock failure) reports that, not its gbrain code.
+ const raw = typeof e.osError === 'string' ? e.osError : typeof e.code === 'string' ? e.code : typeof e.errno === 'number' ? String(e.errno) : undefined;
const errno = raw && ERRNO.test(raw) ? raw : undefined;
const frame = gbrainFrame(e.stack);
return { code: 'storage_error', message: OWNER_EXCEPTION_MESSAGE,
diff --git a/test/e2e/persistence-lock-open-failure-postgres.test.ts b/test/e2e/persistence-lock-open-failure-postgres.test.ts
new file mode 100644
index 0000000000..cb41ef5a71
--- /dev/null
+++ b/test/e2e/persistence-lock-open-failure-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-lock-open-failure.test.ts'));
diff --git a/test/persistence-effects.test.ts b/test/persistence-effects.test.ts
index 22f708a855..0f29a50175 100644
--- a/test/persistence-effects.test.ts
+++ b/test/persistence-effects.test.ts
@@ -298,3 +298,27 @@ test('Git retry disables legacy hooks, preserves unrelated staging and never reb
expect(await publishGitEffect(root, 'page.md')).toMatchObject({ git: 'unchanged' });
expect(git(root, ['rev-parse', 'HEAD'])).toBe(head);
});
+
+test('#6305: a Git effect this process cannot lock never parks and commits once the lock opens', async () => {
+ const f = await fixture();
+ durableGitRepo(f.root, ['page.md']);
+ const admitted = await admit(f);
+ const row = (await claimNextWrite(engine, hostId))!;
+ expect(row.id).toBe(admitted.id);
+ const published = await publishMutation(engine, row, { observedRevision: f.snapshot.revision, file: { path: f.file, root: f.root, content: 'After' },
+ apply: async tx => { await tx.putPage('page', page('After'), { sourceId: f.sourceId }); return {}; } }, hostId);
+ expect(published.state).toBe('committed');
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE request_id=$1::uuid AND kind<>'git'", [row.id]);
+ rmSync(f.binding.coordination_path!, { force: true }); mkdirSync(f.binding.coordination_path!);
+ const effect = async () => (await engine.executeRaw<{ state: string; error_code: string | null }>(
+ "SELECT state,error_code FROM persistence_effects WHERE request_id=$1::uuid AND kind='git'", [row.id]))[0];
+ for (let attempt = 0; attempt < 7; attempt++) {
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid AND kind='git'", [row.id]);
+ await runPersistenceEffects(engine, config, { hostId, limit: 1 });
+ }
+ expect(await effect()).toMatchObject({ state: 'queued', error_code: 'writer_lock_unavailable' });
+ rmSync(f.binding.coordination_path!, { recursive: true, force: true });
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid AND kind='git'", [row.id]);
+ await runPersistenceEffects(engine, config, { hostId, limit: 1 });
+ expect((await effect())!.state).toBe('committed');
+});
diff --git a/test/persistence-lock-open-failure.test.ts b/test/persistence-lock-open-failure.test.ts
new file mode 100644
index 0000000000..acc8419dd7
--- /dev/null
+++ b/test/persistence-lock-open-failure.test.ts
@@ -0,0 +1,131 @@
+/**
+ * #6305: a process that cannot open the worktree lock file leaves its write for an owner instead of failing it.
+ *
+ * Protects: an unopenable lock (a directory where the lock file belongs: EISDIR from the native addon; a file where its
+ * directory belongs: EEXIST from mkdir) is a typed open failure carrying the OS error; `publishMutation` and, on Postgres,
+ * the single-write group path (`publishSingleWrite` → `publishGroup`, the path PR #6310 missed) release the claim as
+ * `queued` / `writer_lock_unavailable` with no page written, and an owner that can open the lock publishes the same request
+ * later. Negative controls: an EISDIR on the brain path (the page's own file) still fails terminally with `storage_error`,
+ * and an addon/close failure is not an open failure. `ownerExceptionFailure` reports the OS error, not the gbrain code.
+ * Test idea from PR #6310 (@andreineacsu).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { acquireNativeLock, isLockOpenFailure, NativeLockUnavailableError, nativeLockOsError } from '../src/core/persistence/native-lock.ts';
+import { ownerExceptionFailure } from '../src/core/persistence/publication-failure.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite, getWriteRequestById } from '../src/core/persistence/journal.ts';
+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 { publishSingleWrite } from '../src/core/persistence/group-publish.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { _resetWriteThroughCacheForTest } from '../src/core/write-through.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const putPage = operations.find(o => o.name === 'put_page')!;
+const page = (body: string) => `---\ntitle: Example\ntype: note\n---\n\n${body}\n`;
+
+describe('native lock open failures are typed and carry the OS error', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-lock-open-'));
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
+ test('a directory at the lock path is EISDIR; a file where its directory belongs is EEXIST (mkdir); both are open failures', async () => {
+ const asDir = join(dir, 'busy.lock'); mkdirSync(asDir);
+ const eisdir = await acquireNativeLock(asDir, { timeoutMs: 0 }).catch((error: unknown) => error);
+ expect(isLockOpenFailure(eisdir)).toBe(true);
+ expect((eisdir as NativeLockUnavailableError).osError).toBe('EISDIR');
+ expect((eisdir as Error).message).toContain('(EISDIR)');
+ const parent = join(dir, 'file'); writeFileSync(parent, 'x');
+ const enotdir = await acquireNativeLock(join(parent, 'w.lock'), { timeoutMs: 0 }).catch((error: unknown) => error);
+ expect(isLockOpenFailure(enotdir)).toBe(true);
+ expect((enotdir as NativeLockUnavailableError).osError).toBe('EEXIST');
+ });
+ test('other native lock failures are not open failures; the addon message maps to an errno name', () => {
+ expect(isLockOpenFailure(new NativeLockUnavailableError('Cannot close the writer lock handle; this host must stop publishing'))).toBe(false);
+ expect(isLockOpenFailure(Object.assign(new Error('Cannot open'), { code: 'writer_lock_unavailable' }))).toBe(false);
+ 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('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' });
+ });
+});
+
+for (const kind of testBackends()) {
+ describe(`a write this process cannot lock waits for an owner (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let root = '';
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-lock-open-home-'));
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engine = lite; close = () => lite.disconnect(); }
+ }, 120_000);
+ afterAll(async () => { await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine)); await close?.(); rmSync(home, { recursive: true, force: true }); });
+ beforeEach(async () => {
+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));
+ if (kind === 'pglite') await resetPgliteState(engine as PGLiteEngine);
+ _resetWriteThroughCacheForTest();
+ if (kind === 'postgres' && root) return;
+ root = mkdtempSync(join(home, 'brain-'));
+ await engine.setConfig('sync.repo_path', root);
+ if (kind === 'postgres') {
+ // Postgres binds no worktree on first write; claim it once for this file (a second claim would need a transfer).
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("UPDATE sources SET local_path=$1 WHERE id='default'", [root]);
+ await withEnv({ GBRAIN_HOME: home }, () => claimWorktree(engine, 'default', root));
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ });
+ const context = (): OperationContext => ({ engine, config: { engine: kind, embedding_disabled: true } as OperationContext['config'],
+ logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' });
+
+ /** Admits and claims one put_page of `slug` the way the resident consumer would, after a first write bound the worktree. */
+ async function claimedPut(slug: string) {
+ await putPage.handler(context(), { slug: `notes/bootstrap-${randomUUID().slice(0, 8)}`, content: page('Binds the worktree.'), request_id: randomUUID() });
+ await disposePersistenceConsumer(engine);
+ const binding = (await getWorktreeBinding(engine, 'default'))!;
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const authority = await submissionAuthority(context(), 'put_page', 'default', source!.incarnation, slug);
+ const intent = { content: page('Written by a process that cannot lock.') };
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default', sourceIncarnation: source!.incarnation,
+ slug, pageId: null, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation, requestId: randomUUID(), callerIntent: intent, intent });
+ const row = (await claimNextWrite(engine, localHostId()))!;
+ return { row, binding, prepared: await preparePageMutation(engine, row, context().config) };
+ }
+ const publish = kind === 'postgres' ? publishSingleWrite : publishMutation;
+
+ test('an unopenable lock leaves the write queued as writer_lock_unavailable; an owner that can lock publishes it', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { row, binding, prepared } = await claimedPut('notes/locked-out');
+ rmSync(binding.coordination_path!, { force: true }); mkdirSync(binding.coordination_path!);
+ const released = await publish(engine, row, prepared);
+ expect(released).toMatchObject({ state: 'queued', blocked_reason: 'writer_lock_unavailable' });
+ expect(await engine.getPage('notes/locked-out', { sourceId: 'default' })).toBeNull();
+ rmSync(binding.coordination_path!, { recursive: true, force: true });
+ const again = (await claimNextWrite(engine, localHostId()))!;
+ expect(again.id).toBe(row.id);
+ const committed = await publish(engine, again, await preparePageMutation(engine, again, context().config));
+ expect(committed.state).toBe('committed');
+ expect((await getWriteRequestById(engine, row.id))?.state).toBe('committed');
+ expect(await engine.getPage('notes/locked-out', { sourceId: 'default' })).not.toBeNull();
+ }), 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 });
+ const failed = await publish(engine, row, prepared);
+ expect(failed).toMatchObject({ state: 'failed', error_code: 'storage_error' });
+ }), 120_000);
+ });
+}