Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
14.5 KB
Raw Blame

Key files: Engines (2/2, continued)

Subsystem index · Previous entries. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.

  • src/core/postgres-engine/ + src/core/pglite-engine/ — per-engine module directories for code that is genuinely dialect-specific. Migrated storage domains (the migrated rows of scripts/engine-sql-baseline.tsv) do not live here: their SQL exists once in src/core/engine-sql/ (see that entry in engines-2.md). What remains: pglite-engine/checkpoint-guard.ts, pglite-engine/code-edges.ts (PGLite's getEdgesByChunk, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed in docs/designs/refactor-wave-1/w1-inventory.md), postgres-engine/cancellation.ts, postgres-engine/init-schema-lock.ts, postgres-engine/keyword-statement-timeout.ts (#6495: KEYWORD_STATEMENT_TIMEOUT_KEY = search.keyword_statement_timeout_ms, default 8000, range 1000-60000; keywordStatementTimeoutMs accepts an integer in range, resolveKeywordStatementTimeoutMs(file, db) applies file > DB > default, keywordStatementTimeoutValueProblem is the config set refusal text, and loadKeywordStatementTimeout(reader, fileValue) yields the <ms>ms setting one connection binds; pinned by test/keyword-statement-timeout-knob-6495.test.ts on a recording handle and, with DATABASE_URL, on a real Postgres whose locked tables make each statement wait until the bound cancels it), postgres-engine/keyword-timeout-cache.ts (#6495 negative cache: KeywordTimeoutNegativeCache.run(enabled, db, keyParts, exec) wraps searchKeyword's strict and relaxed statements when hybrid's keyword arm opts in with SearchOpts.keywordTimeoutCache; the key hashes the statement text, its parameters, the RLS source scope and the statement timeout, so only the exact statement is skipped; a genuine statement-timeout 57014, never a user cancel, records an entry for search.keyword_timeout_negative_cache_seconds (default 600, 0 = off, read once on the first timeout) and later identical runs throw KeywordSkippedAfterTimeoutError (code keyword_skipped_after_timeout, arm reason skipped_after_timeout) without a statement; at most 256 entries per engine; each timeout writes one bounded search.keyword_timeout_stats row that doctor keyword_plan reads; #7082: in a serving process (setKeywordTimeoutReruns(true) from gbrain serve, false when its shutdown begins) each entry is re-run in the background 30 s after the timeout, then 60 s, 120 s and so on, never past its TTL, one at a time per engine and only when keywordRerunPoolIdle, reading the pool the engine queries (enginePoolStats, so a serve's process pool too), sees no waiting query and a connection left free beside the re-run, its rows thrown away, and the first re-run that answers ends the skip; pinned by test/keyword-timeout-negative-cache-6495.test.ts and test/keyword-timeout-rerun-7082.test.ts), postgres-engine/schema-lock-timeout.ts (#5227: resolveSchemaLockTimeoutMs reads GBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60 s; withSchemaLockTimeout sets a session-level lock_timeout on the reserved DDL backend and restores the prior value on release, used by the schema.sql replay in postgres-engine.ts and the transaction: false path of migrate.ts, while a transaction-wrapped migration binds the same wait with SET LOCAL; schemaDiagnosticConnection opens a one-backend connection that samples pg_blocking_pids() of the waiting backend while the wait is active so schemaLockBlockedError names blockers by pid, application, state and transaction age, never query text; init-schema-retry.ts retries schema_lock_blocked / SQLSTATE 55P03 with a short backoff; handler migrations and the post-migration verifySchema run outside the bound) and postgres-engine/search-settings.ts (search transactions run with jit = off; withSearchSettings applies a read's settings in one statement and restores a caller's values when nested), postgres-engine/reserved-transactions.ts (withReservedConnection lends its connection a transaction(); BEGIN READ WRITE and SAVEPOINT go out with the statements after them, and a COMMIT answered with ROLLBACK throws), postgres-engine/read-write-transactions.ts (#7183: a server connection whose default_transaction_read_only is on, from a session SET left on a pooled connection or a role or database default, refuses writes with 25006; beginReadWrite / readWriteTransactions open every pool transaction BEGIN READ WRITE, falling back to a plain BEGIN on a hot standby that refuses it, and retryReadOnlyAutocommit reruns an autocommit statement refused with 25006 once inside one; explicit begin('read only') and SET TRANSACTION ... READ ONLY stay read-only; pinned by test/inherited-read-only-7183.test.ts and, on direct Postgres and PgBouncer, test/e2e/pooler-inherited-read-only-7183.test.ts), postgres-engine/transaction-abort.ts (transaction(fn, { signal }): an abort calls the begin handle's cancelAndDiscard(), which sends the running fenced statement's CancelRequest, keeps successors out until it settles (bounded by GBRAIN_CANCEL_SETTLE_MS), then discards the connection, so a statement blocked on a lock stops instead of waiting out its statement timeout (#6598) and the server rolls the transaction back; the caller gets an AbortError with the driver's CONNECTION_CLOSED as cause and, when the cancel could not be confirmed (unfenced statement, transport failure, settle timeout), the CANCEL_UNCONFIRMED rejection as cancelFailure; an abort after COMMIT keeps the committed result; an already-aborted signal rejects before BEGIN; pinned offline by test/postgres-transaction-cancel-order.test.ts and on direct Postgres and PgBouncer by test/e2e/transaction-cancel-held-lock.test.ts); the forward-reference bootstrap lives once in engine-sql/bootstrap.ts for both engines. Façades import these modules statically (engine-live no-runtime-dynamic-import rule) and keep their full public surface.

  • src/core/analyze-lock.ts — #7083: lockTableForAnalyze takes a table's SHARE UPDATE EXCLUSIVE lock with NOWAIT before every ANALYZE gbrain runs on Postgres on its own (the projection and chunk refreshes, repair planner-stats, analyzeAfterIndexBuild through analyzeYieldingToVacuum), and analyzeDeferred recognizes its 55P03 refusal. An ANALYZE that waited deadlock_timeout on a running autovacuum made Postgres cancel it, so a refresh after every embed drain kept a 10M-chunk content_chunks from ever being vacuumed; a request that never waits never signals a vacuum, and the caller defers its ANALYZE. Doctor planner_stats_stale reports a hot table whose autovacuum stays starved (readVacuumStarvation). Test: test/e2e/analyze-yields-to-autovacuum-postgres.test.ts.

  • src/core/migration-preludes.ts — #7108 runner-side preludes for published migrations whose SQL rewrites a large table in one transaction (published migration files never change; restamp refuses an edit). runMigrationPrelude(engine, version) runs right before that migration's SQL inside the runner's retry wrapper: batchedUpdate repeats the migration's own SET and predicate over id-ordered batches (5,000 rows, inlined so a generic prepared plan cannot scan the table per batch; __setBackfillBatchRowsForTests), each its own transaction with the migration statement budget and the schema lock timeout, so progress is the data itself and a rerun resumes; a column the migration adds first is added first, in the migration's column order (fresh and upgraded ordinals stay equal). Preludes: v011 legacy links.link_source (skipped below PG15, where the migration refuses), v028 chunk keyword vectors, v033 request-log agent names (NULL-token rows stay the migration's own), v116 code-edge source_id, v161 (Postgres) the partial pages index built concurrently under the budget on a reserved connection (the migration caps its own build at 30 s; another session's build or an invalid result stops the run), v221 embedding_pending_since (v221's active-column choice; the first stamping batch writes embedding_pending_since_backfilled_at in its transaction). Pinned by test/e2e/migration-v221-batched-backfill-7108.test.ts. Migrations that cannot be moved here are listed in docs/guides/troubleshooting.md#migration-statement-timeout.

  • src/core/migration-timeout.ts — #7108 the migration statement budget (migrationStatementTimeoutMs, default 10 min; setMigrationStatementTimeoutMs from operator-only gbrain apply-migrations --statement-timeout <minutes>, restored when that run returns; 0 removes it) and the timed-out-migration record (config schema_migration_timeout: version, name, whether the run had a prelude, idle-in-transaction pids sampled at the failure): runMigrations writes it on a 57014 or a statement-timeout retry exhaustion and deletes it after a pass reaches head. A schema-graph leaf (no release version, so the PGLite snapshot hash stays stable). migration-timeout-advice.ts turns a record into the one fix both apply-migrations (migrations_pending still_behind) and doctor schema_version show: timed out unbatched and this release has a prelude → rerun; idle sessions open → ask_user, check doctor --locks, end the ones still open, rerun; none → ask_user, one run with --statement-timeout 120.

  • src/core/owned-table-shapes.ts — #9190 the shape check for tables gbrain owns by a generic name (oauth_clients, oauth_tokens, oauth_codes): one catalog query in current_schema() compares each existing table's v32 columns and their types with what gbrain has always created (a wrong type is named before a missing column), and assertOwnedTableShapes throws foreign_table (table, column, type found, type needed, the SET SCHEMA fix) on the first mismatch. applyForwardReferenceBootstrap (engine-sql/bootstrap.ts) runs it before any DDL, so initSchema on both engines refuses before the schema replay, and runMigrations runs it before its repairs and the first pending migration. Pinned on both engines by test/upgrade-foreign-oauth-table.test.ts.

  • src/core/derived-state-maintainers.ts + src/core/schema-migrations/v281-derived-state-maintainers-fail-closed.ts — #7637: the eight derived-state maintainer triggers (page retrievals, atom scan state, tag revision, version trust and attribution, page search vector, projection queue, trust generation) stay SECURITY INVOKER and fail closed. requireMaintainerPoliciesSql(table, commands) is the PL/pgSQL each body runs before touching another table: when row_security_active(table) holds and no permissive pg_policy row for the caller (PUBLIC or a role it has USAGE of) covers a command, it raises writer_coordinator_required (managed_writer_guard:unreadable_state, DETAIL state = the table), so an empty read never counts as nothing to do. Each body lives with its schema (TAG_REVISION_FUNCTION_SQL, SNAPSHOT_VERSION_FUNCTION, STAMP_VERSION_FUNCTION, BUMP_FUNCTION, PAGE_PROJECTION_QUEUE_FUNCTION_SQL, pageSearchVectorTriggerFnSql); the page retrievals body is a schema blob fragment here. v281 replaces only the functions (the search vector under the configured FTS language), never the triggers. The policies a scoped writer needs are the ENGINES.md maintainer recipe (test/derived-state-maintainers-7637.test.ts, applied verbatim).

  • src/core/rust-engine.ts + src/core/rust-engine/ — the opt-in Rust engine shell (ENGINES.md "The Rust engine shell"). openRustEngine({ addon, databasePath }) is the one seam the addon loader calls after it has loaded and verified the native addon; it returns a RustEngine (every BrainEngine member except kind, which is 'rust'; BrainEngine.kind admits it once the rust config value lands; no capabilities, D18) that keeps the addon handle and store path and owns only its lifecycle (connect records the config, disconnect runs the registerBeforeDisconnect stops, reconnect does both). Every other BrainEngine member is installed from the prototype loop and refuses engine_capability_missing (reason = rustMemberCapability(member), detail member=… capability=… outcome=none written=nothing) before any work. rust-engine/members.ts (RUST_ENGINE_MEMBERS, satisfies Record<keyof BrainEngine, MemberClass>) classifies every member, so a new engine method fails typecheck until it is classified. rust-engine/errors.ts (capabilityMissing(capability, member, outcome)) builds the refusal. src/core/sql-engine-kind.ts (EngineKind, isSqlEngineKind, isRustEngineKind, sqlEngineKind(kind, member)) narrows a kind for SQL-only code and refuses raw_sql for Rust; page-body/limits.ts stageBatchBytes(kind) uses it. Pinned by test/rust-engine-shell.test.ts.

  • src/core/rust-engine/addon-loader.ts — the Rust engine addon loader (ENGINES.md "The Rust engine shell"). loadRustEngineAddon(overrides?) returns { ok: true, addon } or { ok: false, code, reason, message } for the two refusals and rethrows anything else; loadRustAddon is the throwing form. Order: GBRAIN_RUST_ENGINE_ADDON (an absolute path to a bun run rust:build file; skips only the release checksum pin, engine_abi and target are still checked); then the addon at <gbrain home>/engines/rust/<engine_build>/<target>.node named by the cached manifest-<version>.json of the running version, loaded only when its SHA-256 equals the manifest's. It never reaches the network, takes no lock and writes nothing; a refusal leaves every file as it was. Only the Rust engine's open path may import the loader, lazily, so PGLite and Postgres brains never load the addon or create <gbrain home>/engines/; it loads with process.dlopen from a computed path (a literal require of a .node would be bundled into compiled executables). Reasons (addon-errors.ts, listed in error-registry.ts): rust_engine_addon_missing is unsupported_target, not_installed or override_not_found; rust_engine_addon_mismatch is digest, engine_abi, engine_build, target or load_failed; both are raised before the brain is touched. addon-manifest.ts parses the manifest and holds RUST_ENGINE_ABI and RELEASE_ADDON_TARGETS (linux-x64-glibc, darwin-arm64); addon-target.ts names this platform's target. The addon itself (rust/crates/gbrain-napi/src/binding.rs) refuses a typed array whose buffer the runtime (napi_is_arraybuffer) does not call a plain ArrayBuffer, so hiding SharedArrayBuffer or swapping a prototype changes nothing. Pinned by test/rust-engine-addon-loader.test.ts and rust/smoke/smoke.test.ts.