Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(facts): publish an entity's facts in parts of at most 50 so one publication holds the counter row for one part (#6898)

garrytanb7edd2b5bd17
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 812b3c0c24..acfd86c2ac 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -70,7 +70,15 @@ export interface ManagedFactIntent extends Record<string, unknown> {
capture_source?: string;
/** #5575 I2: the extraction's taint, declared at prompt-build time (trust/taint.ts). */
derivation?: DerivationDeclaration;
+ /**
+ * #6898 follow-up: set when the entity's facts were split into parts of at most
+ * MANAGED_FACTS_PUBLICATION_MAX facts, each its own request and publication. `deferred_facts` counts
+ * the facts left to later parts and `follow_up` names their request ids; both are copied into the
+ * part's receipt, so a part never reads as the whole group (the batch's completion request does).
+ */
+ part?: ManagedFactsPart;
}
+export interface ManagedFactsPart { index: number; of: number; deferred_facts: number; follow_up: string[] }
export interface ManagedFactsSession {
authority: WriteAuthority; binding: WorktreeBinding | null; config: GBrainConfig;
batchKey: string; inputDigest: string; origin: ManagedFactOrigin | null; originalRequestId: string | null;
@@ -95,6 +103,15 @@ export interface ManagedFactsSession {
/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */
const MAX_FILE_REFUSAL_RETRIES = 3;
+/**
+ * #6898 follow-up: the most facts one entity request publishes. A publication holds the brain-wide
+ * persistence_counters row from its admission check to its commit, and each fact adds a dedup check and
+ * an index insert to that window (measured ~3.5 ms per fact on Postgres; 200 facts on a 1.6 MB entity page
+ * held it 1.2 s, past the 1 s lock_timeout every other admission waits under). A larger group is admitted
+ * as parts in the same batch, published one after another in queue order.
+ */
+export const MANAGED_FACTS_PUBLICATION_MAX = 50;
+
const receiptFix = (requestId: string): Action => readFix('Reads the fact request\'s durable receipt: its operation, state and outcome, read-only.',
{ argv: ['gbrain', 'write-request', '--', requestId], mcp: { tool: 'get_write_request', arguments: { request_id: requestId } } });
const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`,
@@ -104,8 +121,8 @@ const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sou
const embeddingsFix = (): Action => readFix('Reports the brain\'s embedding model, dimensions and vector columns, read-only.',
{ argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'] });
-function managedFactRequestId(batchKey: string, slug: string): string {
- const hex = digest([batchKey, slug]);
+function managedFactRequestId(batchKey: string, slug: string, part = 1): string {
+ const hex = digest(part === 1 ? [batchKey, slug] : [batchKey, slug, part]);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
}
@@ -307,7 +324,7 @@ async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSes
result.fact_ids.push(...(out.fact_ids as number[] ?? []));
if (out.withdrawn_skipped) result.withdrawn_skipped = (result.withdrawn_skipped ?? 0) + Number(out.withdrawn_skipped);
if (out.would_dedup_same_page) result.would_dedup_same_page = (result.would_dedup_same_page ?? 0) + Number(out.would_dedup_same_page);
- if (out.inserted && out.fenced) result.entity_slugs.push(row.slug);
+ if (out.inserted && out.fenced && !result.entity_slugs.includes(row.slug)) result.entity_slugs.push(row.slug);
}
}
return result;
@@ -429,7 +446,7 @@ async function readmitRefusedFacts(engine: BrainEngine, followUp: ManagedFactsSe
entities.push({ slug: row.slug, pageId: page.page.id, intent: { ...kept, batchKey: followUp.batchKey, expected_revision: page.revision,
facts: privateOnly ? facts!.map(fact => ({ ...fact, visibility: 'private' as const })) : facts } });
}
- return admitManagedFactsBatch(engine, followUp, entities, entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
+ return admitManagedFactsBatch(engine, followUp, regroupParts(followUp.batchKey, entities), entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
}
/**
@@ -457,7 +474,7 @@ async function readmitWithdrawnFacts(engine: BrainEngine, followUp: ManagedFacts
entities.push({ slug: row.slug, pageId: page?.page.id ?? null, intent: { ...kept, batchKey: followUp.batchKey, withdrawn: 'skip',
...(page ? { expected_revision: page.revision } : {}), facts: await Promise.all(facts!.map(narrowed)) } });
}
- return admitManagedFactsBatch(engine, followUp, entities, entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
+ return admitManagedFactsBatch(engine, followUp, regroupParts(followUp.batchKey, entities), entities.some(entity => entity.intent.facts!.some(fact => fact.embedding != null)));
}
export async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,
@@ -490,20 +507,46 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug === slug) && !snapshot) throw opError('page_identity_changed', 'The resolved fact entity was removed.',
`Entity page ${slug} in source ${sourceId} was deleted after the facts were resolved to it, so nothing was admitted. Run the extraction again (the same request_id is safe: nothing was accepted); it resolves entities against the current pages.`,
{ fix: pageFix(sourceId, slug) });
- inputs.push({ slug, pageId: snapshot?.page.id ?? null, intent: { kind: 'managed_facts_entity', batchKey: session.batchKey,
+ const intent: ManagedFactIntent = { kind: 'managed_facts_entity', batchKey: session.batchKey,
inputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,
embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),
...(options.attributeFallback ? { attribute_fallback: true as const } : {}),
...(options.withdrawn === 'skip' ? { withdrawn: 'skip' as const } : {}),
...(session.captureSource ? { capture_source: session.captureSource } : {}),
...(session.derivation ? { derivation: session.derivation } : {}),
- ...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });
+ ...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group };
+ inputs.push(...entityParts(session.batchKey, { slug, pageId: snapshot?.page.id ?? null, intent }));
}
return collectManagedFacts(engine, session, await admitManagedFactsBatch(engine, session, inputs, embedded, ctx.abortSignal));
}
interface ManagedFactsEntityInput { slug: string; pageId: number | null; intent: ManagedFactIntent }
+/**
+ * #6898 follow-up: one entity's facts as requests of at most MANAGED_FACTS_PUBLICATION_MAX facts. A group
+ * within the cap stays one request, exactly as before. Every part targets the revision the batch read; a
+ * later part also accepts the revision its committed predecessor left (facts-prepare.ts).
+ */
+/** A follow-up batch re-admits refused parts: an entity's retained facts are rejoined in part order and split again. */
+function regroupParts(batchKey: string, inputs: ManagedFactsEntityInput[]): ManagedFactsEntityInput[] {
+ const bySlug = new Map<string, ManagedFactsEntityInput>();
+ for (const { intent: { part: _part, ...intent }, ...input } of inputs) {
+ const seen = bySlug.get(input.slug);
+ bySlug.set(input.slug, seen ? { ...seen, intent: { ...seen.intent, facts: [...seen.intent.facts!, ...intent.facts!] } } : { ...input, intent });
+ }
+ return [...bySlug.values()].flatMap(input => entityParts(batchKey, input));
+}
+
+function entityParts(batchKey: string, input: ManagedFactsEntityInput): ManagedFactsEntityInput[] {
+ const facts = input.intent.facts!;
+ if (facts.length <= MANAGED_FACTS_PUBLICATION_MAX) return [input];
+ const of = Math.ceil(facts.length / MANAGED_FACTS_PUBLICATION_MAX);
+ const ids = Array.from({ length: of }, (_, i) => managedFactRequestId(batchKey, input.slug, i + 1));
+ return ids.map((_, i) => ({ ...input, intent: { ...input.intent,
+ facts: facts.slice(i * MANAGED_FACTS_PUBLICATION_MAX, (i + 1) * MANAGED_FACTS_PUBLICATION_MAX),
+ part: { index: i + 1, of, deferred_facts: Math.max(0, facts.length - (i + 1) * MANAGED_FACTS_PUBLICATION_MAX), follow_up: ids.slice(i + 1) } } }));
+}
+
/** One transaction: the session's per-entity fact requests, then the completion request that names them. */
async function admitManagedFactsBatch(engine: BrainEngine, session: ManagedFactsSession, inputs: ManagedFactsEntityInput[],
embedded: boolean, signal?: AbortSignal): Promise<WriteRequest[]> {
@@ -519,7 +562,8 @@ async function admitManagedFactsBatch(engine: BrainEngine, session: ManagedFacts
...(session.captureSource ? { capture_source: session.captureSource } : {}) } as ManagedFactIntent }]) {
if (signal?.aborted) throw new DOMException('Fact extraction was aborted before admission.', 'AbortError');
await authorizePageVisibility(tx, session.authority, input.slug);
- const requestId = input.intent.kind === 'managed_facts_complete' ? session.completionRequestId : managedFactRequestId(session.batchKey, input.slug);
+ const requestId = input.intent.kind === 'managed_facts_complete' ? session.completionRequestId
+ : managedFactRequestId(session.batchKey, input.slug, input.intent.part?.index);
const row = await admitWriteInTransaction(tx, { principal: session.authority.principal, authority: session.authority,
operation: 'extract_facts', sourceId, sourceIncarnation: session.authority.sourceIncarnation,
worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index 75541ac135..54f98e8c1f 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -73,6 +73,21 @@ async function managedFactsTrust(engine: BrainEngine, p: ManagedFactIntent): Pro
return { trust: { tier: minTrust(declared.tier, live.tier), origin: declared.origin }, inputs: declaration.inputs };
}
+/**
+ * #6898 follow-up: a later part of a split entity group (facts-maintenance.ts entityParts) targets the
+ * revision the batch read, which its own earlier part changed. The revision the latest committed earlier
+ * part of the same batch, entity and writer left is accepted too; anything else changed the page.
+ */
+async function predecessorPartRevision(engine: BrainEngine, row: WriteRequest, p: ManagedFactIntent): Promise<string | null | undefined> {
+ if (!p.part || p.part.index <= 1) return undefined;
+ const [earlier] = await engine.executeRaw<{ revision: string | null }>(`SELECT outcome->>'revision' AS revision FROM persistence_requests
+ WHERE operation='extract_facts' AND source_id=$1 AND source_incarnation=$2::uuid AND principal_kind=$3 AND principal_id=$4
+ AND COALESCE(intent->>'batchKey',outcome->>'batch_key')=$5 AND slug=$6 AND state='committed'
+ AND COALESCE(intent->'part'->>'index',outcome->'part'->>'index')::int < $7 ORDER BY sequence DESC LIMIT 1`,
+ [row.source_id, row.source_incarnation, row.principal_kind, row.principal_id, p.batchKey, row.slug, p.part.index]);
+ return earlier ? earlier.revision : undefined;
+}
+
export async function prepareManagedFactsMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as ManagedFactIntent | null;
if (!p || !['managed_facts_entity', 'managed_facts_complete'].includes(p.kind) || row.operation !== 'extract_facts'
@@ -135,7 +150,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
fact_ids: done.flatMap(item => item.outcome.fact_ids ?? []) };
} };
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
- if (snapshot?.page.deleted_at || (snapshot?.page.id ?? null) !== row.page_id || (snapshot?.revision ?? null) !== (p.expected_revision ?? null)) {
+ if (snapshot?.page.deleted_at || (snapshot?.page.id ?? null) !== row.page_id
+ || (snapshot?.revision ?? null) !== (p.expected_revision ?? null) && (snapshot?.revision ?? null) !== await predecessorPartRevision(engine, row, p)) {
throw factsRefusal('revision_conflict', 'The fact entity changed after extraction admission.', row,
`Entity page ${row.slug} changed or was deleted after these facts were admitted, so none were published.`);
}
@@ -218,7 +234,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
// #5575 ENG-1: the appended rows have no facts rows yet; their chunks are cut at the append's tier.
const rowNums = entries.flatMap(entry => entry.rowNum === undefined ? [] : [entry.rowNum]);
page = await withPendingFenceRows({ sourceId: row.source_id, slug: row.slug, rowNums, tier: fenceAppendPendingTier(taint?.trust.tier) },
- () => preparePageMutation(engine, { ...row, intent: { ...p,
+ () => preparePageMutation(engine, { ...row, intent: { ...p, expected_revision: snapshot.revision,
content: serializePageToMarkdown({ ...snapshot.page, ...next }, snapshot.tags) } }, config));
if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,
`Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);
@@ -276,6 +292,7 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
...(withdrawnSkipped ? { withdrawn_skipped: withdrawnSkipped } : {}),
...(wouldDedupSamePage ? { would_dedup_same_page: wouldDedupSamePage } : {}),
fenced: page !== undefined, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,
+ ...(p.part ? { publication: p.part.deferred_facts ? 'partial' : 'final_part', part: p.part } : {}),
...(page && target?.fixes.length ? { fences_normalized: pageFencesNormalized({ sourceId: row.source_id, slug: row.slug, fixes: target.fixes,
writer: row.principal_kind, path: snapshot?.page.source_path ?? null, remote: row.authority.remote }) } : {}) };
} };
diff --git a/test/facts-publication-large-fence-6898.test.ts b/test/facts-publication-large-fence-6898.test.ts
new file mode 100644
index 0000000000..019b946bbc
--- /dev/null
+++ b/test/facts-publication-large-fence-6898.test.ts
@@ -0,0 +1,205 @@
+/**
+ * #6898 follow-ups (wave 19 L3, item 4): fact publication on a large entity page.
+ *
+ * Protects:
+ * 1. Preparation renders the entity's `## Facts` fence once per request: a
+ * 50-fact publication on a 6,000-row fence costs about what a 1-fact one
+ * does. Regression: one parse and one render of the whole fence per fact,
+ * O(facts x fence rows) (a 200-fact batch on an 8,000-row page spent 14.6 s
+ * there; 1,000 facts ran for minutes and the source's queue waited behind it).
+ * 2. A group of more than MANAGED_FACTS_PUBLICATION_MAX facts for one entity is
+ * admitted as parts in the same batch and published one after another. Each
+ * part's receipt says it is a part (`publication`, `part.index/of`,
+ * `part.deferred_facts`, `part.follow_up`), so a partial publication never
+ * reads as the whole group; the batch completion counts every fact once.
+ * 3. The brain-wide persistence_counters row, which a publication holds from
+ * its admission check to its commit, is held for one part, not for the whole
+ * group (window recorded from the coordinator's counter lock to its receipt
+ * write), and a put_page on another source admitted mid-group commits while
+ * later parts are still queued. Regression: one publication held the row for
+ * every fact's dedup check and insert, and every other admission waited on
+ * it (lock_timeout 1 s -> database_contention).
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set
+ * (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { writeFactsToFence } from '../src/core/facts/fence-write.ts';
+import * as journal from '../src/core/persistence/journal.ts';
+import { MANAGED_FACTS_PUBLICATION_MAX } from '../src/core/persistence/facts-maintenance.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { checkPersistenceCounterDrift } from '../src/commands/doctor/checks/persistence-compaction.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUG = 'people/alice-example';
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-facts-large-fence-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ const backends = testBackends();
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+const claim = (tag: string, i: number) => `Claim ${tag}-${i} about the widget-co supply chain and its quarterly planning cadence, long enough to look real`;
+const fence = (rows: number) => `## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${Array.from({ length: rows }, (_, i) => `| ${i + 1} | ${claim('seed', i)} | fact | 1.0 | private | medium | 2020-01-01 | | chat | |`).join('\n')}
+<!--- gbrain:facts:end -->
+`;
+const person = (title: string, body = '') => `---\ntitle: ${title}\ntype: person\n---\n# ${title}\n\n${body}`;
+
+interface Fixture { engine: BrainEngine; sourceId: string; root: string; otherSource: string;
+ write(tag: string, n: number): Promise<{ inserted: number; ms: number }>;
+ putOther(slug: string): Promise<void>; }
+
+/** A managed brain whose entity page carries a `rows`-row fence (seeded unmanaged), plus a second claimed source. */
+async function largeEntity(rows: number, run: (f: Fixture) => Promise<void>): Promise<void> {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-facts-large-fence-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const otherRoot = join(dir, 'other'); mkdirSync(otherRoot);
+ const sourceId = `large-${randomUUID().slice(0, 8)}`, otherSource = `other-${randomUUID().slice(0, 8)}`;
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const [id, path] of [[sourceId, root], [otherSource, otherRoot]]) {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, path]);
+ await claimWorktree(engine, id, path);
+ }
+ await engine.setConfig('sync.write_through', 'true');
+ const ctx = (source: string) => ({ engine, sourceId: source, remote: false as const, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } });
+ await submitPageMutation(ctx(sourceId), { operation: 'put_page', params: { slug: SLUG, content: person('Alice Example', fence(rows)), request_id: randomUUID() } });
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await run({ engine, sourceId, root, otherSource,
+ write: async (tag, n) => {
+ const started = performance.now();
+ const result = await writeFactsToFence(engine, { sourceId, localPath: root, slug: SLUG, resolutionSource: 'exact_page' },
+ Array.from({ length: n }, (_, i) => ({ fact: claim(tag, i), kind: 'fact' as const, source: 'fixture', visibility: 'private' as const,
+ notability: 'medium' as const, embedding: null, sessionId: null })));
+ return { inserted: result.inserted, ms: performance.now() - started };
+ },
+ putOther: async slug => { await submitPageMutation(ctx(otherSource), { operation: 'put_page',
+ params: { slug, content: person('Beta Example'), request_id: randomUUID() } }); } });
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}
+
+async function entityRequests(engine: BrainEngine, sourceId: string) {
+ return engine.executeRaw<{ request_id: string; state: string; outcome: Record<string, any> }>(
+ `SELECT request_id::text, state, outcome FROM persistence_requests WHERE source_id=$1 AND slug=$2 AND operation='extract_facts' ORDER BY sequence`,
+ [sourceId, SLUG]);
+}
+
+/** Records, per committed fact publication on SLUG, the time from the coordinator's counter lock to its receipt write. */
+function recordCounterHolds(): { holds: number[]; restore(): void } {
+ const holds: number[] = [];
+ let locked = 0;
+ const lockCounters = journal.lockCounters, completeWrite = journal.completeWrite;
+ const lock = spyOn(journal, 'lockCounters').mockImplementation(async (tx, keys) => {
+ if (keys.includes('brain')) locked = performance.now();
+ return lockCounters(tx, keys);
+ });
+ const complete = spyOn(journal, 'completeWrite').mockImplementation(async (...args: Parameters<typeof completeWrite>) => {
+ const done = await completeWrite(...args);
+ if (args[2] === 'committed' && args[1].operation === 'extract_facts' && args[1].slug === SLUG) holds.push(performance.now() - locked);
+ return done;
+ });
+ return { holds, restore: () => { lock.mockRestore(); complete.mockRestore(); } };
+}
+
+test('a cap-sized publication on a 6,000-row fence costs about what a 1-fact one does', async () => {
+ await largeEntity(6000, async ({ write }) => {
+ await write('warm', 1);
+ const one = await write('one', 1);
+ const capped = await write('cap', MANAGED_FACTS_PUBLICATION_MAX);
+ expect([one.inserted, capped.inserted]).toEqual([1, MANAGED_FACTS_PUBLICATION_MAX]);
+ expect(capped.ms).toBeLessThan(2 * one.ms);
+ });
+}, 300_000);
+
+test('a group over the cap publishes as parts whose receipts say they are parts', async () => {
+ await largeEntity(20, async ({ engine, sourceId, write }) => {
+ const total = 2 * MANAGED_FACTS_PUBLICATION_MAX + 20;
+ expect((await write('parts', total)).inserted).toBe(total);
+ const rows = await entityRequests(engine, sourceId);
+ expect(rows.map(r => r.state)).toEqual(['committed', 'committed', 'committed']);
+ const ids = rows.map(r => r.request_id);
+ expect(rows.map(r => [r.outcome.publication, r.outcome.part, r.outcome.inserted])).toEqual([
+ ['partial', { index: 1, of: 3, deferred_facts: MANAGED_FACTS_PUBLICATION_MAX + 20, follow_up: ids.slice(1) }, MANAGED_FACTS_PUBLICATION_MAX],
+ ['partial', { index: 2, of: 3, deferred_facts: 20, follow_up: ids.slice(2) }, MANAGED_FACTS_PUBLICATION_MAX],
+ ['final_part', { index: 3, of: 3, deferred_facts: 0, follow_up: [] }, 20]]);
+ const [completion] = await engine.executeRaw<{ outcome: Record<string, any> }>(
+ `SELECT outcome FROM persistence_requests WHERE source_id=$1 AND slug='__managed_facts_complete__' AND state='committed'`, [sourceId]);
+ expect(completion.outcome).toMatchObject({ status: 'completed', entity_requests: 3, inserted: total });
+ const facts = await engine.executeRaw<{ row_num: number }>(
+ `SELECT row_num FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact LIKE 'Claim parts-%' ORDER BY row_num`, [sourceId, SLUG]);
+ expect(facts.map(f => Number(f.row_num))).toEqual(Array.from({ length: total }, (_, i) => 21 + i));
+ // Counter totals stay exact across the parts: receipt bytes (doctor) and, read directly, outstanding requests,
+ // their intent bytes and the permanent request ids each brain and principal row has issued.
+ expect((await checkPersistenceCounterDrift(engine)).status).toBe('ok');
+ const counters = await engine.executeRaw<{ key: string; outstanding: string; intent: string; ids: string; want_outstanding: string; want_intent: string; want_ids: string }>(`
+ WITH r AS (SELECT 'principal:'||principal_kind||':'||principal_id AS key,state,intent_bytes FROM persistence_requests
+ UNION ALL SELECT 'brain',state,intent_bytes FROM persistence_requests),
+ t AS (SELECT 'principal:local_cli:'||principal_id::text AS key FROM persistence_topology_changes UNION ALL SELECT 'brain' FROM persistence_topology_changes),
+ want AS (SELECT key,count(*) FILTER (WHERE state NOT IN ('committed','conflict','failed','cancelled')) AS outstanding,
+ COALESCE(SUM(intent_bytes) FILTER (WHERE state NOT IN ('committed','conflict','failed','cancelled')),0) AS intent,count(*) AS ids FROM r GROUP BY key)
+ SELECT c.key,c.outstanding_count::text AS outstanding,c.intent_bytes::text AS intent,c.lifetime_ids::text AS ids,
+ COALESCE(w.outstanding,0)::text AS want_outstanding,COALESCE(w.intent,0)::text AS want_intent,
+ (COALESCE(w.ids,0)+(SELECT count(*) FROM t WHERE t.key=c.key))::text AS want_ids
+ FROM persistence_counters c LEFT JOIN want w ON w.key=c.key WHERE c.key='brain' OR c.key LIKE 'principal:%' ORDER BY c.key`);
+ expect(counters.length).toBeGreaterThan(1);
+ for (const c of counters) expect([c.key, c.outstanding, c.intent, c.ids]).toEqual([c.key, c.want_outstanding, c.want_intent, c.want_ids]);
+ });
+}, 300_000);
+
+test('the counter row is held for one part, and a put_page on another source commits mid-group', async () => {
+ await largeEntity(2000, async ({ engine, sourceId, write, putOther }) => {
+ await write('warm', 1);
+ const probe = recordCounterHolds();
+ try {
+ await write('one-part', MANAGED_FACTS_PUBLICATION_MAX);
+ const [onePart] = probe.holds.splice(0);
+ const group = write('group', 16 * MANAGED_FACTS_PUBLICATION_MAX);
+ let committed: Array<{ state: string }> = [];
+ while (!committed.some(r => r.state === 'committed')) {
+ await Bun.sleep(20);
+ committed = (await entityRequests(engine, sourceId)).slice(2);
+ }
+ await putOther('people/beta-example');
+ const atPut = (await entityRequests(engine, sourceId)).slice(2);
+ expect((await group).inserted).toBe(16 * MANAGED_FACTS_PUBLICATION_MAX);
+ expect(atPut.filter(r => r.state !== 'committed').length).toBeGreaterThan(0);
+ expect(probe.holds.length).toBeGreaterThan(0);
+ expect(Math.max(...probe.holds)).toBeLessThan(3 * onePart);
+ } finally { probe.restore(); }
+ });
+}, 600_000);
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 6eafacdf0d..26cdb4e43f 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -61,6 +61,7 @@ test/extract-timeline-from-meetings-managed.test.ts
test/extraction-watermark-atoms.test.ts
test/fact-fence-adoption-exits.test.ts
test/fact-purge-lookup-timeout-6511.test.ts
+test/facts-publication-large-fence-6898.test.ts
test/fence-repair-receipts.test.ts
test/forecast-journal.test.ts
test/frontmatter-reserved-keys-6454.test.ts