Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

belief ledger: fold plan-mode and managed-mode reads; reuse unchanged subjects

garrytan80b0c6f45340
diff --git a/src/core/belief/ledger.ts b/src/core/belief/ledger.ts
index 28585bd0f5..3e77d2f99a 100644
--- a/src/core/belief/ledger.ts
+++ b/src/core/belief/ledger.ts
@@ -15,7 +15,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { assertHeldPageKeys } from '../page-state/guards.ts';
-import { readManagedMode } from '../persistence/managed-mode.ts';
+import { managedModeFromRows } from '../persistence/managed-mode.ts';
import { COVERAGE_KEY, heldKey, lifetimeRef, pageKey, sha256Hex, canonicalJson, factKeySubject, slugRef } from './keys.ts';
import { readBeliefState, readFactsById, type RawPage, type RawState } from './state.ts';
import { keyedSubjects, keyFact, pageNeeds, type KeyContext, type Subject } from './subjects.ts';
@@ -83,27 +83,41 @@ export function beliefBatchCovers(sourceId: string, slugs: readonly string[]): b
/** True inside any belief batch: a nested writer's own publication commits with the enclosing transaction, not before it. */
export const insideBeliefBatch = (): boolean => !!store.getStore();
-/** Coverage and purge probes for one source, in one read. `coverage` is the newest coverage event other than `coverage.restored`. */
-export async function readLedgerSource(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<{ incarnation: string; purgeEpoch: number; coverage: string | null; purgesPossible: boolean } | null> {
- const [row] = await tx.executeRaw<Record<string, unknown>>(`SELECT s.incarnation::text AS incarnation, s.purge_epoch,
+/**
+ * Coverage and purge probes for one source, in one read. `coverage` is the newest coverage event other than `coverage.restored`.
+ * `batch` (a batch beginning) also reads the managed mode and, when coverage is active, switches the transaction to
+ * generic plans for the state read that follows, returning the mode to restore (`readBeliefState`'s `planModePrev`).
+ */
+export async function readLedgerSource(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, opts: { batch?: boolean } = {}): Promise<{ incarnation: string; purgeEpoch: number;
+ coverage: string | null; purgesPossible: boolean; managedRows?: Array<{ enabled: unknown }>; planModePrev?: string } | null> {
+ const [row] = await tx.executeRaw<Record<string, unknown>>(`${opts.batch ? `SELECT q.*, (SELECT COALESCE(json_agg(json_build_object('enabled', b.enabled)), '[]'::json)
+ FROM persistence_brain b WHERE b.singleton = 1) AS managed_rows, current_setting('plan_cache_mode') AS plan_mode_prev,
+ set_config('plan_cache_mode', CASE WHEN q.coverage IS NOT NULL AND q.coverage <> 'coverage.stopped' THEN 'force_generic_plan'
+ ELSE current_setting('plan_cache_mode') END, true) FROM (` : ''}SELECT s.incarnation::text AS incarnation, s.purge_epoch,
(SELECT e.event_type FROM belief_events e WHERE e.source_id = s.id AND e.subject_kind = 'coverage' AND e.subject_key = $2
AND e.source_incarnation = s.incarnation AND e.event_type <> 'coverage.restored' ORDER BY e.id DESC LIMIT 1) AS coverage,
(s.purge_epoch > 0 OR EXISTS (SELECT 1 FROM fact_purges WHERE source_id = s.id) OR EXISTS (SELECT 1 FROM take_purges WHERE source_id = s.id)
OR EXISTS (SELECT 1 FROM page_purges WHERE source_id = s.id)) AS purges
- FROM sources s WHERE s.id = $1`, [sourceId, COVERAGE_KEY]);
+ FROM sources s WHERE s.id = $1${opts.batch ? ') q' : ''}`, [sourceId, COVERAGE_KEY]);
if (!row) return null;
return { incarnation: String(row.incarnation), purgeEpoch: Number(row.purge_epoch), coverage: (row.coverage as string | null) ?? null,
- purgesPossible: row.purges === true };
+ purgesPossible: row.purges === true,
+ ...(opts.batch ? { managedRows: row.managed_rows as Array<{ enabled: unknown }>, planModePrev: String(row.plan_mode_prev) } : {}) };
}
export const coverageActive = (coverage: string | null) => coverage != null && coverage !== 'coverage.stopped';
async function beginBeliefBatch(tx: BrainEngine, opts: BeliefBatchOptions): Promise<Batch | null> {
- const source = await readLedgerSource(tx, opts.sourceId);
+ const source = await readLedgerSource(tx, opts.sourceId, { batch: true });
if (!source || !coverageActive(source.coverage)) return null;
- assertHeldPageKeys(tx, opts.slugs.map(slug => ({ sourceId: opts.sourceId, slug })));
- const pre = await readBeliefState(tx, opts.sourceId, opts.slugs);
- return { opts, publicationId: opts.publicationId ?? randomUUID(), incarnation: source.incarnation, managed: await readManagedMode(tx),
+ try {
+ assertHeldPageKeys(tx, opts.slugs.map(slug => ({ sourceId: opts.sourceId, slug })));
+ } catch (error) {
+ await tx.executeRaw(`SELECT set_config('plan_cache_mode', $1, true)`, [source.planModePrev]);
+ throw error;
+ }
+ const pre = await readBeliefState(tx, opts.sourceId, opts.slugs, [], undefined, source.planModePrev);
+ return { opts, publicationId: opts.publicationId ?? randomUUID(), incarnation: source.incarnation, managed: managedModeFromRows(source.managedRows!).enabled,
purgesPossible: source.purgesPossible, pre, notes: [] };
}
@@ -374,7 +388,7 @@ export async function finalizeBeliefEvents(tx: BrainEngine, batch: Batch): Promi
const ctx = (side: 'pre' | 'post'): KeyContext => ({ incarnation: batch.incarnation, lifetimes,
pagesBySlug: new Map(streams.flatMap(s => { const p = side === 'pre' ? s.pre : s.post; return p ? [[p.slug, p] as const] : []; })) });
const preSubjects = keyedSubjects(ctx('pre'), pre, visibilityIn(pre));
- const postSubjects = keyedSubjects(ctx('post'), post, visibilityIn(post));
+ const postSubjects = keyedSubjects(ctx('post'), post, visibilityIn(post), { state: pre, subjects: preSubjects });
const postPageAt = (slug: string) => streams.find(s => s.post?.slug === slug)?.post ?? null;
const lifetimeAt = (slug: string) => { const page = postPageAt(slug); return page ? lifetimes.get(page.id) ?? null : null; };
const subjectsByStream = new Map<string, Subject[]>();
diff --git a/src/core/belief/state.ts b/src/core/belief/state.ts
index 618ba3a1b8..3ef3f7152f 100644
--- a/src/core/belief/state.ts
+++ b/src/core/belief/state.ts
@@ -70,12 +70,15 @@ export function __suppressBeliefTouchedSignalForTests(suppressed: boolean): void
* pages are the same pages at the same slugs: its rows are `known`'s, with fact
* entity pages and link endpoints read fresh. With `track_counts` off every part is read.
*/
-export async function readBeliefState(tx: BrainEngine, sourceId: string, slugs: readonly string[], pageIds: readonly number[] = [], known?: RawState): Promise<RawState> {
+export async function readBeliefState(tx: BrainEngine, sourceId: string, slugs: readonly string[], pageIds: readonly number[] = [], known?: RawState,
+ planModePrev?: string): Promise<RawState> {
// One statement: each part selects the batch's pages itself ($1 source, $2 slugs, $3 page ids) and returns its rows as JSON.
// Fingerprints of claim texts `known` (the batch's pre-read) already has are not recomputed: the SQL fingerprint
// is most of a large page's read. The statement runs with a generic plan (restored after): under the default
// plan_cache_mode a bulk import re-plans it for every page as the tables grow (about 3 ms each, rising with size).
- // $5 `known`'s counters, $6 its stream pages (id:slug), $7 its facts' entity slugs, $8 the test suppression.
+ // $5 `known`'s counters, $6 its stream pages (id:slug), $7 its facts' entity slugs, $8 the test suppression,
+ // $9 the plan_cache_mode to restore (the statement is planned before it runs, so it restores the mode itself);
+ // `planModePrev`: the caller already switched to generic plans (readLedgerSource's `batch`) and this is the mode it replaced.
const knownFp = new Map<string, string>([...(known?.facts ?? []).map(f => [f.fact, f.fp] as const), ...(known?.takes ?? []).map(k => [k.claim, k.claim_fp] as const)]);
const params = [sourceId, [...slugs], [...pageIds], [...knownFp.keys()], known?.counts ?? null, (known?.pages ?? []).map(p => `${p.id}:${p.slug}`),
[...new Set((known?.facts ?? []).flatMap(f => f.entity_slug == null ? [] : [f.entity_slug]))], touchedSignalSuppressed];
@@ -84,11 +87,12 @@ export async function readBeliefState(tx: BrainEngine, sourceId: string, slugs:
const unwritten = (i: number) => `(SELECT ok FROM reuse) AND ($8::boolean OR (${WRITES[i]})::text = ($5::text[])[${i + 1}])`;
const part = (i: number, sql: string) => `CASE WHEN ${unwritten(i)} THEN NULL ELSE (SELECT COALESCE(json_agg(q), '[]'::json) FROM (
${sql}) q) END`;
- const [mode] = await tx.executeRaw<{ prev: string }>(`SELECT current_setting('plan_cache_mode') AS prev, set_config('plan_cache_mode', 'force_generic_plan', true)`);
+ params.push(planModePrev ?? (await tx.executeRaw<{ prev: string }>(`SELECT current_setting('plan_cache_mode') AS prev,
+ set_config('plan_cache_mode', 'force_generic_plan', true)`))[0]!.prev);
const [row] = await tx.executeRaw<Record<string, Record<string, unknown>[] | null>>(`WITH reuse AS (SELECT ($8::boolean OR current_setting('track_counts') = 'on')
AND $5::text[] IS NOT NULL AND ARRAY(SELECT p.id || ':' || p.slug FROM pages p
WHERE p.source_id = $1 AND (p.slug = ANY($2::text[]) OR p.id = ANY($3::int[])) ORDER BY 1) = ARRAY(SELECT unnest($6::text[]) ORDER BY 1) AS ok)
- SELECT
+ SELECT set_config('plan_cache_mode', $9, true) AS restored,
(SELECT COALESCE(json_agg(q), '[]'::json) FROM (
SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.knowledge_revision::text AS revision,
p.content_hash, p.trust_tier, (${privatePagesFilterFragment('p')}) AS visible, s.incarnation::text AS incarnation,
@@ -120,7 +124,6 @@ SELECT p.id, p.slug, p.deleted_at IS NOT NULL AS deleted, p.knowledge_revision::
SELECT p.id, p.slug, p.source_id, s.incarnation::text AS incarnation FROM pages p JOIN sources s ON s.id = p.source_id
WHERE p.id = ANY(ARRAY(SELECT unnest(ARRAY[e.from_page_id, e.to_page_id, e.origin_page_id])
FROM ((${OWNED_ROWS('links', PAGE_IDS, ENDS)}) UNION ALL (${OWNED_ROWS('link_transitions', PAGE_IDS, ENDS)})) e))) q) AS endpoints`, params);
- await tx.executeRaw(`SELECT set_config('plan_cache_mode', $1, true)`, [mode!.prev]);
const { pages: pageRows, counts, facts, entity_pages: entityPages, takes, links, transitions, endpoints } = row!;
const byId = new Map(endpoints!.map(r => [Number(r.id), { id: Number(r.id), slug: String(r.slug), source_id: String(r.source_id), incarnation: String(r.incarnation) }]));
const endpoint = (id: unknown): RawEndpoint | null => id == null ? null : byId.get(Number(id)) ?? null;
@@ -131,7 +134,8 @@ SELECT p.id, p.slug, p.source_id, s.incarnation::text AS incarnation FROM pages
return {
pages,
facts: facts ? facts.map(r => toFact(r.fp == null ? { ...r, fp: knownFp.get(String(r.fact)) } : r))
- : known!.facts.map(f => ({ ...f, entity_page_id: f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null })),
+ : known!.facts.some(f => f.entity_page_id !== (f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null))
+ ? known!.facts.map(f => ({ ...f, entity_page_id: f.entity_slug == null ? null : entityPageOf.get(f.entity_slug) ?? null })) : known!.facts,
takes: takes ? takes.map(r => toTake(r.claim_fp == null ? { ...r, claim_fp: knownFp.get(String(r.claim)) } : r)) : known!.takes,
links: links ? links.map(r => ({ id: Number(r.id), from: endpoint(r.f)!, to: endpoint(r.t)!, origin: endpoint(r.o), link_type: String(r.link_type),
link_source: (r.link_source as string | null) ?? null, context: String(r.context ?? ''), origin_field: (r.origin_field as string | null) ?? null,
diff --git a/src/core/belief/subjects.ts b/src/core/belief/subjects.ts
index 41e2d01b15..0deb959da8 100644
--- a/src/core/belief/subjects.ts
+++ b/src/core/belief/subjects.ts
@@ -50,10 +50,23 @@ export function keyFact(ctx: KeyContext, f: RawFact): { key: string; stream: str
return { stream, entity, key: factKey(subject, f.fp, f.visibility) };
}
-export function keyedSubjects(ctx: KeyContext, state: RawState, pageVisibility: (pageId: number) => string): Subject[] {
+/**
+ * `earlier`: the same batch's other side, keyed with the same lifetimes. Its fact and take subjects are reused when
+ * `state` carries the very same row arrays over the same pages at the same slugs (the post-read reused them), with
+ * take visibility taken from this side.
+ */
+export function keyedSubjects(ctx: KeyContext, state: RawState, pageVisibility: (pageId: number) => string,
+ earlier?: { state: RawState; subjects: Subject[] }): Subject[] {
+ const samePages = earlier != null && earlier.state.pages.length === state.pages.length
+ && state.pages.every(p => earlier.state.pages.some(q => q.id === p.id && q.slug === p.slug));
+ const reuse = (kind: 'fact' | 'take', rows: unknown[], before: unknown[]) => samePages && rows === before ? earlier!.subjects.filter(s => s.kind === kind) : null;
+ const pageIdBySlug = new Map(state.pages.map(p => [p.slug, p.id]));
const out: Subject[] = [];
+ const reusedFacts = reuse('fact', state.facts, earlier?.state.facts ?? []);
+ const reusedTakes = reuse('take', state.takes, earlier?.state.takes ?? []);
+ if (reusedFacts) out.push(...reusedFacts);
const facts = new Map<string, { rows: RawFact[]; stream: string; entity: SubjectRef | null }>();
- for (const f of state.facts) {
+ for (const f of reusedFacts ? [] : state.facts) {
const { key, stream, entity } = keyFact(ctx, f);
const group = facts.get(key) ?? { rows: [], stream, entity };
group.rows.push(f);
@@ -68,8 +81,9 @@ export function keyedSubjects(ctx: KeyContext, state: RawState, pageVisibility:
label: { subject_slug: stream, ...(head.entity_slug && head.entity_slug !== stream ? { entity_slug: head.entity_slug } : {}) } });
}
const pagesById = new Map(state.pages.map(p => [p.id, p]));
+ if (reusedTakes) out.push(...reusedTakes.map(t => ({ ...t, visibility: pageVisibility(pageIdBySlug.get(t.stream)!) })));
const byClaim = new Map<string, RawTake[]>();
- for (const t of state.takes) {
+ for (const t of reusedTakes ? [] : state.takes) {
const group = `${t.page_id}\u0000${takeClaimHash(t.claim, t.kind, t.holder)}`;
byClaim.set(group, [...byClaim.get(group) ?? [], t]);
}
diff --git a/test/belief-ledger-touched.test.ts b/test/belief-ledger-touched.test.ts
index 80dfbfeea8..66653ee27d 100644
--- a/test/belief-ledger-touched.test.ts
+++ b/test/belief-ledger-touched.test.ts
@@ -7,7 +7,9 @@
* touched signal and shows the drift check catches the event it loses.
*/
import { afterEach, describe, expect, test } from 'bun:test';
-import { __suppressBeliefTouchedSignalForTests, readBeliefState } from '../src/core/belief/state.ts';
+import { __suppressBeliefTouchedSignalForTests, readBeliefState, type RawState } from '../src/core/belief/state.ts';
+import { withBeliefBatch } from '../src/core/belief/ledger.ts';
+import { keyedSubjects } from '../src/core/belief/subjects.ts';
import { beliefLedgerEntry } from '../src/commands/doctor/checks/belief-ledger.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
import type { Check } from '../src/commands/doctor.ts';
@@ -88,6 +90,25 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
});
}, 120_000);
+ test('a batch reads state under generic plans and leaves its projections and the rest of the transaction on the mode it found', async () => {
+ await brain(async b => {
+ await seeded(b);
+ const modes = await b.engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: b.sourceId, slug: SLUG }]);
+ await tx.executeRaw("SET LOCAL plan_cache_mode = 'force_custom_plan'");
+ const mode = async () => (await tx.executeRaw<{ m: string }>("SELECT current_setting('plan_cache_mode') AS m"))[0]!.m;
+ const inside = await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [SLUG], op: 'probe_plan_mode' }, mode);
+ return [inside, await mode()];
+ });
+ expect(modes).toEqual(['force_custom_plan', 'force_custom_plan']);
+ await expect(b.engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL plan_cache_mode = 'force_custom_plan'");
+ try { await withBeliefBatch(tx, { sourceId: b.sourceId, slugs: [SLUG], op: 'probe_unheld' }, async () => null); } catch {}
+ return (await tx.executeRaw<{ m: string }>("SELECT current_setting('plan_cache_mode') AS m"))[0]!.m;
+ })).resolves.toBe('force_custom_plan');
+ });
+ }, 120_000);
+
test('with track_counts off the post-read reads every table again', async () => {
await brain(async b => {
await seeded(b);
@@ -109,3 +130,18 @@ for (const engineCase of testBackends().map(beliefEngineCase)) {
}, 120_000);
});
}
+
+test('reused take subjects take their visibility from the side they are keyed for', () => {
+ const page = { id: 7, slug: SLUG, deleted: false, revision: '1', content_hash: null, tier: 'unknown', visible: true, large: false, incarnation: 'i' };
+ const take = { id: 70, page_id: 7, row_num: 1, claim: 'Acme will win', claim_fp: 'fp', kind: 'take', holder: 'brain', weight: 0.5, since_date: null,
+ until_date: null, source: null, active: true, resolved_at: null, resolved_outcome: null, resolved_value: null, resolved_unit: null, resolved_source: null,
+ resolved_by: null, resolved_quality: null, tier: 'unknown' };
+ const pre: RawState = { pages: [page], facts: [], takes: [take], links: [], transitions: [], writerTier: null };
+ const post: RawState = { ...pre, pages: [{ ...page, visible: false }] };
+ const ctx = (state: RawState) => ({ incarnation: 'i', lifetimes: new Map([[7, '00000000-0000-0000-0000-000000000007']]), pagesBySlug: new Map(state.pages.map(p => [p.slug, p])) });
+ const visibility = (state: RawState) => (id: number) => state.pages.find(p => p.id === id)?.visible === false ? 'private' : 'world';
+ const before = keyedSubjects(ctx(pre), pre, visibility(pre));
+ const after = keyedSubjects(ctx(post), post, visibility(post), { state: pre, subjects: before });
+ expect(before.map(s => s.visibility)).toEqual(['world']);
+ expect(after.map(s => [s.key, s.visibility])).toEqual([[before[0]!.key, 'private']]);
+});