Files
evig/scripts/db/migrations/084_missing_performance_indexes.sql
T
Mao NakamotoandClaude Opus 4.7 f733d44b83 feat(db): land Phase V+W+X — solve all DB audit items
Phase V (critical, applied to Neon directly):
- 083: bootstrap schema_migrations on Neon + backfill 001-082 (verified absent: SELECT EXISTS returned false; 92 rows now tracked)
- 084: 4 missing performance indexes — notifications(user_id,is_read,created_at DESC), pool_memberships(pool_id,status), inventory_items(status,assigned_to), partial fundraising_foundations(created_at DESC) WHERE NOT archived (67MB largest table, 534ms seq scans → indexed)
- V.3 RECLASSIFIED — no plaintext API keys actually exist in hirn_provider_settings (audit subagent overstated; verified empty); no action needed
- V.4 — 6 test accounts disabled on Neon (renamed to __disabled-<uuid>@disabled.local, cleared staff/super-admin flags, emailVerified=NULL). All 6 lacked verified emails so couldn't log in anyway, but the flags were latent risk.

Phase W (hardening):
- W.1: .github/workflows/ci.yml gains migration-drift-check job — spins postgres:17 container, applies all 91 SQL migrations in version-sort order, asserts table count + tracking row count. Non-blocking advisory (continue-on-error:true) so transient CI hiccups don't gate merges.
- W.2: scripts/db/check-orphans.sh sweeps real-FK + polymorphic-reference + stale-token orphans against the live DB. Live run shows 0 FK orphans (Postgres enforcement holds), 40 fundraising_activity_log polymorphic orphans (under threshold), 135 notifications.related_id (crosses threshold — flagged for human investigation), 3 stale verification_tokens.
- W.3: docs/MONEY_CONVENTION.md — integer-cents canonical, lists every legacy decimal(10,2) column to migrate later, explains float-bug class avoidance.
- W.4: docs/DISASTER_RECOVERY.md — Neon restore step-by-step, RTO<1h / RPO<5min targets, schema verification path, smoke-test checklist, quarterly drill cadence, local backup workflow.
- W.5: New audit helpers logUserDeletion (sync, critical) + logDataExport (sync, warning) + logContentDecision (buffered, info) in src/lib/auth/audit.ts. Wired into admin user-delete route + content-approval route. Export route already self-audits via raw INSERT (left alone — works).
- W.6 RECLASSIFIED — OAuth tokens in accounts table technically plaintext (Auth.js default) but app code never reads them after login (verified via grep). Real exfiltration risk minimal; provider-side revocation available. Documented in audit; encryption deferred to dedicated Auth.js-adapter-override session.

Phase X (nice-to-have quick wins):
- X.1: /api/cron/prune-audit-log + vercel.json cron entry (daily 02:00 UTC). Preserves critical-severity rows forever; prunes info/warning >180 days.
- X.2: Migration 085 — location_approvals trigger preventing UPDATE of decision fields (action/status/notes/required_changes/reviewer_id/reviewed_at). Append-only audit trail. Applied to Neon. subscription_pools.organizationId FK SKIPPED — verified no organization table exists, pools use owner_id (user FK).

Net Neon state after this commit:
  93 migrations tracked, 4 new indexes, 6 test accounts disabled, 1 trigger added.

Audit subagent overstatement pattern observed AGAIN — 3 of the original "critical" findings were overstated (plaintext API keys, subscription_pools FK, OAuth-token urgency). Documented per the audit_subagent_overflag memory pattern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 18:07:42 +02:00

40 lines
3.1 KiB
SQL

-- Migration 084: Performance indexes the audit flagged as missing
--
-- 2026-06-03 DB audit found 3 composites declared in migration 074 that
-- never landed on Neon, plus 1 new gap (fundraising_foundations is 67 MB
-- / 16k rows — our largest table — doing 534 ms sequential scans).
--
-- All four are CREATE INDEX IF NOT EXISTS so safe to re-run, and they're
-- BIGINT/INTEGER/UUID/TIMESTAMPTZ columns — index build is near-instant
-- at current row counts.
-- ──────────────────────────────────────────────────────────────────────
-- notifications: dashboard "unread, newest first" query forces a sort
-- without this composite. With it, the planner uses an index-ordered scan.
-- ──────────────────────────────────────────────────────────────────────
CREATE INDEX IF NOT EXISTS idx_notifications_user_unread_recent
ON notifications(user_id, is_read, created_at DESC);
-- ──────────────────────────────────────────────────────────────────────
-- pool_memberships: pool-detail page lists active members; without this
-- composite we scan all memberships per pool.
-- ──────────────────────────────────────────────────────────────────────
CREATE INDEX IF NOT EXISTS idx_pool_memberships_pool_status
ON pool_memberships(pool_id, status);
-- ──────────────────────────────────────────────────────────────────────
-- inventory_items: admin "my queue" filters by status + assignee.
-- ──────────────────────────────────────────────────────────────────────
CREATE INDEX IF NOT EXISTS idx_inventory_items_status_assignee
ON inventory_items(status, assigned_to);
-- ──────────────────────────────────────────────────────────────────────
-- fundraising_foundations: NEW finding. 67 MB / 16k rows; current
-- public-browse query (WHERE archived = false ORDER BY created_at DESC)
-- does a sequential scan + sort. Partial index keeps it small (most rows
-- are not archived).
-- ──────────────────────────────────────────────────────────────────────
CREATE INDEX IF NOT EXISTS idx_fundraising_foundations_active_recent
ON fundraising_foundations(created_at DESC)
WHERE archived = false;