diff --git a/addon_service/celery_stress_test/__init__.py b/addon_service/celery_stress_test/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/addon_service/celery_stress_test/control.py b/addon_service/celery_stress_test/control.py new file mode 100644 index 00000000..cd5f57b8 --- /dev/null +++ b/addon_service/celery_stress_test/control.py @@ -0,0 +1,230 @@ +"""Suite transitions serialize on the suite row, including cancellation and publication.""" + +import time + +from django.db import transaction +from django.db.models import ( + Count, + Q, +) +from django.utils import timezone + +from addon_service.celery_stress_test.models import CeleryTestSuite as Suite +from addon_service.celery_stress_test.models import CeleryTestTask as Task + +from .load import ( + load_progress, + sync_load_progress, +) + + +def scenario_progress(suite): + """Count scenario task states, including tasks still waiting or retrying.""" + fields = { + "total": Count("id"), + "published": Count("id", filter=Q(published_at__isnull=False)), + } + fields.update( + {status: Count("id", filter=Q(status=status)) for status in Task.Status.values} + ) + summary = suite.tasks.aggregate(**fields) + summary["active"] = summary["queued"] + summary["running"] + summary["retrying"] + return summary + + +def sync_progress(suite): + """Refresh progress and the coordinator heartbeat for the suite type.""" + if suite.config.get("suite_type", "load") == "load": + return sync_load_progress(suite) + summary = scenario_progress(suite) + Suite.objects.filter(pk=suite.id, finished_at__isnull=True).update( + results={**suite.results, "progress": summary}, heartbeat_at=timezone.now() + ) + return summary + + +def wait_for_tasks(suite_id, publication_error=None): + """Poll in the coordinator slot until tasks finish or the suite deadline passes.""" + if publication_error is not None: + Suite.objects.filter(pk=suite_id, finished_at__isnull=True).update( + error=str(publication_error)[:4000] + ) + Suite.objects.filter( + pk=suite_id, finished_at__isnull=True, publishing_finished_at__isnull=True + ).update(publishing_finished_at=timezone.now()) + Suite.objects.filter( + pk=suite_id, finished_at__isnull=True, cancel_requested_at__isnull=True + ).update(status=Suite.Status.DRAINING) + suite = Suite.objects.get(pk=suite_id) + while True: + suite.refresh_from_db() + if suite.finished_at: + break + if suite.cancel_requested_at: + suite.tasks.filter( + status__in=[Task.Status.QUEUED, Task.Status.RETRYING] + ).update(status=Task.Status.CANCELLED, finished_at=timezone.now()) + if sync_progress(suite)["active"] == 0: + break + remaining = (suite.deadline_at - timezone.now()).total_seconds() + if remaining <= 0: + error = "Execution deadline exceeded; tasks or callbacks did not finish." + suite.tasks.exclude(status__in=Task.TERMINAL_STATUSES).update( + status=Task.Status.FAILED, finished_at=timezone.now(), error=error + ) + if publication_error is not None: + error = f"Publication failed: {publication_error}; {error}" + raise RuntimeError(error) from publication_error + time.sleep(min(5, remaining)) + if publication_error is not None: + raise publication_error + + +def finalize(suite): + """Set the final verdict once publication and execution end. The caller locks the suite row.""" + if suite.finished_at: + return + if ( + not suite.publishing_finished_at + or suite.tasks.exclude(status__in=Task.TERMINAL_STATUSES).exists() + ): + return + if suite.config.get("suite_type", "load") == "load": + suite.results = { + "load": load_progress(suite.id, len(suite.config.get("workloads", []))) + } + else: + suite.results = {**suite.results, "progress": scenario_progress(suite)} + if suite.cancel_requested_at: + suite.status = Suite.Status.CANCELLED + elif suite.config.get("suite_type", "load") != "load": + from .scenarios import evaluate + + results, passed = evaluate(suite) + suite.results = {**suite.results, **results} + suite.verdict = ( + Suite.Verdict.PASSED if passed and not suite.error else Suite.Verdict.FAILED + ) + suite.status = ( + Suite.Status.COMPLETED + if suite.verdict == Suite.Verdict.PASSED + else Suite.Status.FAILED + ) + elif ( + suite.error + or suite.tasks.filter( + status__in=[Task.Status.FAILED, Task.Status.CANCELLED] + ).exists() + ): + suite.status = Suite.Status.FAILED + else: + suite.status = Suite.Status.COMPLETED + if suite.cancel_requested_at: + suite.verdict = Suite.Verdict.CANCELLED + elif suite.config.get("suite_type", "load") == "load": + suite.verdict = ( + Suite.Verdict.PASSED + if suite.status == Suite.Status.COMPLETED + else Suite.Verdict.FAILED + ) + suite.finished_at = timezone.now() + suite.save(update_fields=["status", "finished_at", "verdict", "results"]) + + +def finish_publishing(suite_id, error=""): + """Record the end of publication and finalize if all tasks are terminal.""" + with transaction.atomic(): + suite = Suite.objects.select_for_update().get(pk=suite_id) + if suite.finished_at: + return + suite.publishing_finished_at = suite.publishing_finished_at or timezone.now() + suite.error = (error or suite.error)[:4000] + suite.status = ( + Suite.Status.CANCELLING + if suite.cancel_requested_at + else Suite.Status.DRAINING + ) + suite.save(update_fields=["publishing_finished_at", "error", "status"]) + finalize(suite) + + +def finish_task(task_id, status, error="", runtime=None, result=None): + """Finish one scenario task and its attempt, without locking/updating its suite.""" + with transaction.atomic(): + task = Task.objects.select_for_update().get(pk=task_id) + suite = task.suite + if suite.finished_at or task.status in Task.TERMINAL_STATUSES: + return + now = timezone.now() + task.status = Task.Status.CANCELLED if suite.cancel_requested_at else status + task.finished_at = now + task.runtime_seconds = runtime + if runtime is None and task.started_at: + task.runtime_seconds = max(0, (now - task.started_at).total_seconds()) + task.total_seconds = max(0, (now - task.submitted_at).total_seconds()) + task.error = error[:4000] + if result is not None: + task.observations["result"] = result + task.save( + update_fields=[ + "status", + "finished_at", + "runtime_seconds", + "total_seconds", + "error", + "observations", + ] + ) + task.attempts.filter(finished_at__isnull=True).update( + finished_at=now, outcome=task.status, error=task.error + ) + + +def cancel_suite(suite_id, user, app): + """Record the cancellation request and try to revoke queued work through Celery.""" + with transaction.atomic(): + suite = Suite.objects.select_for_update().get(pk=suite_id) + if not suite.is_active: + return suite, None + if not suite.cancel_requested_at: + suite.cancel_requested_at = timezone.now() + suite.cancelled_by = user + suite.status = Suite.Status.CANCELLING + # A coordinator not yet started will never claim a cancelled suite. + if suite.started_at is None: + suite.publishing_finished_at = timezone.now() + suite.save( + update_fields=[ + "cancel_requested_at", + "cancelled_by", + "status", + "publishing_finished_at", + ] + ) + suite.tasks.filter( + status__in=[Task.Status.QUEUED, Task.Status.RETRYING] + ).update( + status=Task.Status.CANCELLED, + finished_at=timezone.now(), + ) + finalize(suite) + # Cooperative database checks remain authoritative if broker revocation fails. + try: + app.control.revoke(str(suite.coordinator_task_id), terminate=False) + ids = suite.tasks.filter(status=Task.Status.CANCELLED).values_list( + "id", flat=True + ) + batch = [] + for task_id in ids.iterator(chunk_size=500): + batch.append(str(task_id)) + if len(batch) == 500: + app.control.revoke(batch, terminate=False) + batch = [] + if batch: + app.control.revoke(batch, terminate=False) + except Exception: + return ( + suite, + "Cancellation saved. Broker revocation failed; load payloads expire at their deadline and running work finishes naturally.", + ) + return suite, None diff --git a/addon_service/celery_stress_test/forms.py b/addon_service/celery_stress_test/forms.py new file mode 100644 index 00000000..350c1f22 --- /dev/null +++ b/addon_service/celery_stress_test/forms.py @@ -0,0 +1,191 @@ +from django import forms +from django.conf import settings + +from app.celery import app as celery_app + + +class CeleryStressTestForm(forms.Form): + name = forms.CharField(max_length=100, initial="Celery load test") + drain_timeout = forms.IntegerField( + min_value=10, + max_value=3600, + initial=120, + help_text="Time budgeted for published tasks to finish. The execution deadline is set at submission using the publishing duration, this budget, and a 60-second buffer.", + ) + total_duration = forms.IntegerField( + label="Duration (seconds)", + min_value=1, + max_value=3600, + initial=120, + help_text="How long the coordinator publishes tasks after it starts. Already-published tasks can finish afterward.", + ) + max_total_rate = forms.IntegerField( + label="Maximum total task rate (tasks/second)", + min_value=1, + max_value=1000, + initial=20, + help_text="Combined publishing ceiling across all workloads. Each workload also has its own publishing rate.", + ) + + +def stress_test_queue_choices(): + """Offer only queues that are both configured in Celery and allowed for stress tests.""" + declared_queues = {queue.name for queue in celery_app.conf.task_queues} + return [ + (name, name) + for name in settings.CELERY_STRESS_TEST_QUEUES + if name in declared_queues + ] + + +class WorkloadForm(forms.Form): + """Configure the queue, publishing rate, and synthetic work for one workload.""" + + name = forms.CharField( + max_length=100, + initial="Workload", + ) + mode = forms.ChoiceField( + choices=[ + ("io", "I/O-bound"), + ("cpu", "CPU-bound"), + ("mixed", "Mixed"), + ], + initial="io", + ) + queue = forms.ChoiceField(choices=stress_test_queue_choices) + + rate = forms.IntegerField( + label="Task rate (tasks/second)", + min_value=1, + max_value=1000, + initial=10, + ) + io_seconds = forms.FloatField( + label="I/O duration (seconds)", + min_value=0, + max_value=30, + initial=1, + required=False, + ) + cpu_iterations = forms.IntegerField( + label="CPU iterations", + min_value=1, + max_value=100_000_000, + initial=1_000_000, + required=False, + ) + + def clean(self): + cleaned_data = super().clean() + mode = cleaned_data.get("mode") + + if mode in {"io", "mixed"} and cleaned_data.get("io_seconds") is None: + self.add_error("io_seconds", "Specify the I/O duration.") + + if mode in {"cpu", "mixed"} and cleaned_data.get("cpu_iterations") is None: + self.add_error("cpu_iterations", "Specify the CPU iteration count.") + + return cleaned_data + + +class CeleryScenarioForm(forms.Form): + """Expose the fields and validate the task budget for the selected scenario preset.""" + + name = forms.CharField(max_length=100, initial="Celery correctness test") + queue = forms.ChoiceField( + choices=stress_test_queue_choices, + help_text="Workers consuming this queue execute the scenario tasks and workflow callbacks.", + ) + deadline_seconds = forms.IntegerField( + min_value=10, + max_value=3600, + initial=120, + label="Execution time budget (seconds)", + help_text="Starts when you submit the suite. Includes queue wait, execution, retry delays, and callbacks.", + ) + retry_delay = forms.IntegerField( + min_value=1, + max_value=60, + initial=2, + help_text="Seconds Celery schedules between a retryable failure and the next attempt.", + ) + max_retries = forms.IntegerField( + min_value=2, + max_value=10, + initial=3, + help_text="Number of retries allowed after the initial attempt.", + ) + tasks_per_scenario = forms.IntegerField( + min_value=1, + max_value=100, + initial=1, + help_text="Number of tasks for each of the three retry scenarios (3 * this value total).", + ) + transient_failures = forms.IntegerField( + min_value=1, + max_value=10, + initial=2, + help_text="Failures simulated before a transient task succeeds. Must be within the retry limit.", + ) + workflow_count = forms.IntegerField( + min_value=1, + max_value=100, + initial=1, + help_text="Number of independent chain, group and chord sets.", + ) + chain_length = forms.IntegerField( + min_value=2, + max_value=100, + initial=2, + help_text="Sequential steps per chain. Each step receives the previous result.", + ) + group_size = forms.IntegerField( + min_value=2, + max_value=100, + initial=3, + help_text="Independent tasks in each group.", + ) + chord_size = forms.IntegerField( + min_value=2, + max_value=100, + initial=3, + help_text="Tasks that must finish before the chord runs its final callback.", + ) + + def __init__(self, *args, suite_type, **kwargs): + super().__init__(*args, **kwargs) + excluded = ( + ("workflow_count", "chain_length", "group_size", "chord_size") + if suite_type == "retry" + else ( + "tasks_per_scenario", + "transient_failures", + "retry_delay", + "max_retries", + ) + ) + for name in excluded: + del self.fields[name] + + def clean(self): + data = super().clean() + if "max_retries" in data and data.get("deadline_seconds", 0) <= data[ + "max_retries" + ] * data.get("retry_delay", 0): + self.add_error( + "deadline_seconds", "Allow more time than the configured retry delays." + ) + if data.get("transient_failures", 0) > data.get("max_retries", 0): + self.add_error("transient_failures", "Must not exceed maximum retries.") + tasks_per_workflow = ( + data.get("chain_length", 0) + + data.get("group_size", 0) + + data.get("chord_size", 0) + + 1 + ) + if data.get("workflow_count", 0) * tasks_per_workflow > 500: + self.add_error( + "workflow_count", "Choose sizes producing at most 500 tasks in total." + ) + return data diff --git a/addon_service/celery_stress_test/load.py b/addon_service/celery_stress_test/load.py new file mode 100644 index 00000000..ed46a824 --- /dev/null +++ b/addon_service/celery_stress_test/load.py @@ -0,0 +1,131 @@ +"""Rate-limited publication and periodic progress sync from task result rows.""" + +import time + +from django.db.models import ( + Count, + Q, +) +from django.utils import timezone + +from addon_service.celery_stress_test.models import CeleryTestSuite as Suite +from addon_service.celery_stress_test.models import CeleryTestTask as Task +from app.celery import app + + +def load_progress(suite_id, workload_count): + """Count task outcomes for the suite and each configured workload.""" + fields = { + "total": Count("id"), + "published": Count("id", filter=Q(published_at__isnull=False)), + } + fields.update( + {status: Count("id", filter=Q(status=status)) for status in Task.Status.values} + ) + counts = list( + Task.objects.filter(suite_id=suite_id) + .values("workload_index") + .annotate(**fields) + ) + workloads = [{key: 0 for key in fields} for _ in range(workload_count)] + for row in counts: + if row["workload_index"] is not None and row["workload_index"] < workload_count: + workloads[row["workload_index"]] = {key: row[key] for key in fields} + summary = {key: sum(row[key] for row in workloads) for key in fields} + summary["active"] = summary["queued"] + summary["running"] + summary["retrying"] + summary["workloads"] = workloads + return summary + + +def sync_load_progress(suite): + """Save the latest workload counters and coordinator heartbeat.""" + summary = load_progress(suite.id, len(suite.config["workloads"])) + Suite.objects.filter(pk=suite.id, finished_at__isnull=True).update( + results={"load": summary}, heartbeat_at=timezone.now() + ) + return summary + + +def finish_load_task(task_id, status, error="", **timings): + """Record a load task outcome unless the task is already terminal.""" + Task.objects.filter(pk=task_id).exclude(status__in=Task.TERMINAL_STATUSES).update( + status=status, error=error[:4000], finished_at=timezone.now(), **timings + ) + + +def run_load(suite_id, config): + """Publish paced load tasks, then wait for published work even if a send failed.""" + # Control imports the load progress helpers; defer this import to avoid a cycle. + from .control import wait_for_tasks + + suite = Suite.objects.get(pk=suite_id) + publication_error = None + try: + publish(suite, config) + except Exception as exc: + publication_error = exc + finally: + sync_load_progress(suite) + wait_for_tasks(suite_id, publication_error) + + +def publish(suite, config): + """Publish workloads in rotation using per-workload rates and a shared rate cap.""" + started = time.monotonic() + next_workload_due = [started] * len(config["workloads"]) + next_suite_due = started + last_check = started - 5 # force immediate progress sync on first iteration + rotation_start_index = 0 + while time.monotonic() - started < config["total_duration"]: + now = time.monotonic() + # run periodic progress sync and deadline check at most once every 5 seconds + if now - last_check >= 5: + suite.refresh_from_db() + if suite.finished_at or suite.cancel_requested_at: + return + if timezone.now() >= suite.deadline_at: + raise RuntimeError("Load deadline exceeded while publishing.") + sync_load_progress(suite) + last_check = now + now = time.monotonic() + if now < next_suite_due: + time.sleep(min(next_suite_due - now, 0.01)) + continue + for offset in range(len(next_workload_due)): + index = (rotation_start_index + offset) % len(next_workload_due) + if now < next_workload_due[index]: + continue + workload = config["workloads"][index] + + task = Task.objects.create( + suite_id=suite.id, workload_index=index, queue=workload["queue"] + ) + try: + app.send_task( + "stress_testing.simulated_workload", + task_id=str(task.id), + kwargs={ + "mode": workload["mode"], + "io_seconds": workload.get("io_seconds") or 0, + "cpu_iterations": workload.get("cpu_iterations") or 1000000, + "test_task_id": str(task.id), + "sent_at": task.submitted_at.timestamp(), + "deadline": suite.deadline_at.timestamp(), + }, + queue=workload["queue"], + expires=suite.deadline_at, + retry=False, + ignore_result=True, + ) + except Exception as exc: + finish_load_task( + task.id, Task.Status.FAILED, f"Publication failed: {exc}" + ) + raise + Task.objects.filter(pk=task.id).update(published_at=timezone.now()) + next_workload_due[index] = now + 1 / workload["rate"] + next_suite_due = now + 1 / config["max_total_rate"] + rotation_start_index = (index + 1) % len(next_workload_due) + break + else: + time.sleep(0.001) diff --git a/addon_service/celery_stress_test/metrics.py b/addon_service/celery_stress_test/metrics.py new file mode 100644 index 00000000..126ff1ee --- /dev/null +++ b/addon_service/celery_stress_test/metrics.py @@ -0,0 +1,88 @@ +import math + +from django.db.models import ( + Avg, + Count, + Q, +) +from django.utils import timezone + +from addon_service.celery_stress_test.models import CeleryTestTask as Task + + +def latency(tasks, field): + """Summarize a timing field using successful tasks with recorded samples.""" + samples = tasks.filter(status=Task.Status.SUCCEEDED, **{f"{field}__isnull": False}) + summary = samples.aggregate(count=Count("id"), mean=Avg(field)) + p95 = None + if summary["count"]: + p95 = samples.order_by(field).values_list(field, flat=True)[ + math.ceil(summary["count"] * 0.95) - 1 + ] + return {"mean": summary["mean"], "p95": p95, "samples": summary["count"]} + + +def task_metrics(tasks, publish_seconds, elapsed_seconds): + """Calculate task outcomes and rates over the supplied suite time windows.""" + counts = tasks.aggregate( + **{ + status: Count("id", filter=Q(status=status)) + for status in Task.Status.values + } + ) + published = tasks.filter(published_at__isnull=False).count() + attempted = counts["succeeded"] + counts["failed"] + return { + **counts, + "total": sum(counts.values()), + "published": published, + "publish_rate": published / publish_seconds if publish_seconds > 0 else None, + "throughput": ( + counts["succeeded"] / elapsed_seconds if elapsed_seconds > 0 else None + ), + "failure_percent": counts["failed"] * 100 / attempted if attempted else None, + "wait": latency(tasks, "wait_seconds"), + "runtime": latency(tasks, "runtime_seconds"), + "total_latency": latency(tasks, "total_seconds"), + } + + +def suite_metrics(suite): + """Build suite and per-workload metrics for the admin detail page.""" + now = timezone.now() + publish_seconds = ( + ((suite.publishing_finished_at or now) - suite.started_at).total_seconds() + if suite.started_at + else 0 + ) + elapsed = ( + ((suite.finished_at or now) - suite.started_at).total_seconds() + if suite.started_at + else 0 + ) + workloads = [] + for index, workload in enumerate(suite.config.get("workloads", [])): + workloads.append( + { + "config": workload, + **task_metrics( + suite.tasks.filter(workload_index=index), publish_seconds, elapsed + ), + } + ) + return { + **task_metrics(suite.tasks.all(), publish_seconds, elapsed), + "workloads": workloads, + "publishing_seconds": publish_seconds, + "elapsed_seconds": elapsed, + "requested_rate": sum( + workload["rate"] for workload in suite.config.get("workloads", []) + ), + "effective_rate_cap": min( + suite.config.get("max_total_rate", 0), + sum(workload["rate"] for workload in suite.config.get("workloads", [])), + ), + "workers": suite.tasks.exclude(worker="") + .values_list("worker", flat=True) + .distinct(), + } diff --git a/addon_service/celery_stress_test/models.py b/addon_service/celery_stress_test/models.py new file mode 100644 index 00000000..cbc1b856 --- /dev/null +++ b/addon_service/celery_stress_test/models.py @@ -0,0 +1,146 @@ +import uuid + +from django.conf import settings +from django.db import models +from django.utils import timezone + + +class CeleryTestSuite(models.Model): + """A submitted run with its configuration, absolute deadline, and final verdict.""" + + class Status(models.TextChoices): + QUEUED = "queued", "Queued" + RUNNING = "running", "Publishing" + DRAINING = "draining", "Draining" + CANCELLING = "cancelling", "Cancelling" + COMPLETED = "completed", "Completed" + FAILED = "failed", "Failed" + CANCELLED = "cancelled", "Cancelled" + + class Verdict(models.TextChoices): + PENDING = "pending", "Pending" + PASSED = "passed", "Passed" + FAILED = "failed", "Failed" + CANCELLED = "cancelled", "Cancelled" + + ACTIVE_STATUSES = ( + Status.QUEUED, + Status.RUNNING, + Status.DRAINING, + Status.CANCELLING, + ) + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + created_by = models.ForeignKey( + settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL + ) + name = models.CharField(max_length=100, default="Celery load test") + config = models.JSONField() + verdict = models.CharField( + max_length=16, choices=Verdict.choices, default=Verdict.PENDING + ) + results = models.JSONField(default=dict) + deadline_at = models.DateTimeField(null=True, blank=True) + status = models.CharField( + max_length=16, choices=Status.choices, default=Status.QUEUED, db_index=True + ) + coordinator_task_id = models.UUIDField( + default=uuid.uuid4, unique=True, editable=False + ) + created_at = models.DateTimeField(default=timezone.now) + started_at = models.DateTimeField(null=True, blank=True) + heartbeat_at = models.DateTimeField(null=True, blank=True) + publishing_finished_at = models.DateTimeField(null=True, blank=True) + finished_at = models.DateTimeField(null=True, blank=True) + cancel_requested_at = models.DateTimeField(null=True, blank=True) + cancelled_by = models.ForeignKey( + settings.AUTH_USER_MODEL, + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="+", + ) + error = models.TextField(blank=True) + + class Meta: + ordering = ["-created_at"] + + @property + def is_active(self): + return self.status in self.ACTIVE_STATUSES + + @property + def heartbeat_stale(self): + return ( + self.status == self.Status.RUNNING + and self.heartbeat_at is not None + and (timezone.now() - self.heartbeat_at).total_seconds() > 30 + ) + + +class CeleryTestTask(models.Model): + """One workload execution or scenario step and its recorded outcome.""" + + class Status(models.TextChoices): + QUEUED = "queued", "Queued" + RUNNING = "running", "Running" + RETRYING = "retrying", "Retrying" + SUCCEEDED = "succeeded", "Succeeded" + FAILED = "failed", "Failed" + CANCELLED = "cancelled", "Cancelled" + + TERMINAL_STATUSES = (Status.SUCCEEDED, Status.FAILED, Status.CANCELLED) + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + suite = models.ForeignKey( + CeleryTestSuite, related_name="tasks", on_delete=models.CASCADE + ) + workload_index = models.PositiveSmallIntegerField(null=True, blank=True) + scenario = models.CharField(max_length=100, blank=True) + expected = models.JSONField(default=dict) + observations = models.JSONField(default=dict) + queue = models.CharField(max_length=255) + status = models.CharField( + max_length=16, choices=Status.choices, default=Status.QUEUED + ) + submitted_at = models.DateTimeField(default=timezone.now) + published_at = models.DateTimeField(null=True, blank=True) + started_at = models.DateTimeField(null=True, blank=True) + finished_at = models.DateTimeField(null=True, blank=True) + worker = models.CharField(max_length=255, blank=True) + wait_seconds = models.FloatField(null=True, blank=True) + runtime_seconds = models.FloatField(null=True, blank=True) + total_seconds = models.FloatField(null=True, blank=True) + error = models.TextField(blank=True) + + @property + def scenario_name(self): + return self.scenario.partition(".")[0] + + class Meta: + indexes = [ + models.Index( + fields=["suite", "status"], name="celery_test_suite_status_idx" + ) + ] + + +class CeleryTestTaskAttempt(models.Model): + """One execution attempt for a scenario task, including any scheduled retry.""" + + id = models.AutoField(primary_key=True) + task = models.ForeignKey( + CeleryTestTask, related_name="attempts", on_delete=models.CASCADE + ) + number = models.PositiveSmallIntegerField() + started_at = models.DateTimeField(default=timezone.now) + finished_at = models.DateTimeField(null=True, blank=True) + retry_at = models.DateTimeField(null=True, blank=True) + worker = models.CharField(max_length=255, blank=True) + outcome = models.CharField(max_length=32, blank=True) + error = models.TextField(blank=True) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["task", "number"], name="celery_test_attempt_unique" + ) + ] diff --git a/addon_service/celery_stress_test/presets.py b/addon_service/celery_stress_test/presets.py new file mode 100644 index 00000000..dbd486ee --- /dev/null +++ b/addon_service/celery_stress_test/presets.py @@ -0,0 +1,45 @@ +"""Versioned, server-owned defaults; each run stores its resolved configuration.""" + +from copy import deepcopy + +from django.conf import settings + + +PRESETS = { + "load": {"label": "Custom load test", "version": 1, "defaults": {}}, + "retry": { + "label": "Retry and recovery", + "version": 2, + "defaults": { + "queue": settings.CELERY_STRESS_TEST_DEFAULT_QUEUE, + "tasks_per_scenario": 1, + "transient_failures": 2, + "retry_delay": 2, + "max_retries": 3, + "deadline_seconds": 120, + }, + }, + "workflow": { + "label": "Workflow correctness", + "version": 2, + "defaults": { + "queue": settings.CELERY_STRESS_TEST_DEFAULT_QUEUE, + "workflow_count": 1, + "chain_length": 2, + "group_size": 3, + "chord_size": 3, + "deadline_seconds": 120, + }, + }, +} + + +def resolve(preset, overrides): + """Merge submitted values with preset defaults and record the preset version.""" + definition = PRESETS[preset] + return { + **deepcopy(definition["defaults"]), + **overrides, + "suite_type": preset, + "preset_version": definition["version"], + } diff --git a/addon_service/celery_stress_test/scenarios.py b/addon_service/celery_stress_test/scenarios.py new file mode 100644 index 00000000..4046bf10 --- /dev/null +++ b/addon_service/celery_stress_test/scenarios.py @@ -0,0 +1,287 @@ +"""Bounded synthetic scenarios using real Celery retries and canvas primitives.""" + +from datetime import timedelta + +from celery import ( + chain, + chord, + group, + shared_task, +) +from celery.exceptions import Ignore +from django.db import transaction +from django.db.models import Q +from django.utils import timezone + +from addon_service.celery_stress_test.models import CeleryTestSuite as Suite +from addon_service.celery_stress_test.models import CeleryTestTask as Task +from addon_service.celery_stress_test.models import CeleryTestTaskAttempt as Attempt + +from .control import ( + finish_task, + wait_for_tasks, +) + + +def signature(task): + """Build a Celery signature with the stored task ID and target queue.""" + return scenario_task.s(test_task_id=str(task.id)).set( + task_id=str(task.id), queue=task.queue + ) + + +def publish_scenarios(suite_id, config): + """Store expected outcomes, submit the Celery canvas, and wait for its tasks.""" + with transaction.atomic(): + suite = Suite.objects.select_for_update().get(pk=suite_id) + if suite.cancel_requested_at: + return + suite.deadline_at = suite.deadline_at or timezone.now() + timedelta( + seconds=config["deadline_seconds"] + ) + suite.save(update_fields=["deadline_at"]) + + def create_scenario(name, **expected): + return Task.objects.create( + suite=suite, queue=config["queue"], scenario=name, expected=expected + ) + + if config["suite_type"] == "retry": + retry_limit = config["max_retries"] + failures = config.get("transient_failures", 2) + scenario_tasks = [] + for index in range(config.get("tasks_per_scenario", 1)): + scenario_tasks.extend( + [ + create_scenario( + f"transient.{index}", + failures=failures, + attempts=failures + 1, + status="succeeded", + ), + create_scenario( + f"exhausted.{index}", + failures=retry_limit + 1, + attempts=retry_limit + 1, + status="failed", + ), + create_scenario( + f"non_retryable.{index}", + failures=1, + attempts=1, + status="failed", + ), + ] + ) + canvas = group(signature(task) for task in scenario_tasks) + else: + workflows = [] + for index in range(config.get("workflow_count", 1)): + steps = [ + create_scenario( + f"chain.{index}.{step_index}", + value=step_index + 2, + result=sum(range(2, step_index + 3)), + ) + for step_index in range(config.get("chain_length", 2)) + ] + branches = [ + create_scenario( + f"group.{index}.{step_index}", + value=step_index, + result=step_index, + ) + for step_index in range( + config.get("group_size", config.get("width", 3)) + ) + ] + chord_size = config.get("chord_size", config.get("width", 3)) + headers = [ + create_scenario( + f"chord.{index}.{step_index}", + value=step_index, + result=step_index, + ) + for step_index in range(chord_size) + ] + callback = create_scenario( + f"callback.{index}", result=sum(range(chord_size)) + ) + workflows.extend( + [ + chain(*(signature(task) for task in steps)), + group(signature(task) for task in branches), + chord( + [signature(task) for task in headers], signature(callback) + ), + ] + ) + canvas = group(workflows) + # All control rows are committed before the canvas can be consumed. + # If only part of the canvas is published, the deadline closes out steps that never run. + publication_error = None + try: + canvas.apply_async() + Task.objects.filter(suite_id=suite_id).update(published_at=timezone.now()) + except Exception as exc: + publication_error = exc + wait_for_tasks(suite_id, publication_error) + + +@shared_task(bind=True, name="stress_testing.scenario", ignore_result=False) +def scenario_task(self, previous=None, test_task_id=None): + """Record an attempt and simulate a retry outcome or compute a workflow result.""" + attempt_number = self.request.retries + 1 + with transaction.atomic(): + task = Task.objects.select_for_update().get(pk=test_task_id) + suite = task.suite + if task.scenario_name == "callback": + task.observations["callback_count"] = ( + task.observations.get("callback_count", 0) + 1 + ) + task.save(update_fields=["observations"]) + if ( + suite.cancel_requested_at + or suite.finished_at + or task.status in Task.TERMINAL_STATUSES + ): + return task.observations.get("result") + attempt, created = Attempt.objects.get_or_create( + task=task, + number=attempt_number, + defaults={"worker": self.request.hostname or ""}, + ) + if not created: + raise Ignore() + task.status = Task.Status.RUNNING + task.started_at = task.started_at or timezone.now() + task.worker = self.request.hostname or "" + task.wait_seconds = max( + 0, (task.started_at - task.submitted_at).total_seconds() + ) + task.save(update_fields=["status", "started_at", "worker", "wait_seconds"]) + if ( + suite.config["suite_type"] == "retry" + and attempt_number <= task.expected["failures"] + ): + retry = ( + task.scenario_name != "non_retryable" + and attempt_number <= suite.config["max_retries"] + ) + now = timezone.now() + Attempt.objects.filter(pk=attempt.pk).update( + finished_at=now, + outcome="retry" if retry else "failed", + error="Synthetic failure", + retry_at=( + now + timedelta(seconds=suite.config["retry_delay"]) if retry else None + ), + ) + if retry: + retrying = Task.objects.filter( + pk=task.id, + status=Task.Status.RUNNING, + suite__cancel_requested_at__isnull=True, + suite__finished_at__isnull=True, + ).update(status=Task.Status.RETRYING) + if not retrying: + finish_task(task.id, Task.Status.CANCELLED) + return + raise self.retry( + exc=RuntimeError("Synthetic transient failure"), + countdown=suite.config["retry_delay"], + max_retries=suite.config["max_retries"], + ) + finish_task( + task.id, Task.Status.FAILED, "Synthetic failure: no further retries" + ) + raise RuntimeError("Synthetic failure: no further retries") + value = ( + sum(previous) + if task.scenario_name == "callback" + else (previous or 0) + task.expected.get("value", 0) + ) + finish_task(task.id, Task.Status.SUCCEEDED, result=value) + return value + + +def evaluate(suite): + """Compare recorded outcomes, retry timing, and workflow results with expectations.""" + checks = [] + for task in suite.tasks.prefetch_related("attempts").order_by("scenario"): + attempts = list(task.attempts.order_by("number")) + expected = task.expected + passed = task.status == expected.get("status", "succeeded") + if "attempts" in expected: + passed = passed and len(attempts) == expected["attempts"] + if "result" in expected: + passed = passed and task.observations.get("result") == expected["result"] + if task.scenario_name == "callback": + passed = passed and task.observations.get("callback_count") == 1 + observed_retry_delays = [ + (next_attempt.started_at - prior_attempt.finished_at).total_seconds() + for prior_attempt, next_attempt in zip(attempts, attempts[1:]) + if prior_attempt.finished_at + ] + scheduled_retry_delay = suite.config.get("retry_delay", 0) + passed = passed and all( + delay >= scheduled_retry_delay - 0.25 for delay in observed_retry_delays + ) + checks.append( + { + "scenario": task.scenario, + "passed": passed, + "expected": expected, + "actual_status": task.status, + "observations": task.observations, + "attempts": len(attempts), + "observed_retry_delays": observed_retry_delays, + "scheduled_retry_delay": scheduled_retry_delay, + "duration_seconds": task.total_seconds, + "recovery_seconds": ( + task.total_seconds + if task.scenario_name == "transient" and task.status == "succeeded" + else None + ), + "exhausted_retries": task.scenario_name == "exhausted" + and task.status == "failed" + and len(attempts) == expected.get("attempts"), + } + ) + duration = ( + (timezone.now() - suite.started_at).total_seconds() + if suite.started_at + else None + ) + return {"checks": checks, "duration_seconds": duration}, bool(checks) and all( + check["passed"] for check in checks + ) + + +@shared_task(name="stress_testing.sync_overdue_suites") +def sync_overdue_suites(): + """Finalize overdue active suites and fail their remaining nonterminal tasks.""" + from .control import finalize + + now = timezone.now() + # Older suites without a stored deadline use a two-hour cutoff from submission. + overdue = Suite.objects.filter(status__in=Suite.ACTIVE_STATUSES).filter( + Q(deadline_at__lte=now) + | Q(deadline_at__isnull=True, created_at__lte=now - timedelta(hours=2)), + ) + for suite_id in overdue.values_list("id", flat=True): + with transaction.atomic(): + suite = Suite.objects.select_for_update().get(pk=suite_id) + # The coordinator may have finalized the suite since the overdue query. + if not suite.is_active: + continue + suite.error = "Execution deadline exceeded; required tasks or callbacks did not finish." + # An interrupted coordinator may have left publication open. + suite.publishing_finished_at = ( + suite.publishing_finished_at or timezone.now() + ) + suite.tasks.exclude(status__in=Task.TERMINAL_STATUSES).update( + status=Task.Status.FAILED, finished_at=timezone.now(), error=suite.error + ) + suite.save(update_fields=["error", "publishing_finished_at"]) + finalize(suite) diff --git a/addon_service/celery_stress_test/tasks.py b/addon_service/celery_stress_test/tasks.py new file mode 100644 index 00000000..239c3ece --- /dev/null +++ b/addon_service/celery_stress_test/tasks.py @@ -0,0 +1,202 @@ +import time +from datetime import timedelta + +from celery import shared_task +from celery.signals import ( + task_failure, + task_revoked, +) +from django.core.management import call_command +from django.db import transaction +from django.utils import timezone + +from addon_service.celery_stress_test.models import CeleryTestSuite as Suite +from addon_service.celery_stress_test.models import CeleryTestTask as Task +from app.celery import app as celery_app + +from .control import ( + finish_publishing, + finish_task, +) +from .load import ( + finish_load_task, + run_load, +) +from .scenarios import ( # Registers scenario tasks for signal handlers. + publish_scenarios, +) + + +@shared_task(name="stress_testing.start_celery_stress_test") +def start_celery_stress_test(suite_id): + """Claim a queued suite, publish its tasks, and wait for them in this worker slot.""" + with transaction.atomic(): + suite = Suite.objects.select_for_update().get(pk=suite_id) + if suite.status != Suite.Status.QUEUED or suite.cancel_requested_at: + return + suite.status = Suite.Status.RUNNING + suite.started_at = suite.heartbeat_at = timezone.now() + suite.save(update_fields=["status", "started_at", "heartbeat_at"]) + config = suite.config + if suite.deadline_at is None: + suite.deadline_at = suite.created_at + timedelta( + seconds=config.get( + "deadline_seconds", + config.get("total_duration", 0) + + config.get("drain_timeout", 120) + + 60, + ), + ) + suite.save(update_fields=["deadline_at"]) + + error = "" + try: + if config.get("suite_type", "load") == "load": + run_load(suite_id, config) + else: + publish_scenarios(suite_id, config) + except Exception as exc: + error = str(exc) + raise + finally: + finish_publishing(suite_id, error) + + +@shared_task( + bind=True, + name="stress_testing.simulated_workload", + ignore_result=True, + store_errors_even_if_ignored=False, +) +def simulated_workload( + self, + mode="io", + io_seconds=1.0, + cpu_iterations=1_000_000, + test_task_id=None, + sent_at=None, + deadline=None, +): + """Save task timings/outcome directly; the coordinator synchronizes suite progress.""" + received = timezone.now() + started = time.monotonic() + if deadline is not None and received.timestamp() >= deadline: + if test_task_id: + finish_load_task( + test_task_id, Task.Status.FAILED, "Task execution deadline exceeded." + ) + return + if test_task_id: + claimed = Task.objects.filter( + pk=test_task_id, + status=Task.Status.QUEUED, + suite__finished_at__isnull=True, + suite__cancel_requested_at__isnull=True, + ).update( + status=Task.Status.RUNNING, + started_at=received, + worker=self.request.hostname or "", + wait_seconds=max( + 0, received.timestamp() - (sent_at or received.timestamp()) + ), + ) + if not claimed: + Task.objects.filter(pk=test_task_id, status=Task.Status.QUEUED).update( + status=Task.Status.CANCELLED, finished_at=timezone.now() + ) + return + status, error = Task.Status.SUCCEEDED, "" + try: + if mode not in {"io", "cpu", "mixed"}: + raise ValueError(f"Unsupported workload mode: {mode}") + if not 0 <= io_seconds <= 30 or not 1 <= cpu_iterations <= 100_000_000: + raise ValueError("Workload arguments exceed supported bounds.") + if mode in {"io", "mixed"}: + time.sleep(io_seconds) + if mode in {"cpu", "mixed"}: + sum(i * i for i in range(cpu_iterations)) + except Exception as exc: + status, error = Task.Status.FAILED, str(exc) + raise + finally: + if test_task_id: + finish_load_task( + test_task_id, + status, + error, + runtime_seconds=time.monotonic() - started, + total_seconds=max( + 0, timezone.now().timestamp() - (sent_at or received.timestamp()) + ), + ) + + +def record_test_failure(sender=None, task_id=None, exception=None, **kwargs): + """Persist Celery failures that may bypass normal task cleanup.""" + # Covers failures reported by the worker parent, including hard timeouts and + # lost children, where the task's finally block cannot run. + if sender and sender.name == "stress_testing.simulated_workload": + finish_load_task(task_id, Task.Status.FAILED, str(exception)) + elif sender and sender.name == "stress_testing.scenario": + if Task.objects.filter(pk=task_id).exists(): + finish_task(task_id, Task.Status.FAILED, str(exception)) + elif sender and sender.name == "stress_testing.start_celery_stress_test": + suite = Suite.objects.filter(coordinator_task_id=task_id).first() + if suite: + finish_publishing(suite.id, str(exception)) + + +def record_test_revocation(sender=None, request=None, **kwargs): + """Record revocations of scenario tasks and suite coordinators.""" + if request is None: + return + # Parent-process revocation may supply a Context with task, not name. + task_name = ( + getattr(sender, "name", None) + or getattr(request, "task", None) + or getattr(request, "name", None) + ) + if ( + task_name == "stress_testing.scenario" + and Task.objects.filter(pk=request.id).exists() + ): + finish_task(request.id, Task.Status.CANCELLED, "Task revoked.") + elif task_name == "stress_testing.start_celery_stress_test": + suite = Suite.objects.filter(coordinator_task_id=request.id).first() + if suite: + finish_publishing( + suite.id, "" if suite.cancel_requested_at else "Coordinator revoked." + ) + + +@celery_app.on_after_finalize.connect +def register_test_signal_handlers(sender, **kwargs): + """Attach failure and revocation handlers to the registered task instances.""" + # Resolve shared tasks through the finalized app's registry, not their proxies. + for task_name in ( + "stress_testing.simulated_workload", + "stress_testing.scenario", + "stress_testing.start_celery_stress_test", + ): + task = sender.tasks[task_name] + task_failure.connect( + record_test_failure, + sender=task, + dispatch_uid=f"{task_name}.record_test_failure", + ) + task_revoked.connect( + record_test_revocation, + sender=task, + dispatch_uid=f"{task_name}.record_test_revocation", + ) + + +# Admin task discovery can import this module after the app has been finalized. +if celery_app.finalized: + register_test_signal_handlers(sender=celery_app) + + +@shared_task(name="stress_testing.cleanup_history") +def cleanup_history(): + """Apply the configured retention period to terminal suites.""" + call_command("cleanup_celery_tests") diff --git a/addon_service/celery_stress_test/views.py b/addon_service/celery_stress_test/views.py new file mode 100644 index 00000000..6b822e47 --- /dev/null +++ b/addon_service/celery_stress_test/views.py @@ -0,0 +1,261 @@ +from datetime import timedelta + +from dj_celery_panel.conf import panel_config +from django.conf import settings +from django.contrib import messages +from django.core.paginator import Paginator +from django.db import transaction +from django.db.models import ( + Count, + Q, +) +from django.forms import formset_factory +from django.http import HttpResponseBadRequest +from django.shortcuts import ( + get_object_or_404, + redirect, + render, +) +from django.utils import timezone +from django.views.decorators.http import require_http_methods + +from addon_service.celery_stress_test.control import ( + cancel_suite, + finish_publishing, +) +from addon_service.celery_stress_test.forms import ( + CeleryScenarioForm, + CeleryStressTestForm, + WorkloadForm, +) +from addon_service.celery_stress_test.metrics import suite_metrics +from addon_service.celery_stress_test.models import ( + CeleryTestSuite, + CeleryTestTask, +) +from addon_service.celery_stress_test.presets import ( + PRESETS, + resolve, +) +from addon_service.celery_stress_test.scenarios import sync_overdue_suites +from addon_service.celery_stress_test.tasks import start_celery_stress_test +from app.celery import app as celery_app + + +WorkloadFormSet = formset_factory( + WorkloadForm, + extra=1, + can_delete=True, + max_num=10, + min_num=1, + validate_max=True, +) + + +@transaction.non_atomic_requests +@panel_config.permission_required("celery_stress_test") +@require_http_methods(["GET", "POST"]) +def celery_stress_test_view(request): + """ + Configure and start a Celery stress test. + """ + context = panel_config.get_context( + request, + current_tab="celery_stress_test", + ) + preset = request.POST.get("preset", request.GET.get("preset", "load")) + if preset not in PRESETS: + return HttpResponseBadRequest("Unknown suite preset.") + if preset != "load": + form = CeleryScenarioForm( + request.POST if request.method == "POST" else None, + suite_type=preset, + initial=PRESETS[preset]["defaults"], + ) + if request.method == "POST" and form.is_valid(): + config = resolve(preset, form.cleaned_data) + if preset == "workflow": + try: + celery_app.backend.ensure_chords_allowed() + except (NotImplementedError, AttributeError) as exc: + form.add_error( + None, f"This result backend does not support chords: {exc}" + ) + if not form.errors: + suite = CeleryTestSuite.objects.create( + name=config["name"], + config=config, + created_by=request.user, + deadline_at=timezone.now() + + timedelta(seconds=config["deadline_seconds"]), + ) + try: + start_celery_stress_test.apply_async( + args=[str(suite.id)], + task_id=str(suite.coordinator_task_id), + retry=False, + ) + except Exception as exc: + finish_publishing( + suite.id, f"Coordinator publication failed: {exc}" + ) + messages.error(request, "Failed to submit the suite.") + return redirect("celery_stress_suite_detail", suite_id=suite.id) + context.update({"form": form, "presets": PRESETS, "selected_preset": preset}) + return render(request, "admin/dj_celery_panel/scenario_testing.html", context) + context.update({"presets": PRESETS, "selected_preset": preset}) + + if request.method == "POST": + form = CeleryStressTestForm(request.POST) + workload_formset = WorkloadFormSet(request.POST) + + if form.is_valid() and workload_formset.is_valid(): + config = { + **form.cleaned_data, + "suite_type": "load", + "preset_version": 1, + "workloads": [ + workload_form.cleaned_data + for workload_form in workload_formset + if workload_form.cleaned_data + and not workload_form.cleaned_data.get("DELETE", False) + ], + } + + if not config["workloads"]: + messages.error( + request, + "Please configure at least one workload.", + ) + elif ( + config["total_duration"] + * min( + config["max_total_rate"], + sum(workload["rate"] for workload in config["workloads"]), + ) + > settings.CELERY_STRESS_TEST_MAX_TASKS + ): + form.add_error( + None, + f"This run exceeds the {settings.CELERY_STRESS_TEST_MAX_TASKS:,} task limit.", + ) + else: + suite = CeleryTestSuite.objects.create( + name=config["name"], + config=config, + created_by=request.user, + deadline_at=timezone.now() + + timedelta( + seconds=config["total_duration"] + config["drain_timeout"] + 60 + ), + ) + try: + start_celery_stress_test.apply_async( + args=[str(suite.id)], + task_id=str(suite.coordinator_task_id), + retry=False, + ) + except Exception as error: + finish_publishing( + suite.id, f"Coordinator publication failed: {error}" + ) + messages.error( + request, + "Failed to start the stress test. Please try again.", + ) + else: + messages.success( + request, + f"Stress test submitted successfully: {suite.name}", + ) + return redirect("celery_stress_suite_detail", suite_id=suite.id) + else: + form = CeleryStressTestForm() + workload_formset = WorkloadFormSet() + + context.update( + { + "form": form, + "workload_formset": workload_formset, + } + ) + + return render( + request, + "admin/dj_celery_panel/celery_stress_testing.html", + context, + ) + + +@panel_config.permission_required("celery_stress_test") +@require_http_methods(["GET"]) +def celery_stress_suites(request): + """List active suites and paginate terminal runs.""" + context = panel_config.get_context(request, current_tab="celery_stress_test") + suites = CeleryTestSuite.objects.annotate( + task_count=Count("tasks"), + succeeded_count=Count( + "tasks", filter=Q(tasks__status=CeleryTestTask.Status.SUCCEEDED) + ), + failed_count=Count( + "tasks", filter=Q(tasks__status=CeleryTestTask.Status.FAILED) + ), + ).order_by("-created_at", "-id") + context.update( + { + "active_suites": suites.filter(status__in=CeleryTestSuite.ACTIVE_STATUSES), + "history": Paginator( + suites.exclude(status__in=CeleryTestSuite.ACTIVE_STATUSES), 25 + ).get_page(request.GET.get("page")), + } + ) + return render(request, "admin/dj_celery_panel/stress_suites.html", context) + + +@panel_config.permission_required("celery_stress_test") +@require_http_methods(["GET"]) +def celery_stress_suite_detail(request, suite_id): + """Show a saved suite configuration, metrics, and individual task records.""" + suite = get_object_or_404(CeleryTestSuite, pk=suite_id) + context = panel_config.get_context(request, current_tab="celery_stress_test") + context.update( + { + "suite": suite, + "metrics": suite_metrics(suite), + "task_page": Paginator( + suite.tasks.order_by("-submitted_at", "-id"), 50 + ).get_page(request.GET.get("page")), + } + ) + return render(request, "admin/dj_celery_panel/stress_suite_detail.html", context) + + +@transaction.non_atomic_requests +@panel_config.permission_required("celery_stress_test") +@require_http_methods(["POST"]) +def celery_stress_suite_cancel(request, suite_id): + """Request cancellation and report whether broker revocation succeeded.""" + get_object_or_404(CeleryTestSuite, pk=suite_id) + suite, warning = cancel_suite(suite_id, request.user, celery_app) + if warning: + messages.warning(request, warning) + elif suite.cancel_requested_at: + messages.success( + request, + "Cancellation requested. Publishing stops; queued load tasks are revoked where possible and expire at the deadline. Running load tasks finish naturally.", + ) + else: + messages.info(request, "This suite has already finished.") + return redirect("celery_stress_suite_detail", suite_id=suite.id) + + +@transaction.non_atomic_requests +@panel_config.permission_required("celery_stress_test") +@require_http_methods(["POST"]) +def celery_stress_suites_sync_overdue(request): + """Close overdue active suites from the admin dashboard.""" + sync_overdue_suites.run() + messages.success( + request, "Checked for overdue suites and closed any that were still active." + ) + return redirect("celery_stress_test") diff --git a/addon_service/management/commands/cleanup_celery_tests.py b/addon_service/management/commands/cleanup_celery_tests.py new file mode 100644 index 00000000..618f8e05 --- /dev/null +++ b/addon_service/management/commands/cleanup_celery_tests.py @@ -0,0 +1,52 @@ +"""Explicit, bounded cleanup of terminal synthetic-test history.""" + +from datetime import timedelta + +from django.conf import settings +from django.core.management.base import ( + BaseCommand, + CommandError, +) +from django.db import transaction +from django.utils import timezone + +from addon_service.celery_stress_test.models import CeleryTestSuite as Suite +from addon_service.celery_stress_test.models import CeleryTestTask as Task + + +class Command(BaseCommand): + help = "Delete terminal Celery test suites older than the retention period." + + def add_arguments(self, parser): + parser.add_argument( + "--days", type=int, default=settings.CELERY_STRESS_TEST_RETENTION_DAYS + ) + parser.add_argument("--limit", type=int, default=100) + + def handle(self, *args, **options): + if options["days"] < 1 or options["limit"] < 1: + raise CommandError("Days and limit must be positive.") + cutoff = timezone.now() - timedelta(days=options["days"]) + ids = list( + Suite.objects.exclude(status__in=Suite.ACTIVE_STATUSES) + .filter(finished_at__lt=cutoff) + .values_list("id", flat=True)[: options["limit"]] + ) + deleted = 0 + for suite_id in ids: + while True: + with transaction.atomic(): + suite = ( + Suite.objects.select_for_update() + .filter(pk=suite_id, finished_at__lt=cutoff) + .first() + ) + if not suite or suite.is_active: + break + batch = list(suite.tasks.values_list("id", flat=True)[:200]) + if not batch: + suite.delete() + deleted += 1 + break + Task.objects.filter(id__in=batch).delete() + self.stdout.write(f"Deleted {deleted} expired Celery test suites.") diff --git a/addon_service/migrations/0018_celery_stress_test.py b/addon_service/migrations/0018_celery_stress_test.py new file mode 100644 index 00000000..75edd02f --- /dev/null +++ b/addon_service/migrations/0018_celery_stress_test.py @@ -0,0 +1,193 @@ +# Generated by Django 4.2.26 on 2026-11-23 12:26 + +import uuid + +import django.db.models.deletion +import django.utils.timezone +from django.conf import settings +from django.db import ( + migrations, + models, +) + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ("addon_service", "0017_externalredirectservice"), + ] + + operations = [ + migrations.CreateModel( + name="CeleryTestSuite", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ("name", models.CharField(default="Celery load test", max_length=100)), + ("config", models.JSONField()), + ( + "verdict", + models.CharField( + choices=[ + ("pending", "Pending"), + ("passed", "Passed"), + ("failed", "Failed"), + ("cancelled", "Cancelled"), + ], + default="pending", + max_length=16, + ), + ), + ("results", models.JSONField(default=dict)), + ("deadline_at", models.DateTimeField(blank=True, null=True)), + ( + "status", + models.CharField( + choices=[ + ("queued", "Queued"), + ("running", "Publishing"), + ("draining", "Draining"), + ("cancelling", "Cancelling"), + ("completed", "Completed"), + ("failed", "Failed"), + ("cancelled", "Cancelled"), + ], + db_index=True, + default="queued", + max_length=16, + ), + ), + ( + "coordinator_task_id", + models.UUIDField(default=uuid.uuid4, editable=False, unique=True), + ), + ("created_at", models.DateTimeField(default=django.utils.timezone.now)), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("heartbeat_at", models.DateTimeField(blank=True, null=True)), + ("publishing_finished_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("cancel_requested_at", models.DateTimeField(blank=True, null=True)), + ("error", models.TextField(blank=True)), + ( + "cancelled_by", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="+", + to=settings.AUTH_USER_MODEL, + ), + ), + ( + "created_by", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "ordering": ["-created_at"], + }, + ), + migrations.CreateModel( + name="CeleryTestTask", + fields=[ + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ( + "workload_index", + models.PositiveSmallIntegerField(blank=True, null=True), + ), + ("scenario", models.CharField(blank=True, max_length=100)), + ("expected", models.JSONField(default=dict)), + ("observations", models.JSONField(default=dict)), + ("queue", models.CharField(max_length=255)), + ( + "status", + models.CharField( + choices=[ + ("queued", "Queued"), + ("running", "Running"), + ("retrying", "Retrying"), + ("succeeded", "Succeeded"), + ("failed", "Failed"), + ("cancelled", "Cancelled"), + ], + default="queued", + max_length=16, + ), + ), + ( + "submitted_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ("published_at", models.DateTimeField(blank=True, null=True)), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("worker", models.CharField(blank=True, max_length=255)), + ("wait_seconds", models.FloatField(blank=True, null=True)), + ("runtime_seconds", models.FloatField(blank=True, null=True)), + ("total_seconds", models.FloatField(blank=True, null=True)), + ("error", models.TextField(blank=True)), + ( + "suite", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="tasks", + to="addon_service.celerytestsuite", + ), + ), + ], + ), + migrations.CreateModel( + name="CeleryTestTaskAttempt", + fields=[ + ("id", models.AutoField(primary_key=True, serialize=False)), + ("number", models.PositiveSmallIntegerField()), + ("started_at", models.DateTimeField(default=django.utils.timezone.now)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("retry_at", models.DateTimeField(blank=True, null=True)), + ("worker", models.CharField(blank=True, max_length=255)), + ("outcome", models.CharField(blank=True, max_length=32)), + ("error", models.TextField(blank=True)), + ( + "task", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="attempts", + to="addon_service.celerytesttask", + ), + ), + ], + ), + migrations.AddConstraint( + model_name="celerytesttaskattempt", + constraint=models.UniqueConstraint( + fields=("task", "number"), name="celery_test_attempt_unique" + ), + ), + migrations.AddIndex( + model_name="celerytesttask", + index=models.Index( + fields=["suite", "status"], name="celery_test_suite_status_idx" + ), + ), + ] diff --git a/addon_service/models.py b/addon_service/models.py index f381f961..5701f187 100644 --- a/addon_service/models.py +++ b/addon_service/models.py @@ -7,6 +7,11 @@ from addon_service.authorized_account.computing.models import AuthorizedComputingAccount from addon_service.authorized_account.link.models import AuthorizedLinkAccount from addon_service.authorized_account.storage.models import AuthorizedStorageAccount +from addon_service.celery_stress_test.models import ( + CeleryTestSuite, + CeleryTestTask, + CeleryTestTaskAttempt, +) from addon_service.configured_addon.citation.models import ConfiguredCitationAddon from addon_service.configured_addon.computing.models import ConfiguredComputingAddon from addon_service.configured_addon.link.models import ConfiguredLinkAddon @@ -27,6 +32,9 @@ __all__ = ( + "CeleryTestSuite", + "CeleryTestTask", + "CeleryTestTaskAttempt", "AddonImpModel", "AddonOperationInvocation", "AddonOperationModel", diff --git a/addon_service/templates/admin/dj_celery_panel/base.html b/addon_service/templates/admin/dj_celery_panel/base.html new file mode 100644 index 00000000..fd19df17 --- /dev/null +++ b/addon_service/templates/admin/dj_celery_panel/base.html @@ -0,0 +1,14 @@ +{% extends "admin/dj_celery_panel/base.html" %} +{% load i18n %} + +{% block panel_content %} + +{% block panel_page_content %}{% endblock %} +{% endblock %} diff --git a/addon_service/templates/admin/dj_celery_panel/celery_stress_testing.html b/addon_service/templates/admin/dj_celery_panel/celery_stress_testing.html new file mode 100644 index 00000000..b8086878 --- /dev/null +++ b/addon_service/templates/admin/dj_celery_panel/celery_stress_testing.html @@ -0,0 +1,500 @@ +{% extends "admin/dj_celery_panel/base.html" %} +{% load i18n static dcr_icons %} + +{% block panel_page_content %} + {% include "admin/dj_celery_panel/suite_presets.html" %} +
+ {% trans "Publish synthetic tasks at a controlled rate to measure throughput, latency, and failures on selected Celery queues." %} +
+{% trans "Check that transient failures recover, persistent failures exhaust their retries, and non-retryable failures stop after one attempt. The suite compares the recorded outcomes and retry timing with the expected behavior." %}
+ {% else %} +{% trans "Check that chain steps pass results in order, group tasks finish independently, and each chord runs its callback once with the header results. This preset requires a result backend that supports chords." %}
+ {% endif %} + +{% endblock %} diff --git a/addon_service/templates/admin/dj_celery_panel/stress_suite_detail.html b/addon_service/templates/admin/dj_celery_panel/stress_suite_detail.html new file mode 100644 index 00000000..3d4bb723 --- /dev/null +++ b/addon_service/templates/admin/dj_celery_panel/stress_suite_detail.html @@ -0,0 +1,219 @@ +{% extends "admin/dj_celery_panel/base.html" %} +{% load i18n %} + +{% block panel_page_content %} + +Suite: {{ suite.config.suite_type|default:"load" }} · Verdict: {{ suite.verdict }}
+ {% if suite.results.checks %} +Suite duration: {{ suite.results.duration_seconds|floatformat:2 }} s
+ {% for check in suite.results.checks %} +Expected: {{ check.expected }} · Actual: {{ check.actual_status }} · Observations: {{ check.observations }}
+Recovery: {{ check.recovery_seconds|default_if_none:"—" }} s · Retry exhaustion observed: {{ check.exhausted_retries|yesno:"Yes,No" }}
+Attempts: {{ check.attempts }} · Scheduled retry delay: {{ check.scheduled_retry_delay }} s · Observed delays: {{ check.observed_retry_delays }} · Duration: {{ check.duration_seconds }} s
+ {% endfor %} +Attempt {{ attempt.number }} · {{ attempt.outcome }} · {{ attempt.started_at }} → {{ attempt.finished_at }} · Retry at {{ attempt.retry_at|default:"—" }} · {{ attempt.error }}
+ {% endfor %} + {% endfor %} +{{ suite.id }} · {{ suite.get_status_display }}
+ {% if suite.is_active %} + +{% trans "Refresh to update. Draining means publication has ended and the coordinator is waiting for queued, running, or retrying tasks to finish." %}
+ {% endif %} + {% if suite.heartbeat_stale %} +{% trans "The coordinator heartbeat is overdue. The worker may be unavailable; these results may be incomplete." %}
+ {% endif %} + {% if suite.error %} +{{ suite.error }}
+ {% endif %} +{% trans "Submitted" %}: {{ metrics.total }} · {% trans "Published" %}: {{ metrics.published }} · {% trans "Queued" %}: {{ metrics.queued }} · {% trans "Running" %}: {{ metrics.running|default_if_none:"—" }} · {% trans "Retrying" %}: {{ metrics.retrying }} · {% trans "Succeeded" %}: {{ metrics.succeeded }} · {% trans "Failed" %}: {{ metrics.failed }} · {% trans "Cancelled" %}: {{ metrics.cancelled|default_if_none:"—" }}
+{% trans "Failure rate among succeeded and failed tasks" %}: {{ metrics.failure_percent|floatformat:2|default:"—" }}%
+| {% trans "Metric" %} | +{% trans "Mean (s)" %} | +{% trans "P95 (s)" %} | +{% trans "Samples" %} | +
|---|---|---|---|
| {% trans "Submission to start" %} | +{{ metrics.wait.mean|floatformat:3|default:"—" }} | +{{ metrics.wait.p95|floatformat:3|default:"—" }} | +{{ metrics.wait.samples }} | +
| {% trans "Execution" %} | +{{ metrics.runtime.mean|floatformat:3|default:"—" }} | +{{ metrics.runtime.p95|floatformat:3|default:"—" }} | +{{ metrics.runtime.samples }} | +
| {% trans "Submission to finish" %} | +{{ metrics.total_latency.mean|floatformat:3|default:"—" }} | +{{ metrics.total_latency.p95|floatformat:3|default:"—" }} | +{{ metrics.total_latency.samples }} | +
{% trans "P95 is the value at or below which 95% of successful samples fall. Cancelled and failed tasks are excluded from latency summaries. Active runs have partial results." %}
+{% trans "Publishing rate uses confirmed send calls divided by publishing time. Successful throughput uses the full elapsed suite time, including draining. Submission-to-start includes broker submission and scheduling; it is not pure broker wait. Cross-worker timings require synchronized clocks. Task result writes and progress aggregation add database overhead to this test." %}
+| {% trans "Workload / mode / queue" %} | +{% trans "I/O (s) / CPU iterations" %} | +{% trans "Requested / actual rate" %} | +{% trans "Queued / running" %} | +{% trans "Succeeded / failed / cancelled" %} | +{% trans "Wait P95 (s)" %} | +{% trans "Execution P95 (s)" %} | +
|---|---|---|---|---|---|---|
| {{ workload.config.name }} / {{ workload.config.mode }} / {{ workload.config.queue }} | +{{ workload.config.io_seconds|default_if_none:"—" }} / {{ workload.config.cpu_iterations|default_if_none:"—" }} | +{{ workload.config.rate }} / {{ workload.publish_rate|floatformat:2|default:"—" }} | +{{ workload.queued }} / {{ workload.running|default_if_none:"—" }} | +{{ workload.succeeded }} / {{ workload.failed }} / {{ workload.cancelled|default_if_none:"—" }} | +{{ workload.wait.p95|floatformat:3|default:"—" }} | +{{ workload.runtime.p95|floatformat:3|default:"—" }} | +
| {% trans "Task ID" %} | +{% trans "Status" %} | +{% trans "Queue / worker" %} | +{% trans "Submitted / finished" %} | +{% trans "Wait / execution (s)" %} | +{% trans "Error" %} | +
|---|---|---|---|---|---|
| {{ task.id }} | +{{ task.get_status_display }} | +{{ task.queue }} / {{ task.worker|default:"—" }} | +{{ task.submitted_at }} / {{ task.finished_at|default:"—" }} | +{{ task.wait_seconds|floatformat:3|default:"—" }} / {{ task.runtime_seconds|floatformat:3|default:"—" }} | +{{ task.error|default:"—" }} | +
| {% trans "No tasks submitted yet." %} | +|||||
| {% trans "Suite" %} | {% trans "Status" %} | {% trans "Started by" %} | {% trans "Created" %} | {% trans "Tasks" %} | {% trans "Succeeded" %} | {% trans "Failed" %} | {% trans "Actions" %} | |||
|---|---|---|---|---|---|---|---|---|---|---|
| {{ suite.name }} | +{{ suite.get_status_display }} · {{ suite.config.suite_type|default:"load" }} · {{ suite.verdict }}{% if suite.heartbeat_stale %} — {% trans "Coordinator heartbeat overdue" %}{% endif %} | +{{ suite.created_by|default:"—" }} | {{ suite.created_at }} | + {% if suite.results.load %} +{{ suite.results.load.published }} | +{{ suite.results.load.succeeded }} | +{{ suite.results.load.failed }} | + {% else %} +{{ suite.task_count }} | {{ suite.succeeded_count }} | {{ suite.failed_count }} | + {% endif %} +{% if suite.is_active %}{% endif %} | +
| {% trans "No suites." %} | ||||||||||
{% trans "Run custom load, retry and recovery, or workflow correctness suites. Open a run to inspect its configuration and results." %}
+ {% trans "New test suite" %} + +{% trans "Use this action after a worker restart or crash leaves a run active past its execution deadline. It marks remaining tasks as failed and closes the run in the database." %}
+{% trans "Refresh to update suite status. The coordinator uses one worker slot while publishing and waiting for tasks. Cancelling stops further publication and requests revocation of queued work. Running load tasks can finish naturally." %}
+{% endblock %} diff --git a/addon_service/templates/admin/dj_celery_panel/suite_presets.html b/addon_service/templates/admin/dj_celery_panel/suite_presets.html new file mode 100644 index 00000000..d22d02e8 --- /dev/null +++ b/addon_service/templates/admin/dj_celery_panel/suite_presets.html @@ -0,0 +1,5 @@ + diff --git a/app/celery/celery.py b/app/celery/celery.py index 8cf544a8..8c135b5a 100644 --- a/app/celery/celery.py +++ b/app/celery/celery.py @@ -59,11 +59,17 @@ def queue_name(self) -> str: "addon_service.management.commands.refresh_addon_tokens.*": { "queue": gv_chill_queue }, + "stress_testing.cleanup_history": {"queue": gv_chill_queue}, + "stress_testing.sync_overdue_suites": {"queue": gv_chill_queue}, + "stress_testing.scenario": {"queue": gv_chill_queue}, + "stress_testing.simulated_workload": {"queue": gv_chill_queue}, + "stress_testing.start_celery_stress_test": {"queue": gv_chill_queue}, "osf.*": {"queue": osf_high_queue}, "website.*": {"queue": osf_high_queue}, }, include=[ "addon_service.tasks", + "addon_service.celery_stress_test.tasks", "addon_service.management.commands.refresh_addon_tokens", ], ) diff --git a/app/settings.py b/app/settings.py index 6fd7283a..1cdee8d8 100644 --- a/app/settings.py +++ b/app/settings.py @@ -115,6 +115,7 @@ "rest_framework_json_api", "addon_service", "django_celery_beat", + "django_celery_results", "dj_control_room_base", "dj_celery_panel", "drf_spectacular", @@ -278,15 +279,30 @@ DJ_CELERY_PANEL_SETTINGS = { "queues_backend": "app.celery.panel.RoutedTasksQueuesBackend", - # No result backend is configured, so list the tasks workers are running right now + # Keep the task list based on live worker inspection. "tasks_backend": "dj_celery_panel.celery_utils.CeleryTasksInspectBackend", # Beat runs DatabaseScheduler, so the database holds the effective schedule "periodic_tasks_backend": "dj_celery_panel.celery_utils.CeleryPeriodicTasksDjangoCeleryBeatBackend", } +# Store Celery results and workflow chord state in Django's database, as OSF does. +CELERY_RESULT_BACKEND = "django-db" +CELERY_TASK_IGNORE_RESULT = True # Scenario tasks explicitly opt in. +CELERY_STRESS_TEST_QUEUES = tuple( + f"{GV_QUEUE_NAME_PREFIX}.{urgency}" + for urgency in ("INTERACTIVE", "REACTIVE", "CHILL") +) +CELERY_STRESS_TEST_DEFAULT_QUEUE = f"{GV_QUEUE_NAME_PREFIX}.CHILL" +CELERY_STRESS_TEST_MAX_TASKS = 20_000 +CELERY_STRESS_TEST_RETENTION_DAYS = 30 + # Celery Beat CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_BEAT_SCHEDULE = { + "cleanup-celery-test-history": { + "task": "stress_testing.cleanup_history", + "schedule": crontab(minute=30, hour=3), + }, "refresh_addon_tokens": { "task": "addon_service.management.commands.refresh_addon_tokens.refresh_addon_tokens", "schedule": crontab(minute=0, hour=7), # Daily 2:00 a.m, diff --git a/app/urls.py b/app/urls.py index 13c86f14..6c879cf5 100644 --- a/app/urls.py +++ b/app/urls.py @@ -11,9 +11,36 @@ SpectacularSwaggerView, ) +from addon_service.celery_stress_test import views as stress_test_views + urlpatterns = [ path("v1/", include("addon_service.urls")), + path( + "admin/dj-celery-panel/celery_stress_test/", + stress_test_views.celery_stress_suites, + name="celery_stress_test", + ), + path( + "admin/dj-celery-panel/celery_stress_test/sync-overdue/", + stress_test_views.celery_stress_suites_sync_overdue, + name="celery_stress_suites_sync_overdue", + ), + path( + "admin/dj-celery-panel/celery_stress_test/new/", + stress_test_views.celery_stress_test_view, + name="celery_stress_test_new", + ), + path( + "admin/dj-celery-panel/celery_stress_test/