sqlalchemy-audit-trail 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/PKG-INFO +22 -2
  2. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/README.md +21 -1
  3. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/__init__.py +4 -0
  4. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/config.py +53 -10
  5. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/integrations/fastapi.py +7 -1
  6. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/privacy.py +76 -7
  7. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/query.py +3 -1
  8. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/writer.py +38 -3
  9. sqlalchemy_audit_trail-0.2.0/benchmark/README.md +283 -0
  10. sqlalchemy_audit_trail-0.2.0/examples/fastapi_app/README.md +133 -0
  11. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/pyproject.toml +2 -2
  12. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/.gitignore +0 -0
  13. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/LICENSE +0 -0
  14. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/_compaction.py +0 -0
  15. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/_typing.py +0 -0
  16. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/checks.py +0 -0
  17. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/context.py +0 -0
  18. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/diff.py +0 -0
  19. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/events.py +0 -0
  20. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/integrations/__init__.py +0 -0
  21. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/listener.py +0 -0
  22. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/maintenance.py +0 -0
  23. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/migrations.py +0 -0
  24. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/mixin.py +0 -0
  25. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/py.typed +0 -0
  26. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/pytest_plugin.py +0 -0
  27. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/relations.py +0 -0
  28. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/serialization.py +0 -0
  29. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/tables.py +0 -0
  30. {sqlalchemy_audit_trail-0.1.0 → sqlalchemy_audit_trail-0.2.0}/audit_trail/testing.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlalchemy-audit-trail
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log
5
5
  Project-URL: Homepage, https://github.com/WiktorB2004/sqlalchemy-audit-trail
6
6
  Project-URL: Repository, https://github.com/WiktorB2004/sqlalchemy-audit-trail
@@ -130,10 +130,22 @@ audit = AuditTrail(engine, events=[AuthEvent])
130
130
  audit.log(session, AuthEvent.LOGIN_FAILED, payload={"reason": "bad password"})
131
131
  ```
132
132
 
133
- Docs: [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/). Runnable, tested quickstarts for sync, async and FastAPI: [`examples/`](examples/).
133
+ Docs: [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/). Runnable, tested quickstarts for sync, async and FastAPI: [`examples/`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/tree/main/examples). A complete multi-tenant FastAPI app with login events, history, an activity feed and GDPR erasure, with a curl walkthrough: [`examples/fastapi_app`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/blob/main/examples/fastapi_app/README.md).
134
134
 
135
135
  Audit rows are written **in your transaction**: roll back and they are gone with the change. A failed audit write does not fail your transaction by default (`on_error="log"`). `durable` events are committed on their own connection and survive a rollback; `fail_closed` events raise `AuditWriteError` when they cannot be written.
136
136
 
137
+ ## Results
138
+
139
+ Measured on a laptop: PostgreSQL 18 in Docker with stock settings, one connection, synthetic data. Protocol, environment and limits: [`benchmark/README.md`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/blob/main/benchmark/README.md).
140
+
141
+ | What | Plain | Audited | Added |
142
+ | --- | ---: | ---: | ---: |
143
+ | flush of 1 object (p50) | 3.4 ms | 5.8 ms | **+2.4 ms** (+1.5 ms with `on_error="raise"`) |
144
+ | flush of 100 objects (p50) | 8.0 ms | 19.4 ms | **+11.4 ms**, about 114 µs per object |
145
+ | durable `log()` (p50) | | | +6.7 ms |
146
+
147
+ Reads on 5M entries in 80 partitions: the first page of `list_groups` takes **18.5 ms** at p50 (15.1 ms with a 30-day window), of which PostgreSQL spends under 1 ms; a next page reads **5 of 80** partitions. Queries with no time bound (`object_history`, `access_summary`, by `actor_id`) read every monthly partition and take 10 to 22 ms here.
148
+
137
149
  ## Why this instead of sqlalchemy-continuum, triggers or pgaudit
138
150
 
139
151
  [sqlalchemy-continuum](https://github.com/kvesteri/sqlalchemy-continuum) copies every changed row into a version table per model. That answers "what did this row look like then", but a login, a download or someone viewing sensitive data has no row to version. Database triggers and pgaudit see statements, not the application's user, request or intent.
@@ -191,6 +203,14 @@ uv run mkdocs serve
191
203
 
192
204
  Published at [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/).
193
205
 
206
+ ## Benchmark
207
+
208
+ The numbers above come from [`benchmark/`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/tree/main/benchmark). It needs Docker (or `--database-url`) and takes about 12 minutes:
209
+
210
+ ```bash
211
+ uv run python -m benchmark.run_benchmark
212
+ ```
213
+
194
214
  ## Contributing
195
215
 
196
216
  Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). To report a vulnerability, use [SECURITY.md](SECURITY.md).
@@ -88,10 +88,22 @@ audit = AuditTrail(engine, events=[AuthEvent])
88
88
  audit.log(session, AuthEvent.LOGIN_FAILED, payload={"reason": "bad password"})
89
89
  ```
90
90
 
91
- Docs: [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/). Runnable, tested quickstarts for sync, async and FastAPI: [`examples/`](examples/).
91
+ Docs: [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/). Runnable, tested quickstarts for sync, async and FastAPI: [`examples/`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/tree/main/examples). A complete multi-tenant FastAPI app with login events, history, an activity feed and GDPR erasure, with a curl walkthrough: [`examples/fastapi_app`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/blob/main/examples/fastapi_app/README.md).
92
92
 
93
93
  Audit rows are written **in your transaction**: roll back and they are gone with the change. A failed audit write does not fail your transaction by default (`on_error="log"`). `durable` events are committed on their own connection and survive a rollback; `fail_closed` events raise `AuditWriteError` when they cannot be written.
94
94
 
95
+ ## Results
96
+
97
+ Measured on a laptop: PostgreSQL 18 in Docker with stock settings, one connection, synthetic data. Protocol, environment and limits: [`benchmark/README.md`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/blob/main/benchmark/README.md).
98
+
99
+ | What | Plain | Audited | Added |
100
+ | --- | ---: | ---: | ---: |
101
+ | flush of 1 object (p50) | 3.4 ms | 5.8 ms | **+2.4 ms** (+1.5 ms with `on_error="raise"`) |
102
+ | flush of 100 objects (p50) | 8.0 ms | 19.4 ms | **+11.4 ms**, about 114 µs per object |
103
+ | durable `log()` (p50) | | | +6.7 ms |
104
+
105
+ Reads on 5M entries in 80 partitions: the first page of `list_groups` takes **18.5 ms** at p50 (15.1 ms with a 30-day window), of which PostgreSQL spends under 1 ms; a next page reads **5 of 80** partitions. Queries with no time bound (`object_history`, `access_summary`, by `actor_id`) read every monthly partition and take 10 to 22 ms here.
106
+
95
107
  ## Why this instead of sqlalchemy-continuum, triggers or pgaudit
96
108
 
