Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(consolidate): one refused bucket is counted and sampled, later buckets still consolidate (GBRA-130 A-22)

garrytanc3cb0e0e0403
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index 265ad94625..9fd8e00ccb 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -29,6 +29,7 @@ import { cosineSimilarity } from '../../facts/classify.ts';
import { claimsDiverge, EXPLICIT_DUPLICATE_THRESHOLD } from '../../facts/capture-dedup.ts';
import { createHash } from 'node:crypto';
import { isAborted } from '../../abort-check.ts';
+import { classifyItemFailure, ItemRun } from '../../item-failure.ts';
import { maintenancePreflight, submitMaintenanceConsolidation } from '../../persistence/prepared-maintenance.ts';
import { managedPersistenceEnabled } from '../../persistence/ownership.ts';
import { declareDerivation, derivedMaintenanceTransaction, derivedWriteTrust, isExternalTier, readTaintInputs } from '../../trust/taint.ts';
@@ -81,9 +82,47 @@ async function disabledSkip(engine: BrainEngine, opts: ConsolidatePhaseOpts): Pr
details: { reason: 'disabled', enable_hint: `gbrain config set ${CONSOLIDATE_ENABLED_KEY} true` } };
}
+/** At most this many failed buckets are listed in `details.bucket_failures`; `buckets_failed` counts them all. */
+const BUCKET_FAILURE_SAMPLES = 10;
+
export const CLUSTER_THRESHOLD_KEY = 'cycle.consolidate.cluster_threshold';
export const DEFAULT_CLUSTER_THRESHOLD = 0.85;
+/**
+ * v0.35.4 (D-CDX-4 part 2) — chronological valid_until writeback.
+ * Sort the cluster by (valid_from ASC, id ASC); walk consecutive
+ * pairs; stamp the older fact's valid_until = next_newer.valid_from.
+ * The newest fact keeps valid_until = NULL. This makes the facts
+ * table a proper bitemporal record without the contradiction probe
+ * having to mutate it (preserves auto-supersession.ts:4 invariant —
+ * see also R8 test guard).
+ *
+ * Idempotent: re-running on the same cluster produces the same
+ * chronological order and the same valid_until values. No-op if
+ * valid_until is already correct.
+ */
+async function writeValidUntilChain(tx: BrainEngine, cluster: FactRow[]): Promise<void> {
+ const chronological = [...cluster].sort((a, b) => {
+ const t = a.valid_from.getTime() - b.valid_from.getTime();
+ if (t !== 0) return t;
+ return a.id - b.id;
+ });
+ for (let i = 0; i < chronological.length - 1; i++) {
+ const older = chronological[i];
+ const newer = chronological[i + 1];
+ await tx.executeRaw(
+ // Only UPDATE when the new value would actually change. Avoids
+ // touching updated_at on no-op rewrites and keeps idempotency
+ // observable in the DB (zero affected rows on stable re-run).
+ `UPDATE facts
+ SET valid_until = $1
+ WHERE id = $2
+ AND (valid_until IS DISTINCT FROM $1)`,
+ [newer.valid_from, older.id],
+ );
+ }
+}
+
/**
* #5363: parse `cycle.consolidate.cluster_threshold`. A cosine similarity in
* (0, 1]; lower values merge more facts into one take. Throws on anything
@@ -157,6 +196,9 @@ export async function runPhaseConsolidate(
};
}
+ const run = new ItemRun('consolidate.buckets');
+ let bucketsFailed = 0;
+ const bucketFailures: Array<{ source_id: string; entity_slug: string; code: string; message: string; fix: string }> = [];
for (const b of buckets) {
// #1972: bail at the top of the bucket loop on abort. Each prior bucket's
// per-row INSERT/consolidate is already committed, so breaking returns a
@@ -167,218 +209,204 @@ export async function runPhaseConsolidate(
try { await opts.yieldDuringPhase(); } catch { /* keepalive errors non-fatal */ }
}
- const maintenance = managed && !dryRun ? await maintenancePreflight(engine, b.source_id) : null;
- const candidates = await engine.listFactsByEntity(b.source_id, b.entity_slug, {
- activeOnly: true,
- unconsolidatedOnly: true,
- visibility: managed ? ['world'] : undefined,
- limit: 100,
- });
- // Takes here are the user's own (holder 'self'): a claim the assistant or
- // a named third party asserted is never promoted into one.
- const unconsolidated = candidates.filter(f => (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));
- if (unconsolidated.length < minPerBucket) {
- bucketsSkipped += 1;
- continue;
- }
-
- // Age gate: oldest must be at least minOldestAgeMs old.
- const oldest = unconsolidated.reduce((min, f) =>
- f.valid_from.getTime() < min.valid_from.getTime() ? f : min,
- );
- if (Date.now() - oldest.valid_from.getTime() < minOldestAgeMs) {
- bucketsSkipped += 1;
- continue;
- }
-
- bucketsProcessed += 1;
- const claims = await loadClaimShapes(engine, unconsolidated.map(f => f.id));
- // #5575 ENG-3: a take's tier is the least trusted fact in its cluster, so
- // external facts cluster apart from owner facts and their takes are external.
- const taint = new Map((await readTaintInputs(engine, unconsolidated.map(f => ({ table: 'facts' as const, id: f.id })))).map(i => [Number(i.id), i]));
- const clusters = [false, true].flatMap(external =>
- clusterFacts(unconsolidated.filter(f => isExternalTier(taint.get(f.id)!.tier) === external), threshold, claims));
-
- // Resolve entity_slug → page_id. If page missing in this source, skip.
- const pageRows = await engine.executeRaw<{ id: number }>(
- `SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,
- [b.source_id, b.entity_slug],
- );
- if (pageRows.length === 0) continue;
- const pageId = pageRows[0].id;
-
- // Existing row_num max for this page → start appending after it.
- const rowMaxRows = await engine.executeRaw<{ max: number }>(
- `SELECT COALESCE(MAX(row_num), 0)::int AS max FROM takes WHERE page_id = $1`,
- [pageId],
- );
- let nextRowNum = (rowMaxRows[0]?.max ?? 0) + 1;
-
- for (const cluster of clusters) {
- if (cluster.length < 2) continue;
- // Take selection: pick the highest-confidence fact's text as the
- // take claim (v0.31 deterministic). v0.32 will swap to a Sonnet
- // synthesis pass.
- const best = cluster.reduce((a, b) => (b.confidence > a.confidence ? b : a));
- const avgWeight = cluster.reduce((s, f) => s + f.confidence, 0) / cluster.length;
- const sources = Array.from(new Set(cluster.map(c => c.source_session ?? c.source).filter(Boolean))).join(',');
- const sinceISO = cluster
- .map(c => c.valid_from)
- .reduce((min, d) => (d < min ? d : min))
- .toISOString()
- .slice(0, 10);
- const inputs = cluster.map(f => taint.get(f.id)!);
- const derivation = { inputs, trust: derivedWriteTrust({ channel: 'derive:consolidate', inputs }) };
-
- if (dryRun) {
- // Pretend we did it.
- takesWritten += 1;
- factsConsolidated += cluster.length;
- nextRowNum += 1;
- if (preview.length < DRY_RUN_CLUSTER_CAP) {
- const text = (f: FactRow) => (showPrivate || f.visibility === 'world' ? f.fact : null);
- preview.push({ source_id: b.source_id, entity_slug: b.entity_slug, claim: text(best),
- members: cluster.map(f => ({ id: f.id, visibility: f.visibility, fact: text(f) })) });
- }
+ // One bucket the writer refuses (an entity or evidence page made private or deleted while its world facts
+ // stay active) is counted and sampled; later buckets still consolidate. Abort, budget and lost-connection
+ // errors stay run-scoped, and an accepted write still publishing keeps ending the phase as before.
+ try {
+ const maintenance = managed && !dryRun ? await maintenancePreflight(engine, b.source_id) : null;
+ const candidates = await engine.listFactsByEntity(b.source_id, b.entity_slug, {
+ activeOnly: true,
+ unconsolidatedOnly: true,
+ visibility: managed ? ['world'] : undefined,
+ limit: 100,
+ });
+ // Takes here are the user's own (holder 'self'): a claim the assistant or
+ // a named third party asserted is never promoted into one.
+ const unconsolidated = candidates.filter(f => (!managed || f.visibility === 'world') && (!f.attributed_to || f.attributed_to === 'user'));
+ if (unconsolidated.length < minPerBucket) {
+ bucketsSkipped += 1;
continue;
}
- if (maintenance) {
- const receipt = await submitMaintenanceConsolidation(engine, maintenance, b.entity_slug, cluster,
- { claim: best.fact, weight: clamp01(avgWeight), source: sources.slice(0, 200), since: sinceISO },
- declareDerivation(derivation.trust, inputs));
- factsConsolidated += Number(receipt.facts_consolidated ?? 0);
- takesWritten += Number(receipt.takes_written ?? 0);
- if (receipt.reason === 'retired_take') clustersSkippedRetired++;
+ // Age gate: oldest must be at least minOldestAgeMs old.
+ const oldest = unconsolidated.reduce((min, f) =>
+ f.valid_from.getTime() < min.valid_from.getTime() ? f : min,
+ );
+ if (Date.now() - oldest.valid_from.getTime() < minOldestAgeMs) {
+ bucketsSkipped += 1;
continue;
}
- // v0.35.4 (D-CDX-4) — semantic upsert. The full dream cycle runs
- // `extract_facts` BEFORE `consolidate`; `extract_facts` hard-deletes
- // and re-inserts page facts via deleteFactsForPage + insertFacts,
- // which clears `consolidated_at` on every fact. Without this lookup,
- // a second cycle run would re-INSERT a duplicate take via
- // `MAX(row_num)+1`, silently poisoning trajectory + scorecard data.
- // Match on (page_id, claim) restricted to the rows this phase authors.
- //
- // `since_date` is NOT part of the identity: it is derived from
- // MIN(valid_from) of the cluster, so it describes the fact rows that
- // happen to exist right now. When extract_facts re-inserts a claim with
- // a fresh `valid_from` (the common case: an LLM extraction that defaults
- // valid_from to now()), keying on since_date makes this lookup miss and
- // the upsert degrades into the duplicate-INSERT path this block exists
- // to prevent.
- //
- // `kind = 'fact' AND holder = 'self'` mirrors the INSERT below, so the
- // lookup can only ever match a take this phase wrote. Without it the
- // widened match reaches human-authored takes that share the claim text
- // and the UPDATE below would overwrite their provenance.
- //
- // Deliberately NOT filtered on `active`: a superseded take still owns
- // this claim. Skipping it would send us down the INSERT path and
- // resurrect a claim the user retired. `ORDER BY id` keeps the choice
- // deterministic if a page already holds more than one matching row
- // (duplicates minted by the pre-fix since_date lookup).
- const existing = await engine.executeRaw<{ id: number; resolved_at: Date | null }>(
- `SELECT id, resolved_at FROM takes
- WHERE page_id = $1 AND claim = $2 AND kind = 'fact' AND holder = 'self'
- ORDER BY id
- LIMIT 1`,
- [pageId, best.fact],
+ bucketsProcessed += 1;
+ const claims = await loadClaimShapes(engine, unconsolidated.map(f => f.id));
+ // #5575 ENG-3: a take's tier is the least trusted fact in its cluster, so
+ // external facts cluster apart from owner facts and their takes are external.
+ const taint = new Map((await readTaintInputs(engine, unconsolidated.map(f => ({ table: 'facts' as const, id: f.id })))).map(i => [Number(i.id), i]));
+ const clusters = [false, true].flatMap(external =>
+ clusterFacts(unconsolidated.filter(f => isExternalTier(taint.get(f.id)!.tier) === external), threshold, claims));
+
+ // Resolve entity_slug → page_id. If page missing in this source, skip.
+ const pageRows = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,
+ [b.source_id, b.entity_slug],
);
+ if (pageRows.length === 0) continue;
+ const pageId = pageRows[0].id;
- // #5575: the take, its source refresh, the consolidation marks and the
- // valid_until writeback are one maintenance transaction at the cluster's
- // derived tier. A re-promotion changes no content column, so the take is
- // lowered explicitly to min(existing, cluster): an external cluster
- // cannot keep an owner take's tier. Edges: take -> every cluster fact.
- // Write gate on a new take: reject skips the cluster; hold records it for review and leaves the facts unconsolidated.
- const takeRow = { page_id: pageId, row_num: nextRowNum, claim: best.fact, kind: 'fact', holder: 'self', weight: clamp01(avgWeight),
- since_date: sinceISO, source: sources.slice(0, 200), active: true };
- const gate = existing.length ? null : await gateNewTake(engine, derivation, takeRow, { sourceId: b.source_id, slug: b.entity_slug },
- gateConfig ??= (await loadImportSanityConfig(engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG);
- if (gate && gate.action !== 'insert') { if (gate.action === 'hold') clustersGateHeld++; else clustersGateRejected++; continue; }
- const written = await derivedMaintenanceTransaction<{ created: boolean; takeId: number | null } | null>(engine, derivation, async tx => {
- let takeId: number;
- let created = false;
- if (existing.length > 0) {
- // Re-promotion of a cluster we already wrote a take for. Refresh
- // the source-aggregation string (new fact rows may carry new
- // source_session values that the prior run didn't see); leave
- // row_num + weight untouched to keep the take's identity stable.
- takeId = existing[0].id;
- // A resolved take is immutable everywhere else (the engines throw
- // TAKE_RESOLVED_IMMUTABLE / TAKE_ALREADY_RESOLVED); this raw UPDATE
- // would bypass that guard. Reuse its id so the facts still consolidate
- // into it, but leave the row untouched.
- if (existing[0].resolved_at === null) {
- await tx.executeRaw(`UPDATE takes SET source = $1, updated_at = now() WHERE id = $2`, [sources.slice(0, 200), takeId]);
+ // Existing row_num max for this page → start appending after it.
+ const rowMaxRows = await engine.executeRaw<{ max: number }>(
+ `SELECT COALESCE(MAX(row_num), 0)::int AS max FROM takes WHERE page_id = $1`,
+ [pageId],
+ );
+ let nextRowNum = (rowMaxRows[0]?.max ?? 0) + 1;
+
+ for (const cluster of clusters) {
+ if (cluster.length < 2) continue;
+ // Take selection: pick the highest-confidence fact's text as the
+ // take claim (v0.31 deterministic). v0.32 will swap to a Sonnet
+ // synthesis pass.
+ const best = cluster.reduce((a, b) => (b.confidence > a.confidence ? b : a));
+ const avgWeight = cluster.reduce((s, f) => s + f.confidence, 0) / cluster.length;
+ const sources = Array.from(new Set(cluster.map(c => c.source_session ?? c.source).filter(Boolean))).join(',');
+ const sinceISO = cluster
+ .map(c => c.valid_from)
+ .reduce((min, d) => (d < min ? d : min))
+ .toISOString()
+ .slice(0, 10);
+ const inputs = cluster.map(f => taint.get(f.id)!);
+ const derivation = { inputs, trust: derivedWriteTrust({ channel: 'derive:consolidate', inputs }) };
+
+ if (dryRun) {
+ // Pretend we did it.
+ takesWritten += 1;
+ factsConsolidated += cluster.length;
+ nextRowNum += 1;
+ if (preview.length < DRY_RUN_CLUSTER_CAP) {
+ const text = (f: FactRow) => (showPrivate || f.visibility === 'world' ? f.fact : null);
+ preview.push({ source_id: b.source_id, entity_slug: b.entity_slug, claim: text(best),
+ members: cluster.map(f => ({ id: f.id, visibility: f.visibility, fact: text(f) })) });
}
- } else {
- const inserted = await tx.addTakesBatch([takeRow]);
- if (inserted < 1) return { result: null, rows: [] };
- const idRows = await tx.executeRaw<{ id: number }>(
- `SELECT id FROM takes WHERE page_id = $1 AND row_num = $2`,
- [pageId, nextRowNum],
- );
- if (idRows.length === 0) return { result: { created: true, takeId: null }, rows: [] };
- takeId = idRows[0].id;
- created = true;
- if (gate) await recordFlaggedRow(tx, gate, { table: 'takes', id: takeId, sourceId: b.source_id });
+ continue;
}
- // Mark all contributing facts consolidated.
- for (const f of cluster) await tx.consolidateFact(f.id, takeId);
+ if (maintenance) {
+ const receipt = await submitMaintenanceConsolidation(engine, maintenance, b.entity_slug, cluster,
+ { claim: best.fact, weight: clamp01(avgWeight), source: sources.slice(0, 200), since: sinceISO },
+ declareDerivation(derivation.trust, inputs));
+ factsConsolidated += Number(receipt.facts_consolidated ?? 0);
+ takesWritten += Number(receipt.takes_written ?? 0);
+ if (receipt.reason === 'retired_take') clustersSkippedRetired++;
+ continue;
+ }
- // v0.35.4 (D-CDX-4 part 2) — chronological valid_until writeback.
- // Sort the cluster by (valid_from ASC, id ASC); walk consecutive
- // pairs; stamp the older fact's valid_until = next_newer.valid_from.
- // The newest fact keeps valid_until = NULL. This makes the facts
- // table a proper bitemporal record without the contradiction probe
- // having to mutate it (preserves auto-supersession.ts:4 invariant —
- // see also R8 test guard).
+ // v0.35.4 (D-CDX-4) — semantic upsert. The full dream cycle runs
+ // `extract_facts` BEFORE `consolidate`; `extract_facts` hard-deletes
+ // and re-inserts page facts via deleteFactsForPage + insertFacts,
+ // which clears `consolidated_at` on every fact. Without this lookup,
+ // a second cycle run would re-INSERT a duplicate take via
+ // `MAX(row_num)+1`, silently poisoning trajectory + scorecard data.
+ // Match on (page_id, claim) restricted to the rows this phase authors.
+ //
+ // `since_date` is NOT part of the identity: it is derived from
+ // MIN(valid_from) of the cluster, so it describes the fact rows that
+ // happen to exist right now. When extract_facts re-inserts a claim with
+ // a fresh `valid_from` (the common case: an LLM extraction that defaults
+ // valid_from to now()), keying on since_date makes this lookup miss and
+ // the upsert degrades into the duplicate-INSERT path this block exists
+ // to prevent.
+ //
+ // `kind = 'fact' AND holder = 'self'` mirrors the INSERT below, so the
+ // lookup can only ever match a take this phase wrote. Without it the
+ // widened match reaches human-authored takes that share the claim text
+ // and the UPDATE below would overwrite their provenance.
//
- // Idempotent: re-running on the same cluster produces the same
- // chronological order and the same valid_until values. No-op if
- // valid_until is already correct.
- const chronological = [...cluster].sort((a, b) => {
- const t = a.valid_from.getTime() - b.valid_from.getTime();
- if (t !== 0) return t;
- return a.id - b.id;
+ // Deliberately NOT filtered on `active`: a superseded take still owns
+ // this claim. Skipping it would send us down the INSERT path and
+ // resurrect a claim the user retired. `ORDER BY id` keeps the choice
+ // deterministic if a page already holds more than one matching row
+ // (duplicates minted by the pre-fix since_date lookup).
+ const existing = await engine.executeRaw<{ id: number; resolved_at: Date | null }>(
+ `SELECT id, resolved_at FROM takes
+ WHERE page_id = $1 AND claim = $2 AND kind = 'fact' AND holder = 'self'
+ ORDER BY id
+ LIMIT 1`,
+ [pageId, best.fact],
+ );
+
+ // #5575: the take, its source refresh, the consolidation marks and the
+ // valid_until writeback are one maintenance transaction at the cluster's
+ // derived tier. A re-promotion changes no content column, so the take is
+ // lowered explicitly to min(existing, cluster): an external cluster
+ // cannot keep an owner take's tier. Edges: take -> every cluster fact.
+ // Write gate on a new take: reject skips the cluster; hold records it for review and leaves the facts unconsolidated.
+ const takeRow = { page_id: pageId, row_num: nextRowNum, claim: best.fact, kind: 'fact', holder: 'self', weight: clamp01(avgWeight),
+ since_date: sinceISO, source: sources.slice(0, 200), active: true };
+ const gate = existing.length ? null : await gateNewTake(engine, derivation, takeRow, { sourceId: b.source_id, slug: b.entity_slug },
+ gateConfig ??= (await loadImportSanityConfig(engine)).writeGate ?? DEFAULT_WRITE_GATE_CONFIG);
+ if (gate && gate.action !== 'insert') { if (gate.action === 'hold') clustersGateHeld++; else clustersGateRejected++; continue; }
+ const written = await derivedMaintenanceTransaction<{ created: boolean; takeId: number | null } | null>(engine, derivation, async tx => {
+ let takeId: number;
+ let created = false;
+ if (existing.length > 0) {
+ // Re-promotion of a cluster we already wrote a take for. Refresh
+ // the source-aggregation string (new fact rows may carry new
+ // source_session values that the prior run didn't see); leave
+ // row_num + weight untouched to keep the take's identity stable.
+ takeId = existing[0].id;
+ // A resolved take is immutable everywhere else (the engines throw
+ // TAKE_RESOLVED_IMMUTABLE / TAKE_ALREADY_RESOLVED); this raw UPDATE
+ // would bypass that guard. Reuse its id so the facts still consolidate
+ // into it, but leave the row untouched.
+ if (existing[0].resolved_at === null) {
+ await tx.executeRaw(`UPDATE takes SET source = $1, updated_at = now() WHERE id = $2`, [sources.slice(0, 200), takeId]);
+ }
+ } else {
+ const inserted = await tx.addTakesBatch([takeRow]);
+ if (inserted < 1) return { result: null, rows: [] };
+ const idRows = await tx.executeRaw<{ id: number }>(
+ `SELECT id FROM takes WHERE page_id = $1 AND row_num = $2`,
+ [pageId, nextRowNum],
+ );
+ if (idRows.length === 0) return { result: { created: true, takeId: null }, rows: [] };
+ takeId = idRows[0].id;
+ created = true;
+ if (gate) await recordFlaggedRow(tx, gate, { table: 'takes', id: takeId, sourceId: b.source_id });
+ }
+
+ // Mark all contributing facts consolidated.
+ for (const f of cluster) await tx.consolidateFact(f.id, takeId);
+
+ await writeValidUntilChain(tx, cluster);
+ return { result: { created, takeId }, rows: [{ table: 'takes' as const, id: Number(takeId), sourceId: b.source_id }] };
});
- for (let i = 0; i < chronological.length - 1; i++) {
- const older = chronological[i];
- const newer = chronological[i + 1];
- await tx.executeRaw(
- // Only UPDATE when the new value would actually change. Avoids
- // touching updated_at on no-op rewrites and keeps idempotency
- // observable in the DB (zero affected rows on stable re-run).
- `UPDATE facts
- SET valid_until = $1
- WHERE id = $2
- AND (valid_until IS DISTINCT FROM $1)`,
- [newer.valid_from, older.id],
- );
- }
- return { result: { created, takeId }, rows: [{ table: 'takes' as const, id: Number(takeId), sourceId: b.source_id }] };
- });
- if (written?.created) nextRowNum += 1;
- if (!written?.takeId) continue;
- if (written.created) takesWritten += 1;
- factsConsolidated += cluster.length;
+ if (written?.created) nextRowNum += 1;
+ if (!written?.takeId) continue;
+ if (written.created) takesWritten += 1;
+ factsConsolidated += cluster.length;
+ }
+ run.succeed();
+ } catch (error) {
+ if (classifyItemFailure(error).scope === 'pending') throw error;
+ const failure = run.fail(`${b.source_id}:${b.entity_slug}`, error);
+ bucketsFailed += 1;
+ if (bucketFailures.length < BUCKET_FAILURE_SAMPLES) {
+ bucketFailures.push({ source_id: b.source_id, entity_slug: b.entity_slug, code: failure.code, message: failure.message.slice(0, 300),
+ fix: `gbrain dream --phase consolidate --source ${b.source_id}` });
+ }
}
}
return {
phase: 'consolidate',
- status: factsConsolidated === 0 && clustersSkippedRetired > 0 ? 'skipped' : 'ok',
+ status: bucketsFailed > 0 ? 'warn' : factsConsolidated === 0 && clustersSkippedRetired > 0 ? 'skipped' : 'ok',
duration_ms: 0,
summary: dryRun
? `(dry-run) would promote ${factsConsolidated} facts into ${takesWritten} takes across ${bucketsProcessed} buckets`
: `promoted ${factsConsolidated} facts into ${takesWritten} takes across ${bucketsProcessed} buckets` +
(clustersSkippedRetired ? `; skipped ${clustersSkippedRetired} clusters with retired takes` : '') +
(clustersGateHeld ? `; held ${clustersGateHeld} takes for write-gate review` : '') +
- (clustersGateRejected ? `; write gate rejected ${clustersGateRejected} takes` : ''),
+ (clustersGateRejected ? `; write gate rejected ${clustersGateRejected} takes` : '') +
+ (bucketsFailed ? `; ${bucketsFailed} bucket(s) failed (details.bucket_failures)` : ''),
details: {
dryRun,
cluster_threshold: threshold,
@@ -392,6 +420,8 @@ export async function runPhaseConsolidate(
clusters_skipped_retired: clustersSkippedRetired,
clusters_gate_held: clustersGateHeld,
clusters_gate_rejected: clustersGateRejected,
+ buckets_failed: bucketsFailed,
+ bucket_failures: bucketFailures,
...(factsConsolidated === 0 && clustersSkippedRetired > 0 ? { reason: 'retired_take' } : {}),
},
};
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index bb68dd579b..e4d0f7f165 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -27,6 +27,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';
/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */
export const ISOLATE_SITES = {
+ 'consolidate.buckets': 'A-22',
'extract_facts.expire_deleted': 'A-21',
'maintain.cycle_sources': 'A-41',
} as const satisfies Record<string, string>;
diff --git a/test/pathological/a22-consolidate-buckets.test.ts b/test/pathological/a22-consolidate-buckets.test.ts
new file mode 100644
index 0000000000..ad195da3d7
--- /dev/null
+++ b/test/pathological/a22-consolidate-buckets.test.ts
@@ -0,0 +1,94 @@
+/**
+ * GBRA-130 A-22: consolidate walks (source, entity) buckets with no per-bucket
+ * isolation. On a managed brain an entity page made private while its
+ * world-visible facts stay active makes the consolidation submit refuse with
+ * page_not_found on every run, and every bucket after it never consolidated.
+ * Now that bucket is counted in `buckets_failed` with a typed sample and the
+ * phase warns while later buckets consolidate; run-scoped errors still stop it.
+ *
+ * Authoring gate: (1) protects per-bucket isolation in runPhaseConsolidate;
+ * (2) fails when the bucket loop loses its catch or swallows a lost
+ * connection; (3) test/managed-maintenance.test.ts covers healthy and private
+ * facts only, never a private entity page with world facts; (4) no seam: the
+ * bad state is real page and fact rows.
+ */
+import { describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { runPhaseConsolidate } from '../../src/core/cycle/phases/consolidate.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+import { managedSource, type ManagedSource } from './managed-fixture.ts';
+
+const WORDS = ['alpha', 'beta', 'gamma'];
+const PAGE = (slug: string, privacy = '') => `---\ntitle: ${slug}\ntype: note\n${privacy}---\nExample evidence for ${slug}.`;
+
+async function seedFacts(engine: BrainEngine, sourceId: string, slug: string): Promise<void> {
+ const [{ dims }] = await engine.executeRaw<{ dims: number }>(`SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid='facts'::regclass AND attname='embedding'`);
+ const vector = `[${[1, ...Array(Number(dims) - 1).fill(0)].join(',')}]`;
+ for (let i = 0; i < 3; i++) {
+ await engine.executeRaw(`INSERT INTO facts(source_id,entity_slug,fact,kind,source,visibility,confidence,valid_from,embedding,embedding_model,embedded_text_hash)
+ VALUES($1,$2,$3,'fact','test','world',$4,$5::timestamptz,$6::vector,'openai:text-embedding-3-large',md5($3))`,
+ [sourceId, slug, `Example claim ${WORDS[i]} on ${slug}`, 0.9 - i / 10, `2026-01-0${i + 1}T00:00:00Z`, vector]);
+ }
+}
+
+/** One entity page made private while its world facts stay active (the poison bucket), and one healthy bucket. */
+async function seed(s: ManagedSource, privateSlugs = ['people/alice-example'], healthy = ['people/bob-example']): Promise<void> {
+ for (const slug of privateSlugs) { await s.put(slug, PAGE(slug, 'visibility: private\n')); await seedFacts(s.engine, s.sourceId, slug); }
+ for (const slug of healthy) { await s.put(slug, PAGE(slug)); await seedFacts(s.engine, s.sourceId, slug); }
+}
+
+const consolidated = async (engine: BrainEngine, sourceId: string, slug: string) => Number((await engine.executeRaw<{ n: number }>(
+ 'SELECT count(*)::int AS n FROM facts WHERE source_id=$1 AND entity_slug=$2 AND consolidated_at IS NOT NULL', [sourceId, slug]))[0]!.n);
+
+describe('A-22 consolidate isolates one bucket whose consolidation is refused', () => {
+ for (const { backend, databaseUrl } of pathologicalArms()) {
+ test(`[${backend}] a private entity page with world facts fails its bucket and later buckets still consolidate`, async () => {
+ await managedSource(databaseUrl, s => seed(s), async ({ engine, sourceId }) => {
+ const before = await snapshotItems(engine, sourceId);
+ const result = await expectUnitNotAborted(() => runPhaseConsolidate(engine, { sourceId, minOldestAgeMs: 0 }));
+ expect(result.status).toBe('warn');
+ expect(result.details.buckets_failed).toBe(1);
+ const [sample] = result.details.bucket_failures as Array<{ source_id: string; entity_slug: string; code: string; fix: string }>;
+ expect(sample?.source_id).toBe(sourceId);
+ expectItemFailure({ key: sample?.entity_slug, code: sample?.code, fix: sample?.fix },
+ { key: 'people/alice-example', code: 'page_not_found', fix: new RegExp(`^gbrain dream --phase consolidate --source ${sourceId}$`) });
+ expect(await consolidated(engine, sourceId, 'people/alice-example')).toBe(0);
+ expect(await consolidated(engine, sourceId, 'people/bob-example')).toBe(3);
+ expect(result.details.takes_written).toBe(1);
+ expectOthersUnchanged(before, await snapshotItems(engine, sourceId), { expectProgress: ['people/bob-example'], progressFields: ['content_hash'] });
+ });
+ }, 120_000);
+
+ test(`[${backend}] once the entity page is public again its bucket consolidates`, async () => {
+ await managedSource(databaseUrl, s => seed(s), async ({ engine, sourceId, put }) => {
+ expect((await runPhaseConsolidate(engine, { sourceId, minOldestAgeMs: 0 })).details.buckets_failed).toBe(1);
+ await put('people/alice-example', PAGE('people/alice-example'));
+ const result = await runPhaseConsolidate(engine, { sourceId, minOldestAgeMs: 0 });
+ expect(result.status).toBe('ok');
+ expect(result.details.buckets_failed).toBe(0);
+ expect(await consolidated(engine, sourceId, 'people/alice-example')).toBe(3);
+ });
+ }, 120_000);
+
+ test(`[${backend}] most buckets refused trips the breaker instead of failing each one`, async () => {
+ const slugs = ['a', 'b', 'c', 'd', 'e'].map(x => `people/${x}-example`);
+ await managedSource(databaseUrl, s => seed(s, slugs, []), async ({ engine, sourceId }) => {
+ await expect(runPhaseConsolidate(engine, { sourceId, minOldestAgeMs: 0 })).rejects.toMatchObject({ code: 'item_failures_systemic' });
+ });
+ }, 120_000);
+
+ for (const { name, error } of runScopedErrors()) {
+ test(`[${backend}] a run-scoped error inside a bucket still stops consolidate (${name})`, async () => {
+ await managedSource(databaseUrl, s => seed(s), async ({ engine, sourceId }) => {
+ const injected = error();
+ const list = engine.listFactsByEntity.bind(engine);
+ engine.listFactsByEntity = (async () => { throw injected; }) as BrainEngine['listFactsByEntity'];
+ try {
+ await expect(runPhaseConsolidate(engine, { sourceId, minOldestAgeMs: 0 })).rejects.toBe(injected);
+ } finally { engine.listFactsByEntity = list; }
+ expect(await consolidated(engine, sourceId, 'people/bob-example')).toBe(0);
+ });
+ }, 120_000);
+ }
+ }
+});
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index 98c91aef66..d59a6d4e60 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -18,6 +18,9 @@ export interface SiteCases {
}
export const CATALOGUE: Record<IsolateSite, SiteCases> = {
+ 'consolidate.buckets': { file: 'test/pathological/a22-consolidate-buckets.test.ts',
+ item: 'a private entity page with world facts fails its bucket and later buckets still consolidate',
+ run: 'a run-scoped error inside a bucket still stops consolidate' },
'extract_facts.expire_deleted': { file: 'test/pathological/a21-facts-expire-deleted.test.ts',
item: 'a refused deleted-page expiry is reported and the other pages still expire and reconcile',
run: 'a run-scoped error during a deleted-page expiry still stops extract_facts' },
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 260061c706..0346f75723 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -219,6 +219,7 @@ test/page-purge-batch-sweep-6884.test.ts
test/page-purge-journal-timeout-6511.test.ts
test/page-state-engine.test.ts
test/pathological/a21-facts-expire-deleted.test.ts
+test/pathological/a22-consolidate-buckets.test.ts
test/pathological/a41-maintain-sources.test.ts
test/persistence-background-pause.test.ts
test/persistence-bounded-read-session.test.ts