Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(migration): add index on created_at for audit_logs

wizardchen3fbc271e7cc8
diff --git a/migrations/sqlite/000000_init.up.sql b/migrations/sqlite/000000_init.up.sql
index 2c5693ed5..f95ca3b7d 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 68a74c488..52598d796 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 77728734f..577ede492 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 $$;