97
109
  [sqlalchemy-continuum](https://github.com/kvesteri/sqlalchemy-continuum) copies every changed row into a version table per model. That answers "what did this row look like then", but a login, a download or someone viewing sensitive data has no row to version. Database triggers and pgaudit see statements, not the application's user, request or intent.
@@ -149,6 +161,14 @@ uv run mkdocs serve
149
161
 
150
162
  Published at [wiktorb2004.github.io/sqlalchemy-audit-trail](https://wiktorb2004.github.io/sqlalchemy-audit-trail/).
151
163
 
164
+ ## Benchmark
165
+
166
+ The numbers above come from [`benchmark/`](https://github.com/WiktorB2004/sqlalchemy-audit-trail/tree/main/benchmark). It needs Docker (or `--database-url`) and takes about 12 minutes:
167
+
168
+ ```bash
169
+ uv run python -m benchmark.run_benchmark
170
+ ```
171
+
152
172
  ## Contributing
153
173
 
154
174
  Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) and the [Code of Conduct](CODE_OF_CONDUCT.md). To report a vulnerability, use [SECURITY.md](SECURITY.md).
@@ -13,9 +13,11 @@ from audit_trail.privacy import ScrubNotAllowedError, ScrubResult
13
13
  from audit_trail.query import (
14
14
  ALL_HISTORY,
15
15
  AccessCount,
16
+ ActivityData,
16
17
  ActivityDetail,
17
18
  AllHistory,
18
19
  Cursor,
20
+ FieldChange,
19
21
  FieldLabels,
20
22
  Group,
21
23
  LabelResolver,
@@ -35,6 +37,7 @@ except PackageNotFoundError: # pragma: no cover - running from a source tree
35
37
  __all__ = [
36
38
  "ALL_HISTORY",
37
39
  "AccessCount",
40
+ "ActivityData",
38
41
  "ActivityDetail",
39
42
  "Actor",
40
43
  "AllHistory",
@@ -47,6 +50,7 @@ __all__ = [
47
50
  "AuditWriteError",
48
51
  "Audited",
49
52
  "Cursor",
53
+ "FieldChange",
50
54
  "FieldLabels",
51
55
  "FieldPolicyError",
52
56
  "Group",
@@ -554,7 +554,7 @@ class AuditTrail:
554
554
 
555
555
  from audit_trail.listener import PendingEntry, write_entries
556
556
  from audit_trail.writer import (
557
- DURABLE_WRITE_ERRORS,
557
+ async_durable_write_errors,
558
558
  handle_durable_failure,
559
559
  write_durable,
560
560
  )
@@ -593,7 +593,7 @@ class AuditTrail:
593
593
  [entry.entry],
594
594
  auto_create_partitions=self.auto_create_partitions,
595
595
  )
596
- except DURABLE_WRITE_ERRORS as exc:
596
+ except async_durable_write_errors() as exc:
597
597
  handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
598
598
 
599
599
  def scrub(
@@ -603,6 +603,7 @@ class AuditTrail:
603
603
  *,
604
604
  include_targets: bool = True,
605
605
  since: datetime | None = None,
606
+ scope_ids: Collection[str] | None = None,
606
607
  ) -> ScrubResult:
607
608
  """Erase the values the entries of one object hold.
608
609
 
@@ -623,6 +624,11 @@ class AuditTrail:
623
624
  such as changes of its children.
624
625
  since: Only entries created at or after this aware datetime,
625
626
  which also limits the partitions scanned. ``None`` for all.
627
+ scope_ids: Only entries whose ``scope_id`` is one of these, such
628
+ as the tenants of an admin. ``None`` for no restriction; an
629
+ empty collection erases nothing, and an entry without a
630
+ scope never matches a restriction. Recorded in the
631
+ ``audit.scrubbed`` entry.
626
632
 
627
633
  Returns:
628
634
  A ``ScrubResult``: ``activity_rows`` is the number of entries
@@ -631,7 +637,8 @@ class AuditTrail:
631
637
 
632
638
  Raises:
633
639
  ScrubNotAllowedError: ``allow_scrub`` is ``False``.
634
- TypeError: ``engine`` is async; use ``ascrub``.
640
+ TypeError: ``engine`` is async; use ``ascrub``; or
641
+ ``scope_ids`` is a ``str``.
635
642
  ValueError: ``since`` is naive, or ``engine`` is in
636
643
  ``AUTOCOMMIT`` mode.
637
644
  """
@@ -642,6 +649,7 @@ class AuditTrail:
642
649
  if not isinstance(engine, Engine):
643
650
  raise TypeError("the engine is async; use ascrub")
644
651
  privacy.check_since(since)
652
+ privacy.check_scope_ids(scope_ids)
645
653
  record = self._scrubbed_record()
646
654
  if self.auto_create_partitions:
647
655
  self.maintenance.ensure_partitions(months_ahead=0)
@@ -653,6 +661,7 @@ class AuditTrail:
653
661
  object_id,
654
662
  include_targets=include_targets,
655
663
  since=since,
664
+ scope_ids=scope_ids,
656
665
  record=record,
657
666
  )
658
667
 
@@ -663,6 +672,7 @@ class AuditTrail:
663
672
  *,
664
673
  include_targets: bool = True,
665
674
  since: datetime | None = None,
675
+ scope_ids: Collection[str] | None = None,
666
676
  ) -> ScrubResult:
667
677
  """Async ``scrub``, for an ``AuditTrail`` built with an ``AsyncEngine``.
668
678
 
@@ -671,13 +681,16 @@ class AuditTrail:
671
681
  object_id: Stored ``object_id`` of the object.
672
682
  include_targets: Also erase entries whose target is the object.
673
683
  since: Only entries created at or after this aware datetime.
684
+ scope_ids: Only entries with one of these ``scope_id`` values;
685
+ see ``scrub``.
674
686
 
675
687
  Returns:
676
688
  A ``ScrubResult``; see ``scrub``.
677
689
 
678
690
  Raises:
679
691
  ScrubNotAllowedError: ``allow_scrub`` is ``False``.
680
- TypeError: ``engine`` is sync; use ``scrub``.
692
+ TypeError: ``engine`` is sync; use ``scrub``; or ``scope_ids``
693
+ is a ``str``.
681
694
  ValueError: As for ``scrub``.
682
695
  """
683
696
  from audit_trail import privacy
@@ -687,6 +700,7 @@ class AuditTrail:
687
700
  if isinstance(engine, Engine):
688
701
  raise TypeError("the engine is sync; use scrub")
689
702
  privacy.check_since(since)
703
+ privacy.check_scope_ids(scope_ids)
690
704
  record = self._scrubbed_record()
691
705
  if self.auto_create_partitions:
692
706
  await self.maintenance.aensure_partitions(months_ahead=0)
@@ -699,11 +713,14 @@ class AuditTrail:
699
713
  object_id,
700
714
  include_targets=include_targets,
701
715
  since=since,
716
+ scope_ids=scope_ids,
702
717
  record=record,
703
718
  )
704
719
  )
705
720
 
706
- def scrub_actor(self, actor_id: str) -> ScrubResult:
721
+ def scrub_actor(
722
+ self, actor_id: str, *, scope_ids: Collection[str] | None = None
723
+ ) -> ScrubResult:
707
724
  """Clear the personal context stored for one actor.
708
725
 
709
726
  ``audit_transaction`` rows created with this ``actor_id`` get
@@ -715,8 +732,20 @@ class AuditTrail:
715
732
  and user agent on that row. Runs in one transaction on ``engine``
716
733
  with an ``audit.scrubbed`` entry, as ``scrub`` does.
717
734
 
735
+ With ``scope_ids``, only entries whose ``scope_id`` is one of them
736
+ lose the keys, and a transaction row is cleared only when it has
737
+ entries and all of them, whoever their actor, are in those scopes:
738
+ its fields are shared by all its entries, so a request that also
739
+ wrote entries of another scope or without one keeps them, as does a
740
+ transaction row without entries. Clearing an actor completely
741
+ across scopes takes a run without ``scope_ids``.
742
+
718
743
  Args:
719
744
  actor_id: The actor's ``actor_id``.
745
+ scope_ids: The scopes the scrub is restricted to, such as the
746
+ tenants of an admin. ``None`` for no restriction; an empty
747
+ collection changes nothing. Recorded in the
748
+ ``audit.scrubbed`` entry.
720
749
 
721
750
  Returns:
722
751
  A ``ScrubResult`` with the numbers of activity and transaction
@@ -724,7 +753,8 @@ class AuditTrail:
724
753
 
725
754
  Raises:
726
755
  ScrubNotAllowedError: ``allow_scrub`` is ``False``.
727
- TypeError: ``engine`` is async; use ``ascrub_actor``.
756
+ TypeError: ``engine`` is async; use ``ascrub_actor``; or
757
+ ``scope_ids`` is a ``str``.
728
758
  ValueError: ``engine`` is in ``AUTOCOMMIT`` mode.
729
759
  """
730
760
  from audit_trail import privacy
