Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 2 (L5): the post-checkpoint tail runs after the drain lease is released; no_admission is retired

garrytanc610296a7114
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index a527e65632..e48625b04a 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -496,7 +496,7 @@ export type ManagedDelegationOutcome =
| { kind: 'delegated'; result: SyncResult; pid: number }
/** Not delegated; `reason` names the rung, `line` is the one line printed (null when nothing was printed). */
| { kind: 'own_consumer'; reason: 'opted_out' | 'not_host' | 'not_postgres' | 'not_managed' | 'no_owner' | 'owner_not_serve' | 'probe_failed'
- | 'kill_switch' | 'unsupported_flag' | 'no_socket' | 'older_serve' | 'serve_refused' | 'serve_lost' | 'serve_no_admission'; line: string | null };
+ | 'kill_switch' | 'unsupported_flag' | 'no_socket' | 'older_serve' | 'serve_refused' | 'serve_lost'; line: string | null };
/**
* #6543: only a forced rung (the serve cannot take the run) really runs a consumer beside the serve; on the others this
@@ -621,13 +621,6 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:
if (polled.kind === 'lost') return own('serve_lost', '[sync] continuing the catch-up with this process\'s own consumer; the durable cursor resumes where the serve left it.');
if (polled.kind === 'failed') throw polled.error;
const { result, pagesAffectedTotal } = syncResultFromWire(polled.result);
- // #6405/#6423: a delegated drain that admitted nothing left no request a publisher could still be writing, so this run
- // takes the catch-up over with its own consumer, once (the fallback itself never delegates). A publication that never
- // returned is different: the serve may still hold its locks, so that stop is reported as it is (restart the serve).
- if (result.drain?.stop_reason === 'drain_stalled' && result.drain.stall?.cause === 'no_admission') {
- return own('serve_no_admission', `[sync] the serve (PID ${pid}) admitted no write for ${result.drain.stall.stalled_seconds}s${result.drain.stall.step ? ` at step ${result.drain.stall.step}` : ''}; `
- + 'continuing the catch-up with this process\'s own consumer, once (the durable cursor resumes where the serve left it).');
- }
if (pagesAffectedTotal > polled.result.pagesAffected.length) {
serr(`[sync] (+${pagesAffectedTotal - polled.result.pagesAffected.length} more pages affected — list truncated for the IPC wire)`);
}
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 528fd86e68..5cfde14b8d 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -70,6 +70,8 @@ export interface SyncResult {
/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */
slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];
fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
+ /** #6712 PR 2 (L5): the owed post-checkpoint tail (statistics, links) this call ran after releasing the lease; a degraded tail carries its notice. */
+ tail?: Omit<import('../core/persistence/sync-tail.ts').SyncTailReport, 'links'>;
/** #5459 (P4.5): live pages a `--full` tree walk kept because their file is in the working tree and their import provenance is the working tree or unknown. */
working_tree_kept?: number;
/**
diff --git a/src/commands/sync/perform.ts b/src/commands/sync/perform.ts
index 5aeca59acf..a431a077d8 100644
--- a/src/commands/sync/perform.ts
+++ b/src/commands/sync/perform.ts
@@ -143,8 +143,9 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi
};
// A dry run reads and previews only; it never waits for, or keeps out, a drainer.
if (outer.dryRun) return work(undefined);
+ const { withSyncTail } = await import('../../core/persistence/sync-tail.ts');
try {
- return await withDrainLease(engine, sourceId, {
+ return await withSyncTail(engine, sourceId, await withDrainLease(engine, sourceId, {
holder: outer.drainHolder ?? { kind: 'cli', id: null }, remote: currentSubmissionAuthority()?.kind === 'remote_generic',
...(outer.followDrainLease ? { follow: { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs } } : {}),
tty: process.stderr.isTTY === true,
@@ -155,7 +156,7 @@ async function performManagedBranch(engine: BrainEngine, outer: SyncOpts): Promi
? `[sync] source ${sourceId} is being drained by ${who}; following it until it finishes or this run's budget ends (one drainer per source; it resumes the same cursor). Ctrl-C stops following and leaves it running.`
: `[sync] following ${who}: ${done}.`);
},
- }, work);
+ }, work), { signal: outer.signal, deadlineAtMs: outer.deadlineAtMs });
} catch (err) {
if (err instanceof LockUnavailableError && err.lockId === lockKey) throw new SyncLockBusyError(await formatLockBusyMessage(engine, lockKey), lockKey);
throw err;
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index c8de79ddb8..0e55fe8d96 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -60,10 +60,11 @@ type PerSourceResult = {
* #6696 (A4): a sync receipt carries the capacity notices (60 s snapshot, at most once an hour per process per
* scope): under `--json` as rendered `notices`, otherwise as stderr lines.
*/
-async function syncCapacityNotices(engine: BrainEngine, json: boolean): Promise<{ notices?: unknown[] }> {
+async function syncCapacityNotices(engine: BrainEngine, json: boolean, result?: SyncResult): Promise<{ notices?: unknown[] }> {
const { capacityNotices } = await import('../../core/persistence/capacity-snapshot.ts');
const { cliRenderContext, renderNotice } = await import('../../core/agent-output.ts');
- const notices = (await capacityNotices(engine).catch(() => [])).map(notice => renderNotice(notice, cliRenderContext()));
+ // #6712 PR 2 (L5): a degraded post-checkpoint tail rides the same notices.
+ const notices = [...(result?.tail?.notice ? [result.tail.notice] : []), ...await capacityNotices(engine).catch(() => [])].map(notice => renderNotice(notice, cliRenderContext()));
if (!json) for (const notice of notices) process.stderr.write(`[gbrain notice ${notice.code}] ${notice.why}\n`);
return notices.length ? { notices } : {};
}
@@ -942,7 +943,7 @@ async function runSingleSourceSync(
process.stderr.write(` → embed-backfill submission failed: ${e instanceof Error ? e.message : String(e)}\n`);
}
}
- const capacity = await syncCapacityNotices(engine, jsonOut);
+ const capacity = await syncCapacityNotices(engine, jsonOut, result);
if (jsonOut) {
emitJson(JSON.stringify({ ...buildSingleSyncJsonEnvelope(sourceId, result, singleEmbedBackfill, singleCostGate),
...(result.managedWrite ? { managed_write: result.managedWrite } : {}), ...drainJsonFields(result, resumeCommand, sourceId), ...capacity }));
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 9b579eab25..6aa8e6c156 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -23,6 +23,11 @@ export interface CodeEntry {
why?: string;
/** Closed vocabulary for `reason` when one code covers several causes. */
reasons?: readonly string[];
+ /**
+ * Tombstones of reasons nothing emits any more (reason → the release that retired it); a receipt an older build wrote may
+ * still carry one, so it stays explained here, and it never returns to `reasons`.
+ */
+ retired_reasons?: Readonly<Record<string, string>>;
/** Repo-relative anchor; default `docs/guides/error-codes.md#<code>`. */
docs?: string;
/** Default prose suggestion when a site supplies none. */
@@ -173,7 +178,9 @@ export const CODES = {
drain_stalled: { class: 'server', retryable: false, actor: 'host_admin',
summary: "A managed sync drain stopped `blocked` because its head write made no progress (no committed receipt and no step advance) for the whole stall window.",
why: "A renewed lease is not progress: the detector keys on the head claim's phase and step. With a live owner on this host the drain prints `stalled <N>s on <step>` from the allowance (budget plus 30 s) and keeps going; it stops only when `persistence.preparation_ceiling_ms` passes without the root being released, or when that owner's heartbeat row reads wedged (`cause: owner_wedged_here`, with the owner's kind, pid and nonce and `retry_after_ms` to the ceiling, after which the owner frees the root and the next pass holds the entry). A lapsed claim (`owner_missing`) stops at once unless this host owns the checkout and a live full consumer can reclaim it, which gets one more window. `drain.stall.cause` names which.",
- reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress', 'no_admission'],
+ reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress'],
+ // #6712 PR 2: a pass that admits nothing with no unfinished request stops `no_progress`; an older build wrote `no_admission` for it.
+ retired_reasons: { no_admission: '0.60.256.0' },
docs: 'docs/guides/write-refusals.md#drain-stalled',
suggestion: 'Inspect the writer with gbrain sources writer status --source <id> --json (read-only: the owner process, its step and what it waits on, and the next action). Before the ceiling (`next.safe_to_loop` true) rerun next.command after retry_after_ms; past it, or with a wedged owner, restart the named owner process on the brain host and rerun the same sync.',
fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', '{source_id}', '--json'], consent: [], actor: 'agent', why: "Read-only: names the owner process holding the head write (kind, pid), its step and wait cause, and ends in a next_action.", requires_exclusive: false,
@@ -609,6 +616,7 @@ export const NOTICE_CODES = {
first_run_decisions: { kind: 'ask', summary: 'init finished (or a stdio MCP session started on a brain with open decisions); the first-run decisions (search mode, writeback, harness wiring, skills) carry defaults the user may change. The one muteable ask.' },
first_run_decisions_muted: { kind: 'info', summary: 'First-run decisions are still open, but the user muted them; the fix shows them again (`gbrain notices unmute first_run_decisions`).' },
migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
+ sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source <id>`, or doctor for the statistics).' },
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
record_types_undeclared: { kind: 'info', summary: 'entity.record_types names a page type that neither the schema pack declares nor any page uses, so no record of that type is listed.' },
diff --git a/src/core/persistence/drain-step.ts b/src/core/persistence/drain-step.ts
index 698659d777..12efb3f0d9 100644
--- a/src/core/persistence/drain-step.ts
+++ b/src/core/persistence/drain-step.ts
@@ -1,18 +1,15 @@
/**
* #6423: the step this process's managed-sync pass is in, process-local. A pass that admits nothing (a transaction-mode
* pooler that never answers a pipelined waiver run) leaves no claim on any request for the drain's head probe to read, so
- * the in-pass governor in `sync-drain.ts` names this step and the last statement label on its `no_admission` stop.
- * #6696 C4: `finish` is the tail after the run's checkpoint committed (statistics, link extraction); it admits nothing by
- * design, so the governor gives it `FINISH_BUDGET_MS` instead of reading it as `no_admission`.
+ * the in-pass governor in `sync-drain.ts` names this step and the last statement label on its `no_progress` stop, and a
+ * pass it abandoned throws at its next step boundary. #6712 PR 2: the tail after a committed checkpoint (statistics, links)
+ * runs after the lease is released (`sync-tail.ts`), so no step covers it.
*/
import { sqlLabel } from './claim-phase.ts';
-export type DrainStep = 'freeze' | 'waiver_run' | 'admission' | 'await_receipt' | 'finish';
+export type DrainStep = 'freeze' | 'waiver_run' | 'admission' | 'await_receipt';
export interface DrainStepStamp { step: DrainStep; since: number; last_sql: { label: string; at: number } | null }
-/** #6696 C4: the link-extraction budget of the tail after a committed checkpoint; the governor allows it plus `STALL_GRACE_MS`. */
-export const FINISH_BUDGET_MS = 5 * 60_000;
-
let current: DrainStepStamp | null = null;
/** The reason the in-pass governor aborts the pass it abandons. */
diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.ts
index 74a4ee876e..6f967d6e58 100644
--- a/src/core/persistence/fault-points.ts
+++ b/src/core/persistence/fault-points.ts
@@ -24,6 +24,8 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect
// #6712 PR 1: after a pass took the source's drain lease (before it reads the cursor); after each cursor the fan-in
// superseded is retired (before the next one), and after a pass stamped its authority on a cursor another writer started.
| 'sync:lease_acquired' | 'sync:cursor_adopted'
+ // #6712 PR 2 (L5): after the drain lease is released, before the owed tail (statistics, links) of a committed checkpoint runs.
+ | 'sync:tail_started'
// #6511: the page purge's in-transaction journal lookups (page-purge.ts `journalLookup`); a hook that throws a 57014 models a statement timeout there.
| 'purge:slug_lookup' | 'purge:tail_recheck' | 'purge:pending_recheck' | 'purge:redaction_read'
// #6511: before each keyset chunk of the preparation-time journal sweep (a stalling hook models a slow chunk), and the fact purge's planning read.
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index 667e05730f..56eb50f267 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -23,7 +23,7 @@ import { ERROR_CATALOGUE, type CatalogueName } from '../error-catalogue.ts';
import { cliRenderContext, renderAction, type Action, type RenderedAction } from '../agent-output.ts';
import { managedSyncResumeArgs, syncResumeCommand } from '../sync-reconcile.ts';
import { isWriteCapacityWait, outstandingCapacityOf } from './admission-retry.ts';
-import { clearDrainStep, DrainPassAbandoned, FINISH_BUDGET_MS, markPassAbandoned, readDrainStep } from './drain-step.ts';
+import { clearDrainStep, DrainPassAbandoned, markPassAbandoned, readDrainStep } from './drain-step.ts';
import { PUBLICATION_CEILING_DEFAULT_MS, readPublicationCeilingMs } from './publication-deadline.ts';
import { isOwnerThisProcess, stampLastSql, WAITING_ON, type ClaimLastSql, type WaitingOn } from './claim-phase.ts';
import { describeHostConsumer, headBlockedNext, headBlockerText, headClaimability, type HeadBlocker } from './head-blocker.ts';
@@ -106,9 +106,9 @@ export interface DrainStall {
* #6278: why the drain called it a stall: no renewal (`owner_missing`), a preparation or publication past its allowance, or no change at all.
* #6317: `owner_wedged_here` is a live same-host owner whose preparation passed the ceiling, or whose own heartbeat row says it is wedged
* (`restart_required`, a root barrier past the ceiling); `preparation_overdue` is kept for an owner on another host.
- * #6423: `no_admission` is a pass that admitted nothing and left no unfinished request for the whole no-progress window.
+ * #6712 PR 2: a pass that admitted nothing and left no unfinished request is `no_progress` too (`no_admission` is retired).
*/
- cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'no_admission' | 'head_blocked';
+ cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'head_blocked';
/** #6405/#6423: the in-pass governor ended a pass that never returned (the pass was aborted and its late result is ignored). */
in_pass?: boolean;
/** #6317: the head owner as the stamp names it, so the stop can say which process to restart. */
@@ -330,8 +330,6 @@ export interface DrainInput {
stallMs?: number;
/** #6405/#6423 test seams: the in-pass no-progress window, the publication ceiling and how often the in-pass governor looks. */
noProgressMs?: number;
- /** #6696 C4: how long the tail after a committed checkpoint (drain step `finish`) may run before the governor stops it `no_progress`. */
- finishMs?: number;
publicationCeilingMs?: number;
governMs?: number;
/** Test seam: the drain's clock for commit times, stall windows and the governor's quiet time (its timers still tick on real time). */
@@ -434,7 +432,6 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
// the abandoned pass: its signal is aborted (the pass's step boundaries throw, so it admits and writes nothing more) and its
// late result or rejection is dropped.
const noProgressMs = input.noProgressMs ?? IN_PASS_NO_PROGRESS_MS, ceilingMs = input.publicationCeilingMs ?? PUBLICATION_CEILING_DEFAULT_MS;
- const finishMs = input.finishMs ?? FINISH_BUDGET_MS + STALL_GRACE_MS;
const governedPass = (): Promise<{ result: SyncResult } | { stall: DrainStall } | { deadline: true }> => {
const controller = new AbortController(), passStartedAt = clock();
const passSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
@@ -478,11 +475,10 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
const print = read.ok ? head ? `${head.head_state}|${claim?.phase ?? ''}|${claim?.step ?? ''}|${claim?.lapsed ?? ''}` : 'none' : 'unreadable';
if (print !== key) { key = print; keySince = now; }
const elapsed = now - Math.max(keySince, lastCommitAt, passStartedAt);
- const finishing = step?.step === 'finish', windowMs = finishing ? finishMs : noProgressMs;
- if (quiet < windowMs || elapsed < windowMs && key !== 'none') return;
+ if (quiet < noProgressMs || elapsed < noProgressMs && key !== 'none') return;
const sql = step?.last_sql ? { label: step.last_sql.label, age_ms: now - step.last_sql.at } : claim?.last_sql ?? null;
stop({ ...base, stalled_seconds: Math.round(quiet / 1000), phase: claim?.phase ?? null, step: head ? claim?.step ?? null : step?.step ?? null,
- waiting_on: claim?.waiting_on ?? null, cause: read.ok && !head && !finishing ? 'no_admission' : claim?.lapsed ? 'owner_missing' : 'no_progress',
+ waiting_on: claim?.waiting_on ?? null, cause: claim?.lapsed ? 'owner_missing' : 'no_progress',
owner_pid: claim?.owner_pid ?? null, owner_kind: claim?.owner_kind ?? null, owner_nonce: claim?.owner_nonce ?? null, last_sql: sql });
}).finally(() => { probing = false; });
}, governEvery);
@@ -790,12 +786,6 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
const laneRun = bulk.enabled && (bulk.lanes ?? 1) > 1 ? randomUUID() : undefined;
const { closeLaneRun } = await import('./sync-lanes.ts');
const publicationCeilingMs = await readPublicationCeilingMs(engine);
- // #6423: the sync's own waiver runs and admissions use the ordinary pool even where the consumer has a direct route.
- if (announce) {
- const { consumerConnectionRoute } = await import('./consumer-lane.ts');
- if (consumerConnectionRoute(engine).pooler_mode === 'transaction') serr('[sync] this sync admits its writes through a transaction-mode pooler (prepare=false, port 6543); '
- + `a round trip it never answers stops the drain no_admission after ${formatDuration(IN_PASS_NO_PROGRESS_MS / 1000)}. A session-mode (5432) or direct database URL avoids it.`);
- }
let result: SyncResult | undefined;
// #6696 (A7): the first pass checks the run's estimated receipts against the capacity left before any admission.
let preflighted = false;
@@ -1027,15 +1017,6 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
+ `Run the sync from a process that can write the source's lock directory (the owner's gbrain serve, or this command outside the sandbox), then rerun: ${resumeCommand}`,
...(docs ? { docs } : {}) };
}
- // #6423: the pass admitted nothing for the whole window; the step and statement name where it waited.
- if (d?.stop_reason === 'drain_stalled' && d.stall?.cause === 'no_admission') {
- const stall = d.stall;
- return { command: resumeCommand, safe_to_loop: false, retry_after_ms: 0, ...estimate, code: 'drain_stalled', cause: 'no_admission',
- why: `The sync admitted no write for ${stall.stalled_seconds}s${stall.step ? ` while at step ${stall.step}` : ''}${stall.last_sql ? ` (last statement ${stall.last_sql.label})` : ''}, and no request for this source was unfinished, `
- + 'so it stopped instead of waiting forever. A transaction-mode pooler (port 6543) that never answers a round trip does this. The cursor and its frozen manifest are intact. '
- + `Point the brain's database URL at the session-mode (port 5432) or direct URL of the same database (GBRAIN_DIRECT_DATABASE_URL routes only the consumer, not the sync's own admissions), check it with gbrain doctor --json, then rerun: ${resumeCommand}`,
- ...(docs ? { docs } : {}) };
- }
const writerBlocked = d?.stop_reason && d.stop_reason !== 'blocked_by_failures' && d.stop_reason !== 'deadline';
if (writerBlocked) {
return { command: `gbrain sources writer status ${sourceId}`, safe_to_loop: false, retry_after_ms: 0, ...estimate,
@@ -1082,8 +1063,8 @@ export function formatDrainSummary(result: SyncResult, resumeCommand: string, so
if (d.capacity) lines.push(` Waited ${d.capacity.waited_seconds}s for write capacity: ${d.capacity.outstanding ?? '?'} of ${d.capacity.limit ?? '?'} ${d.capacity.scope ?? 'principal'} outstanding-request slots in use.`);
if (d.connection) lines.push(` Database connection dropped ${d.connection.drops} times in a row (${d.connection.last_error}); the cursor and its frozen manifest are intact.`);
// #6317 (C3): the summary line carries the same step / waiting_on / last_sql triple as the log lines, and the owner process.
- if (d.stall?.cause === 'no_admission') lines.push(` Nothing admitted for ${d.stall.stalled_seconds}s${d.stall.step ? `, step=${d.stall.step}` : ''}${d.stall.last_sql ? `, last_sql=${d.stall.last_sql.label}` : ''}, cause=no_admission.`);
- else if (d.stall) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`
+ // #6712 PR 2: a pass that admitted nothing with no unfinished request (the retired no_admission) reads as such, with its step and statement.
+ if (d.stall) lines.push(`${d.stall.head_request_id === null && d.stall.request_id === 'none' ? ' No request of this source was unfinished' : ` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`}`
+ `${d.stall.blocked_reason ? `, blocked_reason=${d.stall.blocked_reason}` : ''}${d.stall.step ? `, step=${d.stall.step}` : ''}${d.stall.waiting_on ? `, waiting_on=${d.stall.waiting_on}` : ''}`
+ `${d.stall.last_sql ? `, last_sql=${d.stall.last_sql.label}${d.stall.last_sql.age_ms === null ? '' : ` (${Math.round(d.stall.last_sql.age_ms / 1000)}s ago)`}` : ''}`
+ `${d.stall.cause ? `, cause=${d.stall.cause}` : ''}${d.stall.owner_pid ? `, owner=${d.stall.owner_kind ?? 'process'} pid ${d.stall.owner_pid}` : ''}; claimable here: ${d.stall.claimable_here === null ? 'unknown' : d.stall.claimable_here ? 'yes' : 'no'}`
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index c826671c2c..7eac69cc60 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -44,6 +44,7 @@ import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source
import { checkpointRetryCommand, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { CURSOR_CHANGED_REFUSAL_MESSAGE, SYNC_CURSOR_FENCE_ORIGIN } from './sync-knock-on.ts';
import { checkpointCursorReplaced } from './sync-checkpoint-replaced.ts';
+import { recordSyncTail } from './sync-tail-record.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { chunkerStamp } from '../chunkers/code.ts';
import { clearGitHold, countGitHolds, recordSyncImportProvenance, syncDiskProvenance, syncImportParser, syncImportParserFor, type SyncImportProvenanceBase } from './sync-holds.ts';
@@ -468,6 +469,8 @@ async function applyManagedSyncCheckpoint(tx: BrainEngine, row: WriteRequest, p:
// #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.
if (settled && (p.from === null || p.syncOptions?.full === true)) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, chunkerStamp()]);
await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);
+ // #6712 PR 2 (L5): the tail (statistics, links) runs after the lease is released; it is owed from this commit on.
+ await recordSyncTail(tx, row.source_id, p.cursorKey, p.runId);
for (const path of p.releasedHolds ?? []) await releaseHold(tx, path);
return { status: 'synced', source_id: row.source_id, committed_pages: p.total };
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 069d75bb67..367c0a7d7a 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -23,17 +23,15 @@ import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority
import { prepareManagedSyncMutation, type SyncCursorOptions, type SyncIntent } from './sync-prepare.ts';
import { startClaimPhase } from './claim-phase.ts';
import { screeningRequest } from './noop-kernel.ts';
-import { FINISH_BUDGET_MS, stampDrainStep } from './drain-step.ts';
import { noopWaiversEnabled, prescreenedHead, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waivePrescreenedRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
import { existsSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
import { readCommittedBlob } from '../company-brain/revision.ts';
-import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-stats.ts';
import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, managedSyncRetryCommand, type ManagedSyncFailure, type ManagedSyncRootCause } from './sync-failures.ts';
import { writeFailureDiagnostic } from './verb-errors.ts';
-import { extractManagedStaleLinks } from './links-maintenance.ts';
+import { stampDrainStep } from './drain-step.ts';
import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import { principalKey, type WriteRequest } from './model.ts';
@@ -66,6 +64,7 @@ import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
import { receiptClass, resumableStop, stopRecorded } from './sync-stop-class.ts';
import { advanceHeld, committedPast, deletionSettled, entryOf, indexOf, promoteWindow, waivedCursor, withHeldKeys, withoutPending } from './sync-cursor-moves.ts';
+import { withSyncTail } from './sync-tail.ts';
import { assertDrainLease, currentDrainLease, leaseHeldResult, readDrainHolder, withDrainLease } from './sync-lease.ts';
import { LockStolenError, LockUnavailableError, syncLockId } from '../db-lock.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
@@ -1297,8 +1296,6 @@ async function cursorMovedAdmission(engine: BrainEngine, key: string, admitting:
*/
async function finishCheckpoint(engine: BrainEngine, key: string, cursor: Cursor, company: boolean, assertActive: () => void): Promise<SyncResult> {
await clearManagedSyncFailureAfterSuccess(engine, key);
- const changed = cursor.counts.added + cursor.counts.modified + cursor.counts.deleted;
- if (changed > 0) await refreshProjectionStatistics(engine, changed);
assertActive();
const scheduled = company ? [] : await readGitHoldRetryPaths(engine, cursor.sourceId, cursor.incarnation);
assertActive();
@@ -1395,6 +1392,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
const remote = currentSubmissionAuthority()?.kind === 'remote_generic';
return withDrainLease(engine, sourceId, { holder: opts.drainHolder ?? { kind: slice ? 'owner_slice' : 'cli', id: null }, remote },
signal => performManagedPass(engine, signal ? { ...opts, signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal } : opts, slice))
+ .then(result => withSyncTail(engine, sourceId, result, { signal: opts.signal, deadlineAtMs: opts.deadlineAtMs }))
.catch(async error => {
if (!(error instanceof LockUnavailableError) || error.lockId !== syncLockId(sourceId)) throw error;
return leaseHeldResult(sourceId, await readDrainHolder(engine, sourceId).catch(() => null), { remote });
@@ -1473,19 +1471,9 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
throwIfAborted(signal);
assertPersistenceAccepting(engine);
};
- // Links derive from committed pages once the checkpoint lands, in this owner
- // process, so forward references inside one run resolve and PGLite-delegated
- // syncs match Postgres. Content is already committed: a failure here leaves
- // the pages stale for `gbrain extract --stale` instead of failing the sync.
- // #6696 C4: the checkpoint committed, so the tail admits nothing; step `finish` and its progress event keep the drain's
- // governor from reading it as `no_admission`, and link extraction stops at the tail's own budget.
- const finishing = (done: Cursor) => { stampDrainStep('finish', signal); opts.onProgress?.({ phase: 'managed_sync.finish', bankedFiles: done.index, total: done.entries.length }); };
- const withLinks = async (done: Cursor, synced: SyncResult): Promise<SyncResult> => {
- if (company || (done.processingOptions ?? processingOptions).noExtract) return synced;
- try { return { ...synced, links: await extractManagedStaleLinks(engine, { sourceId: done.sourceId, maxPages: 1000, timeBudgetMs: FINISH_BUDGET_MS, signal, mentions: false,
- slugs: done.entries.flatMap(entry => entry.action === 'import' && entry.slug ? [entry.slug] : []) }) }; }
- catch { return synced; }
- };
+ // #6696 C4: the checkpoint commit is the run's last commit. #6712 PR 2 (L5): its tail (statistics, links) is owed from that
+ // commit (sync-tail.ts) and runs after the lease is released, outside this governed pass.
+ const finishing = (done: Cursor) => { opts.onProgress?.({ phase: 'managed_sync.finish', bankedFiles: done.index, total: done.entries.length }); };
try {
assertActive();
const resolved = await resolvePassCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, remote: authority.writer.remote, dryRun: !!opts.dryRun, assertActive, state });
@@ -1694,7 +1682,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (!cursor?.done) throw syncRunRefusal('storage_error', 'Committed sync checkpoint lost its cursor.',
{ sourceId: context.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? frozenRun.repoPath },
`The final checkpoint request ${pending.requestId} of this sync committed, but its cursor could not be read back to finish the run.`);
- finishing(cursor); return withLinks(cursor, await finishCheckpoint(engine, key, cursor, !!company, assertActive));
+ finishing(cursor); return finishCheckpoint(engine, key, cursor, !!company, assertActive);
}
// The frozen manifest is shared; only the cursor header changes per page.
const next: Cursor = committedPast({ ...cursor, ...committedBreaker(cursor), counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }, pending);
@@ -1713,7 +1701,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
batchPages = 0; batchStart = performance.now();
}
}
- finishing(cursor); return withLinks(cursor, result(cursor, cursor.from === null ? 'first_sync' : 'synced'));
+ finishing(cursor); return result(cursor, cursor.from === null ? 'first_sync' : 'synced');
} catch (error) {
assertSyncDispatchActive();
if (signal?.aborted && error instanceof Error && error.name === 'AbortError') {
diff --git a/src/core/persistence/sync-tail-record.ts b/src/core/persistence/sync-tail-record.ts
new file mode 100644
index 0000000000..081c82c691
--- /dev/null
+++ b/src/core/persistence/sync-tail-record.ts
@@ -0,0 +1,30 @@
+/**
+ * #6712 PR 2 (L5): the durable obligation of a committed checkpoint's tail (statistics, links; `sync-tail.ts` runs it). The
+ * checkpoint's own transaction records it, so a process that dies between that commit and the tail leaves it owed. Kept
+ * free of heavy imports: the checkpoint's publication (`sync-prepare.ts`) loads it.
+ */
+import type { BrainEngine } from '../engine.ts';
+
+export const SYNC_TAIL_OP = 'managed-sync-tail';
+/** Obligations kept per source; an older one folds into the stale-page scan every tail runs. */
+const SYNC_TAIL_KEEP = 16;
+
+export interface TailObligation { run_id: string; changed: number; extract: boolean; at: string }
+
+/** Inside the checkpoint's transaction: the run's tail is owed before anyone can read the run as synced. */
+export async function recordSyncTail(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, cursorKey: string, runId: string): Promise<void> {
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at)
+ SELECT $1, $2, jsonb_build_array(jsonb_build_object('run_id',$3::text,'at',now(),
+ 'changed',COALESCE((c.completed_keys->0->'counts'->>'added')::int,0)+COALESCE((c.completed_keys->0->'counts'->>'modified')::int,0)+COALESCE((c.completed_keys->0->'counts'->>'deleted')::int,0),
+ 'extract',COALESCE(c.completed_keys->0->'processingOptions'->>'noExtract','false')<>'true' AND c.completed_keys->0->>'companyReceiptId' IS NULL)), now()
+ FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=$4
+ ON CONFLICT (op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=CASE WHEN jsonb_array_length(op_checkpoints.completed_keys)>=${SYNC_TAIL_KEEP}
+ THEN (op_checkpoints.completed_keys-0)||EXCLUDED.completed_keys ELSE op_checkpoints.completed_keys||EXCLUDED.completed_keys END`,
+ [SYNC_TAIL_OP, sourceId, runId, cursorKey]);
+}
+
+/** The source's owed tail, or null when none is owed. */
+export async function readSyncTail(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<TailObligation[] | null> {
+ const [row] = await engine.executeRaw<{ completed_keys: TailObligation[] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [SYNC_TAIL_OP, sourceId]);
+ return row?.completed_keys?.length ? row.completed_keys : null;
+}
diff --git a/src/core/persistence/sync-tail.ts b/src/core/persistence/sync-tail.ts
new file mode 100644
index 0000000000..6ff2411b9b
--- /dev/null
+++ b/src/core/persistence/sync-tail.ts
@@ -0,0 +1,97 @@
+/**
+ * #6712 PR 2 (L5): the tail of a managed sync whose checkpoint committed: projection statistics and link extraction for the
+ * pages the run imported. It runs after the drain lease is released and outside the drain's in-pass governor, so a slow
+ * tail never holds the source or reads as a stalled pass. The checkpoint's own transaction records the obligation
+ * (`recordSyncTail`), so a process that dies between the checkpoint commit and the tail leaves it for the next tail on the
+ * source; the tail is bounded, and work it leaves undone stays durable (the obligation, and every unextracted page stays
+ * stale for `gbrain extract --stale`). A failed or truncated tail attaches one degraded notice with its fix; the run's
+ * outcome stays synced.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { Notice } from '../agent-output.ts';
+import { refreshProjectionStatistics } from '../search/projection-statistics.ts';
+import { extractManagedStaleLinks, type ManagedLinkExtraction } from './links-maintenance.ts';
+import { faultPoint } from './fault-points.ts';
+import { currentDrainLease } from './sync-lease.ts';
+import { readSyncTail, SYNC_TAIL_OP, type TailObligation } from './sync-tail-record.ts';
+import type { SyncResult } from '../../commands/sync.ts';
+
+/** The tail's link-extraction budget (it was the governed pass's `FINISH_BUDGET_MS`); a caller deadline shortens it. */
+export const SYNC_TAIL_BUDGET_MS = 5 * 60_000;
+/** Link extraction per tail, as before the move. */
+const SYNC_TAIL_MAX_PAGES = 1000;
+
+export interface SyncTailReport {
+ /**
+ * `done`: every step ran to the end; `truncated`: links stopped at the budget (the rest stay stale); `degraded`: the planner
+ * statistics could not be refreshed (doctor's check owns it); `deferred`: the caller's deadline left no budget, and `failed`:
+ * a step threw (both keep the obligation for the next tail).
+ */
+ status: 'done' | 'truncated' | 'degraded' | 'deferred' | 'failed';
+ runs: number;
+ statistics: 'refreshed' | 'not_needed' | 'failed';
+ links?: ManagedLinkExtraction;
+ notice?: Notice;
+}
+
+/**
+ * Runs the source's owed tail, bounded by `budgetMs` and the caller's deadline. Never throws: a failure is the report's
+ * `failed` status and its notice. The obligation is cleared (compare-and-swap) only when every step ran; a checkpoint
+ * that committed meanwhile keeps its own.
+ */
+export async function runSyncTail(engine: BrainEngine, sourceId: string, opts: { signal?: AbortSignal; deadlineAtMs?: number; budgetMs?: number } = {}): Promise<SyncTailReport | null> {
+ let owed: TailObligation[] | null;
+ try { owed = await readSyncTail(engine, sourceId); } catch { return null; }
+ if (!owed) return null;
+ const budgetMs = Math.max(0, Math.min(opts.budgetMs ?? SYNC_TAIL_BUDGET_MS, opts.deadlineAtMs === undefined ? Infinity : opts.deadlineAtMs - Date.now()));
+ const changed = owed.reduce((sum, item) => sum + (Number(item.changed) || 0), 0);
+ const extract = owed.some(item => item.extract);
+ let statistics: SyncTailReport['statistics'] = 'not_needed', links: ManagedLinkExtraction | undefined, failure: string | null = null, linksStarted = 0;
+ try {
+ await faultPoint('sync:tail_started', { sourceId });
+ if (changed > 0) statistics = await refreshProjectionStatistics(engine, changed) ? 'refreshed' : 'failed';
+ if (extract && budgetMs > 0) {
+ const slugs = (await engine.executeRaw<{ slug: string }>(`SELECT DISTINCT e->>'slug' AS slug FROM op_checkpoints m, jsonb_array_elements(m.completed_keys) e
+ WHERE m.op='managed-sync-manifest' AND m.fingerprint=ANY($1::text[]) AND e->>'action'='import' AND e->>'slug' IS NOT NULL`, [owed.map(item => item.run_id)])).map(row => row.slug);
+ linksStarted = Date.now();
+ links = await extractManagedStaleLinks(engine, { sourceId, maxPages: SYNC_TAIL_MAX_PAGES, timeBudgetMs: budgetMs, signal: opts.signal, mentions: false, slugs });
+ }
+ } catch (error) {
+ failure = error instanceof Error ? error.message : String(error);
+ }
+ const ran = failure === null && (!extract || links !== undefined);
+ if (ran) await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 AND completed_keys=$3::text::jsonb', [SYNC_TAIL_OP, sourceId, JSON.stringify(owed)]).catch(() => undefined);
+ const status: SyncTailReport['status'] = failure !== null ? 'failed' : !ran ? 'deferred' : links && links.remaining > 0 && (Date.now() - linksStarted >= budgetMs || links.pages + links.skipped >= SYNC_TAIL_MAX_PAGES) ? 'truncated' : statistics === 'failed' ? 'degraded' : 'done';
+ return { status, runs: owed.length, statistics, ...(links ? { links } : {}), ...(status === 'done' ? {} : { notice: tailNotice(sourceId, status, { statistics, links, failure }) }) };
+}
+
+function tailNotice(sourceId: string, status: Exclude<SyncTailReport['status'], 'done'>, d: { statistics: SyncTailReport['statistics']; links?: ManagedLinkExtraction; failure: string | null }): Notice {
+ const extract = { argv: ['gbrain', 'extract', '--stale', '--source', sourceId], consent: [], actor: 'agent' as const, requires_exclusive: false,
+ why: 'Derives links for the pages this sync imported that are still stale; it changes no page content.',
+ verify: { argv: ['gbrain', 'extract', '--stale', '--source', sourceId, '--dry-run'] } };
+ if (status === 'truncated') {
+ return { code: 'sync_tail_degraded', kind: 'degraded', fix: extract,
+ why: `The sync of source ${sourceId} is synced, but link extraction stopped at its budget with ${d.links!.remaining} page(s) still stale; their links and backlinks are missing until they are extracted.` };
+ }
+ if (status === 'degraded') {
+ return { code: 'sync_tail_degraded', kind: 'degraded',
+ fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Names the planner-statistics check and the database-owner step that fixes it; changes nothing.' },
+ why: `The sync of source ${sourceId} is synced, but the search planner statistics could not be refreshed (database-owner maintenance is required), so searches may plan slowly.` };
+ }
+ const what = status === 'deferred' ? 'link extraction did not start (the run\'s deadline had passed)' : `the post-sync step failed (${d.failure ?? 'unknown error'})`;
+ return { code: 'sync_tail_degraded', kind: 'degraded', fix: extract,
+ why: `The sync of source ${sourceId} is synced, but ${what}; the step stays scheduled, the next sync of this source runs it again, and the fix runs the links now.` };
+}
+
+/**
+ * After the drain lease is released: runs the source's owed tail and folds it into the result (`tail`, and `links` when
+ * links ran). A dry run, a run that never held the lease (a follower) and a call still inside a lease (its holder runs
+ * the tail) run none.
+ */
+export async function withSyncTail(engine: BrainEngine, sourceId: string, result: SyncResult, opts: { signal?: AbortSignal; deadlineAtMs?: number } = {}): Promise<SyncResult> {
+ if (result.status === 'dry_run' || result.leaseHeld || currentDrainLease(sourceId)) return result;
+ const tail = await runSyncTail(engine, sourceId, opts);
+ if (!tail) return result;
+ const { links, ...report } = tail;
+ return { ...result, tail: report, ...(links ? { links } : {}) };
+}
diff --git a/test/error-registry-6317-contract.test.ts b/test/error-registry-6317-contract.test.ts
index bbe50be5e7..7ceb94aa20 100644
--- a/test/error-registry-6317-contract.test.ts
+++ b/test/error-registry-6317-contract.test.ts
@@ -95,7 +95,9 @@ describe('#6317 codes are registered with a full envelope', () => {
describe('drain_stalled: the same-host stop has a cause vocabulary and a filled writer-status fix', () => {
test('owner_wedged_here is a registered reason beside the earlier causes, and the row says what changed', () => {
const entry = CODES.drain_stalled as CodeEntry;
- expect(entry.reasons).toEqual(['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress', 'no_admission']); // #6423: the in-pass governor's no-admission stop
+ expect(entry.reasons).toEqual(['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress']);
+ // #6712 PR 2: the in-pass governor's no-admission stop (#6423) is `no_progress` now; the retired reason keeps its tombstone.
+ expect(entry.retired_reasons).toEqual({ no_admission: '0.60.256.0' });
expect(entry.why).toContain('owner_wedged_here');
expect(entry.why).toContain('retry_after_ms');
expect(entry.why).not.toContain('nothing here can claim it');
diff --git a/test/sync-drain-finish-tail.test.ts b/test/sync-drain-finish-tail.test.ts
index 7300b2820d..e4b6889000 100644
--- a/test/sync-drain-finish-tail.test.ts
+++ b/test/sync-drain-finish-tail.test.ts
@@ -1,8 +1,9 @@
/**
- * #6696 C4: a managed sync whose checkpoint committed and whose manifest is exhausted still runs a tail (projection
- * statistics, link extraction) that admits nothing. The in-pass governor read that tail as `no_admission` and stopped a
- * finished run `blocked`, blaming the pooler. The pass now stamps drain step `finish` and emits `managed_sync.finish`
- * once the checkpoint commits; the tail runs under its own budget, and a pass stuck in admission still stops.
+ * #6696 C4 / #6712 PR 2 (L5): the tail of a managed sync whose checkpoint committed (projection statistics, link extraction).
+ * C4 kept it inside the governed pass under a drain step `finish` with its own budget, so the governor stopped reading it
+ * as `no_admission`. L5 moves it out: the checkpoint's own transaction records the tail as owed, the pass returns at the
+ * checkpoint commit, and the tail runs after the drain lease is released, bounded, with a degraded notice when it fails or
+ * is cut short. These tests pinned the C4 behavior (the `finish` step and window); they now assert the L5 behavior.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -11,13 +12,15 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { SyncResult } from '../src/commands/sync.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { stampDrainStep } from '../src/core/persistence/drain-step.ts';
+import { installFaultHook } from '../src/core/persistence/fault-points.ts';
import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { runDrain, type StallProbe } from '../src/core/persistence/sync-drain.ts';
-import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { readSyncTail } from '../src/core/persistence/sync-tail-record.ts';
import { withEnv } from './helpers/with-env.ts';
const empty: StallProbe = { blockedHead: async () => null, fingerprint: async () => null, head: async () => null };
@@ -25,36 +28,32 @@ const synced: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', a
managedCursor: { index: 1, total: 1 } };
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
-describe('in-pass governor: the tail after a committed checkpoint', () => {
- test('a tail longer than the no-progress window ends synced, not blocked/no_admission', async () => {
- const result = await runDrain({ governMs: 10, noProgressMs: 80, probe: empty, pass: async (signal, onProgress) => {
+describe('in-pass governor: no tail inside the pass', () => {
+ test('a pass that returns at its checkpoint commit ends synced', async () => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 80, probe: empty, pass: async (_signal, onProgress) => {
onProgress({ phase: 'managed_sync.page_committed', bankedFiles: 1, total: 1 });
- stampDrainStep('finish', signal);
onProgress({ phase: 'managed_sync.finish', bankedFiles: 1, total: 1 });
- await sleep(300);
return synced;
} });
expect(result.drain).toMatchObject({ outcome: 'synced', passes: 1 });
});
- test('a tail past its own budget stops no_progress at step finish, never no_admission', async () => {
- const result = await runDrain({ governMs: 10, noProgressMs: 40, finishMs: 120, probe: empty, pass: (signal, onProgress) => {
- stampDrainStep('finish', signal);
+ test('a pass quiet past the window after its last commit stops no_progress (no finish window any more)', async () => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 80, probe: empty, pass: (_signal, onProgress) => {
onProgress({ phase: 'managed_sync.finish', bankedFiles: 1, total: 1 });
return new Promise<SyncResult>(() => undefined);
} });
- expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', in_pass: true, step: 'finish' } });
- expect(result.drain!.stall!.stalled_seconds).toBeGreaterThanOrEqual(0);
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', in_pass: true } });
});
- test('a pass stuck in admission still stops no_admission inside the no-progress window', async () => {
+ test('a pass stuck in admission with nothing unfinished stops no_progress naming its step (no_admission is retired)', async () => {
const started = Date.now();
- const result = await runDrain({ governMs: 10, noProgressMs: 80, finishMs: 60_000, probe: empty, pass: signal => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 80, probe: empty, pass: signal => {
stampDrainStep('admission', signal);
return new Promise<SyncResult>(() => undefined);
} });
expect(Date.now() - started).toBeLessThan(10_000);
- expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_admission', step: 'admission' } });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', step: 'admission' } });
});
});
@@ -67,7 +66,8 @@ afterAll(async () => {
rmSync(home, { recursive: true, force: true });
});
-test('a real managed run whose link tail outlasts the no-progress window ends synced (PGLite)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+/** A managed source of two notes that link to each other. */
+async function source(): Promise<string> {
const id = `tail-${randomUUID().replace(/-/g, '').slice(0, 20)}`;
const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');
for (let i = 0; i < 2; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nSee [[notes/n${1 - i}]] for acme-example.\n`);
@@ -76,19 +76,77 @@ test('a real managed run whose link tail outlasts the no-progress window ends sy
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return id;
+}
+const stale = (sourceId: string) => engine.countStalePagesForExtraction({ sourceId });
+
+test('the tail runs after the drain lease is released: a second sync takes the lease while the first one\'s links still run (PGLite)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const id = await source();
const count = engine.countStalePagesForExtraction.bind(engine);
+ let entered: () => void = () => {};
+ const inTail = new Promise<void>(resolve => { entered = resolve; });
+ let release: () => void = () => {};
+ const held = new Promise<void>(resolve => { release = resolve; });
let slowed = false;
- engine.countStalePagesForExtraction = async opts => { if (!slowed) { slowed = true; await sleep(5_000); } return count(opts); };
- const phases: string[] = [];
- const drainStartedAt = Date.now();
+ engine.countStalePagesForExtraction = async opts => { if (!slowed) { slowed = true; entered(); await held; } return count(opts); };
try {
- const result = await runDrain({ governMs: 20, noProgressMs: 2_500, pass: (signal, onProgress) =>
- performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, signal, drainStartedAt, onProgress: e => { phases.push(e.phase); onProgress(e); } }) });
+ const first = performSync(engine, { sourceId: id, noPull: true, noEmbed: true, drain: true });
+ await Promise.race([inTail, sleep(60_000)]);
expect(slowed).toBe(true);
+ // On the base the first run still held the lease here (its link tail ran inside the pass), so this threw SyncLockBusyError.
+ const second = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, drain: true });
+ expect(second.status).toBe('up_to_date');
+ release();
+ const result = await first;
expect(result.drain).toMatchObject({ outcome: 'synced', written: 2, remaining: 0 });
expect(result.status).toBe('first_sync');
- expect(phases).toContain('managed_sync.finish');
+ expect(result.tail).toMatchObject({ status: 'done', runs: 1 });
+ expect(result.links?.pages).toBe(2);
+ expect(await stale(id)).toBe(0);
+ expect(await readSyncTail(engine, id)).toBeNull();
} finally {
+ release();
engine.countStalePagesForExtraction = count;
}
}), 120_000);
+
+test('a tail that never ran after its checkpoint committed stays owed and the next sync runs it; the failed one carries a degraded notice (PGLite)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const id = await source();
+ let fired = 0;
+ installFaultHook(point => { if (point === 'sync:tail_started' && fired++ === 0) throw new Error('injected death between the checkpoint commit and the tail'); });
+ try {
+ const first = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, drain: true });
+ expect(fired).toBe(1);
+ expect(first.drain?.outcome).toBe('synced');
+ expect(first.status).toBe('first_sync');
+ expect(first.tail).toMatchObject({ status: 'failed', runs: 1, notice: { code: 'sync_tail_degraded', kind: 'degraded', fix: { argv: ['gbrain', 'extract', '--stale', '--source', id] } } });
+ expect(first.links).toBeUndefined();
+ const owed = await readSyncTail(engine, id);
+ expect(owed?.map(item => ({ changed: item.changed, extract: item.extract }))).toEqual([{ changed: 2, extract: true }]);
+ expect(await stale(id)).toBe(2);
+ const second = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, drain: true });
+ expect(second.status).toBe('up_to_date');
+ expect(second.tail).toMatchObject({ status: 'done', runs: 1, statistics: 'refreshed' });
+ expect(second.tail?.notice).toBeUndefined();
+ expect(await stale(id)).toBe(0);
+ expect(await readSyncTail(engine, id)).toBeNull();
+ } finally { installFaultHook(undefined); }
+}), 120_000);
+
+test('a --no-extract run owes statistics only, and a run past its deadline defers the links with the notice (PGLite)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const id = await source();
+ const result = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });
+ expect(result.tail).toMatchObject({ status: 'done', statistics: 'refreshed' });
+ expect(result.links).toBeUndefined();
+ expect(await stale(id)).toBe(2);
+ const { runSyncTail } = await import('../src/core/persistence/sync-tail.ts');
+ const { recordSyncTail } = await import('../src/core/persistence/sync-tail-record.ts');
+ const [cursor] = await engine.executeRaw<{ fingerprint: string; run_id: string }>("SELECT fingerprint, completed_keys->0->>'runId' AS run_id FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [id]);
+ await engine.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,processingOptions,noExtract}','false'::jsonb) WHERE op='managed-sync' AND fingerprint=$1", [cursor!.fingerprint]);
+ await recordSyncTail(engine, id, cursor!.fingerprint, cursor!.run_id);
+ const deferred = await runSyncTail(engine, id, { deadlineAtMs: Date.now() - 1 });
+ expect(deferred).toMatchObject({ status: 'deferred', notice: { code: 'sync_tail_degraded' } });
+ expect(await readSyncTail(engine, id)).not.toBeNull();
+ expect((await runSyncTail(engine, id))?.status).toBe('done');
+ expect(await stale(id)).toBe(0);
+}), 120_000);
diff --git a/test/sync-drain-inpass-stall.test.ts b/test/sync-drain-inpass-stall.test.ts
index 4c5954b91e..abbfb3d9f1 100644
--- a/test/sync-drain-inpass-stall.test.ts
+++ b/test/sync-drain-inpass-stall.test.ts
@@ -85,7 +85,7 @@ describe('in-pass governor over the real head read (engineStallProbe)', () => {
}, 120_000);
afterAll(async () => { for (const [kind, engine] of engines) if (kind === 'pglite') await engine.disconnect(); await closePostgres?.(); });
- test('a running request stamped publishing for 10 minutes stops publication_overdue naming it; with no request left the stop is no_admission', async () => {
+ test('a running request stamped publishing for 10 minutes stops publication_overdue naming it; with no request left the stop is no_progress (#6712 PR 2 retired no_admission)', async () => {
for (const [, engine] of engines) {
const id = `gov-${randomUUID().slice(0, 8)}`;
await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, `/tmp/${id}`]);
@@ -106,7 +106,7 @@ describe('in-pass governor over the real head read (engineStallProbe)', () => {
expect(hung.drain!.stall!.stalled_seconds).toBeGreaterThanOrEqual(599);
await engine.executeRaw('DELETE FROM persistence_requests WHERE id=$1::uuid', [row!.id]);
const idle = await runDrain({ governMs: 10, noProgressMs: 80, publicationCeilingMs: 100, probe, pass: () => new Promise<SyncResult>(() => undefined) });
- expect(idle.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_admission', head_request_id: null } });
+ expect(idle.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', head_request_id: null } });
}
}, 60_000);
});
diff --git a/test/sync-drain-no-admission.test.ts b/test/sync-drain-no-admission.test.ts
index 8a00e9a8ed..f99397fd84 100644
--- a/test/sync-drain-no-admission.test.ts
+++ b/test/sync-drain-no-admission.test.ts
@@ -1,8 +1,10 @@
/**
* #6423 (P2.2): behind a transaction-mode pooler a managed sync pass admitted nothing and never returned, and with no
* unfinished request there was no claim for the stall detector to read. The in-pass governor stops it `blocked /
- * drain_stalled / no_admission` after the no-progress window and names the process-local step and the last statement
- * label the pass stamped. Synthetic results only.
+ * drain_stalled` after the no-progress window and names the process-local step and the last statement label the pass
+ * stamped. #6712 PR 2 retired the separate `no_admission` cause (and its serve fallback and pooler warning): the stop is
+ * `no_progress` like any other pass that moved nothing, with the same step and statement, and its next step is the
+ * writer inspection. These tests pinned `no_admission`; they now assert `no_progress`. Synthetic results only.
*/
import { describe, expect, test } from 'bun:test';
import { drainNext, formatDrainSummary, runDrain, type StallProbe } from '../src/core/persistence/sync-drain.ts';
@@ -13,19 +15,21 @@ const RESUME = 'gbrain sync --source s --no-pull';
const empty: StallProbe = { blockedHead: async () => null, fingerprint: async () => null, head: async () => null };
describe('in-pass governor: a pass that admits nothing', () => {
- test('pass blocked forever with no unfinished head: blocked/drain_stalled/no_admission naming waiver_run and the last SQL', async () => {
+ test('pass blocked forever with no unfinished head: blocked/drain_stalled/no_progress naming waiver_run and the last SQL', async () => {
const started = Date.now();
const result = await runDrain({ governMs: 10, noProgressMs: 80, probe: empty,
pass: signal => { stampDrainStep('waiver_run', signal); noteDrainSql('SELECT id FROM persistence_requests WHERE page_id=$1'); return new Promise<SyncResult>(() => undefined); } });
expect(Date.now() - started).toBeGreaterThanOrEqual(80);
- expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_admission', in_pass: true, step: 'waiver_run', head_request_id: null } });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', in_pass: true, step: 'waiver_run', head_request_id: null } });
expect(result.drain!.stall!.last_sql?.label).toBe('SELECT persistence_requests');
const summary = formatDrainSummary(result, RESUME, 's').join('\n');
- expect(summary).toContain('Nothing admitted for');
- expect(summary).toContain('step=waiver_run, last_sql=SELECT persistence_requests, cause=no_admission');
+ expect(summary).toContain('No request of this source was unfinished');
+ expect(summary).toContain('step=waiver_run, last_sql=SELECT persistence_requests');
+ expect(summary).toContain('cause=no_progress');
+ expect(summary).not.toContain('no_admission');
const next = drainNext(result, RESUME, 's')!;
- expect(next).toMatchObject({ command: RESUME, safe_to_loop: false, code: 'drain_stalled', cause: 'no_admission' });
- expect(next.why).toContain('transaction-mode pooler');
+ expect(next).toMatchObject({ command: 'gbrain sources writer status s', safe_to_loop: false, code: 'drain_stalled', cause: 'no_progress' });
+ expect(next.why).toContain('stuck at step waiver_run');
});
test('the abandoned pass admits nothing more: its next step boundary throws the abort', async () => {
@@ -55,6 +59,6 @@ describe('in-pass governor: a pass that admits nothing', () => {
now += 61;
return new Promise<SyncResult>(() => undefined);
} });
- expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', written: 1, stall: { cause: 'no_admission', in_pass: true } });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', written: 1, stall: { cause: 'no_progress', in_pass: true } });
});
});
diff --git a/test/sync-waivers-chunk.test.ts b/test/sync-waivers-chunk.test.ts
index 634f757874..f6a3ce151b 100644
--- a/test/sync-waivers-chunk.test.ts
+++ b/test/sync-waivers-chunk.test.ts
@@ -3,7 +3,7 @@
* trip (two calls per entry, 128 for a 64-entry run of deletes). It now sends them in chunks of at most
* WAIVER_PIPELINE_MAX calls, and sends a chunk only while every entry before it validated, so the contiguous-prefix result
* is unchanged. The engine here is a recording fake that reports `kind: 'postgres'` (so `pipelined` really issues a chunk
- * at once) and counts the statements outstanding at the same time. The #6423 forced probe is the `no_admission` governor
+ * at once) and counts the statements outstanding at the same time. The #6423 forced probe is the in-pass governor (its `no_progress` stop; #6712 PR 2 retired `no_admission`)
* test in test/sync-drain-no-admission.test.ts. Synthetic data only.
*/
import { afterAll, describe, expect, test } from 'bun:test';