Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): true up receipt reservations at completion (#6696 A1)
garrytan1f63191a5578
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.tsindex 3d37268c28..c6a97e9561 100644--- a/src/core/facts/conversation-publication.ts+++ b/src/core/facts/conversation-publication.ts@@ -60,6 +60,7 @@ import { opError, OperationError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';import { digest, jsonBytes } from '../persistence/digest.ts';+import { receiptReservation } from '../persistence/receipt-bytes.ts';import { getWriteRequestById } from '../persistence/journal.ts';import { readJournalLimits } from '../persistence/limits.ts';import { principalKey } from '../persistence/model.ts';@@ -262,7 +263,7 @@ export async function assertConversationAdmissionHeadroom(engine: BrainEngine, a`Conversation fact extraction stopped admitting: ${outstanding} of this writer's ${limits.principalOutstanding} outstanding requests are still pending.`,`Let the pending requests settle (gbrain sources writer status --source ${sourceId} --json shows them; a resident gbrain serve or the next CLI run publishes them), then rerun the same command. Pages already published keep their facts.`);}- const reservation = Math.max(16_384, jsonBytes(authority.writer) + 8192);+ const reservation = receiptReservation(authority.writer);const cumulative = [{ resource: 'reserved receipt bytes', key: 'persistence.limits.principal_terminal_bytes', used: Number(counter?.terminal_bytes ?? 0),limit: limits.principalTerminalBytes, per: reservation,diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 55aad87689..de5a9a902f 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -62,6 +62,7 @@ import { decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedpublishPersistenceFile, recoverPublication, type PreparedMutation } from './coordinator.ts';import { pipelined } from '../page-state/transactions.ts';import { jsonBytes } from './digest.ts';+import { EFFECT_BYTES_SQL, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';import { readJournalLimits } from './limits.ts';import type { JournalLimits } from './model.ts';import { writerStamp } from './writer-versions.ts';@@ -483,24 +484,34 @@ export async function completeGroup(tx: BrainEngine, rows: WriteRequest[], outco() => tx.executeRaw(ENSURE_COUNTERS_SQL, [keys]),() => tx.executeRaw(LOCK_COUNTERS_SQL, [keys]),() => tx.executeRaw<WriteRequest & { principal_key: string }>(`WITH m AS (- SELECT * FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::bigint[],$5::text[]) AS m(id,token,outcome,need,principal_key)+ SELECT * FROM unnest($1::uuid[],$2::uuid[],$3::text[],$4::bigint[],$5::text[],$8::bigint[]) AS m(id,token,outcome,need,principal_key,retained)), e AS (- SELECT request_id,SUM(octet_length(data::text)+octet_length(kind)+1024) AS bytes FROM persistence_effects WHERE request_id=ANY($1::uuid[]) GROUP BY request_id+ SELECT request_id,SUM(${EFFECT_BYTES_SQL}) AS bytes,bool_or(state<>'committed') AS unfinished FROM persistence_effects WHERE request_id=ANY($1::uuid[]) GROUP BY request_id+ ), prior AS (+ SELECT r.id,r.terminal_reservation FROM persistence_requests r JOIN m ON m.id=r.id), done AS (UPDATE persistence_requests r SET state='committed',outcome=m.outcome::jsonb,error_code=NULL,error_message=NULL,completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,- consumer_version=$6,consumer_host_id=$7::uuid,published_at=now(),preparation_attempts=0+ consumer_version=$6,consumer_host_id=$7::uuid,published_at=now(),preparation_attempts=0,+ terminal_reservation=CASE WHEN COALESCE(e.unfinished,false) THEN r.terminal_reservation+ ELSE LEAST(r.terminal_reservation,m.retained+COALESCE(e.bytes,0)) ENDFROM m LEFT JOIN e ON e.request_id=m.idWHERE r.id=m.id AND r.execution_token=m.token AND r.state='running' AND m.need+COALESCE(e.bytes,0)<=r.terminal_reservationRETURNING r.*,m.principal_key+ ), d AS (+ SELECT k.key,count(*) AS n,SUM(done.intent_bytes) AS bytes,SUM(prior.terminal_reservation-done.terminal_reservation) AS freed+ FROM done JOIN prior ON prior.id=done.id CROSS JOIN LATERAL (VALUES ('brain'),(done.principal_key)) AS k(key) GROUP BY k.key), released AS (- UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-d.n,intent_bytes=c.intent_bytes-d.bytes- FROM (SELECT k.key,count(*) AS n,SUM(done.intent_bytes) AS bytes FROM done CROSS JOIN LATERAL (VALUES ('brain'),(done.principal_key)) AS k(key) GROUP BY k.key) d- WHERE c.key=d.key- )+ UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-d.n,intent_bytes=c.intent_bytes-d.bytes,+ terminal_bytes=c.terminal_bytes-LEAST(d.freed,c.terminal_bytes)+ FROM d WHERE c.key=d.key+ ), ${TRUE_UP_CLAMP_SQL('SELECT count(*) FROM d JOIN persistence_counters c ON c.key=d.key WHERE d.freed>c.terminal_bytes')}SELECT * FROM done`, [ids, rows.map(row => row.execution_token), outcomes.map(outcome => JSON.stringify(outcome)),rows.map((row, i) => jsonBytes(outcomes[i]) + jsonBytes(row.authority) + 1024),- rows.map(row => principalKey(requestPrincipal(row))), stamp.version, stamp.hostId]),+ rows.map(row => principalKey(requestPrincipal(row))), stamp.version, stamp.hostId,+ // #6696 (A1): each member's true-up target, sized down at commit once none of its effects is unfinished.+ rows.map((row, i) => retainedReceiptBytes({ intent: row.intent, authority: row.authority, outcome: outcomes[i], error_detail: row.error_detail,+ client_request_id: row.client_request_id }, { stage: 'terminal' }))]),]) as [unknown, unknown, Array<WriteRequest & { principal_key: string }>];if (completed.length !== rows.length) throw new OperationError('write_claim_lost', 'A group member failed its claim or terminal-reservation check before publication.','The group rolls back and its members publish one at a time, where each member reports its own outcome; inspect the requests rather than resubmitting.');diff --git a/src/core/persistence/intent-redaction.ts b/src/core/persistence/intent-redaction.tsindex 4fa41b9e40..4bd4db0afb 100644--- a/src/core/persistence/intent-redaction.ts+++ b/src/core/persistence/intent-redaction.ts@@ -31,7 +31,7 @@import { opError } from '../ops/contract.ts';import type { BrainEngine } from '../engine.ts';import { enterClaimStep, type ClaimPhaseClock } from './claim-phase.ts';-import { jsonBytes } from './digest.ts';+import { EFFECT_BYTES_SQL, retainedReceiptBytes } from './receipt-bytes.ts';import { lockCounters } from './journal.ts';import { isTerminal, principalKey, requestPrincipal, type WriteRequest } from './model.ts';@@ -207,15 +207,15 @@ export async function redactRequestIntents(tx: BrainEngine, targets: readonly Inconst detail = redactJson(current.error_detail, opts.needles ?? []);if (current.compacted && JSON.stringify(outcome) === JSON.stringify(current.outcome) && JSON.stringify(detail) === JSON.stringify(current.error_detail)&& current.error_message === null) continue;- const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes+ const [effects] = await tx.executeRaw<{ bytes: string }>(`SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS bytesFROM persistence_effects WHERE request_id=$1::uuid`, [current.id]);- const retained = Math.min(Number(current.terminal_reservation), jsonBytes(current.authority) + jsonBytes(outcome ?? {})- + (detail ? jsonBytes(detail) : 0) + Number(effects.bytes) + 1024);+ const retained = Math.min(Number(current.terminal_reservation), retainedReceiptBytes({ authority: current.authority, outcome, error_detail: detail,+ client_request_id: current.client_request_id }, { stage: 'compacted', effects: Number(effects.bytes) }));await tx.executeRaw(`UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2,outcome=$3::text::jsonb,error_detail=$4::text::jsonb WHERE id=$1::uuid`,[current.id, retained, outcome == null ? null : JSON.stringify(outcome), detail == null ? null : JSON.stringify(detail)]);for (const key of ['brain', principalKey(requestPrincipal(current))]) {- await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-$2 WHERE key=$1', [key, Number(current.terminal_reservation) - retained]);+ await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-LEAST($2::bigint,terminal_bytes) WHERE key=$1', [key, Number(current.terminal_reservation) - retained]);}redacted++;}diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 120d40c67e..43e65edd48 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -11,6 +11,7 @@ import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentiimport { outstandingCapacityDetail, retryWriteAdmission } from './admission-retry.ts';import { PreadmitBrainChanged } from './preadmit-cache.ts';import { pipelined } from '../page-state/transactions.ts';+import { EFFECT_BYTES_SQL, receiptReservation, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';import { writerStamp } from './writer-versions.ts';import { intentCarriesContent, intentCarriesPurgedContent, PURGE_PRESENCE_COLUMNS } from './purged-intent.ts';@@ -175,7 +176,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overconst requestId = requireUuid(input.requestId ?? randomUUID());const fingerprint = intentDigest(input);const bytes = jsonBytes(input.intent) + jsonBytes(input.authority);- const terminalBytes = input.terminalReservation ?? Math.max(16_384,jsonBytes(input.authority)+8192);+ const terminalBytes = input.terminalReservation ?? receiptReservation(input.authority);if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');const stamp = writerStamp();return { requestId, apply: async (tx: BrainEngine): Promise<WriteRequest> => {@@ -255,7 +256,7 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ}const stamp = writerStamp();const items = inputs.map(input => ({ input, requestId: requireUuid(input.requestId ?? randomUUID()), fingerprint: intentDigest(input),- bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: input.terminalReservation ?? Math.max(16_384, jsonBytes(input.authority) + 8192) }));+ bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: input.terminalReservation ?? receiptReservation(input.authority) }));assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });const ids = items.map(item => item.requestId);// #5984: the checks are independent reads and share locks, so they go out back to back in the order they always@@ -770,19 +771,27 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co// releases its outstanding counters; no row means the encoding exceeds the reservation and nothing changed.const resultBytes = jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0);const probePurges = intentCarriesContent(current.intent);- const [terminal] = await tx.executeRaw<WriteRequest & { purge_has_facts?: boolean; purge_has_pages?: boolean }>(`WITH effects AS (SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0) AS bytes- FROM persistence_effects WHERE request_id=$1::uuid),+ // #6696 (A1): the true-up sizes the reservation down to what the receipt keeps, once no effect is unfinished.+ const retained = retainedReceiptBytes({ intent: current.intent, authority: current.authority, outcome, error_message: error?.message ?? null,+ error_detail: error?.detail ?? current.error_detail, client_request_id: current.client_request_id }, { stage: 'terminal' });+ const [terminal] = await tx.executeRaw<WriteRequest & { purge_has_facts?: boolean; purge_has_pages?: boolean }>(`WITH effects AS (SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0) AS bytes,+ COALESCE(bool_or(state<>'committed'),false) AS unfinished FROM persistence_effects WHERE request_id=$1::uuid),done AS (UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END,- preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END+ preparation_attempts=CASE WHEN $2='committed' THEN 0 ELSE preparation_attempts END,+ terminal_reservation=CASE WHEN (SELECT unfinished FROM effects) THEN terminal_reservation+ ELSE LEAST(terminal_reservation,$12::bigint+(SELECT bytes FROM effects)) ENDWHERE id=$1::uuid AND $9::bigint+(SELECT bytes FROM effects)<=terminal_reservation RETURNING *),- released AS (UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$11- WHERE key=ANY($10::text[]) AND EXISTS (SELECT 1 FROM done))+ released AS (UPDATE persistence_counters c SET outstanding_count=c.outstanding_count-1,intent_bytes=c.intent_bytes-$11,+ terminal_bytes=c.terminal_bytes-LEAST($13::bigint-done.terminal_reservation,c.terminal_bytes)+ FROM done WHERE c.key=ANY($10::text[])),+ ${TRUE_UP_CLAMP_SQL('SELECT count(*) FROM persistence_counters c, done WHERE c.key=ANY($10::text[]) AND $13::bigint-done.terminal_reservation>c.terminal_bytes')}SELECT done.*${probePurges ? `, ${PURGE_PRESENCE_COLUMNS}` : ''} FROM done`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId,- error?.detail ? JSON.stringify(error.detail) : null, resultBytes, ['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);+ error?.detail ? JSON.stringify(error.detail) : null, resultBytes, ['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes),+ retained, Number(current.terminal_reservation)]);if (!terminal) throw capacityError('terminal result and effects exceed their reserved bounded encoding');const { purge_has_facts: purgeFacts, purge_has_pages: purgePages, ...doneRow } = terminal;const done = doneRow as WriteRequest;@@ -790,7 +799,15 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co// reason first, or committed as a no-op after the overlay dropped the purged rows) keeps no copy of it; replay answers// from the stored outcome, and the intent bytes were released above.if (error && PURGED_REFUSAL.test(`${error.code}: ${error.message}`) || probePurges && await intentCarriesPurgedContent(tx as BrainEngine, current, { facts: purgeFacts === true, pages: purgePages === true })) {- const [redacted] = await tx.executeRaw<WriteRequest>('UPDATE persistence_requests SET intent=NULL,compacted=true WHERE id=$1::uuid RETURNING *', [row.id]);+ // #6696: the redaction compacts the receipt, so its reservation shrinks to what is left (no intent) once no effect is unfinished.+ const left = retainedReceiptBytes({ ...done, intent: null }, { stage: 'terminal' });+ const [redacted] = await tx.executeRaw<WriteRequest>(`WITH effects AS (SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0) AS bytes,+ COALESCE(bool_or(state<>'committed'),false) AS unfinished FROM persistence_effects WHERE request_id=$1::uuid),+ r AS (UPDATE persistence_requests SET intent=NULL,compacted=true,terminal_reservation=CASE WHEN (SELECT unfinished FROM effects) THEN terminal_reservation+ ELSE LEAST(terminal_reservation,$2::bigint+(SELECT bytes FROM effects)) END WHERE id=$1::uuid RETURNING *),+ released AS (UPDATE persistence_counters c SET terminal_bytes=c.terminal_bytes-LEAST($3::bigint-r.terminal_reservation,c.terminal_bytes)+ FROM r WHERE c.key=ANY($4::text[]))+ SELECT * FROM r`, [row.id, left, Number(done.terminal_reservation), ['brain', principalKey(requestPrincipal(row))]]);return redacted ?? done;}// Recovery bytes remain reserved until physical cleanup has been verified.@@ -859,7 +876,12 @@ export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<numbreturn Number(requests?.rows ?? 0);}+/** What one compaction pass did (#6696 A11): receipts compacted, reservation bytes it freed, candidates it left and why. */+export interface ReceiptCompactionResult { compacted: number; freed_bytes: number; skipped_by_reason: Record<string, number> }export async function compactWriteReceipts(engine: BrainEngine, retentionDays?: number): Promise<number> {+ return (await compactWriteReceiptsDetailed(engine, retentionDays)).compacted;+}+export async function compactWriteReceiptsDetailed(engine: BrainEngine, retentionDays?: number): Promise<ReceiptCompactionResult> {retentionDays ??= await readReceiptRetentionDays(engine);if (!Number.isFinite(retentionDays) || retentionDays < 0) throw new TypeError('Invalid receipt retention.');// Receipts with unfinished effects stay retained; filtering them before the@@ -869,23 +891,26 @@ export async function compactWriteReceipts(engine: BrainEngine, retentionDays?:AND completed_at < now()-($1::double precision*interval '1 day')AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state<>'committed')ORDER BY sequence LIMIT 100`, [retentionDays]);- let count=0;- for(const row of rows) count+=await engine.transaction(async tx=>{+ const result: ReceiptCompactionResult = { compacted: 0, freed_bytes: 0, skipped_by_reason: {} };+ const skip = (reason: string) => { result.skipped_by_reason[reason] = (result.skipped_by_reason[reason] ?? 0) + 1; return 0; };+ for(const row of rows) result.freed_bytes+=await engine.transaction(async tx=>{await declarePersistenceProtocol(tx);const keys=['brain',principalKey(requestPrincipal(row))];await lockCounters(tx,keys);const [current]=await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE',[row.id]);- if(!current || current.compacted || current.recovery || !isTerminal(current)) return 0;+ if(!current || current.compacted || current.recovery || !isTerminal(current)) return skip('changed');const unfinished=await tx.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND state<>'committed' LIMIT 1",[row.id]);- if(unfinished.length) return 0;- const [effects]=await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes+ if(unfinished.length) return skip('unfinished_effect');+ const [effects]=await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS bytesFROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);- const retained=Math.min(Number(current.terminal_reservation),jsonBytes(current.authority)+jsonBytes(current.outcome??{})+(current.error_detail?jsonBytes(current.error_detail):0)+(current.client_request_id?.length??0)+Number(effects.bytes)+1024);+ const retained=Math.min(Number(current.terminal_reservation),retainedReceiptBytes(current,{stage:'compacted',effects:Number(effects.bytes)}));+ const freed=Number(current.terminal_reservation)-retained;await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid',[row.id,retained]);- for(const key of keys) await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-$2 WHERE key=$1',[key,Number(current.terminal_reservation)-retained]);- return 1;+ await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-LEAST($2::bigint,terminal_bytes) WHERE key=ANY($1::text[])',[keys,freed]);+ result.compacted++;+ return freed;});- return count;+ return result;}export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Date.now()) {return {diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex b10fb59671..57fcfdc917 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -15,6 +15,7 @@ import { computeContentHash } from '../ingestion/types.ts';import { resolveSlugForPath } from '../sync.ts';import { scannerSlugRootMode, scannerSourcePath } from '../write-through.ts';import { sha256 } from './digest.ts';+import { receiptReservation } from './receipt-bytes.ts';import { assertPersistenceAccepting, estimatedRetryAfterMs, waiterOnlyOwner, onPersistenceLane, waitForWrite, writeResponse } from './service.ts';import { parseWireWriteWaitMs } from './write-wait.ts';import { assertTimelineNotOmitted, isTimelineSection, timelineSectionOf, type TimelineSection } from './timeline-omission.ts';@@ -391,7 +392,6 @@ export async function preparePageAdmission(ctx: OperationContext,}return { typeWarning, slugAdvisory, admission: { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId: input.batch ? undefined : clientRequestIdOf(params.request_id), callerIntent, intent, authority,- ...(input.operation === 'edit_page' ? { terminalReservation: Math.max(16_384, Buffer.byteLength(JSON.stringify(authority)) + 8192)- + (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE } : {}),+ ...(input.operation === 'edit_page' ? { terminalReservation: receiptReservation(authority, (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE) } : {}),worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null } };}diff --git a/src/core/persistence/receipt-bytes.ts b/src/core/persistence/receipt-bytes.tsindex bc58a2ce6f..374ed04866 100644--- a/src/core/persistence/receipt-bytes.ts+++ b/src/core/persistence/receipt-bytes.ts@@ -37,3 +37,11 @@ export function retainedReceiptBytes(row: ReceiptBytesFields, opts: { stage: 'teconst dropped = opts.stage === 'terminal' ? json(row.intent) + Buffer.byteLength(row.error_message ?? '') : 0;return kept + dropped + (opts.effects ?? 0) + RECEIPT_HEADROOM_BYTES;}++/** Config row counting true-up decrements clamped at a counter below the delta (counter drift); doctor reports it. */+export const TRUE_UP_CLAMPED_KEY = 'persistence.true_up.clamped';+/** A `clamped` CTE adding the clamp count `countSql` selects to `TRUE_UP_CLAMPED_KEY`; it writes nothing when no decrement was clamped. */+export function TRUE_UP_CLAMP_SQL(countSql: string): string {+ return `clamped AS (INSERT INTO config(key,value) SELECT '${TRUE_UP_CLAMPED_KEY}',k.n::text FROM (${countSql}) AS k(n) WHERE k.n>0+ ON CONFLICT (key) DO UPDATE SET value=(CASE WHEN config.value ~ '^[0-9]+$' THEN config.value::bigint ELSE 0 END+EXCLUDED.value::bigint)::text)`;+}diff --git a/src/core/persistence/topology-receipts.ts b/src/core/persistence/topology-receipts.tsindex bcdbc07e9a..3366c17485 100644--- a/src/core/persistence/topology-receipts.ts+++ b/src/core/persistence/topology-receipts.ts@@ -4,6 +4,7 @@ import { digest, jsonBytes } from './digest.ts';import { lockCounters } from './journal.ts';import { journalLimitKey, readJournalLimits } from './limits.ts';import { principalKey } from './model.ts';+import { receiptReservation, retainedReceiptBytes } from './receipt-bytes.ts';export interface TopologyChange {id:string; principal_id:string; request_id:string; digest:string; operation:string; source_id:string;@@ -21,10 +22,12 @@ export async function priorTopologyChange(engine:BrainEngine,principal:string,re}export async function recordTopologyChange(tx:BrainEngine, input:{principal:string;requestId:string;intent:unknown;operation:string;sourceId:string;incarnation:string|null;worktrees:string[]},outcome:Record<string,unknown>, recovery:Record<string,unknown>|null=null,recoveryBytes=0):Promise<TopologyChange> {- const terminalBytes=16_384;+ const reservation=receiptReservation(null);const intentBytes=recovery?jsonBytes(input.intent):0;- if(Buffer.byteLength(JSON.stringify(outcome))+1024>terminalBytes) throw opError('request_too_large','Lifecycle outcome exceeds its retained receipt capacity.',- `The ${input.operation} of source ${input.sourceId} would record an outcome over ${terminalBytes - 1024} bytes, so nothing was recorded. Report this to the user with the request id ${input.requestId}; it is not a caller mistake.`);+ if(Buffer.byteLength(JSON.stringify(outcome))+1024>reservation) throw opError('request_too_large','Lifecycle outcome exceeds its retained receipt capacity.',+ `The ${input.operation} of source ${input.sourceId} would record an outcome over ${reservation - 1024} bytes, so nothing was recorded. Report this to the user with the request id ${input.requestId}; it is not a caller mistake.`);+ // #6696 (A1): a change recorded committed keeps only its outcome, so it is trued up at insert; a recovering one keeps the reservation.+ const terminalBytes=recovery?reservation:Math.min(reservation,retainedReceiptBytes({outcome},{stage:'terminal'}));const limits=await readJournalLimits(tx);const key=principalKey({kind:'local_cli',id:input.principal});const counters=await lockCounters(tx,['brain',key,...input.worktrees.map(id=>`worktree:${id}`)]);diff --git a/src/core/repair/core.ts b/src/core/repair/core.tsindex 161ece39ca..4f5b841e6a 100644--- a/src/core/repair/core.ts+++ b/src/core/repair/core.ts@@ -34,6 +34,7 @@ import { redactConnectionInfo } from '../audit/redact-connection-info.ts';import type { RepairKindSpec } from './registry.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';import { repairAdmissionWindow, repairPublicationOwner, settleRepairReceipts, type PendingRepair } from './settle.ts';+import { RECEIPT_RESERVATION_FLOOR } from '../persistence/receipt-bytes.ts';export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'take-supersession', 'orphan-bindings', 'embedding-effects', 'attribution-backfill', 'planner-stats', 'google-file-modes', 'stale-atoms', 'extractor-facts', 'conversation-labels', 'captured-facts', 'loop-facts', 'ontology-facts', 'orphan-children', 'failed-writes', 'frontmatter', 'fences', 'slug-conflicts', 'timeline-comments', 'managed-sync-orphans', 'frontmatter-keys', 'file-drift', 'stuck-recovery'] as const;export type RepairKind = typeof REPAIR_KINDS[number];@@ -177,7 +178,6 @@ export interface RepairResult {details?: Record<string, unknown>;}-const RECEIPT_BYTES = 16_384;const STOP_RATIO = 0.9;const SAMPLE = 10;@@ -299,7 +299,7 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, sconst result: RepairResult = {kind: handler.kind, mode: opts.apply ? 'apply' : 'dry_run', scope, affected: plan.items.length,sample: plan.items.slice(0, SAMPLE).map(item => `${item.source_id}:${item.slug}`), residuals: plan.residuals,- cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_BYTES, embedding_pages: handler.embeds === false ? 0 : pending.length,+ cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_RESERVATION_FLOOR, embedding_pages: handler.embeds === false ? 0 : pending.length,embedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel),...(llm ? { llm_usd: opts.apply || !plan.llm ? 0 : plan.llm.usd === null ? null: pending.some(item => item.llm_usd !== undefined) ? pending.reduce((sum, item) => sum + (item.llm_usd ?? 0), 0) : plan.llm.usd,@@ -381,9 +381,9 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s+ `${llmSpent >= opts.maxLlmUsd! ? 'is used up' : `cannot cover its estimate ($${item.llm_usd!.toFixed(4)})`} `+ `($${llmSpent.toFixed(4)} spent of $${opts.maxLlmUsd!.toFixed(4)}; ${remaining} item(s) still pending). Rerun \`${result.apply_command}\` to resume.` });}- const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) : undefined;+ const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR) > c.stop_at) : undefined;if (full) {- const perItem = full.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES;+ const perItem = full.resource === 'lifetime_ids' ? 1 : RECEIPT_RESERVATION_FLOOR;const needed = Math.ceil((full.used + remaining * perItem) / STOP_RATIO) + 1;return stopAfterSettle({ reason: 'capacity', message: `Stopped before crossing 90% of ${full.scope} ${full.resource} (${full.used} of ${full.limit} used; `+ `${remaining} item(s) still need ${remaining * perItem} more). Run: gbrain config set ${full.config_key} ${needed} — then rerun \`${result.apply_command}\` to resume.` });diff --git a/test/persistence-receipt-true-up.test.ts b/test/persistence-receipt-true-up.test.tsnew file mode 100644index 0000000000..3652eb0d68--- /dev/null+++ b/test/persistence-receipt-true-up.test.ts@@ -0,0 +1,131 @@+/**+ * #6696 (A1): a finished receipt gives back the part of its 16 KiB admission+ * reservation it does not keep, in the completion statement, single and group+ * paths, unless an effect is still unfinished; a counter already below the+ * delta clamps at zero and the clamp is counted. Both backends.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { localHostId } from '../src/core/persistence/identity.ts';+import { claimNextWrite, completeWrite } from '../src/core/persistence/journal.ts';+import { completeGroup } from '../src/core/persistence/group-publish.ts';+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';+import { RECEIPT_RESERVATION_FLOOR, retainedReceiptBytes, TRUE_UP_CLAMPED_KEY } from '../src/core/persistence/receipt-bytes.ts';+import { recordTopologyChange } from '../src/core/persistence/topology-receipts.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { freshBrainFactory, requestFixture } from './helpers/persistence-request-fixture.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const databaseUrl = process.env.DATABASE_URL;+const row = async (engine: BrainEngine, id: string) => (await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id]))[0]!;+const counters = async (engine: BrainEngine) => Object.fromEntries((await engine.executeRaw<{ key: string; terminal_bytes: string }>(+ "SELECT key,terminal_bytes::text FROM persistence_counters WHERE key='brain' OR key LIKE 'principal:%'")).map(c => [c.key, Number(c.terminal_bytes)]));+const reservations = async (engine: BrainEngine) => Number((await engine.executeRaw<{ n: string }>(+ 'SELECT COALESCE(SUM(terminal_reservation),0)::text AS n FROM persistence_requests'))[0]!.n);+const formula = (r: WriteRequest) => retainedReceiptBytes(r, { stage: 'terminal' });++for (const kind of testBackends()) {+ describe(`receipt true-up at completion ${kind}`, () => {+ let factory: Awaited<ReturnType<typeof freshBrainFactory>>;+ let scratch: string;+ beforeAll(async () => {+ scratch = mkdtempSync(join(tmpdir(), 'gbrain-true-up-'));+ factory = await freshBrainFactory(kind, databaseUrl);+ }, 120_000);+ afterAll(async () => {+ await factory?.dispose();+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ });+ const check = (name: string, fn: (engine: BrainEngine) => Promise<void>) => test(name, async () => {+ const engine = await factory.fresh();+ await withEnv({ GBRAIN_HOME: scratch, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () => fn(engine));+ }, 120_000);++ check('a single completion with no effects shrinks its reservation to the formula and releases the rest', async engine => {+ const requests = await requestFixture(engine);+ const admitted = await requests.admit('refused');+ expect(Number(admitted.terminal_reservation)).toBe(RECEIPT_RESERVATION_FLOOR);+ const claimed = (await claimNextWrite(engine, localHostId()))!;+ await engine.transaction(tx => completeWrite(tx, claimed, 'conflict', {}, { code: 'source_changed', message: 'the file moved' }));+ const done = await row(engine, admitted.id);+ expect(Number(done.terminal_reservation)).toBe(formula(done));+ expect(Number(done.terminal_reservation)).toBeLessThan(RECEIPT_RESERVATION_FLOOR);+ for (const value of Object.values(await counters(engine))) expect(value).toBe(Number(done.terminal_reservation));+ expect(await reservations(engine)).toBe(Number(done.terminal_reservation));+ });++ check('an unfinished effect keeps the admission reservation', async engine => {+ const requests = await requestFixture(engine);+ const published = await requests.publish(await requests.admit('published'));+ const pending = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND state<>'committed'", [published.id]);+ expect(pending.length).toBeGreaterThan(0);+ expect(Number((await row(engine, published.id)).terminal_reservation)).toBe(RECEIPT_RESERVATION_FLOOR);+ for (const value of Object.values(await counters(engine))) expect(value).toBe(RECEIPT_RESERVATION_FLOOR);+ });++ check('a three-member group completion trues up every member in one statement', async engine => {+ const requests = await requestFixture(engine);+ const admitted = [await requests.admit('g1'), await requests.admit('g2'), await requests.admit('g3')];+ // Claimed together, as claimGroupFollowers claims a lane group's members behind its head.+ const claimed = await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ return tx.executeRaw<WriteRequest>(`UPDATE persistence_requests r SET state='running',execution_token=t.token,claim_expires_at=now()+interval '1 minute'+ FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id RETURNING r.*`, [admitted.map(a => a.id), admitted.map(() => randomUUID())]);+ });+ claimed.sort((a, b) => Number(BigInt(a.sequence) - BigInt(b.sequence)));+ const outcomes = claimed.map(r => ({ slug: r.slug, status: 'created_or_updated' }));+ await engine.transaction(async tx => { await declarePersistenceProtocol(tx); await completeGroup(tx, claimed, outcomes); });+ const done = await Promise.all(admitted.map(a => row(engine, a.id)));+ const sum = done.reduce((total, r) => total + Number(r.terminal_reservation), 0);+ for (const r of done) {+ expect(r.state).toBe('committed');+ expect(Number(r.terminal_reservation)).toBe(formula(r));+ expect(Number(r.terminal_reservation)).toBeLessThan(RECEIPT_RESERVATION_FLOOR);+ }+ for (const value of Object.values(await counters(engine))) expect(value).toBe(sum);+ });++ check('a counter already below the delta still commits, clamps at zero and counts the clamp', async engine => {+ const requests = await requestFixture(engine);+ const admitted = await requests.admit('drifted');+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ await tx.executeRaw("UPDATE persistence_counters SET terminal_bytes=100 WHERE key='brain' OR key LIKE 'principal:%'");+ });+ const claimed = (await claimNextWrite(engine, localHostId()))!;+ await engine.transaction(tx => completeWrite(tx, claimed, 'failed', {}, { code: 'storage_error', message: 'generic failure' }));+ expect((await row(engine, admitted.id)).state).toBe('failed');+ for (const value of Object.values(await counters(engine))) expect(value).toBe(0);+ expect(await engine.getConfig(TRUE_UP_CLAMPED_KEY)).toBe('2');+ });++ check('a receipt redacted for purged content at completion shrinks to what it keeps', async engine => {+ const requests = await requestFixture(engine);+ const admitted = await requests.admit(`purged-${'x'.repeat(120)}`);+ const claimed = (await claimNextWrite(engine, localHostId()))!;+ await engine.transaction(tx => completeWrite(tx, claimed, 'failed', {}, { code: 'purged_content', message: 'the page carries content the owner purged' }));+ const done = await row(engine, admitted.id);+ expect(done).toMatchObject({ compacted: true, intent: null });+ expect(Number(done.terminal_reservation)).toBe(retainedReceiptBytes(done, { stage: 'terminal' }));+ for (const value of Object.values(await counters(engine))) expect(value).toBe(Number(done.terminal_reservation));+ });++ check('a lifecycle change recorded committed is charged its retained bytes, not 16 KiB', async engine => {+ const requests = await requestFixture(engine);+ const [writer] = await engine.executeRaw<{ id: string }>('SELECT id FROM persistence_local_writers LIMIT 1');+ const change = await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx);+ return recordTopologyChange(tx, { principal: writer!.id, requestId: randomUUID(), intent: { op: 'example' }, operation: 'example',+ sourceId: requests.sourceId, incarnation: requests.incarnation, worktrees: [] }, { done: true });+ });+ expect(change.state).toBe('committed');+ expect(Number(change.terminal_bytes)).toBe(retainedReceiptBytes({ outcome: { done: true } }, { stage: 'terminal' }));+ for (const value of Object.values(await counters(engine))) expect(value).toBe(Number(change.terminal_bytes));+ });+ });+}