@@ -733,17 +763,24 @@ class AuditTrail:
733
763
  engine = self.engine
734
764
  if not isinstance(engine, Engine):
735
765
  raise TypeError("the engine is async; use ascrub_actor")
766
+ privacy.check_scope_ids(scope_ids)
736
767
  record = self._scrubbed_record()
737
768
  if self.auto_create_partitions:
738
769
  self.maintenance.ensure_partitions(months_ahead=0)
739
770
  with engine.begin() as conn:
740
- return privacy.scrub_actor(conn, self.tables, actor_id, record=record)
771
+ return privacy.scrub_actor(
772
+ conn, self.tables, actor_id, scope_ids=scope_ids, record=record
773
+ )
741
774
 
742
- async def ascrub_actor(self, actor_id: str) -> ScrubResult:
775
+ async def ascrub_actor(
776
+ self, actor_id: str, *, scope_ids: Collection[str] | None = None
777
+ ) -> ScrubResult:
743
778
  """Async ``scrub_actor``, for an ``AuditTrail`` built with an ``AsyncEngine``.
744
779
 
745
780
  Args:
746
781
  actor_id: The actor's ``actor_id``.
782
+ scope_ids: The scopes the scrub is restricted to; see
783
+ ``scrub_actor``.
747
784
 
748
785
  Returns:
749
786
  A ``ScrubResult`` with the numbers of activity and transaction
@@ -751,7 +788,8 @@ class AuditTrail:
751
788
 
752
789
  Raises:
753
790
  ScrubNotAllowedError: ``allow_scrub`` is ``False``.
754
- TypeError: ``engine`` is sync; use ``scrub_actor``.
791
+ TypeError: ``engine`` is sync; use ``scrub_actor``; or
792
+ ``scope_ids`` is a ``str``.
755
793
  ValueError: ``engine`` is in ``AUTOCOMMIT`` mode.
756
794
  """
757
795
  from audit_trail import privacy
@@ -760,13 +798,18 @@ class AuditTrail:
760
798
  engine = self.engine
761
799
  if isinstance(engine, Engine):
762
800
  raise TypeError("the engine is sync; use scrub_actor")
801
+ privacy.check_scope_ids(scope_ids)
763
802
  record = self._scrubbed_record()
764
803
  if self.auto_create_partitions:
765
804
  await self.maintenance.aensure_partitions(months_ahead=0)
766
805
  async with engine.begin() as conn:
767
806
  return await conn.run_sync(
768
807
  lambda sync_conn: privacy.scrub_actor(
769
- sync_conn, self.tables, actor_id, record=record
808
+ sync_conn,
809
+ self.tables,
810
+ actor_id,
811
+ scope_ids=scope_ids,
812
+ record=record,
770
813
  )
771
814
  )
772
815
 
@@ -260,7 +260,9 @@ def session_provider() -> Session | AsyncSession | None:
260
260
  return None if state is None else state.session
261
261
 
262
262
 
263
- def set_actor(actor: Actor, *, auth_method: str | None = None) -> AuditContext:
263
+ def set_actor(
264
+ actor: Actor, *, auth_method: str | None = None, scope_id: str | None = None
265
+ ) -> AuditContext:
264
266
  """Set the actor of the current request, after authentication.
265
267
 
266
268
  Updates the request's context (the one ``AuditMiddleware`` activated) in
@@ -271,6 +273,8 @@ def set_actor(actor: Actor, *, auth_method: str | None = None) -> AuditContext:
271
273
  Args:
272
274
  actor: The actor. All three actor fields are overwritten.
273
275
  auth_method: How the actor authenticated, stored when given.
276
+ scope_id: Scope (such as the tenant) of the request's entries,
277
+ stored when given; ``None`` keeps the current one.
274
278
 
275
279
  Returns:
276
280
  The request's context.
@@ -288,6 +292,8 @@ def set_actor(actor: Actor, *, auth_method: str | None = None) -> AuditContext:
288
292
  ctx.actor_label = actor.label
289
293
  if auth_method is not None:
290
294
  ctx.auth_method = auth_method
295
+ if scope_id is not None:
296
+ ctx.scope_id = scope_id
291
297
  return ctx
292
298
 
293
299
 
@@ -11,18 +11,21 @@ from __future__ import annotations
11
11
 
12
12
  import dataclasses
13
13
  import json
14
- from collections.abc import Callable
14
+ from collections.abc import Callable, Collection
15
15
  from datetime import datetime
16
16
  from typing import TYPE_CHECKING, NamedTuple
17
17
 
18
18
  from sqlalchemy import (
19
+ ColumnElement,
19
20
  Connection,
20
21
  Text,
21
22
  Update,
22
23
  and_,
24
+ exists,
23
25
  false,
24
26
  func,
25
27
  literal_column,
28
+ not_,
26
29
  null,
27
30
  or_,
28
31
  update,
@@ -32,6 +35,7 @@ from sqlalchemy.dialects.postgresql import ARRAY, JSONB
32
35
  from audit_trail.context import AuditContext, current_context
33
36
  from audit_trail.diff import ERASED
34
37
  from audit_trail.events import AuditSystem
38
+ from audit_trail.query import _check_collection, _member_of
35
39
  from audit_trail.writer import (
36
40
  ENVELOPE_VERSION,
37
41
  Entry,
@@ -163,6 +167,18 @@ def check_since(since: datetime | None) -> None:
163
167
  raise ValueError("since must be timezone-aware")
164
168
 
165
169
 
170
+ def check_scope_ids(scope_ids: Collection[str] | None) -> None:
171
+ """Refuse a ``str`` as ``scope_ids``, which would be read as its letters.
172
+
173
+ Args:
174
+ scope_ids: The scope restriction, or ``None``.
175
+
176
+ Raises:
177
+ TypeError: ``scope_ids`` is a ``str``.
178
+ """
179
+ _check_collection(scope_ids, "scope_ids")
180
+
181
+
166
182
  def scrub_context(
167
183
  context_provider: Callable[[], AuditContext | None] | None,
168
184
  ) -> AuditContext:
@@ -190,6 +206,7 @@ def scrub_statement(
190
206
  *,
191
207
  include_targets: bool,
192
208
  since: datetime | None,
209
+ scope_ids: Collection[str] | None = None,
193
210
  ) -> Update:
194
211
  """Build the ``UPDATE`` that erases the entries of one object.
195
212
 
