Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): an in-pass governor stops a drain whose pass never returns (#6405, #6423)

time-attackcc1fa48f27e1
diff --git a/docs/architecture/key-files/persistence-stalls.md b/docs/architecture/key-files/persistence-stalls.md
index 6ffc74d73a..828cf877ce 100644
--- a/docs/architecture/key-files/persistence-stalls.md
+++ b/docs/architecture/key-files/persistence-stalls.md
@@ -47,3 +47,4 @@ owner (`owner_wedged_here`), movement surfaces (`data_moving`, doctor
- `src/core/persistence/consumer-lane.ts` — #6317 (reporter ask 2): `consumerStatementEngine`, the Proxy that routes the consumer's own tick statements (idle probe, switch read, recovery and expired-claim scans, capacity, releases, floor) to `executeRawDirect` while the dual pool is active (`GBRAIN_DIRECT_DATABASE_URL` or the Supabase-derived direct URL), so the owner's round-trips avoid a transaction-mode pooler; `status().connection = { lane, pooler_mode, direct_host? }` says which lane is in use, and one `[persistence] phase=start reason=transaction_pooler` line prints when only a `prepare=false` URL exists.
- `src/core/persistence/consumer-diagnostics.ts` — #6317 (B3, I1): `hostConsumersReport` (the `host.consumers` block of `writer status --json`), `consumerOverlap` (two resident-kind full rows alive over 30 s), `ownersWithoutHeartbeat` (claim owners on running claims with no row) and `hostIdentityMismatches` (this process's `host.json` id differs from a binding owner's while the owner's checkout resolves on this filesystem or the machine id matches), read-only and shared by doctor and writer status.
- `src/core/postgres-engine/pool-stats.ts` — #6317 (C1, G1): `driverPoolStats(sql)` reads the vendored postgres.js driver's `sql.pool` getter (`vendor/postgres`, patch regenerated) for real `{checked_out, max, waiters}`; `enginePoolStats(engine)` labels the source (`driver` or `tracked_subset` from `pool-gauge.ts`). Filled into the heartbeat row, `writer status` running claims and `getPoolDiagnostics()`.
+- `src/core/persistence/sync-drain.ts` (#6405, #6423 in-pass governor) + `src/core/persistence/drain-step.ts` — `runDrain` races every pass against a governor that runs with or without `announce`: the pass gets its own `AbortController`, the governor's head read is bounded (`GOVERN_PROBE_MS`, or the window when shorter), and on a stop the pass signal is aborted (the pass's `assertActive` / `stampDrainStep` boundaries throw, so it admits and writes nothing more) and its late result or rejection is dropped. A head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300000, 60000 to 3600000; `PUBLICATION_CEILING_DEFAULT_MS`) stops `blocked` / `drain_stalled` / `publication_overdue` with `stall.in_pass` and a `next` that says restart (never a promised reclaim); a pass with no commit, no unfinished request and nothing changing for `IN_PASS_NO_PROGRESS_MS` (5 min) stops `no_admission`, an unchanged non-empty head `no_progress` / `owner_missing`; a live preparation is left to its own budget and ceiling. `drain-step.ts` holds the process-local step (`freeze`, `waiver_run`, `admission`, `await_receipt`, stamped in `sync-run.ts`) and the last statement label (`noteDrainSql`, from `waiveNoopRun`). `enterClaimPhase(clock, 'publishing')` stamps `waiting_on: 'publication'`. `drainManagedSync` prints one line when the sync's own pool is a transaction-mode pooler. `sync-waivers.ts` `waiveNoopRun` pipelines at most `WAIVER_PIPELINE_MAX` (64) calls per round trip and sends the next chunk only while the prefix holds. `commands/sync-delegate.ts`: a serve-delegated `no_admission` stop continues once with the CLI's own consumer (`serve_no_admission`); a `publication_overdue` stop is reported as it is. Tests: `test/sync-drain-inpass-stall.test.ts`, `test/sync-drain-no-admission.test.ts`, `test/sync-waivers-chunk.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 3b47cfe03d..aa7bffee83 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -766,7 +766,7 @@ More: [docs/guides/ambient-recall.md#replay-after-a-degraded-wake](../../docs/gu
|---|---|---|---|---|---|---|
| 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. | 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. | 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. Run: gbrain sources writer status --source '{source_id}' --json | host_admin | `gbrain doctor --only managed_sync_not_moving --json` | 1 | no |
-Reasons: `owner_wedged_here`, `owner_missing`, `preparation_overdue`, `publication_overdue`, `no_progress`.
+Reasons: `owner_wedged_here`, `owner_missing`, `preparation_overdue`, `publication_overdue`, `no_progress`, `no_admission`.
More: [docs/guides/write-refusals.md#drain-stalled](../../docs/guides/write-refusals.md#drain-stalled)
@@ -1632,6 +1632,14 @@ More: [docs/guides/write-refusals.md#maintenance_backpressure](../../docs/guides
More: [docs/guides/cron-schedule.md#dream-beside-autopilot](../../docs/guides/cron-schedule.md#dream-beside-autopilot)
+### managed_failure_unsettled
+
+<a id="managed_failure_unsettled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The recorded managed sync failure is not settled by the imported state, so it was not acknowledged. | Acknowledging removes a failure record only when the file it failed on is already imported unchanged (or deleted in both the commit and the brain); anything else would hide content that never reached the brain. | Resume or retry the sync the failure names (gbrain sync status --source <id> --json shows it), then acknowledge again if the record remains. | agent | `repeat the read that failed` | 1 | no |
+
### managed_pull_skipped
<a id="managed_pull_skipped"></a>
@@ -2500,7 +2508,7 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| The source changed during the operation; nothing was committed. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
+| The source changed during the operation; nothing was committed. | Covers a replaced, archived or re-bound source and a canonical file that differs from the page's database copy (detail file_database_drift). A page that records no file of its own reconciles against the file at its slug path only with gbrain sources reconcile <source> <slug> --preview --adopt-slug-path. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |
### source_id_taken
@@ -2996,7 +3004,7 @@ More: [docs/guides/write-refusals.md#write_outcome_unknown](../../docs/guides/wr
| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
|---|---|---|---|---|---|---|
-| Another activation probe is running. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |
+| A writer lock could not be taken: another process holds it (busy), or this process cannot open the lock file at all. | Busy clears when the holder finishes. A process that cannot open the lock file (a sandbox, an unwritable lock directory) fails the same way on every retry, so its write stays queued with blocked_reason writer_lock_unavailable until an owner process that can take the lock publishes it; the OS error is kept in the owner-only detail. | For a queued write, wait for the owner (gbrain sources writer status --json names it) or run the write from a process that can open the lock directory; retrying from the same sandboxed process changes nothing. | agent | `repeat the read that failed` | 1 | yes |
### writer_manifest_mismatch
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 7290aa48e6..8907777fe4 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -462,7 +462,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run
| Stop reason | Code | Outcome | What it means | Recovery |
| --- | --- | --- | --- | --- |
| <a id="drain-stopped-at-its-deadline"></a>`deadline` | `writer_pending` | `resumable` | `--timeout`, `--hard-deadline`, Ctrl-C or the run deadline stopped the drain. Accepted page writes keep their request IDs and the cursor is intact. | Rerun `next.command` (the same options). It resumes where the last run stopped. |
-| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |
+| <a id="drain-stalled"></a>`drain_stalled` | `drain_stalled` | `blocked` | The awaited page write and the oldest unfinished write on its checkout made no progress for the whole stall window: no committed receipt and no step advance. A lease renewal is not a change: the detector keys on the head claim's phase and step. With a live owner on **this host**, the drain does not stop at the allowance (the preparation budget plus 30 s): from there it prints `stalled <N>s on <step>` with the owner's pid and kind every 10 s and keeps going, because the owner's own budget frees the root by `persistence.preparation_ceiling_ms` (600 s) and the next pass holds the entry. It stops `drain_stalled` only when the ceiling passes without the root being released, or when the owner's `persistence_consumers` row reads wedged (`restart_required`, or a root barrier older than the ceiling); the stop then carries `cause: owner_wedged_here`, the owner `{kind, pid, nonce}`, `retry_after_ms` (the time left to the ceiling, 0 once past), `next.safe_to_loop: true` while the ceiling is ahead and `next.fix.next` `wait` before it, `tell_user_to_run` (restart the named pid) after it. A lapsed claim (`owner_missing`) stops at once, unless this host owns the checkout and a live full consumer exists, which gets exactly one more window. Other causes: `preparation_overdue` / `publication_overdue` (a live owner elsewhere past its allowance) and `no_progress` (an unstamped head). A pass that never returns is stopped from inside (`drain.stall.in_pass: true`, the same rules whether or not the drain prints progress): a head claim live in `publishing` past `persistence.publication_ceiling_ms` (default 300 s) stops `publication_overdue`, and its `next` says to restart the process that owns the publication, because an unfinished publish can hold its locks until it settles and nothing reclaims it for you; a pass that admitted nothing and left no unfinished request for 5 minutes stops `no_admission` with the step it was in (`freeze`, `waiver_run`, `admission`, `await_receipt`) and the last statement label, which is what a transaction-mode pooler that never answers a round trip looks like. A serve-delegated `no_admission` continues once with the CLI's own consumer. `drain.stall` carries `phase`, `step`, `waiting_on`, `cause`, the owner and whether this host owns the checkout. | `gbrain sources writer status --source <source> --json`: its `next_action` says whether to wait (`retry_after_ms`) or which pid to restart. Before the ceiling, rerun `next.command` after `retry_after_ms` (safe in a loop). Past it, or with a wedged owner, restart the named owner process (`gbrain serve`, the jobs worker or autopilot) on the brain host, then rerun `next.command`; the held entry needs `gbrain sources retry-held <source>` afterwards. When this host is not the owner, make sure the owner's `gbrain serve` is running. |
| <a id="drain-database-contention"></a>`database_contention` | `database_contention` | `blocked` (or an error) | Three consecutive passes hit database contention, a statement timeout or a dropped connection, or reading the awaited write's state failed (an authentication or permission failure stops at once). The drain retries transient failures with backoff before giving up. Accepted writes keep their request IDs. | Fix database access (`gbrain engine status --probe`), then rerun `next.command`. |
| <a id="drain-writer-blocked"></a>`recovery_required`, `owner_unavailable`, `unexpected_file_bytes`, `unexpected_staging_bytes` | `recovery_required` | `blocked` | The checkout's writer needs intervention before more pages can publish: interrupted publication recovery, no live owner, or unexpected bytes in the file or staging area. | `gbrain sources writer status <source>` and the fix it prints. Unexpected bytes are the user's edits; ask before discarding them. Then rerun `next.command`. |
| <a id="drain-blocked-by-a-failed-page"></a>`blocked_by_failures` | `blocked_by_failures` | `blocked` | A page write failed terminally. `managed_write` and `failures` name the page and cause. Rerunning without a fix returns the same failure. | Fix the cause, then run `next.command` (it adds `--retry-failed`). Ask the user before skipping content. |
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index e80bd18e38..2927391569 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -498,7 +498,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'; line: string | null };
+ | 'kill_switch' | 'unsupported_flag' | 'no_socket' | 'older_serve' | 'serve_refused' | 'serve_lost' | 'serve_no_admission'; line: string | null };
const fallbackLine = (pid: number, cause: string, fix = 'Restart that serve on this gbrain version to remove the second consumer.'): string =>
`[sync] ${cause}; this run uses its own consumer beside the serve (PID ${pid}). ${fix}`;
@@ -607,6 +607,13 @@ 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/core/config.ts b/src/core/config.ts
index ae149dc029..1e74528d1b 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1734,6 +1734,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
'persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts
'persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts', 'persistence.preparation_deadlines', // #6278: persistence/preparation-budget.ts, switches.ts
+ 'persistence.publication_ceiling_ms', // #6405: persistence/sync-drain.ts (in-pass publication ceiling)
'persistence.single_consumer', // #6317: persistence/switches.ts, consumer-election.ts (one full consumer per host; off by default)
// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)
'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries',
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 8a1b7f8c50..4711354a56 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -149,7 +149,7 @@ 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'],
+ reasons: ['owner_wedged_here', 'owner_missing', 'preparation_overdue', 'publication_overdue', 'no_progress', 'no_admission'],
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,
diff --git a/src/core/persistence/claim-phase.ts b/src/core/persistence/claim-phase.ts
index 97a0cc93dd..0f6c1bca33 100644
--- a/src/core/persistence/claim-phase.ts
+++ b/src/core/persistence/claim-phase.ts
@@ -43,7 +43,8 @@ import { VERSION } from '../../version.ts';
import { consumerIdentity, sameProcess } from './consumer-heartbeat.ts';
export type ClaimPhaseName = 'preparing' | 'publishing';
-export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'unknown'] as const;
+/** #6405: `publication` is the publish phase's own wait (a stamp in `publishing` no longer reads `unknown`). */
+export const WAITING_ON = ['git', 'fs', 'db', 'pool', 'publication', 'unknown'] as const;
export type WaitingOn = typeof WAITING_ON[number];
export interface ClaimPhaseClock {
phase: ClaimPhaseName;
@@ -88,7 +89,7 @@ export function enterClaimPhase(clock: ClaimPhaseClock, phase: ClaimPhaseName, n
clock.since = now;
clock.step = null;
clock.stepSince = now;
- clock.waitingOn = 'unknown';
+ clock.waitingOn = phase === 'publishing' ? 'publication' : 'unknown';
}
/**
* A preparer's step boundary: names the step and what its await waits on,
diff --git a/src/core/persistence/drain-step.ts b/src/core/persistence/drain-step.ts
new file mode 100644
index 0000000000..6a6366da92
--- /dev/null
+++ b/src/core/persistence/drain-step.ts
@@ -0,0 +1,23 @@
+/**
+ * #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.
+ */
+import { sqlLabel } from './claim-phase.ts';
+
+export type DrainStep = 'freeze' | 'waiver_run' | 'admission' | 'await_receipt';
+export interface DrainStepStamp { step: DrainStep; since: number; last_sql: { label: string; at: number } | null }
+
+let current: DrainStepStamp | null = null;
+
+/** Enters `step` and throws the pass's abort reason, so an abandoned pass admits and writes nothing more. */
+export function stampDrainStep(step: DrainStep, signal?: AbortSignal, now = Date.now()): void {
+ signal?.throwIfAborted();
+ current = { step, since: now, last_sql: null };
+}
+/** Records the statement the current step is about to send (label only, never text or parameters). */
+export function noteDrainSql(sql: string, now = Date.now()): void {
+ if (current) current.last_sql = { label: sqlLabel(sql), at: now };
+}
+export function readDrainStep(): DrainStepStamp | null { return current; }
+export function clearDrainStep(): void { current = null; }
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index f762aceda4..d9e665ea46 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -23,7 +23,8 @@ 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 { isOwnerThisProcess, stampLastSql, type ClaimLastSql } from './claim-phase.ts';
+import { clearDrainStep, readDrainStep } from './drain-step.ts';
+import { isOwnerThisProcess, stampLastSql, WAITING_ON, type ClaimLastSql, type WaitingOn } from './claim-phase.ts';
export type DrainOutcome = 'synced' | 'resumable' | 'blocked';
/** Why a drain ended short of `synced`. Each value has an error-catalogue entry (DX-A4). */
@@ -43,7 +44,7 @@ export interface DrainCapacityWait { outstanding: number | null; limit: number |
export interface DrainClaim {
phase: 'preparing' | 'publishing' | null;
step: string | null;
- waiting_on: 'git' | 'fs' | 'db' | 'pool' | 'unknown' | null;
+ waiting_on: WaitingOn | null;
/** How long the current phase/step has been in flight, from the stamp; null without a stamp of this claim. */
step_age_ms: number | null;
claim_age_ms: number | null;
@@ -88,8 +89,11 @@ 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.
*/
- cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here';
+ cause?: 'owner_missing' | 'preparation_overdue' | 'publication_overdue' | 'no_progress' | 'owner_wedged_here' | 'no_admission';
+ /** #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. */
owner_pid?: number | null;
owner_kind?: string | null;
@@ -158,6 +162,13 @@ const NO_PASS_RESULT: SyncResult = { status: 'partial', reason: 'writer_pending'
const REFRESH_WAIT_MS = 5 * 60_000;
const DEADLINE_MARGIN_MS = 15_000;
const PROGRESS_EVERY_MS = 10_000;
+/** #6405/#6423: a pass with no commit, no admission and no change at the head for this long is ended by the in-pass governor. */
+const IN_PASS_NO_PROGRESS_MS = 5 * 60_000;
+/** #6405: `persistence.publication_ceiling_ms`' default; a live claim in `publishing` past it ends the pass. */
+export const PUBLICATION_CEILING_DEFAULT_MS = 5 * 60_000;
+/** #6405 (R6): the governor's head read is abandoned past this, so a stuck read never parks the governor. */
+const GOVERN_PROBE_MS = 5_000;
+const GOVERN_EVERY_MS = 5_000;
function continues(result: SyncResult): boolean {
return result.status === 'partial' && (result.reason === 'writer_pending' || result.reason === 'writer_yield');
@@ -256,7 +267,7 @@ export interface StallProbe {
*/
fingerprint(result: SyncResult): Promise<{ key: string; stall: Omit<DrainStall, 'stalled_seconds'>; claim?: DrainClaim | null } | null>;
/** #6278: the source's head while a pass runs (its oldest running request, else its oldest queued one); null when nothing is unfinished. Bounded; may reject. */
- head?(): Promise<{ head_state: string; claim: DrainClaim | null } | null>;
+ head?(): Promise<{ head_state: string; claim: DrainClaim | null; request_id?: string | null } | null>;
/** #6317: the head owner's heartbeat row on this host, or null (no row: an older owner, PGLite, the table absent, or another host). Never rejects. */
owner?(claim: DrainClaim): Promise<DrainOwnerRow | null>;
/** #6317: whether a consumer here could reclaim a lapsed head: this process's own, or a live full row on this host. Never rejects. */
@@ -276,6 +287,10 @@ export interface DrainInput {
bulk?: { enabled: boolean; reason: string | null; lanes?: number; lanesMax?: number; lanesReason?: string | null; lanesCap?: LanesCap };
/** Test seams: the no-progress window, the pause after a pending write, the transient backoff base and the progress-line interval. */
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;
+ publicationCeilingMs?: number;
+ governMs?: number;
pauseMs?: number;
backoffMs?: number;
progressMs?: number;
@@ -359,6 +374,59 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
+ `${estimate.rate_pages_per_min ?? '?'} pages/min · indexing ETA ${estimate.eta_seconds === null ? 'unknown' : formatDuration(estimate.eta_seconds)}`);
}
};
+ // #6405/#6423 (R6): every stop rule above runs between passes, so a pass that never returns (a publish that neither resolves nor
+ // rejects, an admission parked behind a transaction pooler) was never stopped. The governor runs whether or not the drain
+ // announces, races the pass so the drain settles even when the hung promise never does, bounds its own head read, and owns
+ // 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 governedPass = (): Promise<{ result: SyncResult } | { stall: DrainStall }> => {
+ const controller = new AbortController(), passStartedAt = Date.now();
+ const passSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
+ clearDrainStep();
+ const running = Promise.resolve().then(() => input.pass(passSignal, onProgress));
+ let timer: ReturnType<typeof setInterval> | null = null, probing = false, key: string | null = null, keySince = passStartedAt;
+ const stopped = new Promise<{ stall: DrainStall }>(resolve => {
+ const stop = (stall: DrainStall) => { if (timer) clearInterval(timer); timer = null; controller.abort(new Error(`drain_stalled: ${stall.cause}`)); resolve({ stall }); };
+ timer = setInterval(() => {
+ const quietSince = Math.max(lastCommitAt, passStartedAt);
+ if (probing || Date.now() - quietSince < Math.min(noProgressMs, ceilingMs)) return;
+ probing = true;
+ const head = input.probe?.head
+ ? Promise.race([Promise.resolve().then(() => input.probe!.head!()), new Promise<never>((_, reject) => setTimeout(() => reject(new Error('head read timed out')), Math.min(GOVERN_PROBE_MS, noProgressMs)).unref?.())])
+ .then(value => ({ ok: true as const, value }), () => ({ ok: false as const }))
+ : Promise.resolve({ ok: true as const, value: null });
+ void head.then(read => {
+ if (!timer) return;
+ const now = Date.now(), quiet = now - Math.max(lastCommitAt, passStartedAt);
+ const head = read.ok ? read.value : null, claim = head?.claim ?? null;
+ const step = readDrainStep();
+ const base = { request_id: head?.request_id ?? 'none', state: head?.head_state ?? 'none', blocked_reason: null, head_request_id: head?.request_id ?? null,
+ head_state: head?.head_state ?? null, claimable_here: false, owner_is_this_host: null, in_pass: true } as const;
+ if (claim && !claim.lapsed && claim.phase === 'publishing') {
+ const age = claim.step_age_ms ?? quiet;
+ if (age < ceilingMs) return;
+ stop({ ...base, stalled_seconds: Math.round(age / 1000), phase: 'publishing', step: claim.step, waiting_on: claim.waiting_on, cause: 'publication_overdue',
+ owner_pid: claim.owner_pid, owner_kind: claim.owner_kind, owner_nonce: claim.owner_nonce, last_sql: claim.last_sql, ceiling_ms: ceilingMs });
+ return;
+ }
+ // A live preparation is bounded by its own budget and the preparation ceiling (#6298), which settle the pass.
+ if (claim && !claim.lapsed && claim.phase === 'preparing') { key = null; return; }
+ 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);
+ 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 ? 'no_admission' : 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; });
+ }, input.governMs ?? Math.min(every, GOVERN_EVERY_MS));
+ timer.unref?.();
+ });
+ running.catch(() => undefined);
+ return Promise.race([running.then(result => ({ result })), stopped]).finally(() => { if (timer) clearInterval(timer); timer = null; inPass = false; });
+ };
const finish = (result: SyncResult, outcome: DrainOutcome, stopReason?: DrainStopReason, extra?: Partial<DrainReport>): SyncResult => {
if (result.managedCursor) { index = result.managedCursor.index; total = result.managedCursor.total; }
const left = outcome === 'synced' ? 0 : remaining();
@@ -377,7 +445,9 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
let result: SyncResult;
try {
inPass = true;
- try { result = await input.pass(signal, onProgress); } finally { inPass = false; }
+ const governed = await governedPass();
+ if ('stall' in governed) return finish(last ?? NO_PASS_RESULT, 'blocked', 'drain_stalled', { stall: governed.stall });
+ result = governed.result;
attempt = 0; capacity = null;
if (last?.runId && result.runId && result.runId !== last.runId) {
const sum: RunCounts = carried ?? { added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0 };
@@ -503,7 +573,7 @@ export function drainClaimOf(row: { head_state: string | null; head_claim_phase:
const waiting = own ? stamp!.waiting_on : null;
const owner = own && stamp!.owner && typeof stamp!.owner === 'object' ? stamp!.owner as Record<string, unknown> : null;
return { phase, step: own && typeof stamp!.step === 'string' ? stamp!.step : null,
- waiting_on: typeof waiting === 'string' && ['git', 'fs', 'db', 'pool', 'unknown'].includes(waiting) ? waiting as DrainClaim['waiting_on'] : own ? 'unknown' : null,
+ waiting_on: typeof waiting === 'string' && (WAITING_ON as readonly string[]).includes(waiting) ? waiting as DrainClaim['waiting_on'] : own ? 'unknown' : null,
step_age_ms: own ? age(stamp!.step_since ?? stamp!.since) : null, claim_age_ms: own ? age(stamp!.claimed_at) : null, lapsed: row.head_lapsed === true,
owner_pid: own ? ownerPid(stamp!) : null, owner_kind: owner && typeof owner.kind === 'string' ? owner.kind : null, owner_nonce: owner && typeof owner.nonce === 'string' ? owner.nonce : null,
last_sql: own ? stampLastSql(stamp!.last_sql, now) : null,
@@ -517,6 +587,11 @@ function ownerPid(stamp: Record<string, unknown>): number | null {
return typeof pid === 'number' ? pid : null;
}
/** The preparation budgets the drain's allowance reads (Lane A defines and validates the keys; defaults are the documented ones). */
+/** #6405: `persistence.publication_ceiling_ms` (60000 to 3600000; anything else reads as the default). */
+async function readPublicationCeilingMs(engine: Pick<BrainEngine, 'getConfig'>): Promise<number> {
+ const n = Number((await engine.getConfig('persistence.publication_ceiling_ms').catch(() => null))?.trim());
+ return Number.isInteger(n) && n >= 60_000 && n <= 3_600_000 ? n : PUBLICATION_CEILING_DEFAULT_MS;
+}
async function readPreparationBudgets(engine: Pick<BrainEngine, 'getConfig'>): Promise<{ syncMs: number; maintenanceMs: number; ceilingMs: number }> {
const read = async (key: string, fallback: number) => { const n = Number((await engine.getConfig(key).catch(() => null))?.trim()); return Number.isInteger(n) && n > 0 ? n : fallback; };
return { syncMs: await read('persistence.sync_preparation_ms', SYNC_PREPARATION_DEFAULT_MS), maintenanceMs: await read('persistence.maintenance_preparation_ms', MAINTENANCE_PREPARATION_DEFAULT_MS),
@@ -587,15 +662,15 @@ export function engineStallProbe(engine: BrainEngine, sourceId?: string): StallP
return (await listHostConsumers(engine, localHostId()).catch(() => [])).some(row => (row.mode === 'full' || row.mode === 'promoted') && row.liveness === 'live');
},
...(sourceId ? { async head() {
- const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null }>(
- `SELECT h.state AS head_state, h.claim_phase AS head_claim_phase, h.execution_token::text AS head_token,
+ const [row] = await engine.executeRaw<{ head_state: string; head_claim_phase: unknown; head_token: string | null; head_lapsed: boolean | null; head_kind: string | null; head_request_id: string | null }>(
+ `SELECT h.state AS head_state, h.id::text AS head_request_id, h.claim_phase AS head_claim_phase, h.execution_token::text AS head_token,
(h.claim_expires_at IS NOT NULL AND h.claim_expires_at < now()) AS head_lapsed, h.intent->>'kind' AS head_kind
FROM persistence_source_bindings b
JOIN sources s ON s.id = b.source_id AND s.incarnation = b.source_incarnation
- JOIN LATERAL (SELECT e.state, e.claim_phase, e.execution_token, e.claim_expires_at, e.intent FROM persistence_requests e
+ JOIN LATERAL (SELECT e.id, e.state, e.claim_phase, e.execution_token, e.claim_expires_at, e.intent FROM persistence_requests e
WHERE e.worktree_id = b.worktree_id AND e.state IN ('queued','running','recovering') ORDER BY (e.state <> 'running'), e.sequence LIMIT 1) h ON true
WHERE b.source_id = $1`, [sourceId], { timeoutMs: HEAD_READ_TIMEOUT_MS, signal: AbortSignal.timeout(HEAD_READ_TIMEOUT_MS + 500) });
- return row ? { head_state: row.head_state, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))) } : null;
+ return row ? { head_state: row.head_state, request_id: row.head_request_id, claim: drainClaimOf(row, await (budgets ??= readPreparationBudgets(engine))) } : null;
} } : {}),
};
}
@@ -613,9 +688,16 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
// #5984 lanes: one lane run per drain; its groups carry the id and this process claims them out of FIFO order.
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;
try {
- result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce,
+ result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce, publicationCeilingMs,
reconnect: error => engine.reconnect({ error }),
bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },
pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });
@@ -637,7 +719,7 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
if (head && head !== result.toCommit) {
if (announce) serr(`[sync] HEAD moved past the pinned target ${result.toCommit.slice(0, 8)} while the run drained; one more pass imports the commits since (to ${head.slice(0, 8)}).`);
const pin = result.toCommit;
- const again = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce: false,
+ const again = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine, opts.sourceId), announce: false, publicationCeilingMs,
reconnect: error => engine.reconnect({ error }),
bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },
pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });
@@ -784,6 +866,27 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: s
: `Restart that process, then rerun: ${resumeCommand}`),
code: 'drain_stalled', cause: 'owner_wedged_here', fix: renderAction(action, cliRenderContext()), ...(docs ? { docs } : {}) };
}
+ // #6405: a publish that never returned. Its transaction may still hold the request, page and worktree locks, so nothing here
+ // promises a reclaim: the process that owns the publication has to end it (UC2).
+ if (d?.stop_reason === 'drain_stalled' && d.stall?.in_pass && d.stall.cause === 'publication_overdue') {
+ const stall = d.stall, owner = stall.owner_pid ? `the gbrain ${stall.owner_kind ?? 'owner'} process (pid ${stall.owner_pid})` : 'the process that owns the publication';
+ return { command: `gbrain sources writer status --source ${sourceId} --json`, safe_to_loop: false, retry_after_ms: 0, ...estimate, code: 'drain_stalled', cause: 'publication_overdue',
+ why: `The write at the head of this source (${stall.head_request_id ?? 'unknown request'}) has been publishing for ${stall.stalled_seconds}s, past the ${formatDuration(Math.round((stall.ceiling_ms ?? PUBLICATION_CEILING_DEFAULT_MS) / 1000))} publication ceiling`
+ + `${stall.step ? ` (step ${stall.step})` : ''}${stall.last_sql ? `, last statement ${stall.last_sql.label}` : ''}. The sync ended its pass and admits nothing more, but an unfinished publish can hold its locks until it settles, `
+ + `so it is not reclaimed for you: restart ${owner}, then rerun: ${resumeCommand}`,
+ fix: renderAction({ argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'Status names the request, its step and the owner process, read-only.', user_message: `Restart ${owner} on this host, then run: ${resumeCommand}`,
+ verify: { argv: ['gbrain', 'sources', 'writer', 'movement', sourceId, '--json'] } }, cliRenderContext()), ...(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,
@@ -817,7 +920,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) lines.push(` Oldest unfinished request ${d.stall.head_request_id ?? d.stall.request_id} (${d.stall.head_state ?? d.stall.state})`
+ 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})`
+ `${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 ? 'yes' : 'no'}.`);
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index e136aac281..3ae4633fd3 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -19,6 +19,7 @@ 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 { stampDrainStep } from './drain-step.ts';
import { noopWaiversEnabled, raceSyncBudget, screenWaiver, syncPreparationBudgetMs, unfinishedPageRequestParams, UNFINISHED_PAGE_REQUEST_SQL, waiveNoopEntry, waiveNoopRun, waiverBatchEnabled, type NoopWaiver, type WaiverRunEntry } from './sync-waivers.ts';
import { resolve } from 'node:path';
import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';
@@ -813,6 +814,7 @@ async function waiveRun(engine: BrainEngine, cursor: Cursor, head: Pending, key:
const run = await withScreeningPaths(() => withBoundedReadSession(engine, session => screenWaiverRun(session, cursor, head, key, config, assertActive, frozenRun, limit)));
if (!run) return null;
assertActive();
+ stampDrainStep('waiver_run', frozenRun.signal);
const observedAt = frozenRun.observedAt ?? new Date().toISOString();
const done = await waiveNoopRun(engine, cursor, run, key, async (tx, prefix) => {
let next: Cursor = cursor;
@@ -1362,7 +1364,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
creditedPages = 25; creditStarted = performance.now();
}
foregroundWaitStart = 0;
- phase = 'freeze';
+ phase = 'freeze'; stampDrainStep('freeze', signal);
const frozen = await freezeEntry(engine, cursor, key, assertActive, frozenRun);
if ('hold' in frozen) {
cursor = await saveCursor(engine, key, cursor, { ...advanceHeld(cursor), ...(frozen.overtaken ? { overtaken: true as const } : {}) }, false, assertActive, heldWrite(cursor, frozen.hold, observedAt));
@@ -1378,7 +1380,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}
if (!cursor.pending) continue; // another owner-loop advanced the cursor
const pending: Pending = cursor.pending;
- phase = 'admission';
+ phase = 'admission'; stampDrainStep('admission', signal);
const prior = await getWriteRequest(engine, cursor.authority.writer.principal, pending.requestId);
assertActive();
// #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.
@@ -1423,7 +1425,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
}), undefined, error => engine.reconnect({ error })).catch(error => cursorMovedAdmission(engine, key, admitting, pending, error));
if (!row) { cursor = await currentCursor(engine, key, cursor); continue; }
await validateSyncAuthority(engine, cursor.authority, pending.slug);
- assertSyncDispatchActive();
+ assertSyncDispatchActive(); stampDrainStep('await_receipt', signal);
// #5762: a checkpoint's validation runs under the coordinator's 5 s statement timeout, so its wait outlasts that
// budget; a timed-out checkpoint then reports its terminal refusal and hint in this run instead of the next.
// #5984: a drain re-enters anyway, so it waits longer per page instead of paying a full re-entry; its stop signal bounds the wait.
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index 62e8c5a88e..96d6139913 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -17,6 +17,7 @@ import { getWorktreeBinding } from './ownership.ts';
import { assertSyncPageOrigin, syncOriginScope } from './sync-origin.ts';
import { faultPoint } from './fault-points.ts';
import { pipelined } from '../page-state/transactions.ts';
+import { noteDrainSql } from './drain-step.ts';
import { REVISION_BACKFILL_PENDING } from '../page-state/types.ts';
import { withScreeningPaths } from './screening-paths.ts';
import { withBoundedReadSession } from './bounded-reads.ts';
@@ -161,6 +162,8 @@ export async function waiverBatchEnabled(engine: BrainEngine, env: NodeJS.Proces
return !(value === '0' || value === 'false');
}
export interface WaiverRunEntry { pending: WaiverEntry; waived: NoopWaiver }
+/** #6423: the most calls `waiveNoopRun` pipelines in one round trip (two per entry: the unfinished-request read and the delete origin check). */
+export const WAIVER_PIPELINE_MAX = 64;
/**
* #5984 Phase 3: commits a run of consecutive screened waivers at the cursor
* head in one transaction. It takes every page guard (in the engine's key
@@ -192,21 +195,27 @@ export async function waiveNoopRun<C extends WaiverCursor>(engine: BrainEngine,
'SELECT id,slug,deleted_at IS NOT NULL AS deleted,knowledge_revision FROM pages WHERE source_id=$1 AND slug=ANY($2::text[])', [cursor.sourceId, run.map(entry => entry.pending.slug)]);
const bySlug = new Map(pages.map(page => [page.slug, page]));
const scope = syncOriginScope(cursor);
- const checks = await pipelined(tx, run.flatMap(({ pending, waived }) => [
- () => tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending)),
- () => waived.kind === 'delete'
- ? assertSyncPageOrigin(tx, cursor.sourceId, pending.intent.sourcePath!, pending.pageId, true, scope).then(() => true, () => false)
- : Promise.resolve(true),
- ])) as Array<unknown[] | boolean>;
+ // #6423: the per-entry checks go out in pipelined chunks of at most WAIVER_PIPELINE_MAX calls, and a chunk is sent only
+ // while every entry before it validated (the prefix stops at the first entry that does not).
let valid = 0;
- for (const [i, { pending, waived }] of run.entries()) {
- const page = bySlug.get(pending.slug);
- const revision = page ? page.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(page.knowledge_revision) : null;
- if (!page || Number(page.id) !== pending.pageId || revision !== pending.intent.expected_revision) break;
- if (waived.kind === 'delete' ? !page.deleted || readSyncFile(cursor.root, pending.intent.path!) !== null : page.deleted) break;
- if ((checks[2 * i] as unknown[]).length || checks[2 * i + 1] !== true) break;
- if (waived.kind === 'import' && syncRawHash(cursor.root, pending.intent.path!) !== pending.intent.rawHash) break;
- valid++;
+ chunks: for (let from = 0; from < run.length; from += WAIVER_PIPELINE_MAX / 2) {
+ const chunk = run.slice(from, from + WAIVER_PIPELINE_MAX / 2);
+ noteDrainSql(UNFINISHED_PAGE_REQUEST_SQL);
+ const checks = await pipelined(tx, chunk.flatMap(({ pending, waived }) => [
+ () => tx.executeRaw(UNFINISHED_PAGE_REQUEST_SQL, unfinishedPageRequestParams(cursor, pending)),
+ () => waived.kind === 'delete'
+ ? assertSyncPageOrigin(tx, cursor.sourceId, pending.intent.sourcePath!, pending.pageId, true, scope).then(() => true, () => false)
+ : Promise.resolve(true),
+ ])) as Array<unknown[] | boolean>;
+ for (const [i, { pending, waived }] of chunk.entries()) {
+ const page = bySlug.get(pending.slug);
+ const revision = page ? page.knowledge_revision == null ? REVISION_BACKFILL_PENDING : String(page.knowledge_revision) : null;
+ if (!page || Number(page.id) !== pending.pageId || revision !== pending.intent.expected_revision) break chunks;
+ if (waived.kind === 'delete' ? !page.deleted || readSyncFile(cursor.root, pending.intent.path!) !== null : page.deleted) break chunks;
+ if ((checks[2 * i] as unknown[]).length || checks[2 * i + 1] !== true) break chunks;
+ if (waived.kind === 'import' && syncRawHash(cursor.root, pending.intent.path!) !== pending.intent.rawHash) break chunks;
+ valid++;
+ }
}
if (!valid) return null;
return { cursor: await advance(tx, run.slice(0, valid)), waived: valid, ...(valid < run.length ? { next: run[valid]!.pending } : {}) };
diff --git a/test/error-registry-6317-contract.test.ts b/test/error-registry-6317-contract.test.ts
index 5886a2f6e7..bbe50be5e7 100644
--- a/test/error-registry-6317-contract.test.ts
+++ b/test/error-registry-6317-contract.test.ts
@@ -95,7 +95,7 @@ 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']);
+ 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.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/persistence-claim-step.test.ts b/test/persistence-claim-step.test.ts
index 112b958c5a..8f3619e710 100644
--- a/test/persistence-claim-step.test.ts
+++ b/test/persistence-claim-step.test.ts
@@ -27,7 +27,7 @@ describe('enterClaimStep', () => {
enterClaimStep(clock, 'git_rev_parse', undefined, 'git', 2_500);
expect(clock).toMatchObject({ step: 'git_rev_parse', stepSince: 2_500, waitingOn: 'git' });
enterClaimPhase(clock, 'publishing', 3_000);
- expect(clock).toMatchObject({ phase: 'publishing', since: 3_000, step: null, stepSince: 3_000, waitingOn: 'unknown' });
+ expect(clock).toMatchObject({ phase: 'publishing', since: 3_000, step: null, stepSince: 3_000, waitingOn: 'publication' }); // #6405: the publish phase names its own wait
});
test('throws the preparation\'s abort reason at the boundary, with or without a clock, and leaves the clock unchanged', () => {
const abort = new AbortController();
diff --git a/test/sync-drain-inpass-stall.test.ts b/test/sync-drain-inpass-stall.test.ts
new file mode 100644
index 0000000000..4c5954b91e
--- /dev/null
+++ b/test/sync-drain-inpass-stall.test.ts
@@ -0,0 +1,112 @@
+/**
+ * #6405 (P2.1): every drain stop rule used to run between passes, so a pass that never returned (a publish that neither
+ * resolves nor rejects inside a delegated serve) was never stopped and the CLI waited forever. The in-pass governor races
+ * the pass: a live head claim in `publishing` past the publication ceiling ends the drain `blocked / drain_stalled /
+ * publication_overdue`, with or without the stall line (R6), and the abandoned pass is aborted and its late result ignored.
+ * Synthetic results only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { engineStallProbe } from '../src/core/persistence/sync-drain.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { drainNext, formatDrainSummary, runDrain, type DrainClaim, type StallProbe } from '../src/core/persistence/sync-drain.ts';
+import { enterClaimPhase, startClaimPhase } from '../src/core/persistence/claim-phase.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+
+const RESUME = 'gbrain sync --source s --no-pull';
+const done: SyncResult = { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [] };
+const publishing = (ageMs: number): DrainClaim => ({ phase: 'publishing', step: 'group_commit', waiting_on: 'publication', step_age_ms: ageMs, claim_age_ms: ageMs, lapsed: false,
+ owner_pid: 4242, owner_kind: 'serve', owner_nonce: 'n1', last_sql: { label: 'UPDATE persistence_requests', age_ms: ageMs }, allowance_ms: 150_000, ceiling_ms: 600_000 });
+const probeWith = (head: () => Promise<{ head_state: string; claim: DrainClaim | null; request_id?: string | null } | null>): StallProbe =>
+ ({ blockedHead: async () => null, fingerprint: async () => null, head });
+
+describe('in-pass governor: a publish that never returns', () => {
+ for (const announce of [true, false]) {
+ test(`a live claim in publishing past the ceiling stops the drain blocked/drain_stalled/publication_overdue (announce: ${announce})`, async () => {
+ let passSignal: AbortSignal | undefined;
+ const started = Date.now();
+ const result = await runDrain({ announce, progressMs: 20, governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 50,
+ probe: probeWith(async () => ({ head_state: 'running', request_id: 'req-head', claim: publishing(Date.now() - started) })),
+ pass: signal => { passSignal = signal; return new Promise<SyncResult>(() => undefined); } });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled',
+ stall: { cause: 'publication_overdue', in_pass: true, phase: 'publishing', step: 'group_commit', waiting_on: 'publication', head_request_id: 'req-head', owner_pid: 4242, ceiling_ms: 50 } });
+ expect(result.drain!.stall!.last_sql?.label).toBe('UPDATE persistence_requests');
+ expect(passSignal?.aborted).toBe(true);
+ const next = drainNext(result, RESUME, 's')!;
+ expect(next).toMatchObject({ command: 'gbrain sources writer status --source s --json', safe_to_loop: false, code: 'drain_stalled', cause: 'publication_overdue' });
+ expect(next.why).toContain('restart the gbrain serve process (pid 4242)');
+ expect(next.why).toContain('not reclaimed for you');
+ expect(formatDrainSummary(result, RESUME, 's').join('\n')).toContain('cause=publication_overdue');
+ });
+ }
+
+ test('a publish within the ceiling is left alone and the pass result is used', async () => {
+ const result = await runDrain({ governMs: 5, noProgressMs: 60_000, publicationCeilingMs: 10_000,
+ probe: probeWith(async () => ({ head_state: 'running', claim: publishing(10) })),
+ pass: () => new Promise<SyncResult>(resolve => setTimeout(() => resolve({ ...done, managedCursor: { index: 2, total: 2 } }), 80)) });
+ expect(result.drain).toMatchObject({ outcome: 'synced', passes: 1 });
+ });
+
+ test('a head read that never answers does not park the governor: past the window the stop is no_progress', async () => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 60, publicationCeilingMs: 60_000,
+ probe: probeWith(() => new Promise(() => undefined)), pass: () => new Promise<SyncResult>(() => undefined) });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled', stall: { cause: 'no_progress', in_pass: true } });
+ }, 15_000);
+
+ test('a late result or rejection of the abandoned pass is dropped', async () => {
+ let settle!: (value: SyncResult) => void, fail!: (error: Error) => void;
+ const started = Date.now();
+ const result = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 30,
+ probe: probeWith(async () => ({ head_state: 'running', claim: publishing(Date.now() - started) })),
+ pass: () => new Promise<SyncResult>((resolve, reject) => { settle = resolve; fail = reject; }) });
+ expect(result.drain?.stop_reason).toBe('drain_stalled');
+ fail(new Error('late')); settle({ ...done });
+ await new Promise(r => setTimeout(r, 20));
+ expect(result.drain?.outcome).toBe('blocked');
+ });
+
+ test('the publish phase stamps waiting_on publication instead of unknown', () => {
+ const clock = startClaimPhase(0);
+ expect(clock.waitingOn).toBe('unknown');
+ enterClaimPhase(clock, 'publishing', 1);
+ expect(clock.waitingOn).toBe('publication');
+ });
+});
+
+describe('in-pass governor over the real head read (engineStallProbe)', () => {
+ const engines: Array<[string, BrainEngine]> = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(['pglite', lite]); }
+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(['postgres', pg.engine]); closePostgres = pg.close; }
+ }, 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 () => {
+ 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}`]);
+ const [wt] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees(owner_host_id) VALUES(gen_random_uuid()) RETURNING id::text AS id');
+ const [src] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
+ await engine.executeRaw('INSERT INTO persistence_source_bindings(source_id,source_incarnation,worktree_id) VALUES($1,$2::uuid,$3::uuid)', [id, src!.incarnation, wt!.id]);
+ const token = randomUUID(), at = new Date(Date.now() - 600_000).toISOString();
+ const stamp = JSON.stringify({ phase: 'publishing', claimed_at: at, since: at, token, step: null, step_since: at, waiting_on: 'publication', owner: { kind: 'serve', pid: 4343, version: 'test', nonce: 'n2' },
+ last_sql: { label: 'UPDATE persistence_requests', at } });
+ const [row] = await engine.executeRaw<{ id: string }>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,worktree_id,digest,authority,intent,intent_bytes,terminal_reservation,
+ state,execution_token,claim_expires_at,claim_phase)
+ VALUES('local_cli','cli:example',$1::uuid,'submit_job',$2,$3::uuid,'notes/p',$4::uuid,'d','{}'::jsonb,'{"kind":"managed_sync_import","path":"notes/p.md"}'::jsonb,1,16384,'running',$5::uuid,now()+interval '30 seconds',$6::text::jsonb)
+ RETURNING id::text AS id`, [randomUUID(), id, src!.incarnation, wt!.id, token, stamp]);
+ const probe = engineStallProbe(engine, id);
+ const hung = await runDrain({ governMs: 10, noProgressMs: 60_000, publicationCeilingMs: 100, probe, pass: () => new Promise<SyncResult>(() => undefined) });
+ expect(hung.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'drain_stalled',
+ stall: { cause: 'publication_overdue', in_pass: true, head_request_id: row!.id, head_state: 'running', waiting_on: 'publication', owner_pid: 4343, owner_kind: 'serve' } });
+ 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 } });
+ }
+ }, 60_000);
+});
diff --git a/test/sync-drain-no-admission.test.ts b/test/sync-drain-no-admission.test.ts
new file mode 100644
index 0000000000..c9d4ef2f97
--- /dev/null
+++ b/test/sync-drain-no-admission.test.ts
@@ -0,0 +1,45 @@
+/**
+ * #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.
+ */
+import { describe, expect, test } from 'bun:test';
+import { drainNext, formatDrainSummary, runDrain, type StallProbe } from '../src/core/persistence/sync-drain.ts';
+import { noteDrainSql, readDrainStep, stampDrainStep } from '../src/core/persistence/drain-step.ts';
+import type { SyncResult } from '../src/commands/sync.ts';
+
+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 () => {
+ 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!.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');
+ 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');
+ });
+
+ test('the abandoned pass admits nothing more: its next step boundary throws the abort', async () => {
+ let signal: AbortSignal | undefined;
+ await runDrain({ governMs: 10, noProgressMs: 40, probe: empty, pass: s => { signal = s; return new Promise<SyncResult>(() => undefined); } });
+ expect(() => stampDrainStep('admission', signal)).toThrow();
+ expect(readDrainStep()).toBeNull();
+ });
+
+ test('a pass that commits keeps the governor quiet', async () => {
+ const result = await runDrain({ governMs: 10, noProgressMs: 60, probe: empty, pass: async (_signal, onProgress) => {
+ for (let i = 1; i <= 6; i++) { await new Promise(r => setTimeout(r, 25)); onProgress({ phase: 'managed_sync.page_committed', bankedFiles: i, total: 6 }); }
+ return { status: 'synced', fromCommit: 'a', toCommit: 'b', added: 6, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], managedCursor: { index: 6, total: 6 } };
+ } });
+ expect(result.drain).toMatchObject({ outcome: 'synced', written: 6 });
+ });
+});
diff --git a/test/sync-waivers-chunk.test.ts b/test/sync-waivers-chunk.test.ts
new file mode 100644
index 0000000000..f0ca62c1d9
--- /dev/null
+++ b/test/sync-waivers-chunk.test.ts
@@ -0,0 +1,74 @@
+/**
+ * #6423 (P2.2, mitigation, not the hang reproduction): `waiveNoopRun` used to pipeline every entry's checks in one round
+ * 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
+ * test in test/sync-drain-no-admission.test.ts. Synthetic data only.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { UNFINISHED_PAGE_REQUEST_SQL, WAIVER_PIPELINE_MAX, waiveNoopRun, type WaiverCursor, type WaiverRunEntry } from '../src/core/persistence/sync-waivers.ts';
+
+const root = mkdtempSync(join(tmpdir(), 'waiver-chunk-'));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+const cursor = { sourceId: 's1', incarnation: '1', root, gitRoot: root, slugMode: 'git-root', binding: { worktree_id: '00000000-0000-0000-0000-000000000001' },
+ authority: {} as WaiverCursor['authority'], runId: 'run-1', index: 0 } as WaiverCursor;
+const entries = (n: number): WaiverRunEntry[] => Array.from({ length: n }, (_, i) => ({
+ pending: { requestId: `r${i}`, slug: `p${i}`, pageId: i + 1, intent: { kind: 'managed_sync_delete', path: `p${i}.md`, sourcePath: `p${i}.md`, expected_revision: '7', ownerEpoch: '3' } as never },
+ waived: { kind: 'delete', kernel: [] } }));
+
+function fakeEngine(opts: { busySlugs?: Set<string> } = {}) {
+ let outstanding = 0, peak = 0, unfinishedReads = 0;
+ const statement = <T>(value: T): Promise<T> => {
+ outstanding++; peak = Math.max(peak, outstanding);
+ return new Promise(resolve => setTimeout(() => { outstanding--; resolve(value); }, 1));
+ };
+ const tx = {
+ kind: 'postgres',
+ lockPageKeys: async () => undefined,
+ executeRaw: async (sql: string, params: unknown[] = []) => {
+ if (sql.includes('set_config')) return [];
+ if (sql.includes('FROM op_checkpoints')) return [{ run_id: 'run-1', index: 0, request_id: null }];
+ if (sql.includes('FROM persistence_source_bindings')) return [{ owner_epoch: '3' }];
+ if (sql.startsWith('SELECT id,slug,deleted_at')) return (params[1] as string[]).map(slug => ({ id: Number(slug.slice(1)) + 1, slug, deleted: true, knowledge_revision: '7' }));
+ if (sql === UNFINISHED_PAGE_REQUEST_SQL) { unfinishedReads++; return statement(opts.busySlugs?.has(String(params[3])) ? [{ id: 'busy' }] : []); }
+ if (sql.startsWith('SELECT id,slug,source_path FROM pages')) { const path = (params[1] as string[])[0]!; const i = Number(/p(\d+)\.md/.exec(path)![1]); return statement([{ id: i + 1, slug: `p${i}`, source_path: path }]); }
+ throw new Error(`unexpected SQL: ${sql.slice(0, 60)}`);
+ },
+ };
+ const engine = { kind: 'postgres', transaction: async <T>(fn: (t: BrainEngine) => Promise<T>) => fn(tx as unknown as BrainEngine) } as unknown as BrainEngine;
+ return { engine, peak: () => peak, unfinishedReads: () => unfinishedReads };
+}
+
+describe('waiveNoopRun pipeline chunks (#6423 mitigation)', () => {
+ test('64 delete entries: no round trip carries more than WAIVER_PIPELINE_MAX statements, and all 64 are waived', async () => {
+ const fake = fakeEngine();
+ let advanced = 0;
+ const done = await waiveNoopRun(fake.engine, cursor, entries(64), 'key', async (_tx, prefix) => { advanced = prefix.length; return { ...cursor, index: prefix.length }; }, async () => cursor);
+ expect(WAIVER_PIPELINE_MAX).toBe(64);
+ expect(fake.peak()).toBeGreaterThan(1);
+ expect(fake.peak()).toBeLessThanOrEqual(WAIVER_PIPELINE_MAX);
+ expect(done).toMatchObject({ waived: 64 });
+ expect(done!.next).toBeUndefined();
+ expect(advanced).toBe(64);
+ });
+
+ test('the prefix stops at the first entry that fails, and no chunk after it is sent', async () => {
+ const fake = fakeEngine({ busySlugs: new Set(['p5']) });
+ const done = await waiveNoopRun(fake.engine, cursor, entries(64), 'key', async (_tx, prefix) => ({ ...cursor, index: prefix.length }), async () => cursor);
+ expect(done).toMatchObject({ waived: 5 });
+ expect(done!.next?.slug).toBe('p5');
+ expect(fake.unfinishedReads()).toBe(WAIVER_PIPELINE_MAX / 2);
+ });
+
+ test('a failure in a later chunk keeps every entry before it', async () => {
+ const fake = fakeEngine({ busySlugs: new Set(['p40']) });
+ const done = await waiveNoopRun(fake.engine, cursor, entries(64), 'key', async (_tx, prefix) => ({ ...cursor, index: prefix.length }), async () => cursor);
+ expect(done).toMatchObject({ waived: 40 });
+ expect(done!.next?.slug).toBe('p40');
+ });
+});