Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): effects get the worktree under cross-process contention; GC and shared-read cancel flakes (GBRA-133 wave 7)
garrytane92c5253cea5
diff --git a/src/commands/doctor/checks/parked-effects.ts b/src/commands/doctor/checks/parked-effects.tsindex 1ebb031a09..62dc692c8a 100644--- a/src/commands/doctor/checks/parked-effects.ts+++ b/src/commands/doctor/checks/parked-effects.ts@@ -64,12 +64,17 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: stringconst reclaims = recentIndexLockReclaims();// #7010: per source, Git effects whose commit did not reach the remote, with the one command that moves them.const pushHolds = await (await import('../../../core/persistence/git-push-holds.ts')).readGitPushHolds(engine, sourceIds);- const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects, git_push_holds: pushHolds, ...(reclaims ? { index_lock_reclaims: reclaims } : {}) };+ // GBRA-133: per source, effects that have waited on a busy worktree for over 10 minutes (a catch-up that does not move).+ const stalled = await (await import('../../../core/persistence/effect-catchup.ts')).readStalledCatchups(engine, sourceIds);+ const details = { parked_effects: count, exact: true, inspected: rows.length, truncated: count > rows.length, effects, git_push_holds: pushHolds,+ ...(stalled.length ? { stalled_catchups: stalled } : {}), ...(reclaims ? { index_lock_reclaims: reclaims } : {}) };const conflicts = pushHolds.filter(hold => hold.conflict);const pushNote = pushHolds.length ? ' Git backups not pushed: ' + pushHolds.map(hold => `${hold.source_id} ${hold.retrying} retrying, ${hold.parked} parked (${hold.codes.join(', ')})${hold.conflict? `, CONFLICT in ${hold.conflict.paths.join(', ')}: ask the user which version wins (${hold.fix.argv?.join(' ')})` : hold.parked ? `: ${hold.fix.argv?.join(' ')}` : ''}`).join(' | ') + '.' : '';- if (!count && conflicts.length) return { name: 'parked_effects', status: 'warn', details,- message: `No effect is parked yet, but Git backups are held by a conflict between this machine and the remote.${pushNote}` };+ const stalledNote = stalled.length ? ' Catch-up not progressing: ' + stalled.map(item => `${item.source_id} ${item.stalled_effects} effect(s) have waited on a busy canonical worktree since ${item.busy_since} `+ + `(${item.busy_effects} waiting now, up to ${item.busy_retries} busy retries); see who holds it: ${item.fix.argv?.join(' ')}`).join(' | ') + '.' : '';+ if (!count && (conflicts.length || stalled.length)) return { name: 'parked_effects', status: 'warn', details,+ message: `No effect is parked yet, but ${conflicts.length ? 'Git backups are held by a conflict between this machine and the remote' : 'a backlog of effects is not moving'}.${pushNote}${stalledNote}` };if (!count) return { name: 'parked_effects', status: 'ok', message: `No Git or withdrawal effect is parked.${pushNote}${reclaims ? reclaimNote(reclaims) : ''}`, details };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}`);@@ -79,7 +84,7 @@ export async function checkParkedEffects(engine: BrainEngine, sourceIds?: string(count > rows.length ? ` (first ${rows.length} of ${count} shown)` : '') +(effects.some(effect => effect.parked.some(target => target.error_code === 'git_target_pending'))? '. git_target_pending: Git still lists a removed page file in the index; on Windows close the program holding it open (a sync watcher, indexer or antivirus), check with `git -c core.fscache=false status` on the brain host, then run the retry command.' : '') +- pushNote + (reclaims ? reclaimNote(reclaims) : '') };+ pushNote + stalledNote + (reclaims ? reclaimNote(reclaims) : '') };} catch (error) {return { name: 'parked_effects', status: 'warn',message: `Parked effects could not be read: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 5aa480207b..735f13abbc 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1200,6 +1200,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// GBRA-133 wave 6 (#7402 explicit request_id facts replay; git-durability push probe on a moved remote). `since` is stamped at the merge slot.{ since: '0.60.420.0', text: 'A managed facts write retried with the caller\'s own `request_id` now always returns that request\'s recorded outcome, a retained file refusal included; only a page-triggered or re-admitted facts job rechecks a refusal once its hold clears (#7402).' },{ since: '0.60.420.0', text: '`gbrain sources writer git-durability <source> --enable` no longer refuses with `git_push_unavailable` when the remote branch has commits the checkout lacks (`[rejected] (fetch first)` or `(non-fast-forward)` from the read-only push probe): the Git effect publishes that case itself by merging the remote commits in memory, without pulling into the checkout, so enable succeeds and reports `push_probe.remote_moved: true`. Authentication, permission, protected-branch and unreachable-remote failures are still refused.' },+ // GBRA-133 wave 7 (writer_busy catch-up fairness across processes). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'A Git or mirror effect that finds its canonical worktree held by another gbrain process now waits for it (up to 5 seconds per pass) instead of trying once between that process\'s writes, and once it has waited a second the other process yields: its lane leases drain and its no-wait takes report busy until the effect took its turn. Before, a long sync in one process could win every race for the worktree, so another process\'s backlog of Git effects never ran. Waiters mark themselves beside the worktree\'s coordination lock (`<lock>.waiters/<pid>`); a marker its process stopped refreshing is ignored.' },+ { since: 'TBD', text: 'An effect that still finds its worktree busy retries as `writer_busy` with a backoff that grows per consecutive busy retry (250 ms doubling to 60 s) instead of every 250 ms, and it never parks on contention. Its data records `busy_retries`, `busy_since` and `busy_at`.' },+ { since: 'TBD', text: 'doctor `parked_effects` and `gbrain sources writer status` now report `stalled_catchups`: per source, effects that have waited on a busy canonical worktree for over 10 minutes, with when the wait began and the read-only writer status command that shows who holds the worktree. doctor warns "Catch-up not progressing" for them even when nothing is parked.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/hardened-git.ts b/src/core/hardened-git.tsindex 9f6519ae87..bbd7371b2d 100644--- a/src/core/hardened-git.ts+++ b/src/core/hardened-git.ts@@ -107,12 +107,18 @@ export type HardenedGitInput = string | Buffer | Iterable<Buffer | string> | Asy* returns a promise holds stdout until it settles (a large read yields to the* event loop between chunks); a rejection fails the run like a throw.*/-export async function hardenedGitStream(root: string, args: string[],+export function hardenedGitStream(root: string, args: string[],opts: { stdin?: HardenedGitInput; timeoutMs: number; maxBytes?: number; onChunk?: (chunk: Buffer) => void | Promise<void> }): Promise<HardenedGitStreamResult> {- assertHardenedGitArgs(args);- return await new Promise<HardenedGitStreamResult>((accept, reject) => {+ try { assertHardenedGitArgs(args); } catch (error) { return Promise.reject(error); }+ // GBRA-133: not an async function and no callback below names `opts`, so no timer or listener closes over the caller's+ // options, and the chunk handler is dropped once the read settled. Before, an async function's parameters were captured by+ // every callback here: the exited-stdout idle timer kept the caller's `onChunk` (and through it the whole pass that read)+ // reachable for seconds after the read had ended.+ const { stdin, timeoutMs, maxBytes } = opts;+ let onChunk = opts.onChunk;+ return new Promise<HardenedGitStreamResult>((accept, reject) => {const child = spawn('git', [...HARDENED_GIT_ARGS, '-C', root, ...args],- { env: hardenedGitEnvironment(), stdio: [opts.stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });+ { env: hardenedGitEnvironment(), stdio: [stdin === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });let bytes = 0;let last = -1;let stopped: 'timeout' | 'too_large' | undefined;@@ -121,9 +127,9 @@ export async function hardenedGitStream(root: string, args: string[],let exited = false;let holding = false;let idle: ReturnType<typeof setTimeout> | undefined;- const settle = (outcome: () => void): void => { if (settled) return; settled = true; clearTimeout(timer); clearTimeout(idle); outcome(); };+ const settle = (outcome: () => void): void => { if (settled) return; settled = true; onChunk = undefined; clearTimeout(timer); clearTimeout(idle); outcome(); };const fail = (error: unknown): void => { failure ??= { error }; child.kill('SIGKILL'); };- const timer = setTimeout(() => { stopped ??= 'timeout'; child.kill('SIGKILL'); }, opts.timeoutMs);+ const timer = setTimeout(() => { stopped ??= 'timeout'; child.kill('SIGKILL'); }, timeoutMs);const watchIdle = (): void => {clearTimeout(idle);if (exited && !holding) idle = setTimeout(() => settle(() => failure ? reject(failure.error) : accept({ ok: false, reason: stopped ?? 'stalled' })), EXITED_STDOUT_IDLE_MS);@@ -131,10 +137,10 @@ export async function hardenedGitStream(root: string, args: string[],child.stdout?.on('data', (chunk: Buffer) => {if (settled || stopped || failure) return;bytes += chunk.length;- if (opts.maxBytes !== undefined && bytes > opts.maxBytes) { stopped = 'too_large'; child.kill('SIGKILL'); return; }+ if (maxBytes !== undefined && bytes > maxBytes) { stopped = 'too_large'; child.kill('SIGKILL'); return; }last = chunk[chunk.length - 1] ?? last;let held: void | Promise<void>;- try { held = opts.onChunk?.(chunk); } catch (error) { fail(error); return; }+ try { held = onChunk?.(chunk); } catch (error) { fail(error); return; }if (held) { holding = true; child.stdout?.pause(); held.then(() => { holding = false; watchIdle(); child.stdout?.resume(); }, fail); }watchIdle();});@@ -147,7 +153,7 @@ export async function hardenedGitStream(root: string, args: string[],else if (code !== 0) accept({ ok: false, reason: 'exit', ...(code === null ? {} : { status: code }) });else accept({ ok: true, exitCode: 0, signal: null, bytes, endsWithNul: last === 0 });}));- if (opts.stdin !== undefined && child.stdin) void feedStdin(child.stdin, opts.stdin, fail);+ if (stdin !== undefined && child.stdin) void feedStdin(child.stdin, stdin, fail);});}diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.tsindex 2e7b56c132..1d6a900b73 100644--- a/src/core/persistence/administration.ts+++ b/src/core/persistence/administration.ts@@ -280,6 +280,8 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatiolocal_markers: await cleanupRetiredManagedMarkers(engine),host_id: existingLocalHostId(), local_host_id: existingLocalHostId(), bindings, admin_state: adminState,admin_lock: { locked: adminLock.locked, set_at: adminLock.set_at, host_id: adminLock.host_id }, blocking_effects: blockingEffects,+ // GBRA-133: effects that have waited on a busy canonical worktree for over 10 minutes.+ stalled_catchups: await (await import('./effect-catchup.ts')).readStalledCatchups(engine, params.source_id ? [params.source_id as string] : undefined),writer_versions: writerVersions, onboarding, shared_skills: sharedSkills, ...(native ? { native_lock: native } : {}),// #6317 (B3): every process holding a consumer on this host, from the heartbeat rows (kind, pid, nonce, mode, age, wedge report).host: { host_id: existingLocalHostId(), ...await (await import('./consumer-diagnostics.ts')).hostConsumersReport(engine, existingLocalHostId()) },diff --git a/src/core/persistence/effect-catchup.ts b/src/core/persistence/effect-catchup.tsnew file mode 100644index 0000000000..2ab6b77473--- /dev/null+++ b/src/core/persistence/effect-catchup.ts@@ -0,0 +1,43 @@+/**+ * GBRA-133: an effect catch-up that is not progressing. Effects that find their worktree held by another writer retry as+ * `writer_busy` with a backoff (effect-journal.ts `retryBusyEffect`), which records when each one's busy streak began.+ * This reads, per source, the effects that have waited on the worktree for over `CATCHUP_STALL_MS` without one take:+ * ordinary writes may still commit beside them, but this backlog does not move. Read by doctor (`parked_effects`) and+ * `gbrain sources writer status`.+ */+import type { BrainEngine } from '../engine.ts';+import type { Action } from '../agent-output.ts';+import { readFix } from '../ops/op-fix.ts';++/** How long an effect may wait on a busy worktree before its catch-up counts as not progressing. */+export const CATCHUP_STALL_MS = 10 * 60_000;++export interface StalledCatchup {+ source_id: string;+ /** Effects queued on `writer_busy` whose busy streak began over `CATCHUP_STALL_MS` ago. */+ stalled_effects: number;+ /** All effects of the source queued on `writer_busy` now. */+ busy_effects: number;+ /** When the oldest stalled effect's busy streak began. */+ busy_since: string;+ /** The longest busy streak (consecutive `writer_busy` retries) among them. */+ busy_retries: number;+ fix: Action;+}++export async function readStalledCatchups(engine: BrainEngine, sourceIds?: string[], stallMs = CATCHUP_STALL_MS): Promise<StalledCatchup[]> {+ const rows = await engine.executeRaw<{ source_id: string; stalled: number; busy: number; since: string | Date; retries: number }>(+ `SELECT e.source_id,+ count(*) FILTER (WHERE (e.data->>'busy_since')::timestamptz < now() - ($2::double precision * interval '1 millisecond'))::int AS stalled,+ count(*)::int AS busy, min((e.data->>'busy_since')::timestamptz) AS since, COALESCE(max((e.data->>'busy_retries')::int), 0)::int AS retries+ FROM persistence_effects e+ WHERE e.state='queued' AND e.error_code='writer_busy' AND e.data ? 'busy_since' AND ($1::text[] IS NULL OR e.source_id=ANY($1::text[]))+ GROUP BY e.source_id ORDER BY e.source_id`, [sourceIds ?? null, stallMs]);+ return rows.filter(row => Number(row.stalled) > 0).map(row => ({+ source_id: row.source_id, stalled_effects: Number(row.stalled), busy_effects: Number(row.busy), busy_since: new Date(row.since).toISOString(),+ busy_retries: Number(row.retries),+ fix: readFix(`Lists the processes on this host that hold or wait for source ${row.source_id}'s canonical worktree, and its retrying effects, read-only. `+ + 'A process that keeps the worktree for minutes at a time (a long sync or a stuck job) is what this backlog waits behind.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] }),+ }));+}diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 75e9465a88..ccf4cbee35 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -361,6 +361,22 @@ export async function retryEffect(engine: SqlEngine, effect: PersistenceEffect,next_attempt_at=now()+($4::double precision*interval '1 millisecond'),updated_at=now()WHERE id=$1 AND execution_token=$2::uuid AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [effect.id, effect.execution_token, reason, delayMs]);}+/** GBRA-133: the longest a `writer_busy` effect waits before its next claim. */+export const BUSY_RETRY_MAX_MS = 60_000;+/**+ * GBRA-133: a `writer_busy` retry backs off per consecutive busy retry (250 ms doubling to `BUSY_RETRY_MAX_MS`), so a+ * catch-up that cannot take the worktree stops claiming its effects several times a second. A streak whose last busy+ * retry is over two caps old starts again. It never parks: contention says nothing about the target.+ */+export async function retryBusyEffect(engine: SqlEngine, effect: PersistenceEffect, now = Date.now()): Promise<void> {+ const last = Date.parse(effect.data.busy_at ?? '');+ const streak = Number.isFinite(last) && now - last < 2 * BUSY_RETRY_MAX_MS ? (effect.data.busy_retries ?? 0) + 1 : 1;+ const busy = { busy_retries: streak, busy_since: streak > 1 && effect.data.busy_since ? effect.data.busy_since : new Date(now).toISOString(), busy_at: new Date(now).toISOString() };+ await engine.executeRaw(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,claim_owner=NULL,error_code='writer_busy',+ data=data||$3::text::jsonb,next_attempt_at=now()+($4::double precision*interval '1 millisecond'),updated_at=now()+ WHERE id=$1 AND execution_token=$2::uuid AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,+ [effect.id, effect.execution_token, JSON.stringify(busy), Math.min(BUSY_RETRY_MAX_MS, 250 * 2 ** Math.min(streak - 1, 8))]);+}/** Release a claim with replacement bookkeeping; parking never applies while recovery is recorded. */export async function requeueEffect(engine: SqlEngine, effect: PersistenceEffect, data: PersistenceEffect['data'], reason: string | null, delayMs: number): Promise<void> {await engine.executeRaw(`UPDATE persistence_effects SET state='queued',data=$3::text::jsonb,execution_token=NULL,claim_expires_at=NULL,claim_owner=NULL,error_code=$4,diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex 26f0866a52..846ec0a845 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -81,6 +81,10 @@ export interface PersistenceEffect {commit_trailer?: string;/** Consecutive execution failures of the current Git or withdrawal target. */target_failures?: number;+ /** GBRA-133: consecutive `writer_busy` retries of this streak, when the streak began and when its last retry was recorded (ISO). */+ busy_retries?: number;+ busy_since?: string;+ busy_at?: string;/** The target `target_failures` belongs to; a different target starts from zero. */failing_target?: string;/** Targets set aside after repeated failures; a slugless entry parks the whole effect. */diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex b1de6d0e06..dda24593ca 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -30,14 +30,15 @@ import { EMBEDDING_ZERO_NORM, isEmbeddingZeroNormError, type EmbeddingZeroNormErimport { isAIInvocationPolicyError, withAIInvocationPreflight } from '../ai/invocation-guard.ts';import { quoteIdentifier } from '../search/embedding-column.ts';import type { ResolvedColumn } from '../types.ts';-import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';+import { acquireWorktree, acquireWorktreeWaiting, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';+import { clearWaiting } from './worktree-lease.ts';import { persistenceFileHash, transientDatabaseFailure } from './coordinator.ts';import { sha256 } from './digest.ts';import { prepareFileTarget, unreadPageFile } from './page-prepare.ts';import { isStreamedContent, type StreamedFileContent } from './large-file.ts';import { atomicStagingPath } from '../atomic-write.ts';import { isSourceDbOnlySlug } from './source-storage.ts';-import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, effectClaimStamp, effectClaimKeeper, failEffect, hasRearmableTargets, mirrorGates, parkEffect, rearmWithheldTargets, renewPersistenceEffectClaim, requeueEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';+import { advanceEffectCursor, claimCoalescedGitEffects, claimPersistenceEffect, completeEffect, effectClaimStamp, effectClaimKeeper, failEffect, hasRearmableTargets, mirrorGates, parkEffect, rearmWithheldTargets, renewPersistenceEffectClaim, requeueEffect, retryBusyEffect, retryEffect, singleFileGitEffect, type MirrorGate } from './effect-journal.ts';import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } from './effect-recovery.ts';import { commitGitTargets, DURABILITY_NOT_ENABLED, gitRootAhead, publishGitEffect, pushGitRoot, type GitEffectOwner } from './effect-git.ts';import { retryIndexLockParks } from './effect-retry.ts';@@ -670,6 +671,7 @@ async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, err: transientBackoffMs(attempt - 1);await retryEffect(engine, effect, reason, delay); return;}+ if (code === 'writer_busy') { await retryBusyEffect(engine, effect); return; }if (CONTENTION_CODES.includes(code)) { await retryEffect(engine, effect, code, 250); return; }// A lost connection, a failed transaction or an abort is never the effect's own failure (GBRA-130); for links and// facts-backstop effects neither is a run-scoped refusal.@@ -749,6 +751,8 @@ async function parkEffectTarget(engine: BrainEngine, effect: PersistenceEffect,...(remaining.length ? { retry_slugs: remaining, target_failures: PARK_AFTER_FAILURES - 1 } : {}) }, code, 0);}+/** GBRA-133: how long one effect pass waits for a contended worktree before its effects back off as writer_busy. */+const EFFECT_LOCK_WAIT_MS = 5_000;/** #5530: at most this many single-file Git effects share one commit. */const GIT_GROUP_SIZE = 100;/** A short Git group yields to queued publications at most this many claims, GIT_YIELD_MS apart. */@@ -781,8 +785,10 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC// #6696 (A1): every request whose effect this pass claimed is trued up after the pass, outside the settling transactions.const touched = new Set<string>();const derived: DerivedFailures = { run: new ItemRun('effects.derived_retry_budget'), counted: [] };- try { return await runEffectPass(engine, config, opts, touched, derived); }+ const waited = new Set<string>();+ try { return await runEffectPass(engine, config, opts, touched, derived, waited); }finally {+ for (const path of waited) clearWaiting(path);await settleDerivedFailures(engine, derived).catch(() => { /* an unsettled claim expires and the effect is claimed again */ });await (async () => { if (await hasRearmableTargets(engine, [...touched])) await engine.transaction(tx => rearmWithheldTargets(tx, [...touched])); })().catch(() => { /* idempotent; the next pass touching the request retries it */ });@@ -790,8 +796,20 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC}}-async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions, touched: Set<string>, derived: DerivedFailures): Promise<number> {+async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions, touched: Set<string>, derived: DerivedFailures,+ waited: Set<string>): Promise<number> {const limit = Math.max(1, Math.min(opts.limit ?? 2, 20));+ // GBRA-133: a Git or mirror effect waits for a contended worktree (other processes yield to it after a grace) instead of+ // trying once per claim; a root this pass already waited out is tried once, so one busy root costs the pass one wait.+ const stalled = new Set<string>();+ const takeLock = async (binding: WorktreeBinding) => {+ const path = binding.coordination_path ?? '';+ if (stalled.has(path)) return acquireWorktree(binding, 0, undefined, engine);+ waited.add(path);+ const lock = await acquireWorktreeWaiting(binding, engine, EFFECT_LOCK_WAIT_MS, opts.signal);+ if (!lock) stalled.add(path);+ return lock;+ };await resumeGatedMirrors(engine, opts.hostId);const recoveries = await selectEffectRecoveries(engine, opts.hostId, limit);let attempted = 0;@@ -817,7 +835,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Eftry {if (effect.worktree_id && !['embedding', 'facts-backstop', 'links'].includes(effect.kind)) {if (!binding) throw ownerUnavailable(effect);- lock = await acquireWorktree(binding, 0, undefined, engine);+ lock = await takeLock(binding);if (!lock) throw writerBusy(effect);if (recordOnly) { await lock.release(); lock = null; }}@@ -880,7 +898,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Eflet gates: Map<string, MirrorGate>;try {gates = await mirrorGates(engine, effects.map(effect => effect.request_id));- lock = await acquireWorktree(binding, 0, undefined, engine);+ lock = await takeLock(binding);if (!lock) throw writerBusy(effects[0]!);} catch (error) {for (const effect of effects) await recordFailure(engine, effect, error, opts.signal);@@ -1029,7 +1047,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Eflet failure: unknown;let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;try {- lock = await acquireWorktree(binding, 0, undefined, engine);+ lock = await takeLock(binding);if (!lock) throw writerBusy(items[0]!.effect);pushed = await pushGitRoot(root, opts.signal);} catch (error) { failure = error; } finally { await lock?.release(); }diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.tsindex b5344b9be2..bd36c0e143 100644--- a/src/core/persistence/ownership.ts+++ b/src/core/persistence/ownership.ts@@ -15,7 +15,7 @@ import { localHostId } from './identity.ts';import { repairWedgedReservation, resolveCoordinationLock } from './coordination-lock.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';-import { acquireShared, deferToLease, exclusiveAcquired, joinLease, yieldLease } from './worktree-lease.ts';+import { acquireShared, deferToLease, exclusiveAcquired, foreignWaiterAhead, joinLease, noteWaiting, yieldLease } from './worktree-lease.ts';import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { assertPhysicalRoot, claimPhysicalRoot, preparePhysicalRootTransfer, readPhysicalRootReservation, restampPhysicalRoot } from './physical-root.ts';import { assertPhysicalRootReservation, readPhysicalRootStamp } from './physical-root-record.ts';@@ -169,10 +169,31 @@ export async function acquireWorktree(binding: WorktreeBinding, waitMs = 0, signif (!binding.local_path || !binding.coordination_path) return null;// #5984 lanes: an exclusive writer drains this process's lane lease first; while lanes still hold it the worktree is busy.if (waitMs <= 0 && !opts.yieldLanes ? !deferToLease(binding.coordination_path) : !await yieldLease(binding.coordination_path, waitMs, signal)) return null;+ // GBRA-133: a no-wait take yields to another process's background writer that has waited its grace (worktree-lease.ts).+ if (waitMs <= 0 && foreignWaiterAhead(binding.coordination_path)) return null;const lock = await lockWorktree(binding, waitMs, signal, engine, opts.identity);if (lock) exclusiveAcquired(binding.coordination_path);return lock;}++/** GBRA-133: how often a waiting background writer retries the worktree lock. */+const WAITING_POLL_MS = 25;+/**+ * GBRA-133: a background writer's (the effect worker's) take of the worktree lock under cross-process contention. It+ * retries the no-wait take for up to `waitMs` and leaves a marker that other processes yield to once it has waited+ * (worktree-lease.ts `noteWaiting`). The marker stays after the take, so the writer's next take in the same turn goes+ * first again; the caller ends its turn with `clearWaiting`.+ */+export async function acquireWorktreeWaiting(binding: WorktreeBinding, engine: BrainEngine, waitMs: number, signal?: AbortSignal): Promise<NativeLockHandle | null> {+ if (!binding.local_path || !binding.coordination_path) return null;+ const deadline = Date.now() + waitMs;+ for (;;) {+ noteWaiting(binding.coordination_path);+ const lock = await acquireWorktree(binding, 0, signal, engine);+ if (lock || Date.now() >= deadline || signal?.aborted) return lock;+ await new Promise(resolve => setTimeout(resolve, WAITING_POLL_MS));+ }+}/** #5984 lanes: database-only lane publications share one native lock in this process (worktree-lease.ts). */export async function acquireWorktreeShared(binding: WorktreeBinding, engine: BrainEngine): Promise<NativeLockHandle | null> {if (!binding.local_path || !binding.coordination_path) return null;diff --git a/src/core/persistence/worktree-lease.ts b/src/core/persistence/worktree-lease.tsindex fae7e86579..9a725759af 100644--- a/src/core/persistence/worktree-lease.ts+++ b/src/core/persistence/worktree-lease.ts@@ -17,7 +17,19 @@* `LEASE_TURN_MS` of continuous holding: lanes already claimed still join it,* but no new lane is claimed until it ends, so writers in other processes,* which cannot mark it, still get a turn.+ *+ * GBRA-133: across processes, every take of the native lock is a poll, so a+ * process that releases the lock and takes it again at once (a sync drain's+ * publications, one lane lease ending and the next starting) wins every race+ * against an effect worker that tries between claims, and a catch-up of Git+ * effects never runs. A background writer that waits therefore leaves a marker+ * beside the lock (`<lock>.waiters/<pid>`, refreshed while it waits). Once the+ * oldest live marker of another process has waited `FOREIGN_WAIT_GRACE_MS`,+ * this process's lanes drain and its no-wait takes report busy, until that+ * writer took its turn and removed its marker.*/+import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';import type { NativeLockHandle } from './native-lock.ts';/** A lease stops admitting lanes after this long, so other processes get the native lock between turns. */@@ -38,9 +50,77 @@ const deferred = new Map<string, number>();export const DEFER_WAIT_MS = 10_000;const DEFER_HOLD_MS = 5_000;+/** How long another process's background writer waits before this process's lanes and no-wait takes yield to it. */+export const FOREIGN_WAIT_GRACE_MS = 1_000;+/** A marker its writer stopped refreshing this long ago is ignored (the writer gave up, or holds the lock now). */+const WAITER_STALE_MS = 5_000;+/** One directory read per worktree at most this often. */+const WAITER_PROBE_MS = 100;++/** This process's waiting background writers: since when each worktree's waits, as its marker says. */+const ownWaits = new Map<string, number>();+const written = new Map<string, number>();+const probes = new Map<string, { at: number; ahead: boolean }>();+const waiterDir = (path: string) => `${path}.waiters`;++/** Records (or refreshes) that a background writer of this process waits for `path`'s lock; keeps its first `since`. */+export function noteWaiting(path: string): void {+ const now = Date.now(), since = ownWaits.get(path) ?? now;+ ownWaits.set(path, since);+ if (now - (written.get(path) ?? 0) < WAITER_STALE_MS / 5) return;+ written.set(path, now);+ try {+ const dir = waiterDir(path), file = join(dir, String(process.pid));+ mkdirSync(dir, { recursive: true });+ writeFileSync(`${file}.tmp`, JSON.stringify({ since, at: Date.now() }));+ renameSync(`${file}.tmp`, file);+ } catch { /* the marker only lends priority; without it the writer competes as before */ }+}++/** The background writer of this process got its turn (or stopped waiting): other processes no longer yield to it. */+export function clearWaiting(path: string): void {+ written.delete(path);+ if (!ownWaits.delete(path)) return;+ try { unlinkSync(join(waiterDir(path), String(process.pid))); } catch { /* already gone */ }+}++function pidAlive(pid: number): boolean {+ try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; }+}++/**+ * Whether a background writer of another process waits for `path` ahead of this process: its live, fresh marker is the+ * oldest, it has waited `FOREIGN_WAIT_GRACE_MS`, and this process waits for less long (an older own wait goes first).+ */+export function foreignWaiterAhead(path: string): boolean {+ const now = Date.now(), probed = probes.get(path);+ if (probed && now - probed.at < WAITER_PROBE_MS) return probed.ahead;+ let oldest: { since: number; pid: number } | null = null;+ let names: string[] = [];+ try { names = readdirSync(waiterDir(path)); } catch { /* no waiter ever wrote here */ }+ for (const name of names) {+ const pid = Number(name);+ if (!/^\d+$/.test(name) || pid === process.pid) continue;+ let marker: { since?: unknown; at?: unknown };+ try { marker = JSON.parse(readFileSync(join(waiterDir(path), name), 'utf8')); } catch { continue; }+ if (typeof marker.since !== 'number' || typeof marker.at !== 'number' || now - marker.at > WAITER_STALE_MS) continue;+ if (!pidAlive(pid)) { try { unlinkSync(join(waiterDir(path), name)); } catch { /* raced */ } continue; }+ if (!oldest || marker.since < oldest.since || marker.since === oldest.since && pid < oldest.pid) oldest = { since: marker.since, pid };+ }+ const own = ownWaits.get(path);+ const ahead = !!oldest && now - oldest.since >= FOREIGN_WAIT_GRACE_MS+ && (own === undefined || oldest.since < own || oldest.since === own && oldest.pid < process.pid);+ probes.set(path, { at: now, ahead });+ return ahead;+}+/** Whether lanes of this worktree should stop: an exclusive writer waits, or the lease used up its turn. */export function leaseDraining(path: string): boolean {const lease = leases.get(path);+ if (foreignWaiterAhead(path)) {+ if (lease) lease.draining = true;+ return true;+ }const waiting = deferred.get(path);if (!lease) {if (waiting === undefined) return false;@@ -89,6 +169,7 @@ export async function acquireShared(path: string, acquire: () => Promise<NativeL}const pending = opening.get(path);if (pending) { await pending; return acquireShared(path, acquire); }+ if (foreignWaiterAhead(path)) return null;const attempt = acquire();opening.set(path, attempt.catch(() => null));let lock: NativeLockHandle | null;diff --git a/test/effect-catchup-contention-gbra133.test.ts b/test/effect-catchup-contention-gbra133.test.tsnew file mode 100644index 0000000000..ed7641a9a3--- /dev/null+++ b/test/effect-catchup-contention-gbra133.test.ts@@ -0,0 +1,113 @@+/**+ * GBRA-133: a catch-up of Git effects could never finish while writers in other processes took turns on the canonical+ * worktree. Every take of the native lock is a poll, so a process that gives the lock back and takes it again at once+ * won every race against an effect worker that tried once per claim; thousands of effects cycled on `writer_busy`+ * (retried every 250 ms, never parked) and none committed.+ *+ * Now a waiting effect worker leaves a marker other processes yield to after a grace (worktree-lease.ts), `writer_busy`+ * backs off per busy streak (effect-journal.ts `retryBusyEffect`), and doctor `parked_effects` and writer status name a+ * backlog that has waited over 10 minutes (effect-catchup.ts).+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { spawn } from 'node:child_process';+import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { getWorktreeBinding } from '../src/core/persistence/ownership.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';+import { readStalledCatchups } from '../src/core/persistence/effect-catchup.ts';+import { checkParkedEffects } from '../src/commands/doctor/checks/parked-effects.ts';+import { bindSource, createGitCoalescingFixture, effectSql, gitStates, harden, pass, pauseGitEffects, release, seed } from './helpers/git-coalescing-fixture.ts';++const { makeRepo, withBrain, dispose } = createGitCoalescingFixture('catchup');+afterAll(dispose);++const busyRows = (engine: BrainEngine) => engine.executeRaw<{ state: string; error_code: string | null; busy_retries: number | null; busy_since: string | null; wait_ms: number }>(+ `SELECT state,error_code,(data->>'busy_retries')::int AS busy_retries,data->>'busy_since' AS busy_since,+ GREATEST(0, EXTRACT(EPOCH FROM (next_attempt_at-now()))*1000)::int AS wait_ms FROM persistence_effects WHERE kind='git' ORDER BY id`);++/** Starts the contender in another process and resolves once it holds the lock for the first time. */+async function contend(engine: BrainEngine, home: string, source: string) {+ const binding = await getWorktreeBinding(engine, source, localHostId());+ const stop = join(home, 'contender.stop'), stats = join(home, 'contender.json');+ const child = spawn(process.execPath, [join(import.meta.dir, 'fixtures', 'worktree-contender.ts'), JSON.stringify(binding), stop, stats],+ { env: { ...process.env, GBRAIN_HOME: home }, stdio: ['ignore', 'pipe', 'inherit'] });+ await new Promise<void>((resolve, reject) => {+ child.stdout.on('data', chunk => { if (String(chunk).includes('ready')) resolve(); });+ child.on('exit', code => reject(new Error(`the contender exited (${code}) before it held the lock`)));+ });+ return async () => {+ writeFileSync(stop, '');+ await new Promise(resolve => child.exitCode === null ? child.on('exit', resolve) : resolve(null));+ return existsSync(stats) ? JSON.parse(readFileSync(stats, 'utf8')) as { held: number; refused: number } : { held: 0, refused: 0 };+ };+}++describe('GBRA-133 Git effect catch-up under cross-process worktree contention', () => {+ test('a catch-up finishes while another process keeps taking the worktree lock, and that process keeps getting turns', () => withBrain('pglite', async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 150));+ const stop = await contend(engine, home, 'default');+ let stats: { held: number; refused: number };+ const deadline = Date.now() + 60_000;+ try {+ while (Date.now() < deadline && (await gitStates(engine)).committed !== 150) { await release(engine); await pass(engine); }+ } finally { stats = await stop(); }+ expect(await gitStates(engine)).toEqual({ committed: 150 });+ expect(repo.pushes()).toBeGreaterThan(0);+ // The other writer was held back only for the effect worker's turns, never shut out.+ expect(stats.held).toBeGreaterThan(5);+ }), 180_000);++ test('writer_busy backs off per busy streak, records when the streak began, and a stalled backlog is named', () => withBrain('pglite', async ({ engine, home, ctx }) => {+ const repo = makeRepo(home, 'content');+ await bindSource(engine, 'default', repo);+ await activateSharedSkillPersistence(engine, { confirmQuiesced: true });+ harden(repo);+ await pauseGitEffects(engine, () => seed(ctx('default'), 3));+ // The contender stops yielding: it holds the lock for good, so every effect pass is refused.+ const binding = await getWorktreeBinding(engine, 'default', localHostId());+ const { acquireNativeLock } = await import('../src/core/persistence/native-lock.ts');+ const held = (await acquireNativeLock(binding!.coordination_path!, { timeoutMs: 5_000 }))!;+ try {+ const waits: number[] = [];+ let firstSince: Array<string | null> = [];+ for (let round = 1; round <= 3; round++) {+ await release(engine);+ const started = Date.now();+ await pass(engine);+ // One pass waits for a busy root once, not once per effect group.+ expect(Date.now() - started).toBeLessThan(15_000);+ const rows = await busyRows(engine);+ expect(rows.every(row => row.state === 'queued' && row.error_code === 'writer_busy' && row.busy_retries === round)).toBe(true);+ waits.push(Math.max(...rows.map(row => row.wait_ms)));+ if (round === 1) firstSince = rows.map(row => row.busy_since);+ }+ expect(waits[1]).toBeGreaterThan(waits[0]!);+ expect(waits[2]).toBeGreaterThan(waits[1]!);+ // Each effect's streak keeps the instant it began.+ expect((await busyRows(engine)).map(row => row.busy_since)).toEqual(firstSince);+ expect(firstSince.every(since => since !== null)).toBe(true);+ expect(await readStalledCatchups(engine)).toEqual([]);++ // The streak began 11 minutes ago: the backlog is not progressing.+ await effectSql(engine, `UPDATE persistence_effects SET data=data||jsonb_build_object('busy_since', (now()-interval '11 minutes')::text) WHERE kind='git'`);+ expect(await readStalledCatchups(engine)).toMatchObject([{ source_id: 'default', stalled_effects: 3, busy_effects: 3, busy_retries: 3,+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json'] } }]);+ const doctor = await checkParkedEffects(engine);+ expect(doctor.status).toBe('warn');+ expect(doctor.message).toContain('Catch-up not progressing: default 3 effect(s) have waited on a busy canonical worktree');+ expect(doctor.details).toMatchObject({ parked_effects: 0, stalled_catchups: [{ source_id: 'default', stalled_effects: 3 }] });+ } finally { await held.release(); }++ // Once the worktree is free the backlog commits and its busy streak no longer counts.+ await release(engine);+ await pass(engine);+ expect(await gitStates(engine)).toEqual({ committed: 3 });+ expect(await readStalledCatchups(engine)).toEqual([]);+ }), 180_000);+});diff --git a/test/fixtures/worktree-contender.ts b/test/fixtures/worktree-contender.tsnew file mode 100644index 0000000000..573eefa51b--- /dev/null+++ b/test/fixtures/worktree-contender.ts@@ -0,0 +1,19 @@+/**+ * GBRA-133 test fixture: a writer in another process that takes a canonical worktree's lock and gives it back in a tight+ * loop, the way a sync drain's publications do (no-wait takes that yield lanes, each held briefly, the next one at once).+ * argv: the binding as JSON, a stop file, a stats file. Writes "ready" when it first held the lock.+ */+import { existsSync, writeFileSync } from 'node:fs';+import { acquireWorktree, type WorktreeBinding } from '../../src/core/persistence/ownership.ts';++const [bindingJson, stopFile, statsFile] = process.argv.slice(2) as [string, string, string];+const binding = JSON.parse(bindingJson) as WorktreeBinding;+let held = 0, refused = 0;+while (!existsSync(stopFile)) {+ const lock = await acquireWorktree(binding, 0, undefined, undefined, { yieldLanes: true });+ if (!lock) { refused++; await Bun.sleep(1); continue; }+ if (++held === 1) process.stdout.write('ready\n');+ await Bun.sleep(40);+ await lock.release();+}+writeFileSync(statsFile, JSON.stringify({ held, refused }));diff --git a/test/hardened-git-held-chunk-gbra133.test.ts b/test/hardened-git-held-chunk-gbra133.test.tsnew file mode 100644index 0000000000..2bf4169f0f--- /dev/null+++ b/test/hardened-git-held-chunk-gbra133.test.ts@@ -0,0 +1,52 @@+/**+ * GBRA-133: a hardened Git stream whose last chunk the caller still holds when the stream closes (a level read pausing+ * at its loop budget) must leave nothing behind once it settled. Before, the held chunk's settle re-armed the+ * exited-stdout idle timer after the read had already ended, and that timer held the read (its `onChunk`, and through it+ * the pass that read) for five more seconds: test/sync-tree-reuse-gbra133.test.ts's collectability checks failed under load.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { hardenedGitStream } from '../src/core/hardened-git.ts';++let root: string;+beforeAll(() => {+ root = mkdtempSync(join(tmpdir(), 'gbrain-held-chunk-'));+ const git = (...args: string[]) => execFileSync('git', ['-C', root, '-c', 'user.name=Example', '-c', '[email protected]', ...args]);+ git('init', '-q', '-b', 'main');+ for (let i = 0; i < 50; i++) writeFileSync(join(root, `note-${i}.md`), `note ${i}\n`);+ git('add', '-A'); git('commit', '-qm', 'notes');+});+afterAll(() => rmSync(root, { recursive: true, force: true }));++async function collectGarbage(): Promise<void> {+ for (let round = 0; round < 3; round++) { await Bun.sleep(0); Bun.gc(true); }+}++/** One read whose every chunk the caller holds until the stream has settled, as a paused level read's last chunk can be. */+async function heldRead(refs: Array<WeakRef<object>>): Promise<boolean> {+ const read = { chunks: 0 };+ refs.push(new WeakRef(read));+ const releases: Array<() => void> = [];+ const result = hardenedGitStream(root, ['ls-tree', '-r', '-z', 'HEAD'], { timeoutMs: 60_000,+ onChunk: () => { read.chunks++; return new Promise<void>(resolve => { releases.push(resolve); }); } });+ while (!releases.length) await Bun.sleep(5);+ let settled = false;+ void result.then(() => { settled = true; });+ for (let waited = 0; !settled && waited < 3_000; waited += 10) await Bun.sleep(10);+ const settledFirst = settled;+ for (const release of releases) release();+ await result;+ return settledFirst;+}++test('a chunk held past the stream close leaves nothing holding the read once it settled', async () => {+ const refs: Array<WeakRef<object>> = [];+ const settledFirst = [await heldRead(refs), await heldRead(refs), await heldRead(refs)];+ // Bun settles the stream while the caller still holds its chunk: the case under test.+ expect(settledFirst).toEqual([true, true, true]);+ await collectGarbage();+ expect(refs.map(ref => ref.deref() === undefined)).toEqual([true, true, true]);+});diff --git a/test/persistence-write-interrupted.test.ts b/test/persistence-write-interrupted.test.tsindex eac7c784fb..e7087b8d87 100644--- a/test/persistence-write-interrupted.test.ts+++ b/test/persistence-write-interrupted.test.ts@@ -29,7 +29,7 @@* statement: a bounded member never reads it as its own deadline, and it is charged once, to the first member that* settles with it (the member that would have sent it alone), never to every member. A shared read the database* cancels every time therefore ends bounded: each charged member reaches the limit and ends write_interrupted, and- * the last member, alone, takes the single path. write_interrupted is a write error code (a foreground receipt and a+ * the last member, alone, takes the single path, where the same read is its own statement and is charged to it. write_interrupted is a write error code (a foreground receipt and a* source lifecycle failure name it, never storage_error), and the sync breaker names the write_interrupted receipts* it tripped on instead of reporting them as preparations that could not finish.* 4. Semantic injection: installFaultHook on the publication's before_commit seam (inside the publication transaction),@@ -357,7 +357,13 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiexpect(readFileSync(path, 'utf8')).toContain(`Next ${n}`);}, 120_000);- test('a group\'s shared read the database cancels every time ends bounded: each cancelled read is charged to one member, and every member ends write_interrupted', async () => withEnv({ GBRAIN_HOME: home,+ /**+ * Every read of the members' shared skill-pack check is cancelled: a group's shared read at its seam, and the same read a+ * lone member sends on the single path, where no shared read exists. `holdMs` holds each cancelled shared read, so every+ * member waiting joins it: one member is charged and the others are released uncounted, and the last of them is claimed+ * again alone, uncharged, which takes the single path.+ */+ const sharedReadCancelledEveryTime = (holdMs: number) => withEnv({ GBRAIN_HOME: home,OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined }, async () => {await registerLocalWriter(engine, 'cli');await retries(1);@@ -367,15 +373,26 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiwriteFileSync(join(brainDir, dir, `${name}.md`), page(`Shared ${n} ${name}`));return { filePath: join(brainDir, dir, `${name}.md`), sourcePath: `${dir}/${name}.md` };});- // Every shared read of a group's preparation is cancelled; a guard far above the bound stops it, so an unbounded loop- // ends committed instead of hanging the test.+ // A guard far above the bound stops the cancels, so an unbounded loop ends committed instead of hanging the test.const GUARD = 40;let cancelled = 0;+ let preparing = false;installFaultHook(async point => {- if (point === 'group:shared_read' && cancelled < GUARD) { cancelled++; throw interruption('57014'); }+ if (point === 'consumer:preparing') preparing = true;+ if (point !== 'group:shared_read' || cancelled >= GUARD) return;+ cancelled++;+ if (holdMs) await new Promise(resolve => setTimeout(resolve, holdMs));+ throw interruption('57014');});- const settled = await importManagedFiles(engine, files, { sourceId, noEmbed: true });- installFaultHook(undefined);+ // The single path reads through the engine itself (a transaction's view is another object and is left alone); a shared+ // read never gets here, because its seam above threw first. The import's own screening, before any preparation, reads it too.+ const direct = engine.executeRaw;+ engine.executeRaw = function (this: BrainEngine, sql: string, ...rest: unknown[]) {+ if (preparing && this === engine && /shared_skill_packs/.test(sql) && cancelled < GUARD) { cancelled++; return Promise.reject(interruption('57014')); }+ return (direct as (...args: unknown[]) => Promise<unknown>).call(this, sql, ...rest);+ } as BrainEngine['executeRaw'];+ const settled = await importManagedFiles(engine, files, { sourceId, noEmbed: true })+ .finally(() => { installFaultHook(undefined); engine.executeRaw = direct; });const rows = await engine.executeRaw<{ slug: string; state: string; error_code: string | null; transient_interruptions: number }>(`SELECT slug,state,error_code,transient_interruptions FROM persistence_requests WHERE source_id=$1 AND slug LIKE $2 ORDER BY slug`, [sourceId, `${dir}/%`]);// Each cancelled read is charged to exactly one member (the first that settles with it), so the reads stop once every@@ -383,6 +400,12 @@ for (const backend of testBackends()) describe(`[${backend}] transient publicatiexpect(cancelled).toBe(3 * 2);expect(rows).toEqual(['a', 'b', 'c'].map(name => ({ slug: `${dir}/${name}`, state: 'failed', error_code: 'write_interrupted', transient_interruptions: 2 })));expect(settled.map(result => result.status === 'rejected' ? (result.reason as { code?: string }).code : 'ok')).toEqual(['write_interrupted', 'write_interrupted', 'write_interrupted']);- }), 120_000);+ });++ test('a group\'s shared read the database cancels every time ends bounded: each cancelled read is charged to one member, and every member ends write_interrupted',+ () => sharedReadCancelledEveryTime(0), 120_000);++ test('a member a cancelled shared read released uncounted, claimed again alone, is cancelled and charged on the single path too (forced probe)',+ () => sharedReadCancelledEveryTime(150), 120_000);});});