Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
persistence: a running effect whose stamped owner is provably dead is claimed on the next scan, not after its 2-minute lease
garrytan5f8b64da63dd
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex a773b1b015..b93468874a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1184,6 +1184,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7436 (GBRA-151). `since` is restamped at the merge slot.{ since: '0.60.410.0', text: 'A page write onto a file that differs from the database no longer stops the write owner (`serve`) while gbrain checks, with Git, whether the file holds a committed change sync has not imported yet: the Git commands are awaited instead of run synchronously, so lease renewals and other preparations keep going, and the preparation deadline now ends the check, killing its Git process group (SIGTERM, then SIGKILL after 2 s) instead of letting the preparation run on. A preparation stalled in that check, or in the new-page `.gitignore` check, now reports `waiting_on=git` instead of `waiting_on=db` with the last statement before Git started (`last_sql=SELECT_sources`). The refusals are unchanged (#7436).' },{ since: '0.60.411.0', text: '`gbrain doctor` no longer counts a check that did not finish within the run\'s budget as a warning in `health_score` or the category scores. The report counts those checks in `unknown_count`, a category with no finished check is listed in `unknown_scores` instead of scoring 100, and the status stays at warnings, never healthy. `derived_visibility` now runs as its own check right after the cheap incident checks, so it no longer waits on the wave checks\' budget.' },+ // Dead-owner effect-claim release (GBRA-133).+ { since: 'TBD', id: 'dead_owner_effect_claims', text: 'On Linux with Postgres, when a gbrain process is killed while it runs a Git, embedding, links, facts or withdrawal-mirror effect, another consumer on the same machine now takes that effect over within about 5 s, instead of after the effect\'s 2-minute claim lease (the same rule #6650 gave write claims). An owner on another machine or container, an owner whose process this one cannot inspect, and an effect holding a recovery record wait as before. A takeover cannot apply an effect twice: the old claim\'s outcome writes are refused, and Git and mirror effects still wait for the worktree lock while the old owner holds it.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex d28dd6e742..1f75268d5a 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -32,7 +32,7 @@ import { monitorEventLoopDelay, type IntervalHistogram } from 'node:perf_hooks';import { maybeRefreshPlannerStats } from '../planner-stats.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { faultPoint } from './fault-points.ts';-import { releaseAbandonedClaims } from './effect-journal.ts';+import { EFFECT_OWNER_KEY_SQL, 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';@@ -209,6 +209,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {private deadOwnerScanAt = 0;/** #6650: the dead owners (`deadOwnerClaims`) an idle tick found, handed to that tick's expired-claim reclaim. */private deadOwnersSeen: string[] | null = null;+ /** GBRA-133: the dead owners the last `deadOwnerClaims` scan found, handed to every effect pass until the next scan. */+ private deadOwnerKeys: string[] = [];private projectionWorker: Promise<unknown> | undefined;private effectsWorker: Promise<void> | undefined;private draining: { since: number; settled: number; ran: number; noticedAt: number } | undefined;@@ -751,20 +753,26 @@ export class PersistenceConsumer implements PersistenceConsumerLike {* `running`) or rolled back with its connection. A live owner, however slow, and an owner on another host or* container keep their full lease. Postgres only, at most every `DEAD_OWNER_SCAN_MS`: PGLite admits one process* and releases abandoned claims at start. An `idle` scan runs where the idle probe does (its reserved lane), so an- * idle pool still drains.+ * idle pool still drains. GBRA-133: the owners of running effect claims (no recovery record, stamped `claim_owner` of+ * their current token) are read in the same statement; the effect passes until the next scan claim their effects.*/private async deadOwnerClaims(signal?: AbortSignal, idle = false): Promise<string[]> {if (this.engine.kind !== 'postgres' || Date.now() - this.deadOwnerScanAt < DEAD_OWNER_SCAN_MS) return [];this.deadOwnerScanAt = Date.now();const lane = idle && !this.laneInUse && consumerConnectionRoute(this.engine).lane !== 'direct' ? await this.acquireIdleLane(signal) : undefined;- const owners = await this.probeQuery<{ key: string; owner: string }>(lane, `SELECT DISTINCT+ const owners = await this.probeQuery<{ key: string; owner: string }>(lane, `SELECT DISTINCT key,owner FROM (SELECTconcat_ws(':',r.claim_phase->'owner'->>'pid',r.claim_phase->'owner'->>'nonce',r.claim_phase->'owner'->>'start') AS key,(r.claim_phase->'owner')::text AS ownerFROM persistence_requests rWHERE r.state='running' AND r.recovery IS NULL AND r.publication_started=false AND r.claim_expires_at>=now()AND r.claim_phase->>'token'=r.execution_token::text AND r.claim_phase->'owner'->>'boot_id' IS NOT NULLAND (r.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=r.worktree_id AND w.owner_host_id=$1::uuid))+ UNION ALL SELECT ${EFFECT_OWNER_KEY_SQL('e')},(e.claim_owner->'owner')::text+ FROM persistence_effects e+ WHERE e.state='running' AND e.recovery IS NULL AND e.claim_expires_at>=now()+ AND e.claim_owner->>'token'=e.execution_token::text AND e.claim_owner->'owner'->>'boot_id' IS NOT NULL+ AND (e.worktree_id IS NULL OR EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=e.worktree_id AND w.owner_host_id=$1::uuid))) oLIMIT 100`, [this.hostId], signal);- return owners.filter(row => claimOwnerProvablyDead({ owner: JSON.parse(row.owner) })).map(row => row.key);+ return this.deadOwnerKeys = owners.filter(row => claimOwnerProvablyDead({ owner: JSON.parse(row.owner) })).map(row => row.key);}/** #5984 lanes: claims the next group heads of every open lane run in this process, up to its effective lane count. */private async claimLanes(): Promise<void> {@@ -832,7 +840,7 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (!done) await yieldToEventLoop();}for (let ran = limit; ran >= limit && !signal.aborted;) {- ran = await runPersistenceEffects(this.engine, this.config, { hostId: this.hostId, limit, signal });+ ran = await runPersistenceEffects(this.engine, this.config, { hostId: this.hostId, limit, signal, deadOwners: this.deadOwnerKeys });drain.ran += ran;this.drainNotice(drain);if (ran >= limit) await yieldToEventLoop();diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex 35cda9f79c..f75a2707fd 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -13,7 +13,7 @@ import { isFactsExtractionEnabled } from '../facts/extract.ts';import { loadConfig } from '../config.ts';import { resolveDefaultVisibility } from '../facts/visibility.ts';import { declarePersistenceProtocol, isPersistenceDeclaration, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';-import { EXPIRED_PREPARING_CHARGE_SQL } from './claim-phase.ts';+import { claimOwner, EXPIRED_PREPARING_CHARGE_SQL } from './claim-phase.ts';import { refreshFenceClear } from './worktree-refresh-schema.ts';import { pageBatchChildRequestIds } from './page-batch-id.ts';import { EFFECT_FAULT_POINTS, faultPoint } from './fault-points.ts';@@ -124,13 +124,31 @@ async function embeddingDisabled(tx: BrainEngine): Promise<boolean> {return (await tx.getConfig('embedding_disabled')) === 'true';}-/** Claims release their database connection before waiting for a filesystem lock/provider. Nothing on a refresh-fenced worktree is claimed. */-export async function claimPersistenceEffect(engine: BrainEngine, hostId: string): Promise<PersistenceEffect | null> {+/** GBRA-133: the `pid:nonce:start` key of the owner an effect's `claim_owner` stamp names (the request side's key, consumer.ts). */+export const EFFECT_OWNER_KEY_SQL = (e: string) =>+ `concat_ws(':',${e}.claim_owner->'owner'->>'pid',${e}.claim_owner->'owner'->>'nonce',${e}.claim_owner->'owner'->>'start')`;+/**+ * GBRA-133: a running effect with no recovery record whose stamp of its current token names an owner in `param`, the+ * owners the consumer proved dead (`claimOwnerProvablyDead`). It is claimable now, not when its 2-minute lease runs out:+ * the takeover mints a new token, so the dead owner's outcome writes (each a compare-and-set on the token) cannot land, and+ * the Git and mirror kinds still take the worktree's native lock first. An effect holding a recovery record keeps its own+ * path (`selectEffectRecoveries` under the native lock).+ */+const DEAD_OWNER_EFFECT_SQL = (e: string, param: string) => `${e}.state='running' AND ${e}.recovery IS NULL+ AND ${e}.claim_owner->>'token'=${e}.execution_token::text AND ${EFFECT_OWNER_KEY_SQL(e)}=ANY(${param}::text[])`;+/** The `claim_owner` stamp of the claim minting `token`: this process (`claimOwner`). */+export const effectClaimStamp = (token: string) => JSON.stringify({ token, owner: claimOwner() });++/**+ * Claims release their database connection before waiting for a filesystem lock/provider. Nothing on a refresh-fenced worktree is claimed.+ * `deadOwners` (GBRA-133): owner keys the consumer proved dead, whose running effects are claimable before their lease lapses.+ */+export async function claimPersistenceEffect(engine: BrainEngine, hostId: string, deadOwners: readonly string[] = []): Promise<PersistenceEffect | null> {return engine.transactionDirect(async tx => {await declarePersistenceProtocol(tx);const [candidate] = await tx.executeRaw<PersistenceEffect>(`SELECT e.* FROM persistence_effects eLEFT JOIN persistence_worktrees w ON w.id=e.worktree_id- WHERE (e.state='queued' OR e.state='running' AND e.claim_expires_at<now()) AND e.next_attempt_at<=now()+ WHERE (e.state='queued' OR e.state='running' AND e.claim_expires_at<now() OR ${DEAD_OWNER_EFFECT_SQL('e', '$2')}) AND e.next_attempt_at<=now()AND (e.worktree_id IS NULL OR w.owner_host_id=$1::uuid) AND (e.worktree_id IS NULL OR ${refreshFenceClear('e')})AND e.recovery IS NULL AND NOT EXISTS (SELECT 1 FROM persistence_effects blockedWHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)@@ -138,10 +156,11 @@ export async function claimPersistenceEffect(engine: BrainEngine, hostId: stringWHERE blocked.worktree_id=e.worktree_id AND blocked.recovery IS NOT NULL)AND (e.kind='withdrawal-mirror' OR NOT EXISTS (SELECT 1 FROM persistence_effects mirrorWHERE mirror.request_id=e.request_id AND mirror.kind='withdrawal-mirror' AND mirror.state IN ('queued','running')))- ORDER BY e.next_attempt_at,e.id LIMIT 1 FOR UPDATE OF e SKIP LOCKED`, [hostId]);+ ORDER BY e.next_attempt_at,e.id LIMIT 1 FOR UPDATE OF e SKIP LOCKED`, [hostId, [...deadOwners]]);if (!candidate) return null;- const [claimed] = await tx.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,- claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 RETURNING *`, [candidate.id, randomUUID()]);+ const token = randomUUID();+ const [claimed] = await tx.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,claim_owner=$3::text::jsonb,+ claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 RETURNING *`, [candidate.id, token, effectClaimStamp(token)]);return claimed;}, { pipelineFirst: isPersistenceDeclaration });}@@ -227,28 +246,30 @@ export async function rearmWithheldTargets(engine: SqlEngine, requestIds: readon* worktree, under the same readiness, recovery and withdrawal-mirror ordering* rules as claimPersistenceEffect, so the runner commits them together.*/-export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: string, worktreeId: string, limit: number): Promise<PersistenceEffect[]> {+export async function claimCoalescedGitEffects(engine: BrainEngine, hostId: string, worktreeId: string, limit: number,+ deadOwners: readonly string[] = []): Promise<PersistenceEffect[]> {if (limit <= 0) return [];const rows = await engine.transactionDirect(async tx => {await declarePersistenceProtocol(tx);// The worktree-wide conditions (owner, refresh fence, recovery blocks) are one// InitPlan, so the claim walks persistence_effects_pending in order and stops at// $3 rows instead of probing every ready effect of the worktree.- return tx.executeRaw<PersistenceEffect>(`WITH ready AS (SELECT e.id FROM persistence_effects e+ return tx.executeRaw<PersistenceEffect>(`WITH ready AS (SELECT e.id,gen_random_uuid() AS token FROM persistence_effects eWHERE EXISTS (SELECT 1 FROM persistence_worktrees w WHERE w.id=$2::uuid AND w.owner_host_id=$1::uuidAND ${refreshFenceClear('w', 'id')}AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=w.id AND blocked.recovery IS NOT NULL)AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=w.id AND blocked.recovery IS NOT NULL))AND e.worktree_id=$2::uuid AND e.kind='git' AND e.data ? 'relative_path'AND NOT (e.data ? 'targets') AND NOT (e.data ? 'source_scan') AND NOT (e.data ? 'version')- AND (e.state='queued' OR e.state='running' AND e.claim_expires_at<now()) AND e.next_attempt_at<=now()+ AND (e.state='queued' OR e.state='running' AND e.claim_expires_at<now() OR ${DEAD_OWNER_EFFECT_SQL('e', '$4')}) AND e.next_attempt_at<=now()AND e.recovery IS NULLAND NOT EXISTS (SELECT 1 FROM persistence_effects mirrorWHERE mirror.request_id=e.request_id AND mirror.kind='withdrawal-mirror' AND mirror.state IN ('queued','running'))ORDER BY e.next_attempt_at,e.id LIMIT $3 FOR UPDATE OF e SKIP LOCKED)- UPDATE persistence_effects p SET state='running',execution_token=gen_random_uuid(),+ UPDATE persistence_effects p SET state='running',execution_token=ready.token,+ claim_owner=jsonb_build_object('token',ready.token::text,'owner',$5::text::jsonb),claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now()- FROM ready WHERE p.id=ready.id RETURNING p.*`, [hostId, worktreeId, limit]);+ FROM ready WHERE p.id=ready.id RETURNING p.*`, [hostId, worktreeId, limit, [...deadOwners], JSON.stringify(claimOwner())]);}, { pipelineFirst: isPersistenceDeclaration });return rows.sort((a, b) => Number(a.id) - Number(b.id));}diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex d345ad38c3..ecbdfeedf4 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -37,7 +37,7 @@ 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, 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, 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';@@ -86,6 +86,8 @@ export interface EffectWorkerOptions {/** Failure boundary injection; production never supplies this. */boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void>;embedding?: { signature: string; model: string; embed: typeof embedBatch };+ /** GBRA-133: owner keys the consumer proved dead (`deadOwnerClaims`); their running effects are claimed before the lease lapses. */+ deadOwners?: readonly string[];}export async function selectedEffectPage(engine: BrainEngine, effect: PersistenceEffect): Promise<PageSnapshot | null> {@@ -763,8 +765,9 @@ export async function claimAndRecoverEffect(engine: BrainEngine, id: string | nuhooks: Parameters<typeof recoverEffectPublication>[3] = {}): Promise<PersistenceEffect | undefined> {let claimed: PersistenceEffect | undefined;try {- [claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,- claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, randomUUID()]);+ const token = randomUUID();+ [claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,claim_owner=$3::text::jsonb,+ claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, token, effectClaimStamp(token)]);if (claimed) await recoverEffectPublication(engine, claimed, hostId, { ...hooks, between: hooks.between ?? effectClaimKeeper(engine, claimed, effectRenewalIntervalMs) });} catch (error) { if (claimed) await recordFailure(engine, claimed, error); }return claimed;@@ -984,7 +987,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef// or work unblocked by an earlier effect) is claimable again after the flush.for (;;) {while (attempted < limit && !opts.signal?.aborted) {- const effect = await claimPersistenceEffect(engine, opts.hostId);+ const effect = await claimPersistenceEffect(engine, opts.hostId, opts.deadOwners);if (!effect) break;attempted++;touched.add(effect.request_id);@@ -997,7 +1000,7 @@ async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: Ef// #5182: the binding's recorded setting decides; the legacy hook probe only when nothing is recorded (fail-closed).if (!probes.has(root)) probes.set(root, gitDurabilityPolicy(binding, root).then(policy => ({ durable: policy.durable }), error => ({ error })));const group = singleFileGitEffect(effect) && effect.worktree_id- ? [effect, ...await claimCoalescedGitEffects(engine, opts.hostId, effect.worktree_id, GIT_GROUP_SIZE - 1)] : [effect];+ ? [effect, ...await claimCoalescedGitEffects(engine, opts.hostId, effect.worktree_id, GIT_GROUP_SIZE - 1, opts.deadOwners)] : [effect];for (const member of group) touched.add(member.request_id);deferred.push({ effects: group, binding, hardened: probes.get(root)! });} else await run(effect, binding);diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 0446a17bcc..7455a19853 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 267;+export const LATEST_SCHEMA_VERSION = 268;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 2df9303dd2..ff5908c2e9 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -268,6 +268,7 @@ import { v264 } from './v264-set-based-fact-insert-guards.ts';import { v265 } from './v265-derived-generations.ts';import { v266 } from './v266-derived-generation-activations.ts';import { v267 } from './v267-pages-title-search-index.ts';+import { v268 } from './v268-effect-claim-owner.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -534,4 +535,5 @@ export const MIGRATIONS: Migration[] = [v265,v266,v267,+ v268,];diff --git a/src/core/schema-migrations/v268-effect-claim-owner.ts b/src/core/schema-migrations/v268-effect-claim-owner.tsnew file mode 100644index 0000000000..9d4d9a285c--- /dev/null+++ b/src/core/schema-migrations/v268-effect-claim-owner.ts@@ -0,0 +1,16 @@+import type { Migration } from './types.ts';++export const v268: Migration = {+ // GBRA-133: the owner stamp of an effect claim ({ token, owner }), written in the+ // statement that mints the token, so a consumer can release a running effect+ // whose stamped owner it proves dead instead of waiting out the 2-minute lease+ // (the request side has done this since #6650 through claim_phase). Nullable,+ // no backfill, no index (bootstrap-coverage: column-only). Fresh installs get it+ // from this migration too (not src/schema.sql), like v155's effect columns.+ version: 268,+ name: 'effect_claim_owner',+ idempotent: true,+ sql: `+ ALTER TABLE persistence_effects ADD COLUMN IF NOT EXISTS claim_owner JSONB;+ `,+};diff --git a/test/e2e/persistence-dead-owner-effect-gbra133.test.ts b/test/e2e/persistence-dead-owner-effect-gbra133.test.tsnew file mode 100644index 0000000000..03a10b1de7--- /dev/null+++ b/test/e2e/persistence-dead-owner-effect-gbra133.test.ts@@ -0,0 +1,184 @@+/**+ * GBRA-133 on Postgres: an effect claim whose stamped owner this host can prove dead (same boot and pid namespace, its+ * pid gone or reused) is claimed on the consumer's next scan instead of after its 2-minute lease. Before, a crash while+ * a Git effect ran left the survivor waiting out the lease (the crash robot's 120 s stalls at `consumer:preparing` and+ * `effect_recovery:before_clear`). A live owner and an owner from another boot keep the claim. The takeover stays+ * exactly-once: the Git effect takes the worktree's native lock first, so while the old owner still holds it the+ * takeover settles `writer_busy` without parking and commits once the lock is free; the old owner's outcome write,+ * a compare-and-set on its token, lands nowhere.+ *+ * The claim is staged the way a SIGKILLed owner leaves it: `running`, its token, a lease minutes out, no recovery+ * record, and a `claim_owner` stamp of that token.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync, spawn, type ChildProcess } from 'node:child_process';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import postgres from '#postgres';+import { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { PersistenceConsumer } from '../../src/core/persistence/consumer.ts';+import { completeEffect } from '../../src/core/persistence/effect-journal.ts';+import type { PersistenceEffect } from '../../src/core/persistence/effect-model.ts';+import { admitWrite } from '../../src/core/persistence/journal.ts';+import { acquireWorktree } from '../../src/core/persistence/ownership.ts';+import { consumerIdentity } from '../../src/core/persistence/consumer-heartbeat.ts';+import { processStartTime, readBootId } from '../../src/core/pglite-lock.ts';+import { admission, fixtures, initializeFixtures, prepared, selectFixtureHost, type FixtureSource, type HarnessConfig } from '../../scripts/persistence/harness.ts';+import { assertSafeE2eDatabaseUrl, hasDatabase } from './helpers.ts';+import { deadPid } from '../helpers/dead-pid.ts';+import { withEnv } from '../helpers/with-env.ts';+import { waitFor } from '../helpers/wait-for.ts';++const DATABASE_URL = process.env.DATABASE_URL ?? '';+const linux = process.platform === 'linux' && readBootId() !== null;+const FOREIGN_BOOT = '00000000-0000-0000-0000-000000000000';+let live: ChildProcess;+let liveStart: string;++beforeAll(async () => {+ if (!linux) return;+ live = spawn('sleep', ['120'], { stdio: 'ignore' });+ await new Promise(resolve => live.once('spawn', resolve));+ liveStart = processStartTime(live.pid!)!;+});+afterAll(() => { live?.kill('SIGKILL'); });++type Ctx = { engine: PostgresEngine; config: HarnessConfig; sources: FixtureSource[] };+async function withBrain(run: (ctx: Ctx) => Promise<void>) {+ assertSafeE2eDatabaseUrl(DATABASE_URL);+ const name = `gbrain_test_dead_effect_${randomUUID().replaceAll('-', '')}`;+ const admin = postgres(DATABASE_URL, { max: 1, prepare: false, onnotice: () => {} });+ await admin.unsafe(`CREATE DATABASE ${name}`);+ const url = new URL(DATABASE_URL); url.pathname = `/${name}`;+ const root = mkdtempSync(join(tmpdir(), 'gbrain-dead-effect-'));+ const config: HarnessConfig = { kind: 'postgres', root, dataDir: join(root, 'unused'), hostId: randomUUID(),+ seed: 133, schedules: 0, operations: 0, sourceIds: ['effect-a', 'effect-b'], principalIds: [randomUUID(), randomUUID()] };+ const engine = new PostgresEngine();+ try {+ await withEnv({ GBRAIN_HOME: root, GBRAIN_PERSISTENCE_FIXTURE_HOME: root }, async () => {+ await engine.connect({ database_url: url.toString(), poolSize: 6 });+ await engine.initSchema();+ selectFixtureHost(config.hostId);+ await initializeFixtures(engine, config);+ const sources = await fixtures(engine, config);+ for (const source of sources) {+ execFileSync('git', ['init', '-q', source.root]);+ execFileSync('git', ['-C', source.root, '-c', 'user.name=t', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', 'init']);+ }+ await engine.executeRaw("UPDATE persistence_host_bindings SET git_durability='enabled'");+ await run({ engine, config, sources: await fixtures(engine, config) });+ });+ } finally {+ await engine.disconnect();+ try { await admin.unsafe(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`); } finally { await admin.end(); }+ rmSync(root, { recursive: true, force: true });+ }+}++/**+ * Committed page writes whose Git effects are pending again: a consumer publishes them, then every source's commits are+ * undone (the files stay) and the effects are queued again, as they stood before their Git run.+ */+async function gitEffects(ctx: Ctx, pages: Array<[FixtureSource, string]>): Promise<PersistenceEffect[]> {+ const { engine, config, sources } = ctx;+ const rows = [];+ for (const [source, slug] of pages) rows.push(await admitWrite(engine, admission(config, source, slug, `${slug} body`)));+ const ids = rows.map(row => row.id);+ const consumer = consumerFor(ctx);+ try {+ consumer.start();+ await waitFor(async () => (await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=ANY($1::uuid[]) AND kind='git' AND state='committed'", [ids])).length === ids.length,+ { timeoutMs: 30_000, label: 'the writes and their Git effects commit' });+ } finally { await consumer.stop(); }+ for (const source of sources) execFileSync('git', ['-C', source.root, 'reset', '-q', execFileSync('git', ['-C', source.root, 'rev-list', '--max-parents=0', 'HEAD'], { encoding: 'utf8' }).trim()]);+ const effects = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='queued',execution_token=NULL,claim_expires_at=NULL,outcome=NULL,+ next_attempt_at=now() WHERE request_id=ANY($1::uuid[]) AND kind='git' RETURNING *`, [ids]);+ for (const [source, slug] of pages) expect(commits(source, `${slug}.md`)).toBe(0);+ return rows.map(row => effects.find(effect => effect.request_id === row.id)!);+}++/** Stages `effect` as claimed by `owner` with a lease `leaseS` seconds out; returns the claim's token. */+async function stageClaim(engine: PostgresEngine, effect: PersistenceEffect, owner: Record<string, unknown>, leaseS = 120): Promise<string> {+ const token = randomUUID();+ const stamp = { token, owner: { kind: 'serve', version: '0.0.0', nonce: `n-${String(owner.pid)}`, pid_ns: consumerIdentity().pid_ns, boot_id: readBootId(), ...owner } };+ await engine.executeRaw(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,claim_expires_at=now()+($3::integer*interval '1 second'),+ claim_owner=$4::text::jsonb,attempts=attempts+1,updated_at=now() WHERE id=$1`, [effect.id, token, leaseS, JSON.stringify(stamp)]);+ return token;+}++const effectRow = async (engine: PostgresEngine, id: string | number) =>+ (await engine.executeRaw<PersistenceEffect & { lease_left_s: number | null }>(+ "SELECT *,EXTRACT(EPOCH FROM claim_expires_at-now())::float8 AS lease_left_s FROM persistence_effects WHERE id=$1", [id]))[0]!;+const commits = (source: FixtureSource, path: string) =>+ execFileSync('git', ['-C', source.root, 'log', '--format=%H', '--', path], { encoding: 'utf8' }).split('\n').filter(Boolean).length;+const consumerFor = ({ engine, config, sources }: Ctx) => new PersistenceConsumer(engine, { engine: 'postgres' },+ async (_engine, row) => prepared(row, sources, null, true), { hostId: config.hostId, concurrency: 2, pollMs: 500, phaseMs: 5_000, onError: () => {} });++describe.skipIf(!hasDatabase() || !linux)('an effect claim held by a provably dead owner is claimed at once (GBRA-133)', () => {+ test('dead and reused-pid owners: their Git effects commit within seconds, long before the lease; a live owner keeps its claim', () => withBrain(async ctx => {+ const { engine, sources } = ctx;+ const [dead, reused, kept] = await gitEffects(ctx, [[sources[0]!, 'effect-a/dead'], [sources[1]!, 'effect-b/reused'], [sources[0]!, 'effect-a/kept']]);+ const deadToken = await stageClaim(engine, dead, { pid: deadPid(), start: '1' });+ await stageClaim(engine, reused, { pid: live.pid!, start: '1' });+ const liveToken = await stageClaim(engine, kept, { pid: live.pid!, start: liveStart });+ const consumer = consumerFor(ctx);+ const started = Date.now();+ try {+ consumer.start();+ await waitFor(async () => (await effectRow(engine, dead.id)).state === 'committed' && (await effectRow(engine, reused.id)).state === 'committed',+ { timeoutMs: 20_000, label: 'the dead and reused-pid owners\' Git effects commit' });+ expect(Date.now() - started).toBeLessThan(20_000);+ const done = await effectRow(engine, dead.id);+ expect(done.execution_token).toBeNull();+ expect(done.outcome).toMatchObject({ git: 'committed' });+ expect([commits(sources[0]!, 'effect-a/dead.md'), commits(sources[1]!, 'effect-b/reused.md')]).toEqual([1, 1]);+ expect(deadToken).not.toBe(liveToken);+ const held = await effectRow(engine, kept.id);+ expect({ state: held.state, token: held.execution_token }).toEqual({ state: 'running', token: liveToken });+ expect(held.lease_left_s!).toBeGreaterThan(90);+ } finally { await consumer.stop(); }+ }), 90_000);++ test('a lying probe (the owner still runs and holds the native lock): the takeover waits as writer_busy without parking, the old owner\'s outcome write lands nowhere, one commit', () => withBrain(async ctx => {+ const { engine, sources } = ctx;+ const [effect] = await gitEffects(ctx, [[sources[0]!, 'effect-a/lying']]);+ const oldToken = await stageClaim(engine, effect, { pid: live.pid!, start: '1' });+ const lock = await acquireWorktree(sources[0]!.binding, 0, undefined, engine);+ expect(lock).not.toBeNull();+ const consumer = consumerFor(ctx);+ try {+ consumer.start();+ await waitFor(async () => (await effectRow(engine, effect.id)).execution_token !== oldToken, { timeoutMs: 20_000, label: 'the effect is taken from the probed-dead owner' });+ await waitFor(async () => (await effectRow(engine, effect.id)).error_code === 'writer_busy', { timeoutMs: 20_000, label: 'the takeover meets the held lock' });+ const busy = await effectRow(engine, effect.id);+ expect(busy.state).not.toBe('failed');+ expect(busy.data.parked ?? []).toEqual([]);+ await completeEffect(engine, { ...effect, execution_token: oldToken }, { git: 'old_owner' });+ expect((await effectRow(engine, effect.id)).outcome).not.toEqual({ git: 'old_owner' });+ expect(commits(sources[0]!, 'effect-a/lying.md')).toBe(0);+ await lock!.release();+ await waitFor(async () => (await effectRow(engine, effect.id)).state === 'committed', { timeoutMs: 20_000, label: 'the effect commits once the lock is free' });+ expect((await effectRow(engine, effect.id)).outcome).toMatchObject({ git: 'committed' });+ expect(commits(sources[0]!, 'effect-a/lying.md')).toBe(1);+ } finally { await lock?.release().catch(() => undefined); await consumer.stop(); }+ }), 90_000);++ test('an owner from another boot, an owner without the markers, and a stamp of an earlier claim wait for their lease', () => withBrain(async ctx => {+ const { engine, sources } = ctx;+ const [foreign, older, stale] = await gitEffects(ctx, [[sources[0]!, 'effect-a/foreign'], [sources[1]!, 'effect-b/older'], [sources[0]!, 'effect-a/stale']]);+ const foreignToken = await stageClaim(engine, foreign, { pid: deadPid(), start: '1', boot_id: FOREIGN_BOOT });+ const olderToken = await stageClaim(engine, older, { pid: deadPid(), boot_id: undefined, start: undefined });+ await stageClaim(engine, stale, { pid: deadPid(), start: '1' });+ const staleToken = randomUUID();+ await engine.executeRaw('UPDATE persistence_effects SET execution_token=$2::uuid WHERE id=$1', [stale.id, staleToken]);+ const consumer = consumerFor(ctx);+ try {+ consumer.start();+ await Bun.sleep(8_000);+ expect([(await effectRow(engine, foreign.id)).execution_token, (await effectRow(engine, older.id)).execution_token, (await effectRow(engine, stale.id)).execution_token])+ .toEqual([foreignToken, olderToken, staleToken]);+ } finally { await consumer.stop(); }+ }), 90_000);+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 96e209d5a8..a8ee4b69fa 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -3247,7 +3247,8 @@"15 error_code text/text NULL","16 outcome jsonb/jsonb NULL","17 recovery jsonb/jsonb NULL",- "18 recovery_bytes bigint/int8 NOT NULL DEFAULT 0"+ "18 recovery_bytes bigint/int8 NOT NULL DEFAULT 0",+ "19 claim_owner jsonb/jsonb NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex d25271865d..5cb3d5d25a 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -3247,7 +3247,8 @@"15 error_code text/text NULL","16 outcome jsonb/jsonb NULL","17 recovery jsonb/jsonb NULL",- "18 recovery_bytes bigint/int8 NOT NULL DEFAULT 0"+ "18 recovery_bytes bigint/int8 NOT NULL DEFAULT 0",+ "19 claim_owner jsonb/jsonb NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex cb3ecd5e65..e201c18f79 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -3243,7 +3243,8 @@"15 error_code text/text NULL","16 outcome jsonb/jsonb NULL","17 recovery jsonb/jsonb NULL",- "18 recovery_bytes bigint/int8 NOT NULL DEFAULT 0"+ "18 recovery_bytes bigint/int8 NOT NULL DEFAULT 0",+ "19 claim_owner jsonb/jsonb NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 959baff9a4..e72f47700b 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 262,+ "count": 263,"gaps": [17,18,@@ -73,7 +73,7 @@"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 267,+ "latest": 268,"records": [{"handler": {@@ -4257,6 +4257,19 @@"transaction": false,"verify": "absent","version": 267+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "effect_claim_owner",+ "sql": {+ "length": 83,+ "sha256": "1342d23315a82e4b650358cc8ddd08a1197a2da8ddd3be107a2c96976a032a7f"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 268}],"versions": [@@ -4521,7 +4534,8 @@264,265,266,- 267+ 267,+ 268]},"normalizer": "migrations-record-v1"