Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(reindex): size the markdown writer pool from the pending total and document --workers (#5181)
garrytan9cb30a2d93b9
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.mdindex cce9d227eb..20a42950c1 100644--- a/docs/architecture/key-files/commands-5.md+++ b/docs/architecture/key-files/commands-5.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/commands/repair.ts` — `gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]` and `gbrain repair --all`. Kinds `timeline` (#5567 materialize), `visibility` (#5525 tighten-only backfill) `safe-chunks` (#5050/#5247 projection-only re-seal of pages of every kind below the safe-chunk fence; `--no-embed` defers embedding to `embed --stale`), `contextual-mode` (#5621 projection-only stamp of the import-time contextual retrieval mode on pages that have none; honors `--no-embed`) `connector-checkpoints` (#5686 brain-wide cleanup of connector checkpoint rows no source can load), `orphan-bindings` (#5732 brain-wide cleanup of persistence source bindings whose source or incarnation is gone) and `embedding-effects` (#5629/#5734 settlement of stale queued and failed embedding effects: reconciled, superseded, retry_queued or blocked, reported per item in `outcomes` / `outcome_items`) and `google-file-modes` (clears group/other bits on gbrain's own files under Google source dirs outside `~/.gbrain`; filesystem only); no kind previews every kind. Dry run unless `--apply` (no prompt; `--yes` refused). `parseRepairArgs` is strict: any unknown option or a second positional refuses `invalid_params` before anything runs, and `--max-usd`/`--max-cost` name the capped route `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. Help lines come from `REPAIR_REGISTRY`; `--json` adds `paid` per kind and `paid_kinds`. Output carries the resolved scope, affected count, a capped `source:slug` sample, residual counts, request-ID / receipt-byte / re-embedding cost and capacity, and the apply command; `--json` has the same fields. Host-only: thin clients refuse via `THIN_CLIENT_REFUSED_COMMANDS`. Logic lives in `src/core/repair/`.-- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.+- `src/commands/reindex.ts` — `gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--json] [--no-embed] [--repo PATH]`. The writer pool is sized once from the run's page target (pending, capped by `--limit`) through `resolveWorkersWithClamp`, so Postgres runs over 100 pages default to `DEFAULT_PARALLEL_WORKERS` while PGLite stays at one; `--workers` overrides and the used count is reported as `workers` in the result and JSON (pinned by `test/e2e/reindex-auto-workers-5181.test.ts`). Walks markdown pages with stale `chunker_version` (plus unstamped contextual-retrieval mode when embedding is enabled; `--no-embed` still stamps the mode of every page it re-chunks) in 100-row id-keyset batches; a failed row cannot starve later batches in the same invocation. `--type` adds a bound-parameter `pages.type = $N` scope for focused backfills such as atom pages and is rejected by reindex modes that do not consume it. Current-version chunkless healing deliberately remains owned by the native, bounded `embed --stale` path. Rows with non-null `source_path` re-import via `importFromFile`; rows without fall back to `importFromContent`. Both paths pass `forceRechunk: true` to bypass `importFromContent`'s `content_hash` short-circuit — without it the chunker version bump never reaches pages whose source content hasn't changed, AND the stripFactsFence privacy strip never applies to chunks stored without it. Wired into `src/commands/upgrade.ts:runPostUpgrade` after `apply-migrations`. The DB-only fallback (no source file on disk) does NOT pass body-only `compiled_truth` to `importFromContent` (that path re-parses with EMPTY frontmatter and OVERWRITES the page's real frontmatter/title/timeline); it `getPage`+`getTags`, reconstructs FULL markdown via `serializeMarkdown(frontmatter, compiled_truth, timeline, {type, title, tags})`, and re-imports THAT so re-chunking a DB-only page preserves everything while bumping `chunker_version`. Pinned by `test/reindex-preserve-tags.test.ts` and `test/reindex.test.ts`.- `src/commands/repair-jsonb.ts` — `gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 8 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter, subagent_messages.content_blocks, subagent_tool_executions.input, subagent_tool_executions.output). The subagent targets are `jsonPayloadOnly`: those columns can legitimately hold jsonb string scalars (persistToolExec binds a tool's pre-serialized string payload as-is), so their damage predicate additionally requires container-shaped content (`^\s*[\[{]`) that `pg_input_is_valid(..., 'jsonb')` (PG16+ floor, same as the IS JSON predicate `updateSourceConfig` relies on) actually parses — a plain-text value that merely starts with `[` or `{` is never flagged or corrupted. Targets whose table doesn't exist on the brain are skipped via `to_regclass` (brains without the subagent tables), and one target's failure is recorded on stderr while the run continues — earlier repairs are already committed and the v0_12_2 migration orchestrator JSON-parses stdout. `runDoctor`'s `jsonb_integrity` check counts damage with the same predicate over the same target list. Repairs double-encoded rows on Postgres; PGLite no-ops. Idempotent. Pinned by `test/repair-jsonb.test.ts` + `test/doctor.test.ts`.diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 7d376a30e5..bf5c9ba1ef 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -24,6 +24,8 @@ const MIGRATION_WAVE_TESTS = [];export const E2E_TEST_MAP: Record<string, string[]> = {+ // Fix wave 8, Lane G: reindex auto-concurrency sizing (#5181).+ "src/commands/reindex.ts": ["test/e2e/reindex-auto-workers-5181.test.ts"],// Fix wave 4, Lane D: the apply-migrations orchestration lease (#5693), source deletes and// orphan bindings (#5732), and deactivate racing admission (#5455)."src/core/migration-orchestration-lock.ts": ["test/e2e/apply-migrations-orchestration-lock.test.ts"],diff --git a/src/commands/reindex.ts b/src/commands/reindex.tsindex 7803a74c4b..b1155ccf6a 100644--- a/src/commands/reindex.ts+++ b/src/commands/reindex.ts@@ -70,6 +70,8 @@ export interface ReindexResult {dryRun: boolean;chunkerVersion: number;type: string | null;+ /** Parallel writers used for the run (#5181); absent when nothing ran. */+ workers?: number;}// #3686: real usage, reachable via `gbrain reindex --help` (the generic@@ -79,7 +81,7 @@ export interface ReindexResult {const REINDEX_HELP = `gbrain reindex — re-chunk / re-embed existing pages after a pipeline upgradeUSAGE- gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--dry-run] [--no-embed] [--json] [--repo PATH]+ gbrain reindex --markdown [--type PAGE_TYPE] [--limit N] [--workers N] [--dry-run] [--no-embed] [--json] [--repo PATH]gbrain reindex --multimodal [--limit N] [--workers N] [--dry-run] [--cost-estimate] [--no-embed] [--yes] [--json]gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]gbrain reindex --vectors [--dry-run] [--json]@@ -98,8 +100,10 @@ TARGETS (exactly one required)OPTIONS--type <t> --markdown only: restrict to one page type--limit N Cap pages/chunks processed this run- --workers N --multimodal only: parallel UPDATEs per batch- (--concurrency is an alias)+ --workers N --markdown and --multimodal: parallel writers per batch+ (--concurrency is an alias). --markdown on Postgres+ defaults to 4 when more than 100 pages are pending;+ PGLite always uses 1--dry-run Report what would change; write nothing--cost-estimate --multimodal only: print the embed cost estimate and stop--no-embed Skip re-embedding (chunk-only reindex)@@ -367,6 +371,9 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<Rlet afterId: number | null = null;const BATCH = 100;const repoPath = opts.repoPath ? resolve(opts.repoPath) : null;+ // #5181: size the pool from the whole run, not one batch. A full batch is+ // exactly the auto threshold (100), so batch length never enabled it.+ const { workers } = resolveWorkersWithClamp(engine, opts.workers, 'reindex', target);while (reindexed + skipped + failed < target) {const remaining = target - (reindexed + skipped + failed);@@ -380,15 +387,9 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<R// v0.41.15.0 (T10, D9): per-batch sliding pool. Counters are JS-// single-thread atomic so reindexed++ / failed++ are race-free// across workers.- const writersResolved = resolveWorkersWithClamp(- engine,- opts.workers,- 'reindex',- batch.length,- );await runSlidingPool({items: batch,- workers: writersResolved.workers,+ workers,failureLabel: (row) => row.slug,onItem: async (row) => {reporter.tick();@@ -473,6 +474,7 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<RdryRun: false,chunkerVersion: MARKDOWN_CHUNKER_VERSION,type,+ workers,};if (opts.json) {@@ -480,10 +482,11 @@ export async function runReindex(engine: BrainEngine, args: string[]): Promise<Rpending, pending_after: pendingAfter, reindexed, skipped, failed,chunker_version: MARKDOWN_CHUNKER_VERSION,type,+ workers,}) + '\n');} else {const scope = type ? ` type=${type}` : '';- process.stderr.write(`[reindex] Done.${scope} reindexed=${reindexed} skipped=${skipped} failed=${failed} pending_before=${pending} pending_after=${pendingAfter}\n`);+ process.stderr.write(`[reindex] Done.${scope} reindexed=${reindexed} skipped=${skipped} failed=${failed} pending_before=${pending} pending_after=${pendingAfter} workers=${workers}\n`);}return result;diff --git a/test/e2e/reindex-auto-workers-5181.test.ts b/test/e2e/reindex-auto-workers-5181.test.tsnew file mode 100644index 0000000000..403ebbc8e1--- /dev/null+++ b/test/e2e/reindex-auto-workers-5181.test.ts@@ -0,0 +1,44 @@+/**+ * #5181 on Postgres: `reindex --markdown` sizes its writer pool from the+ * pending total. A full batch is exactly the auto-concurrency threshold+ * (100), so sizing from the batch length kept every run at one writer no+ * matter how many pages were pending.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { hasDatabase, setupDB, teardownDB, getEngine } from './helpers.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { runReindex } from '../../src/commands/reindex.ts';+import { DEFAULT_PARALLEL_WORKERS } from '../../src/core/sync-concurrency.ts';++const RUN = hasDatabase();+const describeE2E = RUN ? describe : describe.skip;+const PAGES = 120;++describeE2E('reindex --markdown auto-concurrency (Postgres, #5181)', () => {+ beforeAll(async () => {+ await setupDB();+ const engine = getEngine();+ for (let i = 0; i < PAGES; i++) {+ const body = `---\ntitle: Reindex note ${i}\ntype: note\n---\nReindex worker sizing body ${i}.\n`;+ await importFromContent(engine, `notes/reindex-${String(i).padStart(3, '0')}`, body, { noEmbed: true });+ }+ await engine.executeRaw("UPDATE pages SET chunker_version = 0 WHERE slug LIKE 'notes/reindex-%'");+ }, 120_000);+ afterAll(async () => { await teardownDB(); });++ test('more than 100 pending pages use the auto worker count and reindex every page', async () => {+ const result = await runReindex(getEngine(), ['--markdown', '--no-embed']);+ expect(result.pending).toBe(PAGES);+ expect(result.workers).toBe(DEFAULT_PARALLEL_WORKERS);+ expect(result.reindexed).toBe(PAGES);+ expect(result.failed).toBe(0);+ expect(result.pendingAfter).toBe(0);+ }, 120_000);++ test('a run capped at 100 pages stays on one writer', async () => {+ await getEngine().executeRaw("UPDATE pages SET chunker_version = 0 WHERE slug LIKE 'notes/reindex-%'");+ const result = await runReindex(getEngine(), ['--markdown', '--no-embed', '--limit', '100']);+ expect(result.workers).toBe(1);+ expect(result.reindexed).toBe(100);+ }, 120_000);+});