Garry's Opinionated OpenClaw/Hermes Agent Brain
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 (themigratedrows ofscripts/engine-sql-baseline.tsv) do not live here: their SQL exists once insrc/core/engine-sql/(see that entry in engines-2.md). What remains:pglite-engine/checkpoint-guard.ts,pglite-engine/code-edges.ts(PGLite'sgetEdgesByChunk, whose master SQL behaves differently from Postgres's: one UNION ALL under a shared LIMIT; listed indocs/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;keywordStatementTimeoutMsaccepts an integer in range,resolveKeywordStatementTimeoutMs(file, db)applies file > DB > default,keywordStatementTimeoutValueProblemis theconfig setrefusal text, andloadKeywordStatementTimeout(reader, fileValue)yields the<ms>mssetting one connection binds; pinned bytest/keyword-statement-timeout-knob-6495.test.tson 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)wrapssearchKeyword's strict and relaxed statements when hybrid's keyword arm opts in withSearchOpts.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 forsearch.keyword_timeout_negative_cache_seconds(default 600, 0 = off, read once on the first timeout) and later identical runs throwKeywordSkippedAfterTimeoutError(codekeyword_skipped_after_timeout, arm reasonskipped_after_timeout) without a statement; at most 256 entries per engine; each timeout writes one boundedsearch.keyword_timeout_statsrow that doctorkeyword_planreads; #7082: in a serving process (setKeywordTimeoutReruns(true)fromgbrain serve,falsewhen 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 whenkeywordRerunPoolIdle, 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 bytest/keyword-timeout-negative-cache-6495.test.tsandtest/keyword-timeout-rerun-7082.test.ts),postgres-engine/schema-lock-timeout.ts(#5227:resolveSchemaLockTimeoutMsreadsGBRAIN_SCHEMA_LOCK_TIMEOUT_SECONDS, default 60 s;withSchemaLockTimeoutsets a session-levellock_timeouton the reserved DDL backend and restores the prior value on release, used by theschema.sqlreplay inpostgres-engine.tsand thetransaction: falsepath ofmigrate.ts, while a transaction-wrapped migration binds the same wait withSET LOCAL;schemaDiagnosticConnectionopens a one-backend connection that samplespg_blocking_pids()of the waiting backend while the wait is active soschemaLockBlockedErrornames blockers by pid, application, state and transaction age, never query text;init-schema-retry.tsretriesschema_lock_blocked/ SQLSTATE 55P03 with a short backoff; handler migrations and the post-migrationverifySchemarun outside the bound) andpostgres-engine/search-settings.ts(search transactions run withjit = off;withSearchSettingsapplies a read's settings in one statement and restores a caller's values when nested),postgres-engine/reserved-transactions.ts(withReservedConnectionlends its connection atransaction(); 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 whosedefault_transaction_read_onlyis on, from a session SET left on a pooled connection or a role or database default, refuses writes with 25006;beginReadWrite/readWriteTransactionsopen every pool transactionBEGIN READ WRITE, falling back to a plain BEGIN on a hot standby that refuses it, andretryReadOnlyAutocommitreruns an autocommit statement refused with 25006 once inside one; explicitbegin('read only')andSET TRANSACTION ... READ ONLYstay read-only; pinned bytest/inherited-read-only-7183.test.tsand, 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'scancelAndDiscard(), which sends the running fenced statement's CancelRequest, keeps successors out until it settles (bounded byGBRAIN_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 anAbortErrorwith the driver'sCONNECTION_CLOSEDascauseand, when the cancel could not be confirmed (unfenced statement, transport failure, settle timeout), theCANCEL_UNCONFIRMEDrejection ascancelFailure; an abort after COMMIT keeps the committed result; an already-aborted signal rejects before BEGIN; pinned offline bytest/postgres-transaction-cancel-order.test.tsand on direct Postgres and PgBouncer bytest/e2e/transaction-cancel-held-lock.test.ts); the forward-reference bootstrap lives once inengine-sql/bootstrap.tsfor 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:lockTableForAnalyzetakes 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,analyzeAfterIndexBuildthroughanalyzeYieldingToVacuum), andanalyzeDeferredrecognizes its 55P03 refusal. An ANALYZE that waiteddeadlock_timeouton 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. Doctorplanner_stats_stalereports 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:batchedUpdaterepeats 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 legacylinks.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-edgesource_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), v221embedding_pending_since(v221's active-column choice; the first stamping batch writesembedding_pending_since_backfilled_atin its transaction). Pinned bytest/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;setMigrationStatementTimeoutMsfrom operator-onlygbrain apply-migrations --statement-timeout <minutes>, restored when that run returns; 0 removes it) and the timed-out-migration record (configschema_migration_timeout: version, name, whether the run had a prelude, idle-in-transaction pids sampled at the failure):runMigrationswrites 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.tsturns a record into the one fix both apply-migrations (migrations_pendingstill_behind) and doctorschema_versionshow: timed out unbatched and this release has a prelude → rerun; idle sessions open → ask_user, checkdoctor --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 incurrent_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), andassertOwnedTableShapesthrowsforeign_table(table, column, type found, type needed, theSET SCHEMAfix) on the first mismatch.applyForwardReferenceBootstrap(engine-sql/bootstrap.ts) runs it before any DDL, soinitSchemaon both engines refuses before the schema replay, andrunMigrationsruns it before its repairs and the first pending migration. Pinned on both engines bytest/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: whenrow_security_active(table)holds and no permissivepg_policyrow for the caller (PUBLIC or a role it has USAGE of) covers a command, it raiseswriter_coordinator_required(managed_writer_guard:unreadable_state, DETAILstate= 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 aRustEngine(everyBrainEnginemember exceptkind, which is'rust';BrainEngine.kindadmits it once therustconfig value lands; no capabilities, D18) that keeps the addon handle and store path and owns only its lifecycle (connectrecords the config,disconnectruns theregisterBeforeDisconnectstops,reconnectdoes both). Every otherBrainEnginemember is installed from the prototype loop and refusesengine_capability_missing(reason =rustMemberCapability(member), detailmember=… 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 refusesraw_sqlfor Rust;page-body/limits.tsstageBatchBytes(kind)uses it. Pinned bytest/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;loadRustAddonis the throwing form. Order:GBRAIN_RUST_ENGINE_ADDON(an absolute path to abun run rust:buildfile; skips only the release checksum pin,engine_abiand target are still checked); then the addon at<gbrain home>/engines/rust/<engine_build>/<target>.nodenamed by the cachedmanifest-<version>.jsonof 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 withprocess.dlopenfrom a computed path (a literalrequireof a.nodewould be bundled into compiled executables). Reasons (addon-errors.ts, listed inerror-registry.ts):rust_engine_addon_missingisunsupported_target,not_installedoroverride_not_found;rust_engine_addon_mismatchisdigest,engine_abi,engine_build,targetorload_failed; both are raised before the brain is touched.addon-manifest.tsparses the manifest and holdsRUST_ENGINE_ABIandRELEASE_ADDON_TARGETS(linux-x64-glibc,darwin-arm64);addon-target.tsnames 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 plainArrayBuffer, so hidingSharedArrayBufferor swapping a prototype changes nothing. Pinned bytest/rust-engine-addon-loader.test.tsandrust/smoke/smoke.test.ts.