Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): put_page re-extraction feeds the same-page shadow counter (#6333)

time-attackacd9bf1f6cf3
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index 3c9e50a4a1..71c4df7a62 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -30,7 +30,7 @@ Managed facts extraction (withdrawn-candidate skip and recovery, conversation fa
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
-- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `dispatchFactsBackstopEffect` stamps the job's `notabilityFilter` from `facts.page_write_notability_filter` (default `all`; `facts/notability-filter.ts`), read inside the dispatch transaction so retries keep one filter (#6231). `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.
+- `src/core/persistence/effect-facts.ts` + `page-advisories.ts` + `derived-extraction-gate.ts` — bounded writer-lint/facts-backstop outbox. `dispatchFactsBackstopEffect` stamps the job's `notabilityFilter` from `facts.page_write_notability_filter` (default `all`; `facts/notability-filter.ts`), read inside the dispatch transaction so retries keep one filter (#6231). The job also carries the stable session `put_page:<slug>` (mirrors sync's `sync:<slug>`), so a re-extraction of the page feeds the #6333 `would_dedup_same_page` shadow counter and the facts it writes record that `source_session` (visible to `recall --session`). `derivedExtractionSkip` is the writer-confinement rule facts and Life Chronicle share (slug-bound/delegated/restricted → `slug_bound_client`; an operation-bound grant without `extract_facts` → `operation_bound_client`). Eligibility, anti-loop, selected configuration, original/current grants and source/page revision guards precede scheduling; a write that keeps the `compiled_truth` (the only text extraction reads) of a live, already-eligible page skips with `body_unchanged` only when a facts-absorb job bound to that page id has completed and no facts-backstop effect or startable facts-absorb job for it is still pending (the new revision would supersede it), so a timeline or frontmatter-only republish such as `repair timeline` queues no extraction for an extracted page, while a page no extraction ever completed for still queues one. Page publication records the effect; job insertion and completion use its stable idempotency key. Managed backstop retains the committed original page request as the facts-absorb job authority, including OAuth/stdio origin; no fabricated CLI authority or blanket managed skip. Legacy unsupported raw queue/fence paths remain refused. Tests: `test/persistence-facts-backstop.test.ts`, `test/managed-facts-backstop.test.ts`.
- `src/core/persistence/effect-recovery-scan.ts` — bounded owner-scoped recovery selection rotates through durable effect IDs even when an earlier root has no available native lock, and wraps to retry prior roots. It never changes recovery authority or releases reservations. `test/persistence-effect-recovery-fairness.test.ts` holds two real native roots, recovers a later mirror, then verifies wraparound cleanup and exact counters on both engines.
diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.ts
index 46d7e6d362..35e99d69fc 100644
--- a/src/core/persistence/effect-facts.ts
+++ b/src/core/persistence/effect-facts.ts
@@ -145,7 +145,8 @@ export async function dispatchFactsBackstopEffect(engine: BrainEngine, effect: P
// #6231: the page-write filter in force when the effect dispatches; the job keeps it across retries.
const notabilityFilter = await resolvePageWriteNotabilityFilter(tx);
const job = await new MinionQueue(tx).add('facts-absorb', {
- slug: effect.data.slug, sourceId: effect.source_id, source: 'mcp:put_page', notabilityFilter,
+ // #6333: a stable per-page session (mirrors sync's `sync:<slug>`) so a re-extraction feeds the same-page shadow counter.
+ slug: effect.data.slug, sourceId: effect.source_id, source: 'mcp:put_page', sessionId: `put_page:${effect.data.slug}`, notabilityFilter,
visibility: effect.data.visibility === 'world' ? 'world' : 'private',
persistence_request_id: effect.request_id, page_id: effect.data.page_id, revision: effect.revision,
}, { queue: 'default', idempotency_key: `facts-absorb:write:${effect.request_id}`, max_attempts: 5, backoff_delay: 60_000 });
diff --git a/test/facts-absorb-put-page-session-6333.test.ts b/test/facts-absorb-put-page-session-6333.test.ts
new file mode 100644
index 0000000000..022f6c5a0d
--- /dev/null
+++ b/test/facts-absorb-put-page-session-6333.test.ts
@@ -0,0 +1,116 @@
+/**
+ * #6333 measurement gap: the page-write facts backstop enqueued `facts-absorb`
+ * with no session, so a managed `put_page` re-extraction could never feed the
+ * `would_dedup_same_page` shadow counter (the same-page predicate needs a
+ * session; sync imports carry `sync:<slug>`). The page-write effect now carries
+ * the stable session `put_page:<slug>`, threaded through the job to the facts
+ * it writes.
+ *
+ * End to end: committed page write → facts-backstop effect dispatch → the
+ * facts-absorb handler → extraction, on an unmanaged and a managed brain. Stub
+ * transports only; zero paid calls.
+ */
+import { afterAll, beforeAll, afterEach, 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 { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { submissionAuthority } from '../src/core/persistence/authority.ts';
+import { admitWrite, claimNextWrite } from '../src/core/persistence/journal.ts';
+import { localHostId, registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { claimPersistenceEffect } from '../src/core/persistence/effect-journal.ts';
+import { dispatchFactsBackstopEffect } from '../src/core/persistence/effect-facts.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { makeFactsAbsorbHandler } from '../src/core/minions/handlers/facts-absorb.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const DIMS = 1536;
+const ENTITY = 'people/alice-example';
+const PAGE = 'notes/example';
+const SESSION = `put_page:${PAGE}`;
+const config = { engine: 'pglite' as const, embedding_disabled: true };
+const content = `---\ntype: note\ntitle: Field notes\n---\n\n${'Alice Example is the lead of the example company platform team, per this record. '.repeat(3)}`;
+let engine: PGLiteEngine;
+
+function vector(): number[] {
+ const v = new Array<number>(DIMS).fill(0);
+ v[0] = 1;
+ return v;
+}
+function reworded(): number[] {
+ const v = new Array<number>(DIMS).fill(0);
+ v[0] = Math.sqrt(0.9);
+ v[1] = Math.sqrt(0.1);
+ return v;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterEach(() => { __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway(); });
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+
+async function pageWriteJob(): Promise<{ id: number; data: Record<string, unknown> }> {
+ const [source] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation FROM sources WHERE id='default'");
+ const ctx: OperationContext = { engine, config, dryRun: false, remote: false, sourceId: 'default', logger: { info() {}, warn() {}, error() {} } };
+ const authority = await submissionAuthority(ctx, 'put_page', 'default', source.incarnation, PAGE);
+ await admitWrite(engine, { principal: authority.principal, authority, operation: 'put_page', sourceId: 'default',
+ sourceIncarnation: source.incarnation, slug: PAGE, pageId: null, requestId: randomUUID(), callerIntent: { content }, intent: { content } });
+ const row = (await claimNextWrite(engine, localHostId()))!;
+ const published = await publishMutation(engine, row, await preparePageMutation(engine, row, config));
+ expect(published.outcome?.facts_backstop).toEqual({ queued: true });
+ await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now()+interval '1 hour' WHERE kind<>'facts-backstop'");
+ const effect = (await claimPersistenceEffect(engine, localHostId()))!;
+ expect(effect.kind).toBe('facts-backstop');
+ await dispatchFactsBackstopEffect(engine, effect, localHostId());
+ const [job] = await engine.executeRaw<{ id: number; data: Record<string, unknown> }>("SELECT id,data FROM minion_jobs WHERE name='facts-absorb'");
+ return job;
+}
+
+async function scenario(managed: boolean) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6333-put-page-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: 'test' }, async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', '156');
+ await engine.setConfig('embedding_model', 'openai:text-embedding-3-small');
+ await engine.setConfig('embedding_dimensions', String(DIMS));
+ await registerLocalWriter(engine, 'cli');
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });
+ await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: 'Alice Example is a person.', timeline: '', frontmatter: {} });
+ await engine.insertFact({ fact: 'Alice Example leads the platform team at the example company', entity_slug: ENTITY, kind: 'fact',
+ visibility: 'private', source: 'mcp:put_page', source_session: SESSION, embedding: Float32Array.from(vector()),
+ embedding_model: 'openai:text-embedding-3-small' }, { source_id: 'default' });
+ const job = await pageWriteJob();
+ expect(job.data.sessionId).toBe(SESSION);
+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ __setChatTransportForTests(async (): Promise<ChatResult> => ({
+ text: JSON.stringify({ facts: [{ fact: 'Alice Example is the lead of the example company platform team', kind: 'fact', entity: ENTITY, confidence: 1, notability: 'high' }] }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test',
+ }));
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => ({ embeddings: values.map(() => reworded()) })) as never);
+ const result = await makeFactsAbsorbHandler(engine)({ id: job.id, name: 'facts-absorb', data: job.data, signal: new AbortController().signal } as never) as Record<string, unknown>;
+ expect(result.would_dedup_same_page).toBe(1);
+ const sessions = await engine.executeRaw<{ source_session: string | null }>(
+ "SELECT source_session FROM facts WHERE source_id='default' AND entity_slug=$1 AND expired_at IS NULL ORDER BY id", [ENTITY]);
+ expect(sessions.map(r => r.source_session)).toEqual([SESSION, SESSION]);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+describe('#6333: a put_page re-extraction feeds the same-page shadow counter', () => {
+ test('the page-write job carries put_page:<slug> and the unmanaged backstop counts the rewording', () => scenario(false), 120_000);
+ test('the managed preparer counts the rewording from the page-write job', () => scenario(true), 120_000);
+});