Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync lanes: a maximum of 16 clamped by the pool, lane timing, and the drain says what limited it (#5984)

garrytan02af2a6c2a53
diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.ts
index 08dccc40a1..51203d5236 100644
--- a/src/commands/sync/args.ts
+++ b/src/commands/sync/args.ts
@@ -97,10 +97,11 @@ Options:
'gbrain config set sync.bulk false' or
GBRAIN_SYNC_BULK=0; tune with sync.bulk_size and
sync.bulk_max_txn_ms.
- --lanes N Managed Postgres sync: publish up to N bulk groups at
- once (1-8, default 6, capped by the connection pool).
- Pages still commit in file order. Persist with
- 'gbrain config set sync.lanes N' or GBRAIN_SYNC_LANES.
+ --lanes N Managed Postgres sync: publish at most N bulk groups at
+ once (1-16, default 16, capped by the connection pool:
+ GBRAIN_POOL_SIZE minus 4). Pages still commit in file
+ order. Persist with 'gbrain config set sync.lanes N' or
+ GBRAIN_SYNC_LANES; the drain reports what limited it.
--no-lanes Same as --lanes 1: one bulk group at a time.
--no-delegate On a PGLite brain with a live 'gbrain serve', sync
normally delegates the run to the serve process over
@@ -193,7 +194,7 @@ export function parseSyncFlags(args: string[]) {
const noPull = args.includes('--no-pull');
const noBulk = args.includes('--no-bulk');
const lanesAt = args.indexOf('--lanes');
- const lanes = args.includes('--no-lanes') ? 1 : lanesAt === -1 ? undefined : intFlagValue(args[lanesAt + 1], '--lanes', { min: 1, max: 8, example: 4 });
+ const lanes = args.includes('--no-lanes') ? 1 : lanesAt === -1 ? undefined : intFlagValue(args[lanesAt + 1], '--lanes', { min: 1, max: 16, example: 8 });
let noEmbed = resolveNoEmbed(args, loadConfig());
const noExtract = args.includes('--no-extract'); // v0.42.7 #1696
const skipFailed = args.includes('--skip-failed');
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index f543e71e09..812ed4cdbb 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -108,7 +108,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'repair': ['--all', '--apply', '--brain', '--client', '--diff', '--expect', '--help', '--id', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--only', '--remediate', '--remediation-plan', '--scopes', '--skip', '--source', '--stale', '--yes'],
'repair-jsonb': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url', '--wait'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
- 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
+ 'repos': ['--abandon', '--abbrev-ref', '--abort', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait-drain', '--yes'],
'resolvers': ['--backend', '--brain', '--cost', '--help', '--json', '--source'],
'retrieval-upgrade': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--priority', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--retarget', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--wait', '--yes'],
'routing-eval': ['--brain', '--help', '--json', '--llm', '--skills-dir', '--source'],
@@ -121,7 +121,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
'skillpack-check': ['--accept-pending', '--background', '--brain', '--explain', '--fast', '--follow', '--help', '--json', '--list', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--strict', '--timeout', '--wait', '--yes'],
'smoke-test': ['--brain', '--help', '--json', '--source'],
- 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait', '--wait-drain', '--yes'],
+ 'sources': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--accept-suggested', '--access', '--account', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--all-new', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--auto-additive', '--background', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-usd-per-day', '--cached', '--calendar-id', '--classify', '--cleanup-dead-local-locks', '--clear', '--client', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--db-url', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--explain', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--if-version', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--lanes', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--migrate-legacy', '--migration', '--name', '--name-only', '--no-accept-pending', '--no-cron', '--no-embed', '--no-extract', '--no-federate', '--no-federated', '--no-harden', '--no-lanes', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--operations', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--read-sources', '--rebase', '--redirect-uri', '--refresh-operations', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--reset-default', '--resume', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--sources', '--stale', '--status', '--surface', '--takes-holders', '--timeout', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--wait', '--wait-drain', '--yes'],
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index c11338f559..e75cd7399f 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -31,7 +31,7 @@ import { OperationError } from '../ops/contract.ts';
import { authorizeStoredRequest } from './authority.ts';
import { localHostId } from './identity.ts';
import { acquireWorktree, acquireWorktreeShared, getWorktreeBinding, guardOwnership } from './ownership.ts';
-import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneClaimed, laneFinished, stepDownLanes, type LaneState } from './sync-lanes.ts';
+import { awaitLaneBegin, awaitLaneTurn, LaneAbort, laneApplyBegin, laneClaimed, laneFinished, stepDownLanes, type LaneState } from './sync-lanes.ts';
import { cancelRows, windowPredecessor } from './sync-window.ts';
import { clearResolvedRecoveries, completeWrite, ENSURE_COUNTERS_SQL, getWriteRequestById, LOCK_COUNTERS_SQL, markRecovering, prepareRecoveries,
publicationGroupKey, reclaimReleasedWrite, releaseUnpublishedClaim, renewGroupClaims } from './journal.ts';
@@ -129,6 +129,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
let releaseCapacity: (() => void) | null = null;
const recorded = new Map<number, { row: WriteRequest; record: FileRecoveryRecord; bytes: number }>();
let committed = false;
+ const timed: { apply: ReturnType<typeof laneApplyBegin> | null } = { apply: 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)]);
@@ -151,6 +152,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
}
if (lane) await awaitLaneBegin(lane, rows);
const done = await engine.transaction(async transaction => {
+ timed.apply?.end(rows.length);
+ if (lane) timed.apply = laneApplyBegin(lane);
const tx = groupReads(transaction);
await declareDurablePersistence(tx);
const live = await guardOwnership(tx, head, hostId);
@@ -193,7 +196,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
}
}, requestAttribution(head));
// #5984 lanes: applied concurrently, committed in manifest order.
- if (lane) await awaitLaneTurn(tx, lane, rows);
+ if (lane) { timed.apply?.turn(); await awaitLaneTurn(tx, lane, rows); timed.apply?.turned(); }
const done = await completeGroup(tx, rows, outcomes);
// Every member is complete in this transaction: the batch's last page re-arms the batch's mention links once.
const last = rows[rows.length - 1]!;
@@ -226,6 +229,7 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], pr
await hooks.rolledBack?.(rows);
return { done: null, requeued };
} finally {
+ timed.apply?.end(rows.length);
releaseCapacity?.();
await lock.release();
}
diff --git a/src/core/persistence/sync-drain.ts b/src/core/persistence/sync-drain.ts
index cf2b6497d3..c3d73597b8 100644
--- a/src/core/persistence/sync-drain.ts
+++ b/src/core/persistence/sync-drain.ts
@@ -12,6 +12,7 @@
* `SyncResult.drain`; the CLI turns it into the exit code and `next`.
*/
import { randomUUID } from 'node:crypto';
+import type { LanesCap } from './sync-group.ts';
import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { OperationError } from '../ops/contract.ts';
@@ -53,9 +54,17 @@ export interface DrainReport {
/** #5984 admit-ahead: groups admitted while the previous group was still publishing. */
admitted_ahead: number;
/** #5984 lanes: groups published at once, as asked and as in effect at the end, and why fewer. */
- lanes: { configured: number; effective: number; reason: string | null; step_down: string | null; overlapped_groups: number; fallbacks: number } };
+ lanes: LanesReport };
}
+/** #5984 lanes: groups published at once (maximum asked, ceiling at start, in effect at the end), and what limited them. */
+export interface LanesReport { maximum: number; configured: number; effective: number; reason: string | null; step_down: string | null; overlapped_groups: number; fallbacks: number;
+ /** Mean lane transactions open while at least one was, apply time per page, share of lane time spent waiting to commit in order. */
+ busy?: number | null; apply_ms_per_page?: number | null; turn_wait_share?: number | null;
+ limited_by?: LanesLimit }
+/** What held the drain's throughput, and what raises it (none when nothing a setting changes would help). */
+export interface LanesLimit { kind: 'lanes_off' | 'database_contention' | 'feeder' | 'pool' | 'maximum'; message: string; raise: string | null }
+
const TERMINAL_STATUSES = new Set(['synced', 'first_sync', 'up_to_date', 'dry_run']);
const BLOCKED_HEAD_REASONS = new Set(['recovery_required', 'owner_unavailable', 'unexpected_file_bytes', 'unexpected_staging_bytes']);
const PENDING_PAUSE_MS = 250;
@@ -150,7 +159,7 @@ export interface DrainInput {
/** Throttled progress lines on stderr (CLI). */
announce?: boolean;
/** Publication mode for the report and the start line. */
- bulk?: { enabled: boolean; reason: string | null; lanes?: number; lanesReason?: string | null };
+ bulk?: { enabled: boolean; reason: string | null; lanes?: number; lanesMax?: number; lanesReason?: string | null; lanesCap?: LanesCap };
/** Test seams: the no-progress window, the pause after a pending write and the transient backoff base. */
stallMs?: number;
pauseMs?: number;
@@ -196,7 +205,8 @@ export async function runDrain(input: DrainInput): Promise<SyncResult> {
return { ...result, drain: { outcome, ...(stopReason ? { stop_reason: stopReason } : {}), passes, processed: written + waived, written, waived,
remaining: left, ...drainEstimate(left, written + waived, Date.now() - startedAt),
...(input.bulk ? { bulk: { enabled: input.bulk.enabled, reason: input.bulk.reason, groups, grouped_pages: groupedPages, largest_group: largestGroup, admitted_ahead: admittedAhead,
- lanes: { configured: input.bulk.lanes ?? 1, effective: lanes?.effective ?? input.bulk.lanes ?? 1, reason: input.bulk.lanesReason ?? null, step_down: lanes?.stepDown ?? null, overlapped_groups: lanes?.overlapped ?? 0, fallbacks: lanes?.fallbacks ?? 0 } } } : {}), ...extra } };
+ lanes: { maximum: input.bulk.lanesMax ?? input.bulk.lanes ?? 1, configured: input.bulk.lanes ?? 1, effective: lanes?.effective ?? input.bulk.lanes ?? 1, reason: input.bulk.lanesReason ?? null,
+ step_down: lanes?.stepDown ?? null, overlapped_groups: lanes?.overlapped ?? 0, fallbacks: lanes?.fallbacks ?? 0 } } } : {}), ...extra } };
};
try {
for (;;) {
@@ -296,17 +306,44 @@ export async function drainManagedSync(engine: BrainEngine, opts: SyncOpts, anno
// #5984 lanes: one lane run per drain; its groups carry the id and this process claims them out of FIFO order.
const laneRun = bulk.enabled && (bulk.lanes ?? 1) > 1 ? randomUUID() : undefined;
const { closeLaneRun } = await import('./sync-lanes.ts');
+ let result: SyncResult | undefined;
try {
- return await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,
- bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesReason: bulk.lanesReason ?? null },
+ result = await runDrain({ signal: opts.signal, onProgress: opts.onProgress, probe: engineStallProbe(engine), announce,
+ bulk: { enabled: bulk.enabled, reason: bulk.reason, lanes: bulk.lanes ?? 1, lanesMax: bulk.lanesMax, lanesReason: bulk.lanesReason ?? null, lanesCap: bulk.lanesCap },
pass: (signal, onProgress) => performManagedSync(engine, { ...opts, signal, onProgress, drainStartedAt, ...(bulk.enabled ? { bulk: { ...bulk, laneRun } } : {}) }) });
} finally {
if (laneRun) {
- await closeLaneRun(laneRun);
+ const stats = await closeLaneRun(laneRun);
const { cancelOrphanedLaneRows } = await import('./sync-window.ts');
await cancelOrphanedLaneRows(engine, laneRun).catch(() => undefined);
+ const lanes = result?.drain?.bulk?.lanes;
+ if (lanes && stats) Object.assign(lanes, { busy: stats.busy, apply_ms_per_page: stats.applyMsPerPage, turn_wait_share: stats.turnWaitShare });
}
}
+ const lanes = result.drain?.bulk?.enabled ? result.drain.bulk.lanes : undefined;
+ if (lanes && (result.drain!.written > 0 || lanes.configured === 1)) {
+ lanes.limited_by = lanesLimit(lanes, bulk.lanesCap);
+ if (announce) serr(`[sync] lanes: ${lanes.effective} of ${lanes.maximum}${lanes.busy != null ? `, ${lanes.busy} busy on average` : ''}; ${lanes.limited_by.message}${lanes.limited_by.raise ? ` ${lanes.limited_by.raise}` : ''}`);
+ }
+ return result;
+}
+
+/**
+ * #5984 (E5): what limited a drain's lanes, for the agent. A lock or statement timeout that lowered the lane
+ * count comes first, then lanes that were mostly idle (the sync side did not prepare groups fast enough), then
+ * the connection pool, then the configured maximum.
+ */
+export function lanesLimit(lanes: Pick<LanesReport, 'maximum' | 'configured' | 'effective' | 'step_down' | 'busy'>, cap: LanesCap | undefined): LanesLimit {
+ if (lanes.configured <= 1) return { kind: 'lanes_off', message: 'lanes are off, so one group publishes at a time.',
+ raise: 'Drop --no-lanes, or run gbrain config set sync.lanes 16, to publish groups in parallel.' };
+ if (lanes.step_down) return { kind: 'database_contention', message: `lanes stepped down to ${lanes.effective} after ${lanes.step_down}.`,
+ raise: 'The database was contended; rerun when it is less busy. No setting raises this.' };
+ if (lanes.busy != null && lanes.busy < 0.75 * lanes.effective) return { kind: 'feeder',
+ message: `lanes waited for the sync loop to prepare groups (${lanes.busy} of ${lanes.effective} busy on average).`, raise: null };
+ if (cap === 'pool') return { kind: 'pool', message: `the connection pool allowed ${lanes.configured} of ${lanes.maximum} lanes.`,
+ raise: `Set GBRAIN_POOL_SIZE=${lanes.maximum + 4} for ${lanes.maximum} lanes, if the database has the connections to spare.` };
+ return { kind: 'maximum', message: `the configured maximum of ${lanes.maximum} lanes was in use.`,
+ raise: lanes.maximum < 16 ? 'Run gbrain config set sync.lanes 16 (or pass --lanes 16) to allow more.' : null };
}
export interface DrainNext {
diff --git a/src/core/persistence/sync-group.ts b/src/core/persistence/sync-group.ts
index dd0564e9ed..d6ea24a30e 100644
--- a/src/core/persistence/sync-group.ts
+++ b/src/core/persistence/sync-group.ts
@@ -21,9 +21,11 @@ import type { WriteRequest } from './model.ts';
import type { SyncIntent } from './sync-prepare.ts';
import type { SyncAuthority } from './sync-authority.ts';
+/** What sets a drain's lane ceiling: lanes off, the configured maximum, or the connection pool. */
+export type LanesCap = 'disabled' | 'maximum' | 'pool';
export interface BulkSettings { enabled: boolean; reason: string | null; size: number; maxTxnMs: number;
/** #5984 lanes: groups published at once (1 = one at a time), and why it is lower than asked when it is. */
- lanes?: number; lanesReason?: string | null;
+ lanes?: number; lanesMax?: number; lanesReason?: string | null; lanesCap?: LanesCap;
/** The drain's lane run (set by the drain when lanes > 1); lane groups carry it as `intent.lane`. */
laneRun?: string }
export interface BulkReport { enabled: boolean; reason: string | null; groups: number; grouped_pages: number; largest_group: number }
@@ -44,21 +46,25 @@ async function resolveGrouping(engine: BrainEngine, noBulk: boolean | undefined)
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 };
}
+/** The most groups a drain publishes at once: what `--lanes`, `sync.lanes` and `GBRAIN_SYNC_LANES` accept, and their default. */
+export const MAX_SYNC_LANES = 16;
/**
- * #5984 lanes: `--lanes N` / `--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 6, then clamped to what the
- * connection pool can hold at once (its long-hold capacity minus 3 for the sync loop, one foreground write and
- * the consumer's control work). Lanes need bulk groups.
+ * #5984 lanes: `--lanes N` / `--no-lanes` > `GBRAIN_SYNC_LANES` > `sync.lanes` > 16 sets the maximum number of
+ * groups published at once; the drain runs that many unless the connection pool holds fewer long transactions
+ * (its long-hold capacity minus 3 for the sync loop, one foreground write and the consumer's control work).
+ * `lanesMax` is the maximum asked for, `lanes` the ceiling in effect, and `lanesReason` why it is lower.
+ * Lanes need bulk groups.
*/
-async function resolveLanes(engine: BrainEngine, bulk: BulkSettings, flag: number | undefined): Promise<{ lanes: number; lanesReason: string | null }> {
- if (!bulk.enabled) return { lanes: 1, lanesReason: `bulk groups are off (${bulk.reason})` };
- if (flag !== undefined && (!Number.isInteger(flag) || flag < 1 || flag > 8)) throw new OperationError('invalid_params', `--lanes must be a whole number from 1 to 8; got ${flag}.`,
- 'Pass --lanes 6 (the default), or --no-lanes to publish one group at a time.');
- const asked = flag ?? await whole(engine, 'GBRAIN_SYNC_LANES', 'sync.lanes', 6, 1, 8);
- if (asked === 1) return { lanes: 1, lanesReason: flag === 1 ? 'disabled by --no-lanes' : 'disabled by sync.lanes=1 (or GBRAIN_SYNC_LANES=1)' };
+async function resolveLanes(engine: BrainEngine, bulk: BulkSettings, flag: number | undefined): Promise<{ lanes: number; lanesMax: number; lanesReason: string | null; lanesCap: LanesCap }> {
+ if (!bulk.enabled) return { lanes: 1, lanesMax: 1, lanesReason: `bulk groups are off (${bulk.reason})`, lanesCap: 'disabled' };
+ if (flag !== undefined && (!Number.isInteger(flag) || flag < 1 || flag > MAX_SYNC_LANES)) throw new OperationError('invalid_params', `--lanes must be a whole number from 1 to ${MAX_SYNC_LANES}; got ${flag}.`,
+ `Pass --lanes ${MAX_SYNC_LANES} (the default maximum), or --no-lanes to publish one group at a time.`);
+ const asked = flag ?? await whole(engine, 'GBRAIN_SYNC_LANES', 'sync.lanes', MAX_SYNC_LANES, 1, MAX_SYNC_LANES);
+ if (asked === 1) return { lanes: 1, lanesMax: 1, lanesReason: flag === 1 ? 'disabled by --no-lanes' : 'disabled by sync.lanes=1 (or GBRAIN_SYNC_LANES=1)', lanesCap: 'disabled' };
const pool = (engine as BrainEngine & { sql?: BudgetPool }).sql;
const capacity = pool ? poolLongHoldCapacity(pool) - 3 : 1;
- if (capacity >= asked) return { lanes: asked, lanesReason: null };
- return { lanes: Math.max(1, capacity), lanesReason: `the connection pool holds ${capacity + 3} long transactions; raise GBRAIN_POOL_SIZE for more lanes` };
+ if (capacity >= asked) return { lanes: asked, lanesMax: asked, lanesReason: null, lanesCap: 'maximum' };
+ return { lanes: Math.max(1, capacity), lanesMax: asked, lanesReason: `the connection pool holds ${capacity + 3} long transactions; set GBRAIN_POOL_SIZE=${asked + 4} for ${asked} lanes`, lanesCap: 'pool' };
}
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);
diff --git a/src/core/persistence/sync-lanes.ts b/src/core/persistence/sync-lanes.ts
index e07d7bed95..a10c6b446a 100644
--- a/src/core/persistence/sync-lanes.ts
+++ b/src/core/persistence/sync-lanes.ts
@@ -26,25 +26,73 @@ export interface LanePolicy { run: string; asked: number; effective: number; ste
fallbacks: number }
export interface LaneState extends LanePolicy { coordinationPath: string | null; claimed: Set<string>; begun: Set<string>;
/** Lane tasks this process runs for the run, from the head's claim until the task settles; `closing` stops new claims. */
- tasks: number; closing: boolean }
+ tasks: number; closing: boolean; timing: LaneTiming }
+/** Lane group transactions of a run in this process: how many are open, and where their time went. */
+interface LaneTiming { open: number; since: number; openArea: number; activeMs: number;
+ applyMs: number; appliedMembers: number; turnWaitMs: number; transactionMs: number }
+/**
+ * #5984 lanes: what a drain's lanes did, for its report. `busy` is the mean number of lane transactions open
+ * while at least one was; `applyMsPerPage` the time from a group's transaction begin to its commit-turn wait,
+ * per member; `turnWaitShare` the share of lane transaction time spent waiting for the group before to commit.
+ */
+export interface LaneStats { busy: number | null; applyMsPerPage: number | null; turnWaitShare: number | null }
const policies = new Map<string, LaneState>();
let claiming = 0;
/** The drain's lane policy for a worktree; replaces any earlier one. */
export function openLanes(worktreeId: string, run: string, lanes: number, coordinationPath: string | null): void {
- policies.set(worktreeId, { run, asked: lanes, effective: lanes, stepDown: null, overlapped: 0, fallbacks: 0, coordinationPath, claimed: new Set(), begun: new Set(), tasks: 0, closing: false });
+ policies.set(worktreeId, { run, asked: lanes, effective: lanes, stepDown: null, overlapped: 0, fallbacks: 0, coordinationPath, claimed: new Set(), begun: new Set(), tasks: 0, closing: false,
+ timing: { open: 0, since: Date.now(), openArea: 0, activeMs: 0, applyMs: 0, appliedMembers: 0, turnWaitMs: 0, transactionMs: 0 } });
}
/**
* Ends a drain's lane run on every worktree it opened: no new lane claims, then waits (up to `maxMs`) for the
* consumer claims in flight and the lane tasks already running to settle, so a drain never reports while one of
* its groups is still publishing or aborting. Its unclaimed groups go back to the FIFO claim.
*/
-export async function closeLaneRun(run: string, maxMs = 90_000): Promise<void> {
+export async function closeLaneRun(run: string, maxMs = 90_000): Promise<LaneStats | null> {
const open = [...policies].filter(([, state]) => state.run === run);
for (const [, state] of open) state.closing = true;
const started = Date.now();
while ((claiming > 0 || open.some(([, state]) => state.tasks > 0)) && Date.now() - started < maxMs) await sleep(20);
for (const [worktreeId, state] of open) if (policies.get(worktreeId) === state) policies.delete(worktreeId);
+ return open.length ? laneStats(open.map(([, state]) => state.timing)) : null;
+}
+function laneStats(timings: LaneTiming[]): LaneStats {
+ const sum = (key: keyof LaneTiming) => timings.reduce((total, timing) => total + timing[key], 0);
+ const round = (value: number, places: number) => Math.round(value * 10 ** places) / 10 ** places;
+ const active = sum('activeMs'), members = sum('appliedMembers'), transactions = sum('transactionMs');
+ return { busy: active > 0 ? round(sum('openArea') / active, 2) : null, applyMsPerPage: members > 0 ? Math.round(sum('applyMs') / members) : null,
+ turnWaitShare: transactions > 0 ? round(sum('turnWaitMs') / transactions, 3) : null };
+}
+function account(timing: LaneTiming, delta: number): void {
+ const now = Date.now();
+ if (timing.open > 0) { timing.openArea += timing.open * (now - timing.since); timing.activeMs += now - timing.since; }
+ timing.open += delta;
+ timing.since = now;
+}
+/**
+ * Times one lane group transaction: call at its begin, `turn()` when it starts waiting for the group before it
+ * to commit, `turned()` when that wait ends, and `end(members)` once the transaction has finished either way.
+ * Only a transaction that reached its turn counts toward the apply time per page.
+ */
+export function laneApplyBegin(state: LaneState): { turn(): void; turned(): void; end(members: number): void } {
+ const timing = state.timing, began = Date.now();
+ let turnAt: number | null = null, waited = 0, ended = false;
+ account(timing, 1);
+ return {
+ turn() { turnAt ??= Date.now(); },
+ turned() { if (turnAt !== null && !waited) waited = Date.now() - turnAt; },
+ end(members) {
+ if (ended) return;
+ ended = true;
+ account(timing, -1);
+ timing.transactionMs += Date.now() - began;
+ if (turnAt === null) return;
+ timing.applyMs += turnAt - began;
+ timing.appliedMembers += members;
+ timing.turnWaitMs += waited || Date.now() - turnAt;
+ },
+ };
}
/**
* Counts a consumer claim that can take a lane row, from before its claim query until the claimed head's lane
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 0c7054f433..813d0b02c9 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -18,7 +18,8 @@ import { WINDOW_CANCEL_MESSAGE } from '../src/core/persistence/sync-window.ts';
import { acquireShared, leaseDraining, leaseWounded, yieldLease } from '../src/core/persistence/worktree-lease.ts';
import type { NativeLockHandle } from '../src/core/persistence/native-lock.ts';
import { withEnv } from './helpers/with-env.ts';
-import { awaitLaneTurn, closeLaneRun, laneClaim, laneOf, laneRoots, laneTask, openLanes } from '../src/core/persistence/sync-lanes.ts';
+import { awaitLaneTurn, closeLaneRun, laneApplyBegin, laneClaim, laneOf, laneRoots, laneTask, openLanes } from '../src/core/persistence/sync-lanes.ts';
+import { lanesLimit } from '../src/core/persistence/sync-drain.ts';
const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-lanes-'));
let engine: BrainEngine | undefined;
@@ -55,14 +56,44 @@ afterAll(async () => {
rmSync(home, { recursive: true, force: true });
});
-test('lane settings follow flag > env > config > 6, clamp to the pool and need bulk groups', async () => {
+test('lane settings are a maximum: flag > env > config > 16, clamped to the pool, and need bulk groups', async () => {
if (!engine) return;
- expect(await resolveBulkSettings(engine, false)).toMatchObject({ enabled: true, lanes: 6, lanesReason: null });
- expect(await resolveBulkSettings(engine, false, 1)).toMatchObject({ lanes: 1, lanesReason: 'disabled by --no-lanes' });
- expect(await resolveBulkSettings(engine, false, 8)).toMatchObject({ lanes: 8, lanesReason: null });
+ expect(await resolveBulkSettings(engine, false)).toMatchObject({ enabled: true, lanes: 8, lanesMax: 16, lanesCap: 'pool',
+ lanesReason: 'the connection pool holds 11 long transactions; set GBRAIN_POOL_SIZE=20 for 16 lanes' });
+ expect(await resolveBulkSettings(engine, false, 1)).toMatchObject({ lanes: 1, lanesMax: 1, lanesCap: 'disabled', lanesReason: 'disabled by --no-lanes' });
+ expect(await resolveBulkSettings(engine, false, 8)).toMatchObject({ lanes: 8, lanesMax: 8, lanesCap: 'maximum', lanesReason: null });
+ expect(await resolveBulkSettings(engine, false, 12)).toMatchObject({ lanes: 8, lanesMax: 12, lanesCap: 'pool' });
expect(await resolveBulkSettings(engine, true, 4)).toMatchObject({ enabled: false, lanes: 1 });
- await withEnv({ GBRAIN_SYNC_LANES: '2' }, async () => expect(await resolveBulkSettings(engine!, false)).toMatchObject({ lanes: 2 }));
- await expect(resolveBulkSettings(engine, false, 9)).rejects.toMatchObject({ code: 'invalid_params' });
+ await withEnv({ GBRAIN_SYNC_LANES: '2' }, async () => expect(await resolveBulkSettings(engine!, false)).toMatchObject({ lanes: 2, lanesCap: 'maximum' }));
+ await expect(resolveBulkSettings(engine, false, 17)).rejects.toMatchObject({ code: 'invalid_params' });
+ await withEnv({ GBRAIN_SYNC_LANES: '17' }, async () => expect(resolveBulkSettings(engine!, false)).rejects.toMatchObject({ code: 'invalid_params' }));
+});
+
+test('the drain names what limited its lanes and what raises it', () => {
+ const base = { maximum: 16, configured: 6, effective: 6, step_down: null, busy: 5.8 };
+ expect(lanesLimit({ ...base, configured: 1, effective: 1, maximum: 1 }, 'disabled')).toMatchObject({ kind: 'lanes_off' });
+ expect(lanesLimit({ ...base, effective: 5, step_down: 'lock_timeout on a lane group' }, 'pool')).toMatchObject({ kind: 'database_contention' });
+ expect(lanesLimit({ ...base, busy: 3.1 }, 'pool')).toMatchObject({ kind: 'feeder', raise: null });
+ expect(lanesLimit(base, 'pool')).toMatchObject({ kind: 'pool', raise: expect.stringContaining('GBRAIN_POOL_SIZE=20') });
+ expect(lanesLimit({ ...base, maximum: 6 }, 'maximum')).toMatchObject({ kind: 'maximum', raise: expect.stringContaining('sync.lanes 16') });
+ expect(lanesLimit({ ...base, maximum: 16, configured: 16, effective: 16, busy: 15 }, 'maximum')).toMatchObject({ kind: 'maximum', raise: null });
+});
+
+test('lane timing counts busy lanes, apply time per page and the commit-turn wait share', async () => {
+ openLanes('wt-time', 'run-time', 4, null);
+ const state = laneOf({ worktree_id: 'wt-time', intent: { lane: 'run-time' } } as never)!;
+ const a = laneApplyBegin(state), b = laneApplyBegin(state);
+ await new Promise(resolve => setTimeout(resolve, 60));
+ a.turn(); b.turn();
+ await new Promise(resolve => setTimeout(resolve, 40));
+ a.turned(); a.end(4);
+ b.turned(); b.end(2);
+ const stats = (await closeLaneRun('run-time'))!;
+ expect(stats.busy).toBeGreaterThan(1.8);
+ expect(stats.applyMsPerPage).toBeGreaterThanOrEqual(15);
+ expect(stats.applyMsPerPage).toBeLessThan(40);
+ expect(stats.turnWaitShare).toBeGreaterThan(0.3);
+ expect(stats.turnWaitShare).toBeLessThan(0.6);
});
test('a lease is shared by lanes; an exclusive writer drains and wounds it and gets the lock once the lanes leave', async () => {
@@ -168,7 +199,9 @@ test('lanes publish several groups at once and every page still commits, attribu
if (!engine) return;
const f = await fixture(engine, notes(80));
const result = await performSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, drain: true, lanes: 4 });
- expect(result.drain).toMatchObject({ outcome: 'synced', bulk: { enabled: true, lanes: { configured: 4 } } });
+ expect(result.drain).toMatchObject({ outcome: 'synced', bulk: { enabled: true, lanes: { maximum: 4, configured: 4, limited_by: { kind: expect.any(String) } } } });
+ expect(result.drain!.bulk!.lanes.busy).toBeGreaterThan(1);
+ expect(result.drain!.bulk!.lanes.apply_ms_per_page).toBeGreaterThan(0);
expect(result.drain!.bulk!.lanes.overlapped_groups).toBeGreaterThan(0);
expect(result.drain!.bulk!.lanes.fallbacks).toBe(0);
const rows = await imports(engine, f.id);