Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(conversation-facts): round 6 - a lost grammar keeps a transcript's facts, settle under the page lock, exact-yield oracle with path floors, bounded detector memory

garrytand532e3368675
diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
index 8d585fbfae..6e87193757 100644
--- a/src/commands/doctor/checks/extraction-input.ts
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -41,8 +41,10 @@ const FAILED_WINDOWS = 'failed_windows';
const FAILED_REMEDY = 'a conversation window failed to extract in run after run and is skipped, so the older windows still get extracted (the sample names the window, its receipt the last error); fix the cause, then gbrain extract-conversation-facts --slug <slug> --force tries it again';
const NO_MESSAGES = 'no_messages';
const NO_MESSAGES_REMEDY = 'the page reads as a transcript format over its whole text, yet no message parsed under that format (a conversation parser fault), so the last run changed nothing and kept its facts; rerunning repeats this, so report it with gbrain doctor --json and the page\'s format (a page that is not a transcript settles as non-extractable instead)';
+const GRAMMAR_LOST = 'grammar_lost';
+const GRAMMAR_LOST_REMEDY = 'no chat format is detected over the whole page any more (text added around the transcript, such as reference paragraphs, can outweigh its message lines), yet its messages still parse in the format it was extracted in, so the run kept every conversation fact and settled nothing; move the added text to another page (or below a heading the transcript does not need) and rerun gbrain extract-conversation-facts --slug <slug>; if the page is no longer meant to be a transcript, remove its message lines and rerun, which marks it non-extractable and clears its conversation facts';
const remedy = (g: ReceiptGroup): string | null => g.kind === UNREAD_WINDOWS ? UNREAD_REMEDY : g.kind === FAILED_WINDOWS ? FAILED_REMEDY
- : g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : REMEDY[g.pipeline] ?? null;
+ : g.kind === NO_MESSAGES ? NO_MESSAGES_REMEDY : g.kind === GRAMMAR_LOST ? GRAMMAR_LOST_REMEDY : REMEDY[g.pipeline] ?? null;
const describe = (g: ReceiptGroup): string =>
`${g.pipeline}/${g.kind}: ${g.pages} page(s) (e.g. ${g.samples.join(', ')}); ${remedy(g) ?? 'see the receipt in page_extraction_state'}`;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 440198cea7..5bdd62acb5 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1065,7 +1065,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },
{ since: 'TBD', text: 'Atom extraction now covers very large pages, and after an append reads only the new text.' },
{ since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls, the synopsis step\'s embedding included, turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped. A model with no price still reserves its ceiling estimate (about one window per page at the default cap; no default changed and no price is assumed), and its receipt now says `unpriced_model` with the model; doctor `derivation_unpriced_model` warns and names the fix, `gbrain pricing set <model> --input <usd> --output <usd>`, which writes `pricing.overrides`.' },
- { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page that is no longer a transcript is marked non-extractable and its conversation facts are cleared, even under `--force`; only a page that reads as a transcript yet parses no message keeps every fact and leaves a receipt doctor lists.' },
+ { since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page that is no longer a transcript (no message parses even in the format it was extracted in) is marked non-extractable and its conversation facts are cleared, even under `--force`. A page whose format is no longer detected over the whole page (text added around the transcript can outweigh its message lines) but whose messages still parse in that format keeps every fact, settles nothing and leaves a `grammar_lost` receipt doctor lists with the fix; a page that reads as a transcript yet parses no message does the same with a `no_messages` receipt. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },
// PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.
{ since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },
// PR 4 (Wave B incremental derivation, transcripts)
diff --git a/src/core/conversation-parser/normalize-block.ts b/src/core/conversation-parser/normalize-block.ts
index d8ce7c9690..eb61d96e01 100644
--- a/src/core/conversation-parser/normalize-block.ts
+++ b/src/core/conversation-parser/normalize-block.ts
@@ -54,11 +54,14 @@ function to24h(hour: number, ampm?: string): number {
/**
* normalizeBlockConversation one line at a time: `emit` gets each collapsed message line once the message ends (the next
- * header, or `end()`); `headers` counts the block headers seen. Lines before the first header are dropped.
+ * header, or `end()`); `headers` counts the block headers seen. Lines before the first header are dropped. With
+ * `maxBodyChars`, a message's body keeps only its first that many characters (pattern detection, which needs the
+ * collapsed line's shape, not all of its text), copied so a kept line never holds the text it was cut from alive.
*/
-export function blockNormalizer(emit: (line: string) => void): { line(line: string): void; end(): void; readonly headers: number } {
+export function blockNormalizer(emit: (line: string) => void, opts: { maxBodyChars?: number } = {}): { line(line: string): void; end(): void; readonly headers: number } {
let current: { name: string; time: string } | null = null;
let bodyParts: string[] = [];
+ let bodyChars = 0;
let headers = 0;
const flush = () => {
@@ -68,6 +71,7 @@ export function blockNormalizer(emit: (line: string) => void): { line(line: stri
}
current = null;
bodyParts = [];
+ bodyChars = 0;
};
return {
@@ -82,8 +86,9 @@ export function blockNormalizer(emit: (line: string) => void): { line(line: stri
current = { name: m[1].trim(), time };
} else if (current) {
// Body line of the current message. Drop blank lines; keep the rest.
- const trimmed = line.trim();
- if (trimmed) bodyParts.push(trimmed);
+ const room = (opts.maxBodyChars ?? Infinity) - bodyChars;
+ const trimmed = room > 0 ? line.trim().slice(0, room) : '';
+ if (trimmed) { bodyParts.push(opts.maxBodyChars === undefined ? trimmed : Buffer.from(trimmed).toString()); bodyChars += trimmed.length; }
}
// Lines before the first header (page title, leading blanks) are dropped —
// they never matched a pattern anyway.
diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.ts
index eb85498432..f315df1ada 100644
--- a/src/core/conversation-parser/parse.ts
+++ b/src/core/conversation-parser/parse.ts
@@ -29,6 +29,7 @@ import {
cleanSpeaker,
} from './builtins.ts';
import { blockNormalizer, normalizeBlockConversation } from './normalize-block.ts';
+import { SCAN_LINE_BUFFER_BYTES } from '../page-body/limits.ts';
import type {
DateContext,
MatchedMessage,
@@ -761,26 +762,41 @@ export function pickHeadPattern(head: string): string | null {
* parseConversation's pattern choice over a body fed in pieces (a segmented page's occurrences, in order), holding
* counters instead of the body: the same block-format collapse (when any block header appears), head pass over the first
* SCORING_HEAD_LINES non-blank lines, full-body re-score, acceptance floor and structure gate, over the built-in
- * patterns. `finish()` returns the pattern id parseConversation(body).matched_pattern_id would, or null.
+ * patterns. `finish()` returns the pattern id parseConversation(body).matched_pattern_id would, or null. A line over
+ * SCAN_LINE_BUFFER_BYTES characters is scored by its first that many characters (every pattern anchors at the line's
+ * start) and the rest is never held (a block message's body is held up to that many characters), so the detector retains
+ * at most that much text between pieces.
*/
export function createPatternDetector(): { push(text: string): void; finish(): string | null } {
const raw = scoringTrack();
const block = scoringTrack();
- const normalizer = blockNormalizer(line => block.line(line));
+ const normalizer = blockNormalizer(line => block.line(line), { maxBodyChars: SCAN_LINE_BUFFER_BYTES });
let partial = '';
+ let oversized: string | null = null;
const line = (text: string) => {
- normalizer.line(text);
- raw.line(text.endsWith('\r') ? text.slice(0, -1) : text);
+ const scored = text.length > SCAN_LINE_BUFFER_BYTES ? text.slice(0, SCAN_LINE_BUFFER_BYTES) : text;
+ normalizer.line(scored);
+ raw.line(scored.endsWith('\r') ? scored.slice(0, -1) : scored);
};
return {
push(text: string) {
- const lines = (partial + text).split('\n');
+ let rest = text;
+ if (oversized !== null) {
+ const end = rest.indexOf('\n');
+ if (end < 0) return;
+ line(oversized);
+ oversized = null;
+ rest = rest.slice(end + 1);
+ }
+ const lines = (partial + rest).split('\n');
partial = lines.pop()!;
for (const l of lines) line(l);
+ if (partial.length > SCAN_LINE_BUFFER_BYTES) { oversized = Buffer.from(partial.slice(0, SCAN_LINE_BUFFER_BYTES)).toString(); partial = ''; }
},
finish() {
- line(partial);
+ line(oversized ?? partial);
partial = '';
+ oversized = null;
normalizer.end();
return (normalizer.headers > 0 ? block : raw).finish();
},
diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.ts
index 533ef1b6ea..2992a78c75 100644
--- a/src/core/extraction-watermark.ts
+++ b/src/core/extraction-watermark.ts
@@ -37,7 +37,7 @@ export type HeadFallbackReason = 'no_watermark' | 'prefix_changed' | 'version_ch
/** The durable receipt of an extraction that did not read all of its input. */
export interface InputTruncated {
/** PR 4 (Wave B incremental derivation, transcripts): `no_messages`, a segmented conversation page reads as a transcript format over its whole text yet no message parsed under it; the run changed nothing. */
- kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages';
+ kind: 'head' | 'tail_window' | 'skipped_too_large' | 'no_messages' | 'grammar_lost';
pipeline: ExtractionPipeline;
/** Characters the extractor read (0 for a skipped page). */
processed_chars: number;
@@ -55,6 +55,13 @@ export interface InputTruncated {
*/
window_rule?: 'no_prior_facts' | 'prior_facts_kept';
prior_facts?: number;
+ /**
+ * PR 4 (Wave B incremental derivation, transcripts): `grammar_lost`, no chat format is detected over a segmented
+ * conversation page that holds windows or facts, yet `messages` still parse under the format it was extracted in
+ * (`pattern`), or it recorded none; the run changed nothing.
+ */
+ pattern?: string;
+ messages?: number;
}
export interface StoredWatermark { pipelineVersion: number; bytes: number; sha256: string }
diff --git a/src/core/facts/conversation-incremental.ts b/src/core/facts/conversation-incremental.ts
index ccb39821f6..467cab7589 100644
--- a/src/core/facts/conversation-incremental.ts
+++ b/src/core/facts/conversation-incremental.ts
@@ -55,7 +55,7 @@ import { planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor,
import { conversationDetectionWork, readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';
import { emptySaveTimeResolutionCounts, mergeSaveTimeResolutionCounts } from '../entities/resolve-on-save.ts';
import { conversationEntityHints } from './conversation-entity-hints.ts';
-import { countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
+import { countConversationFacts, countWindowFacts, publishConversationFacts, type ConversationFactRow } from './conversation-publication.ts';
import { recordFailedPage } from './conversation-run-status.ts';
import { detectPagePattern, startsConversationRun, streamConversationWindows } from './conversation-stream.ts';
import type { ConversationSegment } from './conversation-types.ts';
@@ -180,6 +180,27 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
if (!pattern && from < liveIds.length) pattern = await detectPagePattern(occurrences, i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }));
if (!pattern && from < liveIds.length) {
if (opts.sinceIso) { result.pages_skipped++; return { newestEnd: null }; }
+ // No grammar over the whole page. Only a page that holds no window or fact, or that parses no message under the
+ // grammar it was extracted in either, has stopped being a transcript (it settles as non-extractable below and its
+ // facts are collected); one that still does (prose added around the transcript can tip the density test) keeps
+ // everything and settles nothing.
+ const recordedGrammar = prior.map(row => rowOutput(row).pattern).find(Boolean) ?? null;
+ const holds = prior.some(row => rowOutput(row).windows.length > 0) || await countConversationFacts(engine, sourceId, page.slug, { active: true }) > 0;
+ let still = holds && !recordedGrammar ? null : 0;
+ if (holds && recordedGrammar) {
+ still = (await streamConversationWindows(occurrences, 0, liveIds.length, { page, gapMinutes: opts.gapMinutes, pattern: recordedGrammar },
+ i => readOccurrenceText(engine, body, occurrences[i]!.row, { detection: true }), { window() {}, occurrence() {} })).messages;
+ }
+ if (still !== 0) {
+ await setExtractionReceipt(engine, page.id, KIND, { kind: 'grammar_lost', pipeline: KIND, processed_chars: 0, ...(recordedGrammar ? { pattern: recordedGrammar } : {}),
+ ...(still !== null ? { messages: still } : {}) });
+ const why = recordedGrammar ? `no chat format is detected over the page any more, yet ${still} message(s) still parse as ${recordedGrammar}`
+ : 'no chat format is detected over the page, which holds conversation facts from a run that recorded none';
+ process.stderr.write(`[extract-conversation-facts] ${page.slug}: ${why}; its facts were kept, nothing settled; gbrain doctor lists it\n`);
+ result.pages_failed++;
+ recordFailedPage(result, page.slug, `${why}; facts kept`);
+ return { newestEnd: null };
+ }
from = 0;
}
// Earlier windows of the occurrences the stream covers (and of retired ones), reusable by rendered text under the same context.
@@ -257,14 +278,12 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
let newestEnd: string | null = null;
let extracted = 0;
let batch: { rows: ConversationFactRow[]; windows: SourceWindow[]; keys: string[] } = { rows: [], windows: [], keys: [] };
- /** Publish the facts extracted since the last publication and the rows of the streamed occurrences; `final` settles a finished page. */
+ /**
+ * Publish the facts extracted since the last publication and the rows of the streamed occurrences; `final` settles a
+ * finished page, but only if the page is still the version the run read, checked under the publication's row lock on
+ * the page (a write that commits after the check waits for the publication; one that committed before is seen).
+ */
const publish = async (final: boolean) => {
- let unchanged = true;
- if (final) {
- const now = await engine.getPage(page.slug, { sourceId });
- unchanged = !!now && now.id === page.id && regularPageVersionToken(now) === versionToken;
- }
- const settled = final && unchanged && stop === null && !opts.sinceIso && streamedFrom <= from;
const owned = new Map<number, StreamWindow[]>();
for (const w of windows) owned.set(w.owner, [...(owned.get(w.owner) ?? []), w]);
// Rows of the occurrences this run streamed; an occurrence it never reached keeps its row.
@@ -291,18 +310,26 @@ export async function processSegmentedConversationPage(run: SegmentedConversatio
});
const settledWindows = [...liveIds.slice(0, from).flatMap(id => rowOutput(priorRow.get(id)).windows.map(w => ({ key: keyOf(id, w), failed: !!w.failed }))),
...windows.map(w => ({ key: sourceWindowKey(w.window), failed: w.state === 'failed' }))];
- const liveKeys = settled ? settledWindows.map(w => w.key) : null;
- const collect = settled && !settledWindows.some(w => w.failed);
- const outcome = !liveKeys ? null : liveKeys.length ? terminalAuditFact(page.slug, 0, versionToken)
- : nonExtractableAuditFact(page.slug, 0, versionToken, pattern ? 'fewer than two eligible messages' : 'no conversation messages found');
const moves = [...pendingMoves];
const out = await writeDerivedFacts(engine, sourceId, page.slug, async db => {
+ let unchanged = true;
+ if (final) {
+ await db.executeRaw('SELECT id FROM pages WHERE id = $1 FOR UPDATE', [page.id]);
+ const now = await db.getPage(page.slug, { sourceId });
+ unchanged = !!now && now.id === page.id && regularPageVersionToken(now) === versionToken;
+ }
+ const settled = final && unchanged && stop === null && !opts.sinceIso && streamedFrom <= from;
+ const liveKeys = settled ? settledWindows.map(w => w.key) : null;
+ const collect = settled && !settledWindows.some(w => w.failed);
+ const outcome = !liveKeys ? null : liveKeys.length ? terminalAuditFact(page.slug, 0, versionToken)
+ : nonExtractableAuditFact(page.slug, 0, versionToken, pattern ? 'fewer than two eligible messages' : 'no conversation messages found');
const published = await publishConversationFacts(db, sourceId, page.slug, outcome ? [...batch.rows, outcome] : batch.rows,
{ scope: 'window', segments: { windows: batch.windows, moves, replace: batch.keys, live: collect ? liveKeys : null } });
if (derived.length || released.length) await db.upsertSegmentDerivations([...derived, ...released]);
if (settled) await db.retireSegmentDerivations(page.id, liveIds, { kind: KIND });
- return published;
+ return { ...published, unchanged, settled, liveKeys, outcome };
});
+ const { unchanged, settled, liveKeys, outcome } = out;
pendingMoves.splice(0, moves.length);
movedOff.clear();
for (const row of [...derived, ...released]) rowsNow.set(row.occurrenceId, row);
diff --git a/src/core/facts/conversation-publication.ts b/src/core/facts/conversation-publication.ts
index 70abb1676e..d9309cb642 100644
--- a/src/core/facts/conversation-publication.ts
+++ b/src/core/facts/conversation-publication.ts
@@ -544,9 +544,9 @@ export const LABEL_RETIRED_MARKER = 'retired: conversation-labels';
* page is deleted. Returns the rows removed from the active batch.
*/
/** The page's conversation facts, audit rows aside: what a clear would lose that a window extraction may not see again. */
-export async function countConversationFacts(db: BrainEngine, sourceId: string, slug: string): Promise<number> {
+export async function countConversationFacts(db: BrainEngine, sourceId: string, slug: string, opts: { active?: boolean } = {}): Promise<number> {
const [row] = await db.executeRaw<{ count: string }>(`SELECT count(*)::text AS count FROM facts f WHERE f.source_id=$1 AND f.source_markdown_slug=$2
- AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND NOT (f.source = ANY($3::text[]))`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]);
+ AND f.source LIKE '${CONVERSATION_FACTS_SOURCE_PREFIX}%' AND NOT (f.source = ANY($3::text[]))${opts.active ? ' AND f.expired_at IS NULL' : ''}`, [sourceId, slug, [...AUDIT_ROW_SOURCES]]);
return Number(row?.count ?? 0);
}
diff --git a/test/conversation-parser/pattern-detector.test.ts b/test/conversation-parser/pattern-detector.test.ts
index 20fa06d8ea..a869a5b72f 100644
--- a/test/conversation-parser/pattern-detector.test.ts
+++ b/test/conversation-parser/pattern-detector.test.ts
@@ -6,9 +6,12 @@
* parseConversation(body) matches, or null when it matches none: head pass, full-body re-score, score_full_body
* re-score, acceptance floor, structure gate, block-format collapse and the speaker-object region scan included.
* 2. Fails when: the detector diverges from the whole-page parser on any seeded body (a preamble that tips the head
- * pass, a block header deep in the body, an invalid speaker-object region, a label list with no repeated speaker).
+ * pass, a block header deep in the body, an invalid speaker-object region, a label list with no repeated speaker),
+ * or holds more than a bounded amount of text between pieces: a 40 MiB line with no newline, or a 40 MiB block
+ * message body, fed in 1 MiB pieces (N6, round 6); a message line over the cap is still scored by its head.
*/
import { describe, expect, test } from 'bun:test';
+import { heapSize } from 'bun:jsc';
import { BUILTIN_PATTERNS } from '../../src/core/conversation-parser/builtins.ts';
import { createPatternDetector, parseConversation } from '../../src/core/conversation-parser/parse.ts';
@@ -80,4 +83,33 @@ describe('createPatternDetector', () => {
expect(parseConversation(text.slice(0, 64 * 1024)).matched_pattern_id).toBe('plain-role-no-time');
expect({ parsed: parseConversation(text).matched_pattern_id, detected: detect(text, 1) }).toEqual({ parsed: 'bold-paren-time-12h', detected: 'bold-paren-time-12h' });
});
+
+ /** Heap growth (bytes) over a baseline after each of 40 fresh 1 MiB pieces `piece(i)` the detector is fed: the most it retained. */
+ const peakRetained = (head: string, piece: (i: number) => string, tail: string) => {
+ const detector = createPatternDetector();
+ detector.push(head);
+ Bun.gc(true);
+ const base = heapSize();
+ let peak = 0;
+ for (let i = 0; i < 40; i++) {
+ detector.push(piece(i));
+ Bun.gc(true);
+ peak = Math.max(peak, heapSize() - base);
+ }
+ detector.push(tail);
+ return { peak, pattern: detector.finish() };
+ };
+ const MIB = 1024 ** 2;
+ const transcript = Array.from({ length: 60 }, (_, t) => `**${t % 2 ? 'Alice' : 'Bob'}** (${1 + (t % 11)}:0${t % 10} PM): turn ${t} about the roadmap review.`).join('\n');
+
+ test('N6: a 40 MiB line with no newline, fed in 1 MiB pieces, is never held whole; only its head is scored', () => {
+ const { peak, pattern } = peakRetained(`${transcript}\n`, i => String.fromCharCode(97 + (i % 26)).repeat(MIB - 8) + String(i).padStart(8, '0'), `\n${transcript}\n`);
+ expect({ held: peak < 4 * MIB, pattern }).toEqual({ held: true, pattern: 'bold-paren-time-12h' });
+ });
+
+ test('N6: a block message whose 40 MiB body arrives in 1 MiB pieces of short lines holds a bounded body', () => {
+ const line = (i: number, j: number) => ` body line ${j} of piece ${i} `.padEnd(1023, 'x');
+ const { peak, pattern } = peakRetained('- **Theo** (Mon 11:18)\n', i => Array.from({ length: 1024 }, (_, j) => `${line(i, j)}\n`).join(''), '- **Juan** (11:20 AM)\n done\n');
+ expect({ held: peak < 4 * MIB, pattern }).toEqual({ held: true, pattern: 'bold-paren-time' });
+ });
});
diff --git a/test/helpers/conversation-facts-invariant-cases.ts b/test/helpers/conversation-facts-invariant-cases.ts
index 47ded6713b..0350df22c0 100644
--- a/test/helpers/conversation-facts-invariant-cases.ts
+++ b/test/helpers/conversation-facts-invariant-cases.ts
@@ -9,10 +9,13 @@
* leaves the facts of the window the append retired standing (F2); a run that re-extracts every window under an
* unchanged key (a model change) leaves one batch per key (F6); rows from an older derivation version are never
* read as window positions (F9); the grammar is detected over the whole page, not its head (F3), and that read is
- * counted; a page that reads as a transcript yet parses no message changes nothing and leaves a no_messages receipt.
+ * counted; a page that reads as a transcript yet parses no message changes nothing and leaves a no_messages receipt;
+ * a transcript whose format the whole page no longer shows yet still parses changes nothing and leaves a
+ * grammar_lost receipt (N1); an append that commits after the old version check and before the publication locks
+ * the page leaves the run unsettled (N2).
* 2. Fails when: anything but an exact-key replacement or a fully settled collection deletes a fact, a moved window's
- * old row keeps claiming it, a settling run keeps the old batch beside the new one, or the head of a page picks its
- * grammar.
+ * old row keeps claiming it, a settling run keeps the old batch beside the new one, the head of a page picks its
+ * grammar, a lost grammar collects a transcript's facts, or a run settles a page version it did not read.
*/
import { expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -42,6 +45,12 @@ export async function claimMismatches(engine: BrainEngine, slug: string) {
.filter(w => (count.get(w.key) ?? 0) !== w.claimed).map(w => ({ ...w, held: count.get(w.key) ?? 0 })));
}
+/** A meeting-notes transcript (`**Name:** text`, no times) whose turns carry `notes` continuation lines each: sparse enough
+ * that text added around it can tip the whole-page density test. */
+const sparseTranscript = (count: number, notes: number) => Array.from({ length: count }, (_, t) => [`**${['Alice Example', 'Bob Example', 'Carol Example'][t % 3]}:** turn ${t} opens the item`,
+ ...Array.from({ length: notes }, (_, j) => `note ${j} of item ${t} on the roadmap review`)].join('\n')).join('\n\n');
+const references = (count: number) => Array.from({ length: count }, (_, i) => `Reference ${i}: the roadmap review moved to next quarter and the budget stays flat.`).join('\n\n');
+
export function defineConversationFactsInvariantCases(opts: { getBrain: () => AppendBrain }): void {
test('F1: two interrupted runs after an append lose no fact and leave every row claiming exactly the facts it holds', async () => {
const brain = opts.getBrain();
@@ -170,4 +179,64 @@ export function defineConversationFactsInvariantCases(opts: { getBrain: () => Ap
const group = groups.find(g => g.pipeline === 'conversation_facts' && g.kind === 'no_messages');
expect({ listed: group?.samples.includes(`default:${slug}`), fault: group?.remedy?.includes('parser fault') }).toEqual({ listed: true, fault: true });
}, 600_000);
+
+ test('N1: a transcript whose grammar the whole page no longer shows (references added, title changed) keeps every fact, settles nothing and leaves a grammar_lost receipt doctor lists', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/grammar-lost-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ const transcript = sparseTranscript(3000, 18);
+ await brain.seed(slug, chatPage('Grammar lost', transcript));
+ const first = await extract(brain.engine, slug);
+ const before = (await factsOf(brain.engine, slug)).map(f => f.id);
+ expect({ processed: first.result.pages_processed, facts: before.length > 100 }).toEqual({ processed: 1, facts: true });
+ await brain.seed(slug, chatPage('Grammar lost, renamed', `${transcript}\n\n## References\n\n${references(3000)}`));
+ const page = (await brain.engine.getPage(slug, { sourceId: 'default' }))!;
+ const truth = (await brain.body(slug)).truth;
+ expect(parser.parseConversation(truth, { page }).matched_pattern_id).toBeUndefined();
+ const { calls, result } = await extract(brain.engine, slug);
+ expect({ calls: calls.length, failed: result.pages_failed, nonExtractable: result.pages_marked_non_extractable, cleaned: result.orphan_facts_cleaned,
+ facts: (await factsOf(brain.engine, slug)).map(f => f.id), states: [...new Set((await derivations(brain.engine, slug)).states)] })
+ .toEqual({ calls: 0, failed: 1, nonExtractable: 0, cleaned: 0, facts: before, states: ['done'] });
+ const check = (await extractionInputTruncatedEntry.run({ engine: brain.engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;
+ const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[]; remedy: string | null }> }).groups;
+ const group = groups.find(g => g.pipeline === 'conversation_facts' && g.kind === 'grammar_lost');
+ expect({ listed: group?.samples.includes(`default:${slug}`), remedy: group?.remedy?.includes('still parse') }).toEqual({ listed: true, remedy: true });
+ }, 600_000);
+
+ test('N2: an append_page that commits right after the old version check (before the publication locks the page) leaves the run unsettled with its facts kept; the next run settles it', async () => {
+ const brain = opts.getBrain();
+ const slug = `notes/concurrent-append-${randomUUID().slice(0, 8)}`;
+ await caps(brain.engine, 'off');
+ await brain.seed(slug, chatPage('Concurrent append', chatDays(4400, 100, 37)));
+ await extract(brain.engine, slug);
+ // Two new days: one or two new windows, fewer than a checkpoint, so the only publication after them is the final one.
+ expect(await brain.call('append_page', { slug, text: chatDays(4500, 2, 37), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ const before = (await factsOf(brain.engine, slug)).map(f => f.id);
+ let armed = false;
+ let injected = 0;
+ const transaction = brain.engine.transaction;
+ // The outermost transaction the publication opens (a transaction engine inherits the spy; its nested calls are skipped).
+ const spy = spyOn(brain.engine, 'transaction').mockImplementation((async function (this: BrainEngine, ...args: Parameters<BrainEngine['transaction']>) {
+ if (armed && this === brain.engine && (new Error().stack ?? '').includes('maintenanceTransaction')) {
+ armed = false;
+ injected++;
+ expect(await brain.call('append_page', { slug, text: chatDays(4502, 1, 37), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });
+ }
+ return transaction.apply(this, args);
+ }) as typeof brain.engine.transaction);
+ let run: Awaited<ReturnType<typeof extract>>;
+ try {
+ run = await extract(brain.engine, slug, { failOn: () => { armed = true; return false; } });
+ } finally {
+ spy.mockRestore();
+ }
+ const kept = await factsOf(brain.engine, slug);
+ expect({ injected, calls: run.calls.length > 0, failed: run.result.pages_failed, processed: run.result.pages_processed, cleaned: run.result.orphan_facts_cleaned,
+ lost: before.filter(id => !kept.some(f => f.id === id)).length, reason: run.result.failed_pages[0]?.error ?? null })
+ .toEqual({ injected: 1, calls: true, failed: 1, processed: 0, cleaned: 0, lost: 0, reason: 'the page changed during extraction; left unfinished for replay' });
+ const next = await extract(brain.engine, slug);
+ const rows = await derivations(brain.engine, slug);
+ expect({ calls: next.calls.length > 0, processed: next.result.pages_processed, mismatches: await claimMismatches(brain.engine, slug), states: [...new Set(rows.states)],
+ facts: (await factsOf(brain.engine, slug)).length }).toEqual({ calls: true, processed: 1, mismatches: [], states: ['done'], facts: rows.keys.length });
+ }, 600_000);
}
diff --git a/test/helpers/conversation-facts-property-cases.ts b/test/helpers/conversation-facts-property-cases.ts
index 6bfcc7dad8..28972dabd8 100644
--- a/test/helpers/conversation-facts-property-cases.ts
+++ b/test/helpers/conversation-facts-property-cases.ts
@@ -11,8 +11,14 @@
* (i) a fact that disappeared had its exact window key extracted again (or a moved window's facts re-anchored onto
* it) in that step, or the step fully settled the page and its key is no current window's; a moved fact keeps
* its window text;
- * (ii) every window key holds exactly one batch: the fact count its text yields, no fact twice;
+ * (ii) every window key holds exactly one batch: the fact count its text yields, no fact twice; every window a live
+ * row records holds exactly that count (a key holding no fact included), and a window marked failed holds either
+ * that count (an earlier context's batch) or none;
* (iii) every window a row claims holds exactly the facts the row says, and a settled page holds only current windows.
+ * Each step records which paths it exercised (a moved window, a window-specific failure, a window marked failed, a
+ * settled collection, a --since run, a cap refusal); across the seeds every path must fire at least its floor. Each seed
+ * also dooms the windows whose text hash starts with one chosen digit for a span of steps, so windows reach the failure
+ * limit and block collection until the final --force run.
* At the end a healthy unconstrained --force run leaves the same windows and facts as one extraction of the same page on
* a fresh brain.
*
@@ -56,7 +62,7 @@ async function factsOf(engine: BrainEngine, slug: string): Promise<Fact[]> {
}
const shaOf = (key: string) => key.split(':')[2] ?? key;
-interface RunOpts { force?: boolean; segmentLimit?: number; sinceIso?: string; abortAfter?: number; failAt?: number; doomed?: boolean; paid?: boolean }
+interface RunOpts { force?: boolean; segmentLimit?: number; sinceIso?: string; abortAfter?: number; failAt?: number; doomed?: string; paid?: boolean }
/** One extraction run with the deterministic fake extractor; returns whether it threw and its counters. */
async function run(engine: BrainEngine, slug: string, o: RunOpts) {
@@ -69,13 +75,13 @@ async function run(engine: BrainEngine, slug: string, o: RunOpts) {
const windowSha = sha(input.turnText);
if (o.paid) await gatewayChat({ model: PAID_MODEL, messages: [{ role: 'user', content: input.turnText }], maxTokens: 64 });
if (calls === o.failAt) throw Object.assign(new Error('fake provider: upstream unavailable'), { status: 503 });
- if (o.doomed && /^[01]/.test(windowSha)) throw Object.assign(new Error('fake extractor: malformed output on this window'), { extractionReason: 'malformed_output' });
+ if (o.doomed?.includes(windowSha[0]!)) throw Object.assign(new Error('fake extractor: malformed output on this window'), { extractionReason: 'malformed_output' });
if (calls === o.abortAfter) controller.abort();
return Array.from({ length: yieldOf(windowSha) }, (_, j) => ({ fact: `Alice Example noted window ${windowSha.slice(0, 16)} item ${j}`, kind: 'fact', entity_slug: null, source: SOURCE }));
} }, controller.signal);
- return { threw: false, failed: result.pages_failed };
+ return { threw: false, failed: result.pages_failed, calls };
} catch {
- return { threw: true, failed: 1 };
+ return { threw: true, failed: 1, calls };
}
}
@@ -84,14 +90,17 @@ async function pageState(engine: BrainEngine, slug: string) {
const d = await derivations(engine, slug);
const liveRows = d.rows.filter(row => d.live.includes(row.occurrenceId));
const windowsOf = (row: (typeof d.rows)[number]) => ((row.output as { windows?: Array<{ ordinal: number; sha: string; failed?: unknown }> })?.windows ?? []);
- const liveKeys = new Set(liveRows.flatMap(row => windowsOf(row).map(w => `${row.occurrenceId}:${w.ordinal}:${w.sha}`)));
+ const liveWindows = liveRows.flatMap(row => windowsOf(row).map(w => ({ key: `${row.occurrenceId}:${w.ordinal}:${w.sha}`, sha: w.sha, failed: !!w.failed })));
+ const liveKeys = new Set(liveWindows.map(w => w.key));
const settled = liveRows.length === d.live.length && liveRows.every(row => row.state === 'done' && row.version === CONVERSATION_FACTS_DERIVATION_VERSION)
&& d.rows.every(row => windowsOf(row).every(w => !w.failed));
- return { liveKeys, settled, windowShas: liveRows.flatMap(row => windowsOf(row).map(w => w.sha)).sort() };
+ const retrying = liveRows.some(row => ((row.output as { retries?: unknown[] })?.retries ?? []).length > 0);
+ const capped = d.receipts.some(r => (r as { reason?: string } | null)?.reason === 'cap_reached');
+ return { liveKeys, liveWindows, settled, retrying, capped, windowShas: liveRows.flatMap(row => windowsOf(row).map(w => w.sha)).sort() };
}
/** Problems with one page's facts after a step (the module doc's (i)–(iii)). */
-async function violations(engine: BrainEngine, slug: string, before: Fact[], o: RunOpts, outcome: { threw: boolean; failed: number }) {
+async function violations(engine: BrainEngine, slug: string, before: Fact[], o: RunOpts, outcome: { threw: boolean; failed: number; calls: number }) {
const after = await factsOf(engine, slug);
const state = await pageState(engine, slug);
const fullySettled = !outcome.threw && outcome.failed === 0 && !o.sinceIso && state.settled;
@@ -100,13 +109,20 @@ async function violations(engine: BrainEngine, slug: string, before: Fact[], o:
const replaced = new Set([...after.filter(f => !beforeById.has(f.id)).map(f => f.key),
...after.filter(f => beforeById.has(f.id) && beforeById.get(f.id)!.key !== f.key).map(f => f.key)]);
const problems: string[] = [];
+ const fired = new Set<PropertyPath>();
+ if (state.retrying) fired.add('failed_window');
+ if (state.liveWindows.some(w => w.failed)) fired.add('marked_failed');
+ if (o.sinceIso && outcome.calls > 0) fired.add('since');
+ if (o.paid && state.capped) fired.add('cap');
for (const f of before) {
if (afterById.has(f.id)) continue;
- if (replaced.has(f.key) || (fullySettled && !state.liveKeys.has(f.key))) continue;
+ if (replaced.has(f.key)) continue;
+ if (fullySettled && !state.liveKeys.has(f.key)) { fired.add('collected'); continue; }
problems.push(`(i) fact ${f.id} of window ${f.key} disappeared without its window being extracted again or a settled collection`);
}
for (const f of after) {
const was = beforeById.get(f.id);
+ if (was && was.key !== f.key) fired.add('moved');
if (was && shaOf(was.key) !== shaOf(f.key)) problems.push(`(i) fact ${f.id} moved from ${was.key} to a window of other text ${f.key}`);
}
const perKey = new Map<string, Fact[]>();
@@ -115,12 +131,22 @@ async function violations(engine: BrainEngine, slug: string, before: Fact[], o:
if (key === 'unanchored') continue;
if (facts.length !== yieldOf(shaOf(key)) || new Set(facts.map(f => f.fact)).size !== facts.length) problems.push(`(ii) window ${key} holds ${facts.length} facts, ${new Set(facts.map(f => f.fact)).size} distinct; its text yields ${yieldOf(shaOf(key))}`);
}
+ for (const w of state.liveWindows) {
+ const held = perKey.get(w.key)?.length ?? 0;
+ if (held !== yieldOf(w.sha) && !(w.failed && held === 0)) problems.push(`(ii) live window ${w.key}${w.failed ? ' (marked failed)' : ''} holds ${held} facts; its text yields ${yieldOf(w.sha)}`);
+ }
for (const m of await claimMismatches(engine, slug)) problems.push(`(iii) a row claims ${m.claimed} facts of ${m.key}; it holds ${m.held}`);
if (fullySettled) for (const key of perKey.keys()) if (!state.liveKeys.has(key)) problems.push(`(iii) the settled page still holds facts of ${key}, no current window`);
- return { problems, after };
+ return { problems, after, fired };
}
+type PropertyPath = 'moved' | 'failed_window' | 'marked_failed' | 'collected' | 'since' | 'cap';
+/** Steps, across every seed, that must exercise each path: about half of what the 30 seeds exercise on both engines (193, 165, 46, 133, 28, 21). */
+export const PROPERTY_PATH_FLOORS: Record<PropertyPath, number> = { moved: 96, failed_window: 82, marked_failed: 23, collected: 66, since: 14, cap: 10 };
+
export function defineConversationFactsPropertyCases(opts: { getBrain: () => AppendBrain; getFresh: () => AppendBrain }): void {
+ const firedSteps: Record<PropertyPath, number> = { moved: 0, failed_window: 0, marked_failed: 0, collected: 0, since: 0, cap: 0 };
+ let seedsRun = 0;
for (let seed = 1; seed <= PROPERTY_SEEDS; seed++) {
test(`seed ${seed}: ${PROPERTY_STEPS} seeded changes and constrained runs keep the deletion invariant, and the page converges to a fresh extraction`, async () => {
const brain = opts.getBrain();
@@ -138,6 +164,10 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
await brain.seed(slug, chatPage(title, chatDays(FIRST_DAY, DAYS, seed)));
const log: string[] = [];
let facts = await factsOf(engine, slug);
+ // The windows whose text hash starts with this digit fail in every run of these steps.
+ const doomDigit = pick([...'0123456789abcdef']);
+ const doomFrom = 1 + Math.floor(next() * (PROPERTY_STEPS - 6));
+ const doomSteps = 4 + Math.floor(next() * 3);
const reseed = async (edit: (lines: string[], turnsAt: number[]) => void) => {
const lines = (await brain.body(slug)).truth.split('\n');
const turnsAt = lines.flatMap((line, i) => (line.startsWith('**') ? [i] : []));
@@ -186,7 +216,8 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
if (constraint === 'limit') o.segmentLimit = 1 + Math.floor(next() * 20);
if (constraint === 'abort') o.abortAfter = 1 + Math.floor(next() * 30);
if (constraint === 'provider') o.failAt = 1 + Math.floor(next() * 30);
- if (constraint === 'doomed') o.doomed = true;
+ if (constraint === 'doomed') o.doomed = '01';
+ if (!final && step >= doomFrom && step < doomFrom + doomSteps) o.doomed = `${o.doomed ?? ''}${doomDigit}`;
if (constraint === 'since') o.sinceIso = `${dateOf(FIRST_DAY + Math.floor(next() * (lastDay - FIRST_DAY)))}T12:00:00Z`;
if (constraint === 'cap') {
const { pageId } = await derivations(engine, slug);
@@ -200,7 +231,8 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
await engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');
});
const checked = await violations(engine, slug, facts, o, outcome);
- log.push(`step ${step}: ${change} + ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts`);
+ log.push(`step ${step}: ${change} + ${constraint} ${JSON.stringify(o)} -> ${JSON.stringify(outcome)}, ${checked.after.length} facts; ${[...checked.fired].join(' ') || 'no path'}`);
+ for (const path of checked.fired) firedSteps[path]++;
expect({ step, log: log.at(-1), problems: checked.problems.slice(0, 5) }).toEqual({ step, log: log.at(-1), problems: [] });
facts = checked.after;
}
@@ -212,16 +244,23 @@ export function defineConversationFactsPropertyCases(opts: { getBrain: () => App
for (const key of ['facts.extraction_model', 'facts.default_visibility']) await fresh.engine.setConfig(key, (await engine.getConfig(key)) ?? '');
for (const key of [PAGE_DERIVATION_CAP_KEY, PAGE_EMBED_CAP_KEY]) await fresh.engine.setConfig(key, 'off');
await fresh.seed(freshSlug, chatPage(title, (await brain.body(slug)).truth));
- expect(await run(fresh.engine, freshSlug, {})).toEqual({ threw: false, failed: 0 });
+ expect(await run(fresh.engine, freshSlug, {})).toMatchObject({ threw: false, failed: 0 });
const freshState = await pageState(fresh.engine, freshSlug);
const byWindow = (list: Fact[]) => list.map(f => `${shaOf(f.key)} ${f.fact}`).sort();
expect({ windows: state.windowShas.length, sameWindows: state.windowShas.join() === freshState.windowShas.join(), facts: facts.length,
sameFacts: byWindow(facts).join('\n') === byWindow(await factsOf(fresh.engine, freshSlug)).join('\n') })
.toEqual({ windows: freshState.windowShas.length, sameWindows: true, facts: (await factsOf(fresh.engine, freshSlug)).length, sameFacts: true });
+ seedsRun++;
} finally {
await engine.setConfig('facts.extraction_model', '');
await engine.setConfig('facts.default_visibility', 'private');
}
}, 900_000);
}
+
+ test(`every path fires at least its floor across the ${PROPERTY_SEEDS} seeds`, () => {
+ process.stderr.write(`[property] steps per path across ${seedsRun} seeds: ${JSON.stringify(firedSteps)}\n`);
+ expect({ seedsRun, short: Object.entries(PROPERTY_PATH_FLOORS).filter(([path, floor]) => firedSteps[path as PropertyPath] < floor).map(([path]) => path) })
+ .toEqual({ seedsRun: PROPERTY_SEEDS, short: [] });
+ });
}