Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(facts): third-pass review fixes for #7602 (keep facts rows off the sync path, list mixed extractions for re-extraction, share the facts-absorb key)
garrytan9d536f14647a
diff --git a/src/core/facts/dead-absorb-retry.ts b/src/core/facts/dead-absorb-retry.tsindex fb898a4549..562ea129b1 100644--- a/src/core/facts/dead-absorb-retry.ts+++ b/src/core/facts/dead-absorb-retry.ts@@ -25,6 +25,11 @@ export const MAX_RESUBMITS_PER_PASS = 20;export const RESUBMIT_SPACING_MS = 60 * 60_000;const WRITE_KEY_PREFIX = 'facts-absorb:write:';+/** The idempotency key of the facts-absorb job a page write's facts-backstop effect submits. */+export function factsAbsorbWriteKey(requestId: string): string {+ return `${WRITE_KEY_PREFIX}${requestId}`;+}+export type DeadAbsorbClass = 'provider' | 'config' | 'not_retryable';/**diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex 6646ed1aa0..4c266b8efb 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -1,5 +1,6 @@import type { BrainEngine } from '../engine.ts';import type { ParsedPage } from '../import-file.ts';+import { factsAbsorbWriteKey } from '../facts/dead-absorb-retry.ts';import { isFactsBackstopEligible } from '../facts/eligibility.ts';import { isFactsExtractionEnabled } from '../facts/extract.ts';import { resolvePageWriteNotabilityFilter } from '../facts/notability-filter.ts';@@ -151,7 +152,7 @@ export async function dispatchFactsBackstopEffect(engine: BrainEngine, effect: Pslug: 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 });+ }, { queue: 'default', idempotency_key: factsAbsorbWriteKey(effect.request_id), max_attempts: 5, backoff_delay: 60_000 });await completeEffect(tx, effect, { facts: 'queued', job_id: job.id });});}diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.tsindex e2becfcc7b..fc7b97746f 100644--- a/src/core/persistence/facts-maintenance.ts+++ b/src/core/persistence/facts-maintenance.ts@@ -114,7 +114,7 @@ export interface ManagedFactsSession {signal?: AbortSignal;}-/** #6048: follow-up batches one input-keyed extraction may admit for file-check refusals. */+/** #6048: follow-up batches one extraction may admit for each followed refusal walk (file check, withdrawal, #7602 moved entity). */export const MAX_FILE_REFUSAL_RETRIES = 3;/**diff --git a/src/core/persistence/large-file.ts b/src/core/persistence/large-file.tsindex a43cf55831..1910a60400 100644--- a/src/core/persistence/large-file.ts+++ b/src/core/persistence/large-file.ts@@ -18,6 +18,7 @@ import { OperationError, opError } from '../ops/contract.ts';import { assertManagedFilesystemWrite } from './filesystem-guard.ts';import { sha256 } from './digest.ts';import type { RecoveryStagingFile } from './staging.ts';+import { PAGE_CHANGED_DURING_PREPARATION_MESSAGE } from './verb-errors.ts';import { faultPoint } from './fault-points.ts';/** A canonical file of more bytes than this is read, hashed, copied and written in pieces. */@@ -180,7 +181,7 @@ export async function stageStreamedContent(engine: BrainEngine, path: string, cobytes += piece.length;await faultPoint('large_file:stage_streaming', { path: streaming });}- if (bytes !== stage.bytes || hash.digest('hex') !== stage.hash) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');+ if (bytes !== stage.bytes || hash.digest('hex') !== stage.hash) throw new OperationError('revision_conflict', PAGE_CHANGED_DURING_PREPARATION_MESSAGE, 'Read its current revision and submit the updated intent with a new request_id.');fsyncSync(fd);} finally { closeSync(fd); }if (existsAt(stage.path)) throw opError('unexpected_staging_bytes', 'A file already holds the reserved stage name.',diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex 69fd8694ac..76817f5a8d 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -14,7 +14,8 @@ export const FACTS_BATCH_INCOMPLETE_MESSAGE = 'Some extracted facts have not comexport const FACTS_ENTITY_CHANGED_MESSAGE = 'The fact entity changed after extraction admission.';export const FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE = 'The fact entity changed during preparation.';export const FACTS_DEDUP_CHANGED_MESSAGE = 'The fact deduplication state changed before publication.';-/** The coordinator's refusal when the page moved between preparation and publication (coordinator.ts, group-publish.ts). */+/** The coordinator's refusal when the page moved between preparation and publication (coordinator.ts, group-publish.ts), also+ * thrown when a staged large file no longer matches its stage (large-file.ts); fact requests never stage large files. */export const PAGE_CHANGED_DURING_PREPARATION_MESSAGE = 'The page changed during preparation.';/** #7602: entity request refusals a follow-up batch re-admits at the entity's current revision (facts-maintenance.ts). */export const FACTS_ENTITY_MOVED_MESSAGES: readonly string[] = [FACTS_ENTITY_CHANGED_MESSAGE, FACTS_ENTITY_CHANGED_IN_PREPARATION_MESSAGE, FACTS_DEDUP_CHANGED_MESSAGE,diff --git a/src/core/repair/failed-writes.ts b/src/core/repair/failed-writes.tsindex b300f40076..7ed58b38cf 100644--- a/src/core/repair/failed-writes.ts+++ b/src/core/repair/failed-writes.ts@@ -56,7 +56,7 @@ import { prepareFileTarget } from '../persistence/page-prepare.ts';import { PENDING_IMPORT, SYNC_HELD } from '../persistence/pending-import.ts';import { FACTS_ENTITY_MOVED_MESSAGES } from '../persistence/verb-errors.ts';import { MAX_FILE_REFUSAL_RETRIES } from '../persistence/facts-maintenance.ts';-import { factsRetryDeadCommand } from '../facts/dead-absorb-retry.ts';+import { factsAbsorbWriteKey, factsRetryDeadCommand } from '../facts/dead-absorb-retry.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';import { resolveEntitySlugWithSource } from '../entities/resolve.ts';import { dispositionOf, PAGE_REMOVAL_OPERATIONS, supersessionOrderSql, supersessionSql } from '../persistence/terminal-classify.ts';@@ -79,6 +79,9 @@ const FACTS_RECOVERED = `EXISTS (SELECT 1 FROM persistence_requests c WHERE r.opAND COALESCE(c.intent->>'inputDigest', c.outcome->>'input_digest')=r.intent->>'inputDigest'AND COALESCE(c.intent->>'batchKey', c.outcome->>'batch_key') IS DISTINCT FROM r.intent->>'batchKey')`;+/** One managed fact entity request of an extraction (every request sharing its source and input digest). */+interface ExtractionRequest { slug: string; state: string; error_code: string | null; error_message: string | null; batch_key: string | null }+interface FailedWrite {id: string; request_id: string; sequence: string; operation: string; source_id: string; slug: string; digest: string; state: string;intent: Record<string, unknown>; authority: WriteAuthority; created_at: string; producer: string | null; error_code: string | null; page_id: string | null;@@ -97,34 +100,41 @@ function previewCommand(scope: RepairScope): string {/*** #7602: a refused fact request keeps its extracted facts. A page-triggered one (its job is keyed by the page write) is* recovered by resetting that job once it is dead: its retry re-admits them at the entity page's current revision with- * no model call, once the cause clears. A batch whose follow-ups were refused too, an entity page replaced since, a job- * that completed or is gone, a writer-guard refusal and a batch with no page write would replay the refusal or have no- * job to retry: those are extracted again.+ * no model call, once the cause clears. Only an extraction whose open entity requests are all moved-entity refusals (the+ * entity walk) or all held-file refusals (the file walk) is re-admitted by one retry. A mixed extraction, a batch whose+ * follow-ups were refused too, an entity page replaced since, a job that completed or is gone, a writer-guard refusal+ * and a batch with no page write would replay the refusal or have no job to retry: those are extracted again.*/-async function factsRecovery(engine: BrainEngine, write: FailedWrite, rows: FailedWrite[]): Promise<string> {+async function factsRecovery(engine: BrainEngine, write: FailedWrite, extractions: Map<string, ExtractionRequest[]>): Promise<string> {const origin = (write.intent.origin as { slug?: string } | null | undefined)?.slug;const job = typeof write.intent.originalRequestId === 'string' ? write.intent.originalRequestId : null;const extractAgain = `re-extract: gbrain call extract_facts again on the current text of ${origin ?? 'the source turn'} with a new request_id (one model call)`;if (!job || write.state !== 'conflict') return extractAgain;- const chain = rows.filter(row => row.operation === 'extract_facts' && row.source_id === write.source_id && row.slug === write.slug- && row.intent.inputDigest === write.intent.inputDigest);- if (chain.some(row => row.error_code === 'source_changed' && chain.some(prior => prior.error_code === 'revision_conflict' && Number(prior.sequence) < Number(row.sequence)))) {- return `${extractAgain}; a follow-up of its moved-entity refusal was refused for a held file, which a job retry does not re-admit`;+ const extraction = `${write.source_id}\n${String(write.intent.inputDigest)}`;+ if (!extractions.has(extraction)) extractions.set(extraction, await engine.executeRaw<ExtractionRequest>(+ `SELECT slug, state, error_code, error_message, intent->>'batchKey' AS batch_key FROM persistence_requests+ WHERE operation='extract_facts' AND source_id=$1 AND intent->>'inputDigest'=$2 AND intent->>'kind'='managed_facts_entity'`, [write.source_id, write.intent.inputDigest]));+ const open = extractions.get(extraction)!.filter(row => row.state !== 'committed');+ const moved = (row: ExtractionRequest) => row.error_code === 'revision_conflict' && FACTS_ENTITY_MOVED_MESSAGES.includes(row.error_message ?? '');+ if (!open.every(moved) && !open.every(row => row.error_code === 'source_changed')) {+ return `${extractAgain}; its extraction also holds refusals one job retry does not re-admit together`;}if (write.error_code === 'revision_conflict') {const [page] = await engine.executeRaw<{ id: string }>('SELECT id::text FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [write.source_id, write.slug]);if (!page && write.page_id !== null) return `not recoverable: entity page ${write.slug} was deleted after these facts were admitted`;if ((page?.id ?? null) !== write.page_id) return `${extractAgain}; entity page ${write.slug} was replaced after these facts were admitted, so a job retry replays the refusal`;- const batches = new Set(chain.filter(row => row.error_code === 'revision_conflict').map(row => row.intent.batchKey));- if (batches.size > MAX_FILE_REFUSAL_RETRIES) return `${extractAgain}; its follow-up batches were refused as well, so a job retry replays the refusal`;+ if (new Set(open.filter(row => row.slug === write.slug).map(row => row.batch_key)).size > MAX_FILE_REFUSAL_RETRIES) {+ return `${extractAgain}; its follow-up batches were refused as well, so a job retry replays the refusal`;+ }}- const key = `facts-absorb:write:${job}`;+ const key = factsAbsorbWriteKey(job);const [run] = await engine.executeRaw<{ status: string }>("SELECT status FROM minion_jobs WHERE name='facts-absorb' AND idempotency_key=$1 ORDER BY id DESC LIMIT 1", [key]);if (run && run.status !== 'dead' && run.status !== 'completed' && run.status !== 'cancelled') return `pending: its facts-absorb job (${key}) is ${run.status}; preview again once it ends`;if (run?.status !== 'dead') return `${extractAgain}; its facts-absorb job ${run ? `is ${run.status}` : 'is gone'}, so gbrain facts retry-dead has no dead job to reset`;return `recover: ${factsRetryDeadCommand('--reset', key)} (the next facts_drain pass retries the page's facts-absorb job, which re-admits the retained facts without a model call${write.error_code === 'source_changed' ? ' once the file check passes' : ''})`;}+/** The command that produces an owner-internal write again, from current content. */function producerCommand(producer: string, sourceId: string): string {const parts = producer.split(':');@@ -139,14 +149,16 @@ function producerCommand(producer: string, sourceId: string): string {return 'the next `gbrain dream` cycle (or autopilot) produces it again';}-async function failedWrites(engine: BrainEngine, sourceIds: string[], id?: string): Promise<FailedWrite[]> {+/** `facts` (the preview only) adds refused fact requests, without the ones a later request of the same extraction recovered. */+async function failedWrites(engine: BrainEngine, sourceIds: string[], opts: { id?: string; facts?: boolean } = {}): Promise<FailedWrite[]> {+ const { id, facts } = opts;const rows = await engine.executeRaw<FailedWrite>(`SELECT r.id::text, r.request_id::text, r.sequence::text, r.operation, r.source_id, r.slug, r.digest, r.state, r.intent, r.authority,to_char(r.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS created_at, r.error_detail->>'origin' AS origin, r.error_code, r.page_id::text AS page_id,CASE WHEN r.operation = ANY($2::text[]) AND NOT (r.operation='put_page' AND r.intent ? 'kind') THEN NULLELSE r.operation || COALESCE(':' || (r.intent->>'kind'), '') END AS producerFROM persistence_requests r- WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL} OR ${FACTS_MOVED_REFUSAL})- AND NOT ${FACTS_RECOVERED}+ WHERE r.source_id = ANY($1::text[]) AND NOT r.compacted AND r.intent IS NOT NULL AND (${GUARD_REFUSAL} OR ${DRIFT_REFUSAL}${facts ? ` OR ${FACTS_MOVED_REFUSAL}` : ''})+ ${facts ? `AND NOT ${FACTS_RECOVERED}` : ''}${id ? 'AND r.id=$3::uuid' : ''}ORDER BY r.sequence`, id ? [sourceIds, REPLAYABLE, id] : [sourceIds, REPLAYABLE]);if (id) return rows;@@ -349,7 +361,8 @@ export const failedWritesRepair: RepairHandler = {async plan(engine, scope, after, opts): Promise<RepairPlan> {const command = previewCommand(scope);if (!opts?.apply) {- const rows = await failedWrites(engine, scope.source_ids);+ const rows = await failedWrites(engine, scope.source_ids, { facts: true });+ const extractions = new Map<string, ExtractionRequest[]>();const residuals: Record<string, number> = {};const listing: NonNullable<RepairPlan['listing']> = [];const producers = new Map<string, string>();@@ -359,7 +372,7 @@ export const failedWritesRepair: RepairHandler = {if (write.producer) {residuals[`producer_owned:${write.producer}`] = (residuals[`producer_owned:${write.producer}`] ?? 0) + 1;const facts = write.operation === 'extract_facts';- const run = facts ? await factsRecovery(engine, write, rows) : producerCommand(write.producer, write.source_id);+ const run = facts ? await factsRecovery(engine, write, extractions) : producerCommand(write.producer, write.source_id);producers.set(`${write.producer} in ${write.source_id}`, facts ? 'each listed request names the command that recovers its facts' : run);listing.push({ item: label, class: 'producer_owned', detail: facts ? run : `re-run: ${run}` });continue;@@ -447,7 +460,7 @@ async function replayParams(ctx: OperationContext, write: ApprovedWrite, request}async function replay(ctx: OperationContext, failed: ApprovedWrite): Promise<RepairItemOutcome> {- const [live] = await failedWrites(ctx.engine, [failed.source_id], failed.id);+ const [live] = await failedWrites(ctx.engine, [failed.source_id], { id: failed.id });if (!live || live.digest !== failed.digest) return { applied: false, outcome: 'changed_since_preview', reason: 'the failed request was compacted or changed' };const lane = laneContext(ctx, live.authority);await initializeLocalPersistence(lane);diff --git a/test/facts-entity-moved-7602.test.ts b/test/facts-entity-moved-7602.test.tsindex 2d7a407f8b..0c81926ac4 100644--- a/test/facts-entity-moved-7602.test.ts+++ b/test/facts-entity-moved-7602.test.ts@@ -319,6 +319,33 @@ for (const backend of testBackends()) {expect((await factsListing(engine)).map(entry => entry.detail)).toEqual([`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); entity page ${TARGET} was replaced after these facts were admitted, so a job retry replays the refusal`]);}, { databaseUrl }), 120_000);+ // Value: protects=a held-file sibling refused beside a moved entity is listed for re-extraction, not the job retry (the+ // file walk re-admits only a batch whose open requests are all held-file refusals); fails_when=the sibling is listed+ // with retry-dead, or the moved entity is not re-admitted; why_new=#7439 holds the only entity, the held-follow-up row+ // holds the moved entity itself; seam=the hold is written directly, as #7439 does; no_claim=does not clear the hold+ test(`#7602 [${backend}]: a held-file sibling refused beside a moved entity is listed for re-extraction`, () => managedBrain(async brain => {+ const { engine, ctx, root } = brain;+ const { move, loser } = await setup(brain, 1);+ await put(ctx, OTHER, 'company');+ const other = (await engine.readPageSnapshot(OTHER, { sourceId: 'default' }))!;+ const path = `${OTHER}.md`, file = join(root, path);+ writeFileSync(file, readFileSync(file, 'utf8') + '\nAn unimported edit.\n');+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation: other.sourceIncarnation,+ path, source_path: path, slug: OTHER, page_id: null, code: 'preparation_stalled', message: 'The write owner stalled.',+ upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'managed', meta: { recovery_version: RECOVERY_VERSION } }));+ const race = raceEntityReads(engine, 1, move);+ const refused = await publishManagedFacts(engine, await loser.session(), loser.backstop, [{ ...fact(CLAIM_OTHER), entity_slug: OTHER }, fact(CLAIM_B)],+ 'private', loser.slug).catch(error => error).finally(race.restore);+ expect(race.moves()).toBe(1);+ expect(refused.code).toBe('source_changed');+ expect(await claimB(engine)).toEqual([{ fact: CLAIM_B, source_markdown_slug: TARGET }]);+ expect(await engine.executeRaw("UPDATE minion_jobs SET status='dead' WHERE name='facts-absorb' AND idempotency_key=$1 RETURNING id", [`facts-absorb:write:${loser.write}`])).toHaveLength(1);+ const preview = await (await repairRunner(engine, { apply: false, logger: { info() {}, warn() {}, error() {} } }))+ .run('failed-writes', await resolveRepairScope(engine, 'default'), { explicit: true, sourceFlag: 'default' });+ expect((preview.listing ?? []).filter(entry => entry.item.includes(' extract_facts')).map(entry => [entry.item.split(' ')[0], entry.detail])).toEqual([+ [`default:${OTHER}`, `re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); its extraction also holds refusals one job retry does not re-admit together`]]);+ }, { databaseUrl }), 120_000);+// Value: protects=when the entity's file is held between the move and the follow-up, repair lists the whole chain for// re-extraction instead of the job retry, which would replay the follow-up's file refusal; fails_when=either request is listed// with retry-dead; why_new=#7439 covers a held file on the original batch only; seam=the hold is written directly, as #7439 does;@@ -340,7 +367,7 @@ for (const backend of testBackends()) {expect(refused.code).toBe('source_changed');expect((await entityRequests(engine)).map(row => [row.state, row.error_code])).toEqual([['conflict', 'revision_conflict'], ['conflict', 'source_changed']]);expect(await claimB(engine)).toEqual([]);- expect((await factsListing(engine)).map(entry => entry.detail)).toEqual(Array(2).fill(`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); a follow-up of its moved-entity refusal was refused for a held file, which a job retry does not re-admit`));+ expect((await factsListing(engine)).map(entry => entry.detail)).toEqual(Array(2).fill(`re-extract: gbrain call extract_facts again on the current text of ${loser.slug} with a new request_id (one model call); its extraction also holds refusals one job retry does not re-admit together`));}, { databaseUrl }), 120_000);test(`#7602 [${backend}]: an entity page deleted after admission is not re-targeted; the refusal is not retryable`, () => managedBrain(async brain => {diff --git a/test/pathological/a-36-facts-batch-partial-refusal.test.ts b/test/pathological/a-36-facts-batch-partial-refusal.test.tsindex e373d6f9cb..c1aeb21e33 100644--- a/test/pathological/a-36-facts-batch-partial-refusal.test.ts+++ b/test/pathological/a-36-facts-batch-partial-refusal.test.ts@@ -271,12 +271,12 @@ for (const backend of testBackends()) {});}, 180_000);- test('A-36 explicit: a fact writer that names its entity still refuses when that entity changed after admission', async () => {+ test('A-36 explicit: a fact writer that names its entity still refuses, not retryable, when that entity changed after admission', async () => {await managedSource(engine, editB, async ({ sourceId, reachedB }) => {const facts = [{ fact: 'Acme Example hired a new CFO.', kind: 'fact', source: 'test', notability: 'high', sessionId: null, visibility: 'world', confidence: 1 }];const refusal = await publishManagedEntityFacts(engine, sourceId, B, facts as never).then(() => null, (thrown: { code?: string }) => thrown);expect(reachedB()).toBe(1);- expect(refusal).toMatchObject({ code: 'revision_conflict' });+ expect(refusal).toMatchObject({ code: 'revision_conflict', retryable: false });});}, 180_000);});