Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embed): clamp embed concurrency to the Postgres client pool (#5183)
garrytanbb3c79339e1b
diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex ba7783fc10..445af1f695 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -36,6 +36,7 @@ import {import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';import { embedBackfillLockId } from '../core/embed-backfill-lock.ts';import { AITransientError } from '../core/ai/errors.ts';+import { resolvePoolSize } from '../core/db.ts';import { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';import {@@ -1168,6 +1169,43 @@ function preserveCodeMetadata(loaded: any, base: ChunkInput): ChunkInput {return carryChunkMetadata(loaded, base);}+let warnedEmbedConcurrencyClamp = false;++/** Test seam: let the clamp warning print again. */+export function _resetEmbedConcurrencyClampWarningForTest(): void {+ warnedEmbedConcurrencyClamp = false;+}++/**+ * Parallel page-embedding workers: GBRAIN_EMBED_CONCURRENCY (default 20),+ * lowered to a paced run's cap, and on Postgres never above the client pool+ * (#5183). Each worker holds a connection across its read and upsert, so more+ * workers than pool connections left the run waiting on itself: no progress,+ * no error, 0% CPU. An explicit setting that gets lowered is reported once+ * per process; the default is lowered silently.+ */+export function resolveEmbedConcurrency(+ engineKind: string,+ paceMaxConcurrency?: number,+ env: Record<string, string | undefined> = process.env,+ poolSize: number = resolvePoolSize(),+): number {+ const explicit = env.GBRAIN_EMBED_CONCURRENCY;+ const parsed = parseInt(explicit || '20', 10);+ const base = Number.isFinite(parsed) && parsed > 0 ? parsed : 20;+ const paced = paceMaxConcurrency ? Math.min(base, paceMaxConcurrency) : base;+ if (engineKind !== 'postgres' || paced <= poolSize) return paced;+ const clamped = Math.max(1, poolSize);+ if (explicit && !warnedEmbedConcurrencyClamp) {+ warnedEmbedConcurrencyClamp = true;+ process.stderr.write(+ `[embed] GBRAIN_EMBED_CONCURRENCY=${explicit} is above the connection pool (${poolSize}); using ${clamped} workers. ` ++ `Raise GBRAIN_POOL_SIZE or lower GBRAIN_EMBED_CONCURRENCY to match.\n`,+ );+ }+ return clamped;+}+async function embedAll(engine: BrainEngine,staleOnly: boolean,@@ -1247,10 +1285,7 @@ async function embedAll(// Paced runs lower this to the resolved cap (the real lever vs pooler-slot// starvation); unpaced keeps the env/default 20. Codex P2: only ever LOWER —// never raise above an operator's existing env cap.- const BASE_CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);- const CONCURRENCY = staleOpts?.paceMaxConcurrency- ? Math.min(BASE_CONCURRENCY, staleOpts.paceMaxConcurrency)- : BASE_CONCURRENCY;+ const CONCURRENCY = resolveEmbedConcurrency(engine.kind, staleOpts?.paceMaxConcurrency);async function embedOnePage(page: typeof pages[number]) {// #1737: bail before doing any work for this page if the run was aborted.@@ -1803,10 +1838,7 @@ async function embedAllStale(// Paced runs lower concurrency to the resolved cap (E-1: worker count IS the// lever on this single pool, no separate permit). Codex P2: pacing only ever// LOWERS concurrency — never raise above an operator's existing env cap.- const BASE_CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);- const CONCURRENCY = staleOpts?.paceMaxConcurrency- ? Math.min(BASE_CONCURRENCY, staleOpts.paceMaxConcurrency)- : BASE_CONCURRENCY;+ const CONCURRENCY = resolveEmbedConcurrency(engine.kind, staleOpts?.paceMaxConcurrency);const pacer = staleOpts?.pacer ?? createNoopPacer();// D3 + D3a + D8: wall-clock budget. 30 min default; env override.diff --git a/test/embed-concurrency-pool-clamp.test.ts b/test/embed-concurrency-pool-clamp.test.tsnew file mode 100644index 0000000000..6943d98d25--- /dev/null+++ b/test/embed-concurrency-pool-clamp.test.ts@@ -0,0 +1,53 @@+/**+ * #5183: `embed --stale` wedged (no progress, no error, 0% CPU) when+ * GBRAIN_EMBED_CONCURRENCY (default 20) exceeded the Postgres client pool:+ * every worker holds a connection, so extra workers waited on the pool+ * forever. Embed concurrency is now clamped to the pool on Postgres.+ */++import { describe, test, expect, spyOn } from 'bun:test';+import { readFileSync } from 'fs';+import { resolve } from 'path';++import { _resetEmbedConcurrencyClampWarningForTest, resolveEmbedConcurrency } from '../src/commands/embed.ts';++describe('#5183 embed concurrency never exceeds the Postgres pool', () => {+ test('an explicit setting above the pool is clamped, with one warning per process', () => {+ _resetEmbedConcurrencyClampWarningForTest();+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: '20' }, 12)).toBe(12);+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: '20' }, 12)).toBe(12);+ const lines = err.mock.calls.map(c => String(c[0])).filter(l => l.includes('[embed]'));+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain('GBRAIN_EMBED_CONCURRENCY=20 is above the connection pool (12); using 12 workers');+ expect(lines[0]).toContain('GBRAIN_POOL_SIZE');+ } finally {+ err.mockRestore();+ }+ });++ test('the default 20 is clamped to the pool silently (the pool-2 guidance case)', () => {+ _resetEmbedConcurrencyClampWarningForTest();+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ expect(resolveEmbedConcurrency('postgres', undefined, {}, 2)).toBe(2);+ expect(err.mock.calls.filter(c => String(c[0]).includes('[embed]'))).toHaveLength(0);+ } finally {+ err.mockRestore();+ }+ });++ test('unchanged when the pool is large enough, on PGLite, and for a lower paced cap', () => {+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: '8' }, 12)).toBe(8);+ expect(resolveEmbedConcurrency('pglite', undefined, {}, 2)).toBe(20);+ expect(resolveEmbedConcurrency('postgres', 4, {}, 12)).toBe(4);+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: 'junk' }, 50)).toBe(20);+ });++ test('both embed loops use the clamped value', () => {+ const src = readFileSync(resolve(import.meta.dir, '..', 'src', 'commands', 'embed.ts'), 'utf-8');+ expect(src.match(/const CONCURRENCY = resolveEmbedConcurrency\(engine\.kind, staleOpts\?\.paceMaxConcurrency\);/g)).toHaveLength(2);+ expect(src).not.toMatch(/parseInt\(process\.env\.GBRAIN_EMBED_CONCURRENCY/);+ });+});