Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(dream): defer pending and contended pattern/drift publication (#6059)

time-attack078263f017ce
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index dc03b7b52d..7f6966dc81 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -83,6 +83,7 @@ test/cycle-lock-release-diagnostic.serial.test.ts R1 R1: mutates process.env (GB
test/cycle-lock-steal.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_CYCLE_LOCK_REFRESH_MS)
test/cycle-patterns-completed-outcome.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
test/cycle-patterns-evidence-gate.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
+test/cycle-publication-deferral.serial.test.ts R2 R2: mock.module replaces paid child and maintenance publication boundaries for every file in the process
test/cycle-pglite-lock-ordering.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/cycle-start-recovery-throw.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts) replaces modules for every file in the process
test/cycle/cycle-sync-uncommitted-warn.serial.test.ts R2 R2: mock.module(../../src/commands/sync.ts) replaces modules for every file in the process
diff --git a/src/core/cycle/drift.ts b/src/core/cycle/drift.ts
index e4db929f11..7cff261fff 100644
--- a/src/core/cycle/drift.ts
+++ b/src/core/cycle/drift.ts
@@ -31,6 +31,7 @@ import type { DreamPhaseResult } from './auto-think.ts';
import { maintenancePreflight, publishMaintenancePage } from '../persistence/prepared-maintenance.ts';
import { serializeMarkdown } from '../markdown.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { maintenancePublicationDeferral } from './publication-deferral.ts';
export interface DriftPhaseOpts {
brainDir?: string;
@@ -362,6 +363,7 @@ export async function runPhaseDrift(
const driftedCount = judged.filter(j => j.verdict.drifted).length;
let reportSlug: string | undefined;
+ let publicationDeferred: 'pending' | 'contention' | null = null;
if (judged.length > 0) {
reportSlug = `reports/drift-${cycleDate}`;
// Report-only v1: the report page is the ONLY write this phase makes.
@@ -370,8 +372,14 @@ export async function runPhaseDrift(
// upsert the same slug).
if (maintenance) {
const snapshot = await engine.readPageSnapshot(reportSlug, { sourceId: 'default' });
- await publishMaintenancePage(engine, maintenance, reportSlug, serializeMarkdown({ report_type: 'drift' }, buildReportBody(judged, config, modelId), '',
- { type: 'note', title: `Drift report ${cycleDate}`, tags: [] }), { expectedRevision: snapshot?.revision ?? null, file: false });
+ try {
+ await publishMaintenancePage(engine, maintenance, reportSlug, serializeMarkdown({ report_type: 'drift' }, buildReportBody(judged, config, modelId), '',
+ { type: 'note', title: `Drift report ${cycleDate}`, tags: [] }), { expectedRevision: snapshot?.revision ?? null, file: false });
+ } catch (error) {
+ publicationDeferred = maintenancePublicationDeferral(error);
+ if (!publicationDeferred) throw error;
+ reportSlug = undefined;
+ }
} else {
await maintenanceTransaction(engine, tx => tx.putPage(reportSlug!, {
type: 'note',
@@ -385,6 +393,7 @@ export async function runPhaseDrift(
const detail =
`judged ${judged.length}/${candidates.length} candidates: ${driftedCount} drifted` +
(reportSlug ? ` → ${reportSlug}` : '') +
+ (publicationDeferred ? ` (publication deferred: ${publicationDeferred === 'pending' ? 'accepted report still publishing' : 'admission contended; retry next cycle'})` : '') +
(budgetExhausted ? ' (budget exhausted)' : '') +
(failed > 0 ? ` (${failed} judge failure(s))` : '') +
`. Cumulative cost: $${meter.totalSpent.toFixed(4)} / $${config.budgetUsd.toFixed(2)}` +
@@ -393,7 +402,7 @@ export async function runPhaseDrift(
return {
name: 'drift',
status: judged.length > 0
- ? (budgetExhausted || failed > 0 ? 'partial' : 'complete')
+ ? (budgetExhausted || failed > 0 || publicationDeferred ? 'partial' : 'complete')
// Zero judged: budget capped before any judge ran → partial (capped,
// not broken); otherwise every judge call failed → failed.
: (budgetExhausted ? 'partial' : 'failed'),
@@ -403,6 +412,8 @@ export async function runPhaseDrift(
judged: judged.length,
drifted: driftedCount,
failed,
+ reports_written: reportSlug ? 1 : 0,
+ publish_deferred: publicationDeferred ? 1 : 0,
},
duration_ms: Date.now() - start,
};
diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.ts
index 6d73614f17..f307619e06 100644
--- a/src/core/cycle/patterns.ts
+++ b/src/core/cycle/patterns.ts
@@ -48,6 +48,7 @@ import { normalizeModelId } from '../model-id.ts';
import { throwIfAborted } from '../abort-check.ts';
import { resolveCycleDate } from './cycle-date.ts';
import { dreamBreakerRefusal, loadDreamBreaker } from './dream-breaker.ts';
+import { maintenancePublicationDeferral } from './publication-deferral.ts';
export interface PatternsPhaseOpts {
brainDir: string;
@@ -361,24 +362,19 @@ export async function runPhasePatterns(
throwIfAborted(opts.signal, '[dream] patterns output');
const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);
- await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), opts.signal);
- const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, writtenRefs)
+ const deferredSlugs = await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), opts.signal);
+ const finalizedRefs = writtenRefs.filter(ref => !deferredSlugs.has(ref.slug));
+ const reverseWriteCount = maintenance ? (finalizedRefs.length ? await verifyMaintenanceOutputs(engine, maintenance, finalizedRefs) : 0)
: await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);
- const details = {
- reflections_considered: reflections.length,
- patterns_written: writtenRefs.length,
- reverse_write_count: reverseWriteCount,
- child_outcome: outcome,
- job_id: job.id,
- };
+ const details = patternOutputDetails(reflections.length, finalizedRefs.length, reverseWriteCount, outcome, job.id, deferredSlugs.size);
// #2782: the phase status must reflect the child outcome. Pre-fix this
// returned status:ok even when the subagent timed out (e.g. no
// subagent-capable worker slot free for the whole wait window) and zero
// pattern pages were written — a silent no-op for days.
if (outcome !== 'completed') {
- if (writtenRefs.length === 0) {
+ if (finalizedRefs.length === 0) {
return {
phase: 'patterns',
status: 'fail',
@@ -400,11 +396,16 @@ export async function runPhasePatterns(
phase: 'patterns',
status: 'warn',
duration_ms: 0,
- summary: `${writtenRefs.length} pattern page(s) written but subagent job ${job.id} ended '${outcome}'`,
+ summary: `${finalizedRefs.length} pattern page(s) written but subagent job ${job.id} ended '${outcome}'`,
details,
};
}
+ if (deferredSlugs.size) {
+ return { phase: 'patterns', status: 'warn', duration_ms: 0,
+ summary: `${finalizedRefs.length} pattern page(s) finalized; ${deferredSlugs.size} publication(s) deferred (writer busy); retry next cycle`, details };
+ }
+
// #4879: stamp the EVIDENCE watermark (not now()) only on a completed
// child — fail/warn/timeout above must retry next tick. A reflection
// edited between gather and here has updated_at > stamp, so the next run
@@ -441,6 +442,12 @@ export async function runPhasePatterns(
// ── Config ────────────────────────────────────────────────────────────
+function patternOutputDetails(reflections: number, finalized: number, reverseWrites: number,
+ outcome: MinionJobStatus | 'timeout', jobId: number, deferred: number) {
+ return { reflections_considered: reflections, patterns_written: finalized,
+ reverse_write_count: reverseWrites, child_outcome: outcome, job_id: jobId, publish_deferred: deferred };
+}
+
interface PatternsConfig {
enabled: boolean;
lookbackDays: number;
@@ -634,14 +641,24 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag
* stamped raw-trace exempt (doctor raw_provenance) on every run that writes it.
*/
async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null,
- refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal?: AbortSignal): Promise<void> {
+ refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal?: AbortSignal): Promise<Set<string>> {
const reason = `derived from reflections under ${sourceSlugPrefix}/; raw traces live on the cited reflection pages`;
// A pattern earns a seat only while its reflections share one, so a pattern without one drops a seat an earlier run stamped.
- if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, seat: seat ?? null })), cycleDate, signal);
+ const deferred = new Set<string>();
+ if (!maintenance) {
+ await stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, seat: seat ?? null })), cycleDate, signal);
+ return deferred;
+ }
for (const ref of refs) {
throwIfAborted(signal, '[dream] patterns provenance');
- await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat ?? null);
+ try {
+ await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat ?? null);
+ } catch (error) {
+ if (!maintenancePublicationDeferral(error)) throw error;
+ deferred.add(ref.slug);
+ }
}
+ return deferred;
}
// ── Provenance via put_page tool execution rows ─────────────────────
diff --git a/src/core/cycle/publication-deferral.ts b/src/core/cycle/publication-deferral.ts
new file mode 100644
index 0000000000..82dc20c772
--- /dev/null
+++ b/src/core/cycle/publication-deferral.ts
@@ -0,0 +1,13 @@
+import { OperationError } from '../ops/contract.ts';
+import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';
+
+/** Publication waits and confirmed admission rollback are not dream failures.
+ * Never infer deferral from a message, a generic storage error, or a terminal
+ * receipt: those must still reach the phase's normal failure path.
+ */
+export function maintenancePublicationDeferral(error: unknown): 'pending' | 'contention' | null {
+ if (acceptedPendingReceipt(error)) return 'pending';
+ if (error instanceof OperationError && error.code === 'storage_error' &&
+ error.detail === 'database_contention' && !error.writeRequest) return 'contention';
+ return null;
+}
diff --git a/test/cycle-publication-deferral.serial.test.ts b/test/cycle-publication-deferral.serial.test.ts
new file mode 100644
index 0000000000..c584ddf685
--- /dev/null
+++ b/test/cycle-publication-deferral.serial.test.ts
@@ -0,0 +1,124 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { retryWriteAdmission } from '../src/core/persistence/admission-retry.ts';
+
+// Only the paid child and maintenance boundary are replaced. Phase selection,
+// evidence, jobs, watermark and drift report construction use the real engine.
+let publishError: unknown;
+let stampCalls = 0;
+let publishCalls = 0;
+let verified = 0;
+let childStatus = 'completed';
+const maintenance = { writer: { sourceId: 'default' } };
+mock.module('../src/core/ai/gateway.ts', () => ({ probeChatModel: () => ({ ok: true }) }));
+mock.module('../src/core/cycle/synthesize-concepts.ts', () => ({ resolveSynthMaxOutputTokens: () => 4096 }));
+mock.module('../src/core/persistence/prepared-maintenance.ts', () => ({
+ maintenancePreflight: async () => maintenance,
+ stampMaintenancePage: async () => { stampCalls++; if (publishError) throw publishError; },
+ publishMaintenancePage: async () => { publishCalls++; if (publishError) throw publishError; return {}; },
+ verifyMaintenanceOutputs: async () => { verified++; return 1; },
+}));
+mock.module('../src/core/cycle/synthesize.ts', () => ({
+ loadAllowedSlugPrefixes: async () => ['wiki/personal/patterns/*'],
+ loadOutputRoot: async () => 'wiki',
+ runSubagentsInline: async () => undefined,
+}));
+mock.module('../src/core/minions/wait-for-completion.ts', () => ({
+ TimeoutError: class TimeoutError extends Error {},
+ waitForCompletionRenewing: async (_queue: unknown, jobId: number, opts?: { renew?: () => Promise<void> }) => {
+ await opts?.renew?.();
+ await engine.executeRaw(`INSERT INTO subagent_tool_executions (job_id, message_idx, tool_use_id, tool_name, input, output, status)
+ VALUES ($1, 0, 'fixture-tool', 'brain_put_page', '{"slug":"wiki/personal/patterns/example"}'::jsonb, '{}'::jsonb, 'complete')`, [jobId]);
+ return { id: jobId, status: childStatus };
+ },
+}));
+const { runPhasePatterns } = await import('../src/core/cycle/patterns.ts');
+const { runPhaseDrift } = await import('../src/core/cycle/drift.ts');
+let engine: PGLiteEngine;
+let schemaVersion: string;
+const scratch = mkdtempSync(join(tmpdir(), 'gbrain-publication-deferral-'));
+const STAMP_KEY = 'dream.patterns.last_evidence_ts';
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ schemaVersion = (await engine.getConfig('version'))!;
+}, 60_000);
+afterAll(async () => { await engine.disconnect(); rmSync(scratch, { recursive: true, force: true }); });
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('version', schemaVersion);
+ publishError = undefined; stampCalls = 0; publishCalls = 0; verified = 0; childStatus = 'completed';
+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');
+ await engine.setConfig('models.drift', 'anthropic:claude-sonnet-4-6');
+ for (let i = 0; i < 3; i++) await engine.putPage(`wiki/personal/reflections/example-${i}`, {
+ type: 'note', title: `Reflection ${i}`, compiled_truth: 'A recurring synthetic theme.',
+ });
+ const page = await engine.putPage('people/alice-example', { type: 'person', title: 'Alice Example', compiled_truth: 'Example person.' });
+ await engine.addTakesBatch([{ page_id: page.id, row_num: 1, claim: 'Careful operator', kind: 'take', holder: 'brain', weight: 0.6 }]);
+ await engine.addTimelineEntriesBatch([{ slug: page.slug, date: '2030-01-15', source: 'meeting', summary: 'Changed roles' }]);
+});
+async function contention(): Promise<unknown> {
+ try { await retryWriteAdmission('00000000-0000-4000-a000-000000000001', async () => { throw Object.assign(new Error('synthetic SQL lock'), { code: '55P03' }); }, 0); }
+ catch (error) { return error; }
+ throw new Error('Admission must fail');
+}
+function pending(terminal = false): OperationError {
+ const error = new OperationError('write_pending', 'Accepted publication is pending.', 'Read its receipt.');
+ error.writeRequest = { request_id: '00000000-0000-4000-a000-000000000002',
+ state: terminal ? 'failed' : 'queued', retry_after_ms: terminal ? null : 1000 };
+ return error;
+}
+const runDrift = () => runPhaseDrift(engine, { dryRun: false, forceEnabled: true, cycleDate: '2030-01-20',
+ auditPath: join(scratch, 'drift.jsonl'), judge: async () => ({ drifted: true, confidence: 0.9, reasoning: 'Changed evidence.' }) });
+
+describe('managed dream publication deferral (#6052)', () => {
+ for (const fault of ['contention', 'pending'] as const) {
+ test(`patterns defers ${fault} without advancing evidence or verifying unfinished output`, async () => {
+ publishError = fault === 'contention' ? await contention() : pending();
+ const result = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });
+ expect(result.error).toBeUndefined();
+ expect(result.status).toBe('warn');
+ expect(result.details.publish_deferred).toBe(1);
+ expect(result.details.patterns_written).toBe(0);
+ expect(result.details.child_outcome).toBe('completed');
+ expect(result.error).toBeUndefined();
+ expect(verified).toBe(0);
+ expect(await engine.getConfig(STAMP_KEY)).toBeNull();
+ publishError = undefined;
+ const resumed = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });
+ expect(resumed.status).toBe('ok');
+ expect(await engine.getConfig(STAMP_KEY)).not.toBeNull();
+ });
+ test(`drift defers ${fault} without claiming a published report`, async () => {
+ publishError = fault === 'contention' ? await contention() : pending();
+ const result = await runDrift();
+ expect(result.status).toBe('partial');
+ expect(result.totals?.publish_deferred).toBe(1);
+ expect(result.totals?.reports_written).toBe(0);
+ expect(result.totals?.judged).toBe(1);
+ expect(result.detail).toContain('publication deferred');
+ expect(result.detail).not.toContain(' → reports/');
+ expect(await engine.getPage('reports/drift-2030-01-20')).toBeNull();
+ });
+ }
+ test('a failed patterns child remains a failure even if its partial output is pending', async () => {
+ childStatus = 'failed'; publishError = pending();
+ const result = await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true });
+ expect(result.status).toBe('fail');
+ expect(result.error?.code).toBe('PATTERNS_CHILD_FAILED');
+ expect(await engine.getConfig(STAMP_KEY)).toBeNull();
+ });
+ for (const error of [new OperationError('storage_error', 'A real storage failure.', ''),
+ new OperationError('permission_denied', 'Revoked writer.', ''), pending(true),
+ new OperationError('write_pending', 'No accepted receipt.', '')]) {
+ test(`does not defer ${error.message}`, async () => {
+ publishError = error;
+ expect((await runPhasePatterns(engine, { brainDir: scratch, dryRun: false, once: true })).status).toBe('fail');
+ await expect(runDrift()).rejects.toBe(error);
+ });
+ }
+});