authentik.tasks.tests.test_signals
Tests for authentik.tasks.signals.monitoring_set_queued_tasks.
Regression guards: the handler must enumerate (queue_name, actor_name)
from the in-memory dramatiq broker registry, not via a
SELECT DISTINCT ... FROM authentik_tasks_task full-table scan.
Pure unit tests — Task.objects and get_broker are mocked so no DB
connection is required.
1"""Tests for ``authentik.tasks.signals.monitoring_set_queued_tasks``. 2 3Regression guards: the handler must enumerate ``(queue_name, actor_name)`` 4from the in-memory dramatiq broker registry, not via a 5``SELECT DISTINCT ... FROM authentik_tasks_task`` full-table scan. 6 7Pure unit tests — ``Task.objects`` and ``get_broker`` are mocked so no DB 8connection is required. 9""" 10 11from types import SimpleNamespace 12from unittest import TestCase, mock 13 14 15class _FakeActor: 16 def __init__(self, queue_name: str, actor_name: str): 17 self.queue_name = queue_name 18 self.actor_name = actor_name 19 20 21class TestMonitoringSetQueuedTasksDoesNotScan(TestCase): 22 """The handler must not full-scan ``authentik_tasks_task``.""" 23 24 def _run_handler(self, fake_actors, task_objects_mock): 25 """Run the handler with mocked broker, Task.objects, and gauge. 26 Returns (broker_mock, task_mock, gauge_mock).""" 27 from authentik.tasks import signals 28 29 with ( 30 mock.patch.object(signals, "get_broker") as mock_get_broker, 31 mock.patch.object(signals, "Task") as mock_task, 32 mock.patch.object(signals, "GAUGE_TASKS_QUEUED") as mock_gauge, 33 ): 34 mock_get_broker.return_value.actors = fake_actors 35 mock_task.objects = task_objects_mock 36 signals.monitoring_set_queued_tasks(sender=self) 37 return mock_get_broker, mock_task, mock_gauge 38 39 def test_does_not_call_values_distinct_on_task_objects(self): 40 """Direct ``Task.objects.values(...).distinct()`` (the old DB-hot path) 41 must never be called.""" 42 fake_actors = { 43 "a": _FakeActor("default", "a"), 44 "b": _FakeActor("default", "b"), 45 } 46 task_objects = mock.MagicMock() 47 # Empty result for the remaining filter-based query. 48 task_objects.filter.return_value.values.return_value.annotate.return_value = [] 49 50 _, mock_task, _ = self._run_handler(fake_actors, task_objects) 51 52 # ``values`` called without going through ``filter`` first means 53 # something is enumerating the whole table. 54 for call in mock_task.objects.values.call_args_list: 55 self.fail( 56 f"Task.objects.values{call} was called directly — " 57 "this would issue a full-table SELECT DISTINCT." 58 ) 59 60 def test_gauges_set_for_every_registered_actor(self): 61 """Every actor registered with the broker has its gauge initialized 62 to 0 so prometheus shows the actor's existence even when no tasks 63 are queued for it.""" 64 fake_actors = { 65 "actor_a": _FakeActor("queue_x", "actor_a"), 66 "actor_b": _FakeActor("queue_y", "actor_b"), 67 "actor_c": _FakeActor("queue_x", "actor_c"), 68 } 69 task_objects = mock.MagicMock() 70 task_objects.filter.return_value.values.return_value.annotate.return_value = [] 71 72 _, _, mock_gauge = self._run_handler(fake_actors, task_objects) 73 74 labeled_combos = {(c.args[0], c.args[1]) for c in mock_gauge.labels.call_args_list} 75 expected_combos = {(actor.queue_name, actor.actor_name) for actor in fake_actors.values()} 76 self.assertEqual(labeled_combos, expected_combos) 77 for child_call in mock_gauge.labels.return_value.set.call_args_list: 78 self.assertEqual(child_call.args, (0,)) 79 80 def test_queued_count_query_uses_filter_state_queued(self): 81 """The remaining DB query goes through ``.filter(state=QUEUED)`` so 82 it can use the ``(queue_name, state)`` index.""" 83 from django_dramatiq_postgres.models import TaskState 84 85 fake_actors = {"a": _FakeActor("default", "a")} 86 task_objects = mock.MagicMock() 87 task_objects.filter.return_value.values.return_value.annotate.return_value = [ 88 {"queue_name": "default", "actor_name": "a", "count": 5}, 89 ] 90 91 _, mock_task, mock_gauge = self._run_handler(fake_actors, task_objects) 92 93 mock_task.objects.filter.assert_called_once_with(state=TaskState.QUEUED) 94 mock_gauge.labels.return_value.set.assert_any_call(5) 95 96 97class TestMonitoringSetWorkers(TestCase): 98 """Tests for worker-count gauge refreshes.""" 99 100 def _scrape(self, signals, gauges, versions): 101 """Run the handler with ``versions`` as the currently-live workers.""" 102 worker_status = mock.Mock() 103 worker_status.objects.filter.return_value = [ 104 SimpleNamespace(version=version) for version in versions 105 ] 106 with ( 107 mock.patch.object(signals, "authentik_full_version", return_value="2026.5.6"), 108 mock.patch.object(signals, "WorkerStatus", worker_status), 109 mock.patch.object(signals, "OLD_GAUGE_WORKERS", gauges[0]), 110 mock.patch.object(signals, "GAUGE_WORKERS", gauges[1]), 111 ): 112 signals.monitoring_set_workers(sender=self) 113 return { 114 gauge._name: { 115 (s.labels["version"], s.labels["version_matched"]): s.value 116 for metric in gauge.collect() 117 for s in metric.samples 118 } 119 for gauge in gauges 120 } 121 122 def test_obsolete_version_labels_are_reset(self): 123 """A version that no longer has any WorkerStatus row is reported as zero. 124 125 The gauges are exported through prometheus' multiprocess collector, where a labelset 126 stays in the process' mmap file until it is overwritten — so it has to be zeroed 127 explicitly, and cannot be derived from the rows still in the database. 128 """ 129 from prometheus_client import Gauge 130 131 from authentik.tasks import signals 132 133 gauges = [ 134 Gauge( 135 name, 136 "test", 137 ["version", "version_matched"], 138 multiprocess_mode="livemostrecent", 139 registry=None, 140 ) 141 for name in ("test_admin_workers", "test_tasks_workers") 142 ] 143 144 samples = self._scrape(signals, gauges, ["2026.5.6", "2026.4.0"]) 145 for series in samples.values(): 146 self.assertEqual(series[("2026.5.6", "True")], 1) 147 self.assertEqual(series[("2026.4.0", "False")], 1) 148 149 # The 2026.4.0 worker is gone, and so is its WorkerStatus row 150 samples = self._scrape(signals, gauges, ["2026.5.6"]) 151 for series in samples.values(): 152 self.assertEqual(series[("2026.5.6", "True")], 1) 153 self.assertEqual(series[("2026.4.0", "False")], 0)
22class TestMonitoringSetQueuedTasksDoesNotScan(TestCase): 23 """The handler must not full-scan ``authentik_tasks_task``.""" 24 25 def _run_handler(self, fake_actors, task_objects_mock): 26 """Run the handler with mocked broker, Task.objects, and gauge. 27 Returns (broker_mock, task_mock, gauge_mock).""" 28 from authentik.tasks import signals 29 30 with ( 31 mock.patch.object(signals, "get_broker") as mock_get_broker, 32 mock.patch.object(signals, "Task") as mock_task, 33 mock.patch.object(signals, "GAUGE_TASKS_QUEUED") as mock_gauge, 34 ): 35 mock_get_broker.return_value.actors = fake_actors 36 mock_task.objects = task_objects_mock 37 signals.monitoring_set_queued_tasks(sender=self) 38 return mock_get_broker, mock_task, mock_gauge 39 40 def test_does_not_call_values_distinct_on_task_objects(self): 41 """Direct ``Task.objects.values(...).distinct()`` (the old DB-hot path) 42 must never be called.""" 43 fake_actors = { 44 "a": _FakeActor("default", "a"), 45 "b": _FakeActor("default", "b"), 46 } 47 task_objects = mock.MagicMock() 48 # Empty result for the remaining filter-based query. 49 task_objects.filter.return_value.values.return_value.annotate.return_value = [] 50 51 _, mock_task, _ = self._run_handler(fake_actors, task_objects) 52 53 # ``values`` called without going through ``filter`` first means 54 # something is enumerating the whole table. 55 for call in mock_task.objects.values.call_args_list: 56 self.fail( 57 f"Task.objects.values{call} was called directly — " 58 "this would issue a full-table SELECT DISTINCT." 59 ) 60 61 def test_gauges_set_for_every_registered_actor(self): 62 """Every actor registered with the broker has its gauge initialized 63 to 0 so prometheus shows the actor's existence even when no tasks 64 are queued for it.""" 65 fake_actors = { 66 "actor_a": _FakeActor("queue_x", "actor_a"), 67 "actor_b": _FakeActor("queue_y", "actor_b"), 68 "actor_c": _FakeActor("queue_x", "actor_c"), 69 } 70 task_objects = mock.MagicMock() 71 task_objects.filter.return_value.values.return_value.annotate.return_value = [] 72 73 _, _, mock_gauge = self._run_handler(fake_actors, task_objects) 74 75 labeled_combos = {(c.args[0], c.args[1]) for c in mock_gauge.labels.call_args_list} 76 expected_combos = {(actor.queue_name, actor.actor_name) for actor in fake_actors.values()} 77 self.assertEqual(labeled_combos, expected_combos) 78 for child_call in mock_gauge.labels.return_value.set.call_args_list: 79 self.assertEqual(child_call.args, (0,)) 80 81 def test_queued_count_query_uses_filter_state_queued(self): 82 """The remaining DB query goes through ``.filter(state=QUEUED)`` so 83 it can use the ``(queue_name, state)`` index.""" 84 from django_dramatiq_postgres.models import TaskState 85 86 fake_actors = {"a": _FakeActor("default", "a")} 87 task_objects = mock.MagicMock() 88 task_objects.filter.return_value.values.return_value.annotate.return_value = [ 89 {"queue_name": "default", "actor_name": "a", "count": 5}, 90 ] 91 92 _, mock_task, mock_gauge = self._run_handler(fake_actors, task_objects) 93 94 mock_task.objects.filter.assert_called_once_with(state=TaskState.QUEUED) 95 mock_gauge.labels.return_value.set.assert_any_call(5)
The handler must not full-scan authentik_tasks_task.
40 def test_does_not_call_values_distinct_on_task_objects(self): 41 """Direct ``Task.objects.values(...).distinct()`` (the old DB-hot path) 42 must never be called.""" 43 fake_actors = { 44 "a": _FakeActor("default", "a"), 45 "b": _FakeActor("default", "b"), 46 } 47 task_objects = mock.MagicMock() 48 # Empty result for the remaining filter-based query. 49 task_objects.filter.return_value.values.return_value.annotate.return_value = [] 50 51 _, mock_task, _ = self._run_handler(fake_actors, task_objects) 52 53 # ``values`` called without going through ``filter`` first means 54 # something is enumerating the whole table. 55 for call in mock_task.objects.values.call_args_list: 56 self.fail( 57 f"Task.objects.values{call} was called directly — " 58 "this would issue a full-table SELECT DISTINCT." 59 )
Direct Task.objects.values(...).distinct() (the old DB-hot path)
must never be called.
61 def test_gauges_set_for_every_registered_actor(self): 62 """Every actor registered with the broker has its gauge initialized 63 to 0 so prometheus shows the actor's existence even when no tasks 64 are queued for it.""" 65 fake_actors = { 66 "actor_a": _FakeActor("queue_x", "actor_a"), 67 "actor_b": _FakeActor("queue_y", "actor_b"), 68 "actor_c": _FakeActor("queue_x", "actor_c"), 69 } 70 task_objects = mock.MagicMock() 71 task_objects.filter.return_value.values.return_value.annotate.return_value = [] 72 73 _, _, mock_gauge = self._run_handler(fake_actors, task_objects) 74 75 labeled_combos = {(c.args[0], c.args[1]) for c in mock_gauge.labels.call_args_list} 76 expected_combos = {(actor.queue_name, actor.actor_name) for actor in fake_actors.values()} 77 self.assertEqual(labeled_combos, expected_combos) 78 for child_call in mock_gauge.labels.return_value.set.call_args_list: 79 self.assertEqual(child_call.args, (0,))
Every actor registered with the broker has its gauge initialized to 0 so prometheus shows the actor's existence even when no tasks are queued for it.
81 def test_queued_count_query_uses_filter_state_queued(self): 82 """The remaining DB query goes through ``.filter(state=QUEUED)`` so 83 it can use the ``(queue_name, state)`` index.""" 84 from django_dramatiq_postgres.models import TaskState 85 86 fake_actors = {"a": _FakeActor("default", "a")} 87 task_objects = mock.MagicMock() 88 task_objects.filter.return_value.values.return_value.annotate.return_value = [ 89 {"queue_name": "default", "actor_name": "a", "count": 5}, 90 ] 91 92 _, mock_task, mock_gauge = self._run_handler(fake_actors, task_objects) 93 94 mock_task.objects.filter.assert_called_once_with(state=TaskState.QUEUED) 95 mock_gauge.labels.return_value.set.assert_any_call(5)
The remaining DB query goes through .filter(state=QUEUED) so
it can use the (queue_name, state) index.
98class TestMonitoringSetWorkers(TestCase): 99 """Tests for worker-count gauge refreshes.""" 100 101 def _scrape(self, signals, gauges, versions): 102 """Run the handler with ``versions`` as the currently-live workers.""" 103 worker_status = mock.Mock() 104 worker_status.objects.filter.return_value = [ 105 SimpleNamespace(version=version) for version in versions 106 ] 107 with ( 108 mock.patch.object(signals, "authentik_full_version", return_value="2026.5.6"), 109 mock.patch.object(signals, "WorkerStatus", worker_status), 110 mock.patch.object(signals, "OLD_GAUGE_WORKERS", gauges[0]), 111 mock.patch.object(signals, "GAUGE_WORKERS", gauges[1]), 112 ): 113 signals.monitoring_set_workers(sender=self) 114 return { 115 gauge._name: { 116 (s.labels["version"], s.labels["version_matched"]): s.value 117 for metric in gauge.collect() 118 for s in metric.samples 119 } 120 for gauge in gauges 121 } 122 123 def test_obsolete_version_labels_are_reset(self): 124 """A version that no longer has any WorkerStatus row is reported as zero. 125 126 The gauges are exported through prometheus' multiprocess collector, where a labelset 127 stays in the process' mmap file until it is overwritten — so it has to be zeroed 128 explicitly, and cannot be derived from the rows still in the database. 129 """ 130 from prometheus_client import Gauge 131 132 from authentik.tasks import signals 133 134 gauges = [ 135 Gauge( 136 name, 137 "test", 138 ["version", "version_matched"], 139 multiprocess_mode="livemostrecent", 140 registry=None, 141 ) 142 for name in ("test_admin_workers", "test_tasks_workers") 143 ] 144 145 samples = self._scrape(signals, gauges, ["2026.5.6", "2026.4.0"]) 146 for series in samples.values(): 147 self.assertEqual(series[("2026.5.6", "True")], 1) 148 self.assertEqual(series[("2026.4.0", "False")], 1) 149 150 # The 2026.4.0 worker is gone, and so is its WorkerStatus row 151 samples = self._scrape(signals, gauges, ["2026.5.6"]) 152 for series in samples.values(): 153 self.assertEqual(series[("2026.5.6", "True")], 1) 154 self.assertEqual(series[("2026.4.0", "False")], 0)
Tests for worker-count gauge refreshes.
123 def test_obsolete_version_labels_are_reset(self): 124 """A version that no longer has any WorkerStatus row is reported as zero. 125 126 The gauges are exported through prometheus' multiprocess collector, where a labelset 127 stays in the process' mmap file until it is overwritten — so it has to be zeroed 128 explicitly, and cannot be derived from the rows still in the database. 129 """ 130 from prometheus_client import Gauge 131 132 from authentik.tasks import signals 133 134 gauges = [ 135 Gauge( 136 name, 137 "test", 138 ["version", "version_matched"], 139 multiprocess_mode="livemostrecent", 140 registry=None, 141 ) 142 for name in ("test_admin_workers", "test_tasks_workers") 143 ] 144 145 samples = self._scrape(signals, gauges, ["2026.5.6", "2026.4.0"]) 146 for series in samples.values(): 147 self.assertEqual(series[("2026.5.6", "True")], 1) 148 self.assertEqual(series[("2026.4.0", "False")], 1) 149 150 # The 2026.4.0 worker is gone, and so is its WorkerStatus row 151 samples = self._scrape(signals, gauges, ["2026.5.6"]) 152 for series in samples.values(): 153 self.assertEqual(series[("2026.5.6", "True")], 1) 154 self.assertEqual(series[("2026.4.0", "False")], 0)
A version that no longer has any WorkerStatus row is reported as zero.
The gauges are exported through prometheus' multiprocess collector, where a labelset stays in the process' mmap file until it is overwritten — so it has to be zeroed explicitly, and cannot be derived from the rows still in the database.