Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(wave19): review fixes: schema-behind refusal on group admission (put_pages, sync groups); ghost-pages records only per-item refusals; schema_missing never parses RAISE text; structural assertions instead of wall-clock ratios

garrytan68df30c94d0d
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index c6758b0a91..b6f6ce7aa4 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -380,6 +380,8 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writ
}
const fresh = items.filter(item => !priors.has(item.requestId));
if (fresh.length) {
+ const schemaRefusal = await schemaAdmissionRefusal(tx);
+ if (schemaRefusal) throw schemaRefusal;
const bytes = fresh.reduce((sum, item) => sum + item.bytes, 0), terminalBytes = fresh.reduce((sum, item) => sum + item.terminalBytes, 0);
for (const row of counters) {
const brain = row.key === 'brain', scope = brain ? 'brain' : 'principal';
diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.ts
index 7289a54438..12b0935115 100644
--- a/src/core/persistence/publication-failure.ts
+++ b/src/core/persistence/publication-failure.ts
@@ -100,14 +100,15 @@ function publicationReason(sqlstate: string, raiser: string | undefined, message
/**
* #6904: a relation or column the write path needs is missing (42P01 / 42703, `schema_missing` in `pg-access-classify.ts`):
- * the brain schema is behind this build or lost a table, never a gbrain defect. Names the missing identifier from the error.
+ * the brain schema is behind this build or lost a table, never a gbrain defect. Names the missing identifier from the server's
+ * own parser error; a PL/pgSQL RAISE carries caller text, so it is never parsed (#5974 fixed identifiers).
*/
const SCHEMA_MISSING_SQLSTATES = new Set(['42P01', '42703']);
const MISSING_NAME = /(column|relation)\s+"?([A-Za-z_][A-Za-z0-9_.]*)"?(?:\s+of relation\s+"?([A-Za-z_][A-Za-z0-9_.]*)"?)?\s+does not exist/i;
function schemaMissing(sqlstate: string, message: string): PublicationFailure {
const match = MISSING_NAME.exec(message);
const missing = match ? ident(match[3] ? `${match[3]}.${match[2]}` : match[2]) : undefined;
- const what = match ? `${match[1]!.toLowerCase()} ${missing ?? 'unnamed'}` : 'a relation or column';
+ const what = match ? `${match[1]!.toLowerCase()} ${missing ?? 'unnamed'}` : 'relation or column';
return { code: 'storage_error', message: `Publication failed: the database has no ${what} (${sqlstate}), which this gbrain build needs, so the brain schema is missing a migration or a table. Nothing was committed.`,
detail: { origin: 'database', sqlstate, reason: 'schema_missing', ...(missing ? { missing } : {}) } };
}
@@ -118,7 +119,7 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {
const e = error as Record<string, unknown>;
const sqlstate = typeof e.code === 'string' && /^[0-9A-Z]{5}$/.test(e.code) ? e.code : null;
if (sqlstate && SCHEMA_MISSING_SQLSTATES.has(sqlstate) && classifyPgAccessError(error).reason === 'schema_missing') {
- return schemaMissing(sqlstate, typeof e.message === 'string' ? e.message : '');
+ return schemaMissing(sqlstate, typeof e.message === 'string' && e.routine !== 'exec_stmt_raise' ? e.message : '');
}
if (sqlstate !== 'P0001' && sqlstate !== GRADUATION_SQLSTATE) return null;
const where = typeof e.where === 'string' ? e.where : '';
diff --git a/src/core/repair/ghost-pages.ts b/src/core/repair/ghost-pages.ts
index aa60522fa5..9b3345f068 100644
--- a/src/core/repair/ghost-pages.ts
+++ b/src/core/repair/ghost-pages.ts
@@ -41,7 +41,6 @@ import type { GBrainConfig } from '../config.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import type { WriteRequest } from '../persistence/model.ts';
import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
-import { CODES } from '../error-registry.ts';
import { GHOST_RETIREMENT_INTENT } from '../shared-skills/knowledge-guard.ts';
import { readFix } from '../ops/op-fix.ts';
import { authorizeWrite } from '../persistence/authority.ts';
@@ -52,7 +51,7 @@ import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/pr
import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
import { MASS_RECONCILE_MIN_PAGES, MASS_RECONCILE_RATIO, massReconcileAllowed } from '../sync-reconcile.ts';
import { ghostPageNow, scanGhostSource, type GhostOwner, type GhostPage, type GhostSourceScan } from '../ghost-pages.ts';
-import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+import { afterCursor, REPAIR_ITEM_FAILURE_CODES, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
export const GHOST_PAGES_INTENT = GHOST_RETIREMENT_INTENT;
/** Ghosts one preview lists; a larger set is applied in rounds (preview, apply, preview again). */
@@ -198,7 +197,7 @@ export const ghostPagesRepair: RepairHandler = {
try {
outcome = await retireGhost(ctx, ghost, owner, () => repairRequestId(ctx, 'ghost-pages', ghost, ghost.revision));
} catch (error) {
- if (!(error instanceof OperationError) || (CODES as Record<string, { class: string } | undefined>)[error.code]?.class !== 'caller') throw error;
+ if (!(error instanceof OperationError) || !GHOST_ITEM_REFUSALS.has(error.code)) throw error;
outcome = { applied: false, outcome: 'refused', reason: error.code, detail: { message: error.message } };
}
if (last) await clearApprovedSet(ctx.engine, { command: 'ghost-pages', hash });
@@ -209,6 +208,9 @@ export const ghostPagesRepair: RepairHandler = {
},
};
+/** Refusals about one ghost only; a run-wide refusal (migrations_pending, worktree_dirty, writer transfer) stops the run and keeps the approval. */
+const GHOST_ITEM_REFUSALS: ReadonlySet<string> = new Set([...REPAIR_ITEM_FAILURE_CODES, 'skill_bundle_required']);
+
const restored = (ghost: GhostPage): RepairItemOutcome => ({ applied: false, outcome: 'file_restored', detail: { path: ghost.path },
reason: `The canonical file ${ghost.path} exists again, so ${ghost.slug} was kept; run ${ghostPreviewCommand(ghost.source_id)} again for a new preview.` });
const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
diff --git a/test/admission-schema-behind-6904.test.ts b/test/admission-schema-behind-6904.test.ts
index 89493112de..ffb92951c4 100644
--- a/test/admission-schema-behind-6904.test.ts
+++ b/test/admission-schema-behind-6904.test.ts
@@ -20,6 +20,7 @@ import { OperationError } from '../src/core/ops/contract.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { submitPageBatch } from '../src/core/persistence/page-batch.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { LATEST_SCHEMA_VERSION } from '../src/core/schema-migrations/latest.generated.ts';
import { acquireMigrationOrchestrationLock } from '../src/core/migration-orchestration-lock.ts';
@@ -96,6 +97,25 @@ describe('#6904 writes refused while the schema is behind', () => {
} finally { await atHead(); }
}), 60_000);
+ test('put_pages (group admission) refuses the same way and admits nothing; a replayed batch still reconciles', () => inHome(async () => {
+ await atHead();
+ const batch = (requestId: string, prefix: string) => submitPageBatch(ctx, { request_id: requestId,
+ pages: [{ slug: `notes/${prefix}-a`, content: page(`${prefix}-a`) }, { slug: `notes/${prefix}-b`, content: page(`${prefix}-b`) }], wait_ms: 5000 });
+ const accepted = randomUUID();
+ await batch(accepted, 'batch-accepted');
+ const before = (await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0]!.n;
+ await behind();
+ try {
+ const error = await refusal(() => batch(randomUUID(), 'batch-behind'));
+ expect(error.code).toBe('migrations_pending');
+ expect(error.reason).toBe('schema_behind');
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0]!.n).toBe(before);
+ expect(await live('notes/batch-behind-a')).toBe(false);
+ await batch(accepted, 'batch-accepted');
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests'))[0]!.n).toBe(before);
+ } finally { await atHead(); }
+ }), 60_000);
+
test('a write made while this process holds the apply-migrations orchestration lock is admitted', () => inHome(async () => {
await behind();
try {
diff --git a/test/facts-publication-large-fence-6898.test.ts b/test/facts-publication-large-fence-6898.test.ts
index 019b946bbc..8296ccd289 100644
--- a/test/facts-publication-large-fence-6898.test.ts
+++ b/test/facts-publication-large-fence-6898.test.ts
@@ -31,6 +31,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { writeFactsToFence } from '../src/core/facts/fence-write.ts';
import * as journal from '../src/core/persistence/journal.ts';
+import * as factsFence from '../src/core/facts-fence.ts';
import { MANAGED_FACTS_PUBLICATION_MAX } from '../src/core/persistence/facts-maintenance.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { checkPersistenceCounterDrift } from '../src/commands/doctor/checks/persistence-compaction.ts';
@@ -136,13 +137,17 @@ function recordCounterHolds(): { holds: number[]; restore(): void } {
return { holds, restore: () => { lock.mockRestore(); complete.mockRestore(); } };
}
-test('a cap-sized publication on a 6,000-row fence costs about what a 1-fact one does', async () => {
+test('a cap-sized publication on a 6,000-row fence edits the fence once, never once per fact', async () => {
await largeEntity(6000, async ({ write }) => {
await write('warm', 1);
- const one = await write('one', 1);
- const capped = await write('cap', MANAGED_FACTS_PUBLICATION_MAX);
- expect([one.inserted, capped.inserted]).toEqual([1, MANAGED_FACTS_PUBLICATION_MAX]);
- expect(capped.ms).toBeLessThan(2 * one.ms);
+ const editor = spyOn(factsFence, 'factsFenceEditor');
+ const perFact = [spyOn(factsFence, 'upsertFactRow'), spyOn(factsFence, 'strikeFactRowInPage')];
+ try {
+ const capped = await write('cap', MANAGED_FACTS_PUBLICATION_MAX);
+ expect(capped.inserted).toBe(MANAGED_FACTS_PUBLICATION_MAX);
+ expect(editor).toHaveBeenCalledTimes(1);
+ expect(perFact.map(spy => spy.mock.calls.length)).toEqual([0, 0]);
+ } finally { editor.mockRestore(); for (const spy of perFact) spy.mockRestore(); }
});
}, 300_000);
@@ -198,8 +203,10 @@ test('the counter row is held for one part, and a put_page on another source com
const atPut = (await entityRequests(engine, sourceId)).slice(2);
expect((await group).inserted).toBe(16 * MANAGED_FACTS_PUBLICATION_MAX);
expect(atPut.filter(r => r.state !== 'committed').length).toBeGreaterThan(0);
- expect(probe.holds.length).toBeGreaterThan(0);
- expect(Math.max(...probe.holds)).toBeLessThan(3 * onePart);
+ expect(onePart).toBeGreaterThan(0);
+ expect(probe.holds).toHaveLength(16);
+ const parts = (await entityRequests(engine, sourceId)).slice(2);
+ expect(parts.map(r => r.outcome.inserted)).toEqual(Array(16).fill(MANAGED_FACTS_PUBLICATION_MAX));
} finally { probe.restore(); }
});
}, 600_000);
diff --git a/test/ghost-pages-skill-paths-6910.test.ts b/test/ghost-pages-skill-paths-6910.test.ts
index b76df1aafe..35bedc6fa1 100644
--- a/test/ghost-pages-skill-paths-6910.test.ts
+++ b/test/ghost-pages-skill-paths-6910.test.ts
@@ -175,4 +175,19 @@ describe('#6910 ghost pages under the shared skillpack', () => {
expect(await live(f.engine, 'notes/c')).toBe(false);
expect(await live(f.engine, SKILL)).toBe(false);
}), 120_000);
+
+ test('a run-wide caller refusal stops the apply and keeps the approval instead of marking every ghost refused', () => fixture(async f => {
+ const preview = await repair(f.engine);
+ installFaultHook(async (at, detail) => {
+ if (at !== 'consumer:preparing' || detail.operation !== 'submit_job') return;
+ throw opError('worktree_dirty', 'The canonical worktree has uncommitted changes.', 'Forced run-wide refusal.');
+ });
+ const stopped = await repair(f.engine, { apply: true, expect: preview.preview_hash }).catch((error: unknown) => error);
+ expect(JSON.stringify((stopped as { outcomes?: unknown }).outcomes ?? {})).not.toContain('refused');
+ expect(await live(f.engine, 'notes/a')).toBe(true);
+ installFaultHook(undefined);
+ const applied = await repair(f.engine, { apply: true, expect: preview.preview_hash });
+ expect(applied).toMatchObject({ outcomes: { soft_deleted: 4 } });
+ expect(await live(f.engine, 'notes/a')).toBe(false);
+ }), 120_000);
});
diff --git a/test/terminal-schema-missing-6904.test.ts b/test/terminal-schema-missing-6904.test.ts
index 88fbccaefe..1cb01f3bd3 100644
--- a/test/terminal-schema-missing-6904.test.ts
+++ b/test/terminal-schema-missing-6904.test.ts
@@ -77,6 +77,14 @@ describe('#6904 a missing relation or column at publication is schema_missing',
expect(publicFailureDetail(row!.error_detail)).toMatchObject({ origin: 'database', reason: 'schema_missing', sqlstate: '42703' });
});
+ test('a PL/pgSQL RAISE with SQLSTATE 42703 never puts its caller text into the failure', () => {
+ const failure = databaseRefusal(Object.assign(new Error('column "acme-example-codename" does not exist'), { code: '42703', routine: 'exec_stmt_raise' }));
+ expect(failure).toMatchObject({ code: 'storage_error', detail: { origin: 'database', sqlstate: '42703', reason: 'schema_missing' } });
+ expect(failure!.detail).not.toHaveProperty('missing');
+ expect(JSON.stringify(failure)).not.toContain('acme-example-codename');
+ expect(failure!.message).toContain('has no relation or column (42703)');
+ });
+
test('at head the diagnosis is schema_missing / storage and asks the user, with the missing-tables check', () => inHome(async () => {
await engine.setConfig('version', String(LATEST_SCHEMA_VERSION));
const d = await diagnosis();