diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql index 2c5693ed..f95ca3b7 100644 --- a/migrations/sqlite/000000_init.up.sql +++ b/migrations/sqlite/000000_init.up.sql @@ -296,6 +296,8 @@ CREATE INDEX IF NOT EXISTS idx_audit_logs_actor ON audit_logs(actor_user_id); CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_action ON audit_logs(tenant_id, action); +CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at + ON audit_logs(created_at); CREATE TABLE IF NOT EXISTS knowledge_tags ( id VARCHAR(36) PRIMARY KEY, diff --git a/migrations/versioned/000044_audit_log.down.sql b/migrations/versioned/000044_audit_log.down.sql index 68a74c48..52598d79 100644 --- a/migrations/versioned/000044_audit_log.down.sql +++ b/migrations/versioned/000044_audit_log.down.sql @@ -17,6 +17,7 @@ BEGIN RAISE WARNING '[Migration 000044 down] Dropping audit_logs — durable history will be lost'; END $$; +DROP INDEX IF EXISTS idx_audit_logs_created_at; DROP INDEX IF EXISTS idx_audit_logs_tenant_action; DROP INDEX IF EXISTS idx_audit_logs_actor; DROP INDEX IF EXISTS idx_audit_logs_tenant_id_desc; diff --git a/migrations/versioned/000044_audit_log.up.sql b/migrations/versioned/000044_audit_log.up.sql index 77728734..577ede49 100644 --- a/migrations/versioned/000044_audit_log.up.sql +++ b/migrations/versioned/000044_audit_log.up.sql @@ -53,4 +53,14 @@ CREATE INDEX IF NOT EXISTS idx_audit_logs_actor CREATE INDEX IF NOT EXISTS idx_audit_logs_tenant_action ON audit_logs (tenant_id, action); +-- Powers the daily retention sweep `DELETE FROM audit_logs WHERE +-- created_at < cutoff`. Without it the sweep would Seq Scan the whole +-- table on every run, which on a 90-day-retained tenant with bursty +-- RBAC traffic is enough to blow past the runner's 30s timeout and +-- never converge. Indexing created_at also keeps the per-day DELETE +-- bounded to roughly one day's worth of rows once the table reaches +-- steady state. +CREATE INDEX IF NOT EXISTS idx_audit_logs_created_at + ON audit_logs (created_at); + DO $$ BEGIN RAISE NOTICE '[Migration 000044] audit_logs table ready'; END $$;