Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(sync): #6712 PR 4b checkpoint-validation timeout rows run through the pass stamp's validation
garrytana325bc569964
diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.tsindex 5480362651..055f52a3cc 100644--- a/src/core/persistence/checkpoint-validation.ts+++ b/src/core/persistence/checkpoint-validation.ts@@ -81,6 +81,14 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa}}+/** The pass stamp's validation statement (`findOpenPassWork`): `$1` the worktree, `$2` the stamp's own request id. */+export const OPEN_PASS_WORK_SQL = `(SELECT r.request_id::text AS request_id FROM persistence_requests r+ WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)+ UNION ALL (SELECT r.request_id::text FROM persistence_requests r+ WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid+ AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1)+ LIMIT 1`;+/*** #6712 PR 4b (design v3.2 §3.3, clause 2): a live pass's stamp commits only with no recovery row on the worktree and no* other open managed-sync request of it (page kinds and the checkpoint, filtered on the row). The open read is served by@@ -90,12 +98,7 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa*/export async function findOpenPassWork(tx: Pick<BrainEngine, 'executeRaw'>, worktreeId: string, selfRequestId: string): Promise<string | null> {try {- const [row] = await tx.executeRaw<{ request_id: string }>(`(SELECT r.request_id::text AS request_id FROM persistence_requests r- WHERE r.worktree_id=$1::uuid AND r.recovery IS NOT NULL LIMIT 1)- UNION ALL (SELECT r.request_id::text FROM persistence_requests r- WHERE r.worktree_id=$1::uuid AND r.state IN ('queued','running','recovering') AND r.request_id<>$2::uuid- AND r.intent->>'kind' IN ('managed_sync_import','managed_sync_delete','managed_sync_checkpoint') LIMIT 1)- LIMIT 1`, [worktreeId, selfRequestId]);+ const [row] = await tx.executeRaw<{ request_id: string }>(OPEN_PASS_WORK_SQL, [worktreeId, selfRequestId]);return row?.request_id ?? null;} catch (error) {const failure = error as { code?: string; message?: string };diff --git a/test/e2e/persistence-request-indexes-postgres.test.ts b/test/e2e/persistence-request-indexes-postgres.test.tsindex 2deb02d10f..ac62cd57a4 100644--- a/test/e2e/persistence-request-indexes-postgres.test.ts+++ b/test/e2e/persistence-request-indexes-postgres.test.ts@@ -9,7 +9,7 @@ import type { OperationContext } from '../../src/core/ops/contract.ts';import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';import { performManagedSync } from '../../src/core/persistence/sync-run.ts';import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';-import { INCOMPLETE_SYNC_RECEIPT_SQL, readRequestIndexStates } from '../../src/core/persistence/checkpoint-validation.ts';+import { INCOMPLETE_SYNC_RECEIPT_SQL, OPEN_PASS_WORK_SQL, readRequestIndexStates } from '../../src/core/persistence/checkpoint-validation.ts';import { PERSISTENCE_REQUEST_ONLINE_INDEXES, PERSISTENCE_SYNC_RUN_INDEXES } from '../../src/core/persistence/schema.ts';import { SCHEMA_SQL } from '../../src/core/schema-embedded.generated.ts';import { v179 } from '../../src/core/schema-migrations/v179-persistence-request-sync-run-indexes.ts';@@ -151,7 +151,7 @@ test('#5762 recovery journey: a checkpoint timeout with a dropped index is fixedconst transaction = engine.transaction;engine.transaction = async function<T>(this: PostgresEngine, run: (tx: PostgresEngine) => Promise<T>): Promise<T> {return transaction.call(this, tx => run(new Proxy(tx, { get(target, property) {- if (property === 'executeRaw') return (sql: string, params?: unknown[]) => sql === INCOMPLETE_SYNC_RECEIPT_SQL+ if (property === 'executeRaw') return (sql: string, params?: unknown[]) => sql === OPEN_PASS_WORK_SQL? target.executeRaw('SELECT pg_sleep(8)::text AS request_id') : target.executeRaw(sql, params);const value = Reflect.get(target, property);return typeof value === 'function' ? value.bind(target) : value;diff --git a/test/fix-wave-4-journeys.test.ts b/test/fix-wave-4-journeys.test.tsindex 9dd0c4ab5b..c053a19dc9 100644--- a/test/fix-wave-4-journeys.test.ts+++ b/test/fix-wave-4-journeys.test.ts@@ -29,7 +29,7 @@ import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts'import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';import { claimWorktree } from '../src/core/persistence/ownership.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';-import { INCOMPLETE_SYNC_RECEIPT_SQL } from '../src/core/persistence/checkpoint-validation.ts';+import { OPEN_PASS_WORK_SQL } from '../src/core/persistence/checkpoint-validation.ts';import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';import { currentExitCode, setCliExitVerdict } from '../src/core/cli-force-exit.ts';import { createConnectorFixture, withGoogleAccount } from './helpers/connector-fixture.ts';@@ -240,7 +240,7 @@ function timeoutOnce(engine: BrainEngine): () => void {engine.transaction = async function<T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {return transaction.call(this, tx => run(new Proxy(tx, { get(target, property) {if (property === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql !== INCOMPLETE_SYNC_RECEIPT_SQL || fired) return target.executeRaw(sql, params);+ if (sql !== OPEN_PASS_WORK_SQL || fired) return target.executeRaw(sql, params);fired = true;if (engine.kind === 'postgres') return target.executeRaw('SELECT pg_sleep(8)::text AS request_id');throw Object.assign(new Error('canceling statement due to statement timeout'), { code: '57014' });diff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.tsindex 873de0dfe3..37504d6118 100644--- a/test/persistence-sync-checkpoint-validation.test.ts+++ b/test/persistence-sync-checkpoint-validation.test.ts@@ -9,10 +9,11 @@ import type { OperationContext } from '../src/core/ops/contract.ts';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { readPassRow } from '../src/core/persistence/sync-pass-row.ts';import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';-import { INCOMPLETE_SYNC_RECEIPT_SQL, checkpointRetryCommand, findIncompleteSyncReceipt, formatCheckpointTimeoutHint, readRequestIndexStates } from '../src/core/persistence/checkpoint-validation.ts';+import { INCOMPLETE_SYNC_RECEIPT_SQL, OPEN_PASS_WORK_SQL, checkpointRetryCommand, findIncompleteSyncReceipt, formatCheckpointTimeoutHint, readRequestIndexStates } from '../src/core/persistence/checkpoint-validation.ts';import { persistenceOperations } from '../src/core/ops/persistence.ts';import { printManagedSyncDiagnostic } from '../src/commands/sync-diagnostics.ts';import { WRITE_ERROR_CODES } from '../src/core/persistence/types.ts';@@ -92,13 +93,13 @@ test('#5762 the three index probes find exactly what the former predicate found'await engine.executeRaw('DELETE FROM persistence_requests WHERE source_id=$1', [f.id]);}), 180_000);-/** Makes the checkpoint's validation statement fail inside the coordinator's own transaction. */+/** Makes the checkpoint's validation statement (#6712 PR 4b: the pass stamp's) fail inside the coordinator's own transaction. */function failValidation(engine: BrainEngine, failure: 'timeout' | 'lock'): () => void {const transaction = engine.transaction;engine.transaction = async function<T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {return transaction.call(this, tx => run(new Proxy(tx, { get(target, property) {if (property === 'executeRaw') return async (sql: string, params?: unknown[]) => {- if (sql !== INCOMPLETE_SYNC_RECEIPT_SQL) return target.executeRaw(sql, params);+ if (sql !== OPEN_PASS_WORK_SQL) return target.executeRaw(sql, params);// Postgres raises a real statement timeout under the coordinator's own 5 s budget; PGLite has none, so the error is injected.if (failure === 'timeout' && engine.kind === 'postgres') return target.executeRaw('SELECT pg_sleep(8)::text AS request_id');throw Object.assign(new Error(failure === 'timeout' ? 'canceling statement due to statement timeout' : 'canceling statement due to lock timeout'),@@ -127,8 +128,18 @@ async function timedOutSync(engine: BrainEngine, f: Awaited<ReturnType<typeof fireturn result;}-const checkpointRuns = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ state: string; error_code: string | null; run_id: string }>(- "SELECT state, error_code, intent->>'runId' AS run_id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence", [sourceId]);+/** #6712 PR 4b: a pass's checkpoint intent names its pass (`passId`), not a cursor run. */+const checkpointRuns = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ state: string; error_code: string | null; pass_id: string }>(+ "SELECT state, error_code, intent->>'passId' AS pass_id FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_checkpoint' ORDER BY sequence", [sourceId]);+/** The pass id the source's pass row names now. */+const currentPassId = async (engine: BrainEngine, sourceId: string) => {+ const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [sourceId]);+ return (await readPassRow(engine, sourceId, source!.incarnation))!.value.telemetry.pass_id;+};+/** Every page request of the source: rediscovering the run would admit the pages again. */+const pageRequests = (engine: BrainEngine, sourceId: string) => engine.executeRaw<{ slug: string; state: string }>(+ "SELECT slug, state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') ORDER BY slug, sequence", [sourceId]);+const ADMITTED_ONCE = [{ slug: 'a', state: 'committed' }, { slug: 'b', state: 'committed' }];test('#5762 a validation statement timeout fails the checkpoint terminally with a typed code and a filled hint; other writes proceed', async () => each(async engine => {const f = await fixture(engine);@@ -158,23 +169,34 @@ test('#5762 a validation statement timeout fails the checkpoint terminally with// The printed retry admits a fresh run that commits.expect((await performManagedSync(engine, { ...f.opts, retryFailed: true })).status).toBe('first_sync');- // #6735: it re-validated the pinned checkpoint of the timed-out run; it did not rediscover the manifest under a new run.+ // #6735 through the pass (#6712 PR 4b, design v3.2 §3.1, §3.3): the retry's pass validated a fresh stamp; it admitted no page write again.const runs = await checkpointRuns(engine, f.id);- expect(runs.at(-1)).toMatchObject({ state: 'committed', run_id: runs[0]!.run_id });+ expect(runs.map(row => [row.state, row.error_code])).toEqual([['failed', 'checkpoint_validation_timeout'], ['committed', null]]);+ expect(runs[1]!.pass_id).toBe(await currentPassId(engine, f.id));+ expect(runs[1]!.pass_id).not.toBe(runs[0]!.pass_id);+ expect(await pageRequests(engine, f.id)).toEqual(ADMITTED_ONCE);}), 180_000);test('#6735 a plain resume re-validates a checkpoint whose validation timed out, once per invocation', async () => each(async engine => {const f = await fixture(engine);expect(await timedOutSync(engine, f)).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'checkpoint_validation_timeout', count: 1 }] });const [failed] = await checkpointRuns(engine, f.id);- // A timeout that persists is revived once by the next invocation, then recorded again: the run is never rediscovered.+ expect(await pageRequests(engine, f.id)).toEqual(ADMITTED_ONCE);+ // #6712 PR 4b (design v3.2 §3.1, §3.3): a timeout that persists is validated once by the next invocation's pass, in its+ // own stamp, then recorded again; no page write is admitted again.expect(await timedOutSync(engine, f)).toMatchObject({ status: 'blocked_by_failures', failureCodes: [{ code: 'checkpoint_validation_timeout', count: 1 }] });- expect((await checkpointRuns(engine, f.id)).map(row => [row.state, row.error_code, row.run_id]))- .toEqual([['failed', 'checkpoint_validation_timeout', failed!.run_id], ['failed', 'checkpoint_validation_timeout', failed!.run_id]]);- // Once validation fits its budget, the plain sync the run stopped on commits that same checkpoint.+ const second = await currentPassId(engine, f.id);+ expect(second).not.toBe(failed!.pass_id);+ expect((await checkpointRuns(engine, f.id)).map(row => [row.state, row.error_code, row.pass_id]))+ .toEqual([['failed', 'checkpoint_validation_timeout', failed!.pass_id], ['failed', 'checkpoint_validation_timeout', second]]);+ expect(await pageRequests(engine, f.id)).toEqual(ADMITTED_ONCE);+ // Once validation fits its budget, the plain sync commits its pass's stamp, still without admitting a page again.expect((await performManagedSync(engine, f.opts)).status).toBe('first_sync');- expect((await checkpointRuns(engine, f.id)).map(row => [row.state, row.run_id]))- .toEqual([['failed', failed!.run_id], ['failed', failed!.run_id], ['committed', failed!.run_id]]);+ const third = await currentPassId(engine, f.id);+ expect((await checkpointRuns(engine, f.id)).map(row => [row.state, row.pass_id]))+ .toEqual([['failed', failed!.pass_id], ['failed', second], ['committed', third]]);+ expect(third).not.toBe(second);+ expect(await pageRequests(engine, f.id)).toEqual(ADMITTED_ONCE);expect(await engine.executeRaw('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [f.id])).toEqual([{ slug: 'a' }, { slug: 'b' }]);}), 180_000);