Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
pglite: the autocommit WAL probe runs behind the write, keeping issue order
garrytana65607e692dd
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex c8d143f471..f341a4e6b9 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -20,7 +20,7 @@ src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2178 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.tssrc/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 336 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts)-src/core/pglite-engine.ts 2926 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)+src/core/pglite-engine.ts 2930 ratchet +4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts)src/core/postgres-engine.ts 2917 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured)src/core/search/hybrid.ts 1584 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache keysrc/core/types.ts 2124 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field)diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 677372b6a6..bc5c898b2a 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -2749,7 +2749,8 @@ export class PGLiteEngine implements BrainEngine {if (opts?.signal?.aborted) {throw new DOMException('aborted', 'AbortError');}- const queryPromise = this.autocommitWrite(sql)+ // #5449: an autocommit write is its own outermost transaction, so it takes the WAL checkpoint guard.+ const queryPromise = !this._pageTransaction && this._dbWork !== null && writesWal(sql)? (this._checkpointGuard ??= new PgliteCheckpointGuard()).runStatement(q => this.db.query(q), () => this.db.query(sql, params)).then((r) => r.rows as T[]): this.db.query(sql, params).then((r) => r.rows as T[]);@@ -2762,16 +2763,6 @@ export class PGLiteEngine implements BrainEngine {return Promise.race([queryPromise, abortPromise]);}- /**- * #5449 for statements outside engine.transaction(): an autocommit write is- * its own outermost transaction, so it takes the same checkpoint guard. Bulk- * raw writers (extract batches, vector updates) otherwise grow WAL past the- * automatic trigger and wedge PGLite inside the write that crosses it.- */- private autocommitWrite(sql: string): boolean {- return !this._pageTransaction && this._dbWork !== null && writesWal(sql);- }-/*** PGLite is in-process WASM with no connection pooler, so the direct-pool* routing that `executeRawDirect` provides on Postgres is a no-op here:diff --git a/src/core/pglite-engine/checkpoint-guard.ts b/src/core/pglite-engine/checkpoint-guard.tsindex 2c8f8cb92d..036980e65c 100644--- a/src/core/pglite-engine/checkpoint-guard.ts+++ b/src/core/pglite-engine/checkpoint-guard.ts@@ -63,38 +63,29 @@ export class PgliteCheckpointGuard {}/**- * An autocommit write statement probes like an outermost transaction but- * never queues behind one: a statement issued from inside an open- * transaction's callback must not wait for that transaction to finish. While- * a guarded transaction is open or queued, its own probe covers the WAL.+ * An autocommit write statement is its own outermost transaction. Its WAL+ * probe is issued right behind it, so statements keep their issue order (a+ * read issued after an unawaited write still sees it), and a CHECKPOINT the+ * probe calls for is queued before the caller can issue its next statement:+ * the probe after one statement is the probe before the next, with the same+ * half-distance margin. While a guarded transaction is open or queued, its+ * own probe covers the WAL and the statement adds none.*/async runStatement<T>(query: Query, statement: () => Promise<T>): Promise<T> {- if (this.outermost === 0) await this.beforeOutermostTransaction(this.override ?? query);- return statement();+ const result = statement();+ if (this.outermost > 0) return result;+ const probe = this.issueProbe(this.override ?? query);+ let value: T;+ try { value = await result; } catch (error) { void probe.catch(() => undefined); throw error; }+ if (await this.overThreshold(probe)) {+ // The write committed; a failed CHECKPOINT here warns instead of failing it, and the next probe retries.+ try { await (this.override ?? query)('CHECKPOINT'); } catch (error) { this.warnOnce(error); }+ }+ return value;}private async beforeOutermostTransaction(query: Query): Promise<void> {- let walSinceRedo: number;- try {- if (this.threshold === undefined) {- const [settings] = (await query(`SELECT pg_size_bytes(current_setting('max_wal_size'))::float8 AS max_wal,- pg_size_bytes(current_setting('wal_segment_size'))::float8 AS segment,- current_setting('checkpoint_completion_target')::float8 AS target`)).rows;- this.threshold = checkpointGuardThreshold(Number(settings!.max_wal), Number(settings!.segment), Number(settings!.target));- }- const [probe] = (await query(- 'SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), redo_lsn)::float8 AS since_redo FROM pg_control_checkpoint()')).rows;- walSinceRedo = Number(probe!.since_redo);- if (!Number.isFinite(walSinceRedo)) throw new Error('WAL position is unavailable');- } catch (error) {- if (!this.warned) {- this.warned = true;- this.warn(`[pglite] WAL checkpoint guard is unavailable (${error instanceof Error ? error.message : String(error)}); `- + 'continuing without it. Large imports may stall; restart the command to resume if one does.');- }- return;- }- if (walSinceRedo < this.threshold) return;+ if (!await this.overThreshold(this.issueProbe(query))) return;try {await query('CHECKPOINT');} catch (error) {@@ -103,4 +94,36 @@ export class PgliteCheckpointGuard {'stop other gbrain processes, restart the command, and run `gbrain pglite-repair --dry-run` if it fails again');}}++ /** Issues the settings read (first time only) and the WAL read immediately, in that order. */+ private issueProbe(query: Query): Promise<{ settings: Record<string, unknown> | undefined; since: Record<string, unknown> | undefined }> {+ const settings = this.threshold === undefined ? query(`SELECT pg_size_bytes(current_setting('max_wal_size'))::float8 AS max_wal,+ pg_size_bytes(current_setting('wal_segment_size'))::float8 AS segment,+ current_setting('checkpoint_completion_target')::float8 AS target`) : null;+ const since = query('SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), redo_lsn)::float8 AS since_redo FROM pg_control_checkpoint()');+ return Promise.all([settings, since]).then(([s, w]) => ({ settings: s?.rows[0], since: w.rows[0] }));+ }++ /** Whether WAL since redo passed the threshold; false (after one warning) when the probe cannot answer. */+ private async overThreshold(probe: ReturnType<PgliteCheckpointGuard['issueProbe']>): Promise<boolean> {+ try {+ const { settings, since } = await probe;+ if (this.threshold === undefined) {+ this.threshold = checkpointGuardThreshold(Number(settings!.max_wal), Number(settings!.segment), Number(settings!.target));+ }+ const walSinceRedo = Number(since!.since_redo);+ if (!Number.isFinite(walSinceRedo)) throw new Error('WAL position is unavailable');+ return walSinceRedo >= this.threshold;+ } catch (error) {+ this.warnOnce(error);+ return false;+ }+ }++ private warnOnce(error: unknown): void {+ if (this.warned) return;+ this.warned = true;+ this.warn(`[pglite] WAL checkpoint guard is unavailable (${error instanceof Error ? error.message : String(error)}); `+ + 'continuing without it. Large imports may stall; restart the command to resume if one does.');+ }}diff --git a/test/pglite-checkpoint-guard.test.ts b/test/pglite-checkpoint-guard.test.tsindex 6ead892886..70a9700b29 100644--- a/test/pglite-checkpoint-guard.test.ts+++ b/test/pglite-checkpoint-guard.test.ts@@ -195,7 +195,7 @@ describe('autocommit write statements take the guard', () => {'BEGIN', 'COMMIT', 'ROLLBACK', 'SAVEPOINT s', 'SET search_path = public', 'CHECKPOINT']) expect(writesWal(sql)).toBe(false);});- test('an autocommit write past the threshold checkpoints first; a read never does', async () => {+ test('an autocommit write past the threshold checkpoints before the next statement; a read never does', async () => {const spy = install(engine, { threshold: 0 });await engine.executeRaw("INSERT INTO autocommit_probe VALUES (1, 'guarded')");expect(spy.checkpoints()).toBe(1);@@ -203,6 +203,14 @@ describe('autocommit write statements take the guard', () => {expect(spy.checkpoints()).toBe(1);});+ test('statements keep their issue order: a read issued after an unawaited write sees it', async () => {+ install(engine, { threshold: 0 });+ const write = engine.executeRaw("UPDATE autocommit_probe SET v = 'ordered' WHERE id = 1");+ const read = engine.executeRaw<{ v: string }>('SELECT v FROM autocommit_probe WHERE id = 1');+ await write;+ expect((await read)[0]?.v).toBe('ordered');+ });+test('about 200 MB of autocommit WAL past a 64 MB max_wal_size completes instead of wedging', async () => {const dir = mkdtempSync(join(tmpdir(), 'gbrain-autocommit-wal-'));try {