We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
General system exception - Event Log
**Describe the bug**
Getting a "General system exception" in the Event log, after the user logged in

**To Reproduce**
Steps to reproduce the behavior:

1. Default [default-authentication-flow]
2. between default-authentication-identification and default-authentication-password there is a Prompt Stage with Checkbox ("I'm not a Robot")
3. User login
4. Exception in the Event Log

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
![image](https://github.com/goauthentik/authentik/assets/159008007/7ff5b83e-433e-472d-b403-3e526f51f3d0)
![image](https://github.com/goauthentik/authentik/assets/159008007/de46baf0-6d43-42dd-9649-99afb8d165aa)


**Logs**
Property Mappings Exception:

ExceptionTraceback (most recent call last):   File "/authentik/lib/expression/evaluator.py", line 198, in evaluate     ast_obj = self.compile(expression_source)               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   File "/authentik/lib/expression/evaluator.py", line 187, in compile     return compile(self.wrap_expression(expression, param_keys), self._filename, "exec")            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ builtins.IndentationError: expected an indented block after function definition on line 1 (Checkbox, line 3)
--


General system exception:

Traceback (most recent call last):
  File "/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py", line 494, in trace_task
    I, R, state, retval = on_error(task_request, exc)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py", line 399, in on_error
    R = I.handle_error_state(
        ^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py", line 178, in handle_error_state
    return {
           ^
  File "/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py", line 236, in handle_failure
    task.on_failure(exc, req.id, req.args, req.kwargs, einfo)
  File "/authentik/events/system_tasks.py", line 106, in on_failure
    DBSystemTask.objects.update_or_create(
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py", line 986, in update_or_create
    obj, created = self.select_for_update().get_or_create(
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py", line 955, in get_or_create
    return self.create(**params), True
           ^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py", line 679, in create
    obj.save(force_insert=True, using=self.db)
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py", line 822, in save
    self.save_base(
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py", line 909, in save_base
    updated = self._save_table(
              ^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py", line 1067, in _save_table
    results = self._do_insert(
              ^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py", line 1108, in _do_insert
    return manager._insert(
           ^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py", line 1847, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/models/sql/compiler.py", line 1823, in execute_sql
    cursor.execute(sql, params)
  File "/ak-root/venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__init__.py", line 641, in execute
    result = real_execute(self, sql, params)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/backends/utils.py", line 79, in execute
    return self._execute_with_wrappers(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/backends/utils.py", line 92, in _execute_with_wrappers
    return executor(sql, params, many, context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django/db/backends/utils.py", line 105, in _execute
    return self.cursor.execute(sql, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/django_prometheus/db/common.py", line 69, in execute
    return super().execute(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/cursor.py", line 728, in execute
    self._conn.wait(
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/connection.py", line 969, in wait
    return waiting.wait(gen, self.pgconn.socket, timeout=timeout)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "psycopg_c/_psycopg/waiting.pyx", line 190, in psycopg_c._psycopg.wait_c
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/cursor.py", line 210, in _execute_gen
    pgq = self._convert_query(query, params)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/client_cursor.py", line 79, in _convert_query
    pgq.convert(query, params)
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/_queries.py", line 213, in convert
    self.dump(vars)
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/_queries.py", line 223, in dump
    self.params = tuple(
                  ^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/_queries.py", line 224, in <genexpr>
    self._tx.as_literal(p) if p is not None else b"NULL" for p in params
    ^^^^^^^^^^^^^^^^^^^^^^
  File "psycopg_c/_psycopg/transform.pyx", line 206, in psycopg_c._psycopg.Transformer.as_literal
  File "psycopg_c/_psycopg/transform.pyx", line 215, in psycopg_c._psycopg.Transformer.as_literal
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/adapt.py", line 57, in quote
    value = self.dump(obj)
            ^^^^^^^^^^^^^^
  File "/ak-root/venv/lib/python3.12/site-packages/psycopg/types/json.py", line 151, in dump
    data = dumps(obj)
           ^^^^^^^^^^
  File "/usr/local/lib/python3.12/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/json/encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/json/encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
           ^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/json/encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
builtins.TypeError: Object of type UUID is not JSON serializable


General system exception:

Traceback (most recent call last):
builtins.TypeError: Object of type UUID is not JSON serializable

**Version and Deployment (please complete the following information):**

-   authentik version: 2024.2.0
-   Deployment: Docker

**Additional context**
Add any other context about the problem here.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `authentik/events/system_tasks.py`
Content:
```
1 """Monitored tasks"""
2 
3 from datetime import datetime, timedelta
4 from time import perf_counter
5 from typing import Any, Optional
6 
7 from django.utils.timezone import now
8 from django.utils.translation import gettext_lazy as _
9 from structlog.stdlib import get_logger
10 from tenant_schemas_celery.task import TenantTask
11 
12 from authentik.events.models import Event, EventAction
13 from authentik.events.models import SystemTask as DBSystemTask
14 from authentik.events.models import TaskStatus
15 from authentik.events.utils import sanitize_item
16 from authentik.lib.utils.errors import exception_to_string
17 
18 LOGGER = get_logger()
19 
20 
21 class SystemTask(TenantTask):
22     """Task which can save its state to the cache"""
23 
24     # For tasks that should only be listed if they failed, set this to False
25     save_on_success: bool
26 
27     _status: TaskStatus
28     _messages: list[str]
29 
30     _uid: Optional[str]
31     # Precise start time from perf_counter
32     _start_precise: Optional[float] = None
33     _start: Optional[datetime] = None
34 
35     def __init__(self, *args, **kwargs) -> None:
36         super().__init__(*args, **kwargs)
37         self._status = TaskStatus.SUCCESSFUL
38         self.save_on_success = True
39         self._uid = None
40         self._status = None
41         self._messages = []
42         self.result_timeout_hours = 6
43 
44     def set_uid(self, uid: str):
45         """Set UID, so in the case of an unexpected error its saved correctly"""
46         self._uid = uid
47 
48     def set_status(self, status: TaskStatus, *messages: str):
49         """Set result for current run, will overwrite previous result."""
50         self._status = status
51         self._messages = messages
52 
53     def set_error(self, exception: Exception):
54         """Set result to error and save exception"""
55         self._status = TaskStatus.ERROR
56         self._messages = [exception_to_string(exception)]
57 
58     def before_start(self, task_id, args, kwargs):
59         self._start_precise = perf_counter()
60         self._start = now()
61         return super().before_start(task_id, args, kwargs)
62 
63     def db(self) -> Optional[DBSystemTask]:
64         """Get DB object for latest task"""
65         return DBSystemTask.objects.filter(
66             name=self.__name__,
67             uid=self._uid,
68         ).first()
69 
70     # pylint: disable=too-many-arguments
71     def after_return(self, status, retval, task_id, args: list[Any], kwargs: dict[str, Any], einfo):
72         super().after_return(status, retval, task_id, args, kwargs, einfo=einfo)
73         if not self._status:
74             return
75         if self._status == TaskStatus.SUCCESSFUL and not self.save_on_success:
76             DBSystemTask.objects.filter(
77                 name=self.__name__,
78                 uid=self._uid,
79             ).delete()
80             return
81         DBSystemTask.objects.update_or_create(
82             name=self.__name__,
83             uid=self._uid,
84             defaults={
85                 "description": self.__doc__,
86                 "start_timestamp": self._start or now(),
87                 "finish_timestamp": now(),
88                 "duration": max(perf_counter() - self._start_precise, 0),
89                 "task_call_module": self.__module__,
90                 "task_call_func": self.__name__,
91                 "task_call_args": args,
92                 "task_call_kwargs": kwargs,
93                 "status": self._status,
94                 "messages": sanitize_item(self._messages),
95                 "expires": now() + timedelta(hours=self.result_timeout_hours),
96                 "expiring": True,
97             },
98         )
99 
100     # pylint: disable=too-many-arguments
101     def on_failure(self, exc, task_id, args, kwargs, einfo):
102         super().on_failure(exc, task_id, args, kwargs, einfo=einfo)
103         if not self._status:
104             self._status = TaskStatus.ERROR
105             self._messages = exception_to_string(exc)
106         DBSystemTask.objects.update_or_create(
107             name=self.__name__,
108             uid=self._uid,
109             defaults={
110                 "description": self.__doc__,
111                 "start_timestamp": self._start or now(),
112                 "finish_timestamp": now(),
113                 "duration": max(perf_counter() - self._start_precise, 0),
114                 "task_call_module": self.__module__,
115                 "task_call_func": self.__name__,
116                 "task_call_args": args,
117                 "task_call_kwargs": kwargs,
118                 "status": self._status,
119                 "messages": sanitize_item(self._messages),
120                 "expires": now() + timedelta(hours=self.result_timeout_hours),
121                 "expiring": True,
122             },
123         )
124         Event.new(
125             EventAction.SYSTEM_TASK_EXCEPTION,
126             message=f"Task {self.__name__} encountered an error: {exception_to_string(exc)}",
127         ).save()
128 
129     def run(self, *args, **kwargs):
130         raise NotImplementedError
131 
132 
133 def prefill_task(func):
134     """Ensure a task's details are always in cache, so it can always be triggered via API"""
135     _prefill_tasks.append(
136         DBSystemTask(
137             name=func.__name__,
138             description=func.__doc__,
139             start_timestamp=now(),
140             finish_timestamp=now(),
141             status=TaskStatus.UNKNOWN,
142             messages=sanitize_item([_("Task has not been run yet.")]),
143             task_call_module=func.__module__,
144             task_call_func=func.__name__,
145             expiring=False,
146             duration=0,
147         )
148     )
149     return func
150 
151 
152 _prefill_tasks = []
153
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/authentik/events/system_tasks.py b/authentik/events/system_tasks.py
--- a/authentik/events/system_tasks.py
+++ b/authentik/events/system_tasks.py
@@ -88,8 +88,8 @@
                 "duration": max(perf_counter() - self._start_precise, 0),
                 "task_call_module": self.__module__,
                 "task_call_func": self.__name__,
-                "task_call_args": args,
-                "task_call_kwargs": kwargs,
+                "task_call_args": sanitize_item(args),
+                "task_call_kwargs": sanitize_item(kwargs),
                 "status": self._status,
                 "messages": sanitize_item(self._messages),
                 "expires": now() + timedelta(hours=self.result_timeout_hours),
@@ -113,8 +113,8 @@
                 "duration": max(perf_counter() - self._start_precise, 0),
                 "task_call_module": self.__module__,
                 "task_call_func": self.__name__,
-                "task_call_args": args,
-                "task_call_kwargs": kwargs,
+                "task_call_args": sanitize_item(args),
+                "task_call_kwargs": sanitize_item(kwargs),
                 "status": self._status,
                 "messages": sanitize_item(self._messages),
                 "expires": now() + timedelta(hours=self.result_timeout_hours),

{"golden_diff": "diff --git a/authentik/events/system_tasks.py b/authentik/events/system_tasks.py\n--- a/authentik/events/system_tasks.py\n+++ b/authentik/events/system_tasks.py\n@@ -88,8 +88,8 @@\n                 \"duration\": max(perf_counter() - self._start_precise, 0),\n                 \"task_call_module\": self.__module__,\n                 \"task_call_func\": self.__name__,\n-                \"task_call_args\": args,\n-                \"task_call_kwargs\": kwargs,\n+                \"task_call_args\": sanitize_item(args),\n+                \"task_call_kwargs\": sanitize_item(kwargs),\n                 \"status\": self._status,\n                 \"messages\": sanitize_item(self._messages),\n                 \"expires\": now() + timedelta(hours=self.result_timeout_hours),\n@@ -113,8 +113,8 @@\n                 \"duration\": max(perf_counter() - self._start_precise, 0),\n                 \"task_call_module\": self.__module__,\n                 \"task_call_func\": self.__name__,\n-                \"task_call_args\": args,\n-                \"task_call_kwargs\": kwargs,\n+                \"task_call_args\": sanitize_item(args),\n+                \"task_call_kwargs\": sanitize_item(kwargs),\n                 \"status\": self._status,\n                 \"messages\": sanitize_item(self._messages),\n                 \"expires\": now() + timedelta(hours=self.result_timeout_hours),\n", "issue": "General system exception - Event Log\n**Describe the bug**\r\nGetting a \"General system exception\" in the Event log, after the user logged in\r\n\r\n**To Reproduce**\r\nSteps to reproduce the behavior:\r\n\r\n1. Default [default-authentication-flow]\r\n2. between default-authentication-identification and default-authentication-password there is a Prompt Stage with Checkbox (\"I'm not a Robot\")\r\n3. User login\r\n4. Exception in the Event Log\r\n\r\n**Expected behavior**\r\nA clear and concise description of what you expected to happen.\r\n\r\n**Screenshots**\r\n![image](https://github.com/goauthentik/authentik/assets/159008007/7ff5b83e-433e-472d-b403-3e526f51f3d0)\r\n![image](https://github.com/goauthentik/authentik/assets/159008007/de46baf0-6d43-42dd-9649-99afb8d165aa)\r\n\r\n\r\n**Logs**\r\nProperty Mappings Exception:\r\n\r\nExceptionTraceback (most recent call last):   File \"/authentik/lib/expression/evaluator.py\", line 198, in evaluate     ast_obj = self.compile(expression_source)               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   File \"/authentik/lib/expression/evaluator.py\", line 187, in compile     return compile(self.wrap_expression(expression, param_keys), self._filename, \"exec\")            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ builtins.IndentationError: expected an indented block after function definition on line 1 (Checkbox, line 3)\r\n--\r\n\r\n\r\nGeneral system exception:\r\n\r\nTraceback (most recent call last):\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py\", line 494, in trace_task\r\n    I, R, state, retval = on_error(task_request, exc)\r\n                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py\", line 399, in on_error\r\n    R = I.handle_error_state(\r\n        ^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py\", line 178, in handle_error_state\r\n    return {\r\n           ^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/celery/app/trace.py\", line 236, in handle_failure\r\n    task.on_failure(exc, req.id, req.args, req.kwargs, einfo)\r\n  File \"/authentik/events/system_tasks.py\", line 106, in on_failure\r\n    DBSystemTask.objects.update_or_create(\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/manager.py\", line 87, in manager_method\r\n    return getattr(self.get_queryset(), name)(*args, **kwargs)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py\", line 986, in update_or_create\r\n    obj, created = self.select_for_update().get_or_create(\r\n                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py\", line 955, in get_or_create\r\n    return self.create(**params), True\r\n           ^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py\", line 679, in create\r\n    obj.save(force_insert=True, using=self.db)\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py\", line 822, in save\r\n    self.save_base(\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py\", line 909, in save_base\r\n    updated = self._save_table(\r\n              ^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py\", line 1067, in _save_table\r\n    results = self._do_insert(\r\n              ^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/base.py\", line 1108, in _do_insert\r\n    return manager._insert(\r\n           ^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/manager.py\", line 87, in manager_method\r\n    return getattr(self.get_queryset(), name)(*args, **kwargs)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/query.py\", line 1847, in _insert\r\n    return query.get_compiler(using=using).execute_sql(returning_fields)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/models/sql/compiler.py\", line 1823, in execute_sql\r\n    cursor.execute(sql, params)\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/sentry_sdk/integrations/django/__init__.py\", line 641, in execute\r\n    result = real_execute(self, sql, params)\r\n             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/backends/utils.py\", line 79, in execute\r\n    return self._execute_with_wrappers(\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/backends/utils.py\", line 92, in _execute_with_wrappers\r\n    return executor(sql, params, many, context)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django/db/backends/utils.py\", line 105, in _execute\r\n    return self.cursor.execute(sql, params)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/django_prometheus/db/common.py\", line 69, in execute\r\n    return super().execute(*args, **kwargs)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/cursor.py\", line 728, in execute\r\n    self._conn.wait(\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/connection.py\", line 969, in wait\r\n    return waiting.wait(gen, self.pgconn.socket, timeout=timeout)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"psycopg_c/_psycopg/waiting.pyx\", line 190, in psycopg_c._psycopg.wait_c\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/cursor.py\", line 210, in _execute_gen\r\n    pgq = self._convert_query(query, params)\r\n          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/client_cursor.py\", line 79, in _convert_query\r\n    pgq.convert(query, params)\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/_queries.py\", line 213, in convert\r\n    self.dump(vars)\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/_queries.py\", line 223, in dump\r\n    self.params = tuple(\r\n                  ^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/_queries.py\", line 224, in <genexpr>\r\n    self._tx.as_literal(p) if p is not None else b\"NULL\" for p in params\r\n    ^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"psycopg_c/_psycopg/transform.pyx\", line 206, in psycopg_c._psycopg.Transformer.as_literal\r\n  File \"psycopg_c/_psycopg/transform.pyx\", line 215, in psycopg_c._psycopg.Transformer.as_literal\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/adapt.py\", line 57, in quote\r\n    value = self.dump(obj)\r\n            ^^^^^^^^^^^^^^\r\n  File \"/ak-root/venv/lib/python3.12/site-packages/psycopg/types/json.py\", line 151, in dump\r\n    data = dumps(obj)\r\n           ^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/json/__init__.py\", line 231, in dumps\r\n    return _default_encoder.encode(obj)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/json/encoder.py\", line 200, in encode\r\n    chunks = self.iterencode(o, _one_shot=True)\r\n             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/json/encoder.py\", line 258, in iterencode\r\n    return _iterencode(o, 0)\r\n           ^^^^^^^^^^^^^^^^^\r\n  File \"/usr/local/lib/python3.12/json/encoder.py\", line 180, in default\r\n    raise TypeError(f'Object of type {o.__class__.__name__} '\r\nbuiltins.TypeError: Object of type UUID is not JSON serializable\r\n\r\n\r\nGeneral system exception:\r\n\r\nTraceback (most recent call last):\r\nbuiltins.TypeError: Object of type UUID is not JSON serializable\r\n\r\n**Version and Deployment (please complete the following information):**\r\n\r\n-   authentik version: 2024.2.0\r\n-   Deployment: Docker\r\n\r\n**Additional context**\r\nAdd any other context about the problem here.\r\n\n", "before_files": [{"content": "\"\"\"Monitored tasks\"\"\"\n\nfrom datetime import datetime, timedelta\nfrom time import perf_counter\nfrom typing import Any, Optional\n\nfrom django.utils.timezone import now\nfrom django.utils.translation import gettext_lazy as _\nfrom structlog.stdlib import get_logger\nfrom tenant_schemas_celery.task import TenantTask\n\nfrom authentik.events.models import Event, EventAction\nfrom authentik.events.models import SystemTask as DBSystemTask\nfrom authentik.events.models import TaskStatus\nfrom authentik.events.utils import sanitize_item\nfrom authentik.lib.utils.errors import exception_to_string\n\nLOGGER = get_logger()\n\n\nclass SystemTask(TenantTask):\n    \"\"\"Task which can save its state to the cache\"\"\"\n\n    # For tasks that should only be listed if they failed, set this to False\n    save_on_success: bool\n\n    _status: TaskStatus\n    _messages: list[str]\n\n    _uid: Optional[str]\n    # Precise start time from perf_counter\n    _start_precise: Optional[float] = None\n    _start: Optional[datetime] = None\n\n    def __init__(self, *args, **kwargs) -> None:\n        super().__init__(*args, **kwargs)\n        self._status = TaskStatus.SUCCESSFUL\n        self.save_on_success = True\n        self._uid = None\n        self._status = None\n        self._messages = []\n        self.result_timeout_hours = 6\n\n    def set_uid(self, uid: str):\n        \"\"\"Set UID, so in the case of an unexpected error its saved correctly\"\"\"\n        self._uid = uid\n\n    def set_status(self, status: TaskStatus, *messages: str):\n        \"\"\"Set result for current run, will overwrite previous result.\"\"\"\n        self._status = status\n        self._messages = messages\n\n    def set_error(self, exception: Exception):\n        \"\"\"Set result to error and save exception\"\"\"\n        self._status = TaskStatus.ERROR\n        self._messages = [exception_to_string(exception)]\n\n    def before_start(self, task_id, args, kwargs):\n        self._start_precise = perf_counter()\n        self._start = now()\n        return super().before_start(task_id, args, kwargs)\n\n    def db(self) -> Optional[DBSystemTask]:\n        \"\"\"Get DB object for latest task\"\"\"\n        return DBSystemTask.objects.filter(\n            name=self.__name__,\n            uid=self._uid,\n        ).first()\n\n    # pylint: disable=too-many-arguments\n    def after_return(self, status, retval, task_id, args: list[Any], kwargs: dict[str, Any], einfo):\n        super().after_return(status, retval, task_id, args, kwargs, einfo=einfo)\n        if not self._status:\n            return\n        if self._status == TaskStatus.SUCCESSFUL and not self.save_on_success:\n            DBSystemTask.objects.filter(\n                name=self.__name__,\n                uid=self._uid,\n            ).delete()\n            return\n        DBSystemTask.objects.update_or_create(\n            name=self.__name__,\n            uid=self._uid,\n            defaults={\n                \"description\": self.__doc__,\n                \"start_timestamp\": self._start or now(),\n                \"finish_timestamp\": now(),\n                \"duration\": max(perf_counter() - self._start_precise, 0),\n                \"task_call_module\": self.__module__,\n                \"task_call_func\": self.__name__,\n                \"task_call_args\": args,\n                \"task_call_kwargs\": kwargs,\n                \"status\": self._status,\n                \"messages\": sanitize_item(self._messages),\n                \"expires\": now() + timedelta(hours=self.result_timeout_hours),\n                \"expiring\": True,\n            },\n        )\n\n    # pylint: disable=too-many-arguments\n    def on_failure(self, exc, task_id, args, kwargs, einfo):\n        super().on_failure(exc, task_id, args, kwargs, einfo=einfo)\n        if not self._status:\n            self._status = TaskStatus.ERROR\n            self._messages = exception_to_string(exc)\n        DBSystemTask.objects.update_or_create(\n            name=self.__name__,\n            uid=self._uid,\n            defaults={\n                \"description\": self.__doc__,\n                \"start_timestamp\": self._start or now(),\n                \"finish_timestamp\": now(),\n                \"duration\": max(perf_counter() - self._start_precise, 0),\n                \"task_call_module\": self.__module__,\n                \"task_call_func\": self.__name__,\n                \"task_call_args\": args,\n                \"task_call_kwargs\": kwargs,\n                \"status\": self._status,\n                \"messages\": sanitize_item(self._messages),\n                \"expires\": now() + timedelta(hours=self.result_timeout_hours),\n                \"expiring\": True,\n            },\n        )\n        Event.new(\n            EventAction.SYSTEM_TASK_EXCEPTION,\n            message=f\"Task {self.__name__} encountered an error: {exception_to_string(exc)}\",\n        ).save()\n\n    def run(self, *args, **kwargs):\n        raise NotImplementedError\n\n\ndef prefill_task(func):\n    \"\"\"Ensure a task's details are always in cache, so it can always be triggered via API\"\"\"\n    _prefill_tasks.append(\n        DBSystemTask(\n            name=func.__name__,\n            description=func.__doc__,\n            start_timestamp=now(),\n            finish_timestamp=now(),\n            status=TaskStatus.UNKNOWN,\n            messages=sanitize_item([_(\"Task has not been run yet.\")]),\n            task_call_module=func.__module__,\n            task_call_func=func.__name__,\n            expiring=False,\n            duration=0,\n        )\n    )\n    return func\n\n\n_prefill_tasks = []\n", "path": "authentik/events/system_tasks.py"}], "after_files": [{"content": "\"\"\"Monitored tasks\"\"\"\n\nfrom datetime import datetime, timedelta\nfrom time import perf_counter\nfrom typing import Any, Optional\n\nfrom django.utils.timezone import now\nfrom django.utils.translation import gettext_lazy as _\nfrom structlog.stdlib import get_logger\nfrom tenant_schemas_celery.task import TenantTask\n\nfrom authentik.events.models import Event, EventAction\nfrom authentik.events.models import SystemTask as DBSystemTask\nfrom authentik.events.models import TaskStatus\nfrom authentik.events.utils import sanitize_item\nfrom authentik.lib.utils.errors import exception_to_string\n\nLOGGER = get_logger()\n\n\nclass SystemTask(TenantTask):\n    \"\"\"Task which can save its state to the cache\"\"\"\n\n    # For tasks that should only be listed if they failed, set this to False\n    save_on_success: bool\n\n    _status: TaskStatus\n    _messages: list[str]\n\n    _uid: Optional[str]\n    # Precise start time from perf_counter\n    _start_precise: Optional[float] = None\n    _start: Optional[datetime] = None\n\n    def __init__(self, *args, **kwargs) -> None:\n        super().__init__(*args, **kwargs)\n        self._status = TaskStatus.SUCCESSFUL\n        self.save_on_success = True\n        self._uid = None\n        self._status = None\n        self._messages = []\n        self.result_timeout_hours = 6\n\n    def set_uid(self, uid: str):\n        \"\"\"Set UID, so in the case of an unexpected error its saved correctly\"\"\"\n        self._uid = uid\n\n    def set_status(self, status: TaskStatus, *messages: str):\n        \"\"\"Set result for current run, will overwrite previous result.\"\"\"\n        self._status = status\n        self._messages = messages\n\n    def set_error(self, exception: Exception):\n        \"\"\"Set result to error and save exception\"\"\"\n        self._status = TaskStatus.ERROR\n        self._messages = [exception_to_string(exception)]\n\n    def before_start(self, task_id, args, kwargs):\n        self._start_precise = perf_counter()\n        self._start = now()\n        return super().before_start(task_id, args, kwargs)\n\n    def db(self) -> Optional[DBSystemTask]:\n        \"\"\"Get DB object for latest task\"\"\"\n        return DBSystemTask.objects.filter(\n            name=self.__name__,\n            uid=self._uid,\n        ).first()\n\n    # pylint: disable=too-many-arguments\n    def after_return(self, status, retval, task_id, args: list[Any], kwargs: dict[str, Any], einfo):\n        super().after_return(status, retval, task_id, args, kwargs, einfo=einfo)\n        if not self._status:\n            return\n        if self._status == TaskStatus.SUCCESSFUL and not self.save_on_success:\n            DBSystemTask.objects.filter(\n                name=self.__name__,\n                uid=self._uid,\n            ).delete()\n            return\n        DBSystemTask.objects.update_or_create(\n            name=self.__name__,\n            uid=self._uid,\n            defaults={\n                \"description\": self.__doc__,\n                \"start_timestamp\": self._start or now(),\n                \"finish_timestamp\": now(),\n                \"duration\": max(perf_counter() - self._start_precise, 0),\n                \"task_call_module\": self.__module__,\n                \"task_call_func\": self.__name__,\n                \"task_call_args\": sanitize_item(args),\n                \"task_call_kwargs\": sanitize_item(kwargs),\n                \"status\": self._status,\n                \"messages\": sanitize_item(self._messages),\n                \"expires\": now() + timedelta(hours=self.result_timeout_hours),\n                \"expiring\": True,\n            },\n        )\n\n    # pylint: disable=too-many-arguments\n    def on_failure(self, exc, task_id, args, kwargs, einfo):\n        super().on_failure(exc, task_id, args, kwargs, einfo=einfo)\n        if not self._status:\n            self._status = TaskStatus.ERROR\n            self._messages = exception_to_string(exc)\n        DBSystemTask.objects.update_or_create(\n            name=self.__name__,\n            uid=self._uid,\n            defaults={\n                \"description\": self.__doc__,\n                \"start_timestamp\": self._start or now(),\n                \"finish_timestamp\": now(),\n                \"duration\": max(perf_counter() - self._start_precise, 0),\n                \"task_call_module\": self.__module__,\n                \"task_call_func\": self.__name__,\n                \"task_call_args\": sanitize_item(args),\n                \"task_call_kwargs\": sanitize_item(kwargs),\n                \"status\": self._status,\n                \"messages\": sanitize_item(self._messages),\n                \"expires\": now() + timedelta(hours=self.result_timeout_hours),\n                \"expiring\": True,\n            },\n        )\n        Event.new(\n            EventAction.SYSTEM_TASK_EXCEPTION,\n            message=f\"Task {self.__name__} encountered an error: {exception_to_string(exc)}\",\n        ).save()\n\n    def run(self, *args, **kwargs):\n        raise NotImplementedError\n\n\ndef prefill_task(func):\n    \"\"\"Ensure a task's details are always in cache, so it can always be triggered via API\"\"\"\n    _prefill_tasks.append(\n        DBSystemTask(\n            name=func.__name__,\n            description=func.__doc__,\n            start_timestamp=now(),\n            finish_timestamp=now(),\n            status=TaskStatus.UNKNOWN,\n            messages=sanitize_item([_(\"Task has not been run yet.\")]),\n            task_call_module=func.__module__,\n            task_call_func=func.__name__,\n            expiring=False,\n            duration=0,\n        )\n    )\n    return func\n\n\n_prefill_tasks = []\n", "path": "authentik/events/system_tasks.py"}]}