Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(health): exclude soft-deleted far endpoints from most_connected (#6940)
time-attackd7511c718c11
diff --git a/docs/architecture/key-files/engines-2.md b/docs/architecture/key-files/engines-2.mdindex a5b7df2548..b44e2bcd7b 100644--- a/docs/architecture/key-files/engines-2.md+++ b/docs/architecture/key-files/engines-2.md@@ -32,7 +32,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/engine-sql/titles.ts` + `src/core/search/title-statement.ts` — the page-grain title arm (`BrainEngine.searchTitles`) for both engines: `buildSearchTitlesStatement` in `search/` (SQL composed outside engine-sql like `cjk-keyword-sql.ts`; also used by the plan-proof E2E `test/e2e/title-arm-postgres.test.ts`) and `searchTitles(scoped, query, opts, dialect)` in engine-sql, where `dialect` carries the engine differences kept from master (Postgres: 8s per-attempt `statement_timeout`, `enable_seqscan` off for the relaxed local re-run; PGLite: the timeline `stale` probe). Both orderings sort an exact-title key first (`lower(btrim(title, ' "''' || chr(160))) = normalizeAlias(query)`, bound separately from the websearch text so the OR fallback never rebinds it; #5889). The websearch text is read through `gbrain_fts_input($1)` (#6370), the same CJK/ASCII boundary split the index applies, so a glued title query matches. Safe-chunks callers match `pages.search_vector @@ q_a`, the websearch query with every lexeme labeled `:A` (weight A is the title alone), ranked on `ts_filter(search_vector, '{a}')`: served by `idx_pages_search`, title-only for negated and phrase terms, and following the stored `search_vector` language. Pages with a NULL `search_vector` are absent from the remote arm.-- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as in-scope link endpoints grouped per entity page (ties break by slug in code-point order). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`.+- `src/core/engine-sql/health.ts` — `BrainEngine.getHealth` once for both engines (`migrated health`). Three statements, no per-page rows returned: the counters (pages, chunks, links, embedding coverage, missing embeddings, dead links, entity link/timeline coverage), the linkable scope grouped by page type with islanded and with-timeline counts (the orphan policy rendered in SQL by `orphanExclusionSql`; the brain_score timeline grading applies per type), and `most_connected` as live, in-scope link endpoints grouped per entity page (ties break by slug in code-point order; a link whose far endpoint is soft-deleted does not count, #6940). The linkable groups are a separate statement because folding them into the counters crosses Postgres's JIT cost thresholds at about 20k pages. Per-page and per-link checks that misplan without planner statistics (PGLite before its first ANALYZE) are primary-key lookups the planner cannot reorder (scalar subqueries, a LATERAL fenced with `OFFSET 0`), so the statements stay linear with or without statistics. Scope rules: `sourceIds` > `sourceId` > brain-wide, duplicate ids count once, a link counts only when both endpoints are in scope, endpoint liveness in both directions, quarantined pages out of the entity denominators and the linkable scope. Entity pages (#4772) are the types the active schema pack(s) declare as entities, resolved per source by `HealthDeps.entityTypes` (`src/core/schema-pack/entity-types.ts`) and bound as `text[]` parameters (`entityTypePredicateSql`: one list, or a `CASE p.source_id` when sources' packs disagree); a pack that does not load binds an empty list and the result carries `entity_types_status: 'pack_unavailable'`, never the old hardcoded list. Reads take `LegacyUnscopedRead` (pool, no scope transaction). Engine deps are four functions (`embeddingColumn`, `countStalePagesForExtraction`, `getConfig`, `entityTypes`). Pinned field by field against the pre-F4a implementation (`test/helpers/legacy-get-health.ts`, whose `most_connected` was corrected for #6940 as an intended change) by `test/engine-sql-health-equality.test.ts` and `test/e2e/engine-sql-health-parity.test.ts` (direct Postgres and PgBouncer); the pack-driven entity predicate by `test/health-entity-types-pack.test.ts` and `test/e2e/health-entity-types-pack.test.ts`; `most_connected` liveness by `test/health-most-connected-liveness-6940.test.ts` (+ Postgres twin).- `src/core/engine-sql/chunks.ts` `upsertChunksOnce` — a chunk replacement inside the caller's transaction: the batched `chunkWriteInvalidations` guard, then one prune (`moveDisplacedChunksAndPrune`: a row whose vector still matches its text (`movableChunkSql`) and whose exact text and source reappear at another index is parked at a negative index and moved there; rows outside the new set are deleted), then one multi-row INSERT per `jsonRowBatches` batch (at most `ROW_BATCH_MAX_ROWS` rows and `ROW_BATCH_MAX_BYTES` encoded bytes; the first is pipelined with the seal). A failure in any batch rolls back the prune and every earlier batch. Tests: `engine-sql-chunks-batched-write.test.ts`, the multi-batch case in `helpers/engine-sql-rollback-cases.ts`.- `src/core/pglite-resetwal.ts` — pg_resetwal for PGLite NodeFS data dirs, in TypeScript (a port of the electric-sql/pglite pg_resetwal contribution, PR #994, Apache-2.0). Validates the PG17 pg_control layout fail-closed (`WalResetUnsupportedError` on any unsupported shape — PG_VERSION ≠ 17, control ≠ 8192 bytes, control version ≠ 1700, bad seg/block size), removes stale postmaster.pid + old WAL segments + archive_status/summaries entries, writes a replacement shutdown-checkpoint WAL segment + CRC32C'd pg_control. Both file writes are atomic + durable (tmp cleared then opened `'wx'` so a pre-planted symlink at the predictable tmp name can never redirect the write, + fsync(tmp) + rename + fsync(parent dir)); write order is segment-first/control-last so a mid-write kill leaves a state that still fails startup and the next attempt re-runs (idempotent — a torn pair can never claim success). WAL segment size is capped at 64MB (pglite ships 16MB; the Postgres-general 1GB bound would let a corrupt-but-plausible control field drive a 1GB allocation on the repair path). Exports the shared PG17 layout literals (`PG_CONTROL_FILE_SIZE`, `isWalSegmentName`) consumed by pglite-repair.ts. LAYOUT COUPLING: any pglite bump past PG17 must revisit this file together with the `./vector` export blocker (TODOS.md "pglite upgrade blocker" entry). Pinned by `test/pglite-resetwal.test.ts`.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex fc6784835a..79702a3e17 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -904,9 +904,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },- // Wave 20 lane 1 (#6944 #6945).+ // Wave 20 lane 1 (#6944 #6945 #6940).{ since: '0.60.307.0', text: '`gbrain recall --since <value>` now refuses a value it cannot read (and a `--since` with no value) with `invalid_params` (exit 2), echoing the value and listing the accepted forms, instead of silently recalling every time window. `--session` / `--session-id` with no ID refuses the same way instead of recalling every session. The CLI and the recall operation now share one `--since` parser.' },{ since: '0.60.307.0', text: '`gbrain recall --since-last-run` (and `--watch`) on a local brain no longer skips facts when more than `--limit` of them arrived since the last run. A run that fills the window now shows the OLDEST `--limit` new facts (newest first within the page) and the next run continues right after the last one shown, until it catches up; before, it showed the newest `--limit` and the rest were never shown. The cursor file keeps `schema_version: 1` and gains two optional fields, so cursor files from earlier versions keep working. A thin client cannot page yet: when its window is full it prints a warning to raise `--limit`.' },+ { since: '0.60.307.0', text: '`get_health` / `gbrain health` `most_connected` no longer counts links to or from soft-deleted pages, so a hub whose neighbours were deleted drops in the ranking instead of keeping their edges (#6940). The islanded scan already applied this liveness rule.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/engine-sql/health.ts b/src/core/engine-sql/health.tsindex 39ae1c3b94..1d0b90f9eb 100644--- a/src/core/engine-sql/health.ts+++ b/src/core/engine-sql/health.ts@@ -12,7 +12,7 @@* keeps, rendered in SQL by `orphanExclusionSql`) grouped by page type,* with islanded and with-timeline counts per type. The brain_score* timeline component's pack-aware grading (#5828) applies per type here;- * 3. `most_connected`: in-scope link endpoints grouped per entity page.+ * 3. `most_connected`: live, in-scope link endpoints grouped per entity page.* Statement 2 is separate because, folded into statement 1, the combined* plan cost crosses Postgres's JIT thresholds on a 20k-page brain and JIT* compilation alone costs more than the query.@@ -116,8 +116,6 @@ export async function getHealth(// Endpoint checks by primary key; NULL (not true) when the row is missing.const liveSrc = sqlFragment`(SELECT src.deleted_at IS NULL ${inScope.src} FROM pages src WHERE src.id = l.from_page_id)`;const liveTgt = sqlFragment`(SELECT tgt.deleted_at IS NULL ${inScope.tgt} FROM pages tgt WHERE tgt.id = l.to_page_id)`;- const srcInScope = sqlFragment`(SELECT TRUE ${inScope.src} FROM pages src WHERE src.id = l.from_page_id)`;- const tgtInScope = sqlFragment`(SELECT TRUE ${inScope.tgt} FROM pages tgt WHERE tgt.id = l.to_page_id)`;const deadLinkScope = scope === null? sqlFragment``: sqlFragment`AND EXISTS (SELECT 1 FROM pages src WHERE src.id = l.from_page_id ${inScope.src})`;@@ -190,10 +188,6 @@ export async function getHealth(ORDER BY type`);- const farInScope = {- to: scope === null ? sqlFragment`` : sqlFragment`AND ${tgtInScope}`,- from: scope === null ? sqlFragment`` : sqlFragment`AND ${srcInScope}`,- };const { rows: connected } = await exec.run<{ slug: string; link_count: number }>(sqlFragment`WITH entity_pages AS (SELECT p.id, p.slug FROM pages p@@ -205,10 +199,10 @@ export async function getHealth(SELECT e.id, e.slug, 0 AS hit FROM entity_pages eUNION ALLSELECT e.id, e.slug, 1 AS hit FROM entity_pages e- JOIN links l ON l.from_page_id = e.id ${farInScope.to}+ JOIN links l ON l.from_page_id = e.id AND ${liveTgt}UNION ALLSELECT e.id, e.slug, 1 AS hit FROM entity_pages e- JOIN links l ON l.to_page_id = e.id AND l.from_page_id <> l.to_page_id ${farInScope.from}+ JOIN links l ON l.to_page_id = e.id AND l.from_page_id <> l.to_page_id AND ${liveSrc})SELECT slug, sum(hit)::int AS link_countFROM endpointsdiff --git a/test/e2e/health-most-connected-liveness-6940-postgres.test.ts b/test/e2e/health-most-connected-liveness-6940-postgres.test.tsnew file mode 100644index 0000000000..48f86e4871--- /dev/null+++ b/test/e2e/health-most-connected-liveness-6940-postgres.test.ts@@ -0,0 +1,2 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';+await registerPostgresTests(() => import('../health-most-connected-liveness-6940.test.ts'));diff --git a/test/health-most-connected-liveness-6940.test.ts b/test/health-most-connected-liveness-6940.test.tsnew file mode 100644index 0000000000..6db1d72429--- /dev/null+++ b/test/health-most-connected-liveness-6940.test.ts@@ -0,0 +1,63 @@+/**+ * #6940: get_health's most_connected must not count links whose far endpoint+ * is soft-deleted. The islanded scan already applies endpoint liveness both+ * ways (#4153); most_connected checked only scope, so a hub kept the edges to+ * pages the user deleted and outranked live hubs. Real engines, both backends+ * (Postgres through the e2e twin).+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { testBackends } from './helpers/test-backends.ts';++for (const backend of testBackends()) describe(`most_connected liveness (${backend})`, () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ if (backend === 'postgres') {+ const { setupDB, getEngine } = await import('./e2e/helpers.ts');+ await setupDB();+ engine = getEngine();+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }+ }, 120_000);+ afterAll(async () => {+ if (backend === 'postgres') {+ const { teardownDB } = await import('./e2e/helpers.ts');+ await teardownDB();+ } else await engine?.disconnect();+ });+ beforeEach(async () => {+ for (const t of ['links', 'content_chunks', 'timeline_entries', 'tags', 'page_versions', 'pages']) {+ await engine.executeRaw(`DELETE FROM ${t}`);+ }+ });++ const put = (slug: string, type: string) =>+ engine.putPage(slug, { type: type as never, title: slug, compiled_truth: `about ${slug}`, frontmatter: {} });+ const id = async (slug: string) =>+ (await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]))[0].id;+ const link = async (from: string, to: string) =>+ engine.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type) VALUES ($1, $2, 'mentions')`, [await id(from), await id(to)]);+ const ranking = async () => (await engine.getHealth()).most_connected.map(r => [r.slug, r.link_count]);++ test('edges to and from soft-deleted pages do not count in either direction', async () => {+ await put('people/alice-example', 'person');+ await put('companies/acme-example', 'company');+ for (const n of [0, 1, 2]) await put(`notes/n${n}`, 'note');+ // alice: 3 outbound + 1 inbound; two of the notes get deleted below.+ for (const n of [0, 1, 2]) await link('people/alice-example', `notes/n${n}`);+ await link('notes/n0', 'people/alice-example');+ // acme: 2 live edges.+ await link('companies/acme-example', 'notes/n2');+ await link('notes/n2', 'companies/acme-example');+ expect(await ranking()).toEqual([['people/alice-example', 4], ['companies/acme-example', 2]]);++ await engine.softDeletePage('notes/n0');+ await engine.softDeletePage('notes/n1');+ // alice keeps only her edge to n2; acme's two edges are live.+ expect(await ranking()).toEqual([['companies/acme-example', 2], ['people/alice-example', 1]]);+ });+});diff --git a/test/helpers/legacy-get-health.ts b/test/helpers/legacy-get-health.tsindex fb07903c3e..8ce9e181a0 100644--- a/test/helpers/legacy-get-health.ts+++ b/test/helpers/legacy-get-health.ts@@ -72,15 +72,19 @@ export async function legacyGetHealth(GREATEST((SELECT count(*) FROM entity_pages), 1)::float as timeline_coverage`, [scope]);+ // #6940 intentional contract correction: the legacy parity oracle must also+ // exclude dead far endpoints; every other legacy field stays unchanged.const connected = await engine.executeRaw<{ slug: string; link_count: number }>(`SELECT p.slug,(SELECT count(*) FROM links lWHERE (l.from_page_id = p.id- AND ($1::text[] IS NULL- OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.to_page_id AND fp.source_id = ANY($1))))+ AND EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.to_page_id+ AND fp.deleted_at IS NULL+ AND ($1::text[] IS NULL OR fp.source_id = ANY($1))))OR (l.to_page_id = p.id- AND ($1::text[] IS NULL- OR EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.from_page_id AND fp.source_id = ANY($1))))+ AND EXISTS (SELECT 1 FROM pages fp WHERE fp.id = l.from_page_id+ AND fp.deleted_at IS NULL+ AND ($1::text[] IS NULL OR fp.source_id = ANY($1)))))::int as link_countFROM pages pWHERE p.type IN ('entity', 'person', 'company') AND p.deleted_at IS NULL