Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: health metric that cannot converge, and facts lost to a row_num collision (#3634)

Garry Tana82a83dbc3f3
diff --git a/src/core/facts/fence-write.ts b/src/core/facts/fence-write.ts
index ae35769fb3..69f4c2dda5 100644
--- a/src/core/facts/fence-write.ts
+++ b/src/core/facts/fence-write.ts
@@ -219,10 +219,51 @@ export async function writeFactsToFence(
// 2. Upsert each fact onto the fence in input order. row_num
// monotonically increases (max-existing + 1 per call, append-only).
+ //
+ // Seed the counter from the DB as well as the fence file. Uniqueness
+ // is enforced by idx_facts_fence_key on
+ // (source_id, source_markdown_slug, row_num) in Postgres, but
+ // upsertFactRow derives the next value from the fence in the markdown
+ // alone — and falls back to 1 when the file has no fence at all. Any
+ // write path that rewrites a page without preserving its facts fence
+ // (put_page write-through, sync, dream-cycle reverse-render) therefore
+ // resets the counter below what the DB already holds, and the next
+ // absorb re-issues a row_num that is already taken. That surfaces as
+ // "duplicate key value violates unique constraint idx_facts_fence_key"
+ // and the whole batch of facts is dropped.
+ //
+ // Symptom in the wild: a page whose fence had been rewritten away had
+ // 24 facts in the DB and none in the file, so every subsequent absorb
+ // on it failed permanently. Taking the max of both sources keeps the
+ // file as the readable mirror while the DB stays authoritative about
+ // which row_nums have been issued.
+ //
+ // Degrades to the previous file-only behaviour if the lookup fails
+ // (pre-v51 brain without the fence columns, or a transient DB error):
+ // a fence write must not become impossible just because the counter
+ // hint is unavailable.
+ let dbMaxRowNum = 0;
+ try {
+ const rows = await engine.executeRaw<{ max_row_num: number | null }>(
+ `SELECT MAX(row_num) AS max_row_num FROM facts
+ WHERE source_id = $1 AND source_markdown_slug = $2`,
+ [target.sourceId, target.slug],
+ );
+ dbMaxRowNum = Number(rows[0]?.max_row_num ?? 0);
+ } catch {
+ dbMaxRowNum = 0;
+ }
+ const { facts: existingFenceFacts } = parseFactsFence(body);
+ const fileMaxRowNum = existingFenceFacts.length > 0
+ ? Math.max(...existingFenceFacts.map(f => f.rowNum))
+ : 0;
+ let nextRowNum = Math.max(fileMaxRowNum, dbMaxRowNum) + 1;
+
const assignedRowNums: number[] = [];
for (const f of facts) {
const validFromStr = (f.validFrom ?? new Date()).toISOString().slice(0, 10);
const { body: updated, rowNum } = upsertFactRow(body, {
+ rowNum: nextRowNum++,
claim: f.fact,
kind: (f.kind ?? 'fact') as 'fact' | 'event' | 'preference' | 'commitment' | 'belief',
confidence: f.confidence ?? 1.0,
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 64e139f60a..f085ecfb76 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -2407,7 +2407,7 @@ export class PGLiteEngine implements BrainEngine {
}
// CONSISTENCY: when chunk_text changes and no new embedding is supplied, BOTH embedding AND
- // embedded_at must reset to NULL so `embed --stale` correctly picks up the row for re-embedding.
+ // embedded_at must reset to NULL so 'embed --stale' correctly picks up the row for re-embedding.
// See postgres-engine.ts upsertChunks for the full rationale — pglite mirrors it for parity.
//
// v0.40.3.0 D24 NULL→non-NULL race fix mirrors postgres-engine.ts. Two writers
@@ -5392,7 +5392,16 @@ export class PGLiteEngine implements BrainEngine {
(SELECT count(*) FROM links l
WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
) as dead_links,
- (SELECT count(*) FROM content_chunks WHERE embedded_at IS NULL) as missing_embeddings,
+ -- Parity with postgres-engine.ts: same predicate as
+ -- buildStaleChunkWhere / countStaleChunks, i.e. what 'embed --stale'
+ -- actually processes. 'embedding IS NULL' (not embedded_at, which can
+ -- be non-NULL while embedding is NULL) and embed_skip excluded, so the
+ -- count can reach zero and the embed.stale remediation can converge.
+ (SELECT count(*) FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ WHERE cc.embedding IS NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
+ ) as missing_embeddings,
(SELECT count(*) FROM links) as link_count,
(SELECT count(*) FROM entity_pages e
WHERE EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = e.id))::float /
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index 22e58be767..f99b3eec1f 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -2527,15 +2527,15 @@ export class PostgresEngine implements BrainEngine {
// Single statement upsert: preserves existing embeddings via COALESCE when new value is NULL.
// CONSISTENCY: when chunk_text changes and no new embedding is supplied, BOTH embedding AND
- // embedded_at must reset to NULL so `embed --stale` correctly picks up the row for re-embedding.
+ // embedded_at must reset to NULL so 'embed --stale' correctly picks up the row for re-embedding.
// Without this, embedded_at lies (says "embedded" while embedding=NULL), and any staleness
// predicate on embedded_at would silently skip the row. This is why the egress fix predicates
- // on `embedding IS NULL` rather than `embedded_at IS NULL` — and it's why we now keep both
+ // on 'embedding IS NULL' rather than `embedded_at IS NULL` — and it's why we now keep both
// columns honest at write time.
//
// v0.40.3.0 D24 NULL→non-NULL race fix (TODOS.md v0.35.x item).
// Two writers racing on the same chunk (e.g., autopilot sync + manual
- // `embed --stale` + contextual reindex) previously raced last-write-wins
+ // 'embed --stale' + contextual reindex) previously raced last-write-wins
// via `COALESCE(EXCLUDED.embedding, content_chunks.embedding)`. With
// per-chunk Haiku synopsis the cost of an overwrite jumped from
// ~$0.000001 to ~$0.0003. New rule for the text-unchanged branch:
@@ -5489,7 +5489,25 @@ export class PostgresEngine implements BrainEngine {
(SELECT count(*) FROM links l
WHERE NOT EXISTS (SELECT 1 FROM pages p WHERE p.id = l.to_page_id)
) as dead_links,
- (SELECT count(*) FROM content_chunks WHERE embedded_at IS NULL) as missing_embeddings,
+ -- missing_embeddings uses the same predicate as the thing that
+ -- resolves it: buildStaleChunkWhere / countStaleChunks, i.e. what
+ -- 'embed --stale' actually processes. Two divergences existed:
+ -- 1. embedded_at vs embedding. upsertChunks resets BOTH to NULL
+ -- when chunk_text changes, but the stale-chunk predicate keys
+ -- on 'embedding IS NULL' deliberately (see the CONSISTENCY note
+ -- on that upsert) because embedded_at can be non-NULL while
+ -- embedding is NULL. Health should agree with the embedder.
+ -- 2. embed_skip pages were counted here but excluded there, so
+ -- chunks the author opted out of read as permanently "missing"
+ -- and the count could never reach zero.
+ -- Effect of the mismatch: computeRecommendations emits an embed.stale
+ -- step from a number that 'embed --stale' reports as 0, so the step
+ -- cannot move it and 'doctor --remediate' re-plans it every pass.
+ (SELECT count(*) FROM content_chunks cc
+ JOIN pages p ON p.id = cc.page_id
+ WHERE cc.embedding IS NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')
+ ) as missing_embeddings,
(SELECT count(*) FROM links) as link_count,
(SELECT count(*) FROM entity_pages e
WHERE EXISTS (SELECT 1 FROM links l WHERE l.to_page_id = e.id))::float /
diff --git a/test/fence-write.test.ts b/test/fence-write.test.ts
index 3bcb0c05bd..92207890d3 100644
--- a/test/fence-write.test.ts
+++ b/test/fence-write.test.ts
@@ -292,6 +292,77 @@ describe('lookupSourceLocalPath', () => {
});
});
+describe('writeFactsToFence — row_num survives a fence-less rewrite', () => {
+ // Regression: row_num uniqueness is enforced by idx_facts_fence_key on
+ // (source_id, source_markdown_slug, row_num), but the value was derived
+ // from the markdown fence alone, falling back to 1 when the file has no
+ // fence. Any write path that rewrites a page without preserving its facts
+ // fence (put_page write-through, sync, dream-cycle reverse-render) then
+ // makes the next absorb re-issue an already-taken row_num, and the whole
+ // batch dies on a duplicate-key error.
+ test('does not reuse a row_num after the fence is stripped from the file', async () => {
+ const slug = 'people/carol';
+ const filePath = join(brainDir, `${slug}.md`);
+
+ const first = await writeFactsToFence(
+ engine,
+ { sourceId: 'default', localPath: brainDir, slug },
+ [baseInput({ fact: 'First fact' }), baseInput({ fact: 'Second fact' })],
+ );
+ expect(first.inserted).toBe(2);
+
+ // Simulate a non-fence-aware writer replacing the page body. The DB still
+ // holds row_num 1 and 2; the file now advertises none.
+ writeFileSync(
+ filePath,
+ '---\ntype: person\ntitle: Carol\nslug: people/carol\n---\n\n# Carol\n\nRegenerated without the fence.\n',
+ 'utf-8',
+ );
+ expect(readFileSync(filePath, 'utf-8')).not.toContain('First fact');
+
+ // Pre-fix this threw: upsertFactRow restarted at 1, colliding with the
+ // existing rows on idx_facts_fence_key.
+ const second = await writeFactsToFence(
+ engine,
+ { sourceId: 'default', localPath: brainDir, slug },
+ [baseInput({ fact: 'Third fact' })],
+ );
+ expect(second.inserted).toBe(1);
+ expect(second.fenceWriteFailed).toBeUndefined();
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const rows = await (engine as any).db.query(
+ 'SELECT row_num, fact FROM facts WHERE source_markdown_slug = $1 ORDER BY row_num',
+ [slug],
+ );
+ const rowNums = rows.rows.map((r: { row_num: number }) => r.row_num);
+ // Three distinct row_nums, and the new one clears the previous maximum.
+ expect(new Set(rowNums).size).toBe(3);
+ expect(Math.max(...rowNums)).toBeGreaterThan(2);
+ });
+
+ test('still writes when the facts table cannot be consulted', async () => {
+ // The DB seed is a hint, not a hard dependency: a lookup failure must
+ // degrade to the previous file-derived behaviour rather than making
+ // fence writes impossible (pre-v51 brains, transient DB errors).
+ const brokenEngine = Object.create(engine) as typeof engine;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (brokenEngine as any).executeRaw = async (sqlText: string, params: unknown[]) => {
+ if (sqlText.includes('MAX(row_num)')) throw new Error('simulated lookup failure');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return (engine as any).executeRaw(sqlText, params);
+ };
+
+ const result = await writeFactsToFence(
+ brokenEngine,
+ { sourceId: 'default', localPath: brainDir, slug: 'people/dave' },
+ [baseInput({ fact: 'Written despite the failed hint' })],
+ );
+ expect(result.inserted).toBe(1);
+ expect(result.fenceWriteFailed).toBeUndefined();
+ });
+});
+
// Cleanup any leftover tempdirs after the whole suite.
afterAll(() => {
// No-op: each test cleaned up via the beforeEach; this is a safety net.