Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Release the schedule lock on the happy path too, and dedupe past duplicates

Daoud Clarke93054df10c35
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index 51cb002..decf3e0 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -101,8 +101,13 @@ class MwmblConfig(AppConfig):
report_usage_to_polar(repeat=3600, repeat_until=None)
except Exception:
- # Don't prevent startup if background task scheduling fails. Release
- # the lock so a later-starting worker can retry instead of waiting
- # out the full TTL.
+ # Don't prevent startup if background task scheduling fails
log.exception("Failed to schedule background tasks")
+ finally:
+ # Release promptly rather than holding it for the full TTL: by the
+ # time we get here the Task rows (if created) are already committed,
+ # so a worker that acquires the lock next will see them via the
+ # exists() checks above and correctly skip creating duplicates. The
+ # TTL above is only a safety net for a process that dies before
+ # reaching this point.
cache.delete(MwmblConfig._SCHEDULE_LOCK_KEY)
diff --git a/mwmbl/migrations/0031_dedupe_background_task_schedules.py b/mwmbl/migrations/0031_dedupe_background_task_schedules.py
new file mode 100644
index 0000000..97c6517
--- /dev/null
+++ b/mwmbl/migrations/0031_dedupe_background_task_schedules.py
@@ -0,0 +1,42 @@
+"""
+Data migration cleaning up duplicate periodic Task rows created by past
+deploys racing past the non-atomic scheduling check in
+MwmblConfig._schedule_background_tasks() (fixed alongside this migration).
+
+For each periodic task name, keeps a single unlocked row and deletes the
+rest. Locked (in-flight) rows are left alone so we never interfere with a
+task that's currently running.
+"""
+from django.db import migrations
+
+TASK_NAMES = [
+ "mwmbl.background.sync_search_counts",
+ "mwmbl.background.report_usage_to_polar",
+]
+
+
+def dedupe_task_schedules(apps, schema_editor):
+ Task = apps.get_model("background_task", "Task")
+ for task_name in TASK_NAMES:
+ duplicates = list(
+ Task.objects.filter(task_name=task_name, locked_by__isnull=True).order_by("id")
+ )
+ # Keep the oldest row, delete the rest.
+ for task in duplicates[1:]:
+ task.delete()
+
+
+def noop_reverse(apps, schema_editor):
+ pass
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("mwmbl", "0030_remove_mwmbluser_tier_usagebucket_reported_overage_and_more"),
+ ("background_task", "0003_alter_completedtask_id_alter_task_id"),
+ ]
+
+ operations = [
+ migrations.RunPython(dedupe_task_schedules, noop_reverse),
+ ]
diff --git a/test/test_dedupe_background_task_schedules.py b/test/test_dedupe_background_task_schedules.py
new file mode 100644
index 0000000..98b5bd3
--- /dev/null
+++ b/test/test_dedupe_background_task_schedules.py
@@ -0,0 +1,77 @@
+"""
+Tests for the 0031 data migration that cleans up duplicate periodic Task
+rows left behind by past deploys racing past the (now-fixed) non-atomic
+scheduling check in MwmblConfig._schedule_background_tasks().
+"""
+
+import importlib
+
+import pytest
+from background_task.models import Task
+from django.apps import apps as django_apps
+from django.utils import timezone
+
+migration_module = importlib.import_module("mwmbl.migrations.0031_dedupe_background_task_schedules")
+dedupe_task_schedules = migration_module.dedupe_task_schedules
+
+SYNC_TASK = "mwmbl.background.sync_search_counts"
+POLAR_REPORT_TASK = "mwmbl.background.report_usage_to_polar"
+
+
+def _make_task(task_name, locked_by=None):
+ return Task.objects.create(
+ task_name=task_name,
+ task_params="[[], {}]",
+ task_hash="fake-hash",
+ run_at=timezone.now(),
+ locked_by=locked_by,
+ )
+
+
+def test_dedupe_removes_extra_unlocked_duplicates():
+ kept = _make_task(SYNC_TASK)
+ _make_task(SYNC_TASK)
+ _make_task(SYNC_TASK)
+
+ dedupe_task_schedules(django_apps, None)
+
+ remaining = list(Task.objects.filter(task_name=SYNC_TASK))
+ assert len(remaining) == 1
+ assert remaining[0].id == kept.id
+
+
+def test_dedupe_leaves_locked_task_alone():
+ _make_task(SYNC_TASK, locked_by="worker-1")
+ _make_task(SYNC_TASK)
+ _make_task(SYNC_TASK)
+
+ dedupe_task_schedules(django_apps, None)
+
+ remaining = Task.objects.filter(task_name=SYNC_TASK)
+ # The locked (in-flight) task is left alone, plus one surviving unlocked duplicate.
+ assert remaining.count() == 2
+ assert remaining.filter(locked_by="worker-1").exists()
+
+
+def test_dedupe_is_idempotent_and_leaves_single_task_alone():
+ task = _make_task(POLAR_REPORT_TASK)
+
+ dedupe_task_schedules(django_apps, None)
+ dedupe_task_schedules(django_apps, None)
+
+ remaining = list(Task.objects.filter(task_name=POLAR_REPORT_TASK))
+ assert len(remaining) == 1
+ assert remaining[0].id == task.id
+
+
+def test_dedupe_only_touches_named_periodic_tasks():
+ _make_task("some.other.task")
+ _make_task("some.other.task")
+
+ dedupe_task_schedules(django_apps, None)
+
+ assert Task.objects.filter(task_name="some.other.task").count() == 2