Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): add preparation_attempts to write requests (migration v221 placeholder, #6278)
garrytan97cb44134fd1
diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 3a3e2847ba..37316fb8b8 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -89,6 +89,8 @@ export interface WriteRequest {blocked_reason: string | null;compacted: boolean;publication_started: boolean;+ /** #6278 (v221): preparations cut off by a deadline or an expired `preparing` claim; reset by a commit. Absent on rows read before the migration. */+ preparation_attempts?: number;created_at: Date | string;updated_at: Date | string;completed_at: Date | string | null;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 54cf78e271..dc1b010f73 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -220,6 +220,7 @@ import { v216 } from './v216-chronicle-campaign-stamps.ts';import { v217 } from './v217-persistence-request-claim-phase.ts';import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';import { v219 } from './v219-pages-reconcile-name-indexes.ts';+import { v221 } from './v221-persistence-request-preparation-attempts.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -438,4 +439,5 @@ export const MIGRATIONS: Migration[] = [v217,v218,v219,+ v221,];diff --git a/src/core/schema-migrations/v221-persistence-request-preparation-attempts.ts b/src/core/schema-migrations/v221-persistence-request-preparation-attempts.tsnew file mode 100644index 0000000000..611d6598ca--- /dev/null+++ b/src/core/schema-migrations/v221-persistence-request-preparation-attempts.ts@@ -0,0 +1,21 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// #6278: how many times a write request's preparation was cut off (a+// `preparation_deadline` release, or the reclaim of a claim that expired+// while its owner was preparing). The consumer finishes a request that+// reaches `persistence.max_preparation_attempts` as `failed` with+// `preparation_stalled` instead of claiming it again, so one stuck+// preparation cannot stall a catch-up on every pass. Existing rows start at 0;+// a commit resets the counter. The column is also in the `persistence_requests`+// CREATE TABLE of src/schema.sql for fresh installs; no index references it.+export const v221: Migration = {+ version: 221,+ name: 'persistence_request_preparation_attempts',+ idempotent: true,+ sql: `+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS preparation_attempts integer NOT NULL DEFAULT 0 CHECK (preparation_attempts >= 0);+ `,+};diff --git a/test/e2e/persistence-preparation-attempts-postgres.test.ts b/test/e2e/persistence-preparation-attempts-postgres.test.tsnew file mode 100644index 0000000000..de0df71128--- /dev/null+++ b/test/e2e/persistence-preparation-attempts-postgres.test.ts@@ -0,0 +1,29 @@+/**+ * #6278 (v221) on Postgres: the `preparation_attempts` column on a fresh+ * install and on an upgraded brain holding queued, running, failed and+ * compacted requests. PGLite twin: test/persistence-preparation-attempts-migration.test.ts.+ */+import { afterAll, beforeAll, describe, test } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { hasDatabase } from './helpers.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { assertFreshPreparationAttemptsColumn, assertUpgradedPreparationAttemptsColumn } from '../helpers/preparation-attempts-migration.ts';++let engine: PostgresEngine;+let close: () => Promise<void>;++describe.skipIf(!hasDatabase())('persistence_requests.preparation_attempts (Postgres)', () => {+ beforeAll(async () => {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; close = pg.close;+ }, 120_000);+ afterAll(async () => { await close?.(); });++ test('a fresh install has the column with its default and check', async () => {+ await assertFreshPreparationAttemptsColumn(engine);+ }, 30_000);++ test('an upgraded brain gains the column with 0 on every existing request', async () => {+ await assertUpgradedPreparationAttemptsColumn(engine);+ }, 60_000);+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex ea9e4cf815..e8324ee525 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -230,6 +230,7 @@"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))","persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)","persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",+ "persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))","persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))","persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)","persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",@@ -2566,7 +2567,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 preparation_attempts integer/int4 NOT NULL DEFAULT 0"],"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 a69c264dff..3518c74a66 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -230,6 +230,7 @@"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))","persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)","persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",+ "persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))","persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))","persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)","persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",@@ -2566,7 +2567,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 preparation_attempts integer/int4 NOT NULL DEFAULT 0"],"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 a2c8c94fb9..a56fe0fb3a 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -230,6 +230,7 @@"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))","persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)","persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",+ "persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))","persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))","persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)","persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",@@ -2562,7 +2563,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 preparation_attempts integer/int4 NOT NULL DEFAULT 0"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 3d3d2867e2..23710de3dd 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,11 +1,12 @@{"golden": {- "count": 214,+ "count": 215,"gaps": [17,18,19,- 100+ 100,+ 220],"helpers": {"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",@@ -36,7 +37,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 219,+ "latest": 221,"records": [{"handler": {@@ -3254,6 +3255,19 @@"transaction": false,"verify": "absent","version": 219+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "persistence_request_preparation_attempts",+ "sql": {+ "length": 148,+ "sha256": "c33c596845b68c9a58cde204e44ae082e6d664bc7fe31f9a2a6f21b50231c190"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 221}],"versions": [@@ -3470,7 +3484,8 @@216,217,218,- 219+ 219,+ 221]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex dbdc20143b..d3697952cb 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -230,6 +230,7 @@"persistence_local_writers.persistence_local_writers_lane_check": "c CHECK ((lane = ANY (ARRAY['cli'::text, 'stdio'::text])))","persistence_local_writers.persistence_local_writers_pkey": "p PRIMARY KEY (id)","persistence_requests.persistence_requests_pkey": "p PRIMARY KEY (id)",+ "persistence_requests.persistence_requests_preparation_attempts_check": "c CHECK ((preparation_attempts >= 0))","persistence_requests.persistence_requests_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_cli'::text, 'local_stdio'::text, 'application'::text])))","persistence_requests.persistence_requests_principal_kind_principal_id_request_id_key": "u UNIQUE (principal_kind, principal_id, request_id)","persistence_requests.persistence_requests_protocol_version_check": "c CHECK ((protocol_version = ANY (ARRAY[1, 2])))",@@ -2566,7 +2567,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 preparation_attempts integer/int4 NOT NULL DEFAULT 0"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/helpers/preparation-attempts-migration.ts b/test/helpers/preparation-attempts-migration.tsnew file mode 100644index 0000000000..72ff96c92f--- /dev/null+++ b/test/helpers/preparation-attempts-migration.ts@@ -0,0 +1,75 @@+/**+ * Shared body of the v221 `preparation_attempts` migration tests (#6278):+ * PGLite in `test/persistence-preparation-attempts-migration.test.ts`,+ * Postgres in `test/e2e/persistence-preparation-attempts-postgres.test.ts`.+ */+import { expect } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { LATEST_VERSION, runMigrations } from '../../src/core/migrate.ts';+import { declarePersistenceProtocol } from '../../src/core/persistence/protocol.ts';++const COLUMN_SQL = `SELECT column_name,data_type,is_nullable,column_default FROM information_schema.columns+ WHERE table_name='persistence_requests' AND column_name='preparation_attempts'`;++async function insertRequests(engine: BrainEngine, states: Array<{ state: string; compacted?: boolean }>): Promise<string[]> {+ return engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ const ids: string[] = [];+ for (const row of states) {+ const [inserted] = await tx.executeRaw<{ id: string }>(`INSERT INTO persistence_requests+ (principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,digest,authority,intent,intent_bytes,terminal_reservation,state,execution_token,claim_expires_at,compacted,error_code)+ VALUES ('local_cli','fixture',$1::uuid,'put_page','default',$2::uuid,$3,'digest','{}'::jsonb,'{}'::jsonb,16,16384,$4,+ CASE WHEN $4='running' THEN gen_random_uuid() END,CASE WHEN $4='running' THEN now()+interval '30 seconds' END,$5,+ CASE WHEN $4='failed' THEN 'storage_error' END) RETURNING id`,+ [randomUUID(), randomUUID(), `prep-attempts/${row.state}${row.compacted ? '-compacted' : ''}`, row.state, row.compacted === true]);+ ids.push(inserted!.id);+ }+ return ids;+ });+}++/** A fresh install (initSchema at head) has the column with its default and check. */+export async function assertFreshPreparationAttemptsColumn(engine: BrainEngine): Promise<void> {+ const [column] = await engine.executeRaw<{ column_name: string; data_type: string; is_nullable: string; column_default: string }>(COLUMN_SQL);+ expect(column).toMatchObject({ column_name: 'preparation_attempts', data_type: 'integer', is_nullable: 'NO', column_default: '0' });+ const ids = await insertRequests(engine, [{ state: 'queued' }, { state: 'running' }, { state: 'failed' }, { state: 'committed', compacted: true }]);+ const rows = await engine.executeRaw<{ state: string; preparation_attempts: number }>('SELECT state,preparation_attempts FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [ids]);+ expect(rows.map(row => [row.state, row.preparation_attempts])).toEqual([['queued', 0], ['running', 0], ['failed', 0], ['committed', 0]]);+ await expect(engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw('UPDATE persistence_requests SET preparation_attempts=-1 WHERE id=$1::uuid', [ids[0]]);+ })).rejects.toThrow(/preparation_attempts|check/i);+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw('UPDATE persistence_requests SET preparation_attempts=preparation_attempts+1 WHERE id=$1::uuid', [ids[1]]);+ });+ const [charged] = await engine.executeRaw<{ preparation_attempts: number }>('SELECT preparation_attempts FROM persistence_requests WHERE id=$1::uuid', [ids[1]]);+ expect(charged?.preparation_attempts).toBe(1);+}++/**+ * An upgraded brain: the column is dropped as a pre-v221 brain lacks it, rows in+ * every state exist, the version is set back to 220, and the migration runner+ * adds the column with 0 on every existing row without touching the rows.+ */+export async function assertUpgradedPreparationAttemptsColumn(engine: BrainEngine): Promise<void> {+ const ids = await insertRequests(engine, [{ state: 'queued' }, { state: 'running' }, { state: 'failed' }, { state: 'committed', compacted: true }]);+ const before = await engine.executeRaw<Record<string, unknown>>('SELECT id,state,execution_token,compacted,error_code FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [ids]);+ await engine.executeRaw('ALTER TABLE persistence_requests DROP COLUMN preparation_attempts');+ expect(await engine.executeRaw(COLUMN_SQL)).toEqual([]);+ await engine.setConfig('version', '220');+ const first = await runMigrations(engine);+ expect(first.current).toBe(LATEST_VERSION);+ expect(first.applied).toBeGreaterThanOrEqual(1);+ const [column] = await engine.executeRaw<{ column_name: string; data_type: string; is_nullable: string; column_default: string }>(COLUMN_SQL);+ expect(column).toMatchObject({ column_name: 'preparation_attempts', data_type: 'integer', is_nullable: 'NO', column_default: '0' });+ const after = await engine.executeRaw<Record<string, unknown>>('SELECT id,state,execution_token,compacted,error_code,preparation_attempts FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence', [ids]);+ expect(after.map(({ preparation_attempts: _attempts, ...row }) => row)).toEqual(before);+ expect(after.map(row => row.preparation_attempts)).toEqual([0, 0, 0, 0]);+ // Re-running the idempotent migration is a no-op.+ await engine.setConfig('version', '220');+ const second = await runMigrations(engine);+ expect(second.current).toBe(LATEST_VERSION);+ expect(await engine.executeRaw(COLUMN_SQL)).toHaveLength(1);+}diff --git a/test/persistence-preparation-attempts-migration.test.ts b/test/persistence-preparation-attempts-migration.test.tsnew file mode 100644index 0000000000..b556467003--- /dev/null+++ b/test/persistence-preparation-attempts-migration.test.ts@@ -0,0 +1,32 @@+/**+ * #6278 (v221): `persistence_requests.preparation_attempts`. Protects: a fresh+ * PGLite install has the column (integer, NOT NULL, default 0, non-negative)+ * and an upgraded brain gets it with 0 on every existing request, whatever its+ * state, without the runner touching the rows. Fails when the migration is+ * missing from the registry, is not idempotent, or the column loses its+ * default or check. The Postgres twin is test/e2e/persistence-preparation-attempts-postgres.test.ts.+ */+import { afterAll, beforeAll, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { assertFreshPreparationAttemptsColumn, assertUpgradedPreparationAttemptsColumn } from './helpers/preparation-attempts-migration.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-preparation-attempts-'));+let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({ database_path: join(home, 'data') });+ await engine.initSchema();+}, 120_000);+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });++test('a fresh PGLite install has preparation_attempts with its default and check', async () => {+ await assertFreshPreparationAttemptsColumn(engine);+}, 30_000);++test('an upgraded PGLite brain gains preparation_attempts = 0 on queued, running, failed and compacted rows', async () => {+ await assertUpgradedPreparationAttemptsColumn(engine);+}, 60_000);