Skip to main content

🛡️ django-signal-guard

Make Django signal failures loud.

Catch the bulk writes that silently skip your pre_save / post_save receivers,
the receivers that never get connected, run twice, loop forever,
or send the email before the transaction commits.

CI Python Django PyPI Status Typed Ruff License

Quick start • Bypass guard • Recursion • Before commit • System checks • signals.lock • Configuration • How it works


💥 The problem

Order.objects.bulk_create(rows)  # post_save never fires
Order.objects.filter(...).update(...)  # neither does pre_save

bulk_create(), bulk_update() and update() write rows without calling Model.save(), so your pre_save and post_save receivers never run.

Nothing errors. The search index goes stale, the audit log has gaps, a cache is never invalidated. You usually find out days later, in production.

✅ The fix

django-signal-guard catches those writes in development, tests and CI, and tells you exactly which receivers were skipped and where the call came from:

SignalBypassError: QuerySet.bulk_create() on shop.Order skips 2 receivers:
  pre_save   shop.signals.normalize_status  (shop/signals.py:5)
  post_save  shop.signals.reindex_order  (shop/signals.py:9)
Called from shop/imports.py:42.
Run the receivers' work yourself, or wrap the call in signal_guard.allow_bypass(Order, reason="...").

It doesn't add new signals or replace them with hooks. Your signals stay exactly as they are. It just reports misuse, the way nplusone and django-seal report lazy queries.

✨ What's inside

Feature What it catches
🚧 Bypass guard Bulk writes that skip receivers: raise, warn or log.
🔁 Recursion tracing A receiver that saves its own instance and loops, with the whole chain.
⏳ Before-commit check Emails, Celery tasks and HTTP calls made before the transaction commits.
✅ @receiver_on_commit A drop-in @receiver that runs after the commit.
🩺 System checks Receivers that never run, only run in some processes, die silently, or run twice.
🔒 signals.lock A committed inventory of every receiver, checked in CI, so new receivers show up in code review.

📦 Install

pip install django-signal-guard

Requires Python 3.10+ and Django 5.2+.

🚀 Quick start

1. Add it to INSTALLED_APPS, first in the list:

# settings.py
INSTALLED_APPS = [
    "signal_guard",  # first, so it sees every receiver being connected
    # ...
]

2. Make every finding fail your tests:

# settings/test.py
SIGNAL_GUARD = {"BYPASS": "raise", "RECURSION": "raise", "SIDE_EFFECTS": "raise"}

3. Add two lines to CI:

python manage.py check --tag signals --fail-level WARNING
python manage.py signal_map --check

That's it. Everywhere else, the default is "warn".


🚧 The bypass guard

Every bulk_create(), bulk_update() and update() (plus abulk_create(), abulk_update(), aupdate()) is checked against the live pre_save and post_save receivers for that model. A model with no receivers costs a single has_listeners() call.

When skipping is intended

Wrap the call in allow_bypass and say why. The reason is required, so the decision is written down next to the code:

from signal_guard import allow_bypass

with allow_bypass(Order, reason="import reindexes in one batch"):
    Order.objects.bulk_create(rows)
reindex_orders(rows)
  • allow_bypass() with no models allows every model.
  • It also works as a decorator and with async with.

Receivers that never matter for bulk writes

Mark them once with @bulk_safe:

from django.db.models.signals import post_save
from django.dispatch import receiver
from signal_guard import bulk_safe


@receiver(post_save, sender=Order)
@bulk_safe
def warm_cache(sender, instance, **kwargs): ...
What the guard covers, and what it doesn't

Covered

  • bulk_create(), bulk_update() and update(), called on a manager, a queryset, or your own QuerySet subclass methods.
  • The async variants abulk_create(), abulk_update() and aupdate().
  • Receivers connected to the model, and receivers connected to every sender.
  • bulk_update() is reported once, even though Django runs update() inside it.

Not covered

  • Raw SQL, cursor.execute(), database triggers and other writes that never go through a QuerySet.
  • QuerySet.delete(). It does send pre_delete and post_delete; it only skips your model's own delete() method.
  • Logic in an overridden Model.save() with no signal receiver. The guard only knows about receivers.
  • A QuerySet subclass that overrides one of the three methods and never calls super().

