Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): unpaced embed-stale drains leave half the real pool free (#5902)

garrytan3f2257990130
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 52538ff7fd..3bc956eaa6 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -24,7 +24,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).
-- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines.
+- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`.
- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root) and hands it back to `importImageFile`, so OCR budget, protected-OCR refusal and the rebuild stay in the importer. Reports candidates, rebuilt, unchanged, missing source files and failures (`failures > 0` exits non-zero). Pinned by `test/embed-stale-images.test.ts`.
- `src/core/embed-stall.ts` — progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks via `noteEmbedApiResponse()` on EVERY settled embed API attempt — success, error, or retry (hooked in `embed-retry.ts:embedBatchWithBackoff`; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (`readProgress()`, wired to chunks embedded) for `GBRAIN_EMBED_STALL_ABORT_SECONDS` (env-only knob; default 900 via `DEFAULT_EMBED_STALL_ABORT_SEC`, `<= 0` disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (`reason: 'stall_timeout'`), never a `process.exit`: only the CLI wrapper (`src/commands/embed.ts:runEmbed`) maps it to a non-zero exit, and minion handlers and the cycle's embed phase (`cycle.ts:runPhaseEmbed`) convert it to a failure via `assertEmbedNotStalled`. The abort path runs an idempotent, deadline-bounded cleanup (`EMBED_STALL_CLEANUP_DEADLINE_MS`) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud; `stop()` clears it on every normal path. Pinned by `test/embed-stall.test.ts`.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 5caae7164e..782f0d28ac 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -307,6 +307,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/ai/embedding-guard.ts": ["test/e2e/embedding-zero-norm-4616-postgres.test.ts"],
"src/commands/reindex-vectors.ts": ["test/e2e/embedding-zero-norm-4616-postgres.test.ts"],
"src/core/embedding-invalidation.ts": ["test/e2e/embed-stale-dry-run-restamp-5289-postgres.test.ts", "test/e2e/embedding-tombstones-postgres.test.ts"],
+ "src/core/embed-concurrency.ts": ["test/e2e/embed-stale-pool-default-postgres.test.ts"],
+ "src/core/embed-stale.ts": ["test/e2e/embed-stale-pool-default-postgres.test.ts"],
"src/core/persistence/effect-git.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],
"src/core/persistence/effect-journal.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts"],
"src/core/persistence/grandfather.ts": ["test/e2e/persistence-git-coalescing-5530-postgres.test.ts", "test/e2e/grandfather-projection-postgres.test.ts"],
diff --git a/src/core/embed-concurrency.ts b/src/core/embed-concurrency.ts
index 9daff449cc..a4ca174ac3 100644
--- a/src/core/embed-concurrency.ts
+++ b/src/core/embed-concurrency.ts
@@ -36,3 +36,28 @@ export function resolveEmbedConcurrency(
}
return clamped;
}
+
+/**
+ * Worker count for an embed-stale drain called without one (#5902): the
+ * embed-backfill job unpaced, and the remediation embed step. Each worker
+ * holds a connection across its read and upsert, and a worker job shares the
+ * engine's pool with the read-lane health probe, so the default leaves half
+ * of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's
+ * instance pool included) free: `min(20, max(1, floor(poolMax / 2)))`, or 20
+ * without a pool (PGLite). An explicit GBRAIN_EMBED_CONCURRENCY keeps the
+ * full-pool clamp and its warning; lowering the default stays silent.
+ */
+export function resolveStaleEmbedConcurrency(
+ engine: { kind: string; getPoolDiagnostics?: () => { poolMax: number | null } | null },
+ env: Record<string, string | undefined> = process.env,
+): number {
+ let poolMax: number | null | undefined;
+ try {
+ poolMax = engine.getPoolDiagnostics?.()?.poolMax;
+ } catch {
+ poolMax = null;
+ }
+ const pool = typeof poolMax === 'number' && poolMax > 0 ? poolMax : null;
+ if (env.GBRAIN_EMBED_CONCURRENCY) return resolveEmbedConcurrency(engine.kind, undefined, env, pool ?? resolvePoolSize());
+ return pool === null ? 20 : Math.min(20, Math.max(1, Math.floor(pool / 2)));
+}
diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.ts
index 3f29dd412e..02b2b1ee87 100644
--- a/src/core/embed-stale.ts
+++ b/src/core/embed-stale.ts
@@ -31,6 +31,7 @@ import {
quoteIdentifier,
} from './search/embedding-column.ts';
import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';
+import { resolveStaleEmbedConcurrency } from './embed-concurrency.ts';
import { AbortError } from './abort-check.ts';
/**
@@ -74,7 +75,7 @@ export interface StaleCursor {
export interface EmbedStaleOpts {
/** Chunks per cursor page. Default 2000 (matches the legacy CLI default). */
batchSize?: number;
- /** Max parallel slug-keys embedded inside a single batch. Default 20. */
+ /** Max parallel slug-keys embedded inside a single batch. Default: half the engine pool, at most 20 (`resolveStaleEmbedConcurrency`, #5902). */
concurrency?: number;
/** Resume cursor from a prior run. Default: from start. */
cursor?: StaleCursor;
@@ -348,7 +349,7 @@ export async function embedStaleForSource(
opts: EmbedStaleOpts = {},
): Promise<EmbedStaleResult> {
const batchSize = opts.batchSize ?? 2000;
- const concurrency = opts.concurrency ?? 20;
+ const concurrency = opts.concurrency ?? resolveStaleEmbedConcurrency(engine);
const signal = opts.signal;
const embedFn = opts.embedFn ?? ((texts, fnOpts) =>
embedBatchWithBackoff(texts, { abortSignal: fnOpts.abortSignal }));
diff --git a/test/e2e/embed-stale-pool-default-postgres.test.ts b/test/e2e/embed-stale-pool-default-postgres.test.ts
new file mode 100644
index 0000000000..96f3ad61da
--- /dev/null
+++ b/test/e2e/embed-stale-pool-default-postgres.test.ts
@@ -0,0 +1,69 @@
+/**
+ * #5902 on real Postgres: an embed-stale drain called without a concurrency
+ * runs half as many workers as the engine's actual pool
+ * (`getPoolDiagnostics().poolMax` read from the postgres.js client), so a
+ * worker job leaves connections for the health probe.
+ *
+ * Protects: the default reading the real pool of an instance-pool engine
+ * (the worker shape, E17) and of the module-pool engine (default size), not
+ * a configured guess. Regression: the unconditional 20 workers on a 4- or
+ * 10-connection pool.
+ * Existing coverage: test/embed-stale-pool-default.test.ts fakes the pool on
+ * PGLite; this pins that PostgresEngine reports the pool the default uses.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { embedStaleForSource } from '../../src/core/embed-stale.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { installFixtureChunks } from '../helpers/page-projection.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';
+
+const DATABASE_URL = requirePostgresTestDatabase();
+
+async function seed(engine: PostgresEngine, pages: number): Promise<void> {
+ for (let i = 0; i < pages; i++) {
+ const slug = `notes/p${i}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nseeded` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `chunk of ${slug}`, chunk_source: 'compiled_truth', token_count: 4, embedding: undefined }]);
+ }
+}
+
+async function peak(engine: PostgresEngine, dims: number): Promise<number> {
+ let inFlight = 0;
+ let max = 0;
+ const result = await embedStaleForSource(engine, 'default', {
+ embedFn: async (texts) => {
+ inFlight++;
+ max = Math.max(max, inFlight);
+ await new Promise((r) => setTimeout(r, 150));
+ inFlight--;
+ return texts.map(() => { const v = new Float32Array(dims); v[0] = 1; return v; });
+ },
+ });
+ expect(result.embedded).toBe(12);
+ return max;
+}
+
+async function embeddingDims(engine: PostgresEngine): Promise<number> {
+ const [row] = await engine.executeRaw<{ dims: number }>(
+ `SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding'`,
+ );
+ return Number(row?.dims ?? 1536);
+}
+
+for (const style of ['instance', 'module'] as const) describe(`#5902 embed-stale default concurrency on Postgres (${style} pool)`, () => {
+ let engine: PostgresEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ ({ engine, close } = await isolatedPersistencePostgres(DATABASE_URL, style));
+ }, 120_000);
+ afterAll(async () => { await close(); });
+
+ test('the drain peaks at half the engine pool', async () => {
+ const poolMax = engine.getPoolDiagnostics()?.poolMax;
+ expect(typeof poolMax).toBe('number');
+ if (style === 'instance') expect(poolMax).toBe(4);
+ await seed(engine, 12);
+ expect(await peak(engine, await embeddingDims(engine))).toBe(Math.min(20, Math.max(1, Math.floor(poolMax! / 2))));
+ }, 120_000);
+});
diff --git a/test/embed-stale-pool-default.test.ts b/test/embed-stale-pool-default.test.ts
new file mode 100644
index 0000000000..2474dd2fd5
--- /dev/null
+++ b/test/embed-stale-pool-default.test.ts
@@ -0,0 +1,104 @@
+/**
+ * #5902: an embed-stale drain called without a concurrency (the unpaced
+ * embed-backfill job, the remediation embed step) leaves half of the
+ * engine's real connection pool free.
+ *
+ * Protects: the default worker count `min(20, max(1, floor(poolMax/2)))`
+ * read from `engine.getPoolDiagnostics().poolMax` (a worker's instance pool
+ * included), 20 without a pool, an explicit GBRAIN_EMBED_CONCURRENCY keeping
+ * the full-pool clamp, and an explicit `concurrency` option winning.
+ * Regression: the unconditional default of 20 workers that saturated a
+ * 10-connection pool and starved the worker's health probe.
+ * Existing coverage: test/embed-concurrency-pool-clamp.test.ts covers the
+ * CLI clamp (`resolveEmbedConcurrency`), not this default.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { embedStaleForSource } from '../src/core/embed-stale.ts';
+import { resolveStaleEmbedConcurrency } from '../src/core/embed-concurrency.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 30000);
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+/** The PGLite engine reporting a Postgres-style pool of `poolMax`. */
+function withPool(poolMax: number): BrainEngine {
+ return new Proxy(engine, {
+ get(target, prop) {
+ if (prop === 'getPoolDiagnostics') return () => ({ poolMax, tracked: {} });
+ const value = Reflect.get(target, prop);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ }) as unknown as BrainEngine;
+}
+
+async function seed(pages: number): Promise<void> {
+ for (let i = 0; i < pages; i++) {
+ const slug = `notes/p${i}`;
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}\n\nseeded` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `chunk of ${slug}`, chunk_source: 'compiled_truth', token_count: 4, embedding: undefined }]);
+ }
+}
+
+/** Peak number of keys inside the embed call at once. */
+async function peakConcurrency(target: BrainEngine, opts: { concurrency?: number } = {}): Promise<number> {
+ let inFlight = 0;
+ let peak = 0;
+ const result = await embedStaleForSource(target, 'default', {
+ ...opts,
+ embedFn: async (texts) => {
+ inFlight++;
+ peak = Math.max(peak, inFlight);
+ await new Promise((r) => setTimeout(r, 150));
+ inFlight--;
+ return texts.map(() => { const v = new Float32Array(1536); v[0] = 1; return v; });
+ },
+ });
+ expect(result.embedded).toBe(12);
+ return peak;
+}
+
+describe('embed-stale default concurrency (#5902)', () => {
+ test('the default worker count is half the engine pool, capped at 20; no pool keeps 20', () => {
+ const cases: Array<[number | null | undefined, number]> = [[10, 5], [2, 1], [1, 1], [64, 20], [41, 20], [null, 20], [undefined, 20]];
+ for (const [poolMax, expected] of cases) {
+ const target = { kind: 'postgres', ...(poolMax === undefined ? {} : { getPoolDiagnostics: () => ({ poolMax }) }) };
+ expect(resolveStaleEmbedConcurrency(target, {}), String(poolMax)).toBe(expected);
+ }
+ expect(resolveStaleEmbedConcurrency({ kind: 'pglite' }, {})).toBe(20);
+ expect(resolveStaleEmbedConcurrency({ kind: 'postgres', getPoolDiagnostics: () => ({ poolMax: 10 }) }, { GBRAIN_EMBED_CONCURRENCY: '8' })).toBe(8);
+ expect(resolveStaleEmbedConcurrency({ kind: 'postgres', getPoolDiagnostics: () => ({ poolMax: 10 }) }, { GBRAIN_EMBED_CONCURRENCY: '30' })).toBe(10);
+ });
+
+ test('a pool of 10 peaks at 5 concurrent keys; an instance pool of 2 peaks at 1', async () => {
+ await seed(12);
+ expect(await peakConcurrency(withPool(10))).toBe(5);
+ await resetPgliteState(engine);
+ await seed(12);
+ expect(await peakConcurrency(withPool(2))).toBe(1);
+ }, 60_000);
+
+ test('GBRAIN_EMBED_CONCURRENCY=8 and an explicit concurrency win over the half-pool default', async () => {
+ await seed(12);
+ expect(await withEnv({ GBRAIN_EMBED_CONCURRENCY: '8' }, () => peakConcurrency(withPool(10)))).toBe(8);
+ await resetPgliteState(engine);
+ await seed(12);
+ expect(await peakConcurrency(withPool(10), { concurrency: 7 })).toBe(7);
+ }, 60_000);
+});