Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(sync): capacity preflight and a resumable capacity_paused stop (#6696 A7)
garrytan64370344a5b2
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 97f149f8e5..06ade0f67e 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -363,6 +363,18 @@ More: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../|---|---|---|---|---|---|---|| The write was cancelled before it 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 |+### capacity_paused++<a id="capacity_paused"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A managed sync passed its capacity preflight, then a cumulative write cap (or the background pause line) refused its next admission, so the drain stopped resumable with its cursor and accepted writes intact; nothing failed. | Another writer used the capacity the preflight counted on. Request ids never free, so only the brain host's reversible config raise resumes an ids pause; receipt bytes also free as receipts compact. | Run the gbrain config set the drain report names on the brain host (gbrain doctor --only persistence_capacity --json prints it), then rerun the same gbrain sync; it resumes at the stored cursor. | host_admin | `gbrain doctor --json` | 1 | no |++Reasons: `lifetime_ids`, `terminal_bytes`.++More: [docs/guides/write-refusals.md#drain-capacity-paused](../../docs/guides/write-refusals.md#drain-capacity-paused)+### catalog_capacity_exceeded<a id="catalog_capacity_exceeded"></a>diff --git a/docs/guides/sync-unblock-runbook.md b/docs/guides/sync-unblock-runbook.mdindex 5eb106888d..34f61a5925 100644--- a/docs/guides/sync-unblock-runbook.md+++ b/docs/guides/sync-unblock-runbook.md@@ -107,6 +107,7 @@ Every hold and error has three fields, from one table| `database_contention` | connection | retry | no | three reruns in a row stop on it || `write_capacity` | connection | retry | no | writer status shows the cap held by requests that never settle || `write_capacity_backpressure` | connection | retry | no | reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day |+| `capacity_paused` | connection | retry | no | reason lifetime_ids (only the host raise resumes it), or the same pause after the raise || `storage_error` | connection | retry | no | the same error after a rerun (then it is not a dropped connection) || `graduation_in_progress` | connection | retry | no | gbrain migrate --status --json reports no running move and the fence still refuses || `preparation_systemic` | systemic | upgrade, retry | yes | always |diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 8af2af794a..a52d58685c 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -487,6 +487,7 @@ retry_after_ms, eta_seconds, rate_pages_per_min, why, docs }`. Run| <a id="preparation_systemic"></a><a id="drain-preparation-systemic"></a>`preparation_systemic` | `preparation_systemic` | `blocked` | The run's breaker tripped: more `preparation_stalled` receipts than a source should hold (the `sync.hold_escalate_count` / `sync.hold_escalate_pct` rule over this run's screened imports) or five stalled entries in a row with no page committed between them. The run stopped with one diagnostic instead of holding every file: the write owner, not the files, is the likely cause. `breaker` carries the rule, the counts, the last step and the fix; exit 1. | `gbrain sources writer status --source <source> --json`, fix what it names or upgrade gbrain, then rerun the same sync: it re-freezes the stopped entry under a fresh request and schedules the files this run held for a re-screen. || <a id="drain-write-capacity"></a>`write_capacity` | `queue_capacity` | `blocked` | The sync could not admit its next write for the whole no-progress window (30 s) because other writers' requests held the outstanding-request cap of its write principal (`persistence.limits.principal_outstanding`, default 100; the brain cap `persistence.limits.brain_outstanding`, 1000, works the same way): on one host the CLI sync and a maintenance run (fact-fence adoption, `dream`) share the `local_cli` principal, so a long adoption queue leaves no room for a sync write. Nothing failed and the cursor is intact: the drain retried the admission with backoff while they settled, printing `waiting for write capacity (N outstanding of M)`, and stopped only when the window passed. `drain.capacity` carries the counts and the wait; exit 1. A cumulative cap (permanent request IDs, receipt bytes) is a different refusal: it names its config key and stops at once. | `gbrain sources writer status --source <source> --json` lists the outstanding requests (read-only). Let them finish, or raise the cap (`gbrain config set persistence.limits.principal_outstanding 200`), then rerun the same sync; it resumes where it stopped. || <a id="drain-connection-lost"></a>`connection_lost` | `connection_lost` | `blocked` | The database connection dropped three times in a row (`write ECONNABORTED`, `ECONNRESET`, `ETIMEDOUT`, `EPIPE`: a pooler closing the socket mid-statement) with no page committed between the drops (#6340). Each drop was reconnected and retried after 5, 15 and 45 s; a drop that then moves data is not reported at all. Nothing is recorded against the source: the cursor and its frozen manifest stand, and `drain.connection` carries the count and the last error text (never a URL). Exit 1. | Check the database and pooler (`gbrain doctor --json`), then rerun `next.command` (`safe_to_loop` is true, `retry_after_ms` 60 s): it resumes at the stored cursor without re-freezing the manifest, with or without `--retry-failed`. Runbook: [sync unblock](sync-unblock-runbook.md#connection). |+| <a id="drain-capacity-paused"></a>`capacity_paused` | `capacity_paused` | `resumable` | The run passed its capacity preflight, then a cumulative write cap refused its next admission (`write_quota_exhausted`) or, for a background sync, the pause line did (`write_capacity_backpressure`): another writer used the room the preflight counted on. Nothing failed; the cursor and every accepted write stand, and `drain.capacity_pause` names the refusal and its config raise. | Run the `gbrain config set` the report names on the brain host (request ids never free; receipt bytes also free as receipts compact), then rerun the same `gbrain sync`. Verify with `gbrain doctor --only persistence_capacity --json`. || <a id="head-blocked"></a>`drain_stalled` with `cause: head_blocked` | `drain_stalled` | `blocked` | The queued write at the head of the source cannot be claimed by any consumer, and its blocker needs an operator (#6543). `drain.stall.blocked_by` names the predicate, its ids, state and owner: `refresh_fence` (a refresh left the checkout `fenced`, `merged` or `recovery_required` and no refresh process holds its lock) or `zombie_publication` (a running request ahead of the head is held by a process that reports `restart_required`). The drain stops after one governor tick of confirmation instead of the no-progress window. Live blockers (`root_hold`, a foreground publication; `lease`, a lapsed claim the next consumer reclaims; `withdrawal_mirror`, `effect_recovery`, `request_recovery`, `worktree_owner`) never stop it: the stall line names them as `blocked_by=` beside `consumer=` and the drain keeps waiting. `claimable here` is read for the head itself and prints `unknown` when the probe could not read it. | Run `next.fix`: `refresh_fence` resumes the refresh (`gbrain sources refresh <source> --resume`, which lifts the fence or names why it cannot); `zombie_publication` tells the host admin to restart the named process. Then rerun the sync. `gbrain sources writer status --source <source> --json` names the same blocker for every queued head and, only when the caller may cancel the blocking request, `gbrain cancel-write-request <request_id>`. |## Unbound sources on Postgresdiff --git a/src/commands/sync.ts b/src/commands/sync.tsindex 931fd56e28..8d92c08a69 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -174,6 +174,8 @@ export interface SyncOpts {* Threaded through performSync AND syncOneSource so `sync --all` honors it.*/noSchemaPack?: boolean;+ /** #6696 (A7): server-only; the drain's first pass checks the run's estimated receipts against the capacity left before admitting. */+ capacityPreflight?: boolean;/** Processing options this caller set; an unfinished managed cursor supplies the rest (unset = all explicit). */explicitProcessing?: Array<'noEmbed' | 'noExtract' | 'noSchemaPack'>;/**diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex fc0fe626f2..18fcc72ee0 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -90,6 +90,7 @@ export const ERROR_CATALOGUE = {sync_drain_preparation_systemic: { code: 'preparation_systemic', docs: 'docs/guides/write-refusals.md#preparation_systemic' },sync_drain_write_capacity: { code: 'queue_capacity', docs: 'docs/guides/write-refusals.md#drain-write-capacity' },sync_drain_connection_lost: { code: 'connection_lost', docs: 'docs/guides/write-refusals.md#drain-connection-lost' },+ sync_drain_capacity_paused: { code: 'capacity_paused', docs: 'docs/guides/write-refusals.md#drain-capacity-paused' },sync_drain_head_blocked: { code: 'drain_stalled', docs: 'docs/guides/write-refusals.md#head-blocked' },// D8 `gbrain setup <harness>` (src/commands/setup.ts).setup_harness_unsupported: { code: 'setup_harness_unsupported', docs: 'docs/guides/repair.md#setup-harness-unsupported' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex e594bd752c..8951efa79a 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -85,6 +85,11 @@ export const CODES = {budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },+ capacity_paused: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'],+ summary: "A managed sync passed its capacity preflight, then a cumulative write cap (or the background pause line) refused its next admission, so the drain stopped resumable with its cursor and accepted writes intact; nothing failed.",+ why: "Another writer used the capacity the preflight counted on. Request ids never free, so only the brain host's reversible config raise resumes an ids pause; receipt bytes also free as receipts compact.",+ docs: 'docs/guides/write-refusals.md#drain-capacity-paused',+ suggestion: 'Run the gbrain config set the drain report names on the brain host (gbrain doctor --only persistence_capacity --json prints it), then rerun the same gbrain sync; it resumes at the stored cursor.' },catalog_capacity_exceeded: { class: 'caller', summary: "The shared-skills catalog visible to this connection exceeds the delivery limits.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },changed_since_preview: { class: 'caller', summary: "The file changed after its repair was previewed, so nothing was written.", why: "A repair writes exactly the bytes the operator approved; it binds approval to the previewed file hash and refuses when the file moved on.", suggestion: 'Preview the repair again, review the new proposal, and approve its new hash.' },diff --git a/src/core/persistence/receipt-bytes.ts b/src/core/persistence/receipt-bytes.tsindex 4fd8a24536..a4e8ba4217 100644--- a/src/core/persistence/receipt-bytes.ts+++ b/src/core/persistence/receipt-bytes.ts@@ -19,7 +19,11 @@ export const EFFECT_BYTES_SQL = 'octet_length(data::text)+octet_length(kind)+102*/export function receiptReservation(fields: { intent?: unknown; authority?: unknown }, extra = 0): number {const json = (value: unknown) => value === null || value === undefined ? 0 : jsonBytes(value);- return Math.max(RECEIPT_RESERVATION_FLOOR, json(fields.intent) + json(fields.authority) + RECEIPT_COMPLETION_BYTES) + extra;+ return reservationForRetained(json(fields.intent) + json(fields.authority), extra);+}+/** The same reservation from the retained bytes alone (a sync preflight estimates them from file sizes before it builds intents). */+export function reservationForRetained(retained: number, extra = 0): number {+ return Math.max(RECEIPT_RESERVATION_FLOOR, retained + RECEIPT_COMPLETION_BYTES) + extra;}/** The receipt fields that stay on the row, by name. */diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.tsindex 5f4e531ac3..d0daf96ebe 100644--- a/src/core/persistence/sync-drain.ts+++ b/src/core/persistence/sync-drain.ts@@ -39,7 +39,16 @@ export type DrainStopReason = 'deadline' | 'drain_stalled' | 'database_contentio/** #6278 (B7): the sync's next admission was refused for the whole no-progress window because other requests held the writer's outstanding-request cap. */| 'write_capacity'/** #6340: the database connection dropped `CONNECTION_STRIKES` times in a row with no page committed between the drops; the cursor stands, the same command resumes it. */- | 'connection_lost';+ | 'connection_lost'+ /** #6696 (A7): a cumulative write cap (or the background pause line) refused the next admission after the preflight passed; resumable once capacity returns. */+ | 'capacity_paused';+/** #6696 (A7): the refusal that paused the drain (`capacity_paused`); `fix_argv` is the host's config raise. */+export interface DrainCapacityPause { code: string; reason: string | null; detail: string | null; message: string; fix_argv?: string[] }+/** A capacity refusal raised by an admission after the run's preflight (the preflight's own refusal stops the command up front). */+export function isCapacityPause(error: unknown): boolean {+ return error instanceof OperationError && ['write_quota_exhausted', 'write_capacity_backpressure', 'write_quota_insufficient'].includes(error.code)+ && (error as { capacityPreflight?: true }).capacityPreflight !== true;+}/** #6278 (B7): what the drain waited on when `write_capacity` stopped it: the counts the last refusal carried and how long it waited. */export interface DrainCapacityWait { outstanding: number | null; limit: number | null; scope: 'principal' | 'brain' | null; waited_seconds: number }/** #6278: what a stalled head's live claim says it is doing (`claim_phase`, stamped by its owner on every renewal). */@@ -126,6 +135,8 @@ export interface DrainReport {retry_after_ms?: number;stall?: DrainStall;capacity?: DrainCapacityWait;+ /** #6696 (A7): present on `capacity_paused`. */+ capacity_pause?: DrainCapacityPause;/** #6340 `connection_lost`: how many drops in a row ended the drain and the last error's text (message only, never a URL). */connection?: { drops: number; last_error: string };/** #6340: HEAD moved past the pinned target while the run drained, so the drain took exactly one more pass for the commits since (never a second). */@@ -479,6 +490,12 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {// #6278 (B7): other requests (another writer on the same principal, or the brain) hold the outstanding-request cap, so the pass// could not admit its next write. They settle on their own: wait with backoff, say so, and past the no-progress window stop// `blocked` with the counts and the writer to inspect, never an uncaught exit without a drain summary.+ // #6696 (A7): past the preflight, a cumulative cap or the background pause stops the run resumable, never as a failure.+ if (isCapacityPause(error)) {+ const e = error as OperationError;+ return finish(last ?? NO_PASS_RESULT, 'resumable', 'capacity_paused', { capacity_pause: { code: e.code, reason: e.reason ?? null, detail: e.detail ?? null,+ message: e.message, ...(e.fix?.argv ? { fix_argv: e.fix.argv } : {}) } });+ }if (isWriteCapacityWait(error) && !signal?.aborted) {capacity ??= { since: clock(), attempts: 0 };const counts = outstandingCapacityOf(error), waitedMs = clock() - capacity.since;@@ -719,11 +736,17 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno+ `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;try {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 } } : {}) }) });+ pass: (signal, onProgress) => {+ const capacityPreflight = !preflighted;+ preflighted = true;+ return performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, capacityPreflight, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) });+ } });} finally {if (laneRun) {const stats = await closeLaneRun(laneRun);@@ -819,7 +842,7 @@ const STOP_DOCS: Record<DrainStopReason, CatalogueName> = {recovery_required: 'sync_drain_writer_blocked', owner_unavailable: 'sync_drain_writer_blocked', unexpected_file_bytes: 'sync_drain_writer_blocked',unexpected_staging_bytes: 'sync_drain_writer_blocked', blocked_by_failures: 'sync_drain_blocked_by_failures',preparation_abandoned: 'sync_drain_preparation_abandoned', preparation_systemic: 'sync_drain_preparation_systemic', write_capacity: 'sync_drain_write_capacity',- connection_lost: 'sync_drain_connection_lost',+ connection_lost: 'sync_drain_connection_lost', capacity_paused: 'sync_drain_capacity_paused',};/** What the agent runs next, or null when the sync is done (DX-A2). */@@ -829,6 +852,14 @@ export function drainNext(result: SyncResult, resumeCommand: string, sourceId: sconst d = result.drain;const estimate = { eta_seconds: d?.eta_seconds ?? null, rate_pages_per_min: d?.rate_pages_per_min ?? null };const docs = d?.stop_reason ? ERROR_CATALOGUE[STOP_DOCS[d.stop_reason]].docs : undefined;+ if (outcome === 'resumable' && d?.stop_reason === 'capacity_paused') {+ const pause = d.capacity_pause;+ const raise = pause?.fix_argv?.join(' ');+ return { command: resumeCommand, safe_to_loop: false, retry_after_ms: 0, ...estimate, code: 'capacity_paused',+ why: `The sync paused: ${pause?.message ?? 'a cumulative write cap refused its next admission'} Nothing failed; the cursor and every accepted write are intact. `+ + `${pause?.reason === 'lifetime_ids' ? 'Request ids never free, so ' : ''}${raise ? `the brain host runs ${raise} (reversible)` : 'the brain host raises the cap gbrain doctor --only persistence_capacity --json names'}`+ + `${pause?.reason === 'terminal_bytes' ? ', or receipts compact over time' : ''}; then rerun: ${resumeCommand}`, ...(docs ? { docs } : {}) };+ }if (outcome === 'resumable') {const abandoned = d?.stop_reason === 'preparation_abandoned';return { command: resumeCommand, safe_to_loop: true, retry_after_ms: d?.retry_after_ms ?? 0, ...estimate,diff --git a/src/core/persistence/sync-fault-class.ts b/src/core/persistence/sync-fault-class.tsindex 57bd97d3ef..e2c4a826dc 100644--- a/src/core/persistence/sync-fault-class.ts+++ b/src/core/persistence/sync-fault-class.ts@@ -80,6 +80,8 @@ export const SYNC_FAULT_TABLE: ReadonlyArray<SyncFaultRule> = [// #6696 (A5): a background sync paused near a cumulative cap; interactive writes keep the rest and the pause lifts as capacity returns.{ code: 'write_capacity_backpressure', class: 'connection', safe_actions: ['retry'], needs_human: false,escalate: 'reason lifetime_ids (request ids never free, so only the host raise lifts it), or the pause outlasts a day' },+ { code: 'capacity_paused', class: 'connection', safe_actions: ['retry'], needs_human: false,+ escalate: 'reason lifetime_ids (only the host raise resumes it), or the same pause after the raise' },{ code: 'storage_error', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'the same error after a rerun (then it is not a dropped connection)' },// #6513: the engine-graduation fence (SQLSTATE 55000) refuses every write until the move finishes; the cursor and manifest stand.{ code: 'graduation_in_progress', class: 'connection', safe_actions: ['retry'], needs_human: false, escalate: 'gbrain migrate --status --json reports no running move and the fence still refuses' },diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.tsindex 8564b9a56c..ce182fe41e 100644--- a/src/core/persistence/sync-run.ts+++ b/src/core/persistence/sync-run.ts@@ -7,8 +7,10 @@ import { readFix } from '../ops/op-fix.ts';import type { RegistryCode } from '../error-registry.ts';import { currentSourceFilesystemSignal } from '../minions/source-filesystem.ts';import { throwIfAborted } from '../abort-check.ts';-import { digest, sha256 } from './digest.ts';-import { getWriteRequest, admitWriteInTransaction, foregroundPriority, intentDigest, receiptFor } from './journal.ts';+import { digest, jsonBytes, sha256 } from './digest.ts';+import { getWriteRequest, admitWriteInTransaction, assertWriteHeadroom, foregroundPriority, intentDigest, receiptFor } from './journal.ts';+import { readBackgroundPauseShare, resolveAdmissionOrigin } from './admission-origin.ts';+import { reservationForRetained } from './receipt-bytes.ts';import { preparationConfigView } from './config-snapshot.ts';import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';@@ -22,6 +24,7 @@ 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 { statSync } from 'node:fs';import { resolve } from 'node:path';import { currentCompanyBrainSync, getCompanyBrainProfile, readCompanyBrainPlan } from '../company-brain/profile.ts';import { readCommittedBlob } from '../company-brain/revision.ts';@@ -1388,6 +1391,26 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl}}+/**+ * #6696 (A7): before a run's first admission, its remaining manifest entries (one request id each, and the+ * admission reservation estimator over each file's size and the writer authority) must fit the capacity left under the caller's line: the background pause+ * for a background run, the cap for an operator's. A shortfall refuses `write_quota_insufficient` (writes still+ * work) with the raise that covers the run; the refusal is marked so the drain stops the command instead of+ * pausing it.+ */+/** An intent's fields beside the file content (kind, paths, hashes, revision), estimated. */+const PREFLIGHT_INTENT_FIELDS_BYTES = 512;+async function preflightSyncCapacity(engine: BrainEngine, cursor: Cursor): Promise<void> {+ const remaining = cursor.entries.slice(cursor.index);+ if (!remaining.length) return;+ const authority = jsonBytes(cursor.authority.writer);+ const size = (path: string) => { try { return statSync(resolve(cursor.root, path)).size; } catch { return 0; } };+ const bytes = remaining.reduce((n, entry) => n + reservationForRetained(authority + PREFLIGHT_INTENT_FIELDS_BYTES + (entry.action === 'import' ? size(entry.path) : 0)), 0);+ const share = resolveAdmissionOrigin() === 'background' ? await readBackgroundPauseShare(engine) : 1;+ try { await assertWriteHeadroom(engine, cursor.authority.writer.principal, { ids: remaining.length, bytes }, share); }+ catch (error) { throw Object.assign(error as object, { capacityPreflight: true as const }); }+}+async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPages: number; maxMs: number } | undefined, state: HoldRunState): Promise<SyncResult> {await assertManagedSyncActive(engine);if (opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId)) {@@ -1521,6 +1544,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPconst sliceStarted = performance.now(), sliceFirstIndex = cursor.index, drainStartedAt = opts.drainStartedAt ?? Date.now();const bulk: BulkPass = { settings: opts.bulk && !company ? opts.bulk : { enabled: false, reason: null, size: 1, maxTxnMs: 0 }, perMemberMs: null, foregroundFirst: await foregroundPriority(engine) };const waiveBatch = noopWaiversEnabled() && await waiverBatchEnabled(startupConfig);+ if (opts.capacityPreflight && !cursor.done) await preflightSyncCapacity(engine, cursor);opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });while (!cursor.done) {assertActive();diff --git a/test/sync-capacity-preflight.test.ts b/test/sync-capacity-preflight.test.tsnew file mode 100644index 0000000000..a257427c17--- /dev/null+++ b/test/sync-capacity-preflight.test.ts@@ -0,0 +1,118 @@+/**+ * #6696 (A7): a managed sync checks its remaining manifest (one request id+ * per entry and the admission reservation estimator over each file's size) against the capacity left+ * under its line (the cap for an operator's run, the background pause line+ * otherwise) before its first admission, and refuses `write_quota_insufficient`+ * with the config raise, admitting nothing. A run that passed the preflight+ * and is then refused by a cap a competing writer filled stops resumable+ * (`capacity_paused`), never as a failure, and the same command resumes it.+ * Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { withAdmissionOrigin } from '../src/core/persistence/admission-origin.ts';+import { drainManagedSync, drainNext, runDrain } from '../src/core/persistence/sync-drain.ts';+import { ERROR_CATALOGUE } from '../src/core/error-catalogue.ts';+import type { SyncResult } from '../src/commands/sync.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const base: SyncResult = { status: 'partial', reason: 'writer_yield', fromCommit: 'a', toCommit: 'b', added: 1, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0,+ pagesAffected: [], managedCursor: { index: 1, total: 3 } };+const RESUME = 'gbrain sync --source s --no-pull';+const exhausted = () => {+ const error = new OperationError('write_quota_exhausted', 'Write capacity exhausted: principal permanent request IDs (5 used of 5).', 'raise it');+ Object.assign(error, { reason: 'lifetime_ids', detail: 'principal_lifetime_ids',+ fix: { argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', '100'], consent: [], actor: 'host_admin', requires_exclusive: false, why: 'raise' } });+ return error;+};++describe('capacity_paused in the drain', () => {+ test('a cap refusal after the preflight stops resumable with the refusal and the raise; a preflight refusal is rethrown', async () => {+ let passes = 0;+ const result = await runDrain({ backoffMs: 5, pass: async () => { if (++passes === 1) return base; throw exhausted(); } });+ expect(result).toMatchObject({ added: 1, drain: { outcome: 'resumable', stop_reason: 'capacity_paused', remaining: 2,+ capacity_pause: { code: 'write_quota_exhausted', reason: 'lifetime_ids', fix_argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', '100'] } } });+ const next = drainNext(result, RESUME, 's')!;+ expect(next).toMatchObject({ command: RESUME, code: 'capacity_paused', docs: ERROR_CATALOGUE.sync_drain_capacity_paused.docs });+ expect(next.why).toContain('gbrain config set persistence.limits.principal_lifetime_ids 100');+ expect(next.why).toContain('Request ids never free');+ const preflight = Object.assign(exhausted(), { capacityPreflight: true });+ await expect(runDrain({ backoffMs: 5, pass: async () => { throw preflight; } })).rejects.toBe(preflight);+ });+});++describe('forced probe: a real managed sync against a cap', () => {+ const engines: BrainEngine[] = [];+ let closePostgres: (() => Promise<void>) | undefined;+ const home = mkdtempSync(join(tmpdir(), 'gbrain-sync-preflight-'));+ beforeAll(async () => {+ if (testBackends().includes('pglite')) { const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite); }+ if (testBackends().includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }+ }, 120_000);+ afterAll(async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.(); rmSync(home, { recursive: true, force: true });+ });++ test('the preflight refuses before any admission; a competing writer mid-run pauses it resumable; the rerun finishes', () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {+ for (const engine of engines) {+ const id = `pre-${randomUUID().replace(/-/g, '').slice(0, 20)}`, root = join(home, id);+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });+ const write = (name: string) => writeFileSync(join(root, 'notes', `${name}.md`), `---\ntitle: ${name}\n---\nA synthetic observation about ${name}.\n`);+ const commit = (message: string) => { git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+ mkdirSync(join(root, 'notes'), { recursive: true });+ git('init', '-q'); write('a'); commit('fixture');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);+ await claimWorktree(engine, id, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true };+ const requests = async () => Number((await engine.executeRaw<{ n: string }>('SELECT count(*)::text AS n FROM persistence_requests WHERE source_id=$1', [id]))[0]!.n);+ const ids = async () => Number((await engine.executeRaw<{ n: string }>("SELECT lifetime_ids::text AS n FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'"))[0]!.n);+ const operator = <T>(fn: () => Promise<T>) => withAdmissionOrigin('interactive', fn);+ try {+ expect((await operator(() => drainManagedSync(engine, opts, false))).drain).toMatchObject({ outcome: 'synced', written: 1 });+ // Three new files, room for two more ids: the operator's run refuses up front.+ write('b'); write('c'); write('d'); commit('three more');+ const before = await requests();+ await engine.setConfig('persistence.limits.principal_lifetime_ids', String(await ids() + 2));+ const refusal = await operator(() => drainManagedSync(engine, opts, false)).then(() => null, error => error);+ expect(refusal).toMatchObject({ code: 'write_quota_insufficient', reason: 'lifetime_ids', fix: { actor: 'host_admin',+ argv: ['gbrain', 'config', 'set', 'persistence.limits.principal_lifetime_ids', expect.stringMatching(/^\d+$/)] } });+ expect(await requests()).toBe(before);+ // Enough room for the run: the first pass admits one page, then a competing writer fills the cap.+ await engine.setConfig('persistence.limits.principal_lifetime_ids', String(await ids() + 3));+ let passes = 0;+ const paused = await operator(() => runDrain({ announce: false, backoffMs: 10, pass: async (signal, onProgress) => {+ const { performManagedSync } = await import('../src/core/persistence/sync-run.ts');+ if (++passes === 2) await engine.executeRaw("UPDATE persistence_counters SET lifetime_ids=(SELECT value::bigint FROM config WHERE key='persistence.limits.principal_lifetime_ids') WHERE key LIKE 'principal:local_cli:%'");+ return performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt: Date.now(), capacityPreflight: passes === 1 }, { maxPages: 1, maxMs: 60_000 });+ } }));+ expect(paused.drain).toMatchObject({ outcome: 'resumable', stop_reason: 'capacity_paused', capacity_pause: { code: 'write_quota_exhausted', reason: 'lifetime_ids' } });+ expect(await engine.getPage('notes/d', { sourceId: id })).toBeNull();+ await engine.unsetConfig('persistence.limits.principal_lifetime_ids');+ expect((await operator(() => drainManagedSync(engine, opts, false))).drain).toMatchObject({ outcome: 'synced' });+ for (const name of ['b', 'c', 'd']) expect(await engine.getPage(`notes/${name}`, { sourceId: id })).not.toBeNull();+ // A ~300 KB file reserves its size, not the 16 KiB floor: 100 KB of byte room refuses up front.+ writeFileSync(join(root, 'notes', 'large.md'), `---\ntitle: large\n---\n${'A synthetic line of prose.\n'.repeat(11_000)}`); commit('large');+ const bytes = Number((await engine.executeRaw<{ n: string }>("SELECT terminal_bytes::text AS n FROM persistence_counters WHERE key LIKE 'principal:local_cli:%'"))[0]!.n);+ await engine.setConfig('persistence.limits.principal_terminal_bytes', String(bytes + 100_000));+ const large = await operator(() => drainManagedSync(engine, opts, false)).then(() => null, error => error);+ expect(large).toMatchObject({ code: 'write_quota_insufficient', reason: 'terminal_bytes' });+ expect(await engine.getPage('notes/large', { sourceId: id })).toBeNull();+ await engine.unsetConfig('persistence.limits.principal_terminal_bytes');+ } finally { await engine.unsetConfig('persistence.limits.principal_lifetime_ids'); await engine.unsetConfig('persistence.limits.principal_terminal_bytes'); await disposePersistenceConsumer(engine); }+ }+ }), 180_000);+});