🔁 Recursion tracing

A post_save receiver that calls instance.save() sends post_save again, which calls the receiver again. You get a RecursionError a thousand frames deep, or, worse, a loop that ends on its own after hammering the database.

django-signal-guard traces every signal being sent. When the same signal is sent for the same object while it is already being handled twice, it stops and shows you the loop:

SignalRecursionError: shop.signals.sync_total re-entered for shop.Order #12:
  post_save  shop.Order #12 → shop.signals.sync_total  (shop/signals.py:20)
    Order.save()  shop/signals.py:24
  post_save  shop.Order #12 → shop.signals.sync_total  (shop/signals.py:20)
    Order.save()  shop/signals.py:24
  post_save  shop.Order #12  ← this send
Stop the loop with a guard (check update_fields or a flag on the instance), or write the change with QuerySet.update().
  • Saving once more is fine. The common if created: instance.save() pattern re-enters once and stops, so it is never reported.
  • Same row, any object. Order.objects.get(pk=instance.pk).save() inside the receiver is the same loop, and is caught.
  • Cycles too. Order → Invoice → Order → … shows every hop.
  • Set "RECURSION" to raise, warn (default), log or off.

⏳ Side effects before commit

@receiver(post_save, sender=Order)
def send_confirmation(sender, instance, created, **kwargs):
    send_order_email.delay(instance.pk)  # 💥 the worker may run before COMMIT

