From 3fbc271e7cc8f9b11f4c1a57e5feb810d9d28b43 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Fri, 15 May 2026 20:18:32 +0800 Subject: [PATCH] feat(migration): add index on created_at for audit_logs Introduced an index on the created_at column of the audit_logs table to optimize the daily retention sweep, improving performance by reducing the need for full table scans during deletions. This change enhances the efficiency of the retention process, particularly for tenants with high RBAC traffic. The corresponding down migration includes the removal of this index. Refs: #1303 --- migrations/sqlite/000000_init.up.sql | 2 ++ migrations/versioned/000044_audit_log.down.sql | 1 + migrations/versioned/000044_audit_log.up.sql | 10 ++++++++++ 3 files changed, 13 insertions(+) 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 $$;