Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(atoms): invalidate earlier extractions as each retirement commits; retry identity ignores the generation

garrytan05d5fe6a28fb
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 16ac3026f6..cab9f4bebe 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -155,14 +155,21 @@ export async function bumpAtomGeneration(tx: BrainEngine, sourceId: string, inca
* revision-only source change (a tag, a timeline row) is the same input for
* the drain and for an explicit retry (#5699).
*/
+function atomInput(session: ManagedAtomSession, origin: AtomOrigin): unknown[] {
+ return ['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash];
+}
+
+/** A retirement's regeneration generation enters the drain's key above 0, so earlier receipts are not replayed. */
function atomInputKey(session: ManagedAtomSession, origin: AtomOrigin): string {
- return digest(['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash,
- ...(origin.generation ? [origin.generation] : [])]);
+ return digest([...atomInput(session, origin), ...(origin.generation ? [origin.generation] : [])]);
}
-/** The retry check adds the extracted text's hash: a transcript retry reads the current file under the retained content hash. */
+/**
+ * The retry check adds the extracted text's hash: a transcript retry reads the current file under the retained content hash.
+ * It leaves the generation out: a retirement the reviewed batch itself committed must not invalidate its own retry.
+ */
export function atomRetryInputKey(session: ManagedAtomSession, origin: AtomOrigin): string {
- return digest([atomInputKey(session, origin), origin.textHash]);
+ return digest([digest(atomInput(session, origin)), origin.textHash]);
}
function runKey(session: ManagedAtomSession, origin: AtomOrigin): string {
@@ -265,7 +272,8 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
AND frontmatter->>'${originKey}'=$2
AND COALESCE(frontmatter->>'source_hash','')<>$3
AND NULLIF(frontmatter->>'imported_from','') IS NULL
- AND NOT (slug=ANY($4::text[]))`,
+ AND NOT (slug=ANY($4::text[]))
+ ORDER BY slug`,
[session.sourceId, origin.locator, origin.contentHash.slice(0, 16), atoms.map(atom => atom.slug)],
);
for (const retirement of retirements) {
@@ -337,6 +345,9 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
if (!prepared.noop) {
await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
+ if (p.origin.kind === 'page' && p.origin.pageId !== null) {
+ await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash);
+ }
}
return { ...result, atom_run_key: p.runKey, atom_kind: p.kind };
} };
@@ -375,13 +386,9 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
[p.checkpointKey, checkpoint, p.expectedCheckpoint === null ? null : JSON.stringify(p.expectedCheckpoint)]);
if (!advanced.length) throw new OperationError('revision_conflict', 'The reviewed atom retry checkpoint changed.');
}
- const retired = committed.filter(child => child.kind === 'managed_atom_delete').length;
- if (retired && p.origin.kind === 'page' && p.origin.pageId !== null) {
- await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash);
- }
return { status: p.failure ? 'failed' : 'completed',
atoms: committed.filter(child => child.kind === 'managed_atom_page').length,
- retired,
+ retired: committed.filter(child => child.kind === 'managed_atom_delete').length,
...(p.failure ? { failure: p.failure } : {}) };
} };
}
diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.ts
index 4525e60630..05d0a4fc41 100644
--- a/test/helpers/managed-atoms-contract.ts
+++ b/test/helpers/managed-atoms-contract.ts
@@ -294,7 +294,7 @@ export async function exerciseManagedAtomReconciliation(engine: BrainEngine): Pr
}
}
-export const atomRetirementCases = ['marker_and_republish', 'edit_back', 'user_deleted', 'prefix_pin', 'generation_key_and_purge', 'partial_retry'] as const;
+export const atomRetirementCases = ['marker_and_republish', 'edit_back', 'user_deleted', 'prefix_pin', 'generation_key_and_purge', 'partial_retry', 'partial_then_revert'] as const;
/** #5770 / ENG-O7: retirement markers, republication of retired slugs, the regeneration generation and its purge exclusion. */
export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenario: typeof atomRetirementCases[number]): Promise<void> {
@@ -340,6 +340,14 @@ export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenari
const edit = async (body: string, next: string[]) => { page = await unmanaged(() => writeSource(body)); titles = next; };
expect((await extract()).status).toBe('ok');
const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const settledState = async (requestId: string) => {
+ for (let attempt = 0; attempt < 300; attempt++) {
+ const [row] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ if (row && !['queued', 'running', 'recovering'].includes(row.state)) return row.state;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error(`request ${requestId} did not settle`);
+ };
const generation = async () => (await engine.executeRaw<{ generation: string }>(
"SELECT completed_keys->0->>'generation' AS generation FROM op_checkpoints WHERE op='managed-atoms-generation' AND fingerprint=$1", [String(page.id)]))[0]?.generation;
@@ -411,18 +419,38 @@ export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenari
await edit(bodies[2], ['Patience compounds over years', 'Hire slowly']);
writeFileSync(join(root, `${queued.slug}.md`), 'Uncoordinated operator content.');
const failed = await extract();
- expect(failed.status).toBe('warn');
+ const completion = (failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!;
+ expect(await settledState(completion.request_id)).not.toBe('committed');
expect((await atom('patience-compounds'))).toMatchObject({ deleted: true, frontmatter: { retired_by: 'managed-reextract' } });
expect((await atom('queue-patiently'))?.deleted).toBe(false);
- const completion = (failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!;
rmSync(join(root, `${queued.slug}.md`));
await disposePersistenceConsumer(engine);
expect(await retryManagedAtomBatch(engine, sourceId, completion.request_id, 'reviewed-retirement')).toMatchObject({ status: 'completed', model_rerun: false });
+ expect(await retryManagedAtomBatch(engine, sourceId, completion.request_id, 'reviewed-retirement')).toMatchObject({ status: 'completed', replayed: true, model_rerun: false });
expect(calls).toBe(3);
expect((await atom('queue-patiently'))).toMatchObject({ deleted: true, frontmatter: { retired_by: 'managed-reextract' } });
expect((await atom('patience-compounds'))?.deleted).toBe(true);
}
+ if (scenario === 'partial_then_revert') {
+ await edit(bodies[1], ['Patience compounds', 'Queue patiently', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const queued = (await atom('queue-patiently'))!;
+ await edit(bodies[2], ['Patience compounds over years', 'Hire slowly']);
+ writeFileSync(join(root, `${queued.slug}.md`), 'Uncoordinated operator content.');
+ const failed = await extract();
+ expect(await settledState((failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!.request_id)).not.toBe('committed');
+ expect((await atom('patience-compounds'))?.deleted).toBe(true);
+ rmSync(join(root, `${queued.slug}.md`));
+ await disposePersistenceConsumer(engine);
+ await edit(bodies[1], ['Patience compounds', 'Queue patiently', 'Hire slowly']);
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);
+ expect((await extract()).status).toBe('ok');
+ expect(calls).toBe(4);
+ expect((await atom('patience-compounds'))?.deleted).toBe(false);
+ expect((await atom('patience-compounds-over-years'))?.deleted).toBe(true);
+ }
+
if (scenario === 'generation_key_and_purge') {
const legacyKey = digest(['managed-atoms-v1', incarnation, 'page', slug, page.id, page.content_hash]);
expect((await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-atoms' AND fingerprint=$1", [legacyKey]))).toHaveLength(1);