Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
#6712 PR 2: a pass whose database connection died releases its unpublished claims once the database answers; convergence mode (f) runs
garrytane2776eb88c40
diff --git a/scripts/persistence/README.md b/scripts/persistence/README.mdindex 6d5e353750..5e83d23dbd 100644--- a/scripts/persistence/README.md+++ b/scripts/persistence/README.md@@ -565,12 +565,12 @@ The chaos modes, each named in failures and selectable with| (c) concurrent writers | During the kill loop: `gbrain put` rewrites of 5% of the notes, `remember` facts on an entity page, `gbrain extract timeline --source db` (a managed maintenance job) | strict convergence; every acknowledged write in the ledger | runs || (c-db) DB-only competitor | With `sync.write_through=false`, a DB-only `put` lands while the run is stalled on that page's frozen entry, and another on a page whose file did not change | the raced page is held `concurrent_write` (needs a person), its file keeps the committed bytes and its page the DB write; both pages are left out of disk == DB | runs || (d) out-of-band Git | While a run is stalled mid-manifest: `git mv` and `git rm` of 1% of the files, committed, and deletion of 1% uncommitted | moves and removals converge strictly; each uncommitted deletion is listed by `gbrain pages ghosts` with the `gbrain repair ghost-pages` exit and left out of disk == DB | runs |-| (e) mid-run edit | The `sync:after_freeze` hook writes an uncommitted edit to a seeded entry after it was frozen | the run's receipt and `sync status` name `worktree_dirty`; after the editor commits, strict convergence | skipped until PR 1 of #6712: no `worktree_dirty` hold is named, and the run churns through `source_changed` conflicts and cancellations (5 of 20 entries after 150 s) |-| (f) pooler drop | Every pooled connection drops at the proxy after 20 committed pages of a bulk run (`GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER=<name>` restarts that container instead) | no new hold; the drain resumes within the owner-kill stall bound; strict convergence | skipped until PR 1 of #6712: it converges with no hold, but publication stalls 356 s (a publication lease) after the drop |+| (e) mid-run edit | The `sync:after_freeze` hook writes an uncommitted edit to a seeded entry after it was frozen | the run's receipt and `sync status` name `worktree_dirty`; after the editor commits, strict convergence | runs (turned on by PR 1 of #6712) |+| (f) pooler drop | Every pooled connection drops at the proxy after 20 committed pages of a bulk run (`GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAINER=<name>` restarts that container instead) | no new hold; the drain resumes within the owner-kill stall bound; strict convergence | runs (turned on by PR 2 of #6712: a pass whose connection died releases its unpublished claims once the database answers, instead of holding them under the publication lease) || (g) two drainers | `sync --all --no-delegate` beside a serve draining a delegated sync of the same source | strict convergence | runs || (lease) drain-lease takeover | A `--no-delegate` leader stalls right after it takes the source's drain lease (`sync:lease_acquired`), two `--no-delegate` followers queue behind it, and the leader is SIGKILLed | a follower reports following, one takes over inside the lease TTL (2 min) and finishes `synced`, no follower ends `blocked`; strict convergence | runs (#6712 PR 1) |-| (knock-on) | One page's publication throws P0001 once inside a bulk group, then a trigger refuses one page with P0001 for a whole run | no other page of the run is cancelled; strict convergence once the trigger is gone | skipped until PR 1 of #6712: the one-shot throw is retried and cancels nothing, but the refused page cancels the run's other 74 requests, and both plain syncs after the trigger is dropped stop `blocked_by_failures` on the frozen `storage_error` request until `--retry-failed` |-| (systemic) | A trigger on `pages` raises an unregistered P0001 (one scenario) or 55000 (another) on every page write for one run, then is dropped | the refused run does not report success and its receipt names the SQLSTATE; strict convergence once the trigger is gone | skipped until PR 1 of #6712: the refused run stops `blocked` naming the SQLSTATE, but both plain syncs after the trigger is dropped stay `blocked_by_failures` until `--retry-failed` |+| (knock-on) | One page's publication throws P0001 once inside a bulk group, then a trigger refuses one page with P0001 for a whole run | no other page of the run is cancelled; strict convergence once the trigger is gone | runs (turned on by PR 1 of #6712) |+| (systemic) | A trigger on `pages` raises an unregistered P0001 (one scenario) or 55000 (another) on every page write for one run, then is dropped | the refused run does not report success and its receipt names the SQLSTATE; strict convergence once the trigger is gone | runs (turned on by PR 1 of #6712) |A skipped mode stays written; naming it in `GBRAIN_TEST_CONVERGENCE_MODES` runs itanyway, which is how the PR that fixes it turns it on.diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex de7c70c5f9..93167d8541 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,7 +1,7 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, publicationGroupKey, syncGroup, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';-import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, type PreparedMutation } from './coordinator.ts';+import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, transientDatabaseFailure, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';import { preparationConfigView } from './config-snapshot.ts';@@ -53,6 +53,8 @@ const DRAIN_NOTICE_AFTER_MS = 5_000;const DRAIN_NOTICE_EVERY_MS = 10_000;/** #6696 C7: at most one storage.keep_db policy pass (KEEP_DB_BATCH requests) per this interval. */const KEEP_DB_POLICY_INTERVAL_MS = 10 * 60_000;+/** #6712 (convergence mode f): how long a pass whose connection died keeps trying to release its unpublished claims. */+const CONNECTION_LOSS_RELEASE_MS = 30_000;/** #6650: how often a consumer looks for claims held by an owner it can prove dead. */export const DEAD_OWNER_SCAN_MS = 5_000;const yieldToEventLoop = () => new Promise<void>(resolve => setImmediate(resolve));@@ -1030,38 +1032,65 @@ export class PersistenceConsumer implements PersistenceConsumerLike {}/** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */private async executeOrGroup(row: WriteRequest, root: RootHold): Promise<boolean> {- // #6712: a page publishes whatever its predecessor's fate; a lane group member released mid-group only waits while the- // member before it is still unfinished (#6153 class).- const lane = laneOf(row);- if (await claimedHeadOrder(this.engine, row, lane !== null) === 'wait') { await releaseUnpublishedClaim(this.statements, row, 'group_member_waiting'); return false; }- const group = publicationGroupKey(row);- // A managed import batch also groups on PGLite: its members share one transaction's guards there too.- if (!group || this.engine.kind !== 'postgres' && !group.startsWith('import:')) return this.execute(row, root);- // #6007: a put_pages or import batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.- const followers = await claimGroupFollowers(this.engine, row, group, syncGroup(group) ? 63 : PAGE_BATCH_GROUP_MAX - 1);- if (!followers.length && !lane) return this.execute(row, root);- const rows = [row, ...followers];- for (const member of rows) this.executing.add(member.id);+ const claimed = [row];try {- return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane,- prepare: (member, engine, signal, clock) => this.prepare(engine, member, this.config, signal, clock),- lease: this.leaseTiming(), policy: this.policy, foregroundMs: this.opts.preparationMs ?? 30_000,- publication: this.publicationBound(row, await readPublicationCeilingMs(this.engine)),- leftRunning: (work, blocksRoot, abandoned) => {- if (!blocksRoot) { this.keepUntilSettled(work); return; }- // #6278: an abandoned member blocks its root until it settles or the ceiling passes; several abandoned members all hold it.- const settled = this.keepAbandoned(work, abandoned?.clock.claimedAt);- const block = abandoned ? this.abandonedRootBlock(abandoned.row, abandoned.clock, settled) : settled;- root.until = root.until ? Promise.all([root.until, block]).then(() => undefined) : block;- },- settled: done => {- this.executing.delete(done.id);- if (done.state === 'committed' && done.worktree_id && !String(done.intent?.kind).startsWith('managed_sync_')) {- this.foregroundCounts.set(done.worktree_id, this.foregroundCompletions(done.worktree_id) + 1);- }- this.settled(done);- } });- } finally { for (const member of rows) this.executing.delete(member.id); }+ // #6712: a page publishes whatever its predecessor's fate; a lane group member released mid-group only waits while the+ // member before it is still unfinished (#6153 class).+ const lane = laneOf(row);+ if (await claimedHeadOrder(this.engine, row, lane !== null) === 'wait') { await releaseUnpublishedClaim(this.statements, row, 'group_member_waiting'); return false; }+ const group = publicationGroupKey(row);+ // A managed import batch also groups on PGLite: its members share one transaction's guards there too.+ if (!group || this.engine.kind !== 'postgres' && !group.startsWith('import:')) return this.execute(row, root);+ // #6007: a put_pages or import batch publishes in groups of at most PAGE_BATCH_GROUP_MAX pages.+ const followers = await claimGroupFollowers(this.engine, row, group, syncGroup(group) ? 63 : PAGE_BATCH_GROUP_MAX - 1);+ if (!followers.length && !lane) return this.execute(row, root);+ claimed.push(...followers);+ const rows = [row, ...followers];+ for (const member of rows) this.executing.add(member.id);+ try {+ return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, lane,+ prepare: (member, engine, signal, clock) => this.prepare(engine, member, this.config, signal, clock),+ lease: this.leaseTiming(), policy: this.policy, foregroundMs: this.opts.preparationMs ?? 30_000,+ publication: this.publicationBound(row, await readPublicationCeilingMs(this.engine)),+ leftRunning: (work, blocksRoot, abandoned) => {+ if (!blocksRoot) { this.keepUntilSettled(work); return; }+ // #6278: an abandoned member blocks its root until it settles or the ceiling passes; several abandoned members all hold it.+ const settled = this.keepAbandoned(work, abandoned?.clock.claimedAt);+ const block = abandoned ? this.abandonedRootBlock(abandoned.row, abandoned.clock, settled) : settled;+ root.until = root.until ? Promise.all([root.until, block]).then(() => undefined) : block;+ },+ settled: done => {+ this.executing.delete(done.id);+ if (done.state === 'committed' && done.worktree_id && !String(done.intent?.kind).startsWith('managed_sync_')) {+ this.foregroundCounts.set(done.worktree_id, this.foregroundCompletions(done.worktree_id) + 1);+ }+ this.settled(done);+ } });+ } finally { for (const member of rows) this.executing.delete(member.id); }+ } catch (error) {+ if (transientDatabaseFailure(error)) await this.releaseAfterConnectionLoss(claimed);+ throw error;+ }+ }+ /**+ * #6712 (convergence mode f): a pass whose database connection died (a pooler restart, a dropped connection) gives+ * back every claim it took that did not commit, as soon as the database answers again, so the drain claims them anew+ * at once. Left alone they stay `running` under the publication lease this live process holds, and nothing frees+ * them until it lapses (about six minutes). The release is fenced on the claim's token, no recovery record and+ * publication not started, so a committed member, a member another consumer took over and one whose files need+ * recovery are untouched. Gives up after `CONNECTION_LOSS_RELEASE_MS`, leaving the lease to lapse as before.+ */+ private async releaseAfterConnectionLoss(rows: WriteRequest[]): Promise<void> {+ const deadline = Date.now() + CONNECTION_LOSS_RELEASE_MS;+ for (let attempt = 0; !this.stopping; attempt++) {+ try {+ for (const row of rows) await releaseUnpublishedClaim(this.statements, row, 'database_contention');+ return;+ } catch (error) {+ if (!transientDatabaseFailure(error) || Date.now() >= deadline) return;+ }+ await new Promise(resolve => setTimeout(resolve, Math.min(2000, 250 * 2 ** attempt)));+ }}/** Mandatory barrier: engine.close must be sequenced AFTER this promise. */async stop(): Promise<void> {diff --git a/test/managed-sync-connection-loss.test.ts b/test/managed-sync-connection-loss.test.tsnew file mode 100644index 0000000000..68ffbd6385--- /dev/null+++ b/test/managed-sync-connection-loss.test.ts@@ -0,0 +1,85 @@+/**+ * #6712 PR 2 (convergence mode f): a pooled connection that dies while a bulk group publishes.+ *+ * Protects: the owner that claimed the group releases every claim of the pass that never committed as soon as the+ * database answers again, so the drain re-claims them at once. Before, the error escaped the pass with each member+ * still `running` under the publication lease, and nothing freed them until that lease lapsed (about six minutes,+ * "claim lapsed: owner missing").+ *+ * Postgres only (bulk groups publish on Postgres).+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { execFileSync } from 'node:child_process';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { performSync } from '../src/commands/sync/perform.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { withEnv } from './helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-connection-loss-'));+let engine: BrainEngine | undefined;+let closePostgres: (() => Promise<void>) | undefined;+const sources: string[] = [];+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const note = (i: number, word: string) => `---\ntitle: Note ${i}\n---\nA ${word} observation number ${i}.\n`;++beforeAll(async () => {+ if (!process.env.DATABASE_URL) return;+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engine = pg.engine; closePostgres = pg.close;+}, 120_000);+afterAll(async () => {+ if (engine) await withEnv({ GBRAIN_HOME: home }, async () => {+ await disposePersistenceConsumer(engine!); await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ for (const id of sources) await engine!.executeRaw('DELETE FROM sources WHERE id=$1', [id]);+ });+ await closePostgres?.();+ rmSync(home, { recursive: true, force: true });+});++test('a connection lost while a bulk group publishes frees the group\'s claims at once; the drain finishes without waiting out the publication lease', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_BULK_SIZE: '8' }, async () => {+ const e = engine;+ if (!e) return;+ const id = `loss-${randomUUID().replace(/-/g, '').slice(0, 16)}`; sources.push(id);+ const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (let i = 0; i < 40; i++) writeFileSync(join(root, `notes/n${i}.md`), note(i, 'first'));+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');+ await e.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await e.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(e, id, root);+ await e.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 1 };+ expect((await performSync(e, opts)).drain).toMatchObject({ outcome: 'synced' });+ for (let i = 0; i < 40; i++) writeFileSync(join(root, `notes/n${i}.md`), note(i, 'revised'));+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qam', 'revise');++ // The pooler drops: from the publication's commit boundary on, every statement fails CONNECTION_CLOSED for two seconds.+ const connectionClosed = () => Object.assign(new Error('write CONNECTION_CLOSED 127.0.0.1:6543'), { code: 'CONNECTION_CLOSED' });+ let downUntil = 0, dropped = false;+ const executeRaw = e.executeRaw;+ e.executeRaw = (async function (this: BrainEngine, ...args: Parameters<BrainEngine['executeRaw']>) {+ if (Date.now() < downUntil) throw connectionClosed();+ return executeRaw.apply(this, args);+ }) as BrainEngine['executeRaw'];+ installFaultHook(async (point, detail) => {+ if (dropped || point !== 'publication:before_commit' || detail.sourceId !== id) return;+ dropped = true; downUntil = Date.now() + 2000;+ throw connectionClosed();+ });+ const started = Date.now();+ let result;+ try { result = await performSync(e, opts); }+ finally { installFaultHook(undefined); e.executeRaw = executeRaw; }+ expect(dropped).toBe(true);+ expect(result.drain).toMatchObject({ outcome: 'synced' });+ // The owner-kill bound the convergence gate holds a pooler drop to (mode f), far below the publication lease.+ expect(Date.now() - started).toBeLessThan(70_000);+ const stuck = await e.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running')", [id]);+ expect(stuck).toHaveLength(0);+ for (let i = 0; i < 40; i++) expect((await e.getPage(`notes/n${i}`, { sourceId: id }))?.compiled_truth).toContain(`revised observation number ${i}`);+}), 600_000);diff --git a/test/sync-convergence.serial.test.ts b/test/sync-convergence.serial.test.tsindex ac77ca70ee..9b22c9747e 100644--- a/test/sync-convergence.serial.test.ts+++ b/test/sync-convergence.serial.test.ts@@ -102,7 +102,6 @@ const PGBOUNCER_CONTAINER = process.env.GBRAIN_TEST_CONVERGENCE_PGBOUNCER_CONTAIconst LOG_DIR = process.env.GBRAIN_TEST_CONVERGENCE_LOG_DIR;/** The chaos modes. `skip` names the PR that turns a mode master fails on; the mode stays written and runs when named in GBRAIN_TEST_CONVERGENCE_MODES. */-const PR1 = 'PR 1 of #6712 (L1 content-addressed resume + L2 one page, one fate + the drain lease)';const MODES = {a: { title: 'client kills', skip: null },b: { title: 'serve kills mid-publish', skip: null },@@ -110,9 +109,7 @@ const MODES = {'c-db': { title: 'a DB-only competitor', skip: null },d: { title: 'out-of-band git mv/git rm of committed files and deletion of uncommitted files', skip: null },e: { title: 'a deterministic mid-run edit after freezeEntry', skip: null },- // #6712 lane C: the page that loses its pooled connection mid-publication keeps its live owner's publication claim until- // that lease lapses (~366 s, "claim lapsed: owner missing"); one page's fate converges, the stall is the owner's (the drain lease).- f: { title: 'a pooler drop mid-bulk', skip: PR1 },+ f: { title: 'a pooler drop mid-bulk', skip: null },g: { title: 'two concurrent drainers: a --all run beside a serve', skip: null },lease: { title: 'the drain-lease holder killed with two followers queued behind it', skip: null },'knock-on': { title: 'one page failure inside a bulk group', skip: null },@@ -820,9 +817,8 @@ describe('convergence harness calibration (#6650 L0, #6712 PR 0)', () => {expect(b.git('ls-files', '--others', '--exclude-standard')).toBe('stray.md');} finally { rmSync(b.repo, { recursive: true, force: true }); }});- test('modes master fails stay written and name the PR that turns them on', () => {- expect(MODES.f.skip).toContain('PR 1 of #6712');- for (const mode of ['a', 'b', 'c', 'c-db', 'd', 'e', 'g', 'lease', 'knock-on', 'systemic'] as const) expect(MODES[mode].skip).toBeNull();+ test('every mode runs: #6712 PR 2 turned on the last skipped one (f, a pooler drop mid-bulk)', () => {+ for (const mode of ['a', 'b', 'c', 'c-db', 'd', 'e', 'f', 'g', 'lease', 'knock-on', 'systemic'] as const) expect(MODES[mode].skip).toBeNull();});});