Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): reserve the retained intent; true up after every effect settle (#6696 A1)

garrytan8a73862e91bc
diff --git a/src/core/backup/snapshot.ts b/src/core/backup/snapshot.ts
index 5a23ec2e7f..8e246a8c49 100644
--- a/src/core/backup/snapshot.ts
+++ b/src/core/backup/snapshot.ts
@@ -1,4 +1,5 @@
/** Full PGLite state recovery for managed in-agent installations. Never starts workers. */
+import { trueUpRequests } from '../persistence/receipt-true-up.ts';
import { randomUUID } from 'node:crypto';
import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, renameSync, rmSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
@@ -272,6 +273,9 @@ export async function restorePgliteBackup(options: { archive: string; into: stri
const jobs = await tx.executeRaw<{ id: number }>(`UPDATE minion_jobs SET status = 'cancelled', lock_token = NULL, lock_until = NULL, finished_at = NOW(), updated_at = NOW(), error_text = 'quarantined by backup restore; inspect and explicitly resubmit', data = data || jsonb_build_object('__restore_previous_status', status, '__restore_id', $1::text) WHERE status NOT IN ('completed', 'failed', 'dead', 'cancelled') RETURNING id`, [restoreId]);
quarantined = jobs.length;
});
+ // #6696 (A1): the restore failed every pending effect; their requests give back their unused reservations.
+ await trueUpRequests(engine, (await engine.executeRaw<{ request_id: string }>(
+ "SELECT DISTINCT request_id FROM persistence_effects WHERE error_code IN ('restore_recovery','restore_new_brain')")).map(row => row.request_id));
await engine.executeRaw('CHECKPOINT');
const restoredDatabase = engine.db;
await engine.disconnect();
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index e825788252..f2df71e866 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -266,7 +266,7 @@ export async function assertConversationAdmissionHeadroom(engine: BrainEngine, a
}
// #6696 (A5): the cumulative caps follow the background pause, with the host-only, resource-specific fix: waiting frees no request id.
const pause = await readBackgroundPauseShare(engine);
- const reservation = receiptReservation(authority.writer);
+ const reservation = receiptReservation({ authority: authority.writer });
const key = principalKey(authority.writer.principal);
for (const r of [
{ resource: 'terminal_bytes' as const, setting: 'principalTerminalBytes' as const, used: Number(counter?.terminal_bytes ?? 0), per: reservation },
diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.ts
index b14fb1ad37..67c8e93f29 100644
--- a/src/core/persistence/effect-retry.ts
+++ b/src/core/persistence/effect-retry.ts
@@ -1,4 +1,5 @@
import type { BrainEngine } from '../engine.ts';
+import { trueUpRequests } from './receipt-true-up.ts';
import { loadConfigWithEngine, type GBrainConfig } from '../config.ts';
import { MAX_RATE_LIMIT_RETRIES } from '../embed-retry.ts';
import { EmbeddingDisabledError, readContentChunksColumnDim } from '../embedding-dim-check.ts';
@@ -142,7 +143,7 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string
const config = await loadConfigWithEngine(engine, baseConfig);
const configuredSignature = config?.embedding_model && config.embedding_dimensions
? `${config.embedding_model}:${config.embedding_dimensions}` : null;
- return engine.transaction(async tx => {
+ const result = await engine.transaction(async tx => {
await declarePersistenceProtocol(tx);
const [selected] = await tx.executeRaw<PersistenceEffect>("SELECT * FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [request.id]);
if (!selected) throw opError('invalid_params', 'The embedding obligation is unavailable.',
@@ -223,4 +224,7 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: string
return { ...receipt, state: updated.state, action: complete ? 'reconciled' : 'retry_queued', pending_chunks: pending.length,
next_action: complete ? 'The existing vectors satisfy this obligation; no provider work was scheduled.' : 'The resident owner may spend up to five attempts only when its selected file configuration and the database policy permit embedding, under existing provider and job budgets. Repeating this command does not renew that allowance.' };
});
+ // #6696 (A1): a reconciled obligation settled the request's last effect; its reservation shrinks outside the approval transaction.
+ if (result.action === 'reconciled') await trueUpRequests(engine, [request.id]);
+ return result;
}
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 8b347fc31e..24bfefcb94 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -1,4 +1,5 @@
import { withAIAttribution } from '../ai/invocation-guard.ts';
+import { trueUpRequests } from './receipt-true-up.ts';
import { randomUUID } from 'node:crypto';
import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';
import { existsSync, statSync } from 'node:fs';
@@ -493,6 +494,13 @@ const GIT_YIELD_MS = 250;
* Resolves with the number of effects attempted, so a caller can keep draining.
*/
export async function runPersistenceEffects(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions): Promise<number> {
+ // #6696 (A1): every request whose effect this pass claimed is trued up after the pass, outside the settling transactions.
+ const touched = new Set<string>();
+ try { return await runEffectPass(engine, config, opts, touched); }
+ finally { await trueUpRequests(engine, touched).catch(() => { /* idempotent; the next settlement of the request retries it */ }); }
+}
+
+async function runEffectPass(engine: BrainEngine, config: GBrainConfig, opts: EffectWorkerOptions, touched: Set<string>): Promise<number> {
const limit = Math.max(1, Math.min(opts.limit ?? 2, 20));
const recoveries = await selectEffectRecoveries(engine, opts.hostId, limit);
let attempted = 0;
@@ -508,7 +516,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
// can provide that proof and no second process can steal this claim now.
[claimed] = await engine.executeRaw<PersistenceEffect>(`UPDATE persistence_effects SET state='running',execution_token=$2::uuid,
claim_expires_at=now()+interval '2 minutes',attempts=attempts+1,updated_at=now() WHERE id=$1 AND recovery IS NOT NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [recovery.id, randomUUID()]);
- if (claimed) { attempted++; await recoverEffectPublication(engine, claimed, opts.hostId, opts); }
+ if (claimed) { attempted++; touched.add(claimed.request_id); await recoverEffectPublication(engine, claimed, opts.hostId, opts); }
} catch (error) { if (claimed) await recordFailure(engine, claimed, error); }
finally { await lock.release(); }
}
@@ -679,6 +687,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
const effect = await claimPersistenceEffect(engine, opts.hostId);
if (!effect) break;
attempted++;
+ touched.add(effect.request_id);
let binding: WorktreeBinding | null = null;
try {
if (effect.worktree_id && !['embedding', 'facts-backstop', 'links'].includes(effect.kind)) binding = await getWorktreeBinding(engine, effect.source_id, opts.hostId);
@@ -689,6 +698,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
if (!probes.has(root)) probes.set(root, gitDurabilityPolicy(binding, root).then(policy => ({ durable: policy.durable }), error => ({ error })));
const group = singleFileGitEffect(effect) && effect.worktree_id
? [effect, ...await claimCoalescedGitEffects(engine, opts.hostId, effect.worktree_id, GIT_GROUP_SIZE - 1)] : [effect];
+ for (const member of group) touched.add(member.request_id);
deferred.push({ effects: group, binding, hardened: probes.get(root)! });
} else await run(effect, binding);
}
diff --git a/src/core/persistence/embedding-noop-settle.ts b/src/core/persistence/embedding-noop-settle.ts
index d09450fabd..c9387a8b8b 100644
--- a/src/core/persistence/embedding-noop-settle.ts
+++ b/src/core/persistence/embedding-noop-settle.ts
@@ -21,6 +21,7 @@
* `next_attempt_at, id` across kinds, only Git groups and withdrawal mirrors
* gate other effects, and an embedding effect gates nothing.
*/
+import { trueUpRequests } from './receipt-true-up.ts';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { embeddingWriteTarget } from '../page-state/projections.ts';
@@ -61,7 +62,8 @@ export async function settleNoopEmbeddingEffects(engine: BrainEngine, hostId: st
const [due] = await engine.executeRaw(`SELECT 1 FROM persistence_effects e WHERE e.id>$1::bigint AND e.kind='embedding' AND e.state='queued'
AND e.attempts=0 AND e.recovery IS NULL ORDER BY e.id LIMIT 1`, [from]);
if (!due) return { settled: 0, cursor: { key, through: from }, done: true };
- return engine.transaction(async tx => {
+ const requestIds: string[] = [];
+ const pass = await engine.transaction(async tx => {
await declarePersistenceProtocol(tx);
const [{ newest }] = await tx.executeRaw<{ newest: string }>('SELECT COALESCE(max(id),0)::text AS newest FROM persistence_effects');
// The window is the next `limit` unattempted embedding effects by id, read from the primary key and locked;
@@ -109,8 +111,12 @@ export async function settleNoopEmbeddingEffects(engine: BrainEngine, hostId: st
if (!ids.length) return { settled: 0, cursor, done };
const settled = await tx.executeRaw(`UPDATE persistence_effects SET state='committed', error_code=NULL, attempts=attempts+1,
data=data-'retry_slugs'-'target_failures'-'failing_target', execution_token=NULL, claim_expires_at=NULL, outcome='{}'::jsonb, updated_at=now()
- WHERE id=ANY($1::text[]::bigint[]) AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id`, [ids]);
+ WHERE id=ANY($1::text[]::bigint[]) AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING id, request_id`, [ids]);
await faultPoint('effect:embedding:settle', { effectId: ids[0] });
+ for (const row of settled as Array<{ request_id: string }>) requestIds.push(row.request_id);
return { settled: settled.length, cursor, done };
});
+ // #6696 (A1): the settled requests give back their unused reservation, outside the settle transaction.
+ await trueUpRequests(engine, requestIds);
+ return pass;
}
diff --git a/src/core/persistence/embedding-settlement.ts b/src/core/persistence/embedding-settlement.ts
index e4ae8e5ce7..f71cb7c373 100644
--- a/src/core/persistence/embedding-settlement.ts
+++ b/src/core/persistence/embedding-settlement.ts
@@ -25,6 +25,7 @@
* Every state change is a compare-and-set on state, attempts, execution token
* and recovery. A candidate that changed since planning is `changed_since_preview`.
*/
+import { trueUpRequests } from './receipt-true-up.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { opError, OperationError } from '../ops/contract.ts';
@@ -85,6 +86,15 @@ export function embeddingGrantId(runId: string, effectId: string | number): stri
*/
export async function settleEmbeddingEffect(engine: BrainEngine, candidate: Pick<EmbeddingCandidate, 'effect_id' | 'state' | 'attempts'>,
opts: { dryRun: boolean; config: GBrainConfig | null; hostId: string; runId?: string }): Promise<EmbeddingSettlement> {
+ let requestId: string | undefined;
+ const settlement = await settleInTransaction(engine, candidate, opts, id => { requestId = id; });
+ // #6696 (A1): the request's reservation shrinks once this commit settled its last effect, outside the settling transaction.
+ if (requestId && !opts.dryRun) await trueUpRequests(engine, [requestId]);
+ return settlement;
+}
+
+function settleInTransaction(engine: BrainEngine, candidate: Pick<EmbeddingCandidate, 'effect_id' | 'state' | 'attempts'>,
+ opts: { dryRun: boolean; config: GBrainConfig | null; hostId: string; runId?: string }, settled: (requestId: string) => void): Promise<EmbeddingSettlement> {
return engine.transaction(async tx => {
await declarePersistenceProtocol(tx);
const [effect] = await tx.executeRaw<PersistenceEffect & { request_state: string }>(`SELECT e.*, r.state AS request_state
@@ -99,6 +109,7 @@ export async function settleEmbeddingEffect(engine: BrainEngine, candidate: Pick
outcome=$3::text::jsonb, data=data-'repair_requeued_at', updated_at=now()
WHERE id=$1 AND state=$2 AND attempts=$4 AND execution_token IS NULL AND recovery IS NULL RETURNING id`,
[effect.id, effect.state, JSON.stringify(outcome), effect.attempts]);
+ if (rows.length) settled(effect.request_id);
return rows.length > 0;
};
// The obligation of a removed (or replaced) source incarnation is moot: nothing can read those vectors.
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 9012c6aaff..481f3bb0c6 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -233,7 +233,7 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
const requestId = requireUuid(input.requestId ?? randomUUID());
const fingerprint = intentDigest(input);
const bytes = jsonBytes(input.intent) + jsonBytes(input.authority);
- const terminalBytes = input.terminalReservation ?? receiptReservation(input.authority);
+ const terminalBytes = Math.max(input.terminalReservation ?? 0, receiptReservation(input));
if (!Number.isSafeInteger(terminalBytes) || terminalBytes < 1024) throw new TypeError('Invalid terminal receipt reservation.');
const stamp = writerStamp();
const origin = resolveAdmissionOrigin(input.origin);
@@ -315,7 +315,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 ?? receiptReservation(input.authority) }));
+ bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: Math.max(input.terminalReservation ?? 0, receiptReservation(input)) }));
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
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index aeb608e897..dd76d61ab7 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -392,6 +392,6 @@ export async function preparePageAdmission(ctx: OperationContext,
}
return { typeWarning, slugAdvisory, admission: { origin: ctx.admissionOrigin, 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: receiptReservation(authority, (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE) } : {}),
+ ...(input.operation === 'edit_page' ? { terminalReservation: receiptReservation({ intent, 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.ts
index 266ede6625..4fd8a24536 100644
--- a/src/core/persistence/receipt-bytes.ts
+++ b/src/core/persistence/receipt-bytes.ts
@@ -1,19 +1,25 @@
import { jsonBytes } from './digest.ts';
-/** The smallest terminal reservation an admission takes; the receipt is sized down at commit (true-up). */
+/** The smallest terminal reservation an admission takes; the receipt is sized down once it settles (true-up). */
export const RECEIPT_RESERVATION_FLOOR = 16_384;
/** Slack a trued-up receipt keeps while it can still change (effect re-arms, redaction markers). */
export const RECEIPT_HEADROOM_BYTES = 4096;
/** Slack a compacted receipt keeps: the 1 KiB compaction always kept (a compacted put_page measures about 3.9 KB). */
export const COMPACTED_HEADROOM_BYTES = 1024;
-/** Bumped when the retained-bytes formula changes; `receipt-true-up` previews bind it. */
-export const RECEIPT_FORMULA_VERSION = 1;
+/** Space an admission reserves beyond its intent and authority: the outcome, error, effect rows and headroom a completion may add. */
+export const RECEIPT_COMPLETION_BYTES = 12_288;
/** Bytes one effect row holds on its receipt; the SQL twin of `effectBytes`. */
export const EFFECT_BYTES_SQL = 'octet_length(data::text)+octet_length(kind)+1024';
-/** What an admission reserves: the floor, or the authority plus 8 KiB when that is larger, plus `extra`. */
-export function receiptReservation(authority: unknown, extra = 0): number {
- return Math.max(RECEIPT_RESERVATION_FLOOR, jsonBytes(authority) + 8192) + extra;
+/**
+ * What an admission reserves: the serialized intent and authority the receipt
+ * retains until compaction, plus RECEIPT_COMPLETION_BYTES, never below the
+ * floor, plus a caller's `extra` (edit_page's diff). A 100 KB page body
+ * reserves its 100 KB, so the counters never hold less than the row keeps.
+ */
+export function receiptReservation(fields: { intent?: unknown; authority?: unknown }, extra = 0): number {
+ const json = (value: unknown) => value === null || value === undefined ? 0 : jsonBytes(value);
+ return Math.max(RECEIPT_RESERVATION_FLOOR, json(fields.intent) + json(fields.authority) + RECEIPT_COMPLETION_BYTES) + extra;
}
/** The receipt fields that stay on the row, by name. */
diff --git a/src/core/persistence/receipt-true-up.ts b/src/core/persistence/receipt-true-up.ts
new file mode 100644
index 0000000000..d465e143fd
--- /dev/null
+++ b/src/core/persistence/receipt-true-up.ts
@@ -0,0 +1,92 @@
+/**
+ * #6696 (A1): the settlement-time true-up. A terminal request whose effects
+ * have all settled (none `queued` or `running`) keeps only
+ * `retainedReceiptBytes` of its admission reservation; the rest goes back to
+ * the brain and principal counters.
+ *
+ * Effects settle on many paths (the effect runner's complete/fail/park, the
+ * bulk embedding settles, `retry-effects`, restore's bulk fail), several of
+ * them inside transactions that lock effect rows and page keys before any
+ * counter. So the true-up never runs inside them: each path calls
+ * `trueUpRequests` after its own transaction commits, and it takes its own
+ * short transaction under the established lock order, counters first in
+ * their collated order, then a compare-and-set on the request rows (the
+ * reservation it read and the effect bytes it sized are unchanged, no effect
+ * re-armed). A decrement larger than a counter clamps at zero and is counted
+ * in `persistence.true_up.clamped`. Calling it twice changes nothing.
+ * `test/persistence-true-up-sites.test.ts` fails when an effect state change
+ * site does not reach it.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { lockCounters } from './journal.ts';
+import { principalKey, type WriteRequest } from './model.ts';
+import { declarePersistenceProtocol } from './protocol.ts';
+import { EFFECT_BYTES_SQL, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';
+
+type Candidate = Pick<WriteRequest, 'id' | 'intent' | 'authority' | 'outcome' | 'error_message' | 'error_detail' | 'client_request_id'
+ | 'terminal_reservation' | 'principal_kind' | 'principal_id'> & { compacted: boolean; effect_bytes: string; unfinished: boolean };
+
+const UNSETTLED = "('queued','running')";
+
+/** Shrinks each settled terminal request's reservation to what its receipt keeps; returns the bytes given back. */
+export async function trueUpRequests(engine: BrainEngine, requestIds: Iterable<string>): Promise<number> {
+ const ids = [...new Set(requestIds)];
+ if (!ids.length) return 0;
+ const rows = await engine.executeRaw<Candidate>(`SELECT r.id,r.intent,r.authority,r.outcome,r.error_message,r.error_detail,r.client_request_id,
+ r.terminal_reservation,r.principal_kind,r.principal_id,r.compacted,
+ COALESCE((SELECT SUM(${EFFECT_BYTES_SQL}) FROM persistence_effects e WHERE e.request_id=r.id),0)::text AS effect_bytes,
+ EXISTS(SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state IN ${UNSETTLED}) AS unfinished
+ FROM persistence_requests r WHERE r.id=ANY($1::uuid[]) AND r.state IN ('committed','failed','conflict','cancelled')`, [ids]);
+ const shrink = rows.flatMap(row => {
+ if (row.unfinished) return [];
+ const old = Number(row.terminal_reservation);
+ const kept = retainedReceiptBytes(row, { stage: row.compacted ? 'compacted' : 'terminal', effects: Number(row.effect_bytes) });
+ return kept < old ? [{ row, old, kept }] : [];
+ });
+ if (!shrink.length) return 0;
+ const keys = ['brain', ...shrink.map(({ row }) => principalKey({ kind: row.principal_kind, id: row.principal_id }))];
+ return engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await lockCounters(tx, keys);
+ const [freed] = await tx.executeRaw<{ freed: string }>(`WITH t AS (SELECT * FROM unnest($1::uuid[],$2::bigint[],$3::bigint[],$4::bigint[]) AS t(id,old,kept,effects)),
+ done AS (UPDATE persistence_requests r SET terminal_reservation=t.kept FROM t
+ WHERE r.id=t.id AND r.terminal_reservation=t.old
+ AND NOT EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.state IN ${UNSETTLED})
+ AND COALESCE((SELECT SUM(${EFFECT_BYTES_SQL}) FROM persistence_effects e WHERE e.request_id=r.id),0)=t.effects
+ RETURNING r.principal_kind,r.principal_id,t.old-t.kept AS freed),
+ d AS (SELECT k.key,SUM(done.freed) AS freed FROM done
+ CROSS JOIN LATERAL (VALUES ('brain'),('principal:'||done.principal_kind||':'||done.principal_id)) AS k(key) GROUP BY k.key),
+ released AS (UPDATE persistence_counters c SET 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 COALESCE(SUM(freed),0)::text AS freed FROM done`,
+ [shrink.map(s => s.row.id), shrink.map(s => s.old), shrink.map(s => s.kept), shrink.map(s => s.row.effect_bytes)]);
+ return Number(freed?.freed ?? 0);
+ });
+}
+
+/** Config row: the sequence the one-shot compacted-receipt sweep has walked through (`done` once it reached the end). */
+export const COMPACTED_SWEEP_KEY = 'persistence.true_up.compacted_through';
+
+/**
+ * #6696: receipts compacted before this release (redacted for purged content,
+ * or compacted by an older formula) can still hold their full admission
+ * reservation. One bounded pass walks `scan` rows of the sequence index past
+ * the stored cursor and trues up the compacted ones; the cursor reaches
+ * `done` at the end of the journal, after which the pass costs one config
+ * read. Receipts compacted from now on shrink at compaction. Returns the bytes
+ * given back.
+ */
+export async function sweepCompactedReservations(engine: BrainEngine, scan = 1000): Promise<{ freed_bytes: number; done: boolean }> {
+ const cursor = await engine.getConfig(COMPACTED_SWEEP_KEY);
+ if (cursor === 'done') return { freed_bytes: 0, done: true };
+ const after = cursor && /^\d+$/.test(cursor) ? cursor : '0';
+ const window = await engine.executeRaw<{ id: string; sequence: string; compacted: boolean }>(`SELECT id,sequence::text AS sequence,compacted
+ FROM persistence_requests WHERE sequence>$1::bigint ORDER BY sequence LIMIT $2`, [after, scan]);
+ if (!window.length) {
+ await engine.setConfig(COMPACTED_SWEEP_KEY, 'done');
+ return { freed_bytes: 0, done: true };
+ }
+ const freed = await trueUpRequests(engine, window.filter(row => row.compacted).map(row => row.id));
+ await engine.setConfig(COMPACTED_SWEEP_KEY, window[window.length - 1]!.sequence);
+ return { freed_bytes: freed, done: false };
+}
diff --git a/src/core/persistence/topology-receipts.ts b/src/core/persistence/topology-receipts.ts
index 6d8a372d34..d4bbee1e68 100644
--- a/src/core/persistence/topology-receipts.ts
+++ b/src/core/persistence/topology-receipts.ts
@@ -22,7 +22,7 @@ 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 reservation=receiptReservation(null);
+ const reservation=receiptReservation({});
const intentBytes=recovery?jsonBytes(input.intent):0;
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.`);
diff --git a/test/persistence-embedding-noop-settle.test.ts b/test/persistence-embedding-noop-settle.test.ts
index 9b9065b5be..824dcfe346 100644
--- a/test/persistence-embedding-noop-settle.test.ts
+++ b/test/persistence-embedding-noop-settle.test.ts
@@ -28,6 +28,9 @@ import { installPageEmbeddings, installPageProjection, readProjectionSnapshot }
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { EFFECT_BYTES_SQL, RECEIPT_RESERVATION_FLOOR, retainedReceiptBytes } from '../src/core/persistence/receipt-bytes.ts';
+import type { WriteRequest } from '../src/core/persistence/model.ts';
const databaseUrl = process.env.DATABASE_URL;
const signature = 'test:model:1536';
@@ -124,6 +127,23 @@ for (const kind of testBackends()) {
for (const p of [pending, ...Object.values(stale).filter(p => p.slug !== 'mixed/stale-unsealed')]) expect((await row(p.effectId)).state).toBe('committed');
});
+ check('#6696 (A1): after embed --stale, the bulk settle that finishes a request\'s last effect gives back its unused reservation', async () => {
+ await reset();
+ const p = await page('trueup/noop', true);
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw("UPDATE persistence_effects SET state='committed',outcome='{}'::jsonb WHERE request_id=$1::uuid AND kind<>'embedding'", [p.requestId]);
+ });
+ const reservation = async () => Number((await engine.executeRaw<{ n: string }>('SELECT terminal_reservation::text AS n FROM persistence_requests WHERE id=$1::uuid', [p.requestId]))[0]!.n);
+ expect(await reservation()).toBe(RECEIPT_RESERVATION_FLOOR);
+ await engine.executeRaw('UPDATE persistence_effects SET next_attempt_at=now() WHERE id=$1', [p.effectId]);
+ expect((await settleNoopEmbeddingEffects(engine, localHostId(), signature)).settled).toBe(1);
+ const [request] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [p.requestId]);
+ const [{ bytes }] = await engine.executeRaw<{ bytes: string }>(`SELECT SUM(${EFFECT_BYTES_SQL})::text AS bytes FROM persistence_effects WHERE request_id=$1::uuid`, [p.requestId]);
+ expect(await reservation()).toBe(retainedReceiptBytes(request!, { stage: 'terminal', effects: Number(bytes) }));
+ expect(await reservation()).toBeLessThan(RECEIPT_RESERVATION_FLOOR);
+ });
+
check('a settled no-op ends with the same row the runner leaves for one', async () => {
await reset();
const bulk = await page('rows/bulk', true);
diff --git a/test/persistence-receipt-true-up.test.ts b/test/persistence-receipt-true-up.test.ts
index 3652eb0d68..16f31d5f45 100644
--- a/test/persistence-receipt-true-up.test.ts
+++ b/test/persistence-receipt-true-up.test.ts
@@ -1,8 +1,10 @@
/**
- * #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.
+ * #6696 (A1): a finished receipt gives back the part of its admission
+ * reservation it does not keep: at completion when it has no unfinished
+ * effect (single and group paths), else when its last effect settles
+ * (`trueUpRequests`, idempotent); a reservation covers the retained intent
+ * (a ~100 KB body); 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';
@@ -11,10 +13,13 @@ 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 { admitWrite, claimNextWrite, completeWrite } from '../src/core/persistence/journal.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
+import { COMPACTED_SWEEP_KEY, sweepCompactedReservations, trueUpRequests } from '../src/core/persistence/receipt-true-up.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 { EFFECT_BYTES_SQL, RECEIPT_RESERVATION_FLOOR, receiptReservation, 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';
@@ -27,7 +32,19 @@ const counters = async (engine: BrainEngine) => Object.fromEntries((await engine
"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' });
+const formula = (r: WriteRequest, effects = 0) => retainedReceiptBytes(r, { stage: 'terminal', effects });
+const effectBytes = async (engine: BrainEngine, id: string) => Number((await engine.executeRaw<{ n: string }>(
+ `SELECT COALESCE(SUM(${EFFECT_BYTES_SQL}),0)::text AS n FROM persistence_effects WHERE request_id=$1::uuid`, [id]))[0]!.n);
+/** Runs the effect worker until none of the request's effects is queued or running (no embedding provider: those fail or skip). */
+async function settleEffects(engine: BrainEngine, id: string) {
+ for (let pass = 0; pass < 10; pass++) {
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE request_id=$1::uuid AND state='queued'", [id]);
+ await runPersistenceEffects(engine, { engine: engine.kind }, { hostId: localHostId(), limit: 20 });
+ const [open] = await engine.executeRaw("SELECT 1 FROM persistence_effects WHERE request_id=$1::uuid AND state IN ('queued','running')", [id]);
+ if (!open) return;
+ }
+ throw new Error('effects did not settle');
+}
for (const kind of testBackends()) {
describe(`receipt true-up at completion ${kind}`, () => {
@@ -59,13 +76,43 @@ for (const kind of testBackends()) {
expect(await reservations(engine)).toBe(Number(done.terminal_reservation));
});
- check('an unfinished effect keeps the admission reservation', async engine => {
+ check('an effectful page write keeps the floor until its last effect settles, then equals the formula', 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);
+ // A true-up while an effect is still open changes nothing.
+ expect(await trueUpRequests(engine, [published.id])).toBe(0);
+ await settleEffects(engine, published.id);
+ const done = await row(engine, published.id);
+ expect(Number(done.terminal_reservation)).toBe(formula(done, await effectBytes(engine, published.id)));
+ 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));
+ // Idempotent: a second call (another settle path reaching the same request) gives nothing back twice.
+ expect(await trueUpRequests(engine, [published.id])).toBe(0);
+ for (const value of Object.values(await counters(engine))) expect(value).toBe(Number(done.terminal_reservation));
+ });
+
+ check('a ~100 KB page write reserves its retained intent, completes, and settles to the formula', async engine => {
+ const requests = await requestFixture(engine);
+ const slug = 'large';
+ const body = 'x'.repeat(100_000);
+ const authority = await submissionAuthority(requests.ctx, 'put_page', requests.sourceId, requests.incarnation, slug);
+ const admitted = await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: requests.sourceId,
+ sourceIncarnation: requests.incarnation, slug, requestId: randomUUID(), callerIntent: { body }, intent: { body } });
+ expect(Number(admitted.terminal_reservation)).toBe(receiptReservation({ intent: { body }, authority }));
+ expect(Number(admitted.terminal_reservation)).toBeGreaterThan(100_000);
+ const published = await requests.publish(admitted);
+ expect(published.state).toBe('committed');
+ await settleEffects(engine, published.id);
+ const done = await row(engine, published.id);
+ const kept = formula(done, await effectBytes(engine, published.id));
+ expect(kept).toBeGreaterThan(100_000);
+ expect(Number(admitted.terminal_reservation)).toBeGreaterThanOrEqual(kept);
+ expect(Number(done.terminal_reservation)).toBe(kept);
+ for (const value of Object.values(await counters(engine))) expect(value).toBe(kept);
});
check('a three-member group completion trues up every member in one statement', async engine => {
@@ -115,6 +162,28 @@ for (const kind of testBackends()) {
for (const value of Object.values(await counters(engine))) expect(value).toBe(Number(done.terminal_reservation));
});
+ check('the one-shot sweep shrinks receipts compacted before this release with their full reservation, then stops', async engine => {
+ const requests = await requestFixture(engine);
+ const admitted = await requests.admit('legacy-redacted');
+ const claimed = (await claimNextWrite(engine, localHostId()))!;
+ await engine.transaction(tx => completeWrite(tx, claimed, 'failed', {}, { code: 'storage_error', message: 'generic failure' }));
+ // What an older release left: redacted and marked compacted, still charged the 16 KiB admission reservation.
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ const before = Number((await row(tx as BrainEngine, admitted.id)).terminal_reservation);
+ await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid',
+ [admitted.id, RECEIPT_RESERVATION_FLOOR]);
+ await tx.executeRaw("UPDATE persistence_counters SET terminal_bytes=terminal_bytes+$1 WHERE key='brain' OR key LIKE 'principal:%'", [RECEIPT_RESERVATION_FLOOR - before]);
+ });
+ for (const value of Object.values(await counters(engine))) expect(value).toBe(RECEIPT_RESERVATION_FLOOR);
+ expect(await sweepCompactedReservations(engine, 10)).toMatchObject({ done: false });
+ const done = await row(engine, admitted.id);
+ expect(Number(done.terminal_reservation)).toBe(retainedReceiptBytes(done, { stage: 'compacted' }));
+ for (const value of Object.values(await counters(engine))) expect(value).toBe(Number(done.terminal_reservation));
+ expect(await sweepCompactedReservations(engine, 10)).toEqual({ freed_bytes: 0, done: true });
+ expect(await engine.getConfig(COMPACTED_SWEEP_KEY)).toBe('done');
+ });
+
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');
diff --git a/test/persistence-true-up-sites.test.ts b/test/persistence-true-up-sites.test.ts
new file mode 100644
index 0000000000..7100647f85
--- /dev/null
+++ b/test/persistence-true-up-sites.test.ts
@@ -0,0 +1,50 @@
+/**
+ * #6696 (A1) guard: every site that moves an effect to a settled state
+ * (`committed`, `failed`, or a computed state) must reach `trueUpRequests`
+ * after its transaction, or the request keeps its admission reservation
+ * forever. A new site fails here until it is wired and listed.
+ */
+import { expect, test } from 'bun:test';
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+
+const ROOT = join(import.meta.dir, '..');
+const SRC = join(ROOT, 'src');
+
+/** Settling file -> the file whose code calls trueUpRequests for it (itself when it calls it directly). */
+const SITES: Record<string, string> = {
+ // completeEffect / parkEffect / failEffect run only under the effect runner, which trues up every request it claimed.
+ 'src/core/persistence/effect-journal.ts': 'src/core/persistence/effects.ts',
+ 'src/core/persistence/effects.ts': 'src/core/persistence/effects.ts',
+ 'src/core/persistence/embedding-settlement.ts': 'src/core/persistence/embedding-settlement.ts',
+ 'src/core/persistence/embedding-noop-settle.ts': 'src/core/persistence/embedding-noop-settle.ts',
+ 'src/core/persistence/effect-retry.ts': 'src/core/persistence/effect-retry.ts',
+ 'src/core/shared-skills/restore.ts': 'src/core/backup/snapshot.ts',
+};
+/** Files that may call the effect-journal settle helpers: the runner and the handlers it dispatches. */
+const RUNNER_FILES = new Set(['src/core/persistence/effects.ts', 'src/core/persistence/effect-facts.ts', 'src/core/persistence/effect-links.ts',
+ 'src/core/persistence/effect-journal.ts']);
+
+function files(dir: string): string[] {
+ return readdirSync(dir).flatMap(name => {
+ const path = join(dir, name);
+ return statSync(path).isDirectory() ? files(path) : path.endsWith('.ts') ? [path] : [];
+ });
+}
+const sources = files(SRC).map(path => ({ path: relative(ROOT, path), text: readFileSync(path, 'utf8') }));
+/** An UPDATE of persistence_effects whose SET list (before WHERE) assigns `state` anything but queued/running, in any position. */
+const SETTLE = /UPDATE\s+persistence_effects\b(?:(?!\bWHERE\b)[^`;])*?\bSET\b(?:(?!\bWHERE\b)[^`;])*?(?<![.\w])state\s*=\s*(?!'queued'|'running')/;
+
+test('every effect settle site is listed and reaches trueUpRequests', () => {
+ const settling = sources.filter(file => SETTLE.test(file.text)).map(file => file.path).sort();
+ expect(settling).toEqual(Object.keys(SITES).sort());
+ for (const [site, caller] of Object.entries(SITES)) {
+ const text = sources.find(file => file.path === caller)?.text ?? '';
+ expect({ site, caller, calls: /trueUpRequests\(/.test(text) }).toEqual({ site, caller, calls: true });
+ }
+});
+
+test('the effect-journal settle helpers are called only under the effect runner', () => {
+ const callers = sources.filter(file => /\b(?:completeEffect|failEffect|parkEffect)\(/.test(file.text)).map(file => file.path);
+ expect(callers.filter(path => !RUNNER_FILES.has(path))).toEqual([]);
+});