Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: index human_activity_events on (source, happened_at) so timeline reads stop scanning (#5715)
Adam Eivy07bbb7a5ecbb
diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex 3c8df2f059..62b1647736 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -171,11 +171,34 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {expect(sqlIdx.size).toBeGreaterThan(0);});- // The operator-action ledger (#5594) is a machine-local db-primary table that- // ships in BOTH sources. `human_activity_events` has no dedicated assertion here- // and that is a gap, not a precedent — a column or index added to one file only- // would leave every EXISTING install without it (init-db.sql runs on fresh- // provisioning alone), so pin columns and index names for this one explicitly.+ // The operator-action ledger (#5594) and the human-activity timeline (#2150)+ // are machine-local db-primary tables that ship in BOTH sources. A column or+ // index added to one file only would leave every EXISTING install without it+ // (init-db.sql runs on fresh provisioning alone), so pin columns and index+ // names for both explicitly.+ it('human_activity_events has the same columns and indexes in both files', () => {+ const sqlBody = extractCreateTable(INIT_SQL, 'human_activity_events');+ const jsBody = extractCreateTable(DB_JS, 'human_activity_events');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE human_activity_events').toBeTruthy();+ expect(jsBody, 'db/schema/humanActivity.js missing CREATE TABLE human_activity_events').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());++ const sqlIdx = extractIndexNames(INIT_SQL, 'idx_human_activity_');+ const jsIdx = extractIndexNames(DB_JS, 'idx_human_activity_');+ expect([...sqlIdx].sort()).toEqual([...jsIdx].sort());+ // Name them: the dedupe index is the idempotency contract (ON CONFLICT+ // (source, dedupe_key) DO NOTHING) and the two composites (#5715) are what+ // keep a source-scoped timeline read off a full happened_at walk — dropping+ // either from both files would otherwise read as a passing set match.+ expect([...sqlIdx].sort()).toEqual([+ 'idx_human_activity_dedupe',+ 'idx_human_activity_happened',+ 'idx_human_activity_source_happened',+ 'idx_human_activity_source_kind_happened',+ ]);+ });+it('user_action_events has the same columns and indexes in both files', () => {const sqlBody = extractCreateTable(INIT_SQL, 'user_action_events');const jsBody = extractCreateTable(DB_JS, 'user_action_events');diff --git a/server/lib/db/schema/humanActivity.js b/server/lib/db/schema/humanActivity.jsindex 9b93400350..a183327a89 100644--- a/server/lib/db/schema/humanActivity.js+++ b/server/lib/db/schema/humanActivity.js@@ -25,4 +25,21 @@ export const humanActivityDdl = [)`,`CREATE UNIQUE INDEX IF NOT EXISTS idx_human_activity_dedupe ON human_activity_events (source, dedupe_key)`,`CREATE INDEX IF NOT EXISTS idx_human_activity_happened ON human_activity_events (happened_at)`,+ // Source-scoped timeline reads (#5715). The dominant shape is+ // `WHERE source = $1 [AND kind = ...] ORDER BY happened_at DESC LIMIT n`+ // (listEvents in services/humanActivity.js), which neither index above+ // serves: the dedupe index leads on `source` but carries no ordering, and+ // the `happened_at` index orders but must filter every row on `source` — so+ // a low-volume source behind a high-volume one walks past a large number of+ // non-matching rows before it can fill LIMIT. Two indexes, not one: the+ // kind-filtered read is a distinct shape, and `(source, kind, happened_at)`+ // does not efficiently serve the source-only query for a source with many+ // kinds. Mirrors the composites `user_action_events` already ships.+ //+ // Deliberately NOT `CONCURRENTLY`: ensureSchema() runs this DDL as part of+ // the boot sequence, and CREATE INDEX CONCURRENTLY cannot run inside a+ // transaction block. The table is machine-local and the boot-time build is+ // bounded, so the blocking build is the correct trade here.+ `CREATE INDEX IF NOT EXISTS idx_human_activity_source_happened ON human_activity_events (source, happened_at DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_human_activity_source_kind_happened ON human_activity_events (source, kind, happened_at DESC)`,];diff --git a/server/lib/db/schema/schema.test.js b/server/lib/db/schema/schema.test.jsindex 4fb64592ed..3cd0f72984 100644--- a/server/lib/db/schema/schema.test.js+++ b/server/lib/db/schema/schema.test.js@@ -101,6 +101,20 @@ describe('db/schema barrel + composer (#2832)', () => {expect(firstTrigIdx).toBeGreaterThan(fnIdx);});+ // #5715 — the source-scoped composites are the only indexes serving+ // `WHERE source = $1 [AND kind = ...] ORDER BY happened_at DESC LIMIT n`.+ // Pin both, including the DESC ordering, so a future rewrite of the DDL array+ // can't silently drop one back to a sequential-ish index walk.+ it('humanActivityDdl ships the source-scoped happened_at composites', () => {+ const ddl = schema.humanActivityDdl.join('\n');+ expect(ddl).toContain(+ 'CREATE INDEX IF NOT EXISTS idx_human_activity_source_happened ON human_activity_events (source, happened_at DESC)',+ );+ expect(ddl).toContain(+ 'CREATE INDEX IF NOT EXISTS idx_human_activity_source_kind_happened ON human_activity_events (source, kind, happened_at DESC)',+ );+ });+it('buildAuditTriggers emits a DROP + CREATE pair per audited table', () => {const triggers = buildAuditTriggers();expect(triggers.length).toBe(auditedTables.length * 2);diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 2f20824302..478a9b4ce6 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -196,6 +196,10 @@ CREATE TABLE IF NOT EXISTS human_activity_events ();CREATE UNIQUE INDEX IF NOT EXISTS idx_human_activity_dedupe ON human_activity_events (source, dedupe_key);CREATE INDEX IF NOT EXISTS idx_human_activity_happened ON human_activity_events (happened_at);+-- Source-scoped timeline reads (#5715) — see db/schema/humanActivity.js for why+-- there are two composites and why neither uses CONCURRENTLY.+CREATE INDEX IF NOT EXISTS idx_human_activity_source_happened ON human_activity_events (source, happened_at DESC);+CREATE INDEX IF NOT EXISTS idx_human_activity_source_kind_happened ON human_activity_events (source, kind, happened_at DESC);-- Operator-action ledger (#5594) — the durable, filterable record of what the-- human actually did in PortOS. Machine-local like human_activity_events:diff --git a/server/services/humanActivity.db.test.js b/server/services/humanActivity.db.test.jsindex c33a48d150..b56ead99a0 100644--- a/server/services/humanActivity.db.test.js+++ b/server/services/humanActivity.db.test.js@@ -12,7 +12,7 @@* rows this suite inserts.*/import { describe, it, expect, afterAll } from 'vitest';-import { checkHealth, ensureSchema, close, query } from '../lib/db.js';+import { checkHealth, ensureSchema, close, query, withTransaction } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';import { recordEvents, listEvents, getDaySummary, stripParticipantsForAccount } from './humanActivity.js';@@ -238,3 +238,44 @@ describe.skipIf(!runDb)('stripParticipantsForAccount — send-as alias backfillexpect(row.participants).toEqual([{ email: '[email protected]' }]);});});++// #5715 — the source-scoped composite is what keeps a low-volume source sitting+// behind a high-volume one off a backwards walk of the whole `happened_at`+// index. Assert the PLAN, not a timing: plan shape is deterministic in CI,+// elapsed time is not.+describe.skipIf(!runDb)('source-scoped read plan (#5715)', () => {+ // On a near-empty shared test table a sequential scan is genuinely the+ // cheapest plan, so an unmodified EXPLAIN would prove nothing about the index.+ // Disabling seqscan for the transaction makes the choice Postgres faces on a+ // real, large table — this composite vs. the plain `happened_at` index —+ // observable here.+ const explainWithoutSeqScan = (sql, params) => withTransaction(async (client) => {+ await client.query('SET LOCAL enable_seqscan = off');+ const res = await client.query(`EXPLAIN (FORMAT JSON) ${sql}`, params);+ return JSON.stringify(res.rows[0]['QUERY PLAN']);+ });++ it('uses idx_human_activity_source_happened for a source-scoped newest-first read', async () => {+ await recordEvents([mk({ dedupeKey: 'plan-1' }), mk({ dedupeKey: 'plan-2' })]);+ const plan = await explainWithoutSeqScan(+ `SELECT * FROM human_activity_events+ WHERE source = $1+ ORDER BY happened_at DESC+ LIMIT 50`,+ [SOURCE],+ );+ expect(plan).toContain('idx_human_activity_source_happened');+ });++ it('uses idx_human_activity_source_kind_happened when the read is also kind-scoped', async () => {+ await recordEvents([mk({ dedupeKey: 'plan-kind-1' })]);+ const plan = await explainWithoutSeqScan(+ `SELECT * FROM human_activity_events+ WHERE source = $1 AND kind = $2+ ORDER BY happened_at DESC+ LIMIT 50`,+ [SOURCE, 'message.received'],+ );+ expect(plan).toContain('idx_human_activity_source_kind_happened');+ });+});