From 4bf30e68229069709c225279ceed9ed08aebec22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Jes=C3=BAs=20Pe=C3=B1a=20Rodr=C3=ADguez?= Date: Mon, 24 Aug 2026 11:38:24 +0200 Subject: [PATCH 1/8] fix(skills): correct Django Celery delivery guidance --- skills/django-celery/SKILL.md | 109 ++++++++++++------ .../django-celery/references/reliability.md | 55 +++++++++ tests/skills/django-celery.test.js | 68 +++++++++++ 3 files changed, 198 insertions(+), 34 deletions(-) create mode 100644 skills/django-celery/references/reliability.md create mode 100644 tests/skills/django-celery.test.js diff --git a/skills/django-celery/SKILL.md b/skills/django-celery/SKILL.md index 0ae987755..060e868f1 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,24 @@ 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 +can remain queued after the transaction rolls back. Use `delay_on_commit()` with +Celery 5.4 or newer, or `transaction.on_commit()` when `apply_async()` options or +older versions require it. See +[Delivery Reliability](references/reliability.md#publish-after-the-database-commits) +for version, task-ID, custom-base, and transactional-outbox boundaries. + +```python +from django.db import transaction + +@transaction.atomic +def create_user(request): + user = User.objects.create(username=request.POST['username']) + send_welcome_email.delay_on_commit(user.pk) +``` + ## Beat Scheduling (Periodic Tasks) ### Code-Defined Schedule @@ -266,6 +289,11 @@ PeriodicTask.objects.update_or_create( ) ``` +Run only one scheduler for a given schedule to avoid duplicate publications. That +does not prevent execution overlap: periodic tasks may overlap when one run lasts +longer than its interval. Use an ownership-safe locking strategy or a database +uniqueness constraint, and keep the task idempotent in case a lock expires. + ## Canvas: Chaining and Grouping Tasks ```python @@ -294,7 +322,7 @@ result = chord( result.delay() ``` -## Error Handling and Dead Letter Queue +## Failure Monitoring ```python # apps/core/tasks.py @@ -314,29 +342,9 @@ 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 normally after recording a final error makes Celery record `SUCCESS`. +Persist the failure and re-raise instead. Broker dead-letter queues live at the queue +and exchange layer; they are not equivalent to a Django model used as an error log. ## Testing Celery Tasks @@ -362,7 +370,11 @@ 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. ```python # config/settings/test.py @@ -382,6 +394,14 @@ def test_registration_triggers_welcome_email(client): 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 +448,25 @@ def charge_and_fulfill(order_id): order.charge() # May charge twice if task retries! order.fulfill() -# GOOD: Idempotent with status guard -@shared_task +# GOOD: External idempotency key plus a short database transaction +from django.db import transaction +from apps.payments.gateway import gateway + +@shared_task(acks_late=True) def charge_and_fulfill(order_id): - order = Order.objects.select_for_update().get(pk=order_id) + order = Order.objects.only('status').get(pk=order_id) if order.status != Order.Status.PENDING: - return # Already processed - order.charge() - order.fulfill() + return + + # Keep network I/O outside the database transaction. The provider must return + # the same charge for repeated calls with this stable idempotency key. + 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.status == Order.Status.PENDING: + order.record_charge(receipt) + order.fulfill() ``` ## Production Checklist @@ -443,13 +474,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..4a663afda --- /dev/null +++ b/skills/django-celery/references/reliability.md @@ -0,0 +1,55 @@ +# 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`. + +## Publish After the Database Commits + +With Celery 5.4 or newer, `delay_on_commit()` is available for tasks based on +`DjangoTask`. Custom task base classes must inherit from `DjangoTask` to expose this +API. The method does not return a task ID because the message is not published until +commit. + +For older Celery versions or when `apply_async()` options are required, register the +publication 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. diff --git a/tests/skills/django-celery.test.js b/tests/skills/django-celery.test.js new file mode 100644 index 000000000..7cda1aece --- /dev/null +++ b/tests/skills/django-celery.test.js @@ -0,0 +1,68 @@ +'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'); +const guidance = `${skill}\n${reliability}`; + +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; + } +} + +console.log('\n=== Django Celery skill tests ===\n'); + +test('documents transaction-aware task publication', () => { + assert.match(skill, /references\/reliability\.md/); + assert.match(guidance, /delay_on_commit/); + assert.match(guidance, /transaction\.on_commit/); + assert.match(guidance, /does not return (?:a )?task ID/i); + assert.match(guidance, /transactional outbox/i); +}); + +test('states the worker-loss boundary for late acknowledgements', () => { + assert.doesNotMatch(guidance, /CELERY_TASK_ACKS_LATE\s*=\s*True[^\n]*re-queue on worker crash/i); + assert.match(guidance, /task_reject_on_worker_lost/i); + assert.match(guidance, /message loops/i); + assert.match(guidance, /idempotent/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')); + + assert.ok(lockingExamples.length > 0, 'Expected at least one select_for_update example'); + for (const block of lockingExamples) { + assert.match(block, /transaction\.atomic/); + } +}); + +test('distinguishes eager execution from real worker integration', () => { + assert.match(skill, /eager mode[^\n]*(?:emulat|not a worker integration)/i); + assert.match(skill, /celery_worker/); + assert.match(skill, /real broker/i); +}); + +test('warns that a single beat scheduler does not prevent task overlap', () => { + assert.match(skill, /periodic tasks? (?:can|may) overlap/i); + assert.match(skill, /locking strategy/i); +}); + +console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0); From 5f0df4196f806530a734b026a9788002f63f5afc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Jes=C3=BAs=20Pe=C3=B1a=20Rodr=C3=ADguez?= Date: Mon, 24 Aug 2026 12:09:20 +0200 Subject: [PATCH 2/8] fix(skills): harden Django Celery reliability contracts --- skills/django-celery/SKILL.md | 48 +++--- .../django-celery/references/reliability.md | 3 +- tests/skills/django-celery.test.js | 150 ++++++++++++++++-- 3 files changed, 160 insertions(+), 41 deletions(-) diff --git a/skills/django-celery/SKILL.md b/skills/django-celery/SKILL.md index 060e868f1..f3bdcc392 100644 --- a/skills/django-celery/SKILL.md +++ b/skills/django-celery/SKILL.md @@ -227,18 +227,17 @@ 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 -can remain queued after the transaction rolls back. Use `delay_on_commit()` with -Celery 5.4 or newer, or `transaction.on_commit()` when `apply_async()` options or -older versions require it. See +remain queued after rollback. Use `delay_on_commit()` with Celery 5.4 or newer; use +`transaction.on_commit()` for `apply_async()` options or older versions. See [Delivery Reliability](references/reliability.md#publish-after-the-database-commits) -for version, task-ID, custom-base, and transactional-outbox boundaries. +for custom-base, task-ID, and transactional-outbox boundaries. ```python from django.db import transaction @transaction.atomic -def create_user(request): - user = User.objects.create(username=request.POST['username']) +def create_user(validated_username: str): + user = User.objects.create(username=validated_username) send_welcome_email.delay_on_commit(user.pk) ``` @@ -289,10 +288,10 @@ PeriodicTask.objects.update_or_create( ) ``` -Run only one scheduler for a given schedule to avoid duplicate publications. That -does not prevent execution overlap: periodic tasks may overlap when one run lasts -longer than its interval. Use an ownership-safe locking strategy or a database -uniqueness constraint, and keep the task idempotent in case a lock expires. +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 @@ -342,9 +341,8 @@ def on_task_failure(sender, task_id, exception, args, kwargs, traceback, einfo, sentry_sdk.capture_exception(exception) ``` -Returning normally after recording a final error makes Celery record `SUCCESS`. -Persist the failure and re-raise instead. Broker dead-letter queues live at the queue -and exchange layer; they are not equivalent to a Django model used as an error log. +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 @@ -448,25 +446,27 @@ def charge_and_fulfill(order_id): order.charge() # May charge twice if task retries! order.fulfill() -# GOOD: External idempotency key plus a short database transaction +# 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(acks_late=True) -def charge_and_fulfill(order_id): - order = Order.objects.only('status').get(pk=order_id) - if order.status != Order.Status.PENDING: - return +@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 - # Keep network I/O outside the database transaction. The provider must return - # the same charge for repeated calls with this stable idempotency key. + # 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.status == Order.Status.PENDING: - order.record_charge(receipt) - order.fulfill() + if order.charge_attempt_id != attempt_id: + return + order.record_charge(receipt) + order.fulfill() ``` ## Production Checklist diff --git a/skills/django-celery/references/reliability.md b/skills/django-celery/references/reliability.md index 4a663afda..997f166d3 100644 --- a/skills/django-celery/references/reliability.md +++ b/skills/django-celery/references/reliability.md @@ -25,7 +25,8 @@ abruptly. Celery acknowledges worker-loss messages unless `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`. +separately by `task_acks_on_failure_or_timeout`, which applies only to tasks using +late acknowledgement. ## Publish After the Database Commits diff --git a/tests/skills/django-celery.test.js b/tests/skills/django-celery.test.js index 7cda1aece..a55881af8 100644 --- a/tests/skills/django-celery.test.js +++ b/tests/skills/django-celery.test.js @@ -9,7 +9,6 @@ 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'); -const guidance = `${skill}\n${reliability}`; let passed = 0; let failed = 0; @@ -26,42 +25,161 @@ function test(name, fn) { } } +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 findUnprotectedSelectForUpdateLines(source) { + const blocks = []; + const atomicDecoratorIndents = new Set(); + const unsafeLines = []; + const lines = source.split('\n'); + + for (const [index, line] of lines.entries()) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) { + continue; + } + + const whitespace = line.match(/^[ \t]*/)[0]; + const indent = whitespace.replaceAll('\t', ' ').length; + while (blocks.length > 0 && indent <= blocks[blocks.length - 1].indent) { + blocks.pop(); + } + + if (trimmed.startsWith('@')) { + if (/^@transaction\.atomic(?:\(\))?$/.test(trimmed)) { + atomicDecoratorIndents.add(indent); + } + continue; + } + + if (trimmed.includes('.select_for_update(') && !blocks.some(block => block.atomic)) { + unsafeLines.push(index + 1); + } + + if (!trimmed.endsWith(':')) { + atomicDecoratorIndents.delete(indent); + continue; + } + + const isFunction = /^(?:async\s+)?def\s+/.test(trimmed); + const isAtomicWith = /^with\s+transaction\.atomic\([^)]*\):$/.test(trimmed); + const isAtomicFunction = isFunction && atomicDecoratorIndents.has(indent); + blocks.push({ indent, atomic: isAtomicWith || isAtomicFunction }); + atomicDecoratorIndents.delete(indent); + } + + return unsafeLines; +} + console.log('\n=== Django Celery skill tests ===\n'); test('documents transaction-aware task publication', () => { - assert.match(skill, /references\/reliability\.md/); - assert.match(guidance, /delay_on_commit/); - assert.match(guidance, /transaction\.on_commit/); - assert.match(guidance, /does not return (?:a )?task ID/i); - assert.match(guidance, /transactional outbox/i); + 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 not return (?:a )?task ID/i); + assert.match(reliabilityPublication, /transactional outbox/i); }); test('states the worker-loss boundary for late acknowledgements', () => { - assert.doesNotMatch(guidance, /CELERY_TASK_ACKS_LATE\s*=\s*True[^\n]*re-queue on worker crash/i); - assert.match(guidance, /task_reject_on_worker_lost/i); - assert.match(guidance, /message loops/i); - assert.match(guidance, /idempotent/i); + 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'); assert.ok(lockingExamples.length > 0, 'Expected at least one select_for_update example'); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(invalidExample), [1]); for (const block of lockingExamples) { - assert.match(block, /transaction\.atomic/); + assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(block), []); } }); test('distinguishes eager execution from real worker integration', () => { - assert.match(skill, /eager mode[^\n]*(?:emulat|not a worker integration)/i); - assert.match(skill, /celery_worker/); - assert.match(skill, /real broker/i); + 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(realWorker, /celery_worker/); + assert.match(realWorker, /real broker/i); }); test('warns that a single beat scheduler does not prevent task overlap', () => { - assert.match(skill, /periodic tasks? (?:can|may) overlap/i); - assert.match(skill, /locking strategy/i); + 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'); + + assertMarkersInOrder(antiPatterns, [ + '.select_for_update(', + 'claim_or_resume_charge', + 'gateway.charge', + '.select_for_update(', + 'charge_attempt_id', + 'record_charge', + ]); + assert.match(antiPatterns, /adapter validates provider data/i); }); console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); From 84c2f30e2a87ec689e5c50d9904bc33708bd27c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Jes=C3=BAs=20Pe=C3=B1a=20Rodr=C3=ADguez?= Date: Mon, 24 Aug 2026 12:48:09 +0200 Subject: [PATCH 3/8] test(skills): harden Celery delivery and lock checks --- tests/skills/django-celery.test.js | 35 +++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/tests/skills/django-celery.test.js b/tests/skills/django-celery.test.js index a55881af8..18cd18acf 100644 --- a/tests/skills/django-celery.test.js +++ b/tests/skills/django-celery.test.js @@ -57,6 +57,19 @@ function assertMarkersInOrder(source, markers) { }, -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 findUnprotectedSelectForUpdateLines(source) { const blocks = []; const atomicDecoratorIndents = new Set(); @@ -76,13 +89,13 @@ function findUnprotectedSelectForUpdateLines(source) { } if (trimmed.startsWith('@')) { - if (/^@transaction\.atomic(?:\(\))?$/.test(trimmed)) { + if (/^@transaction\.atomic(?:\([^)]*\))?$/.test(trimmed)) { atomicDecoratorIndents.add(indent); } continue; } - if (trimmed.includes('.select_for_update(') && !blocks.some(block => block.atomic)) { + if (trimmed.includes('.select_for_update(') && !hasActiveAtomicScope(blocks)) { unsafeLines.push(index + 1); } @@ -94,7 +107,7 @@ function findUnprotectedSelectForUpdateLines(source) { const isFunction = /^(?:async\s+)?def\s+/.test(trimmed); const isAtomicWith = /^with\s+transaction\.atomic\([^)]*\):$/.test(trimmed); const isAtomicFunction = isFunction && atomicDecoratorIndents.has(indent); - blocks.push({ indent, atomic: isAtomicWith || isAtomicFunction }); + blocks.push({ indent, atomic: isAtomicWith || isAtomicFunction, callable: isFunction }); atomicDecoratorIndents.delete(indent); } @@ -137,9 +150,22 @@ test('keeps every select_for_update example inside an atomic block', () => { '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'); 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), []); for (const block of lockingExamples) { assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(block), []); } @@ -171,10 +197,13 @@ test('warns that a single beat scheduler does not prevent task overlap', () => { 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, [ + 'self.request.id', '.select_for_update(', 'claim_or_resume_charge', 'gateway.charge', + "idempotency_key=f'order:{order_id}'", '.select_for_update(', 'charge_attempt_id', 'record_charge', From dfb41283756c442a8815e0d44262d7e5fda0888a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Jes=C3=BAs=20Pe=C3=B1a=20Rodr=C3=ADguez?= Date: Mon, 24 Aug 2026 13:31:03 +0200 Subject: [PATCH 4/8] test(skills): harden transaction scope regression cases --- tests/skills/django-celery.test.js | 163 +++++++++++++++++++++-------- 1 file changed, 121 insertions(+), 42 deletions(-) diff --git a/tests/skills/django-celery.test.js b/tests/skills/django-celery.test.js index 18cd18acf..c58b79ee6 100644 --- a/tests/skills/django-celery.test.js +++ b/tests/skills/django-celery.test.js @@ -70,48 +70,110 @@ function hasActiveAtomicScope(blocks) { return blocks.slice(executionScopeStart).some(block => block.atomic); } -function findUnprotectedSelectForUpdateLines(source) { - const blocks = []; - const atomicDecoratorIndents = new Set(); - const unsafeLines = []; - const lines = source.split('\n'); +function withoutSetValue(values, target) { + return new Set([...values].filter(value => value !== target)); +} - for (const [index, line] of lines.entries()) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) { - continue; - } - - const whitespace = line.match(/^[ \t]*/)[0]; - const indent = whitespace.replaceAll('\t', ' ').length; - while (blocks.length > 0 && indent <= blocks[blocks.length - 1].indent) { - blocks.pop(); - } - - if (trimmed.startsWith('@')) { - if (/^@transaction\.atomic(?:\([^)]*\))?$/.test(trimmed)) { - atomicDecoratorIndents.add(indent); - } - continue; - } - - if (trimmed.includes('.select_for_update(') && !hasActiveAtomicScope(blocks)) { - unsafeLines.push(index + 1); - } - - if (!trimmed.endsWith(':')) { - atomicDecoratorIndents.delete(indent); - continue; - } - - const isFunction = /^(?:async\s+)?def\s+/.test(trimmed); - const isAtomicWith = /^with\s+transaction\.atomic\([^)]*\):$/.test(trimmed); - const isAtomicFunction = isFunction && atomicDecoratorIndents.has(indent); - blocks.push({ indent, atomic: isAtomicWith || isAtomicFunction, callable: isFunction }); - atomicDecoratorIndents.delete(indent); +function getPythonLineDetails(line) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) { + return null; } - return unsafeLines; + 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*:\s*/); + if (!closingAtomic) { + return 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*:\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'); @@ -161,11 +223,28 @@ test('keeps every select_for_update example inside an atomic block', () => { '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'); 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), []); for (const block of lockingExamples) { assert.deepStrictEqual(findUnprotectedSelectForUpdateLines(block), []); } @@ -199,12 +278,12 @@ test('claims and owns a payment attempt around external I/O', () => { assert.match(antiPatterns, /@shared_task\(bind=True,\s*acks_late=True\)/); assertMarkersInOrder(antiPatterns, [ - 'self.request.id', - '.select_for_update(', + 'attempt_id = self.request.id', + '.select_for_update().get(', 'claim_or_resume_charge', 'gateway.charge', "idempotency_key=f'order:{order_id}'", - '.select_for_update(', + '.select_for_update().get(', 'charge_attempt_id', 'record_charge', ]); From 3e34eaa914a7313965121062f352e61d477b3dc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Jes=C3=BAs=20Pe=C3=B1a=20Rodr=C3=ADguez?= Date: Mon, 24 Aug 2026 14:01:56 +0200 Subject: [PATCH 5/8] test(skills): fail closed on incomplete atomic scopes --- tests/skills/django-celery.test.js | 38 +++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/tests/skills/django-celery.test.js b/tests/skills/django-celery.test.js index c58b79ee6..21e30ecd4 100644 --- a/tests/skills/django-celery.test.js +++ b/tests/skills/django-celery.test.js @@ -96,9 +96,10 @@ function trimBlocksForIndent(blocks, indent) { } function inspectPendingAtomicLine(state, code, lineNumber) { - const closingAtomic = code.match(/^\)\s*:\s*/); + const closingAtomic = code.match(/^\)\s*(?:as\s+[A-Za-z_]\w*\s*)?:\s*/); if (!closingAtomic) { - return state; + const unsafeQuery = code.includes('.select_for_update('); + return unsafeQuery ? { ...state, unsafeLines: [...state.unsafeLines, lineNumber] } : state; } const inlineBody = code.slice(closingAtomic[0].length); @@ -126,7 +127,9 @@ function inspectPythonStatement(state, code, indent, lineNumber) { return { ...state, pendingAtomicWithIndent: indent }; } - const atomicWith = code.match(/^with\s+transaction\.atomic\([^)]*\)\s*:\s*/); + 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); @@ -237,6 +240,30 @@ test('keeps every select_for_update example inside an atomic block', () => { '):', ' 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]); @@ -245,6 +272,11 @@ test('keeps every select_for_update example inside an atomic block', () => { 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), []); } From e2e48476b6aff30a51ab82552d92bb854135a838 Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:59:29 -0500 Subject: [PATCH 6/8] docs(skills): document Django on-commit test contract for Celery Add a TestCase example that uses captureOnCommitCallbacks(execute=True) and asserts the Celery delay call, note the pytest-django fixture and when TransactionTestCase is appropriate, wrap the eager-mode request example so post-commit dispatch actually runs, mention apply_async_on_commit(), and pin the examples in the skill test. --- skills/django-celery/SKILL.md | 22 +++++--- .../django-celery/references/reliability.md | 53 ++++++++++++++++--- tests/skills/django-celery.test.js | 28 +++++++++- 3 files changed, 88 insertions(+), 15 deletions(-) diff --git a/skills/django-celery/SKILL.md b/skills/django-celery/SKILL.md index f3bdcc392..54a8d5bc2 100644 --- a/skills/django-celery/SKILL.md +++ b/skills/django-celery/SKILL.md @@ -227,10 +227,12 @@ 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()` with Celery 5.4 or newer; use -`transaction.on_commit()` for `apply_async()` options or older versions. See +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. +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 @@ -373,6 +375,9 @@ class TestSendWelcomeEmail: 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 @@ -381,12 +386,13 @@ 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() diff --git a/skills/django-celery/references/reliability.md b/skills/django-celery/references/reliability.md index 997f166d3..71f046af1 100644 --- a/skills/django-celery/references/reliability.md +++ b/skills/django-celery/references/reliability.md @@ -30,13 +30,13 @@ late acknowledgement. ## Publish After the Database Commits -With Celery 5.4 or newer, `delay_on_commit()` is available for tasks based on -`DjangoTask`. Custom task base classes must inherit from `DjangoTask` to expose this -API. The method does not return a task ID because the message is not published until -commit. +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 when `apply_async()` options are required, register the -publication explicitly: +For older Celery versions, or to keep the publication visible at the call site, +register it explicitly: ```python from functools import partial @@ -54,3 +54,44 @@ transaction.on_commit( 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 index 21e30ecd4..fe35d77ef 100644 --- a/tests/skills/django-celery.test.js +++ b/tests/skills/django-celery.test.js @@ -190,7 +190,7 @@ test('documents transaction-aware task publication', () => { assert.match(skillPublication, /validated_username/); assert.doesNotMatch(skillPublication, /request\.POST/); assert.match(reliabilityPublication, /transaction\.on_commit/); - assert.match(reliabilityPublication, /does not return (?:a )?task ID/i); + assert.match(reliabilityPublication, /(?:does|do) not return (?:a )?task ID/i); assert.match(reliabilityPublication, /transactional outbox/i); }); @@ -282,6 +282,26 @@ test('keeps every select_for_update example inside an atomic 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'); @@ -291,6 +311,12 @@ test('distinguishes eager execution from real worker integration', () => { 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); }); From 8e3c93e4a1f8069317270fd87bf65a5d1f82e7a6 Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:07:41 -0500 Subject: [PATCH 7/8] fix(pi): allowlist Celery docs host and regenerate django-celery pi/core skill The django-celery references link to docs.celeryq.dev, which the pi/core safety scan rejects as a non-allowlisted host. Allow the documentation host and regenerate pi/core so the shipped skill matches its source. --- manifests/pi-core.json | 1 + pi/core/skills/django-celery/SKILL.md | 129 ++++++++++++------ .../django-celery/references/reliability.md | 97 +++++++++++++ 3 files changed, 186 insertions(+), 41 deletions(-) create mode 100644 pi/core/skills/django-celery/references/reliability.md 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. From e70034a4d55bc807a86796403f8ce9d9532fe28b Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:27:49 -0500 Subject: [PATCH 8/8] chore: bind skill trigger digest to updated django-celery guidance --- manifests/context-packs/skill-triggers@1.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 91b727422..0f95f9b55 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": "23bd986cff96ea33424b1a461461a70e3194582ce01927145fd3f956daeebf7f", + "registryDigest": "f4644a4db6f15bb5127343cc63503fbe13e2948e767472ac5ce2881c77a359a1", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [