From 7cd7709b4a34e93a6014f3bb04e6ea4fd0944762 Mon Sep 17 00:00:00 2001 From: Tomas Kracmar Date: Wed, 22 Apr 2026 15:20:19 +0200 Subject: [PATCH] fix: dedupe alert_rules before creating unique index in setup_indexes() The unique index on alert_rules.name was being created before duplicates were cleaned up, causing DuplicateKeyError on startup when existing duplicates were present. Move deduplication into setup_indexes() so it runs before the unique index is created. v1.7.6 --- VERSION | 2 +- backend/database.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 6a126f4..de28578 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.7.5 +1.7.6 diff --git a/backend/database.py b/backend/database.py index c57cd32..c6e1264 100644 --- a/backend/database.py +++ b/backend/database.py @@ -12,6 +12,20 @@ alerts_collection = db["alerts"] logger = structlog.get_logger("aoc.database") +def _dedupe_alert_rules(): + """Remove duplicate alert_rules by name, keeping the oldest document.""" + try: + pipeline = [ + {"$sort": {"_id": ASCENDING}}, + {"$group": {"_id": "$name", "first_id": {"$first": "$_id"}}}, + ] + seen = {doc["_id"]: doc["first_id"] for doc in db["alert_rules"].aggregate(pipeline)} + for name, keep_id in seen.items(): + db["alert_rules"].delete_many({"name": name, "_id": {"$ne": keep_id}}) + except Exception: + pass # Collection may not exist yet + + def setup_indexes(max_retries: int = 5, delay: float = 2.0): """Ensure MongoDB indexes exist. Retries on connection errors.""" from time import sleep @@ -23,6 +37,7 @@ def setup_indexes(max_retries: int = 5, delay: float = 2.0): events_collection.create_index([("service", ASCENDING), ("timestamp", DESCENDING)]) events_collection.create_index("id") saved_searches_collection.create_index([("created_by", ASCENDING), ("created_at", DESCENDING)]) + _dedupe_alert_rules() db["alert_rules"].create_index("name", unique=True) events_collection.create_index( [("actor_display", TEXT), ("raw_text", TEXT), ("operation", TEXT)],