diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 1a4fc6895..dca98a820 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "db0cf09e08bed0151527523143a0fa949717e2c7afb4248a3395dfb4cf41add1", + "registryDigest": "cf9879ff972740a7d2af9b56a0f682870375d3abc75eea9164bd2b1838fd5b81", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/manifests/pi-core.json b/manifests/pi-core.json index 098153742..0bcff6d7f 100644 --- a/manifests/pi-core.json +++ b/manifests/pi-core.json @@ -484,6 +484,7 @@ "developer.android.com", "developer.apple.com", "developers.cloudflare.com", + "docs.celeryq.dev", "docs.flutter.dev", "docs.spring.io", "external-secrets.io", diff --git a/pi/core/skills/django-celery/SKILL.md b/pi/core/skills/django-celery/SKILL.md index 0ae987755..54a8d5bc2 100644 --- a/pi/core/skills/django-celery/SKILL.md +++ b/pi/core/skills/django-celery/SKILL.md @@ -70,7 +70,6 @@ CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 # Hard limit: 30 min CELERY_TASK_SOFT_TIME_LIMIT = 25 * 60 # Soft limit: sends SoftTimeLimitExceeded CELERY_WORKER_PREFETCH_MULTIPLIER = 1 # Prevent worker hoarding long tasks -CELERY_TASK_ACKS_LATE = True # Re-queue on worker crash # Result persistence CELERY_RESULT_EXPIRES = 60 * 60 * 24 # Keep results 24 hours @@ -199,6 +198,12 @@ def generate_pdf_report(self, report_id: int) -> str: raise ``` +### Delivery Guarantees + +Late acknowledgement, worker-loss redelivery, and commit-aware publication are separate +choices. Read [Delivery Reliability](references/reliability.md) before +changing acknowledgement settings or publishing tasks from a database transaction. + ## Calling Tasks ```python @@ -219,6 +224,25 @@ sync_contact_to_crm.apply_async(args=[contact.pk], queue='high_priority') result = generate_pdf_report.apply(args=[report.pk]) ``` +### Publish After the Database Commits + +A task published inside a Django transaction can run before its rows are visible or +remain queued after rollback. Use `delay_on_commit()` or `apply_async_on_commit()` +with Celery 5.4 or newer; use `transaction.on_commit()` on older versions. See +[Delivery Reliability](references/reliability.md#publish-after-the-database-commits) +for custom-base, task-ID, and transactional-outbox boundaries. Django's `TestCase` +never commits, so these callbacks never run in tests unless captured; see +[Test the On-Commit Contract](references/reliability.md#test-the-on-commit-contract). + +```python +from django.db import transaction + +@transaction.atomic +def create_user(validated_username: str): + user = User.objects.create(username=validated_username) + send_welcome_email.delay_on_commit(user.pk) +``` + ## Beat Scheduling (Periodic Tasks) ### Code-Defined Schedule @@ -266,6 +290,11 @@ PeriodicTask.objects.update_or_create( ) ``` +Run only one scheduler for a given schedule to avoid duplicate publications, but this +does not prevent execution overlap: periodic tasks may overlap. Atomically claim an +active-run lease with an owner and expiry or recovery path; a unique schedule row +alone does not serialize executions. Keep the task idempotent if the lease expires. + ## Canvas: Chaining and Grouping Tasks ```python @@ -294,7 +323,7 @@ result = chord( result.delay() ``` -## Error Handling and Dead Letter Queue +## Failure Monitoring ```python # apps/core/tasks.py @@ -314,29 +343,8 @@ def on_task_failure(sender, task_id, exception, args, kwargs, traceback, einfo, sentry_sdk.capture_exception(exception) ``` -```python -# Route failed tasks to dead-letter queue after max retries -@shared_task( - bind=True, - max_retries=3, - name='payments.charge_card', -) -def charge_card(self, order_id: int) -> None: - from apps.payments.models import Order, FailedCharge - - try: - _do_charge(order_id) - except Exception as exc: - if self.request.retries >= self.max_retries: - # Persist to dead-letter table for manual review - FailedCharge.objects.create( - order_id=order_id, - error=str(exc), - task_id=self.request.id, - ) - return # Don't raise — task is permanently failed - raise self.retry(exc=exc) -``` +Returning after recording a final error makes Celery record `SUCCESS`; persist and +re-raise instead. Broker dead-letter queues are not Django model error logs. ## Testing Celery Tasks @@ -362,7 +370,14 @@ class TestSendWelcomeEmail: send_welcome_email(99999) # Non-existent user — must not raise ``` -### Integration Testing with CELERY_TASK_ALWAYS_EAGER +### Django Integration Path with Eager Mode + +Eager mode is a worker emulation, not a worker integration test. Use it to verify +that a Django request selects the expected task and arguments, but do not use it as +evidence for serialization, routing, acknowledgement, retry, or worker-loss behavior. +It also does not prove post-commit dispatch: under `django_db` the test transaction +never commits, so a view that publishes with `delay_on_commit()` runs nothing unless +the request is wrapped in `django_capture_on_commit_callbacks(execute=True)`. ```python # config/settings/test.py @@ -371,17 +386,26 @@ CELERY_TASK_EAGER_PROPAGATES = True # Re-raise exceptions from tasks # tests/test_integration.py @pytest.mark.django_db -def test_registration_triggers_welcome_email(client): +def test_registration_triggers_welcome_email(client, django_capture_on_commit_callbacks): with patch('apps.notifications.services.EmailService') as mock_email: - response = client.post('/api/users/', { - 'email': 'new@example.com', - 'password': 'strongpass123', - }) + with django_capture_on_commit_callbacks(execute=True): + response = client.post('/api/users/', { + 'email': 'new@example.com', + 'password': 'strongpass123', + }) assert response.status_code == 201 mock_email.send_welcome.assert_called_once() ``` +### Worker Integration with a Real Broker + +Use Celery's `celery_worker` pytest fixture with a real broker and result backend for +the delivery boundary. Cover serialization, routing, retry behavior, and any +acknowledgement or redelivery options the application enables. Keep this suite +separate from fast unit tests so a passing eager-mode test is never mistaken for +worker evidence. + ### Testing Retries ```python @@ -428,14 +452,27 @@ def charge_and_fulfill(order_id): order.charge() # May charge twice if task retries! order.fulfill() -# GOOD: Idempotent with status guard -@shared_task -def charge_and_fulfill(order_id): - order = Order.objects.select_for_update().get(pk=order_id) - if order.status != Order.Status.PENDING: - return # Already processed - order.charge() - order.fulfill() +# GOOD: Claim ownership before external I/O, then finalize only as that owner +from django.db import transaction +from apps.payments.gateway import gateway + +@shared_task(bind=True, acks_late=True) +def charge_and_fulfill(self, order_id): + attempt_id = self.request.id # Stable across Celery retry and redelivery + with transaction.atomic(): + order = Order.objects.select_for_update().get(pk=order_id) + if not order.claim_or_resume_charge(attempt_id): + return + + # The adapter validates provider data and returns the same charge on retry. + receipt = gateway.charge(order_id, idempotency_key=f'order:{order_id}') + + with transaction.atomic(): + order = Order.objects.select_for_update().get(pk=order_id) + if order.charge_attempt_id != attempt_id: + return + order.record_charge(receipt) + order.fulfill() ``` ## Production Checklist @@ -443,13 +480,23 @@ def charge_and_fulfill(order_id): | Check | Setting | |-------|---------| | Worker restarts on crash | `supervisord` or `systemd` unit | -| `CELERY_TASK_ACKS_LATE = True` | Re-queue tasks on worker crash | +| Late acknowledgement | Per task, only after proving idempotency; duplicates remain possible | +| Worker-loss redelivery | `task_reject_on_worker_lost`, opt in only with poison-task protection | | `CELERY_WORKER_PREFETCH_MULTIPLIER = 1` | Fair distribution of long tasks | | Separate queues per priority | `-Q default,high_priority,low_priority` | | `CELERY_TASK_SOFT_TIME_LIMIT` set | Graceful timeout before hard kill | | Sentry integration | Capture all `task_failure` signals | | Flower or other monitor | Visibility into queue depths | -| Beat runs on single node only | Prevents duplicate scheduled task execution | +| Beat runs on single node only | Prevents duplicate scheduled task publication | +| Periodic-task locking | Prevents overlapping execution when required | + +## References + +- [Celery task acknowledgement and idempotency](https://docs.celeryq.dev/en/stable/userguide/tasks.html) +- [Celery configuration defaults](https://docs.celeryq.dev/en/stable/userguide/configuration.html) +- [Celery with Django transaction handling](https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html) +- [Celery periodic tasks](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html) +- [Celery testing guide](https://docs.celeryq.dev/en/stable/userguide/testing.html) ## Related Skills diff --git a/pi/core/skills/django-celery/references/reliability.md b/pi/core/skills/django-celery/references/reliability.md new file mode 100644 index 000000000..71f046af1 --- /dev/null +++ b/pi/core/skills/django-celery/references/reliability.md @@ -0,0 +1,97 @@ +# Delivery Reliability + +Read this reference when changing acknowledgement settings, worker-loss behavior, +or task publication around Django database transactions. + +## Acknowledgement and Worker Loss + +Celery acknowledges task messages before execution by default. Opt in to late +acknowledgement only for idempotent tasks that are safe to execute more than once: + +```python +@shared_task( + name='orders.mark_shipped', + acks_late=True, +) +def mark_order_shipped(order_id: int, tracking_number: str) -> None: + # Use an idempotent implementation such as the guarded update in SKILL.md. + ... +``` + +Late acknowledgement means the task may execute more than once if delivery is +interrupted. It does not by itself guarantee redelivery when a worker child exits +abruptly. Celery acknowledges worker-loss messages unless +`task_reject_on_worker_lost` (or Django's +`CELERY_TASK_REJECT_ON_WORKER_LOST`) is enabled. That option can cause message loops +for poison tasks, so enable it only after validating idempotency and monitoring the +redelivery path. Failure and timeout acknowledgement behavior is controlled +separately by `task_acks_on_failure_or_timeout`, which applies only to tasks using +late acknowledgement. + +## Publish After the Database Commits + +With Celery 5.4 or newer, `delay_on_commit()` and `apply_async_on_commit()` are +available for tasks based on `DjangoTask`. Custom task base classes must inherit from +`DjangoTask` to expose this API. These methods do not return a task ID because the +message is not published until commit. + +For older Celery versions, or to keep the publication visible at the call site, +register it explicitly: + +```python +from functools import partial +from django.db import transaction + +transaction.on_commit( + partial( + sync_contact_to_crm.apply_async, + args=[contact.pk], + queue='high_priority', + ) +) +``` + +An on-commit callback avoids publication on rollback, but it does not make the +database commit and broker publish atomic. If task delivery must not be lost when a +publish fails after commit, use a transactional outbox with a separate publisher. + +## Test the On-Commit Contract + +Django's `TestCase` wraps each test in a transaction that is rolled back, never +committed, so `transaction.on_commit()` callbacks (including `delay_on_commit()`) +never run. A test that only checks the new database row still passes when the task +is never queued. Capture the callbacks, execute them, and assert the Celery call: + +```python +from unittest.mock import patch + +from django.contrib.auth.models import User +from django.test import TestCase + +from apps.users.services import create_user +from apps.users.tasks import send_welcome_email + + +class CreateUserTests(TestCase): + def test_queues_welcome_email_after_commit(self): + # Patch before the call: delay_on_commit() binds task.delay when it registers. + with patch.object(send_welcome_email, 'delay') as mock_delay: + with self.captureOnCommitCallbacks(execute=True) as callbacks: + create_user('bob') + mock_delay.assert_not_called() # Not published before commit + + user = User.objects.get(username='bob') + self.assertEqual(len(callbacks), 1) + mock_delay.assert_called_once_with(user.pk) +``` + +`captureOnCommitCallbacks()` is available on `TestCase` in Django 3.2 or newer. With +pytest-django, the `django_capture_on_commit_callbacks` fixture provides the same +context manager inside `@pytest.mark.django_db` tests. + +Use `TransactionTestCase`, or `@pytest.mark.django_db(transaction=True)`, only when a +test needs a real commit: for example, when a real Celery worker in another thread +or process must read the committed rows. Those tests commit for real, so on-commit +callbacks run when the outermost `atomic()` block commits, and Django resets the +database afterwards by truncating tables, which is much slower. Keep them for the +worker integration boundary and use `TestCase` with captured callbacks elsewhere. diff --git a/skills/django-celery/SKILL.md b/skills/django-celery/SKILL.md index 0ae987755..54a8d5bc2 100644 --- a/skills/django-celery/SKILL.md +++ b/skills/django-celery/SKILL.md @@ -70,7 +70,6 @@ CELERY_TASK_TRACK_STARTED = True CELERY_TASK_TIME_LIMIT = 30 * 60 # Hard limit: 30 min CELERY_TASK_SOFT_TIME_LIMIT = 25 * 60 # Soft limit: sends SoftTimeLimitExceeded CELERY_WORKER_PREFETCH_MULTIPLIER = 1 # Prevent worker hoarding long tasks -CELERY_TASK_ACKS_LATE = True # Re-queue on worker crash # Result persistence CELERY_RESULT_EXPIRES = 60 * 60 * 24 # Keep results 24 hours @@ -199,6 +198,12 @@ def generate_pdf_report(self, report_id: int) -> str: raise ``` +### Delivery Guarantees + +Late acknowledgement, worker-loss redelivery, and commit-aware publication are separate +choices. Read [Delivery Reliability](references/reliability.md) before +changing acknowledgement settings or publishing tasks from a database transaction. + ## Calling Tasks ```python @@ -219,6 +224,25 @@ sync_contact_to_crm.apply_async(args=[contact.pk], queue='high_priority') result = generate_pdf_report.apply(args=[report.pk]) ``` +### Publish After the Database Commits + +A task published inside a Django transaction can run before its rows are visible or +remain queued after rollback. Use `delay_on_commit()` or `apply_async_on_commit()` +with Celery 5.4 or newer; use `transaction.on_commit()` on older versions. See +[Delivery Reliability](references/reliability.md#publish-after-the-database-commits) +for custom-base, task-ID, and transactional-outbox boundaries. Django's `TestCase` +never commits, so these callbacks never run in tests unless captured; see +[Test the On-Commit Contract](references/reliability.md#test-the-on-commit-contract). + +```python +from django.db import transaction + +@transaction.atomic +def create_user(validated_username: str): + user = User.objects.create(username=validated_username) + send_welcome_email.delay_on_commit(user.pk) +``` + ## Beat Scheduling (Periodic Tasks) ### Code-Defined Schedule @@ -266,6 +290,11 @@ PeriodicTask.objects.update_or_create( ) ``` +Run only one scheduler for a given schedule to avoid duplicate publications, but this +does not prevent execution overlap: periodic tasks may overlap. Atomically claim an +active-run lease with an owner and expiry or recovery path; a unique schedule row +alone does not serialize executions. Keep the task idempotent if the lease expires. + ## Canvas: Chaining and Grouping Tasks ```python @@ -294,7 +323,7 @@ result = chord( result.delay() ``` -## Error Handling and Dead Letter Queue +## Failure Monitoring ```python # apps/core/tasks.py @@ -314,29 +343,8 @@ def on_task_failure(sender, task_id, exception, args, kwargs, traceback, einfo, sentry_sdk.capture_exception(exception) ``` -```python -# Route failed tasks to dead-letter queue after max retries -@shared_task( - bind=True, - max_retries=3, - name='payments.charge_card', -) -def charge_card(self, order_id: int) -> None: - from apps.payments.models import Order, FailedCharge - - try: - _do_charge(order_id) - except Exception as exc: - if self.request.retries >= self.max_retries: - # Persist to dead-letter table for manual review - FailedCharge.objects.create( - order_id=order_id, - error=str(exc), - task_id=self.request.id, - ) - return # Don't raise — task is permanently failed - raise self.retry(exc=exc) -``` +Returning after recording a final error makes Celery record `SUCCESS`; persist and +re-raise instead. Broker dead-letter queues are not Django model error logs. ## Testing Celery Tasks @@ -362,7 +370,14 @@ class TestSendWelcomeEmail: send_welcome_email(99999) # Non-existent user — must not raise ``` -### Integration Testing with CELERY_TASK_ALWAYS_EAGER +### Django Integration Path with Eager Mode + +Eager mode is a worker emulation, not a worker integration test. Use it to verify +that a Django request selects the expected task and arguments, but do not use it as +evidence for serialization, routing, acknowledgement, retry, or worker-loss behavior. +It also does not prove post-commit dispatch: under `django_db` the test transaction +never commits, so a view that publishes with `delay_on_commit()` runs nothing unless +the request is wrapped in `django_capture_on_commit_callbacks(execute=True)`. ```python # config/settings/test.py @@ -371,17 +386,26 @@ CELERY_TASK_EAGER_PROPAGATES = True # Re-raise exceptions from tasks # tests/test_integration.py @pytest.mark.django_db -def test_registration_triggers_welcome_email(client): +def test_registration_triggers_welcome_email(client, django_capture_on_commit_callbacks): with patch('apps.notifications.services.EmailService') as mock_email: - response = client.post('/api/users/', { - 'email': 'new@example.com', - 'password': 'strongpass123', - }) + with django_capture_on_commit_callbacks(execute=True): + response = client.post('/api/users/', { + 'email': 'new@example.com', + 'password': 'strongpass123', + }) assert response.status_code == 201 mock_email.send_welcome.assert_called_once() ``` +### Worker Integration with a Real Broker + +Use Celery's `celery_worker` pytest fixture with a real broker and result backend for +the delivery boundary. Cover serialization, routing, retry behavior, and any +acknowledgement or redelivery options the application enables. Keep this suite +separate from fast unit tests so a passing eager-mode test is never mistaken for +worker evidence. + ### Testing Retries ```python @@ -428,14 +452,27 @@ def charge_and_fulfill(order_id): order.charge() # May charge twice if task retries! order.fulfill() -# GOOD: Idempotent with status guard -@shared_task -def charge_and_fulfill(order_id): - order = Order.objects.select_for_update().get(pk=order_id) - if order.status != Order.Status.PENDING: - return # Already processed - order.charge() - order.fulfill() +# GOOD: Claim ownership before external I/O, then finalize only as that owner +from django.db import transaction +from apps.payments.gateway import gateway + +@shared_task(bind=True, acks_late=True) +def charge_and_fulfill(self, order_id): + attempt_id = self.request.id # Stable across Celery retry and redelivery + with transaction.atomic(): + order = Order.objects.select_for_update().get(pk=order_id) + if not order.claim_or_resume_charge(attempt_id): + return + + # The adapter validates provider data and returns the same charge on retry. + receipt = gateway.charge(order_id, idempotency_key=f'order:{order_id}') + + with transaction.atomic(): + order = Order.objects.select_for_update().get(pk=order_id) + if order.charge_attempt_id != attempt_id: + return + order.record_charge(receipt) + order.fulfill() ``` ## Production Checklist @@ -443,13 +480,23 @@ def charge_and_fulfill(order_id): | Check | Setting | |-------|---------| | Worker restarts on crash | `supervisord` or `systemd` unit | -| `CELERY_TASK_ACKS_LATE = True` | Re-queue tasks on worker crash | +| Late acknowledgement | Per task, only after proving idempotency; duplicates remain possible | +| Worker-loss redelivery | `task_reject_on_worker_lost`, opt in only with poison-task protection | | `CELERY_WORKER_PREFETCH_MULTIPLIER = 1` | Fair distribution of long tasks | | Separate queues per priority | `-Q default,high_priority,low_priority` | | `CELERY_TASK_SOFT_TIME_LIMIT` set | Graceful timeout before hard kill | | Sentry integration | Capture all `task_failure` signals | | Flower or other monitor | Visibility into queue depths | -| Beat runs on single node only | Prevents duplicate scheduled task execution | +| Beat runs on single node only | Prevents duplicate scheduled task publication | +| Periodic-task locking | Prevents overlapping execution when required | + +## References + +- [Celery task acknowledgement and idempotency](https://docs.celeryq.dev/en/stable/userguide/tasks.html) +- [Celery configuration defaults](https://docs.celeryq.dev/en/stable/userguide/configuration.html) +- [Celery with Django transaction handling](https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html) +- [Celery periodic tasks](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html) +- [Celery testing guide](https://docs.celeryq.dev/en/stable/userguide/testing.html) ## Related Skills diff --git a/skills/django-celery/references/reliability.md b/skills/django-celery/references/reliability.md new file mode 100644 index 000000000..71f046af1 --- /dev/null +++ b/skills/django-celery/references/reliability.md @@ -0,0 +1,97 @@ +# Delivery Reliability + +Read this reference when changing acknowledgement settings, worker-loss behavior, +or task publication around Django database transactions. + +## Acknowledgement and Worker Loss + +Celery acknowledges task messages before execution by default. Opt in to late +acknowledgement only for idempotent tasks that are safe to execute more than once: + +```python +@shared_task( + name='orders.mark_shipped', + acks_late=True, +) +def mark_order_shipped(order_id: int, tracking_number: str) -> None: + # Use an idempotent implementation such as the guarded update in SKILL.md. + ... +``` + +Late acknowledgement means the task may execute more than once if delivery is +interrupted. It does not by itself guarantee redelivery when a worker child exits +abruptly. Celery acknowledges worker-loss messages unless +`task_reject_on_worker_lost` (or Django's +`CELERY_TASK_REJECT_ON_WORKER_LOST`) is enabled. That option can cause message loops +for poison tasks, so enable it only after validating idempotency and monitoring the +redelivery path. Failure and timeout acknowledgement behavior is controlled +separately by `task_acks_on_failure_or_timeout`, which applies only to tasks using +late acknowledgement. + +## Publish After the Database Commits + +With Celery 5.4 or newer, `delay_on_commit()` and `apply_async_on_commit()` are +available for tasks based on `DjangoTask`. Custom task base classes must inherit from +`DjangoTask` to expose this API. These methods do not return a task ID because the +message is not published until commit. + +For older Celery versions, or to keep the publication visible at the call site, +register it explicitly: + +```python +from functools import partial +from django.db import transaction + +transaction.on_commit( + partial( + sync_contact_to_crm.apply_async, + args=[contact.pk], + queue='high_priority', + ) +) +``` + +An on-commit callback avoids publication on rollback, but it does not make the +database commit and broker publish atomic. If task delivery must not be lost when a +publish fails after commit, use a transactional outbox with a separate publisher. + +## Test the On-Commit Contract + +Django's `TestCase` wraps each test in a transaction that is rolled back, never +committed, so `transaction.on_commit()` callbacks (including `delay_on_commit()`) +never run. A test that only checks the new database row still passes when the task +is never queued. Capture the callbacks, execute them, and assert the Celery call: + +```python +from unittest.mock import patch + +from django.contrib.auth.models import User +from django.test import TestCase + +from apps.users.services import create_user +from apps.users.tasks import send_welcome_email + + +class CreateUserTests(TestCase): + def test_queues_welcome_email_after_commit(self): + # Patch before the call: delay_on_commit() binds task.delay when it registers. + with patch.object(send_welcome_email, 'delay') as mock_delay: + with self.captureOnCommitCallbacks(execute=True) as callbacks: + create_user('bob') + mock_delay.assert_not_called() # Not published before commit + + user = User.objects.get(username='bob') + self.assertEqual(len(callbacks), 1) + mock_delay.assert_called_once_with(user.pk) +``` + +`captureOnCommitCallbacks()` is available on `TestCase` in Django 3.2 or newer. With +pytest-django, the `django_capture_on_commit_callbacks` fixture provides the same +context manager inside `@pytest.mark.django_db` tests. + +Use `TransactionTestCase`, or `@pytest.mark.django_db(transaction=True)`, only when a +test needs a real commit: for example, when a real Celery worker in another thread +or process must read the committed rows. Those tests commit for real, so on-commit +callbacks run when the outermost `atomic()` block commits, and Django resets the +database afterwards by truncating tables, which is much slower. Keep them for the +worker integration boundary and use `TestCase` with captured callbacks elsewhere. diff --git a/tests/skills/django-celery.test.js b/tests/skills/django-celery.test.js new file mode 100644 index 000000000..fe35d77ef --- /dev/null +++ b/tests/skills/django-celery.test.js @@ -0,0 +1,352 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); + +const repoRoot = path.resolve(__dirname, '..', '..'); +const skillPath = path.join(repoRoot, 'skills', 'django-celery', 'SKILL.md'); +const reliabilityPath = path.join(repoRoot, 'skills', 'django-celery', 'references', 'reliability.md'); +const skill = fs.readFileSync(skillPath, 'utf8'); +const reliability = fs.readFileSync(reliabilityPath, 'utf8'); + +let passed = 0; +let failed = 0; + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + passed += 1; + } catch (error) { + console.log(` ✗ ${name}`); + console.log(` Error: ${error.message}`); + failed += 1; + } +} + +function getMarkdownSection(document, heading) { + const lines = document.split('\n'); + const start = lines.indexOf(heading); + assert.notStrictEqual(start, -1, `Missing section: ${heading}`); + const level = heading.match(/^#+/)[0].length; + let end = start + 1; + let inFence = false; + + while (end < lines.length) { + if (lines[end].startsWith('```')) { + inFence = !inFence; + end += 1; + continue; + } + const nextHeading = inFence ? null : lines[end].match(/^(#+)\s/); + if (nextHeading?.[1].length <= level) { + break; + } + end += 1; + } + + return lines.slice(start + 1, end).join('\n'); +} + +function assertMarkersInOrder(source, markers) { + markers.reduce((previousIndex, marker) => { + const index = source.indexOf(marker, previousIndex + 1); + assert.ok(index > previousIndex, `Expected ${marker} after the previous marker`); + return index; + }, -1); +} + +function hasActiveAtomicScope(blocks) { + let executionScopeStart = 0; + + for (let index = blocks.length - 1; index >= 0; index -= 1) { + if (blocks[index].callable) { + executionScopeStart = index; + break; + } + } + + return blocks.slice(executionScopeStart).some(block => block.atomic); +} + +function withoutSetValue(values, target) { + return new Set([...values].filter(value => value !== target)); +} + +function getPythonLineDetails(line) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) { + return null; + } + + const whitespace = line.match(/^[ \t]*/)[0]; + return { + code: trimmed.replace(/\s+#.*$/, ''), + indent: whitespace.replaceAll('\t', ' ').length, + }; +} + +function trimBlocksForIndent(blocks, indent) { + let visibleBlocks = blocks; + while (visibleBlocks.length > 0 && indent <= visibleBlocks[visibleBlocks.length - 1].indent) { + visibleBlocks = visibleBlocks.slice(0, -1); + } + return visibleBlocks; +} + +function inspectPendingAtomicLine(state, code, lineNumber) { + const closingAtomic = code.match(/^\)\s*(?:as\s+[A-Za-z_]\w*\s*)?:\s*/); + if (!closingAtomic) { + const unsafeQuery = code.includes('.select_for_update('); + return unsafeQuery ? { ...state, unsafeLines: [...state.unsafeLines, lineNumber] } : state; + } + + const inlineBody = code.slice(closingAtomic[0].length); + const deferredLambda = /^[A-Za-z_]\w*(?:\s*:[^=]+)?\s*=\s*lambda\b/.test(inlineBody); + const unsafeQuery = inlineBody.includes('.select_for_update(') && deferredLambda; + const blocks = inlineBody + ? state.blocks + : [...state.blocks, { indent: state.pendingAtomicWithIndent, atomic: true, callable: false }]; + return { + ...state, + blocks, + pendingAtomicWithIndent: null, + unsafeLines: unsafeQuery ? [...state.unsafeLines, lineNumber] : state.unsafeLines, + }; +} + +function inspectPythonStatement(state, code, indent, lineNumber) { + if (code.startsWith('@')) { + const atomicDecorator = /^@transaction\.atomic(?:\([^)]*\))?$/.test(code); + return atomicDecorator + ? { ...state, atomicDecoratorIndents: new Set([...state.atomicDecoratorIndents, indent]) } + : state; + } + if (/^with\s+transaction\.atomic\(\s*$/.test(code)) { + return { ...state, pendingAtomicWithIndent: indent }; + } + + const atomicWith = code.match( + /^with\s+transaction\.atomic\([^)]*\)\s*(?:as\s+[A-Za-z_]\w*\s*)?:\s*/, + ); + const inlineAtomicBody = atomicWith ? code.slice(atomicWith[0].length) : ''; + const isFunction = /^(?:async\s+)?def\s+/.test(code); + const isAtomicFunction = isFunction && state.atomicDecoratorIndents.has(indent); + const queryIndex = code.indexOf('.select_for_update('); + const functionColon = isFunction ? code.indexOf(':') : -1; + const inlineFunctionQuery = queryIndex > functionColon && functionColon !== -1; + const queryScope = inlineAtomicBody || code; + const deferredLambda = /^[A-Za-z_]\w*(?:\s*:[^=]+)?\s*=\s*lambda\b/.test(queryScope); + + let queryProtected = hasActiveAtomicScope(state.blocks); + queryProtected = atomicWith && inlineAtomicBody ? true : queryProtected; + queryProtected = inlineFunctionQuery ? isAtomicFunction : queryProtected; + queryProtected = deferredLambda ? false : queryProtected; + const unsafeQuery = queryIndex !== -1 && !queryProtected; + const blocks = code.endsWith(':') + ? [...state.blocks, { indent, atomic: Boolean(atomicWith) || isAtomicFunction, callable: isFunction }] + : state.blocks; + return { + ...state, + blocks, + atomicDecoratorIndents: withoutSetValue(state.atomicDecoratorIndents, indent), + unsafeLines: unsafeQuery ? [...state.unsafeLines, lineNumber] : state.unsafeLines, + }; +} + +function inspectPythonLine(state, line, lineNumber) { + const details = getPythonLineDetails(line); + if (!details) { + return state; + } + const scopedState = { ...state, blocks: trimBlocksForIndent(state.blocks, details.indent) }; + return scopedState.pendingAtomicWithIndent === null + ? inspectPythonStatement(scopedState, details.code, details.indent, lineNumber) + : inspectPendingAtomicLine(scopedState, details.code, lineNumber); +} + +function findUnprotectedSelectForUpdateLines(source) { + const initialState = { + blocks: [], + atomicDecoratorIndents: new Set(), + pendingAtomicWithIndent: null, + unsafeLines: [], + }; + const finalState = source + .split('\n') + .reduce((state, line, index) => inspectPythonLine(state, line, index + 1), initialState); + return finalState.unsafeLines; +} + +console.log('\n=== Django Celery skill tests ===\n'); + +test('documents transaction-aware task publication', () => { + const skillPublication = getMarkdownSection(skill, '### Publish After the Database Commits'); + const reliabilityPublication = getMarkdownSection(reliability, '## Publish After the Database Commits'); + + assert.match(skillPublication, /references\/reliability\.md/); + assert.match(skillPublication, /delay_on_commit/); + assert.match(skillPublication, /validated_username/); + assert.doesNotMatch(skillPublication, /request\.POST/); + assert.match(reliabilityPublication, /transaction\.on_commit/); + assert.match(reliabilityPublication, /(?:does|do) not return (?:a )?task ID/i); + assert.match(reliabilityPublication, /transactional outbox/i); +}); + +test('states the worker-loss boundary for late acknowledgements', () => { + const acknowledgements = getMarkdownSection(reliability, '## Acknowledgement and Worker Loss'); + + assert.doesNotMatch(acknowledgements, /late ack(?:nowledgement)?[^\n]*re-queue on worker crash/i); + assert.match( + acknowledgements, + /Late acknowledgement[\s\S]*does not by itself guarantee redelivery[\s\S]*task_reject_on_worker_lost/i, + ); + assert.match(acknowledgements, /message loops/i); + assert.match(acknowledgements, /idempotent/i); + assert.match(acknowledgements, /task_acks_on_failure_or_timeout[\s\S]*only[\s\S]*late acknowledgement/i); +}); + +test('keeps every select_for_update example inside an atomic block', () => { + const pythonBlocks = [...skill.matchAll(/```python\n([\s\S]*?)```/g)].map(match => match[1]); + const lockingExamples = pythonBlocks.filter(block => block.includes('select_for_update')); + const invalidExample = [ + "order = Order.objects.select_for_update().get(pk=order_id)", + 'with transaction.atomic():', + ' audit_order(order)', + ].join('\n'); + const deferredCallableExample = [ + 'with transaction.atomic():', + ' def load_order():', + ' return Order.objects.select_for_update().get(pk=order_id)', + 'load_order()', + ].join('\n'); + const atomicCallableExample = [ + "@transaction.atomic(using='default')", + 'def load_order():', + ' return Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + const deferredLambdaExample = [ + 'with transaction.atomic():', + ' load_order = lambda: Order.objects.select_for_update().get(pk=order_id)', + 'load_order()', + ].join('\n'); + const sameLineAtomicExample = [ + 'with transaction.atomic(): order = Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + const multilineAtomicExample = [ + 'with transaction.atomic(', + " using='default',", + '):', + ' order = Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + const multilineAtomicAliasExample = [ + 'with transaction.atomic(', + " using='default',", + ') as atomic_context:', + ' order = Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + const sameLineAtomicAliasExample = [ + 'with transaction.atomic() as atomic_context:', + ' order = Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + const inlineAtomicAliasExample = [ + 'with transaction.atomic() as atomic_context: order = Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + const atomicArgumentQueryExample = [ + 'with transaction.atomic(', + ' using=Order.objects.select_for_update().get(pk=order_id)._state.db,', + '):', + ' process_order()', + ].join('\n'); + const unterminatedAtomicExample = [ + 'with transaction.atomic(', + " using='default',", + 'order = Order.objects.select_for_update().get(pk=order_id)', + ].join('\n'); + + assert.ok(lockingExamples.length > 0, 'Expected at least one select_for_update example'); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(invalidExample), [1]); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(deferredCallableExample), [3]); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(atomicCallableExample), []); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(deferredLambdaExample), [2]); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(sameLineAtomicExample), []); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(multilineAtomicExample), []); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(multilineAtomicAliasExample), []); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(sameLineAtomicAliasExample), []); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(inlineAtomicAliasExample), []); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(atomicArgumentQueryExample), [2]); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(unterminatedAtomicExample), [3]); + for (const block of lockingExamples) { + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(block), []); + } +}); + +test('documents the on-commit test contract with an asserted Celery call', () => { + const skillPublication = getMarkdownSection(skill, '### Publish After the Database Commits'); + const contract = getMarkdownSection(reliability, '## Test the On-Commit Contract'); + const example = contract.match(/```python\n([\s\S]*?)```/)?.[1]; + + assert.match(skillPublication, /references\/reliability\.md#test-the-on-commit-contract/); + assert.match(contract, /TestCase[\s\S]*never\s+committed[\s\S]*never run/i); + assert.ok(example, 'Expected a Python example in the on-commit test contract'); + assert.match(example, /class \w+\(TestCase\)/); + assertMarkersInOrder(example, [ + "patch.object(send_welcome_email, 'delay')", + 'self.captureOnCommitCallbacks(execute=True)', + "create_user('bob')", + 'mock_delay.assert_not_called()', + 'mock_delay.assert_called_once_with(user.pk)', + ]); + assert.match(contract, /django_capture_on_commit_callbacks/); + assert.match(contract, /TransactionTestCase[\s\S]*real commit[\s\S]*truncating tables/i); +}); + +test('distinguishes eager execution from real worker integration', () => { + const eagerMode = getMarkdownSection(skill, '### Django Integration Path with Eager Mode'); + const realWorker = getMarkdownSection(skill, '### Worker Integration with a Real Broker'); + + assert.match(eagerMode, /worker emulation, not a worker integration test/i); + assert.match( + eagerMode, + /do not use it as[\s\S]*evidence for serialization, routing, acknowledgement, retry, or worker-loss behavior/i, + ); + assert.match(eagerMode, /does not prove post-commit dispatch/i); + assertMarkersInOrder(eagerMode, [ + 'with django_capture_on_commit_callbacks(execute=True):', + "client.post('/api/users/'", + 'mock_email.send_welcome.assert_called_once()', + ]); + assert.match(realWorker, /celery_worker/); + assert.match(realWorker, /real broker/i); +}); + +test('warns that a single beat scheduler does not prevent task overlap', () => { + const beat = getMarkdownSection(skill, '## Beat Scheduling (Periodic Tasks)'); + + assert.match(beat, /only one scheduler[\s\S]*avoid duplicate publications/i); + assert.match(beat, /does not prevent execution overlap[\s\S]*periodic tasks? (?:can|may) overlap/i); + assert.match(beat, /active-run lease[\s\S]*owner[\s\S]*(?:expiry|recovery)/i); + assert.match(beat, /unique schedule row[\s\S]*alone does not serialize executions/i); + assert.match(beat, /idempotent/i); +}); + +test('claims and owns a payment attempt around external I/O', () => { + const antiPatterns = getMarkdownSection(skill, '## Anti-Patterns'); + + assert.match(antiPatterns, /@shared_task\(bind=True,\s*acks_late=True\)/); + assertMarkersInOrder(antiPatterns, [ + 'attempt_id = self.request.id', + '.select_for_update().get(', + 'claim_or_resume_charge', + 'gateway.charge', + "idempotency_key=f'order:{order_id}'", + '.select_for_update().get(', + 'charge_attempt_id', + 'record_charge', + ]); + assert.match(antiPatterns, /adapter validates provider data/i); +}); + +console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0);