@@ -199,6 +216,9 @@ def scrub_statement(
199
216
  object_id: Stored ``object_id`` of the object.
200
217
  include_targets: Also erase entries whose target is the object.
201
218
  since: Only entries with ``created_at >= since``; ``None`` for all.
219
+ scope_ids: Only entries whose ``scope_id`` is one of these; ``None``
220
+ for all, empty for none. Entries without a scope never match a
221
+ restriction.
202
222
 
203
223
  Returns:
204
224
  The statement; its rowcount is the number of rows erased.
@@ -211,6 +231,9 @@ def scrub_statement(
211
231
  conditions = [match, c.verb.not_in(_LIBRARY_VERBS)]
212
232
  if since is not None:
213
233
  conditions.append(c.created_at >= since)
234
+ in_scope = _member_of(c.scope_id, scope_ids)
235
+ if in_scope is not None:
236
+ conditions.append(in_scope)
214
237
  # Rows already erased are left alone, so a repeated scrub changes nothing.
215
238
  conditions.append(or_(c.object_label.is_not(None), c.data.is_distinct_from(erased)))
216
239
  return (
@@ -228,6 +251,7 @@ def scrub(
228
251
  *,
229
252
  include_targets: bool,
230
253
  since: datetime | None,
254
+ scope_ids: Collection[str] | None,
231
255
  record: ScrubbedRecord,
232
256
  ) -> ScrubResult:
233
257
  """Erase the values an object's entries hold, and record it.
@@ -241,6 +265,10 @@ def scrub(
241
265
  erased; a payload value is erased whole, including anything nested in
242
266
  it. ``data.context`` is left to ``scrub_actor``.
243
267
 
268
+ With ``scope_ids``, only entries whose ``scope_id`` is one of them are
269
+ erased: an empty collection erases nothing, and an entry without a scope
270
+ never matches. The ``audit.scrubbed`` entry records the restriction.
271
+
244
272
  Runs in the connection's current transaction; the caller commits.
245
273
 
246
274
  Args:
@@ -251,6 +279,8 @@ def scrub(
251
279
  include_targets: Also erase entries whose target is the object, such
252
280
  as changes of its children.
253
281
  since: Only entries with ``created_at >= since``; ``None`` for all.
282
+ scope_ids: Only entries with one of these ``scope_id`` values;
283
+ ``None`` for no restriction.
254
284
  record: Builds the ``audit.scrubbed`` entry.
255
285
 
256
286
  Returns:
@@ -266,6 +296,7 @@ def scrub(
266
296
  object_id,
267
297
  include_targets=include_targets,
268
298
  since=since,
299
+ scope_ids=scope_ids,
269
300
  )
270
301
  erased = connection.execute(statement).rowcount
271
302
  _write_record(
@@ -281,6 +312,7 @@ def scrub(
281
312
  "object_id": object_id,
282
313
  "include_targets": include_targets,
283
314
  "since": None if since is None else since.isoformat(),
315
+ "scope_ids": _recorded(scope_ids),
284
316
  "activity_rows": erased,
285
317
  },
286
318
  )
@@ -292,6 +324,7 @@ def scrub_actor(
292
324
  tables: AuditTables,
293
325
  actor_id: str,
294
326
  *,
327
+ scope_ids: Collection[str] | None,
295
328
  record: ScrubbedRecord,
296
329
  ) -> ScrubResult:
297
330
  """Clear an actor's personal context, and record it.
@@ -305,6 +338,14 @@ def scrub_actor(
305
338
  that wrote its first entry anonymously and then called ``set_actor``
306
339
  keeps its address and user agent on that anonymous row.
307
340
 
341
+ With ``scope_ids``, only activity rows whose ``scope_id`` is one of them
342
+ are changed, and a transaction row only when it has activity rows and
343
+ every one of them, whoever its actor, is in those scopes: its fields are
344
+ shared by all its entries, so a request that also wrote entries of
345
+ another scope, or without a scope, keeps them, as does a transaction row
346
+ without entries. An empty collection changes nothing. Clearing an
347
+ actor completely across scopes takes a run without ``scope_ids``.
348
+
308
349
  When the actor scrubs themself, the ``audit.scrubbed`` entry is written
309
350
  without those fields too.
310
351
 
@@ -314,6 +355,8 @@ def scrub_actor(
314
355
  connection: Connection whose role may update the audit tables.
315
356
  tables: The audit tables.
316
357
  actor_id: The actor's ``actor_id``.
358
+ scope_ids: The scopes the scrub is restricted to; ``None`` for no
359
+ restriction.
317
360
  record: Builds the ``audit.scrubbed`` entry.
318
361
 
319
362
  Returns:
@@ -324,21 +367,27 @@ def scrub_actor(
324
367
  """
325
368
  _check_transaction(connection)
326
369
  transaction = tables.transaction
370
+ activity = tables.activity
371
+ in_scope = _member_of(activity.c.scope_id, scope_ids)
372
+ tx_conditions = [
373
+ transaction.c.actor_id == actor_id,
374
+ or_(*(transaction.c[name].is_not(None) for name in ACTOR_FIELDS)),
375
+ ]
376
+ activity_conditions = [activity.c.actor_id == actor_id]
377
+ if in_scope is not None:
378
+ tx_conditions.append(_all_entries_match(tables, in_scope))
379
+ activity_conditions.append(in_scope)
327
380
  cleared = connection.execute(
328
381
  update(transaction)
329
- .where(
330
- transaction.c.actor_id == actor_id,
331
- or_(*(transaction.c[name].is_not(None) for name in ACTOR_FIELDS)),
332
- )
382
+ .where(*tx_conditions)
333
383
  .values({name: null() for name in ACTOR_FIELDS})
334
384
  ).rowcount
335
385
 
336
- activity = tables.activity
337
386
  keys = literal_column(_ACTOR_KEYS, ARRAY(Text))
338
387
  context = activity.c.data["context"]
339
388
  stripped = connection.execute(
340
389
  update(activity)
341
- .where(activity.c.actor_id == actor_id, context.has_any(keys))
390
+ .where(*activity_conditions, context.has_any(keys))
342
391
  .values(
343
392
  data=func.jsonb_set(
344
393
  activity.c.data,
@@ -365,6 +414,7 @@ def scrub_actor(
365
414
  payload={
366
415
  "operation": "scrub_actor",
367
416
  "actor_id": actor_id,
417
+ "scope_ids": _recorded(scope_ids),
368
418
  "transaction_rows": cleared,
369
419
  "activity_rows": stripped,
370
420
  },
@@ -372,6 +422,25 @@ def scrub_actor(
372
422
  return ScrubResult(activity_rows=stripped, transaction_rows=cleared)
373
423
 
374
424
 
425
+ def _all_entries_match(
426
+ tables: AuditTables, in_scope: ColumnElement[bool]
427
+ ) -> ColumnElement[bool]:
428
+ # A transaction row has entries, and none of them fails in_scope. A NULL
429
+ # scope_id makes in_scope NULL rather than false, so it is excluded
430
+ # explicitly.
431
+ activity = tables.activity
432
+ of_row = activity.c.transaction_id == tables.transaction.c.id
433
+ outside = or_(activity.c.scope_id.is_(None), not_(in_scope))
434
+ return and_(exists().where(of_row), ~exists().where(of_row, outside))
435
+
436
+
437
+ def _recorded(scope_ids: Collection[str] | None) -> JSONValue:
438
+ if scope_ids is None:
439
+ return None
440
+ recorded: list[JSONValue] = [*sorted(scope_ids)]
441
+ return recorded
442
+
443
+
375
444
  def _check_transaction(connection: Connection) -> None:
376
445
  if getattr(connection.connection.dbapi_connection, "autocommit", False):
377
446
  raise ValueError("scrub needs a transaction, not AUTOCOMMIT")
@@ -57,7 +57,7 @@ from sqlalchemy import (
57
57
  )
58
58
  from sqlalchemy.exc import NoReferenceError
59
59
 
60
- from audit_trail._compaction import ActivityRow, FieldChange, compact_rows
60
+ from audit_trail._compaction import ActivityData, ActivityRow, FieldChange, compact_rows
61
61
  from audit_trail._typing import assert_never
62
62
  from audit_trail.checks import _registry_of
63
63
  from audit_trail.diff import REDACTED, UNKNOWN, field_policy, options_of
@@ -72,11 +72,13 @@ if TYPE_CHECKING:
72
72
  __all__ = [
73
73
  "ALL_HISTORY",
74
74
  "AccessCount",
75
+ "ActivityData",
75
76
  "ActivityDetail",
76
77
  "ActivityRow",
77
78
  "AllHistory",
78
79
  "AuditQuery",
79
80
  "Cursor",
81
+ "FieldChange",
80
82
  "FieldLabels",
81
83
  "Group",
82
84
  "LabelResolver",
@@ -15,6 +15,8 @@ once and never through the caller's session.
15
15
 
16
16
  from __future__ import annotations
17
17
 
18
+ import asyncio
19
+ import functools
18
20
  import logging
19
21
  import re
20
22
  from collections.abc import Callable, Mapping, Sequence
@@ -68,7 +70,8 @@ class AuditWriteError(Exception):
68
70
 
69
71
  Raised for ``fail_closed`` events, and for other durable writes with
70
72
  ``on_error="raise"``. The original error (a ``DBAPIError``, the pool's
71
- ``sqlalchemy.exc.TimeoutError`` or a ``PartitionError``) is the
73
+ ``sqlalchemy.exc.TimeoutError``, a ``PartitionError`` or, from ``alog``,
74
+ a connection error the async driver raised unwrapped) is the
72
75
  ``__cause__``. Nothing of the entry was committed.
73
76
  """
74
77
 
@@ -449,8 +452,39 @@ DURABLE_WRITE_ERRORS = (DBAPIError, PoolTimeoutError, PartitionError)
449
452
  """Failures of a durable write that the write policy handles."""
450
453
 
451
454
 
455
+ @functools.cache
456
+ def async_durable_write_errors() -> tuple[type[Exception], ...]:
457
+ """Failures of an async durable write that the write policy handles.
458
+
459
+ ``DURABLE_WRITE_ERRORS`` plus what asyncpg raises unwrapped when it
460
+ cannot connect; psycopg (sync and async) wraps all of these in a
461
+ ``DBAPIError``. Each extra type is needed:
462
+
463
+ - ``OSError``: asyncpg, SQLAlchemy 2.0 and 2.1: an unreachable server
464
+ (``ConnectionRefusedError``), an unresolvable host
465
+ (``socket.gaierror``), no route to host, TLS failures, and the connect
466
+ timeout on Python 3.11+ (``TimeoutError``).
467
+ - ``asyncio.TimeoutError``: asyncpg, SQLAlchemy 2.0 on Python 3.10 (2.1
468
+ needs 3.11): its connect timeout, which is not an ``OSError`` there.
469
+ - ``asyncpg.PostgresError``: asyncpg, SQLAlchemy 2.0 only: the server
470
+ refusing the connection (missing database, bad password, too many
471
+ connections, closed during the handshake); 2.1 wraps it.
472
+
473
+ Returns:
474
+ The exception types; ``asyncpg.PostgresError`` only when asyncpg is
475
+ installed.
476
+ """
477
+ # asyncio.TimeoutError, not TimeoutError: a different class on 3.10.
478
+ errors = (*DURABLE_WRITE_ERRORS, OSError, asyncio.TimeoutError)
479
+ try:
480
+ from asyncpg import PostgresError # type: ignore[import-untyped]
481
+ except ImportError: # asyncpg is an optional driver
482
+ return errors
483
+ return (*errors, PostgresError)
484
+
485
+
452
486
  def handle_durable_failure(
453
- exc: DBAPIError | PoolTimeoutError | PartitionError,
487
+ exc: Exception,
454
488
  on_error: OnError,
455
489
  fail_closed: bool,
456
490
  ) -> None:
@@ -460,7 +494,8 @@ def handle_durable_failure(
460
494
  raises ``AuditWriteError``; otherwise the failure is logged.
461
495
 
462
496
  Args:
463
- exc: The failure, one of ``DURABLE_WRITE_ERRORS``.
497
+ exc: The failure, one of ``DURABLE_WRITE_ERRORS`` or, from ``alog``,
498
+ ``async_durable_write_errors()``.
464
499
  on_error: The write policy.
465
500
  fail_closed: The entry must not be lost; always raise.
466
501
 
@@ -0,0 +1,283 @@
1
+ # Benchmark
2
+
3
+ What does auditing cost? This benchmark measures two things on PostgreSQL:
4
+
5
+ - **Write overhead**: the same insert or update, and the same request with a
6
+ `log()` call, with and without the library, and with both `on_error`
7
+ settings.
8
+ - **Read latency** on a synthetic log of 5 million entries over 12 months:
9
+ `list_groups`, `object_history` and `access_summary`, and how many
10
+ partitions each one actually reads.
11
+
12
+ It is **not** a comparison with other libraries (sqlalchemy-continuum,
13
+ triggers, pgaudit), and it is not a tuned setup. It uses one connection and
14
+ one machine, with PostgreSQL in a local Docker container on stock settings.
15
+
16
+ ## Headline
17
+
18
+ Measured 2026-09-26 on a laptop (PostgreSQL 18.6 in Docker, stock settings;
19
+ details below):
20
+
21
+ - **Writes:** auditing a flush of 1 object adds **2.4 ms** at p50 (a plain
22
+ insert takes 3.4 ms; audited, 5.8 ms). With `on_error="raise"`, which
23
+ skips the savepoint, it adds **1.5 ms**. A flush of 100 objects adds
24
+ **11.4 ms**, about **114 µs per object** (9.8 ms with `"raise"`). A
25
+ durable `log()` adds **6.7 ms**.
26
+ - **Installed but switched off** (`audit_enabled=False`) stays within
27
+ 0.6 ms of plain at p50.
28
+ - **Reads on 5M entries:** the first page of `list_groups` (50 groups) takes
29
+ **18.5 ms** at p50 without a query window and **15.1 ms** with a 30-day
30
+ window. PostgreSQL spends under 1 ms executing the queries of either. The
31
+ window saves planning time: its plans hold 27 partition scans instead of
32
+ 82.
33
+ - Pagination reads **5 of 80 partitions** for a next page, including one
34
+ six months back. Filters with no time bound (`actor_id`, `object_history`,
35
+ `access_summary` over the whole history) read all 64 activity
36
+ partitions, and come in at 10 to 22 ms here.
37
+
38
+ ## Results
39
+
40
+ Raw JSON: `benchmark/results/run_20260926T104637Z_7e088fba.json`
41
+ (gitignored). Every number in this README comes from that run. The full run
42
+ took 677 s, including 302 s of seeding and 127 s of `VACUUM ANALYZE`.
43
+
44
+ ### Environment
45
+
46
+ | | |
47
+ | --- | --- |
48
+ | CPU | Intel Core i7-8850H @ 2.60GHz, 12 threads |
49
+ | RAM | 15.5 GB visible to the WSL2 VM |
50
+ | OS | Linux 6.18 (WSL2 on Windows), Docker Engine 29.8.1 |
51
+ | PostgreSQL | 18.6 (`postgres:18` image via testcontainers), **stock config**: `shared_buffers` 128 MB, `work_mem` 4 MB, `jit` on, `synchronous_commit` on, `fsync` on |
52
+ | Client | Python 3.12.11, SQLAlchemy 2.1.0, psycopg 3.3.6 (sync `Session`) |
53
+ | Library | sqlalchemy-audit-trail 0.1.0 at commit 953974f |
54
+ | Round trip | `SELECT 1` on an open connection: p50 0.32 ms, p95 0.48 ms |
55
+
56
+ ### Writes
57
+
58
+ Milliseconds per transaction, from `add_all`/change through `commit()`. There
59
+ were 1000 iterations for 1 and 10 objects and 300 for 100 objects, after 100
60
+ warm-up iterations per variant.
61
+ - `audited` uses the default `on_error="log"`; `"raise"` is the same
62
+ capture without the savepoint.
63
+ - "Statements" counts what goes through the cursor per transaction, for
64
+ plain / log / raise. BEGIN and COMMIT are not included.
65
+
66
+ | Operation | Objects | plain p50 / p95 | disabled p50 / p95 | audited p50 / p95 | audited, `"raise"` p50 / p95 | Added p50, `"log"` | Added p50, `"raise"` | Per object, log / raise | Statements |
67
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
68
+ | insert | 1 | 3.37 / 5.17 | 3.34 / 4.98 | 5.80 / 8.51 | 4.88 / 7.33 | +2.43 ms (+72%) | +1.52 ms (+45%) | 2429 / 1516 µs | 1 / 5 / 3 |
69
+ | insert | 10 | 3.98 / 6.69 | 4.05 / 6.59 | 7.68 / 11.86 | 6.34 / 9.63 | +3.70 ms (+93%) | +2.36 ms (+59%) | 370 / 236 µs | 1 / 5 / 3 |
70
+ | insert | 100 | 8.04 / 12.80 | 7.84 / 10.91 | 19.42 / 36.04 | 17.87 / 27.18 | +11.38 ms (+141%) | +9.83 ms (+122%) | 114 / 98 µs | 1 / 5 / 3 |
71
+ | update | 1 | 2.83 / 3.71 | 2.84 / 4.20 | 5.26 / 7.24 | 4.46 / 6.15 | +2.43 ms (+86%) | +1.63 ms (+58%) | 2427 / 1633 µs | 1 / 5 / 3 |
72
+ | update | 10 | 3.37 / 4.42 | 3.51 / 5.28 | 7.13 / 10.53 | 6.04 / 8.89 | +3.76 ms (+112%) | +2.68 ms (+80%) | 376 / 268 µs | 1 / 5 / 3 |
73
+ | update | 100 | 7.07 / 9.96 | 7.64 / 15.78 | 18.75 / 34.57 | 17.34 / 22.91 | +11.68 ms (+165%) | +10.27 ms (+145%) | 117 / 103 µs | 1 / 5 / 3 |
74
+
75
+ The `log()` rows are one plain insert plus the event, compared with the same
76
+ insert without it (1000 iterations each):
77
+
78
+ | Operation | plain p50 / p95 | `"log"` p50 / p95 | `"raise"` p50 / p95 | Added p50, `"log"` | Added p50, `"raise"` | Statements |
79
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: |
80
+ | `log()` | 3.24 / 4.98 | 5.58 / 8.11 | 4.78 / 7.00 | +2.34 ms (+72%) | +1.54 ms (+47%) | 1 / 5 / 3 |
81
+ | durable `log()` | 5.63 / 7.04 | 12.37 / 15.05 | 12.31 / 15.31 | +6.73 ms (+119%) | +6.67 ms (+118%) | 1 / 3 / 3 |
82
+
83
+ Where the time goes:
84
+
85
+ - **The fixed cost is mostly round trips.** With the default
86
+ `on_error="log"`, an audited flush sends four more statements than a
87
+ plain one: a savepoint, the `audit_transaction` insert, the
88
+ `audit_activity` insert, and the savepoint release. At 0.32 ms per
89
+ round trip here, the round trips alone are about 1.3 ms of the 2.4 ms.
90
+ The rest is the server work behind those statements (the savepoint, and
91
+ inserts into two partitioned tables with their indexes), plus a little
92
+ Python. The percentages look large because the baseline is small: one
93
+ statement plus the commit.
94
+ - **What `on_error="raise"` saves:** the savepoint and its release. It
95
+ measured 0.8 to 1.5 ms less than `"log"` at p50 in every insert, update
96
+ and `log()` case. That is more than the two round trips alone (about
97
+ 0.6 ms), so the savepoint's server-side work counts too. The price is
98
+ that a failed audit write (for example a missing partition) fails your
99
+ transaction instead of being logged.
100
+ - **The per-object cost** at 100 objects is about 100 to 120 µs. A cProfile
101
+ of the 100-object insert, taken separately from this run (and inflating
102
+ Python time), put roughly half of the listener's time in the executemany
103
+ of the 100 JSONB activity rows and about a third in building the diffs
104
+ in Python.
105
+ - **A durable `log()`** commits on its own connection, so a request pays
106
+ for a second transaction and a second commit. `on_error` changes nothing
107
+ there (−0.06 ms): a durable write never uses the savepoint.
108
+ - **`disabled`** stays within 0.6 ms of `plain` at p50 (−2.5% to +8.0%).
109
+ The differences go in both directions, which is noise at this scale. The
110
+ mixin's `active_history` listeners have nothing to load here, because the
111
+ rows were loaded before the change (see the protocol).
112
+
113
+ ### Reads
114
+
115
+ 5,000,000 `audit_activity` rows (4.38 GB with indexes) and 2,500,000
116
+ `audit_transaction` rows (0.56 GB), spread over 365 days. There are
117
+ 4 severities × 16 months = 64 activity partitions (12 past months, the
118
+ current one and 3 ahead) and 16 transaction partitions. Each case ran 20
119
+ warm-up and 200 measured calls, each in its own session. Limit is 50
120
+ groups.
121
+
122
+ The last four columns come from one `EXPLAIN (ANALYZE)` run of every
123
+ statement the call sent:
124
+ - "Partitions read" counts distinct partitions actually executed.
125
+ - "Planned" sums the partition scans in the plans, including those pruned
126
+ at run time.
127
+ - "Planning" and "Execution" are server-side milliseconds under EXPLAIN's
128
+ instrumentation.
129
+
130
+ | Case | p50 ms | p95 ms | Groups | Statements | Partitions read (of 80) | Planned | Planning ms | Execution ms |
131
+ | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
132
+ | `list_groups` first page | 18.5 | 25.8 | 50 | 7 | 17 | 82 | 5.3 | 0.7 |
133
+ | `list_groups` first page, 30-day window | 15.1 | 19.7 | 50 | 7 | 17 | 27 | 2.3 | 0.4 |
134
+ | `list_groups` next page | 22.1 | 28.6 | 50 | 8 | 5 | 74 | 5.5 | 0.7 |
135
+ | `list_groups` next page, 30-day window | 17.4 | 23.2 | 50 | 8 | 5 | 19 | 2.8 | 0.7 |
136
+ | `list_groups` page 6 months back | 18.3 | 22.4 | 50 | 8 | 5 | 44 | 4.7 | 0.7 |
137
+ | `list_groups(actor_id=...)` | 22.1 | 33.7 | 50 | 4 | 65 | 121 | 7.8 | 2.7 |
138
+ | `object_history` (with children) | 21.5 | 25.8 | 50 | 4 | 68 | 148 | 9.4 | 1.9 |
139
+ | `access_summary`, whole history | 10.0 | 13.9 | — (367 entries counted) | 1 | 64 | 64 | 3.1 | 1.9 |
140
+
141
+ What this shows:
142
+
143
+ - **Data volume barely matters for pages.** `list_groups` runs one
144
+ `LIMIT 51` query per severity. PostgreSQL reads each severity's monthly
145
+ partitions newest first and stops once it has enough rows. The 17
146
+ partitions read on a first page are 4 per severity plus one transaction
147
+ partition. Of the 4 per severity, 3 are the empty partitions created
148
+ ahead of time and 1 is the current month. A next page, or a page six
149
+ months back, reads one partition per severity, because the cursor bounds
150
+ `created_at` from above.
151
+ - **The window saves planning, not execution.** Without a lower bound, each
152
+ per-severity query is planned over all 16 of its months and pruned at run
153
+ time. With the 30-day window it is planned over 5. That is the 5.3 ms
154
+ versus 2.3 ms planning, and most of the 3.4 ms latency difference on the
155
+ first page. Planning cost grows with the number of partitions a query
156
+ cannot exclude, so it grows with retention.
157
+ - **Most of the latency is client side.** The server executes these pages
158
+ in under 1 ms. The rest is 7 or 8 round trips (about 2.5 ms here),
159
+ planning, and Python: row decoding, grouping and compaction.
160
+ - **Where pruning cannot help.** `actor_id` without `severities`,
161
+ `object_history` and `access_summary` filter on a column that is not a
162
+ partition key, and have no time bound (`object_history` and
163
+ `access_summary` ignore the default window by design). They must probe
164
+ the index of every activity partition, all 64 of them. It stays fast here
165
+ because each probe finds few rows. The cost grows with the number of
166
+ partitions (months kept × severities), not with rows. Passing `since`
167
+ bounds it.
168
+
169
+ ## What these numbers are not
170
+
171
+ - **Not a comparison with other libraries.** Nothing else was measured.
172
+ - **Not a tuned server.** The PostgreSQL configuration is stock (128 MB
173
+ `shared_buffers`, `synchronous_commit` on). The write baseline is
174
+ dominated by commit fsync inside a WSL2 Docker VM. On real hardware, or
175
+ with other durability settings, the plain baseline and the percentages
176
+ will differ. The added round trips and per-object costs are the more
177
+ portable numbers.
178
+ - **A mostly idle machine.** Other workloads were stopped for this run; one
179
+ unrelated, idle PostgreSQL container was still running on the host.
180
+ - **Not concurrent.** One connection, sequential. Throughput columns in the
181
+ JSON (`ops_per_s`, `objects_per_s`) are 1 / mean latency on that one
182
+ connection, not server capacity.
183
+ - **Only sync psycopg.** `AsyncSession`/asyncpg is not measured.
184
+ - **Synthetic data.** The dataset is generated, with this deterministic
185
+ skew: INFO 70%, NOTICE 20%, WARNING 8%, CRITICAL 2%. 10% of entries are
186
+ `person.viewed` on 1,000 people. The rest are `entity.created` /
187
+ `updated` / `deleted` on 9 object types × 100,000 ids, 20% of them with
188
+ an `Order` target (5,000 ids). There are 1,000 actors and 50 scopes, and
189
+ 1 to 3 entries per transaction. Real logs have other shapes. In
190
+ particular, a rare severity makes its per-severity query read further
191
+ back.
192
+ - **Not cold-cache reads.** Each case runs warm-up calls first. The page
193
+ cache holds whatever seeding and warm-up left in it, and cold-cache reads
194
+ of the 4.9 GB dataset are not measured.
195
+
196
+ ## Protocol
197
+
198
+ **Write variants.**
199
+ - `plain`: a model without `Audited`, on a session class the library is not
200
+ installed on. This is the true zero and the baseline for every
201
+ percentage.
202
+ - `disabled`: the `Audited` model (same columns) on the installed session
203
+ class, with `session.info["audit_enabled"] = False`. The mixin's
204
+ `active_history` listeners and the session listeners still run, but no
205
+ entries are written. This answers "what does leaving it installed but off
206
+ cost".
207
+ - `audited`: the `Audited` model on the installed session class, capturing
208
+ inside an `audit.context(...)`, with the default `on_error="log"`: the
209
+ audit inserts run in a savepoint, so a failed audit write does not fail
210
+ the transaction.
211
+ - `audited_raise`: the same with an `AuditTrail(on_error="raise")`,
212
+ installed on its own session class: no savepoint.
213
+
214
+ Before measuring, the runner checks that each variant is what it claims to
215
+ be, and stops if not:
216
+ - the plain model is not `Audited`;
217
+ - the plain session class has no trail installed;
218
+ - each audited session has the expected trail, `on_error` and capture
219
+ flag.
220
+
221
+ The checks that passed are listed under `write.preconditions` in the JSON.
222
+
223
+ **Write operations.** Each operation is one transaction ended by `commit()`.
224
+ - Insert: `add_all(n new objects)` + `commit()`. The objects are built
225
+ outside the timer.
226
+ - Update: the same n rows are loaded in the session's transaction outside
227
+ the timer, then two columns are changed and `commit()` runs, all timed.
228
+ - `log()`: one plain insert, then `audit.log(session, event,
229
+ payload=...)`, then `commit()`. The events use `benchmark.*` verbs and are
230
+ defined only when the write benchmark runs, never at import.
231
+ - Durable `log()`: the same, with an event declared `durable=True`.
232
+
233
+ The variants of a case run in interleaved blocks of 50, after warm-up, so
234
+ drift from table growth or autovacuum falls on all of them. Write tables and
235
+ audit tables start empty and are separate from the read dataset.
236
+
237
+ **Read dataset.** It is seeded with one `INSERT ... SELECT` over
238
+ `generate_series` per table, not through the ORM. Each activity row's
239
+ `created_at` equals its transaction's `issued_at`, as the library writes
240
+ them. `VACUUM (ANALYZE)` runs afterwards. The runner creates its own schemas
241
+ and drops them at the end (`--keep` keeps them).
242
+
243
+ **Partitions.** A listener captures every `SELECT` a call sends. Each one is
244
+ then re-run as `EXPLAIN (ANALYZE, FORMAT JSON)` with the same parameters, on
245
+ the same connection and in the same transaction, after the library's
246
+ `SET LOCAL plan_cache_mode = 'force_custom_plan'`. This needs no superuser.
247
+
248
+ ## Rerun
249
+
250
+ Needs Docker, or an existing server:
251
+
252
+ ```bash
253
+ uv sync --frozen
254
+ uv run python -m benchmark.run_benchmark # postgres:18 in Docker, ~12 min
255
+ uv run python -m benchmark.run_benchmark --image postgres:14
256
+ uv run python -m benchmark.run_benchmark --database-url postgresql://user:pw@host/db
257
+ ```
258
+
259
+ With `--database-url`, the runner creates schemas named `bench_<id>_*` and
260
+ drops them afterwards. The URL's driver is replaced with psycopg.
261
+
262
+ Quick check (seconds):
263
+
264
+ ```bash
265
+ uv run python -m benchmark.run_benchmark --iterations 20 --iterations-large 10 \
266
+ --warmup 5 --activity-rows 20000 --read-iterations 5
267
+ ```
268
+
269
+ | Flag | Default | |
270
+ | --- | --- | --- |
271
+ | `--database-url` | none | use this server instead of a container |
272
+ | `--image` | `postgres:18` | container image |
273
+ | `--batch-sizes` | `1,10,100` | objects per flush |
274
+ | `--iterations` / `--iterations-large` | 1000 / 300 | measured writes; the second for batches ≥ `--large-batch` (100) |
275
+ | `--warmup` / `--block` | 100 / 50 | warm-up writes per variant; interleaving block |
276
+ | `--activity-rows` | 5,000,000 | read dataset size (transactions = half) |
277
+ | `--read-iterations` / `--read-warmup` | 200 / 20 | calls per read case |
278
+ | `--skip-write` / `--skip-read` | off | run one half only |
279
+ | `--keep` | off | keep the benchmark schemas |
280
+ | `--output-dir` | `benchmark/results/` | where the JSON goes |
281
+
282
+ `tests/db/test_benchmark.py` runs the whole runner at tiny sizes in the test
283
+ suite, so the script keeps working between full runs.
@@ -0,0 +1,133 @@
1
+ # Example: an audited multi-tenant CRM on FastAPI
2
+
3
+ A small async FastAPI application (asyncpg) whose audit log answers the usual questions: who changed this customer, from where, and what changed; who read its bank details; who tried to log in and failed. Each tenant sees only its own log, and personal data can be erased from it on request.
4
+
5
+ | File | What it shows |
6
+ |---|---|
7
+ | [`models.py`](models.py) | Audited models with column policies (`hash`, `redact`, `exclude`), a tenant `scope`, a tracked relationship, and the domain events |
8
+ | [`db.py`](db.py) | The application's `AuditTrail` and a separate one for maintenance and scrubbing |
9
+ | [`auth.py`](auth.py) | Fake login, and `set_actor` once the user is known |
10
+ | [`main.py`](main.py) | The endpoints: CRUD, a fail-closed read, the history of a customer, the tenant's activity feed, and GDPR erasure |
11
+ | [`maintenance.py`](maintenance.py) | The daily job: partitions ahead, retention, health |
12
+
13
+ The test suite runs the walkthrough below against a real database (`tests/db/test_example_app.py`).
14
+
15
+ ## Run it
16
+
17
+ You need Docker, [uv](https://docs.astral.sh/uv/) and a clone of this repository. Start PostgreSQL:
18
+
19
+ ```bash
20
+ docker run --rm -d --name audit-demo -p 5432:5432 \
21
+ -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=app postgres:18
22
+ ```
23
+
24
+ Then, from the repository root, start the application:
25
+
26
+ ```bash
27
+ uv sync
28
+ uv run --with uvicorn uvicorn examples.fastapi_app.main:app
29
+ ```
30
+
31
+ uvicorn is not a dependency of the library, so `--with` adds it for this command only. Outside this repository, `pip install "sqlalchemy-audit-trail[fastapi,asyncpg]" uvicorn` installs everything the application imports.
32
+
33
+ The application connects to `postgresql+asyncpg://postgres:postgres@localhost:5432/app`; set `DATABASE_URL` to use another database. At startup it creates its tables, the audit tables and this month's partitions. The interactive API docs are at <http://localhost:8000/docs>.
34
+
35
+ ## Walk through it
36
+
37
+ In another terminal, three users are ready: `ada` (admin of tenant `acme`), `bob` (`acme`) and `eve` (`globex`). The password is the login followed by `-pass`.
38
+
39
+ ```bash
40
+ API=localhost:8000
41
+ JSON='Content-Type: application/json'
42
+ login() {
43
+ curl -s -X POST $API/login -H "$JSON" -d "{\"login\": \"$1\", \"password\": \"$2\"}" |
44
+ python3 -c 'import json, sys; print(json.load(sys.stdin)["token"])'
45
+ }
46
+ show() { python3 -m json.tool; }
47
+ ```
48
+
49
+ **1. A failed login, then three good ones.**
50
+
51
+ ```bash
52
+ curl -s -X POST $API/login -H "$JSON" -d '{"login": "ada", "password": "wrong"}'
53
+ ADA=$(login ada ada-pass); BOB=$(login bob bob-pass); EVE=$(login eve eve-pass)
54
+ ```
55
+
56
+ **2. Ada creates a customer, Bob changes its e-mail and IBAN, Ada adds a contact.**
57
+
58
+ ```bash
59
+ curl -s -X POST $API/customers -H "$JSON" -H "Authorization: Bearer $ADA" \
60
+ -d '{"name": "Initech", "email": "billing@initech.test", "iban": "DE89370400440532013000"}'
61
+ curl -s -X PATCH $API/customers/1 -H "$JSON" -H "Authorization: Bearer $BOB" \
62
+ -d '{"email": "accounts@initech.test", "iban": "GB29NWBK60161331926819"}'
63
+ curl -s -X POST $API/customers/1/contacts -H "$JSON" -H "Authorization: Bearer $ADA" \
64
+ -d '{"name": "Peter Gibbons", "email": "peter@initech.test"}'
65
+ ```
66
+
67
+ **3. Bob reads the bank details.**
68
+
69
+ ```bash
70
+ curl -s $API/customers/1/payment-details -H "Authorization: Bearer $BOB"
71
+ ```
72
+
73
+ **4. Ada looks at the customer's history.**
74
+
75
+ ```bash
76
+ curl -s $API/customers/1/history -H "Authorization: Bearer $ADA" | show
77
+ ```
78
+
79
+ **5. Eve, of another tenant, sees nothing of it.**
80
+
81
+ ```bash
82
+ curl -s $API/customers/1/history -H "Authorization: Bearer $EVE" # 404
83
+ curl -s $API/activity -H "Authorization: Bearer $EVE" | show # her own login only
84
+ ```
85
+
86
+ **6. Ada pages through her tenant's activity feed, two groups at a time.**
87
+
88
+ ```bash
89
+ curl -s "$API/activity?limit=2" -H "Authorization: Bearer $ADA" | show
90
+ curl -s "$API/activity?limit=2&cursor=<next_cursor from the last page>" \
91
+ -H "Authorization: Bearer $ADA" | show
92
+ ```
93
+
94
+ **7. GDPR: Ada, as admin, erases Bob's personal context from the log, then erases the customer.**
95
+
96
+ ```bash
97
+ curl -s -X POST $API/admin/users/u2/scrub -H "Authorization: Bearer $ADA"
98
+ curl -s -X POST $API/admin/customers/1/erase -H "Authorization: Bearer $ADA"
99
+ curl -s $API/customers/1/history -H "Authorization: Bearer $ADA" | show
100
+ ```
101
+
102
+ **8. The raw rows**, for what the API does not show:
103
+
104
+ ```bash
105
+ docker exec audit-demo psql -U postgres -d app -c \
106
+ "SELECT verb, severity, actor_id, scope_id, data->'payload' AS payload
107
+ FROM audit.audit_activity WHERE verb NOT LIKE 'entity.%' ORDER BY id"
108
+ docker exec audit-demo psql -U postgres -d app -c \
109
+ "SELECT actor_id, actor_label, remote_addr, method, path FROM audit.audit_transaction ORDER BY id"
110
+ ```
111
+
112
+ When you are done: `docker stop audit-demo`.
113
+
114
+ ## What to look for
115
+
116
+ - **Every change is attributed.** Each group of the history is one database transaction, with the user (`actor`) and the request (`PATCH /customers/1`) that made it. The endpoints never pass the user to the audit trail: the `current_user` dependency calls `set_actor` once, and `AuditMiddleware` fills in the address, user agent, path and request id.
117
+ - **Column policies.** `email` is stored as `hv1:...`, an HMAC: equal addresses give equal tokens, so you can tell that it changed, and to what, if you already know the candidate value, but the log never holds the address. `iban` is `"***"`, so the log records that it was set or changed. `updated_at` is not there at all.
118
+ - **Children and labels.** The contact's creation shows up in the customer's history, because `Contact` sets its customer as `target`. The customer's own entry records `contacts: {"added": ["1"]}`, and `LabelResolver` adds `"labels": {"contacts": {"added": ["Peter Gibbons"]}}` from the log itself, not from the contact table.
119
+ - **Reads can be audited too.** `customer.payment_details_viewed` is `fail_closed`: the entry is committed before the IBAN is returned, and if it cannot be written the endpoint answers 503 instead.
120
+ - **The failed login survives the 401.** `auth.login_failed` is durable, written on its own connection, so the request's rollback does not remove it. Its payload holds `audit.login.v1:...` instead of the login typed, which might have been a password.
121
+ - **Tenants are isolated by the log's own `scope_id`.** Both audit views pass `Visibility(scope_ids={tenant})`, so Eve gets a 404 for Initech's history and a feed with nothing of `acme`. Logins have no model to take a scope from; `auth.py` puts the tenant on the request's context.
122
+ - **The feed has a window and a cursor.** It reads the last 30 days (`default_query_window`; `window_start` in the response), newest first, and `next_cursor` is an opaque token for the next page. There is no offset and no total: those would read every partition.
123
+ - **Erasure keeps the shape of the history.** After `scrub_actor`, Bob's entries still say `actor_id: u2`, but his e-mail, address and user agent are gone from the transactions and from each entry's context. After the erase, the customer's history still shows who changed which fields when, with every value `"[erased]"` and no label. Each scrub records itself as `audit.scrubbed`, with who did it and how many rows it changed.
124
+
125
+ ## Demo shortcuts
126
+
127
+ This is a demo. Do not copy these parts:
128
+
129
+ - **Authentication is fake.** Users and plain-text passwords are a dict in `auth.py`, and tokens live in memory until restart. Use a real identity provider; keep the `set_actor` call.
130
+ - **The tables are created at startup.** In production, create your tables and the audit tables in migrations (see the [partitions guide](https://wiktorb2004.github.io/sqlalchemy-audit-trail/guides/partitions/)), and run `maintenance.py` on a schedule: `uv run python -m examples.fastapi_app.maintenance`.
131
+ - **One database role does everything.** The application should connect as a role that can only insert into and read the audit tables. Creating partitions, dropping expired ones and scrubbing need the maintenance role (see [`examples/roles.sql`](../roles.sql) and the [permissions guide](https://wiktorb2004.github.io/sqlalchemy-audit-trail/guides/permissions/)). Point `MAINTENANCE_DATABASE_URL` at it; the scrub endpoints and `maintenance.py` use that connection.
132
+ - **The pseudonymization key is a constant.** Set `AUDIT_PSEUDONYMIZE_KEY` to a secret of at least 32 random bytes, and keep it: it is what makes the `hv1:` and `audit.login.v1:` tokens correlatable.
133
+ - **The erase endpoint checks the tenant itself.** `scrub()` erases every entry of an object type and id, in any tenant, so the endpoint loads the customer within the admin's tenant before deleting it and scrubbing.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlalchemy-audit-trail"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -94,7 +94,7 @@ typing-modules = ["audit_trail._typing"]
94
94
 
95
95
  [tool.mypy]
96
96
  python_version = "3.10"
97
- files = ["audit_trail", "tests"]
97
+ files = ["audit_trail", "benchmark", "tests"]
98
98
  strict = true
99
99
  warn_unreachable = true
100
100
  show_error_codes = true