Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): a pass group's cost reservation is the sum of its pages' own estimates (GBRA-130, 4b row parity)
garrytanbcd0a382397e
diff --git a/src/core/persistence/sync-pass-episode.ts b/src/core/persistence/sync-pass-episode.tsindex 8d8cdfd715..7be0c9d166 100644--- a/src/core/persistence/sync-pass-episode.ts+++ b/src/core/persistence/sync-pass-episode.ts@@ -109,6 +109,7 @@ export interface PricedIntent { passId?: string; kind: string; path?: string | n/*** Inside a group's admission transaction: reserves the group's priced embedding spend as one `sync-pass-cost` row,* `ON CONFLICT DO NOTHING` (a replay of the same group reserves nothing more). A group with no paid import reserves nothing.+ * The spend is the sum of each page's own estimate, so a total never depends on how pages were grouped (GBRA-130).*/export async function reservePassCost(tx: Exec, intents: ReadonlyArray<PricedIntent>): Promise<void> {const passId = intents.find(intent => intent.passId)?.passId;@@ -116,11 +117,10 @@ export async function reservePassCost(tx: Exec, intents: ReadonlyArray<PricedIntif (!scope) return;const paid = intents.filter(intent => intent.passId === passId && intent.kind === 'managed_sync_import' && intent.processingOptions?.noEmbed !== true && typeof intent.content === 'string');if (!paid.length) return;- const chars = paid.reduce((sum, intent) => sum + intent.content!.length, 0);const groupId = digest(['sync-pass-cost-v1', passId!, ...paid.map(intent => `${intent.path ?? ''}\0${intent.level ?? ''}`).sort()]).slice(0, 32);await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES($1,$2,jsonb_build_array($3::text::jsonb),now()) ON CONFLICT (op,fingerprint) DO NOTHING`,[SYNC_PASS_COST_OP, `${costPrefix(scope.sourceId, scope.incarnation, scope.scope)}${groupId}`,- JSON.stringify({ source_id: scope.sourceId, incarnation: scope.incarnation, usd: estimateCostFromChars(chars, scope.pricePerMTok) })]);+ JSON.stringify({ source_id: scope.sourceId, incarnation: scope.incarnation, usd: paid.reduce((sum, intent) => sum + estimateCostFromChars(intent.content!.length, scope.pricePerMTok), 0) })]);}/** `reserved_usd`: the reservations of one episode (or pass) scope, or of the whole incarnation; a range read. */diff --git a/test/managed-sync-row-parity.test.ts b/test/managed-sync-row-parity.test.tsindex d910103196..571db27675 100644--- a/test/managed-sync-row-parity.test.ts+++ b/test/managed-sync-row-parity.test.ts@@ -142,8 +142,12 @@ async function dump(e: BrainEngine, source: string): Promise<Record<string, unknreceipts: await rows(`SELECT jsonb_build_object('kind',r.intent->>'kind','path',r.intent->>'path','state',r.state,'error_code',r.error_code,'error_message',r.error_message,'outcome',r.outcome - 'revision','slug',r.slug,'page_id',r.page_id,'publication_started',r.publication_started,'compacted',r.compacted) AS rFROM persistence_requests r WHERE r.source_id=$1 AND r.intent->>'kind' LIKE 'managed_sync_%'`),+ // #6712 PR 4b: a pass reserves its embedding spend in one sync-pass-cost row per admitted group, and lanes group pages+ // differently, so those rows compare as one total per incarnation (each page's own estimate, summed: GBRA-130).provenance: await rows(`SELECT jsonb_build_object('op',op,'record',completed_keys) AS r FROM op_checkpoints- WHERE completed_keys->0->>'source_id'=$1 AND op NOT LIKE 'managed-sync%'`),+ WHERE completed_keys->0->>'source_id'=$1 AND op NOT LIKE 'managed-sync%' AND op <> 'sync-pass-cost'`),+ reserved: await rows(`SELECT jsonb_build_object('incarnation',completed_keys->0->>'incarnation','usd',round(sum((completed_keys->0->>'usd')::numeric),12)::text) AS r+ FROM op_checkpoints WHERE op='sync-pass-cost' AND completed_keys->0->>'source_id'=$1 GROUP BY completed_keys->0->>'incarnation'`),};}@@ -173,7 +177,7 @@ test('lanes and --no-lanes publish the same rows, effects and receipts over impo}const left = await dump(engine, laned.id), right = await dump(engine, serial.id);if (dumpFile) writeFileSync(dumpFile, JSON.stringify(left, null, 1));- for (const table of ['pages', 'chunks', 'page_aliases', 'slug_aliases', 'tags', 'links', 'timeline', 'facts', 'takes', 'versions', 'chronicle', 'effects', 'receipts', 'provenance'] as const) {+ for (const table of ['pages', 'chunks', 'page_aliases', 'slug_aliases', 'tags', 'links', 'timeline', 'facts', 'takes', 'versions', 'chronicle', 'effects', 'receipts', 'provenance', 'reserved'] as const) {expect(left[table]!.length).toBeGreaterThan(0);}const differences = Object.keys(left).flatMap(table => {diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 158be9d067..58bfb13c92 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -314,6 +314,7 @@ test/sync-legacy-retry-actions-6696.test.tstest/sync-legacy-slug-adoption-6727.test.tstest/sync-origin-live-wins-6517.test.tstest/sync-page-write-failed-gbra130.test.ts+test/sync-pass-cost-grouping-gbra130.test.tstest/sync-pass-dirty-after-freeze-gbra130.test.tstest/sync-prescreen-both-delta-6712.test.tstest/sync-prescreen-drift-6712.test.tsdiff --git a/test/sync-pass-cost-grouping-gbra130.test.ts b/test/sync-pass-cost-grouping-gbra130.test.tsnew file mode 100644index 0000000000..b292be3f22--- /dev/null+++ b/test/sync-pass-cost-grouping-gbra130.test.ts@@ -0,0 +1,54 @@+/**+ * GBRA-130 (#6712 PR 4b sweep, managed-sync-row-parity): a pass reserves its priced embedding spend per admitted group+ * (`reservePassCost`, one `sync-pass-cost` row per group). It priced the group's summed characters, and+ * `estimateCostFromChars` rounds tokens up once per call, so the same pages reserved a different total depending on how+ * they were grouped: lanes and --no-lanes reserved different totals for one corpus.+ *+ * Protects (red before: the grouped total is below the per-page total): the same corpus grouped two ways reserves the+ * same total, the sum of each page's own estimate. Runs on PGLite and, with DATABASE_URL, on Postgres.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { estimateCostFromChars } from '../src/core/embedding-pricing.ts';+import { readReservedUsd, registerPassCost, reservePassCost, unregisterPassCost } from '../src/core/persistence/sync-pass-episode.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const PRICE = 0.13;+const SOURCE = `cost-grouping-${randomUUID().slice(0, 8)}`;+/** Lengths that are not multiples of 3.5, so each page's own token count rounds up. */+const corpus = [101, 202, 303, 404, 505, 606, 707, 808].map((n, i) => ({ path: `notes/n${i}.md`, level: `oid-${i}`, content: 'x'.repeat(n) }));++for (const backend of testBackends()) describe(`[${backend}] GBRA-130: pass cost reservations`, () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ if (backend === 'postgres') { const pg = new PostgresEngine(); await pg.connect({ database_url: requirePostgresTestDatabase() } as never); engine = pg; }+ else { const lite = new PGLiteEngine(); await lite.connect({}); engine = lite; }+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => {+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='sync-pass-cost' AND starts_with(fingerprint, $1)", [`${SOURCE}:`]);+ await engine.disconnect();+ });++ test('the same corpus grouped two ways reserves the same total: the sum of each page\'s own estimate', async () => {+ const incarnation = randomUUID();+ const reserve = async (groups: number[][]) => {+ const passId = randomUUID();+ registerPassCost(passId, { sourceId: SOURCE, incarnation, scope: passId, pricePerMTok: PRICE });+ try {+ for (const group of groups) await engine.transaction(tx => reservePassCost(tx, group.map(i => ({ passId, kind: 'managed_sync_import', ...corpus[i]!, processingOptions: { noEmbed: false } }))));+ } finally { unregisterPassCost(passId); }+ return readReservedUsd(engine, SOURCE, incarnation, passId);+ };+ const single = await reserve(corpus.map((_, i) => [i]));+ const grouped = await reserve([[0, 1, 2], [3, 4, 5, 6], [7]]);+ const perPage = corpus.reduce((sum, page) => sum + estimateCostFromChars(page.content.length, PRICE), 0);+ expect(single.rows).toBe(8);+ expect(grouped.rows).toBe(3);+ expect(single.usd).toBeCloseTo(perPage, 12);+ expect(grouped.usd).toBeCloseTo(single.usd, 12);+ });+});