Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): segmented replace no longer races its version sweep (#8729)
garrytan98b22108b941
diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 99f2f4c762..170114c953 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -758,8 +758,8 @@ export async function importFromContent(});const demote = !segmented && bodyStorageOf(existing) === 'segmented';- // Before the page write: an unpinned version reads the page itself, a demoted one references the generation it retires.- if (existing && (!preimage || demote)) await tx.createVersion(slug, preimage ? { ...txOpts, ...opts.history, preimage } : { ...txOpts, ...opts.history });+ // Before the page write: an unpinned version reads the page itself, a demoted one references the generation it retires, a segmented one (#8729) sweeps segment rows so never beside the flip.+ if (existing && (!preimage || demote || segmented)) await tx.createVersion(slug, preimage ? { ...txOpts, ...opts.history, preimage } : { ...txOpts, ...opts.history });if (demote) await demoteSegmentedPage(tx, Number(existing!.id));// Every import keeps each stored row that is identical to its new chunk and// writes only the rest, so an edit rewrites only the chunks it changed. The@@ -776,7 +776,7 @@ export async function importFromContent(let written: Page | undefined;await pipelined(tx, [() => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),- async () => { if (existing && preimage && !demote) await tx.createVersion(slug, { ...txOpts, ...opts.history, preimage }); },+ async () => { if (existing && preimage && !demote && !segmented) await tx.createVersion(slug, { ...txOpts, ...opts.history, preimage }); },async () => {if (segmented) return segmented.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown',effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filenameForChain, source_path: opts.sourcePath ?? null,diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 83641967f0..a0d5e9a581 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -45,7 +45,7 @@ import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, pubimport { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';import { landedCommit, PENDING_IMPORT, SYNC_HELD } from './pending-import.ts';-import { CANONICAL_FILE_MISSING, CHECKOUT_REFUSAL_ORIGINS, type CheckoutRefusalOrigin, databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';+import { CANONICAL_FILE_MISSING, CHECKOUT_REFUSAL_ORIGINS, type CheckoutRefusalOrigin, databaseRefusal, ownerExceptionFailure, stagingFailureDetail, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { SYNC_CURSOR_REPLACED, SYNC_PASS_SUPERSEDED } from './sync-checkpoint-replaced.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { withdrawalFailureDetail } from '../facts/withdrawal.ts';@@ -228,7 +228,8 @@ function requestError(error: unknown): PublicationFailure {?? (error.detail === CANONICAL_FILE_MISSING ? { origin: CANONICAL_FILE_MISSING } : undefined)?? ((CHECKOUT_REFUSAL_ORIGINS as readonly unknown[]).includes(error.detail) ? { origin: error.detail as CheckoutRefusalOrigin } : undefined)// #6693: a refusal on a page whose file awaits import or is held by sync; the replay after import selects on it.- ?? (error.code === 'source_changed' && (error.reason === PENDING_IMPORT || error.reason === SYNC_HELD) ? { origin: error.reason } : undefined);+ ?? (error.code === 'source_changed' && (error.reason === PENDING_IMPORT || error.reason === SYNC_HELD) ? { origin: error.reason } : undefined)+ ?? stagingFailureDetail(error);return { code: error.code, message: error.message, ...(detail ? { detail } : {}) };}const refusal = databaseRefusal(error);diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex 2258ada57a..9c754e002b 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -70,7 +70,37 @@ export type CheckoutRefusalOrigin = typeof CHECKOUT_REFUSAL_ORIGINS[number];export interface CheckoutRefusalDetail { origin: CheckoutRefusalOrigin; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }/** #6693: a page write refused because its file holds a committed change sync has not imported (`pending_import`) or sync holds the file (`sync_held`). */export interface PendingImportDetail { origin: 'pending_import' | 'sync_held'; stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null } }-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | CheckoutRefusalDetail | PendingImportDetail }+/**+ * #8729: a segmented write refused body_staging_expired: the staging it names and, when the flip found the generation it+ * would publish incomplete, what that generation's rows covered. Fixed identifiers and counts only; owner-only (`staging`+ * is not a public key), so the receipt names the staging for the owner's drill-down.+ */+export interface StagingRefusalDetail {+ origin: 'body_staging';+ staging: { staging_id: string; state?: string | null; reason?: 'generation_incomplete'; rows?: number; segment_count?: number; covered_bytes?: number | null; body_bytes?: number };+ stage?: PublicationStage; attempt?: { consumer_version: string; consumer_host_id: string | null };+}+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | WithdrawalRefusalDetail | OwnerExceptionDetail | CanonicalFileDetail | CheckoutRefusalDetail | PendingImportDetail | StagingRefusalDetail }++const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const STAGING_STATES: readonly unknown[] = ['open', 'sealed', 'prepared', 'committed', 'aborted', 'expired'];+const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;++/** #8729: the bounded detail of a body_staging_expired refusal (engine-sql/page-body.ts), read field by field from its JSON, or undefined. */+export function stagingFailureDetail(error: Pick<OperationError, 'code' | 'detail'>): StagingRefusalDetail | undefined {+ if (error.code !== 'body_staging_expired' || typeof error.detail !== 'string') return undefined;+ let raw: Record<string, unknown> | null;+ try { raw = JSON.parse(error.detail) as Record<string, unknown> | null; } catch { return undefined; }+ if (!raw || typeof raw !== 'object' || typeof raw.staging_id !== 'string' || !UUID.test(raw.staging_id)) return undefined;+ const staging: StagingRefusalDetail['staging'] = { staging_id: raw.staging_id.toLowerCase() };+ if (raw.state === null || STAGING_STATES.includes(raw.state)) staging.state = raw.state as string | null;+ if (raw.reason === 'generation_incomplete') {+ staging.reason = 'generation_incomplete';+ for (const key of ['rows', 'segment_count', 'body_bytes'] as const) { const n = count(raw[key]); if (n !== undefined) staging[key] = n; }+ staging.covered_bytes = count(raw.covered_bytes) ?? null;+ }+ return { origin: 'body_staging', staging };+}const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;diff --git a/src/core/persistence/sync-pass-batch.ts b/src/core/persistence/sync-pass-batch.tsindex 354d9cf90c..d2c745b804 100644--- a/src/core/persistence/sync-pass-batch.ts+++ b/src/core/persistence/sync-pass-batch.ts@@ -64,9 +64,13 @@ export async function passBatchHead(tx: Pick<BrainEngine, 'executeRaw'>, key: st/** RFC 4122 namespace of pass request ids (fixed forever: changing it re-admits a same-pass replay). */const NS_SYNC_PASS = Buffer.from('5f0c6712b4a84e0b9d1a2c3e4f5a6712', 'hex');-/** `request_id = uuidv5(NS_SYNC_PASS, passId‖path‖level)` (design v3.2 §3.1): a same-pass replay reads the existing receipt. */-export function passRequestId(passId: string, path: string, level: string | null): string {- const hash = createHash('sha1').update(NS_SYNC_PASS).update(`sync_pass:v1:${passId.toLowerCase()}\0${path}\0${level ?? ''}`).digest();+/**+ * `request_id = uuidv5(NS_SYNC_PASS, passId‖path‖level)` (design v3.2 §3.1): a same-pass replay reads the existing receipt.+ * #8729: `retry` (the entry's in-place re-freezes after a failed receipt) names a new request, so a retry prepares the+ * entry again instead of reading the failed receipt back; the first freeze keeps the v1 id.+ */+export function passRequestId(passId: string, path: string, level: string | null, retry = 0): string {+ const hash = createHash('sha1').update(NS_SYNC_PASS).update(`sync_pass:v1:${passId.toLowerCase()}\0${path}\0${level ?? ''}${retry > 0 ? `\0retry:${retry}` : ''}`).digest();hash[6] = (hash[6]! & 0x0f) | 0x50;hash[8] = (hash[8]! & 0x3f) | 0x80;const hex = hash.subarray(0, 16).toString('hex');diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 50a3ad4d70..e38130bae0 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -688,6 +688,7 @@ async function syncWriteState(tx: BrainEngine, row: WriteRequest, page: Parametereturn { ...await sizeStateField(tx, row.source_id, row.slug, page), ...segmentedOutcome(segmented, isQuarantined(frontmatter)) };}+/** #8729: a screen (`screening`) publishes nothing, so the segmented staging its import opened is aborted at once, never left live beside the admitted write's. */async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig, clock: ClaimPhaseClock | undefined,screening: { unsaved: true } | undefined, at: { root?: string }): Promise<SyncPreparedMutation> {const engine = boundedReads(unbounded, clock, { engineReads: true });@@ -893,8 +894,8 @@ async function prepareSyncMutation(unbounded: BrainEngine, row: WriteRequest, _cif (!prepared) throw result.refusal ? syncContentRefusal(result.refusal, row, p) : syncPublicationRefusal('invalid_params', result.error ?? 'The sync file could not be prepared.', row, p,`The file could not be prepared as page ${row.slug}.`);const ready = prepared;- if (ready.observedRevision !== (base?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The page changed during sync preparation.', row, p,- `Page ${renamed?.slug ?? row.slug} changed while this sync was being prepared.`);+ if (screening) await abortSegmentedStaging(engine, ready.segmented?.prepared);+ if (ready.observedRevision !== (base?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The page changed during sync preparation.', row, p, `Page ${renamed?.slug ?? row.slug} changed while this sync was being prepared.`);if (ready.slug !== (renamed?.slug ?? row.slug)) {// Cross-slug dedup must never advance the origin's checkpoint without a// guarded proof about the other identity. Keep the cursor explicitly blocked.diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 772d94495d..8e8fa00abe 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -699,7 +699,7 @@ export const STOPS_PER_ENTRY = 3;/*** #6712: the entry of a request that did not commit and whose fault is not the page's (a transport fault proven by its* receipt, a systemic stop an earlier invocation recorded, or a legacy knock-on an older gbrain cancelled) is re-frozen in- * place under a fresh request: the cursor does not advance past it and the failed receipt is recorded as converted+ * place under a fresh request (#8729: in a pass, the retry's own `passRequestId`, never the failed one): the cursor does not advance past it and the failed receipt is recorded as converted* (`convertedFromFailed`), so it never blocks the checkpoint. Bounded by `STOPS_PER_ENTRY` re-freezes in a row at the* entry (`Pending.stops`); null past the bound, so the failure is recorded and the next sync takes the entry again (a pass re-classifies its path; a company run retries its recorded stop).*/@@ -718,7 +718,7 @@ async function refreezeInPlace(engine: BrainEngine, input: SettleInput): Promiseconst held = await holdUnderGate(engine, { cursor, key, pending, hold: fresh.hold, assertActive, observedAt, waitMs: input.waitMs, base });return held === 'pending' ? null : held;}- return saveCursor(engine, key, cursor, { ...base, convertedFromFailed: converted, pending: { ...fresh, stops: (pending.stops ?? 0) + 1 } }, false, assertActive,+ return saveCursor(engine, key, cursor, { ...base, convertedFromFailed: converted, pending: { ...fresh, stops: (pending.stops ?? 0) + 1, requestId: cursor.passId ? passRequestId(cursor.passId, entry.path, (entry as PassEntry).level ?? null, (pending.stops ?? 0) + 1) : fresh.requestId } }, false, assertActive,tx => recordSyncConversion(tx, cursor.sourceId, cursor.incarnation, { request_id: pending.requestId, path: pending.intent.path ?? null, slug: pending.slug, run_id: cursor.runId, outcome: 'refrozen' }));}diff --git a/src/core/persistence/terminal-classify.ts b/src/core/persistence/terminal-classify.tsindex ee8f6105e7..05c129cbb7 100644--- a/src/core/persistence/terminal-classify.ts+++ b/src/core/persistence/terminal-classify.ts@@ -407,7 +407,7 @@ export const PAGE_REMOVAL_OPERATIONS: readonly string[] = ['delete_page', 'purge* write, a later committed connector retry whose recorded `retryOf` lineage reaches it (connectorRetrySql). `r` must* expose `id`. Literal strings only; NULL-safe for a compacted `c` (no intent).*/-export function supersessionSql(r: string, c: string): string {+export function supersessionSql(r: string, c: string, rKind?: string): string {const removals = PAGE_REMOVAL_OPERATIONS.map(op => `'${op}'`).join(',');return `(${c}.source_id=${r}.source_id AND ${c}.slug=${r}.slug AND ${c}.sequence>${r}.sequence AND ((${c}.digest=${r}.digest AND ${c}.state IN ('committed','failed','queued','running','recovering'))@@ -416,7 +416,7 @@ export function supersessionSql(r: string, c: string): string {AND COALESCE((SELECT k.intent->>'kind' FROM persistence_requests k WHERE k.id=${r}.id),'managed_sync_checkpoint')='managed_sync_checkpoint'AND COALESCE(${c}.intent->>'kind','managed_sync_checkpoint')='managed_sync_checkpoint')OR (${r}.operation='put_page' AND ${c}.state='failed' AND ${c}.operation='put_page' AND COALESCE(NOT (${c}.intent ? 'kind'), false))- OR ${connectorRetrySql(r, c)}))`;+ OR ${connectorRetrySql(r, c, rKind)}))`;}/** Hops a connector retry's `retryOf` lineage is followed back; a longer chain leaves the refusal unresolved (fail closed). */@@ -432,8 +432,8 @@ const UUID_TEXT = `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}* intent kind, at a lower sequence, within CONNECTOR_RETRY_LINEAGE_MAX_DEPTH hops. Another refusal of the same item with* no recorded link is not proof. Each hop is one lookup on the (principal_kind, principal_id, request_id) unique index.*/-function connectorRetrySql(r: string, c: string): string {- return `(${r}.operation='submit_job' AND ${c}.operation='submit_job' AND ${c}.state='committed' AND COALESCE(${c}.intent ? 'retryOf', false)+function connectorRetrySql(r: string, c: string, rKind?: string): string {+ return `(${r}.operation='submit_job' AND ${c}.operation='submit_job' AND ${c}.state='committed'${rKind ? ` AND ${rKind} IN (${CONNECTOR_WRITE_KINDS})` : ''} AND COALESCE(${c}.intent ? 'retryOf', false)AND EXISTS (SELECT 1 FROM persistence_requests k, persistence_requests cc WHERE k.id=${r}.id AND cc.sequence=${c}.sequenceAND k.intent->>'kind' IN (${CONNECTOR_WRITE_KINDS})AND cc.intent->>'kind'=k.intent->>'kind' AND cc.principal_kind=k.principal_kind AND cc.principal_id=k.principal_iddiff --git a/src/core/persistence/terminal-failures.ts b/src/core/persistence/terminal-failures.tsindex cfd8cf3f39..3340f9d666 100644--- a/src/core/persistence/terminal-failures.ts+++ b/src/core/persistence/terminal-failures.ts@@ -144,7 +144,7 @@ export async function readTerminalFailureSummary(engine: BrainEngine, opts: { soWHERE (${RECOVERY('r')} OR (${TERMINAL('r')} AND ${ENDED('r')} > now()-($1::int*interval '1 day')))AND ($2::text[] IS NULL OR r.source_id=ANY($2::text[]))), resolved AS (- SELECT r.id FROM base r WHERE NOT r.has_recovery AND EXISTS (SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c')})+ SELECT r.id FROM base r WHERE NOT r.has_recovery AND EXISTS (SELECT 1 FROM persistence_requests c WHERE ${supersessionSql('r', 'c', 'r.intent_kind')})), tagged AS (SELECT b.*, (x.id IS NOT NULL OR (NOT b.has_recovery AND b.error_code='${SYNC_PASS_SUPERSEDED}')) AS resolved, (b.has_recovery OR b.ended_at > now()-($3::int*interval '1 day')) AS in_window, ${HISTORICAL_BY_BUILD('b')} AS historical_buildFROM base b LEFT JOIN resolved x ON x.id=b.id@@ -330,17 +330,18 @@ export async function readTerminalFailures(engine: BrainEngine, q: TerminalFailuconst want = q.groupBy ? MAX_SCAN : limit + 1;while (out.length < want && scanned < MAX_SCAN && !exhausted) {const batch = await bounded<KeyColumns & { request_id: string; sequence: string; slug: string; error_detail: Record<string, unknown> | null; ended_at: string; admitted_at: string; later_state: string | null; same_intent: boolean | null }>(engine,- `SELECT r.request_id::text AS request_id, r.sequence::text AS sequence, r.source_id, r.slug, r.operation, r.intent->>'kind' AS intent_kind, r.state, r.error_code, r.error_detail,+ `SELECT r.request_id::text AS request_id, r.sequence::text AS sequence, r.source_id, r.slug, r.operation, r.intent_kind, r.state, r.error_code, r.error_detail,r.error_detail->>'origin' AS origin, r.error_detail->>'reason' AS reason, r.error_detail->>'cause' AS cause,r.recovery IS NOT NULL AS has_recovery, r.blocked_reason, r.compacted, ${terminalKnockOnSql('r')} AS knock_on, ${ROUTED_MESSAGE('r')} AS routed_message, ${BUILD('r')} AS build,to_char(${ENDED('r')} AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS ended_at, to_char(r.created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS"Z"') AS admitted_at,later.state AS later_state, later.same_intent- FROM persistence_requests r- LEFT JOIN LATERAL (SELECT c.state, c.digest=r.digest AS same_intent FROM persistence_requests c WHERE ${supersessionSql('r', 'c')}+ FROM (SELECT p.*, p.intent->>'kind' AS intent_kind FROM persistence_requests p+ WHERE p.source_id=$1 AND (${RECOVERY('p')} OR (${TERMINAL('p')} AND ${ENDED('p')} > now()-($2::int*interval '1 day')))+ AND ($3::bigint IS NULL OR p.sequence < $3::bigint)+ ORDER BY p.sequence DESC LIMIT $4) r+ LEFT JOIN LATERAL (SELECT c.state, c.digest=r.digest AS same_intent FROM persistence_requests c WHERE ${supersessionSql('r', 'c', 'r.intent_kind')}ORDER BY ${supersessionOrderSql('r', 'c')} LIMIT 1) later ON r.recovery IS NULL- WHERE r.source_id=$1 AND (${RECOVERY('r')} OR (${TERMINAL('r')} AND ${ENDED('r')} > now()-($2::int*interval '1 day')))- AND ($3::bigint IS NULL OR r.sequence < $3::bigint)- ORDER BY r.sequence DESC LIMIT $4`, [q.sourceId, t.windowDays, cursor, BATCH]);+ ORDER BY r.sequence DESC`, [q.sourceId, t.windowDays, cursor, BATCH]);if (batch === 'unknown') return { status: 'unknown', source_id: q.sourceId, reason: `the read did not finish within ${TERMINAL_STATEMENT_MS} ms (or no connection within ${TERMINAL_ACQUIRE_MS} ms)` };if (batch.length < BATCH) exhausted = true;for (const row of batch) {diff --git a/test/e2e/segmented-sync-replace-8729-postgres.test.ts b/test/e2e/segmented-sync-replace-8729-postgres.test.tsnew file mode 100644index 0000000000..af13d249a7--- /dev/null+++ b/test/e2e/segmented-sync-replace-8729-postgres.test.ts@@ -0,0 +1,32 @@+/**+ * #8729 Postgres arm: test/helpers/segmented-sync-replace-cases.ts (the PGLite arm is+ * test/large-pages/segmented-sync-replace-8729.test.ts). Only Postgres pipelines a publication's calls, so only this arm+ * can run a version's prune sweep beside the flip.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { defineSegmentedSyncReplaceCases } from '../helpers/segmented-sync-replace-cases.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { hasDatabase } from './helpers.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-replace-8729-pg-'));+let engine: PostgresEngine;+let close: (() => Promise<void>) | undefined;++(hasDatabase() ? describe : describe.skip)('segmented sync replace (#8729) [postgres]', () => {+ beforeAll(async () => {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; close = pg.close;+ }, 120_000);+ afterAll(async () => {+ if (engine) await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));+ await close?.();+ rmSync(home, { recursive: true, force: true });+ });+ defineSegmentedSyncReplaceCases({ getEngine: () => engine, home });+});diff --git a/test/e2e/terminal-failures-large-intents-8729-postgres.test.ts b/test/e2e/terminal-failures-large-intents-8729-postgres.test.tsnew file mode 100644index 0000000000..4566a6ab01--- /dev/null+++ b/test/e2e/terminal-failures-large-intents-8729-postgres.test.ts@@ -0,0 +1,50 @@+/**+ * #8729: `gbrain sources writer failures` (readTerminalFailures) and the terminal summary on a source whose page has many+ * sync writes with large frozen intents.+ *+ * 1. Protects: the drill-down and the summary answer `ok` within their statement bound when a page holds a few hundred+ * failed sync imports and thousands of later committed ones, each carrying a large frozen file in its intent.+ * 2. Fails when: the supersession probe's connector-retry branch reads every later committed submit_job's intent (one+ * detoast per failed row and candidate) before it knows the failed row is a connector write, so each batch outruns+ * TERMINAL_STATEMENT_MS and the read reports `unknown`.+ * 3. Postgres only: the bound is a server-side statement timeout.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { readTerminalFailures, readTerminalFailureSummary } from '../../src/core/persistence/terminal-failures.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { hasDatabase } from './helpers.ts';++let engine: PostgresEngine;+let close: (() => Promise<void>) | undefined;++async function seed(state: 'failed' | 'committed', rows: number): Promise<void> {+ await engine.executeRaw(`INSERT INTO persistence_requests (principal_kind, principal_id, request_id, operation, source_id, source_incarnation, slug, digest,+ authority, intent_bytes, terminal_reservation, state, intent, error_code, error_message, completed_at)+ SELECT 'local_cli', 'example', gen_random_uuid(), 'submit_job', 'source-a', gen_random_uuid(), 'conversations/chat-example', md5($1 || g::text),+ '{}'::jsonb, 1, 1, $1, jsonb_build_object('kind', 'managed_sync_import', 'path', 'conversations/chat-example.md', 'content', repeat(md5(g::text), 65536)),+ CASE WHEN $1 = 'failed' THEN 'body_staging_expired' END, CASE WHEN $1 = 'failed' THEN 'The staged body of this write is expired.' END,+ now() - (g || ' seconds')::interval+ FROM generate_series(1, $2::int) g`, [state, rows]);+}++(hasDatabase() ? describe : describe.skip)('terminal failure reads over large sync intents (#8729) [postgres]', () => {+ beforeAll(async () => {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine; close = pg.close;+ await engine.executeRaw("INSERT INTO sources(id, name, local_path, config) VALUES ('source-a', 'source-a', '/nonexistent/source-a', '{}')");+ await seed('failed', 200);+ for (let i = 0; i < 4; i++) await seed('committed', 500);+ await engine.executeRaw('ANALYZE persistence_requests');+ }, 300_000);+ afterAll(async () => { await close?.(); });++ test('the drill-down rows, its groups and the summary answer ok', async () => {+ const rows = await readTerminalFailures(engine, { sourceId: 'source-a' });+ expect(rows.status).toBe('ok');+ const groups = await readTerminalFailures(engine, { sourceId: 'source-a', groupBy: 'category' });+ expect(groups.status).toBe('ok');+ expect(groups.status === 'ok' && groups.groups?.reduce((sum, group) => sum + group.rows, 0)).toBe(200);+ expect((await readTerminalFailureSummary(engine, { sourceIds: ['source-a'] })).status).toBe('ok');+ }, 120_000);+});diff --git a/test/helpers/segmented-sync-replace-cases.ts b/test/helpers/segmented-sync-replace-cases.tsnew file mode 100644index 0000000000..cb552fe441--- /dev/null+++ b/test/helpers/segmented-sync-replace-cases.ts@@ -0,0 +1,114 @@+/**+ * #8729: a managed sync replace of a page stored in segments, where each write changes only the eof tail row. Shared by+ * the PGLite arm (test/large-pages/segmented-sync-replace-8729.test.ts) and the Postgres arm+ * (test/e2e/segmented-sync-replace-8729-postgres.test.ts).+ *+ * 1. Protects: every replace commits in its own sync run while each write's version prunes the page's segmented history+ * (versions.segmented_max_per_page 1, so every version prunes and sweeps); the live generation tiles the body; no+ * staging is left live after a run (the no-op screen aborts the staging its preparation opened, the admitted write+ * commits its own); a refusal of body_staging_expired records its staging in error_detail, and the run prepares the+ * page again in the same invocation and commits it.+ * 2. Fails when: the version's prune sweep runs beside the flip (Postgres pipelines the publication's calls), deletes the+ * tail row the flip just published and the flip refuses body_staging_expired (generation_incomplete), blocking the+ * source; the screen's staging stays prepared until the idle sweep; or the refusal's error_detail is NULL.+ * 3. PGLite runs pipelined calls in order, so only the Postgres arm can interleave the sweep with the flip; both arms+ * check the staging and error_detail contracts.+ */+import { expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { withEnv } from './with-env.ts';+import { withManagedFixtureWrite } from './managed-e2e-fixture-write.ts';+import { conversationBody } from './conversation-page.ts';++const SLUG = 'conversations/chat-example';+const PATH = 'conversations/chat-example.md';++function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string): void { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'test content'); }++export function defineSegmentedSyncReplaceCases(opts: { getEngine: () => BrainEngine; home: string }): void {+ const env = () => ({ GBRAIN_HOME: opts.home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined });++ async function fixture(name: string) {+ const engine = opts.getEngine();+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('versions.segmented_max_per_page', '1');+ const sourceId = name;+ const root = join(opts.home, sourceId);+ mkdirSync(join(root, 'conversations'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, PATH), '---\ntype: conversation\ntitle: Chat Example\n---\n\n' + conversationBody(2000 * 1024, { seed: 3 }));+ commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ expect(await performManagedSync(engine, { sourceId, noPull: true })).toMatchObject({ status: 'first_sync', filesImported: 1 });+ const [page] = await engine.executeRaw<{ id: number; body_storage: string }>('SELECT id, body_storage FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, SLUG]);+ expect(page!.body_storage).toBe('segmented');+ return { engine, sourceId, root, pageId: Number(page!.id) };+ }++ async function appendTurn(f: { engine: BrainEngine; sourceId: string; root: string }, n: number) {+ appendFileSync(join(f.root, PATH), '\n\n**alice-example**: another turn number ' + n + ' for the tail.\n\n**bob-example**: reply ' + n + '.');+ commit(f.root);+ return performManagedSync(f.engine, { sourceId: f.sourceId, noPull: true, noEmbed: true, noExtract: true });+ }++ async function pageState(engine: BrainEngine, pageId: number) {+ const [page] = await engine.executeRaw<{ gen: string; body_bytes: string; covered: string }>(+ 'SELECT p.body_generation::text AS gen, p.body_bytes::text AS body_bytes, (SELECT COALESCE(sum(m.byte_len),0)::text FROM page_body_manifest m WHERE m.page_id=p.id AND m.staging_id IS NULL AND m.gen_from<=p.body_generation AND (m.gen_to IS NULL OR m.gen_to>p.body_generation)) AS covered FROM pages p WHERE p.id=$1', [pageId]);+ const [live] = await engine.executeRaw<{ n: string }>("SELECT count(*)::text AS n FROM page_body_stagings WHERE page_id=$1 AND state IN ('open','sealed','prepared')", [pageId]);+ return { generation: Number(page!.gen), bodyBytes: Number(page!.body_bytes), covered: Number(page!.covered), liveStagings: Number(live!.n) };+ }++ test('each tail-only replace commits in its own run while every version prunes, and leaves no staging live', async () => withEnv(env(), async () => {+ const f = await fixture('replace-8729');+ let generation = (await pageState(f.engine, f.pageId)).generation;+ const liveAfterRun: number[] = [];+ for (let n = 1; n <= 3; n++) {+ const result = await appendTurn(f, n);+ expect(result.failures).toBeUndefined();+ expect(result.status).toBe('synced');+ const state = await pageState(f.engine, f.pageId);+ expect(state.generation).toBe(generation + 1);+ expect(state.covered).toBe(state.bodyBytes);+ liveAfterRun.push(state.liveStagings);+ generation = state.generation;+ }+ expect(await f.engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state='failed'", [f.sourceId])).toEqual([]);+ expect(liveAfterRun).toEqual([0, 0, 0]);+ }), 600_000);++ test('a body_staging_expired refusal records its staging in error_detail and the run prepares the page again', async () => withEnv(env(), async () => {+ const f = await fixture('expired-8729');+ let expired: string | null = null;+ installFaultHook(async point => {+ if (point !== 'segmented:chunks_staged' || expired !== null) return;+ const running = await f.engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND state='running'", [f.sourceId]);+ if (!running.length) return;+ const [row] = await withManagedFixtureWrite(f.engine, [f.sourceId], tx => tx.executeRaw<{ id: string }>(+ "UPDATE page_body_stagings SET state='expired' WHERE page_id=$1 AND state IN ('open','sealed','prepared') RETURNING id::text AS id", [f.pageId]));+ expired = row?.id ?? null;+ });+ let result: Awaited<ReturnType<typeof appendTurn>>;+ try { result = await appendTurn(f, 1); } finally { installFaultHook(undefined); }+ expect(expired).not.toBeNull();+ expect(result.status).toBe('synced');+ const [failed] = await f.engine.executeRaw<{ error_code: string; error_detail: Record<string, unknown> | null }>(+ "SELECT error_code, error_detail FROM persistence_requests WHERE source_id=$1 AND state='failed'", [f.sourceId]);+ expect(failed?.error_code).toBe('body_staging_expired');+ expect(failed?.error_detail).toMatchObject({ origin: 'body_staging', staging: { staging_id: expired, state: 'expired' } });+ const state = await pageState(f.engine, f.pageId);+ expect(state.covered).toBe(state.bodyBytes);+ expect(state.liveStagings).toBe(0);+ }), 600_000);+}diff --git a/test/large-pages/segmented-sync-replace-8729.test.ts b/test/large-pages/segmented-sync-replace-8729.test.tsnew file mode 100644index 0000000000..c37c8b3d96--- /dev/null+++ b/test/large-pages/segmented-sync-replace-8729.test.ts@@ -0,0 +1,24 @@+/**+ * #8729 PGLite arm: test/helpers/segmented-sync-replace-cases.ts (the Postgres arm is+ * test/e2e/segmented-sync-replace-8729-postgres.test.ts).+ */+import { afterAll, beforeAll, describe } 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 { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { defineSegmentedSyncReplaceCases } from '../helpers/segmented-sync-replace-cases.ts';+import { withEnv } from '../helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-replace-8729-'));+let engine: PGLiteEngine;++describe('segmented sync replace (#8729) [pglite]', () => {+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });+ rmSync(home, { recursive: true, force: true });+ });+ defineSegmentedSyncReplaceCases({ getEngine: () => engine, home });+});diff --git a/test/publication-failure-staging-8729.test.ts b/test/publication-failure-staging-8729.test.tsnew file mode 100644index 0000000000..e14784a359--- /dev/null+++ b/test/publication-failure-staging-8729.test.ts@@ -0,0 +1,26 @@+/**+ * #8729: stagingFailureDetail reads a body_staging_expired refusal's JSON detail into a bounded error_detail.+ *+ * 1. Protects: the flip's generation_incomplete refusal keeps its staging id, rows, segment count and covered bytes, so+ * `sources writer failures` shows which staging was short and by how much.+ * 2. Fails when: the detail is dropped (error_detail NULL), an unexpected key or a non-uuid staging id passes through.+ */+import { expect, test } from 'bun:test';+import { stagingFailureDetail } from '../src/core/persistence/publication-failure.ts';++const id = '0b5e8f3a-1c2d-4e5f-8a9b-0c1d2e3f4a5b';++test('a generation_incomplete refusal keeps its staging and coverage counts', () => {+ const detail = JSON.stringify({ staging_id: id.toUpperCase(), reason: 'generation_incomplete', rows: 7, segment_count: 8, covered_bytes: 900, body_bytes: 1024, extra: 'x' });+ expect(stagingFailureDetail({ code: 'body_staging_expired', detail })).toEqual({ origin: 'body_staging',+ staging: { staging_id: id, reason: 'generation_incomplete', rows: 7, segment_count: 8, covered_bytes: 900, body_bytes: 1024 } });+ const gap = JSON.stringify({ staging_id: id, reason: 'generation_incomplete', rows: 7, segment_count: 8, covered_bytes: null, body_bytes: 1024 });+ expect(stagingFailureDetail({ code: 'body_staging_expired', detail: gap })?.staging.covered_bytes).toBeNull();+});++test('other codes, non-uuid ids and unparseable details give no detail', () => {+ expect(stagingFailureDetail({ code: 'revision_conflict', detail: JSON.stringify({ staging_id: id }) })).toBeUndefined();+ expect(stagingFailureDetail({ code: 'body_staging_expired', detail: JSON.stringify({ staging_id: 'conversations/chat-example' }) })).toBeUndefined();+ expect(stagingFailureDetail({ code: 'body_staging_expired', detail: '{' })).toBeUndefined();+ expect(stagingFailureDetail({ code: 'body_staging_expired', detail: JSON.stringify({ staging_id: id, state: 'bogus' }) })).toEqual({ origin: 'body_staging', staging: { staging_id: id } });+});diff --git a/test/terminal-supersession-kind-8729.test.ts b/test/terminal-supersession-kind-8729.test.tsnew file mode 100644index 0000000000..539a27898a--- /dev/null+++ b/test/terminal-supersession-kind-8729.test.ts@@ -0,0 +1,15 @@+/**+ * #8729: the supersession probe's connector-retry branch tests the failed row's own intent kind (when the caller passes+ * it) before it reads a candidate's intent, so a page with many later committed sync writes is not detoasted once per+ * failed row and candidate. Postgres evaluates an AND inside an OR left to right; the order is the contract.+ */+import { expect, test } from 'bun:test';+import { supersessionSql } from '../src/core/persistence/terminal-classify.ts';++test('the connector branch reads the candidate intent only after the failed row is a connector write', () => {+ const sql = supersessionSql('r', 'c', 'r.intent_kind');+ const kind = sql.indexOf("r.intent_kind IN ('connector_v2_import'");+ expect(kind).toBeGreaterThan(-1);+ expect(kind).toBeLessThan(sql.indexOf("c.intent ? 'retryOf'"));+ expect(supersessionSql('r', 'c')).not.toContain('r.intent_kind');+});