Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(sync): bulk group publication for managed Postgres catch-up; each page keeps its own request (#5984)

garrytan25a945cc52a9
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index ba01957be5..9f6d4f219f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -12,7 +12,7 @@ src/commands/extract.ts 2528 ratchet grown v0.46.26.0 megawave: FS-walk stamp sn
src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)
src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts
src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts)
-src/commands/sync.ts 486 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts)
+src/commands/sync.ts 487 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields
src/core/cycle.ts 3205 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts)
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
-src/core/config.ts 1821 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys
+src/core/config.ts 1825 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1); +1 #5836: facts.entity_inference key row; +6 #5824: search.vector_legacy_guard key row + GBrainConfig.search slot + DB-plane merge; +3 wave 8 lane D1 #5885: takes.auto_embed key row; +3 #5232: GBrainConfig.persistence.write_wait_ms file-plane slot + key row (resolver in persistence/write-wait.ts); +2 F4b: planner.* and import.analyze_every_pages keys; +4 #5984: sync.bulk, sync.bulk_size, sync.bulk_max_txn_ms known keys
src/core/bootstrap/harness.ts 2711 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts); +24 #5893: rotation grant carry wiring and its rotationCarry/withheldOperationsNote helpers (carry rules live in token-mint.ts carryLegacyGrant); +6 #5878: --refresh-skills flag and status epoch line (refresh logic lives in harness-skills.ts); +7 #4618 seat: HarnessFlags.seat field, --seat/--no-seat parse via hooks.ts parseSeatFlags, GBRAIN_SEAT in the hook env
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
src/core/ops/pages.ts 644 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index e8f58944d5..dcff4b6c7c 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -305,7 +305,7 @@ export interface SyncOpts {
* `sync_status` IPC polls read. Absent for direct CLI runs (stderr
* breadcrumbs already cover that surface).
*/
- onProgress?: (p: { phase: string; bankedFiles?: number; total?: number; waived?: boolean }) => void;
+ onProgress?: (p: { phase: string; bankedFiles?: number; total?: number; waived?: boolean; group?: number }) => void;
/**
* #5984: managed sync only. Re-enter the single-pass managed sync until the
* cursor is done, the caller's signal/deadline stops it, or it is blocked
@@ -315,6 +315,7 @@ export interface SyncOpts {
drain?: boolean;
/** #5984: wall-clock ms the current drain started; managed cursors measure their rate from it. */
drainStartedAt?: number;
+ /** #5984: `--no-bulk`; and the drain's resolved bulk settings (internal; absent = one request per pass step). */ noBulk?: boolean; bulk?: import('../core/persistence/sync-group.ts').BulkSettings;
}
// The git-plumbing cluster (git(), discoverGitRoot, createSyncBaselineCommit,
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index 3ca533c808..6cf0078d55 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -71,6 +71,12 @@ Options:
--no-pull Skip 'git pull' before the sync. Required on managed
brains: 'gbrain sources refresh <id>' moves the
checkout, and sync catches the index up to it.
+ --no-bulk Managed Postgres sync: publish one page per transaction
+ instead of bulk groups (each page keeps its own write
+ request either way). Persist with
+ 'gbrain config set sync.bulk false' or
+ GBRAIN_SYNC_BULK=0; tune with sync.bulk_size and
+ sync.bulk_max_txn_ms.
--no-delegate On a PGLite brain with a live 'gbrain serve', sync
normally delegates the run to the serve process over
its IPC socket (the lock owner does the work; embeds
@@ -135,6 +141,7 @@ export function parseSyncFlags(args: string[]) {
const dryRun = args.includes('--dry-run');
const full = args.includes('--full');
const noPull = args.includes('--no-pull');
+ const noBulk = args.includes('--no-bulk');
let noEmbed = resolveNoEmbed(args, loadConfig());
const noExtract = args.includes('--no-extract'); // v0.42.7 #1696
const skipFailed = args.includes('--skip-failed');
@@ -193,7 +200,7 @@ export function parseSyncFlags(args: string[]) {
console.error(`--max-age cannot be combined with --force-break-lock (force skips all guards).`);
process.exit(1);
}
- return { repoPath, watch, interval, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, explicitProcessing, includeGitignored, workingTree, syncAll, missingPathMode, jsonOut, yesFlag, breakLock, forceBreakLock, maxAgeSeconds };
+ return { repoPath, watch, interval, dryRun, full, noPull, noBulk, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, explicitProcessing, includeGitignored, workingTree, syncAll, missingPathMode, jsonOut, yesFlag, breakLock, forceBreakLock, maxAgeSeconds };
}
export type SyncFlags = ReturnType<typeof parseSyncFlags>;
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 5c90ef0130..798ad3afde 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -275,7 +275,7 @@ async function runSyncAll(
input: { noEmbed: boolean; embeddingCredentialError: Error | undefined; resumeCommand: string },
): Promise<void> {
const {
- dryRun, full, noPull, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored,
+ dryRun, full, noPull, noBulk, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored,
workingTree, missingPathMode, jsonOut, yesFlag, serialFlag, noAutoEmbed, maxSources, concurrency, timeoutSeconds,
} = flags;
const { noEmbed, embeddingCredentialError, resumeCommand } = input;
@@ -446,7 +446,7 @@ async function runSyncAll(
strategy: cfg.strategy,
concurrency,
signal: composeAbortSignals(allInterrupt.signal, controller?.signal),
- drain: true,
+ drain: true, noBulk,
};
// v0.40.6.0 (D6): wrap performSync in withSourcePrefix so every slog /
// serr line emitted from inside the sync code path gets prefixed with
@@ -693,7 +693,7 @@ async function runSingleSourceSync(
input: { sourceId: string; companyPolicy: Awaited<ReturnType<typeof getCompanyBrainProfile>> | null; noEmbed: boolean; resumeCommand: string },
): Promise<void> {
const {
- repoPath, watch, interval, dryRun, full, noPull, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,
+ repoPath, watch, interval, dryRun, full, noPull, noBulk, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,
explicitProcessing, includeGitignored, workingTree, jsonOut, yesFlag, noAutoEmbed, strategyArg, srcSubpath,
excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds,
} = flags;
@@ -720,7 +720,7 @@ async function runSingleSourceSync(
exclude: excludePatterns.length > 0 ? excludePatterns : undefined,
includeHidden: includeHiddenPatterns.length > 0 ? includeHiddenPatterns : undefined,
signal: composeAbortSignals(singleSourceInterrupt.signal, singleSourceController?.signal),
- drain: true,
+ drain: true, noBulk,
};
// v0.42.42.0 (#2139, Step 4b): single-source `gbrain sync` gets the SAME
diff --git a/src/core/config.ts b/src/core/config.ts
index 12ef0346a2..312a7ac414 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1591,6 +1591,10 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'sync.cost_gate_min_usd',
'sync.federated_v2',
'sync.include_working_tree',
+ // #5984: managed Postgres sync publishes pages in bulk groups (on by default; each page keeps its own request).
+ 'sync.bulk',
+ 'sync.bulk_size',
+ 'sync.bulk_max_txn_ms',
// Persisted indexing scope (comma/newline-separated glob list; trailing '/'
// normalizes to a '/**' subtree glob). Read best-effort at the top of
// performSyncInner and UNIONED with any per-call --exclude so internal
diff --git a/src/core/page-state/guards.ts b/src/core/page-state/guards.ts
index 6ecab2b528..1ff388223d 100644
--- a/src/core/page-state/guards.ts
+++ b/src/core/page-state/guards.ts
@@ -18,6 +18,16 @@ export async function lockPageKeys(engine: Pick<BrainEngine, 'executeRaw'>, keys
if (!rows.length) throw new Error(`Page source does not exist: ${sourceId}`);
sources.set(sourceId, rows[0].incarnation);
}
+ if (ordered.length > 1) {
+ // #5984: many keys in three statements, still created and locked in the sorted key order.
+ const incarnations = ordered.map(key => sources.get(key.sourceId)!), slugs = ordered.map(key => key.slug), sourceIds = ordered.map(key => key.sourceId);
+ await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) SELECT i,s FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n) ORDER BY n ON CONFLICT DO NOTHING', [incarnations, slugs]);
+ await engine.executeRaw(`SELECT g.slug FROM unnest($1::uuid[],$2::text[]) WITH ORDINALITY AS k(i,s,n)
+ JOIN page_write_guards g ON g.source_incarnation=k.i AND g.slug=k.s ORDER BY k.n FOR UPDATE OF g`, [incarnations, slugs]);
+ await engine.executeRaw(`SELECT p.id FROM unnest($1::text[],$2::text[]) WITH ORDINALITY AS k(src,s,n)
+ JOIN pages p ON p.source_id=k.src AND p.slug=k.s ORDER BY k.n FOR UPDATE OF p`, [sourceIds, slugs]);
+ return;
+ }
for (const key of ordered) {
const params = [sources.get(key.sourceId)!, key.slug];
await engine.executeRaw('INSERT INTO page_write_guards(source_incarnation,slug) VALUES ($1::uuid,$2) ON CONFLICT DO NOTHING', params);
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 4d434d8763..a9e3e56a23 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,8 +1,9 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { CLAIMABLE_WRITE_SQL, claimNextWrite, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
+import { CLAIMABLE_WRITE_SQL, claimGroupFollowers, claimNextWrite, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
+import { executeClaimedGroup } from './group-publish.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
@@ -342,7 +343,7 @@ export class PersistenceConsumer {
if (this.activeRoots.has(key)) { await releaseUnpublishedClaim(this.engine, row, 'writer_busy'); break; }
this.activeRoots.add(key);
let progressed = false;
- const task = this.execute(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
+ const task = this.executeOrGroup(row).then(result => { progressed = result; }).catch(error => this.report(error)).finally(() => {
if (!progressed) this.rootRetryAfter.set(key, Date.now() + (this.opts.pollMs ?? 250));
else { this.progressWake = true; this.publishedSinceMaintenance++; }
this.active.delete(task); this.activeRoots.delete(key); this.schedule(progressed ? 0 : this.opts.pollMs ?? 250);
@@ -505,6 +506,19 @@ export class PersistenceConsumer {
this.abort.signal.removeEventListener('abort', stop); this.preparing.delete(row.id); this.executing.delete(row.id); await renewing;
}
}
+ /** #5984: a claimed bulk sync head takes its directly following group members along; one row runs the single path. */
+ private async executeOrGroup(row: WriteRequest): Promise<boolean> {
+ const group = typeof row.intent?.group === 'string' ? row.intent.group : null;
+ if (!group || this.engine.kind !== 'postgres') return this.execute(row);
+ const followers = await claimGroupFollowers(this.engine, row, group, 63);
+ if (!followers.length) return this.execute(row);
+ const rows = [row, ...followers];
+ for (const member of rows) this.executing.add(member.id);
+ try {
+ return await executeClaimedGroup(this.engine, rows, { hostId: this.hostId, prepare: member => this.prepare(this.engine, member, this.config),
+ settled: done => { this.executing.delete(done.id); this.settled(done); } });
+ } finally { for (const member of rows) this.executing.delete(member.id); }
+ }
/** Mandatory barrier: engine.close must be sequenced AFTER this promise. */
async stop(): Promise<void> {
this.stopping = true;
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index 1824a3b682..89a01db75f 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -97,6 +97,19 @@ export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRe
return engine.transaction(tx => completeWrite(tx, row, conflictCode(failure.code) ? 'conflict' : 'failed', {}, failure));
}
+/** The receipt fields every committed publication carries: revision, persistence mode and write-through. */
+export function decoratePublicationOutcome(row: WriteRequest, prepared: PreparedMutation, outcome: Record<string, unknown>,
+ final: { revision: string } | null, fileCount: number, skill: boolean): void {
+ if (final) outcome.revision = final.revision;
+ outcome.persistence = { mode: fileCount ? 'filesystem' : 'database', ...(fileCount ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };
+ outcome.write_through = fileCount ? { written: !prepared.noop } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };
+ if (prepared.databaseOnlyReason === 'mirror_read_only') outcome.storage = 'database_only';
+ if ((row.operation === 'put_page' || row.operation === 'edit_page') && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);
+ if ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {
+ outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.operation, row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };
+ }
+}
+
/**
* prepare outside locks → durable recovery → file → DB+receipt commit.
* The root lock spans all file effects; the DB guards span authorization and
@@ -247,14 +260,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
if (!skill) await classifyUnboundPage(tx, row);
if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = skill ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
- if (final) outcome.revision = final.revision;
- outcome.persistence = { mode: files.length ? 'filesystem' : 'database', ...(files.length ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };
- outcome.write_through = files.length ? { written: !prepared.noop } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };
- if (prepared.databaseOnlyReason === 'mirror_read_only') outcome.storage = 'database_only';
- if ((row.operation === 'put_page' || row.operation === 'edit_page') && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id, row.operation);
- if ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {
- outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.operation, row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };
- }
+ decoratePublicationOutcome(row, prepared, outcome, final, files.length, skill);
await queuePublicationEffects(tx, row, final, outcome, prepared);
await hooks.boundary?.('before_commit', row);
const committed = await completeWrite(tx, current, 'committed', outcome, undefined, current);
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
new file mode 100644
index 0000000000..34b58ec1cd
--- /dev/null
+++ b/src/core/persistence/group-publish.ts
@@ -0,0 +1,154 @@
+/**
+ * #5984 bulk sync: publishes a claimed group of consecutive managed-sync page
+ * requests in one transaction (ENG-A3/A4).
+ *
+ * Every member keeps its own request row, authorization, page guard,
+ * visibility check, attribution, effects and receipt; only the per-transaction
+ * work is shared: the worktree lock, the recovery and capacity checks, the
+ * ownership guard and the counter and request locks. Counters are locked after
+ * the members are applied and before their request rows, so the brain-wide
+ * counter row is held only for the completion statements (ENG-A5).
+ *
+ * The group is all-or-nothing. Any failure rolls the transaction back and
+ * returns null; the caller then publishes the members one at a time, so a
+ * failure is attributed to its own page and no later member overtakes it.
+ * Only database-only managed-sync page members qualify; their sync
+ * validation includes the knowledge-publication guard. A member with a file,
+ * a skill bundle or a source-exclusive checkpoint takes the single path.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OperationError } from '../ops/contract.ts';
+import { authorizeStoredRequest } from './authority.ts';
+import { localHostId } from './identity.ts';
+import { acquireWorktree, getWorktreeBinding, guardOwnership } from './ownership.ts';
+import { completeWrite, getWriteRequestById, lockCounters, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
+import { principalKey, requestPrincipal, type WriteRequest } from './model.ts';
+import { withCoordinatedWrite } from './context.ts';
+import { requestAttribution } from './attribution.ts';
+import { tryAcquirePublicationCapacity } from './pool-capacity.ts';
+import { queuePublicationEffects } from './effect-journal.ts';
+import { authorizePageVisibility } from './page-visibility.ts';
+import { assertUnboundPublication, classifyUnboundPage } from './unbound-source.ts';
+import { declarePersistenceProtocol } from './protocol.ts';
+import { classifyMirrorPage } from './mirror-read-only.ts';
+import { decoratePublicationOutcome, finishUnpublishedFailure, publishMutation, type PreparedMutation } from './coordinator.ts';
+
+/** Whether a prepared member can share a group transaction. */
+export function groupable(row: WriteRequest, prepared: PreparedMutation): boolean {
+ return row.operation === 'submit_job' && (row.intent?.kind === 'managed_sync_import' || row.intent?.kind === 'managed_sync_delete')
+ && (row.target_kind ?? 'page') === 'page' && prepared.target !== 'skill_bundle' && !prepared.file && !prepared.sourceExclusive && typeof prepared.validate === 'function';
+}
+
+/** Publishes the whole group or nothing; null means the transaction did not commit and the claims are untouched. */
+export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prepared: PreparedMutation[], hostId = localHostId()): Promise<WriteRequest[] | null> {
+ const head = rows[0];
+ if (!head?.worktree_id || rows.some((row, i) => row.worktree_id !== head.worktree_id || !groupable(row, prepared[i]!))) return null;
+ const binding = await getWorktreeBinding(engine, head.source_id, hostId);
+ if (!binding || binding.owner_host_id !== hostId || !binding.local_path) return null;
+ const lock = await acquireWorktree(binding, 0, undefined, engine);
+ if (!lock) return null;
+ let releaseCapacity: (() => void) | null = null;
+ try {
+ const blocked = await engine.executeRaw(`SELECT 1 FROM persistence_requests WHERE worktree_id=$1::uuid AND NOT (id=ANY($2::uuid[])) AND recovery IS NOT NULL
+ UNION ALL SELECT 1 FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1`, [head.worktree_id, rows.map(row => row.id)]);
+ if (blocked.length) return null;
+ releaseCapacity = tryAcquirePublicationCapacity(engine);
+ if (!releaseCapacity) return null;
+ return await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
+ const live = await guardOwnership(tx, head, hostId);
+ if (String(live?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.');
+ for (const row of rows) await authorizeStoredRequest(tx, row, true);
+ await tx.lockPageKeys(rows.flatMap((row, i) => [{ sourceId: row.source_id, slug: row.slug }, ...(prepared[i]!.additionalPageKeys ?? [])]));
+ const outcomes: Record<string, unknown>[] = [];
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i]!, member = prepared[i]!;
+ const snapshot = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ await authorizePageVisibility(tx, row.authority, row.slug);
+ if ((snapshot?.page.id ?? null) !== row.page_id) throw new OperationError('page_identity_changed', 'The accepted page was deleted or recreated.');
+ await assertUnboundPublication(tx, row, snapshot?.page.source_path);
+ if ((snapshot?.revision ?? null) !== member.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.');
+ await member.validate?.(tx);
+ const outcome = await withCoordinatedWrite(tx, [row.source_id], () => member.apply(tx), requestAttribution(row));
+ await classifyUnboundPage(tx, row);
+ if (member.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
+ const final = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
+ decoratePublicationOutcome(row, member, outcome, final, 0, false);
+ await queuePublicationEffects(tx, row, final, outcome, member);
+ outcomes.push(outcome);
+ }
+ await lockCounters(tx, ['brain', ...new Set(rows.map(row => principalKey(requestPrincipal(row)))), `worktree:${head.worktree_id}`]);
+ const current = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence FOR UPDATE', [rows.map(row => row.id)]);
+ const byId = new Map(current.map(row => [row.id, row]));
+ const done: WriteRequest[] = [];
+ for (let i = 0; i < rows.length; i++) {
+ const locked = byId.get(rows[i]!.id);
+ if (!locked || locked.execution_token !== rows[i]!.execution_token || locked.state !== 'running') throw new OperationError('write_claim_lost', 'Execution claim changed before publication.');
+ done.push(await completeWrite(tx, locked, 'committed', outcomes[i]!, undefined, locked));
+ }
+ return done;
+ });
+ } catch {
+ return null;
+ } finally {
+ releaseCapacity?.();
+ await lock.release();
+ }
+}
+
+export interface GroupExecution {
+ prepare(row: WriteRequest): Promise<PreparedMutation>;
+ settled(row: WriteRequest): void;
+ hostId: string;
+}
+
+/**
+ * Prepares a claimed group (four members at a time), publishes it in one
+ * transaction when every member qualifies, and otherwise publishes the
+ * members one at a time in order. After a member ends in failure the later
+ * members are cancelled, and after one is released back to the queue the
+ * later ones are released too, so nothing overtakes it. Claims are renewed
+ * for the whole group while it runs. Returns whether any member settled.
+ */
+export async function executeClaimedGroup(engine: BrainEngine, rows: WriteRequest[], run: GroupExecution): Promise<boolean> {
+ let renewing: Promise<unknown> | undefined;
+ const interval = setInterval(() => { renewing ??= renewGroupClaims(engine, rows).catch(() => undefined).finally(() => { renewing = undefined; }); }, 10_000);
+ interval.unref?.();
+ try {
+ const prepared: Array<{ ok: PreparedMutation } | { error: unknown }> = new Array(rows.length);
+ for (let start = 0; start < rows.length; start += 4) {
+ await Promise.all(rows.slice(start, start + 4).map(async (row, offset) => {
+ try { prepared[start + offset] = { ok: await run.prepare(row) }; } catch (error) { prepared[start + offset] = { error }; }
+ }));
+ }
+ if (prepared.every(p => 'ok' in p)) {
+ const done = await publishGroup(engine, rows, prepared.map(p => (p as { ok: PreparedMutation }).ok), run.hostId);
+ if (done) { for (const row of done) run.settled(row); return true; }
+ }
+ let progressed = false, stop: 'cancel' | 'release' | null = null;
+ for (let i = 0; i < rows.length; i++) {
+ const row = rows[i]!;
+ const current = await getWriteRequestById(engine, row.id);
+ if (!current || current.execution_token !== row.execution_token || current.state !== 'running') {
+ if (current && ['committed', 'conflict', 'failed', 'cancelled'].includes(current.state)) { run.settled(current); progressed = true; if (current.state !== 'committed') stop ??= 'cancel'; }
+ continue;
+ }
+ if (stop === 'release') { await releaseUnpublishedClaim(engine, row, 'group_member_waiting'); continue; }
+ if (stop === 'cancel') {
+ const cancelled = await engine.transaction(tx => completeWrite(tx, current, 'cancelled', {}, { code: 'cancelled',
+ message: 'An earlier page of the same bulk sync group failed; this page was not published and is re-frozen after that failure is resolved.' }));
+ run.settled(cancelled); progressed = true; continue;
+ }
+ const p = prepared[i]!;
+ const done = 'ok' in p ? await publishMutation(engine, row, p.ok, run.hostId) : await finishUnpublishedFailure(engine, current, p.error, 'preparation');
+ run.settled(done);
+ if (done.state === 'committed') { progressed = true; continue; }
+ if (['conflict', 'failed', 'cancelled'].includes(done.state)) { progressed = true; stop = 'cancel'; } else stop = 'release';
+ }
+ return progressed;
+ } finally {
+ clearInterval(interval);
+ await renewing;
+ }
+}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 0d79065a54..af57427d8b 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -189,6 +189,119 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
} };
}
+/**
+ * #5984 bulk sync: admits consecutive managed-sync page requests of one cursor
+ * in one transaction. Each page keeps its own request row, request ID, digest
+ * and receipt; the shared checks (worktree fence, binding, source, counters)
+ * run once and the rows are inserted in order, so their sequences keep the
+ * manifest order. Replays return the prior rows, as single admission does.
+ */
+export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: WriteAdmission[], overrides?: Partial<JournalLimits>): Promise<WriteRequest[]> {
+ const first = inputs[0];
+ if (!first) return [];
+ if (inputs.some(input => input.sourceId !== first.sourceId || input.sourceIncarnation !== first.sourceIncarnation || input.worktreeId !== first.worktreeId
+ || String(input.topologyGeneration) !== String(first.topologyGeneration) || input.principal.kind !== first.principal.kind || input.principal.id !== first.principal.id
+ || input.operation !== first.operation || (input.targetKind ?? 'page') !== 'page' || (input.protocolVersion ?? 1) !== 1 || digest(input.authority) !== digest(first.authority))) {
+ throw new TypeError('A group admission requires one source, worktree, principal, operation and authority.');
+ }
+ const limits = await readJournalLimits(tx, overrides);
+ const stamp = writerStamp();
+ const items = inputs.map(input => ({ input, requestId: requireUuid(input.requestId ?? randomUUID()), fingerprint: intentDigest(input),
+ bytes: jsonBytes(input.intent) + jsonBytes(input.authority), terminalBytes: input.terminalReservation ?? Math.max(16_384, jsonBytes(input.authority) + 8192) }));
+ await declarePersistenceProtocol(tx);
+ assertMutationProtocol({ target_kind: 'page', protocol_version: 1 });
+ if (first.worktreeId) {
+ await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [first.worktreeId]);
+ await assertWorktreeNotRefreshing(tx, first);
+ const binding = await tx.executeRaw(`SELECT source_id FROM persistence_source_bindings WHERE source_id=$1
+ AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4`,
+ [first.sourceId, first.sourceIncarnation, first.worktreeId, first.topologyGeneration]);
+ if (!binding.length) throw new OperationError('source_changed', 'The source binding changed during admission.');
+ }
+ const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [first.sourceId]);
+ if (!source || source.archived || source.incarnation !== first.sourceIncarnation) {
+ throw new OperationError('source_changed', 'The write source is missing, archived, or was replaced.', 'Resolve the source again and submit a new request.');
+ }
+ for (const { input } of items) await authorizeWrite(tx, input.authority, input.operation, input.slug, true);
+ const counters = await lockCounters(tx, ['brain', principalKey(first.principal)]);
+ const ids = items.map(item => item.requestId);
+ if (first.principal.kind === 'local_cli' && (await tx.executeRaw('SELECT id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=ANY($2::uuid[]) LIMIT 1', [first.principal.id, ids])).length) {
+ throw new OperationError('idempotency_conflict', 'A request_id belongs to a source lifecycle operation.');
+ }
+ const priors = new Map((await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
+ [first.principal.kind, first.principal.id, ids])).map(row => [row.request_id, row]));
+ for (const item of items) {
+ const prior = priors.get(item.requestId);
+ if (!prior) continue;
+ if ((prior.target_kind ?? 'page') !== 'page' || (prior.protocol_version ?? 1) !== 1) throw new OperationError('idempotency_conflict', 'This request_id belongs to a different mutation target or protocol.');
+ assertReplayIntent(prior, item.fingerprint);
+ }
+ const fresh = items.filter(item => !priors.has(item.requestId));
+ if (fresh.length) {
+ const bytes = fresh.reduce((sum, item) => sum + item.bytes, 0), terminalBytes = fresh.reduce((sum, item) => sum + item.terminalBytes, 0);
+ for (const row of counters) {
+ const brain = row.key === 'brain', scope = brain ? 'brain' : 'principal';
+ if (Number(row.outstanding_count) + fresh.length > (brain ? limits.brainOutstanding : limits.principalOutstanding)) throw capacityError(`${scope} outstanding requests`);
+ if (Number(row.intent_bytes) + bytes > (brain ? limits.brainIntentBytes : limits.principalIntentBytes)) throw capacityError(`${scope} intent bytes`);
+ if (Number(row.lifetime_ids) + fresh.length > limits[`${scope}LifetimeIds`]) throw await cumulativeCapacityError(tx, `${scope} permanent request IDs`,
+ row.key, `${scope}LifetimeIds`, Number(row.lifetime_ids), limits[`${scope}LifetimeIds`]);
+ if (Number(row.terminal_bytes) + terminalBytes > limits[`${scope}TerminalBytes`]) throw await cumulativeCapacityError(tx, `${scope} reserved receipt bytes`,
+ row.key, `${scope}TerminalBytes`, Number(row.terminal_bytes), limits[`${scope}TerminalBytes`]);
+ }
+ const rows = await tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests
+ (principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,
+ worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,
+ admitter_version,admitter_host_id)
+ SELECT $1,$2,(e->>'request_id')::uuid,$3,$4,$5::uuid,(e->>'page_id')::integer,e->>'slug',$6::uuid,$7,e->>'digest',e->'intent',$8::text::jsonb,
+ (e->>'intent_bytes')::bigint,(e->>'terminal_reservation')::bigint,'page',1,$9,$10::uuid
+ FROM jsonb_array_elements($11::text::jsonb) WITH ORDINALITY AS t(e,n) ORDER BY n
+ RETURNING *`, [first.principal.kind, first.principal.id, first.operation, first.sourceId, first.sourceIncarnation, first.worktreeId ?? null,
+ first.topologyGeneration ?? null, JSON.stringify(first.authority), stamp.version, stamp.hostId,
+ JSON.stringify(fresh.map(item => ({ request_id: item.requestId, page_id: item.input.pageId ?? null, slug: item.input.slug, digest: item.fingerprint,
+ intent: item.input.intent, intent_bytes: item.bytes, terminal_reservation: item.terminalBytes })))]);
+ for (const row of rows) priors.set(row.request_id, row);
+ await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+$4,
+ intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+$4,terminal_bytes=terminal_bytes+$3 WHERE key=ANY($1::text[])`,
+ [counters.map(c => c.key), bytes, terminalBytes, fresh.length]);
+ }
+ return items.map(item => priors.get(item.requestId)!);
+}
+
+/**
+ * #5984 bulk sync: after claiming a group's head, claims the queued members of
+ * the same group that directly follow it on its worktree, in sequence order,
+ * stopping at the first row that is not a queued member of the group. A member
+ * is never claimed past an unfinished non-member, so the FIFO order holds.
+ */
+export async function claimGroupFollowers(engine: BrainEngine, head: WriteRequest, group: string, max: number, leaseMs = 30_000): Promise<WriteRequest[]> {
+ if (!head.worktree_id || max <= 0) return [];
+ return engine.transactionDirect(async tx => {
+ await declarePersistenceProtocol(tx);
+ const next = await tx.executeRaw<{ id: string; state: string; grp: string | null; recovering: boolean }>(`SELECT id,state,intent->>'group' AS grp,recovery IS NOT NULL AS recovering
+ FROM persistence_requests WHERE worktree_id=$1::uuid AND sequence>$2 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL)
+ ORDER BY sequence LIMIT $3 FOR UPDATE`, [head.worktree_id, head.sequence, max]);
+ const members: string[] = [];
+ for (const row of next) {
+ if (row.grp !== group || row.state !== 'queued' || row.recovering) break;
+ members.push(row.id);
+ }
+ if (!members.length) return [];
+ const tokens = members.map(() => randomUUID());
+ return tx.executeRaw<WriteRequest>(`UPDATE persistence_requests r SET state='running',execution_token=t.token,
+ claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now(),blocked_reason=NULL
+ FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.state='queued' RETURNING r.*`, [members, tokens, leaseMs])
+ .then(rows => rows.sort((a, b) => Number(BigInt(a.sequence) - BigInt(b.sequence))));
+ });
+}
+
+/** Renews every claim of a group in one statement; returns the ids still held. */
+export async function renewGroupClaims(engine: SqlEngine, rows: WriteRequest[], leaseMs = 30_000, signal?: AbortSignal): Promise<Set<string>> {
+ const held = await engine.executeRaw<{ id: string }>(`UPDATE persistence_requests r SET claim_expires_at=now()+($3::double precision*interval '1 millisecond'),updated_at=now()
+ FROM unnest($1::uuid[],$2::uuid[]) AS t(id,token) WHERE r.id=t.id AND r.execution_token=t.token AND r.state='running' AND ${PERSISTENCE_PROTOCOL_PREDICATE} RETURNING r.id`,
+ [rows.map(row => row.id), rows.map(row => row.execution_token), leaseMs], { signal });
+ return new Set(held.map(row => row.id));
+}
+
/**
* F0: a write to a worktree under an active `gbrain sources refresh` is refused
* before it is journaled. The fence insert holds the worktree row FOR UPDATE
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index d8e14a66bd..0b05a16db3 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -47,6 +47,8 @@ export interface DrainReport {
eta_seconds: number | null;
retry_after_ms?: number;
stall?: DrainStall;
+ /** DX-A5: whether pages were published in bulk groups, and why not when they were not. */
+ bulk?: { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number };
}
const TERMINAL_STATUSES = new Set(['synced', 'first_sync', 'up_to_date', 'dry_run']);
@@ -140,6 +142,8 @@ export interface DrainInput {
probe?: StallProbe;
/** Throttled progress lines on stderr (CLI). */
announce?: boolean;
+ /** Publication mode for the report and the start line. */
+ bulk?: { enabled: boolean; reason: string | null };
/** Test seams: the no-progress window, the pause after a pending write and the transient backoff base. */
stallMs?: number;
pauseMs?: number;
@@ -152,7 +156,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
const coop = cooperativeDeadline();
const signal = coop.signal && input.signal ? AbortSignal.any([input.signal, coop.signal]) : coop.signal ?? input.signal;
let passes = 0, attempt = 0, readFailures = 0, refreshWaitedMs = 0, written = 0, waived = 0, index = 0, total: number | null = null;
- let announcedStart = false, lastLine = 0;
+ let announcedStart = false, lastLine = 0, groups = 0, groupedPages = 0, largestGroup = 0;
let stall: { key: string; since: number; passes: number } | null = null;
const remaining = () => total === null ? null : Math.max(0, total - index);
const onProgress: NonNullable<SyncOpts['onProgress']> = event => {
@@ -161,8 +165,10 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (typeof event.bankedFiles === 'number') index = event.bankedFiles;
if (event.phase === 'managed_sync.start' && input.announce && !announcedStart) {
announcedStart = true;
- serr(`[sync] managed catch-up: ${total ?? '?'} entries frozen, ${remaining() ?? '?'} remaining; one write request per page.`);
+ serr(`[sync] managed catch-up: ${total ?? '?'} entries frozen, ${remaining() ?? '?'} remaining; `
+ + (input.bulk?.enabled ? 'publishing in bulk groups (each page keeps its own request).' : `one write request per page${input.bulk?.reason ? ` (bulk off: ${input.bulk.reason})` : ''}.`));
}
+ if (event.phase === 'managed_sync.group' && typeof event.group === 'number') { groups++; groupedPages += event.group; largestGroup = Math.max(largestGroup, event.group); }
if (event.phase !== 'managed_sync.page_committed') return;
if (event.waived) waived++; else written++;
noteForwardProgress();
@@ -178,7 +184,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
const left = outcome === 'synced' ? 0 : remaining();
if (stopReason === 'deadline' && continues(result)) result = { ...result, reason: 'timeout' };
return { ...result, drain: { outcome, ...(stopReason ? { stop_reason: stopReason } : {}), passes, processed: written + waived, written, waived,
- remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt), ...extra } };
+ remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt),
+ ...(input.bulk ? { bulk: { ...input.bulk, groups, grouped_pages: groupedPages, largest_group: largestGroup } } : {}), ...extra } };
};
try {
for (;;) {
@@ -198,6 +205,7 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
if (TERMINAL_STATUSES.has(result.status)) return finish(result, 'synced');
if (result.status === 'blocked_by_failures') return finish(result, 'blocked', 'blocked_by_failures');
if (result.managedWrite && result.managedWrite.write_error !== 'write_pending') return finish(result, 'blocked', 'blocked_by_failures');
+ if (result.status === 'partial' && (result.reason === 'timeout' || signal?.aborted)) return finish(result, 'resumable', 'deadline');
const outcome = syncOutcome({ ...result, drain: undefined });
return finish(result, outcome, outcome === 'resumable' ? 'deadline' : undefined);
}
@@ -271,9 +279,11 @@ export function engineStallProbe(engine: BrainEngine): StallProbe {
/** The managed-sync drain over one engine; the CLI's managed path. */
export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, announce: boolean): Promise<SyncResult> {
const { performManagedSync } = await import('./sync-run.ts');
+ const { resolveBulkSettings } = await import('./sync-group.ts');
const drainStartedAt = opts.drainStartedAt ?? Date.now();
- return runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,
- pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt }) });
+ const bulk = await resolveBulkSettings(engine, opts.noBulk);
+ return runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce, bulk: { enabled: bulk.enabled, reason: bulk.reason },
+ pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk } : {}) }) });
}
export interface DrainNext {
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.ts
new file mode 100644
index 0000000000..a2949db7d2
--- /dev/null
+++ b/src/core/persistence/sync-group.ts
@@ -0,0 +1,100 @@
+/**
+ * #5984 bulk sync, the sync side (ENG-A3/A4, DX-A5/A8).
+ *
+ * A draining managed sync freezes the frozen head entry plus the directly
+ * following eligible entries, records them in the cursor as one `group`
+ * (the head stays in `pending`), admits every member in one transaction and
+ * waits for the group. Each member keeps its own request, receipt and
+ * failure attribution; the consumer publishes the group in one transaction
+ * (group-publish.ts) or, member by member, in order. The cursor advances only
+ * over the committed prefix, so a failed or still-pending member is handled
+ * exactly like a single pending entry.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import { OperationError } from '../ops/contract.ts';
+import { admitWriteGroupInTransaction } from './journal.ts';
+import { retryWriteAdmission } from './admission-retry.ts';
+import { wouldWaiveEntry, type WaiverCursor, type WaiverEntry } from './sync-waivers.ts';
+import type { WriteRequest } from './model.ts';
+import type { SyncIntent } from './sync-prepare.ts';
+import type { SyncAuthority } from './sync-authority.ts';
+
+export interface BulkSettings { enabled: boolean; reason: string | null; size: number; maxTxnMs: number }
+export interface BulkReport { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number }
+
+/** Flag > env > config > default (on), as for the other sync knobs (DX-A8). */
+export async function resolveBulkSettings(engine: BrainEngine, noBulk: boolean | undefined): Promise<BulkSettings> {
+ const env = process.env.GBRAIN_SYNC_BULK;
+ const configured = await engine.getConfig('sync.bulk').catch(() => null);
+ const size = await whole(engine, 'GBRAIN_SYNC_BULK_SIZE', 'sync.bulk_size', 16, 1, 64);
+ const maxTxnMs = await whole(engine, 'GBRAIN_SYNC_BULK_MAX_TXN_MS', 'sync.bulk_max_txn_ms', 30_000, 100, 300_000);
+ const reason = noBulk ? 'disabled by --no-bulk' : env === '0' || env === 'false' ? 'disabled by GBRAIN_SYNC_BULK=0'
+ : env === undefined || env === '' ? (configured === 'false' || configured === '0' ? 'disabled by config sync.bulk=false' : null) : null;
+ if (reason) return { enabled: false, reason, size, maxTxnMs };
+ if (engine.kind !== 'postgres') return { enabled: false, reason: 'PGLite publishes without network round trips; bulk applies to Postgres', size, maxTxnMs };
+ return { enabled: true, reason: null, size, maxTxnMs };
+}
+async function whole(engine: BrainEngine, env: string, key: string, fallback: number, min: number, max: number): Promise<number> {
+ const raw = process.env[env] ? Number(process.env[env]) : await engine.getConfig(key).then(v => v == null ? undefined : Number(v)).catch(() => undefined);
+ if (raw === undefined) return fallback;
+ if (!Number.isFinite(raw) || raw < min || raw > max) throw new OperationError('invalid_params', `${key} (or ${env}) must be a whole number from ${min} to ${max}; got ${raw}.`,
+ `Run gbrain config set ${key} ${fallback} (or unset ${env}), then retry.`);
+ return Math.floor(raw);
+}
+
+/** Entries a group may carry: plain page imports and deletes; renames, company plans and the checkpoint stay single. */
+export function groupableIntent(intent: SyncIntent): boolean {
+ return (intent.kind === 'managed_sync_import' || intent.kind === 'managed_sync_delete') && !intent.renameFrom && !intent.companyApproval;
+}
+
+/**
+ * Adaptive group size: as many members as fit the time budget at the last
+ * observed per-member time from admission to commit, within the configured
+ * maximum. Foreground writes queued behind a group wait at most about this
+ * budget (sync.bulk_max_txn_ms).
+ */
+export function nextGroupSize(settings: BulkSettings, perMemberMs: number | null): number {
+ if (perMemberMs === null || perMemberMs <= 0) return Math.min(4, settings.size);
+ return Math.max(1, Math.min(settings.size, Math.floor(settings.maxTxnMs / perMemberMs)));
+}
+
+/**
+ * Followers for a group: frozen in manifest order after the head, four at a
+ * time, stopping at the first entry that is not groupable, was overtaken by
+ * another cursor, or would be waived (the waiver handles it as a head).
+ */
+export async function freezeFollowers<P extends WaiverEntry & { rebound?: true }>(engine: BrainEngine, cursor: WaiverCursor & { entries: unknown[] }, config: GBrainConfig,
+ count: number, freezeAt: (index: number) => Promise<P>): Promise<P[]> {
+ const followers: P[] = [];
+ for (let next = cursor.index + 1; followers.length < count && next < cursor.entries.length;) {
+ const batch = Array.from({ length: Math.min(4, count - followers.length, cursor.entries.length - next) }, (_, i) => next + i);
+ const frozen = await Promise.all(batch.map(async index => {
+ const entry = await freezeAt(index);
+ return entry.rebound || !groupableIntent(entry.intent) || await wouldWaiveEntry(engine, { ...cursor, index }, entry, config) ? null : entry;
+ }));
+ for (const entry of frozen) {
+ if (!entry) return followers;
+ followers.push(entry);
+ }
+ next += batch.length;
+ }
+ return followers;
+}
+
+/** Admits the group's members that have no request yet, in one transaction, while the cursor still holds this group. */
+export async function admitGroup(engine: BrainEngine, members: WaiverEntry[], cursor: { sourceId: string; incarnation: string; binding: { worktree_id: string; topology_generation: string | number }; authority: SyncAuthority },
+ cursorHolds: (tx: BrainEngine) => Promise<boolean>): Promise<WriteRequest[] | null> {
+ const head = members[0]!;
+ return retryWriteAdmission(head.requestId, remaining => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout',$1,true),set_config('statement_timeout',$2,true)",
+ [`${Math.min(1000, remaining)}ms`, `${remaining}ms`]);
+ const rows = await admitWriteGroupInTransaction(tx, members.map(member => ({ requestId: member.requestId, operation: 'submit_job',
+ sourceId: cursor.sourceId, sourceIncarnation: cursor.incarnation, slug: member.slug, pageId: member.pageId,
+ worktreeId: cursor.binding.worktree_id, topologyGeneration: cursor.binding.topology_generation,
+ principal: cursor.authority.writer.principal, authority: cursor.authority.writer, callerIntent: member.intent, intent: member.intent })));
+ if (!await cursorHolds(tx)) throw new GroupMoved();
+ return rows;
+ })).catch(error => { if (error instanceof GroupMoved) return null; throw error; });
+}
+class GroupMoved extends Error {}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 2e843525ea..61945c746f 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -53,6 +53,19 @@ export interface SyncIntent extends Record<string, unknown> {
syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;
from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';
}
+/**
+ * #5984: the source-wide part of sync validation (managed mode, configured
+ * root, cursor, owner epoch) runs once per transaction; a bulk group's
+ * members share it. Its rows stay locked FOR SHARE until the transaction ends.
+ */
+const sharedValidations = new WeakMap<object, Map<string, Promise<{ run_id: string; request_id: string | null; group: string[] | null } | null>>>();
+function sharedSyncValidation(tx: BrainEngine, key: string, run: () => Promise<{ run_id: string; request_id: string | null; group: string[] | null } | null>) {
+ let byKey = sharedValidations.get(tx);
+ if (!byKey) { byKey = new Map(); sharedValidations.set(tx, byKey); }
+ let shared = byKey.get(key);
+ if (!shared) { shared = run(); byKey.set(key, shared); }
+ return shared;
+}
export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as SyncIntent | null;
if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw new OperationError('invalid_params', 'Unsupported internal sync intent.');
@@ -105,15 +118,21 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
}
};
const validate = async (tx: BrainEngine) => {
- await assertManagedSyncActive(tx, true);
+ const cursor = await sharedSyncValidation(tx, `${row.source_id}\0${p.cursorKey}\0${p.ownerEpoch}\0${root}`, async () => {
+ await assertManagedSyncActive(tx, true);
+ const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);
+ assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
+ // #5984: a bulk group's members are held by the cursor's `group`, its head also by `pending`.
+ const [held] = await tx.executeRaw<{ run_id: string; request_id: string | null; group: string[] | null }>(
+ `SELECT completed_keys->0->>'runId' AS run_id,completed_keys->0->'pending'->>'requestId' AS request_id,
+ (SELECT jsonb_agg(m->>'requestId') FROM jsonb_array_elements(COALESCE(completed_keys->0->'group','[]'::jsonb)) m) AS group
+ FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR SHARE`, [p.cursorKey]);
+ const current = await getWorktreeBinding(tx, row.source_id);
+ if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'The accepted sync owner epoch changed.');
+ return held ?? null;
+ });
await validateSyncAuthority(tx, p.syncAuthority, row.slug);
- const [configuredSource] = await tx.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1 FOR SHARE', [row.source_id]);
- assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
- const [cursor] = await tx.executeRaw<{ run_id: string; request_id: string | null }>(
- "SELECT completed_keys->0->>'runId' AS run_id,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR SHARE", [p.cursorKey]);
- if (cursor && (cursor.run_id !== p.runId || cursor.request_id !== row.request_id)) throw new OperationError('revision_conflict', 'The accepted sync cursor changed before publication.');
- const current = await getWorktreeBinding(tx, row.source_id);
- if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'The accepted sync owner epoch changed.');
+ if (cursor && (cursor.run_id !== p.runId || (cursor.request_id !== row.request_id && !cursor.group?.includes(row.request_id)))) throw new OperationError('revision_conflict', 'The accepted sync cursor changed before publication.');
if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row,
p.path === null ? undefined : { root, path: join(root, p.path) });
if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw new OperationError('source_changed', 'The imported file changed after sync admission.');
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index b7613a6ccf..df45f68d3a 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -27,6 +27,8 @@ import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointTimeoutHint } from './checkpoi
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import type { WriteRequest } from './model.ts';
import { assertManagedSyncAllowed } from './worktree-refresh.ts';
+import type { GBrainConfig } from '../config.ts';
+import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';
export interface ManagedSyncWriteDiagnostic {
source_id: string;
@@ -52,7 +54,9 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority
/** DX-A7: entries advanced without an admission because their publication would change nothing. */
waived?: { imports: number; deletes: number } };
/** #5984: the active drain window (reset when a new drain starts), so a backlog ETA never counts downtime. */
- progress?: CursorProgress; }
+ progress?: CursorProgress;
+ /** #5984 bulk: the frozen head (also `pending`) and the members admitted with it, in manifest order. */
+ group?: Pending[]; }
export interface CursorProgress { startedAt: number; startIndex: number; lastAt: number; lastIndex: number }
/** #5984: the cursor's progress after advancing to `index`, in the drain window that started at `drainStartedAt`. */
function stampProgress(prior: CursorProgress | undefined, fromIndex: number, index: number, drainStartedAt: number): CursorProgress {
@@ -119,7 +123,7 @@ function waivedCursor(cursor: Cursor, waived: NoopWaiver): Cursor {
const prior = cursor.counts.waived ?? { imports: 0, deletes: 0 };
const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts,
waived: { imports: prior.imports + (waived.kind === 'import' ? 1 : 0), deletes: prior.deletes + (waived.kind === 'delete' ? 1 : 0) } } };
- delete next.pending;
+ delete next.pending; delete next.group;
if (waived.kernel.includes('contextual_mode')) next.counts.skippedContextualMode = (next.counts.skippedContextualMode ?? 0) + 1;
if (waived.kernel.includes('canonical_file_differs')) next.counts.skippedCanonicalBytes = (next.counts.skippedCanonicalBytes ?? 0) + 1;
return next;
@@ -294,6 +298,68 @@ async function sameContentAtOrigin(engine: BrainEngine, cursor: Cursor, entry: C
}
}
+/** Counts a committed page into the cursor, as the single path does. */
+function countCommitted(counts: Cursor['counts'], pending: Pending, outcome: WriteRequest['outcome']): void {
+ if (outcome?.noop !== true) {
+ if (pending.intent.kind === 'managed_sync_delete') counts.deleted++;
+ else if (pending.intent.renameFrom) counts.renamed = (counts.renamed ?? 0) + 1;
+ else if (pending.pageId === null) counts.added++; else counts.modified++;
+ }
+ counts.chunks += Number(outcome?.chunks ?? 0);
+}
+interface BulkPass { settings: BulkSettings; perMemberMs: number | null }
+/**
+ * #5984 bulk: admits the cursor's group, waits for it and advances over the
+ * committed prefix. A terminal failure leaves that member as the single
+ * pending entry, so the single path records and reports it.
+ */
+async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk: BulkPass, config: GBrainConfig, wait: { waitMs: number; signal?: AbortSignal },
+ drainStartedAt: number, onProgress: SyncOpts['onProgress']): Promise<{ cursor: Cursor } | { result: SyncResult }> {
+ const signal = wait.signal;
+ const members = cursor.group!;
+ const principal = cursor.authority.writer.principal;
+ let rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
+ [principal.kind, principal.id, members.map(member => member.requestId)]);
+ if (rows.length < members.length) {
+ const admitted = await admitGroup(engine, members, cursor, async tx => {
+ const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key]);
+ return held?.request_id === members[0]!.requestId;
+ });
+ if (!admitted) return { cursor: await currentCursor(engine, key, cursor) };
+ rows = admitted;
+ }
+ const admitted = performance.now();
+ onProgress?.({ phase: 'managed_sync.group', bankedFiles: cursor.index, total: cursor.entries.length, group: members.length });
+ await validateSyncAuthority(engine, cursor.authority, members[0]!.slug);
+ assertSyncDispatchActive();
+ const last = rows.find(row => row.request_id === members.at(-1)!.requestId)!;
+ const waited = await awaitWrite(engine, last, config, wait);
+ assertSyncDispatchActive();
+ const states = new Map((await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=ANY($1::uuid[])', [rows.map(row => row.id)])).map(row => [row.request_id, row]));
+ const next: Cursor = { ...cursor, counts: { ...cursor.counts } };
+ let committed = 0;
+ for (const member of members) {
+ const row = states.get(member.requestId);
+ if (row?.state !== 'committed') break;
+ countCommitted(next.counts, member, row.outcome);
+ committed++;
+ }
+ if (committed === members.length) bulk.perMemberMs = (performance.now() - admitted) / members.length;
+ next.index = cursor.index + committed;
+ if (committed) next.progress = stampProgress(cursor.progress, cursor.index, next.index, drainStartedAt);
+ const stuck = members[committed];
+ const stuckRow = stuck ? states.get(stuck.requestId) : undefined;
+ if (!stuck) { delete next.pending; delete next.group; }
+ else { next.pending = stuck; if (stuckRow && isTerminalWriteState(stuckRow.state)) delete next.group; else next.group = members.slice(committed); }
+ const saved = committed || next.group?.length !== members.length ? await saveCursor(engine, key, cursor, next) : cursor;
+ for (let index = cursor.index + 1; index <= saved.index && index <= next.index; index++) onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: index, total: cursor.entries.length });
+ if (stuck && stuckRow && !isTerminalWriteState(stuckRow.state) && saved.index === next.index) {
+ return { result: { ...result(saved, 'partial', signal?.aborted ? 'timeout' : 'writer_pending'), ...(cursor.authority.writer.remote ? {} : {
+ managedWrite: writeDiagnostic(saved, stuck, stuckRow), writeWait: writeWaitOf(last.request_id === stuckRow.request_id ? waited : { kind: 'pending', row: stuckRow }) }) } };
+ }
+ return { cursor: saved };
+}
+
/** One immutable page is admitted at a time; foreground writes can never sit behind a whole scan. */
export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, slice?: { maxPages: number; maxMs: number }): Promise<SyncResult> {
await assertManagedSyncActive(engine);
@@ -440,6 +506,7 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
let batchStart = performance.now(), batchPages = 0, foregroundWaitStart = 0, foregroundBaseline = 0;
let creditedPages = 0, creditStarted = 0;
const 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 };
opts.onProgress?.({ phase: 'managed_sync.start', bankedFiles: cursor.index, total: cursor.entries.length });
while (!cursor.done) {
assertActive();
@@ -485,6 +552,21 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
if (slice && (cursor.index - sliceFirstIndex >= slice.maxPages || performance.now() - sliceStarted >= slice.maxMs)) return result(cursor, 'partial', 'writer_yield');
continue;
}
+ if (bulk.settings.enabled && !prior && !cursor.group && !pending.rebound && groupableIntent(pending.intent)) {
+ const head: Cursor = cursor;
+ const followers = await freezeFollowers(engine, head, config, nextGroupSize(bulk.settings, bulk.perMemberMs) - 1,
+ index => freezeEntry(engine, { ...head, index }, key, assertActive, frozenRun));
+ // Members name their group (the head's request ID), so a consumer can claim them together.
+ const members = [pending, ...followers].map(member => ({ ...member, intent: { ...member.intent, group: pending.requestId } }));
+ if (followers.length) cursor = await saveCursor(engine, key, head, { ...head, pending: members[0], group: members }, false, assertActive);
+ }
+ if (cursor.group?.[0]?.requestId === pending.requestId && cursor.pending?.requestId === pending.requestId) {
+ const step = await groupStep(engine, cursor, key, bulk, config, opts.drainStartedAt ? { waitMs: 30_000, signal } : { waitMs: 5000 }, drainStartedAt, opts.onProgress);
+ if ('result' in step) return step.result;
+ cursor = step.cursor;
+ assertActive();
+ continue;
+ }
const admitting = cursor;
const row = prior ?? await retryWriteAdmission(pending.requestId, remaining => engine.transaction(async tx => {
assertActive();
@@ -536,13 +618,8 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
return withLinks(cursor, result(cursor, cursor.from === null ? 'first_sync' : 'synced'));
}
// The frozen manifest is shared; only the cursor header changes per page.
- const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete next.pending;
- if (done.outcome?.noop !== true) {
- if (pending.intent.kind === 'managed_sync_delete') next.counts.deleted++;
- else if (pending.intent.renameFrom) next.counts.renamed = (next.counts.renamed ?? 0) + 1;
- else if (pending.pageId === null) next.counts.added++; else next.counts.modified++;
- }
- next.counts.chunks += Number(done.outcome?.chunks ?? 0);
+ const next: Cursor = { ...cursor, index: cursor.index + 1, counts: { ...cursor.counts }, progress: stampProgress(cursor.progress, cursor.index, cursor.index + 1, drainStartedAt) }; delete next.pending; delete next.group;
+ countCommitted(next.counts, pending, done.outcome);
cursor = await saveCursor(engine, key, cursor, next);
opts.onProgress?.({ phase: 'managed_sync.page_committed', bankedFiles: cursor.index, total: cursor.entries.length });
// F4b: PGLite plans the rest of a large sync against fresh statistics (spec Addendum A item 2).
diff --git a/src/core/persistence/sync-waivers.ts b/src/core/persistence/sync-waivers.ts
index bb93f06c53..2519f95a53 100644
--- a/src/core/persistence/sync-waivers.ts
+++ b/src/core/persistence/sync-waivers.ts
@@ -74,6 +74,17 @@ export async function waiveNoopEntry<C extends WaiverCursor>(engine: BrainEngine
});
}
+/** #5984: whether `waiveNoopEntry` would waive this frozen entry now (read-only; the bulk group stops before such an entry). */
+export async function wouldWaiveEntry(engine: BrainEngine, cursor: WaiverCursor, pending: WaiverEntry, config: GBrainConfig): Promise<boolean> {
+ if (!noopWaiversEnabled() || pending.pageId === null) return false;
+ const intent = pending.intent;
+ if (intent.kind === 'managed_sync_delete') {
+ if (intent.unownedDeletion || intent.renameFrom || intent.rawHash !== null || typeof intent.path !== 'string' || typeof intent.sourcePath !== 'string') return false;
+ return softDeletedAt(await engine.readPageSnapshot(pending.slug, { sourceId: cursor.sourceId, includeDeleted: true }), pending);
+ }
+ return (await unchangedSyncImport(engine, cursor, pending, config)) !== null;
+}
+
function softDeletedAt(snapshot: Awaited<ReturnType<BrainEngine['readPageSnapshot']>>, pending: WaiverEntry): boolean {
return snapshot?.page.id === pending.pageId && snapshot.page.deleted_at != null && snapshot.revision === pending.intent.expected_revision;
}
diff --git a/src/core/persistence/sync-wire.ts b/src/core/persistence/sync-wire.ts
index 6d40d5880d..d84f0f8442 100644
--- a/src/core/persistence/sync-wire.ts
+++ b/src/core/persistence/sync-wire.ts
@@ -5,7 +5,7 @@ import { OperationError } from '../ops/contract.ts';
export const SYNC_BOOLEAN_FLAGS = {
'--full':'full','--dry-run':'dryRun','--no-pull':'noPull','--no-embed':'noEmbed','--no-extract':'noExtract',
'--no-schema-pack':'noSchemaPack','--retry-failed':'retryFailed','--skip-failed':'skipFailed',
- '--include-gitignored':'includeGitignored','--working-tree':'workingTree','--reset-checkpoint':'resetCheckpoint',
+ '--include-gitignored':'includeGitignored','--working-tree':'workingTree','--reset-checkpoint':'resetCheckpoint','--no-bulk':'noBulk',
} as const;
export const SYNC_VALUE_FLAGS = { '--source':'sourceId','--repo':'repoPath','--src-subpath':'srcSubpath','--strategy':'strategy',
'--exclude':'exclude','--include-hidden':'includeHidden' } as const;
diff --git a/test/managed-sync-bulk.test.ts b/test/managed-sync-bulk.test.ts
new file mode 100644
index 0000000000..1ba050a118
--- /dev/null
+++ b/test/managed-sync-bulk.test.ts
@@ -0,0 +1,105 @@
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { nextGroupSize, resolveBulkSettings } from '../src/core/persistence/sync-group.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-bulk-'));
+let engine: BrainEngine | undefined;
+let closePostgres: (() => Promise<void>) | undefined;
+const sources: string[] = [];
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+async function fixture(e: BrainEngine, files: Record<string, string>) {
+ const id = `bulk-${randomUUID().replace(/-/g, '').slice(0, 20)}`; sources.push(id);
+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');
+ for (const [path, body] of Object.entries(files)) { const full = join(root, path); mkdirSync(join(full, '..'), { recursive: true }); writeFileSync(full, body); }
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'notes');
+ await e.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await e.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ await claimWorktree(e, id, root);
+ await e.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+}
+const notes = (count: number, edit: (i: number) => string | null = () => null) => Object.fromEntries(Array.from({ length: count }, (_, i) =>
+ [`notes/n${i}.md`, edit(i) ?? `---\ntitle: Note ${i}\n---\nA durable observation number ${i}.\n`]));
+
+beforeAll(async () => {
+ if (!process.env.DATABASE_URL) return;
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engine = pg.engine; closePostgres = pg.close;
+}, 120_000);
+afterAll(async () => {
+ if (engine) await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine!); await engine!.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const id of sources) await engine!.executeRaw('DELETE FROM sources WHERE id=$1', [id]);
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+test('group sizing follows the transaction budget and bulk settings follow flag > env > config', async () => {
+ const settings = { enabled: true, reason: null, size: 16, maxTxnMs: 10_000 };
+ expect(nextGroupSize(settings, null)).toBe(4);
+ expect(nextGroupSize(settings, 2000)).toBe(5);
+ expect(nextGroupSize(settings, 100)).toBe(16);
+ expect(nextGroupSize(settings, 60_000)).toBe(1);
+ if (!engine) return;
+ expect(await resolveBulkSettings(engine, true)).toMatchObject({ enabled: false, reason: 'disabled by --no-bulk' });
+ await withEnv({ GBRAIN_SYNC_BULK: '0' }, async () => expect(await resolveBulkSettings(engine!, false)).toMatchObject({ enabled: false, reason: 'disabled by GBRAIN_SYNC_BULK=0' }));
+ await engine.setConfig('sync.bulk', 'false');
+ try { expect(await resolveBulkSettings(engine, false)).toMatchObject({ enabled: false, reason: 'disabled by config sync.bulk=false' }); }
+ finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.bulk'"); }
+ expect(await resolveBulkSettings(engine, false)).toMatchObject({ enabled: true, reason: null, size: 16 });
+});
+
+test('a bulk drain publishes groups in one transaction while every page keeps its own request and receipt', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, notes(14));
+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true });
+ expect(result).toMatchObject({ status: 'first_sync', added: 14 });
+ expect(result.drain).toMatchObject({ outcome: 'synced', written: 14, bulk: { enabled: true } });
+ expect(result.drain!.bulk!.groups).toBeGreaterThan(0);
+ const rows = await engine.executeRaw<{ slug: string; state: string; grp: string | null; published: string }>(
+ `SELECT slug,state,intent->>'group' AS grp,published_at::text AS published FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [f.id]);
+ expect(rows).toHaveLength(14);
+ expect(rows.every(row => row.state === 'committed')).toBe(true);
+ expect(new Set(rows.map(row => row.slug)).size).toBe(14);
+ const sharedTransaction = new Map<string, number>();
+ for (const row of rows) sharedTransaction.set(row.published, (sharedTransaction.get(row.published) ?? 0) + 1);
+ expect(Math.max(...sharedTransaction.values())).toBeGreaterThan(1);
+ for (let i = 0; i < 14; i++) expect((await engine.getPage(`notes/n${i}`, { sourceId: f.id }))?.title).toBe(`Note ${i}`);
+ const [cursor] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0 ? 'group'");
+ expect(cursor!.n).toBe(0);
+}), 300_000);
+
+test('a failing member is attributed to its own page, earlier members commit and later members are cancelled, not published', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, notes(10, i => i === 3 ? '---\ntitle: Conflict\nslug: notes/other\n---\nA conflicting identity must not be imported.\n' : null));
+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true });
+ expect(result).toMatchObject({ status: 'blocked_by_failures', failedFiles: 1 });
+ expect(result.drain).toMatchObject({ outcome: 'blocked', stop_reason: 'blocked_by_failures' });
+ expect(result.managedWrite?.slug).toBe('notes/n3');
+ for (let i = 0; i < 3; i++) expect(await engine.getPage(`notes/n${i}`, { sourceId: f.id })).not.toBeNull();
+ for (let i = 3; i < 10; i++) expect(await engine.getPage(`notes/n${i}`, { sourceId: f.id })).toBeNull();
+ const states = await engine.executeRaw<{ slug: string; state: string }>(
+ `SELECT slug,state FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence`, [f.id]);
+ expect(states.find(row => row.slug === 'notes/n3')?.state).toBe('failed');
+ expect(states.filter(row => row.state === 'committed').map(row => row.slug)).toEqual(['notes/n0', 'notes/n1', 'notes/n2']);
+ expect(states.filter(row => !['committed', 'failed'].includes(row.state)).every(row => row.state === 'cancelled')).toBe(true);
+}), 300_000);
+
+test('--no-bulk publishes one page per transaction', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ if (!engine) return;
+ const f = await fixture(engine, notes(5));
+ const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, noBulk: true });
+ expect(result.drain).toMatchObject({ outcome: 'synced', bulk: { enabled: false, reason: 'disabled by --no-bulk', groups: 0 } });
+ const grouped = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND intent ? 'group'", [f.id]);
+ expect(grouped[0]!.n).toBe(0);
+}), 300_000);
diff --git a/test/zz-rt-latency.test.ts b/test/zz-rt-latency.test.ts
new file mode 100644
index 0000000000..1a6637e22c
--- /dev/null
+++ b/test/zz-rt-latency.test.ts
@@ -0,0 +1,40 @@
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, writeFileSync, appendFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { PostgresEngine } from '../src/core/postgres-engine.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+test('managed catch-up over injected latency', async () => {
+ const N = Number(process.env.RT_PAGES ?? 30);
+ const home = mkdtempSync(join(tmpdir(), 'rtl-'));
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ const git = (...a: string[]) => execFileSync('git', ['-C', root, ...a], { stdio: 'pipe' });
+ const id = `rt-${randomUUID().slice(0, 8)}`; const root = join(home, id); mkdirSync(join(root, 'notes'), { recursive: true }); git('init', '-q');
+ for (let i = 0; i < N; i++) writeFileSync(join(root, 'notes', `n${i}.md`), `---\ntitle: Note ${i}\n---\nObservation ${i} about [[notes/n${(i + 1) % N}]].\n`);
+ git('add', '.'); git('-c', 'user.name=E', '-c', '[email protected]', 'commit', '-qm', 'x');
+ await pg.engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await pg.engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(pg.engine, id, root);
+ await pg.engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await disposePersistenceConsumer(pg.engine);
+ const url = new URL(pg.databaseUrl); url.port = process.env.RT_PROXY_PORT ?? '6666';
+ const engine = new PostgresEngine(); await engine.connect({ database_url: url.toString(), poolSize: 4 });
+ const t0 = performance.now();
+ const r = await performSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true, drain: true });
+ const ms = performance.now() - t0;
+ const line = `${process.env.RT_LABEL ?? ''} pages=${N} status=${r.status} wall_ms=${Math.round(ms)} per_page_ms=${Math.round(ms / N)} pages_per_min=${(N / (ms / 60000)).toFixed(1)}`;
+ console.log(line); appendFileSync(process.env.RT_OUT!, line + '\n');
+ const reqs = await pg.engine.executeRaw<any>(`SELECT intent->>'kind' AS kind, slug, extract(epoch from created_at)*1000 AS c, extract(epoch from published_at)*1000 AS p, extract(epoch from completed_at)*1000 AS d, state FROM persistence_requests WHERE source_id=$1 ORDER BY sequence`, [id]);
+ let prev = 0; for (const q of reqs) { console.log(`${q.kind} ${q.slug} admit_gap=${prev ? Math.round(q.c - prev) : 0} admit_to_done=${Math.round(q.d - q.c)} ${q.state}`); prev = q.d; }
+ await disposePersistenceConsumer(engine); await engine.disconnect(); await pg.close();
+ expect(r.drain?.outcome).toBe('synced');
+ });
+}, 1_800_000);