Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
persistence: charge group publications cancelled at the ceiling, honour backoff in reclaimReleasedWrite, drop v261 CHECK (LPH b/c review)
garrytanc19907386ab5
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 799827e928..cb7b8e8569 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -234,8 +234,7 @@ const TRANSIENT_RETRIES_KEY = PREPARATION_BUDGET_KEYS.transientRetries;* persistence.max_transient_retries. Null when the failure is not one, the `preparation_deadlines` switch is off* (nothing is counted and no backoff applies, as before), or the database cannot be read (released uncounted).*/-async function interruptionCharge(engine: BrainEngine, error: unknown): Promise<{ interruption: TransientInterruption; limit: number } | null> {- const interruption = transientInterruption(error);+async function interruptionCharge(engine: BrainEngine, error: unknown, interruption = transientInterruption(error)): Promise<{ interruption: TransientInterruption; limit: number } | null> {if (!interruption) return null;if (isSharedReadFailure(error)) {if (chargedSharedReads.has(error as object)) return null;@@ -252,7 +251,7 @@ async function interruptionCharge(engine: BrainEngine, error: unknown): Promise<* own statement before `markRecovering`: the request already holds its recovery record, which the expired-owner sweep* never takes, so a crash in between leaves the one charge for the owner's recovery to finish. Null when not charged.*/-async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<{ failure: PublicationFailure | null } | null> {+export async function chargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<{ failure: PublicationFailure | null } | null> {const charge = await interruptionCharge(engine, error);if (!charge) return null;try {@@ -309,24 +308,33 @@ export async function finishPreparationStalled(engine: BrainEngine, row: WriteRereturn engine.transaction(tx => completeWrite(tx, row, 'failed', {}, failure));}+/**+ * Flip lane C: releases a held claim whose work a transient interruption ended, charged in the transaction that releases+ * or finishes it. A crash before it commits leaves the claim uncharged (the expired-owner sweep charges a preparing claim+ * once), after it the charged outcome; never both. The release carries the backoff the charge scheduled+ * (`next_attempt_at`), so no claim waits it out; past the limit the claim ends `failed`/`write_interrupted`. Null when+ * nothing was charged (not an interruption, the switch off, or the database refused). `interruption` is the+ * classification when the caller made it inside the cancelled publication (a lane group's release runs after it).+ */+export async function releaseChargedInterruption(engine: BrainEngine, row: WriteRequest, error: unknown, stage: PublicationStage,+ reason = 'database_contention', interruption = transientInterruption(error)): Promise<WriteRequest | null> {+ const charge = await interruptionCharge(engine, error, interruption);+ if (!charge) return null;+ const done = await engine.transaction(async tx => {+ const attempts = await chargeTransientInterruption(tx, row);+ if (attempts > charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.interruption, attempts, charge.limit), stage));+ await releaseUnpublishedClaim(tx, row, reason);+ return null;+ }).then(outcome => ({ outcome }), () => null);+ if (!done) return null;+ await faultPoint('persistence:interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });+ return done.outcome ?? (await getWriteRequestById(engine, row.id))!;+}+export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRequest, error: unknown,stage: PublicationStage = 'publication'): Promise<WriteRequest> {- const charge = await interruptionCharge(engine, error);- if (charge) {- // Flip lane C: charged in the transaction that releases or finishes the claim. A crash before it commits leaves the claim- // uncharged (the expired-owner sweep charges a preparing claim once), after it the charged outcome; never both. The- // release carries the backoff the charge scheduled (`next_attempt_at`), so no claim waits it out.- const done = await engine.transaction(async tx => {- const attempts = await chargeTransientInterruption(tx, row);- if (attempts > charge.limit) return completeWrite(tx, row, 'failed', {}, withAttempt(writeInterruptedFailure(row, charge.interruption, attempts, charge.limit), stage));- await releaseUnpublishedClaim(tx, row, 'database_contention');- return null;- }).then(outcome => ({ outcome }), () => null);- if (done) {- await faultPoint('persistence:interruption_charged', { requestId: row.request_id, writeId: row.id, sourceId: row.source_id, operation: row.operation });- return done.outcome ?? (await getWriteRequestById(engine, row.id))!;- }- }+ const charged = await releaseChargedInterruption(engine, row, error, stage);+ if (charged) return charged;const failure = withAttempt(requestError(error), stage);if (mayReprepare(row, failure) || transientDatabaseFailure(error)) {await releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 52473c8a75..a2efaf453a 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -60,8 +60,10 @@ import { isWriteTargetContained } from '../path-confine.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { isStreamedContent } from './large-file.ts';import { sharedReadFailure } from './bounded-reads.ts';-import { decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason, publicationPostimage, publishMutation,- publishPersistenceFile, recoverPublication, type PreparedMutation } from './coordinator.ts';+import { chargedInterruption, decoratePublicationOutcome, finishPreparationStalled, finishUnpublishedFailure, pageRecoveryRecord, persistenceFileHash, preparationAbortReason,+ publicationPostimage, publishMutation, publishPersistenceFile, recoverPublication, releaseChargedInterruption, type PreparedMutation } from './coordinator.ts';+import { withAttempt } from './publication-failure.ts';+import { transientInterruption, type TransientInterruption } from './transient-retry.ts';import { pipelined } from '../page-state/transactions.ts';import { jsonBytes } from './digest.ts';import { EFFECT_BYTES_SQL, retainedReceiptBytes, TRUE_UP_CLAMP_SQL } from './receipt-bytes.ts';@@ -398,13 +400,21 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr}return { done, requeued: [] };} catch (error) {- if (committed || !recorded.size) { await hooks.rolledBack?.(rows); return { ...none, reason: groupFailure(error), ...(committed ? {} : culpritOf(error)) }; }+ if (committed || !recorded.size) {+ await hooks.rolledBack?.(rows);+ // LPH (b)/(c): classified here, inside the publication the ceiling may have cancelled; a lane release charges it.+ const interrupted = committed ? null : transientInterruption(error);+ return { ...none, reason: groupFailure(error), ...(committed ? {} : culpritOf(error)), ...(interrupted ? { interrupted } : {}) };+ }// Restore every file this group may have published and release those claims; a committed member (an uncertain commit) only cleans up.+ // LPH (b)/(c): a transient interruption is charged to each member first; past the limit its recovery finishes it write_interrupted.const requeued: string[] = [];for (const { row } of recorded.values()) {try {- await markRecovering(engine, row, 'publication_not_started');- const recovered = await recoverPublication(engine, row.id, hostId, true, undefined, true);+ const charged = await chargedInterruption(engine, row, error);+ const failure = charged?.failure ? withAttempt(charged.failure, 'publication') : undefined;+ await markRecovering(engine, row, failure ? 'publication_failed' : 'publication_not_started', failure);+ const recovered = await recoverPublication(engine, row.id, hostId, true, failure, true);if (recovered.state === 'queued' && !recovered.recovery) requeued.push(row.id);} catch { /* the recovery record stays; the worktree waits for the recovery scan */ }}@@ -450,7 +460,9 @@ export async function publishSingleWrite(engine: BrainEngine, row: WriteRequest,}/** A group publication: its committed receipts, or why it did not commit and, for a member's own refusal, which member. */-export type GroupPublication = { done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure; culprit?: { index: number; error: unknown } };+export type GroupPublication = { done: WriteRequest[] | null; requeued: string[]; reason?: GroupFailure; culprit?: { index: number; error: unknown };+ /** A transient interruption ended the group while every claim was still held (nothing recorded): a lane release charges it. */+ interrupted?: TransientInterruption };/** Why a group transaction did not commit, for the lane fallback and step-down. */export type GroupFailure = 'busy' | 'predecessor_requeued' | 'wounded' | 'order_timeout' | 'lock_timeout' | 'statement_timeout' | 'failed';function groupFailure(error: unknown): GroupFailure {@@ -465,7 +477,8 @@ function groupFailure(error: unknown): GroupFailure {* that found the worktree busy, releases its claims so it runs first. Lock and statement timeouts cost one lane for the* rest of the drain.*/-async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution): Promise<false | null> {+async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: GroupFailure | undefined, run: GroupExecution,+ interrupted?: TransientInterruption): Promise<false | null> {if (run.lane) run.lane.fallbacks++;// #6402 residual (P4.3): a server fault on the lane group is kept on the rows it releases (`blocked_reason` `lane_<fault>`).const laneFault = reason === 'lock_timeout' || reason === 'statement_timeout' ? reason : null;@@ -476,7 +489,13 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G// A group that found the worktree busy (another holder or no publication capacity) releases its claims and is// claimed again as a lane head; publishing its members one at a time would hold the lanes back.if (prior !== null && ['committed', 'failed', 'conflict', 'cancelled'].includes(prior) && reason !== 'busy') return null;- for (const row of rows) await releaseUnpublishedClaim(engine, row, laneFault ? laneFaultBlockedReason(laneFault) : 'group_member_waiting');+ const blocked = laneFault ? laneFaultBlockedReason(laneFault) : 'group_member_waiting';+ for (const row of rows) {+ // LPH (b)/(c): a transient interruption is charged on release, so a lane group the ceiling cancels every time is bounded too.+ const charged = interrupted ? await releaseChargedInterruption(engine, row, undefined, 'publication', blocked, interrupted) : null;+ if (charged) { if (['failed', 'conflict', 'cancelled', 'committed'].includes(charged.state)) run.settled(charged); continue; }+ await releaseUnpublishedClaim(engine, row, blocked);+ }return false;}@@ -760,7 +779,7 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequesif (!publishing.length) return true;continue;}- if (run.lane && await laneFallback(engine, publishRows, result.reason, run) !== null) return progressed;+ if (run.lane && await laneFallback(engine, publishRows, result.reason, run, result.interrupted) !== null) return progressed;break;}} else if (run.lane && await laneFallback(engine, liveRows, 'failed', run) !== null) return progressed;diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c79da27103..ea19e3869e 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -882,12 +882,13 @@ export async function clearResolvedRecoveries(engine: BrainEngine, rows: WriteRefor (const row of resolved) if (!cleared.has(row.id)) await clearResolvedRecovery(engine, row.id);}-/** #6007: claims again a request this owner pass released to the queue itself, while it still holds the worktree's native lock. */+/** #6007: claims again a request this owner pass released to the queue itself, while it still holds the worktree's native lock; never before its backoff (LPH b). */export async function reclaimReleasedWrite(engine: BrainEngine, id: string, leaseMs = 30_000): Promise<WriteRequest | null> {const token = randomUUID();const [claimed] = await engine.executeRawDirect<WriteRequest>(`UPDATE persistence_requests SET state='running',execution_token=$2::uuid,claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL,claim_phase=$4::text::jsonb- WHERE id=$1::uuid AND state='queued' AND recovery IS NULL AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`, [id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);+ WHERE id=$1::uuid AND state='queued' AND recovery IS NULL AND ${BACKOFF_ELAPSED('persistence_requests')} AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING *`,+ [id, token, leaseMs, claimPhaseStamp(startClaimPhase(), token)]);return claimed ?? null;}diff --git a/src/core/schema-migrations/v261-persistence-request-transient-retries.ts b/src/core/schema-migrations/v261-persistence-request-transient-retries.tsindex 3fd7fb47f0..63a04edec4 100644--- a/src/core/schema-migrations/v261-persistence-request-transient-retries.ts+++ b/src/core/schema-migrations/v261-persistence-request-transient-retries.ts@@ -12,13 +12,15 @@ import type { Migration } from './types.ts';// a claim skips a queued row until then. Column-only, no backfill: existing rows// start at 0 and NULL (claimable now). Like v217 and v220 the columns are// migration-created (the `persistence_requests` CREATE TABLE of src/schema.sql-// carries only the original columns) and no index references them.+// carries only the original columns) and no index references them. No CHECK on+// the counter: on Postgres an inline CHECK validates every existing row under the+// ACCESS EXCLUSIVE lock the ALTER takes, and only an increment ever writes it.export const v261: Migration = {version: 261,name: 'persistence_request_transient_retries',idempotent: true,sql: `- ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS transient_interruptions integer NOT NULL DEFAULT 0 CHECK (transient_interruptions >= 0);+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS transient_interruptions integer NOT NULL DEFAULT 0;ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS next_attempt_at timestamptz;`,};diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex f68e359aae..55eb8c97ed 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -320,7 +320,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex 27fd5b46c5..e3f5fad459 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -320,7 +320,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 2673fe4297..c239a503bf 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -320,7 +320,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex e1a346cc30..3bbd58903a 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -324,7 +324,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex efee1ef849..cce0dc9744 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -324,7 +324,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex bf4ce7079a..403893e71c 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -324,7 +324,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex 7f3af13b1d..37ca702351 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -320,7 +320,6 @@"persistence_requests.persistence_requests_sequence_key": "u UNIQUE (sequence)","persistence_requests.persistence_requests_state_check": "c CHECK ((state = ANY (ARRAY['queued'::text, 'running'::text, 'recovering'::text, 'committed'::text, 'conflict'::text, 'failed'::text, 'cancelled'::text])))","persistence_requests.persistence_requests_target_kind_check": "c CHECK ((target_kind = ANY (ARRAY['page'::text, 'skill_bundle'::text])))",- "persistence_requests.persistence_requests_transient_interruptions_check": "c CHECK ((transient_interruptions >= 0))","persistence_requests.persistence_requests_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)","persistence_source_bindings.persistence_source_bindings_pkey": "p PRIMARY KEY (source_id)","persistence_source_bindings.persistence_source_bindings_worktree_id_fkey": "f FOREIGN KEY (worktree_id) REFERENCES persistence_worktrees(id)",diff --git a/test/pathological/lp-b-transient-retry-budget.test.ts b/test/pathological/lp-b-transient-retry-budget.test.tsindex 04beb00f3f..cf2e5eb2ed 100644--- a/test/pathological/lp-b-transient-retry-budget.test.ts+++ b/test/pathological/lp-b-transient-retry-budget.test.ts@@ -34,7 +34,7 @@ import { operations, type OperationContext } from '../../src/core/operations.ts'import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';-import { hasClaimableWrite } from '../../src/core/persistence/journal.ts';+import { hasClaimableWrite, reclaimReleasedWrite, releaseUnpublishedClaim } from '../../src/core/persistence/journal.ts';import { readHeadBlockers } from '../../src/core/persistence/head-blocker.ts';import { localHostId } from '../../src/core/persistence/identity.ts';import * as budget from '../../src/core/persistence/preparation-budget.ts';@@ -154,6 +154,28 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}expect(await call({ slug: `db/after-${n}`, content: page(`After ${n}`), request_id: randomUUID() })).toMatchObject({ state: 'committed' });}, 180_000);+ test('an owner pass never reclaims a released row before its backoff (reclaimReleasedWrite); once it elapses it does', async () => {+ const slug = `db/reclaim-${++n}`, requestId = randomUUID();+ const observed: { early?: unknown; due?: string | null } = {};+ let claims = 0;+ installFaultHook(async (point, detail) => {+ if (detail.requestId !== requestId) return;+ if (point === 'consumer:preparing' && ++claims === 1) throw interruption('57014');+ if (point === 'persistence:interruption_charged') {+ const [queued] = await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ observed.early = await reclaimReleasedWrite(engine, queued!.id);+ await engine.executeRaw('UPDATE persistence_requests SET next_attempt_at=now() WHERE id=$1::uuid', [queued!.id]);+ const due = await reclaimReleasedWrite(engine, queued!.id);+ observed.due = due?.state ?? null;+ if (due) await releaseUnpublishedClaim(engine, due, 'database_contention');+ }+ });+ expect(await call({ slug, content: page(`Reclaim ${n}`), request_id: requestId })).toMatchObject({ state: 'committed' });+ expect(observed.early).toBeNull();+ expect(observed.due).toBe('running');+ expect(claims).toBe(2);+ }, 180_000);+test('the backoff holds no claim: until next_attempt_at the row is not claimable and its head blocker says transient_backoff; then it is claimed and commits', async () => {const slug = `db/held-off-${++n}`, requestId = randomUUID();const observed: { blocker?: unknown; claimable?: boolean; reclaimedAfterBackoff?: boolean } = {};diff --git a/test/pathological/lp-c-publication-ceiling-retry.test.ts b/test/pathological/lp-c-publication-ceiling-retry.test.tsindex 4d5e2741be..27012d03de 100644--- a/test/pathological/lp-c-publication-ceiling-retry.test.ts+++ b/test/pathological/lp-c-publication-ceiling-retry.test.ts@@ -23,7 +23,7 @@*/import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import type { BrainEngine } from '../../src/core/engine.ts';@@ -32,6 +32,7 @@ import { operations, type OperationContext } from '../../src/core/operations.ts'import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { importManagedFiles } from '../../src/core/persistence/import-mutations.ts';import * as publicationDeadline from '../../src/core/persistence/publication-deadline.ts';import { resetWriteSwitches } from '../../src/core/persistence/switches.ts';import { _resetWriteThroughCacheForTest } from '../../src/core/write-through.ts';@@ -168,6 +169,44 @@ for (const { backend, databaseUrl } of pathologicalArms()) describe(`[${backend}expect(await engine.readPageSnapshot(slug, { sourceId })).toEqual(before);}, 180_000);+ test('a grouped import whose group publication overruns every time charges each member once per publication and ends write_interrupted after the cap', async () => {+ await engine.setConfig('persistence.max_transient_retries', '2');+ resetWriteSwitches();+ const dir = `grp-${++n}`;+ mkdirSync(join(brainDir, dir), { recursive: true });+ const files = ['a', 'b'].map(name => {+ const sourcePath = `${dir}/${name}.md`;+ writeFileSync(join(brainDir, sourcePath), page(`Group ${name} ${n}`));+ return { filePath: join(brainDir, sourcePath), sourcePath };+ });+ // Every publication in this source parks past the ceiling, then fails as a discarded connection; each is one interruption.+ const publications: string[] = [], claims = new Map<string, number>();+ installFaultHook(async (point, detail) => {+ if (detail.sourceId !== sourceId) return;+ if (point === 'consumer:preparing') { claims.set(detail.requestId!, (claims.get(detail.requestId!) ?? 0) + 1); return; }+ if (point === 'publication:before_commit' && publications.length < GUARD) {+ publications.push(detail.requestId!);+ await new Promise(resolve => setTimeout(resolve, PARK_MS));+ throw discarded();+ }+ });+ const results = await withEnv({ GBRAIN_HOME: home }, () => importManagedFiles(engine, files, { sourceId, noEmbed: true }));+ installFaultHook(undefined);+ expect(results.map(result => result.status === 'rejected' ? (result.reason as { code?: string }).code : result.status)).toEqual(['write_interrupted', 'write_interrupted']);+ const rows = await engine.executeRaw<{ request_id: string; state: string; error_code: string | null; transient_interruptions: number; detail: Record<string, unknown> | string }>(+ "SELECT request_id::text AS request_id,state,error_code,transient_interruptions,error_detail AS detail FROM persistence_requests WHERE source_id=$1 AND intent->>'import_batch' IS NOT NULL ORDER BY sequence", [sourceId]);+ expect(rows.length).toBe(2);+ for (const member of rows) {+ expect(member).toMatchObject({ state: 'failed', error_code: 'write_interrupted', transient_interruptions: 3 });+ expect(typeof member.detail === 'string' ? JSON.parse(member.detail) : member.detail).toMatchObject({ cause: 'publication_ceiling', attempts: 3, limit: 2 });+ // One claim per interruption: a cancelled group publication is never published again under the same claim.+ expect(claims.get(member.request_id)).toBe(3);+ }+ // Every publication was charged: each member took part in at most its three charged interruptions.+ expect(publications.length).toBeLessThanOrEqual(6);+ for (const { sourcePath } of files) expect(await engine.readPageSnapshot(sourcePath.replace(/\.md$/, ''), { sourceId })).toBeNull();+ }, 180_000);+test('a single overrun is retried, never a terminal storage_error (on Postgres the retried publish surfaces as a bare AbortError), and commits', async () => {const slug = `wt/overrun-once-${++n}`;expect(await call({ slug, content: page(`Prior ${n}`), request_id: randomUUID() }, sourceId)).toMatchObject({ state: 'committed' });