Inside a transaction (ATOMIC_REQUESTS, transaction.atomic(), or Django's own around delete()), a receiver runs before the data is committed. The Celery worker looks for the order and gets DoesNotExist. The confirmation email goes out even when the transaction rolls back.

django-signal-guard reports these calls when a receiver makes them inside a transaction that has not committed:

Side effect Calls that are checked
📧 Email send_mail(), EmailMessage.send(), mail_admins(), send_mass_mail()
🥬 Celery Task.delay(), Task.apply_async() (when Celery is installed)
🌐 HTTP requests, httpx (sync and async clients), when installed
🧩 Your own Any function or method listed in SIDE_EFFECT_CALLS
SideEffectBeforeCommitError: Celery task shop.tasks.send_order_email is queued before the transaction on 'default' commits.
  receiver   shop.signals.send_confirmation  (shop/signals.py:30)
  called at  shop/signals.py:33
A worker can run it before the row is committed, and it still runs if the transaction rolls back.
Connect the receiver with @signal_guard.receiver_on_commit, or wrap the call in transaction.on_commit().

The transaction that TestCase (and pytest.mark.django_db) wraps each test in does not count: in production that code runs in autocommit mode. Your own transaction.atomic() blocks inside a test do count.

SIGNAL_GUARD = {
    "SIDE_EFFECTS": "warn",  # raise | warn | log | off
    "SIDE_EFFECT_CALLS": ["shop.webhooks.post", "shop.payments.Client.charge"],
}

The fix: @receiver_on_commit

A drop-in replacement for @receiver that hands the call to transaction.on_commit():

from signal_guard import receiver_on_commit


@receiver_on_commit(post_save, sender=Order)
def send_confirmation(sender, instance, created, **kwargs):
    if created:
        send_order_email.delay(instance.pk)  # ✅ the row is committed now
  • The receiver gets exactly the arguments the signal sent.
  • Rolled back? It never runs. Outside a transaction it runs at once.
  • It uses the database the signal names in using (model signals do), or using= you pass, or the default database.
  • Takes sender, weak, dispatch_uid, a list of signals, and robust=True to log an exception instead of stopping the other commit callbacks.
  • Returns your function unchanged, so you can still call it in tests. signal_map labels these receivers on commit.
Limits of the side-effect check
  • Only calls made while a signal receiver is running are checked. A view that sends email inside atomic() is out of scope.
  • Calls are wrapped when Django starts. Code that ran from django.core.mail import send_mass_mail before then keeps the unwrapped function. send_mail() and EmailMessage.send() are always covered. The same goes for SIDE_EFFECT_CALLS functions imported by name before signal_guard is ready, so list functions that your receivers import in ready() or later.
  • Receivers from installed packages are skipped unless CHECK_LIBRARY_CALLS is on; IGNORE_RECEIVERS patterns apply too.

🩺 System checks

python manage.py check --tag signals
ID Finds Why it matters
W001 A module in one of your apps defines @receiver functions, but nothing imports it. The decorator never runs, so the receiver never runs. The classic "my signal doesn't fire".
W002 A receiver is connected only after startup, by a lazy import such as views.py importing your signals module. Web requests run it, but Celery workers, management commands and some tests never do.
W003 A weakly connected function or lambda was garbage-collected. Django holds receivers by weak reference, so a nested function or lambda silently stops running.
W004 The same receiver is connected more than once to one signal and sender. Every copy runs, so emails go out twice.
Example output
shop.webhooks: (signal_guard.W002) shop.webhooks.send_webhook is connected only after startup, when shop/views.py:2 imports it.
	HINT: Processes that never run that import, such as Celery workers, management commands and some tests, never run this receiver. Import shop.webhooks in shop.apps.ShopConfig.ready().

All four are warnings, so they never stop runserver. Silence one with SILENCED_SYSTEM_CHECKS = ["signal_guard.W004"].


🔒 The signal map and signals.lock

See which receivers run for which signal and sender: yours, plus third-party receivers that run on your models (add --all for Django's internals).

$ python manage.py signal_map
First-party receivers (3)
  django.db.models.signals.post_save
    shop.Order
      shop.signals.reindex_order  (shop/signals.py:9)
      shop.webhooks.send_webhook  (shop/webhooks.py:6)
  django.db.models.signals.pre_save
    shop.Order
      shop.signals.normalize_status  (shop/signals.py:5)

Commit the same list as a lock file:

python manage.py signal_map --write   # writes signals.lock
python manage.py signal_map --check   # fails with a diff when it's out of date
[first-party]
django.db.models.signals.post_save | shop.Order | shop.signals.reindex_order
django.db.models.signals.post_save | shop.Order | shop.webhooks.send_webhook
django.db.models.signals.pre_save | shop.Order | shop.signals.normalize_status

One line per receiver, no line numbers, so the file only changes when a receiver is added, removed or moved. That includes receivers a dependency upgrade quietly adds to your models.


⚙️ Configuration

Every key is optional:

SIGNAL_GUARD = {
    "BYPASS": "warn",  # raise | warn | log | off
    "RECURSION": "warn",  # raise | warn | log | off
    "SIDE_EFFECTS": "warn",  # raise | warn | log | off
    "SIDE_EFFECT_CALLS": [],  # e.g. ["shop.webhooks.post"]
    "IGNORE_RECEIVERS": [],  # fnmatch patterns, e.g. ["simple_history.*"]
    "CHECK_LIBRARY_CALLS": False,
    "FIRST_PARTY": None,  # e.g. ["shop", "billing"]
    "LOCK_FILE": "signals.lock",
    "ENABLED": True,
}
Key Default Description
BYPASS "warn" raise stops the write with SignalBypassError before anything reaches the database. warn emits a SignalBypassWarning. log writes to the signal_guard logger. off does nothing.
RECURSION "warn" What to do when a receiver re-enters itself for the same object twice. raise stops before the third run.
SIDE_EFFECTS "warn" What to do when a receiver sends email, queues a Celery task or makes an HTTP call before the transaction commits. raise stops the call before it happens.
SIDE_EFFECT_CALLS [] Dotted paths of your own functions or methods that count as side effects. A path that cannot be imported fails at startup.
IGNORE_RECEIVERS [] Receivers whose dotted path matches one of these patterns are never reported, by any check. Handy for third-party receivers you can't change.
CHECK_LIBRARY_CALLS False Also report bulk writes made inside Django or installed packages, such as the UPDATE behind on_delete=SET_NULL, and side effects in their receivers.
FIRST_PARTY None Module prefixes of your own code. By default, anything not Django and not in site-packages counts as yours.
LOCK_FILE "signals.lock" Where signal_map --write / --check keep the lock file. Relative paths resolve against settings.BASE_DIR when it exists.
ENABLED True When False at startup, nothing is wrapped and every check does nothing.

Tip: settings are read on every call, so override_settings just works in tests.


🔍 How it works

flowchart LR
    A["Order.objects.bulk_create(rows)"] --> B{"pre_save / post_save<br/>listeners?"}
    B -- no --> W[("write to DB")]
    B -- yes --> C{"allow_bypass,<br/>@bulk_safe or<br/>IGNORE_RECEIVERS?"}
    C -- all covered --> W
    C -- some left --> D["report skipped receivers<br/>+ call site"]
    D -- raise --> X["SignalBypassError<br/>(nothing written)"]
    D -- warn / log --> W
  • Bypass guard. On app load it wraps QuerySet.bulk_create, bulk_update and update. Before each write it asks Django's dispatcher which pre_save and post_save receivers are live for the model, drops those marked @bulk_safe or matching IGNORE_RECEIVERS, and reports the rest.
  • Tracing. It wraps Signal.send(), send_robust(), asend() and asend_robust() to keep a per-context stack of the signals being sent. Recursion is a match on that stack; the receiver at each hop is found by walking Python frames, only when something is reported. Each send costs under a microsecond more, small next to the database write behind it.
  • Side effects. At startup it wraps the email, Celery, HTTP and SIDE_EFFECT_CALLS functions. Each call first asks: is a receiver running, and is a transaction open that TestCase did not open? Only then does it look up the receiver and report.
  • Registry. It wraps Signal.connect() and disconnect() to record where and when each receiver was connected. It holds only weak references, so it never keeps a receiver alive. That's why signal_guard should come first in INSTALLED_APPS: a receiver connected before it loads has no record, so W003 can't see it die.
  • Checks and map. They import your URLconf first, as a running server would, then read Django's live receivers. W001 also parses your apps' modules (skipping tests and migrations) to find @receiver functions.

🗺️ Roadmap

Version Adds
0.1 Bypass guard ✅
0.2 System checks W001–W004, manage.py signal_map, signals.lock ✅
0.3 Recursion tracing, @receiver_on_commit, a check for side effects before commit ✅
1.0 pytest plugin and test assertions, full documentation 🔜

See the changelog for details.

📚 Prior art

  • Johnny Metz's post on blocking bulk operations that skip signals, which shows the same idea as a custom QuerySet.
  • django-bulk-signals, django-bulk-tracker and similar packages add new bulk signals. Use them if you want receivers that do run on bulk writes; django-signal-guard tells you when your existing receivers don't.
  • django-lifecycle replaces signals with model hooks.

🧑‍💻 Development

uv sync --group dev
uv run pytest
uv run ruff check . && uv run ruff format --check .

Issues and pull requests are welcome.

📄 License

BSD-3-Clause, the same as Django.

Metadata

Release files for django-signal-guard 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-signal-guard 0.3.0
File Size Uploaded Provenance Actions
django_signal_guard-0.3.0.tar.gz 42.8 kB With provenance Details for django_signal_guard-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for django-signal-guard 0.3.0
File Interpreter ABI Platform Actions
django_signal_guard-0.3.0-py3-none-any.whl Python 3 none any Details for django_signal_guard-0.3.0-py3-none-any.whl

Total release size: 82.8 kB

Release files / django_signal_guard-0.3.0.tar.gz

Download URL django_signal_guard-0.3.0.tar.gz
Size 42.8 kB
Tags Source
SHA-256 checksum
How to use checksums
56422b57a85a7977ae1c63c26e377a222ee1e11e951022a572142ff9fa30fa30
BLAKE2b-256 checksum
How to use checksums
065e60419117966354a4c4a1b2e85b45c10c299b2ee62dc4ef136c54848e49a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / django_signal_guard-0.3.0-py3-none-any.whl

Download URL django_signal_guard-0.3.0-py3-none-any.whl
Size 40.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
aa4b369ced5373f8e32c090adcb13cc71aadd435a1737a3782ecf8808f1ecff9
BLAKE2b-256 checksum
How to use checksums
825a489694d078eb84d664289a99447cbab1c184383e2dd1f298d31b77266987
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for django-signal-guard 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for django_signal_guard-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page