Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(e2e): counter and reservation comparisons wait for the settlement true-up (#6696 A1)
garrytan766ea52ff164
diff --git a/test/e2e/persistence-http-liveness.test.ts b/test/e2e/persistence-http-liveness.test.tsindex 1b8a760524..37e946256b 100644--- a/test/e2e/persistence-http-liveness.test.ts+++ b/test/e2e/persistence-http-liveness.test.ts@@ -15,6 +15,7 @@ import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnosticsimport { initializeFixtures, fixtures, selectFixtureHost, assertConservation, type HarnessConfig } from '../../scripts/persistence/harness.ts';import { acquireWorktree } from '../../src/core/persistence/ownership.ts';import type { WriteRequest } from '../../src/core/persistence/model.ts';+import { trueUpRequests } from '../../src/core/persistence/receipt-true-up.ts';const url = process.env.DATABASE_URL;const oldBinary = process.env.GBRAIN_TEST_OLD_BINARY;@@ -32,6 +33,14 @@ describe.skipIf(!url)('authenticated PostgreSQL HTTP accepted-write liveness', (let oauthSecret: string;let stderr = '';const content = (text: string) => `---\ntitle: Synthetic note\ntype: note\n---\n\n${text}`;+ // #6696 (A1): a request keeps its whole reservation until its last effect settles, then gives back what its receipt does not keep.+ // Settle the requests and run the (idempotent) true-up before reading counters, so a comparison measures the write, not effect timing.+ const settle = async (clientRequestIds: string[]) => {+ const ids = (await pg.engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests WHERE request_id=ANY($1::uuid[])', [clientRequestIds])).map(row => row.id);+ await waitFor(async () => (await pg.engine.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=ANY($1::uuid[]) AND state IN ('queued','running') LIMIT 1", [ids])).length === 0,+ { timeoutMs: 45000, label: 'request effects settled' });+ await trueUpRequests(pg.engine, ids);+ };function cli(args: string[]): string {const result = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', ...args], { env, encoding: 'utf8', timeout: 60000 });@@ -162,6 +171,7 @@ describe.skipIf(!url)('authenticated PostgreSQL HTTP accepted-write liveness', (const replacement = clients[index];await committed(replacement, put.request_id);await committed(replacement, memory.request_id);+ await settle([put.request_id, memory.request_id]);const before = await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key');const snapshot = await pg.engine.readPageSnapshot(put.slug, { sourceId: source.id });expect(snapshot?.page.compiled_truth).toBe(`Original ${auth} fixture`);@@ -380,7 +390,12 @@ describe.skipIf(!url)('authenticated PostgreSQL HTTP accepted-write liveness', (expect((await call(successor, 'put_page', args)).body.revision).toBe(done.revision);expect(await pg.engine.executeRaw('SELECT id FROM persistence_requests WHERE request_id=$1::uuid', [args.request_id])).toEqual([{ id: retained.id }]);expect(await pg.engine.executeRaw('SELECT id FROM page_versions WHERE page_id=$1', [before.page.id])).toHaveLength(versions.length + 1);- expect(await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key')).toEqual(counters);+ // The handoff charges nothing twice: the only change since the retained snapshot is this request's settlement true-up.+ await settle([args.request_id]);+ const freed = BigInt(retained.terminal_reservation) - BigInt((await read()).terminal_reservation);+ const charged = new Set(['brain', `principal:${retained.principal_kind}:${retained.principal_id}`]);+ expect(await pg.engine.executeRaw('SELECT key,lifetime_ids,terminal_bytes FROM persistence_counters ORDER BY key')).toEqual(+ (counters as Array<{ key: string; lifetime_ids: bigint; terminal_bytes: bigint }>).map(row => charged.has(row.key) ? { ...row, terminal_bytes: BigInt(row.terminal_bytes) - freed } : row));await assertConservation(pg.engine);}, 90000);}diff --git a/test/helpers/single-write-parity.ts b/test/helpers/single-write-parity.tsindex d2330faa90..4ebe9e4e4d 100644--- a/test/helpers/single-write-parity.ts+++ b/test/helpers/single-write-parity.ts@@ -23,6 +23,7 @@ import { expect } from 'bun:test';import { managedBrain } from './managed-brain.ts';import { withEnv } from './with-env.ts';import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';+import { trueUpRequests } from '../../src/core/persistence/receipt-true-up.ts';const facts = renderFactsTable([{ rowNum: 1, claim: 'Alice Example leads the platform team', kind: 'fact', confidence: 0.9,visibility: 'world', notability: 'medium', source: 'notes/standup', context: 'team update', active: true }]);@@ -43,6 +44,23 @@ async function waitCommitted(engine: BrainEngine): Promise<void> {throw new Error('writes did not settle');}+/**+ * #6696 (A1): a request's terminal_reservation shrinks once its last effect settles, so both runs dump it only after every+ * effect has settled and the (idempotent) true-up has run for every request; otherwise the column records effect timing.+ */+async function waitEffectsSettled(engine: BrainEngine): Promise<void> {+ // 45 s: an effect that met a dependency wait (recovery_required while another publication recovers) retries after 30 s.+ for (let i = 0; i < 900; i++) {+ const [open] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_effects WHERE state IN ('queued','running')");+ if (open!.n === 0) {+ await trueUpRequests(engine, (await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_requests')).map(r => r.id));+ return;+ }+ await Bun.sleep(50);+ }+ throw new Error(`effects did not settle: ${JSON.stringify(await engine.executeRaw("SELECT e.kind,e.state,e.error_code,r.slug FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.state IN ('queued','running')"))}`);+}+/*** Runs the scenario on a fresh managed brain (PGLite unless `databaseUrl`) and returns its normalized dump,* plus `groupCompletions`: how many publications completed through the group path (not compared).@@ -77,6 +95,7 @@ export async function runSingleWriteParityScenario(databaseUrl?: string): Promisawait local({ slug: 'notes/doomed', expected_revision: doomed!.revision }, 'delete_page');await local({ slug: 'notes/db-only', content: '---\ntitle: Database only\n---\n\nNo binding for this source.\n' }, 'put_page', 'scratch').catch(error => ({ refused: (error as { code?: string }).code }));await waitCommitted(engine);+ await waitEffectsSettled(engine);await disposePersistenceConsumer(engine);dump = await normalizedDump(engine, root);} finally { proto.executeRaw = original; }