sqlalchemy-audit-trail 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,1028 @@
1
+ """Partition management, retention and health checks.
2
+
3
+ ``ensure_partitions`` creates the partitions writes will need: every
4
+ severity partition of the activity table, and the monthly partitions of the
5
+ transaction table and of each severity partition, from the current UTC month
6
+ ``months_ahead`` months forward. There is no ``DEFAULT`` partition, so a row
7
+ without a partition fails with SQLSTATE ``23514``; run it on a schedule
8
+ (cron, worker, application start) with enough months ahead to cover a missed
9
+ run.
10
+
11
+ Existing partitions are found by their bounds in the catalog, not by name: a
12
+ partition created by hand or by another tool under a different name, with the
13
+ same (or wider) bounds, counts as present. Names and bounds are described in
14
+ ``audit_trail.migrations``.
15
+
16
+ Locking: ``CREATE TABLE ... PARTITION OF`` takes an ``ACCESS EXCLUSIVE`` lock
17
+ on the parent, so it waits for every open transaction that has touched the
18
+ parent, including business transactions with uncommitted audit rows. Under
19
+ PostgreSQL's documented lock queueing, later lock requests that conflict with
20
+ the waiting one, such as new audit inserts, queue behind it. ``lock_timeout``
21
+ bounds that wait: past it the whole call is rolled back and
22
+ ``PartitionLockTimeoutError`` is raised; retrying later is safe.
23
+
24
+ ``drop_expired`` removes monthly partitions older than a per-severity
25
+ retention, with ``ALTER TABLE ... DETACH PARTITION ... CONCURRENTLY`` and then
26
+ ``DROP TABLE``. ``health`` reports how many months ahead are covered, detaches
27
+ left pending and leftover tables that look like detached partitions.
28
+
29
+ Locks taken by ``drop_expired``, as observed in ``pg_locks`` on PostgreSQL 14
30
+ and 18:
31
+
32
+ * ``DETACH ... CONCURRENTLY`` first takes ``SHARE UPDATE EXCLUSIVE`` on the
33
+ parent, which does not conflict with inserts. It then waits for every
34
+ transaction that has used the parent, holding no lock on any table while
35
+ it waits, so new audit inserts go ahead. Last, it takes ``SHARE UPDATE
36
+ EXCLUSIVE`` on the parent and ``ACCESS EXCLUSIVE`` on the partition, which
37
+ waits for readers of that partition.
38
+ * ``DETACH ... FINALIZE`` takes the same locks as that last step, and waits
39
+ for the same transactions.
40
+ * ``DROP TABLE`` of the detached table takes ``ACCESS EXCLUSIVE`` on that
41
+ table only.
42
+
43
+ ``lock_timeout`` bounds each of these waits, including the wait for other
44
+ transactions. An application transaction left open on an audit table for
45
+ longer than ``lock_timeout`` therefore makes ``drop_expired`` fail with
46
+ ``PartitionLockTimeoutError``; this is expected. If that happens after a
47
+ detach has started, the partition stays "pending detach" and the next call
48
+ finalizes and drops it.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import logging
54
+ import re
55
+ from collections.abc import Iterable, Mapping
56
+ from dataclasses import dataclass
57
+ from datetime import date, datetime, timedelta, timezone
58
+ from typing import TYPE_CHECKING, Literal, NamedTuple, TypeVar
59
+
60
+ from sqlalchemy import Connection, Engine, Table, bindparam, text
61
+ from sqlalchemy.exc import DBAPIError
62
+
63
+ from audit_trail.migrations import (
64
+ _execute_ddl,
65
+ create_month_partition_sql,
66
+ create_severity_partition_sql,
67
+ month_bounds,
68
+ month_partition_name,
69
+ qualified_name,
70
+ severity_partition_name,
71
+ severity_values,
72
+ )
73
+ from audit_trail.tables import MAX_IDENTIFIER_LENGTH, AuditTables
74
+
75
+ if TYPE_CHECKING:
76
+ from sqlalchemy.ext.asyncio import AsyncEngine
77
+
78
+ LOCK_NOT_AVAILABLE = "55P03"
79
+ """SQLSTATE raised when ``lock_timeout`` expires."""
80
+
81
+ logger = logging.getLogger(__name__)
82
+
83
+ # Lets a mapping keyed by a severity IntEnum pass where ints are expected.
84
+ _Severity = TypeVar("_Severity", bound=int)
85
+
86
+ _RANGE_BOUND = r"^FOR VALUES FROM \((.*)\) TO \((.*)\)$"
87
+ _LIST_BOUND = re.compile(r"^FOR VALUES IN \((.*)\)$")
88
+
89
+ # Bounds are cast back to timestamptz in the same statement that renders them,
90
+ # so the round trip is exact whatever the session's TimeZone and DateStyle.
91
+ # MINVALUE / MAXVALUE come out as NULL, meaning unbounded.
92
+ _CHILDREN = text(
93
+ """
94
+ SELECT oid, nspname, relname, relkind, bound, m IS NOT NULL AS is_range,
95
+ CASE WHEN m[1] LIKE '''%' THEN btrim(m[1], '''')::timestamptz END
96
+ AS lower,
97
+ CASE WHEN m[2] LIKE '''%' THEN btrim(m[2], '''')::timestamptz END
98
+ AS upper,
99
+ pending
100
+ FROM (
101
+ SELECT c.oid, n.nspname, c.relname, c.relkind::text AS relkind, b.bound,
102
+ regexp_match(b.bound, :range_pattern) AS m,
103
+ i.inhdetachpending AS pending
104
+ FROM pg_catalog.pg_inherits i
105
+ JOIN pg_catalog.pg_class c ON c.oid = i.inhrelid
106
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
107
+ CROSS JOIN LATERAL pg_catalog.pg_get_expr(c.relpartbound, c.oid) AS b(bound)
108
+ WHERE i.inhparent = :parent
109
+ ) s
110
+ """
111
+ ).bindparams(bindparam("range_pattern", _RANGE_BOUND))
112
+
113
+
114
+ class PartitionError(Exception):
115
+ """Partition maintenance could not be done."""
116
+
117
+
118
+ class PartitionLockTimeoutError(PartitionError):
119
+ """A lock needed for partition maintenance was not granted within ``lock_timeout``.
120
+
121
+ ``lock_timeout`` applies to each lock wait, not to the whole call, so
122
+ ``ensure_partitions`` blocked behind ``drop_expired`` and then behind an
123
+ open transaction can take about twice ``lock_timeout`` before this is
124
+ raised. From ``ensure_partitions``, nothing was created; ``months_ahead``
125
+ leaves room for a later retry. From ``drop_expired``, the partitions dropped
126
+ before the timeout stay dropped (each one is logged), and a detach left
127
+ pending is finalized by the next call.
128
+ """
129
+
130
+
131
+ class _RetentionTarget(NamedTuple):
132
+ """A partitioned table whose monthly partitions expire together."""
133
+
134
+ parent: str
135
+ """Quoted, schema-qualified name of the partitioned table."""
136
+ oid: int
137
+ limit: timedelta | None
138
+ """How long its partitions are kept; ``None`` keeps them forever."""
139
+
140
+
141
+ class _Coverage(NamedTuple):
142
+ covers_now: bool
143
+ months_ahead: int | None
144
+ """Whole months after the current one covered; ``None`` when unbounded."""
145
+
146
+
147
+ class _ShownSchemas(NamedTuple):
148
+ """Schemas of the audit tables, as used in returned names."""
149
+
150
+ transaction: str
151
+ activity: str
152
+
153
+
154
+ @dataclass(frozen=True)
155
+ class _Child:
156
+ oid: int
157
+ schema: str
158
+ name: str
159
+ relkind: str
160
+ bound: str
161
+ is_range: bool
162
+ lower: datetime | None
163
+ upper: datetime | None
164
+ pending: bool
165
+
166
+ @property
167
+ def qualified(self) -> str:
168
+ return qualified_name(self.schema, self.name)
169
+
170
+ @property
171
+ def display(self) -> str:
172
+ return _name(self.schema, self.name)
173
+
174
+ def covers(self, start: datetime, end: datetime) -> bool:
175
+ return (
176
+ self.is_range
177
+ and (self.lower is None or self.lower <= start)
178
+ and (self.upper is None or self.upper >= end)
179
+ )
180
+
181
+ def list_values(self) -> set[int]:
182
+ match = _LIST_BOUND.match(self.bound)
183
+ if match is None:
184
+ return set()
185
+ values = (v.strip().strip("'") for v in match.group(1).split(","))
186
+ return {int(v) for v in values if v.lstrip("-").isdigit()}
187
+
188
+
189
+ def ensure_partitions(
190
+ connection: Connection,
191
+ tables: AuditTables,
192
+ severities: Iterable[int],
193
+ *,
194
+ months_ahead: int = 3,
195
+ now: datetime | None = None,
196
+ lock_timeout: str | None = "5s",
197
+ ) -> list[str]:
198
+ """Create the missing severity and monthly partitions.
199
+
200
+ Covers the UTC month of ``now`` and the ``months_ahead`` months after it,
201
+ for the transaction table and for every severity. Idempotent: a partition
202
+ that already exists with the same or wider bounds, under any name, is
203
+ left alone.
204
+
205
+ Runs in the connection's current transaction, which must not be
206
+ ``AUTOCOMMIT``; the caller commits, or rolls back on error. Concurrent
207
+ calls are serialized with a transaction-level advisory lock.
208
+
209
+ Args:
210
+ connection: Connection with DDL privileges.
211
+ tables: The audit tables, from ``audit_trail.tables.build_tables``.
212
+ severities: A severity ``IntEnum`` class, or any iterable of ints.
213
+ months_ahead: Months to create after the current one.
214
+ now: Reference time. ``None`` uses the database's ``now()``.
215
+ lock_timeout: PostgreSQL ``lock_timeout`` for this transaction, such
216
+ as ``"5s"``. ``None`` keeps the session's setting. It bounds each
217
+ lock wait, not the whole call: blocked behind ``drop_expired``
218
+ (the advisory lock) and then behind an open transaction (the
219
+ ``CREATE``), a call can take about twice ``lock_timeout``.
220
+
221
+ Returns:
222
+ Schema-qualified names of the partitions created, parents first.
223
+
224
+ Raises:
225
+ ValueError: If ``months_ahead`` is negative or the connection is in
226
+ ``AUTOCOMMIT`` mode.
227
+ PartitionError: If a parent table does not exist, or a monthly
228
+ partition name derived from an existing severity partition would
229
+ be longer than PostgreSQL allows.
230
+ PartitionLockTimeoutError: If a lock was not granted within
231
+ ``lock_timeout``; the transaction must be rolled back.
232
+ """
233
+ if months_ahead < 0:
234
+ raise ValueError("months_ahead must not be negative")
235
+ if getattr(connection.connection.dbapi_connection, "autocommit", False):
236
+ raise ValueError("ensure_partitions needs a transaction, not AUTOCOMMIT")
237
+ try:
238
+ return _ensure(
239
+ connection,
240
+ tables,
241
+ severity_values(severities),
242
+ months_ahead,
243
+ now,
244
+ lock_timeout,
245
+ )
246
+ except DBAPIError as exc:
247
+ if getattr(exc.orig, "sqlstate", None) == LOCK_NOT_AVAILABLE:
248
+ raise PartitionLockTimeoutError(
249
+ f"partitions were not created: a lock was not granted within "
250
+ f"lock_timeout={lock_timeout!r}, which applies to each lock "
251
+ "wait, so waiting behind drop_expired and then an open "
252
+ "transaction takes about twice as long; retry later"
253
+ ) from exc
254
+ raise
255
+
256
+
257
+ @dataclass(frozen=True)
258
+ class PartitionHealth:
259
+ """How far ahead one partitioned parent is covered by monthly partitions.
260
+
261
+ Attributes:
262
+ table: Schema-qualified name of the parent (the transaction table or a
263
+ severity partition), or ``None`` if the severity has no partition.
264
+ covers_now: Whether the current UTC month has a partition.
265
+ months_ahead: Whole months after the current one covered without a
266
+ gap; ``0`` when the current month is not covered, ``None`` when
267
+ there is no upper bound (a ``MAXVALUE`` partition, or a severity
268
+ partition that is a plain table).
269
+ below: Whether the current month is not covered or ``months_ahead``
270
+ is below the threshold.
271
+ """
272
+
273
+ table: str | None
274
+ covers_now: bool
275
+ months_ahead: int | None
276
+ below: bool
277
+
278
+
279
+ @dataclass(frozen=True)
280
+ class HealthReport:
281
+ """Result of ``health``.
282
+
283
+ Attributes:
284
+ min_months_ahead: The threshold the report was made with.
285
+ transaction: Coverage of the transaction table.
286
+ activity: Coverage of each requested severity, by severity value.
287
+ pending_detach: Schema-qualified names of partitions left "pending
288
+ detach" by an interrupted ``drop_expired``; its next call
289
+ finalizes them.
290
+ orphaned: Schema-qualified names of tables in the audit schemas that
291
+ are named like monthly partitions but are no partition. A crash
292
+ between the detach and the drop in ``drop_expired`` leaves one
293
+ behind; nothing drops them automatically. Check the name, then
294
+ ``DROP TABLE`` it by hand.
295
+ """
296
+
297
+ min_months_ahead: int
298
+ transaction: PartitionHealth
299
+ activity: dict[int, PartitionHealth]
300
+ pending_detach: list[str]
301
+ orphaned: list[str]
302
+
303
+ @property
304
+ def ok(self) -> bool:
305
+ """Whether nothing is below the threshold, pending or orphaned."""
306
+ return not (
307
+ self.transaction.below
308
+ or any(h.below for h in self.activity.values())
309
+ or self.pending_detach
310
+ or self.orphaned
311
+ )
312
+
313
+
314
+ def drop_expired(
315
+ connection: Connection,
316
+ tables: AuditTables,
317
+ retention: Mapping[_Severity, timedelta | None],
318
+ *,
319
+ transaction_retention: timedelta | None = None,
320
+ now: datetime | None = None,
321
+ lock_timeout: str | None = "5s",
322
+ ) -> list[str]:
323
+ """Detach and drop the monthly partitions past their retention.
324
+
325
+ A partition is dropped when its upper bound is earlier than
326
+ ``now - retention``; one whose upper bound is exactly that instant is
327
+ kept. Each partition is detached with ``DETACH PARTITION ...
328
+ CONCURRENTLY`` from its parent (the transaction table or a severity
329
+ partition) and then dropped, one at a time. Detaches left pending by an
330
+ interrupted call are finalized first. Concurrent calls, and
331
+ ``ensure_partitions``, are serialized with an advisory lock.
332
+
333
+ ``DETACH ... CONCURRENTLY`` cannot run inside a transaction block, so
334
+ ``connection`` must be in ``AUTOCOMMIT`` mode. ``lock_timeout`` is set for
335
+ the session during the call and restored afterwards. The locks taken are
336
+ listed in the module documentation. Waiting for application transactions
337
+ that have used an audit table counts against ``lock_timeout``, so a long
338
+ open transaction makes this call fail; that is expected, and retrying
339
+ later is safe.
340
+
341
+ Args:
342
+ connection: ``AUTOCOMMIT`` connection with DDL privileges.
343
+ tables: The audit tables, from ``audit_trail.tables.build_tables``.
344
+ retention: Retention by severity value. ``None`` keeps a severity
345
+ forever. A severity that has a partition but no key here is also
346
+ kept forever, and a warning names it, so an empty mapping drops no
347
+ activity partition. A severity partition holding several values
348
+ keeps the longest of their retentions.
349
+ transaction_retention: Retention of the transaction table. It is
350
+ capped at the shortest finite severity retention, with a warning
351
+ if it is longer; ``None`` uses that shortest retention. When no
352
+ severity has a finite retention and this is ``None``, transaction
353
+ partitions are kept.
354
+ now: Reference time, timezone-aware. ``None`` uses the database's
355
+ ``now()``.
356
+ lock_timeout: PostgreSQL ``lock_timeout`` for each statement, such as
357
+ ``"5s"``. ``None`` keeps the session's setting.
358
+
359
+ Returns:
360
+ Schema-qualified names of the partitions dropped, in order.
361
+
362
+ Raises:
363
+ ValueError: If the connection is not in ``AUTOCOMMIT`` mode, a
364
+ retention is negative, or ``now`` is naive.
365
+ PartitionError: If a parent table does not exist.
366
+ PartitionLockTimeoutError: If a lock was not granted within
367
+ ``lock_timeout``. Partitions dropped before that stay dropped.
368
+ """
369
+ if not getattr(connection.connection.dbapi_connection, "autocommit", False):
370
+ raise ValueError(
371
+ "drop_expired needs an AUTOCOMMIT connection: DETACH PARTITION "
372
+ "... CONCURRENTLY cannot run inside a transaction block"
373
+ )
374
+ if any(r is not None and r < timedelta(0) for r in retention.values()) or (
375
+ transaction_retention is not None and transaction_retention < timedelta(0)
376
+ ):
377
+ raise ValueError("retention must not be negative")
378
+ _check_aware(now)
379
+ try:
380
+ return _drop(
381
+ connection, tables, retention, transaction_retention, now, lock_timeout
382
+ )
383
+ except DBAPIError as exc:
384
+ if getattr(exc.orig, "sqlstate", None) == LOCK_NOT_AVAILABLE:
385
+ raise PartitionLockTimeoutError(
386
+ f"expired partitions were not all dropped: a lock was not "
387
+ f"granted within lock_timeout={lock_timeout!r}, which applies to "
388
+ "each lock wait. An application "
389
+ "transaction left open on an audit table for longer than that "
390
+ "causes this and is expected; retry later, and a detach left "
391
+ "pending is finalized then"
392
+ ) from exc
393
+ raise
394
+
395
+
396
+ def health(
397
+ connection: Connection,
398
+ tables: AuditTables,
399
+ severities: Iterable[int],
400
+ *,
401
+ min_months_ahead: int = 2,
402
+ now: datetime | None = None,
403
+ ) -> HealthReport:
404
+ """Report partition coverage, pending detaches and orphaned partitions.
405
+
406
+ Read-only; runs on any connection.
407
+
408
+ Args:
409
+ connection: Connection that can read the catalog.
410
+ tables: The audit tables, from ``audit_trail.tables.build_tables``.
411
+ severities: A severity ``IntEnum`` class, or any iterable of ints.
412
+ min_months_ahead: Coverage below this many months after the current
413
+ one is flagged. The default of ``2`` flags one missed run of
414
+ ``ensure_partitions(months_ahead=3)``.
415
+ now: Reference time, timezone-aware. ``None`` uses the database's
416
+ ``now()``.
417
+
418
+ Returns:
419
+ The report.
420
+
421
+ Raises:
422
+ ValueError: If ``now`` is naive.
423
+ PartitionError: If a parent table does not exist.
424
+ """
425
+ _check_aware(now)
426
+ transaction_oid = _oid(connection, _qualified(tables.transaction))
427
+ activity_oid = _oid(connection, _qualified(tables.activity))
428
+ if now is None:
429
+ now = connection.execute(text("SELECT now()")).scalar_one()
430
+
431
+ transaction_months = _children(connection, transaction_oid)
432
+ severity_parents = _children(connection, activity_oid)
433
+ months = {
434
+ parent.oid: _children(connection, parent.oid)
435
+ for parent in severity_parents
436
+ if parent.relkind == "p"
437
+ }
438
+ by_severity: dict[int, _Child] = {}
439
+ for parent in severity_parents:
440
+ for value in parent.list_values():
441
+ by_severity.setdefault(value, parent)
442
+
443
+ def check(table: str | None, children: list[_Child] | None) -> PartitionHealth:
444
+ if children is None: # a plain table takes any date
445
+ covers_now, months_ahead = True, None
446
+ else:
447
+ covers_now, months_ahead = _coverage(children, now)
448
+ below = not covers_now or (
449
+ months_ahead is not None and months_ahead < min_months_ahead
450
+ )
451
+ return PartitionHealth(table, covers_now, months_ahead, below)
452
+
453
+ activity: dict[int, PartitionHealth] = {}
454
+ for value in severity_values(severities):
455
+ severity_parent = by_severity.get(value)
456
+ if severity_parent is None:
457
+ activity[value] = check(None, [])
458
+ else:
459
+ activity[value] = check(
460
+ severity_parent.display, months.get(severity_parent.oid)
461
+ )
462
+
463
+ return HealthReport(
464
+ min_months_ahead=min_months_ahead,
465
+ transaction=check(
466
+ _name(
467
+ _shown_schemas(connection, tables).transaction, tables.transaction.name
468
+ ),
469
+ transaction_months,
470
+ ),
471
+ activity=activity,
472
+ pending_detach=[
473
+ child.display
474
+ for children in (transaction_months, *months.values())
475
+ for child in children
476
+ if child.pending
477
+ ],
478
+ orphaned=_orphans(connection, tables, severity_parents),
479
+ )
480
+
481
+
482
+ class PartitionManager:
483
+ """Runs partition maintenance on the library's own connections.
484
+
485
+ ``ensure_partitions`` runs in one transaction; ``drop_expired`` switches
486
+ its connection to ``AUTOCOMMIT`` itself.
487
+
488
+ Args:
489
+ engine: Sync or async engine with DDL privileges. Must not be
490
+ configured for ``AUTOCOMMIT``.
491
+ tables: The audit tables, from ``audit_trail.tables.build_tables``.
492
+ severities: A severity ``IntEnum`` class, or any iterable of ints.
493
+ """
494
+
495
+ def __init__(
496
+ self,
497
+ engine: Engine | AsyncEngine,
498
+ tables: AuditTables,
499
+ severities: Iterable[int],
500
+ ) -> None:
501
+ self.engine = engine
502
+ self.tables = tables
503
+ self.severities = severity_values(severities)
504
+
505
+ def ensure_partitions(
506
+ self, months_ahead: int = 3, *, lock_timeout: str | None = "5s"
507
+ ) -> list[str]:
508
+ """Create missing partitions in one transaction; see ``ensure_partitions``.
509
+
510
+ Args:
511
+ months_ahead: Months to create after the current UTC month.
512
+ lock_timeout: PostgreSQL ``lock_timeout`` for the transaction.
513
+
514
+ Returns:
515
+ Schema-qualified names of the partitions created.
516
+
517
+ Raises:
518
+ TypeError: If the manager was built with an ``AsyncEngine``.
519
+ PartitionLockTimeoutError: If a lock was not granted in time.
520
+ """
521
+ if not isinstance(self.engine, Engine):
522
+ raise TypeError("the engine is async; use aensure_partitions")
523
+ with self.engine.begin() as conn:
524
+ return ensure_partitions(
525
+ conn,
526
+ self.tables,
527
+ self.severities,
528
+ months_ahead=months_ahead,
529
+ lock_timeout=lock_timeout,
530
+ )
531
+
532
+ async def aensure_partitions(
533
+ self, months_ahead: int = 3, *, lock_timeout: str | None = "5s"
534
+ ) -> list[str]:
535
+ """Async ``ensure_partitions``, for a manager built with an ``AsyncEngine``.
536
+
537
+ Args:
538
+ months_ahead: Months to create after the current UTC month.
539
+ lock_timeout: PostgreSQL ``lock_timeout`` for the transaction.
540
+
541
+ Returns:
542
+ Schema-qualified names of the partitions created.
543
+
544
+ Raises:
545
+ TypeError: If the manager was built with a sync ``Engine``.
546
+ PartitionLockTimeoutError: If a lock was not granted in time.
547
+ """
548
+ if isinstance(self.engine, Engine):
549
+ raise TypeError("the engine is sync; use ensure_partitions")
550
+ async with self.engine.begin() as conn:
551
+ return await conn.run_sync(
552
+ lambda sync_conn: ensure_partitions(
553
+ sync_conn,
554
+ self.tables,
555
+ self.severities,
556
+ months_ahead=months_ahead,
557
+ lock_timeout=lock_timeout,
558
+ )
559
+ )
560
+
561
+ def drop_expired(
562
+ self,
563
+ retention: Mapping[_Severity, timedelta | None],
564
+ *,
565
+ transaction_retention: timedelta | None = None,
566
+ lock_timeout: str | None = "5s",
567
+ ) -> list[str]:
568
+ """Drop expired partitions in ``AUTOCOMMIT`` mode; see ``drop_expired``.
569
+
570
+ Args:
571
+ retention: Retention by severity value; ``None`` keeps forever.
572
+ transaction_retention: Retention of the transaction table.
573
+ lock_timeout: PostgreSQL ``lock_timeout`` for each statement.
574
+
575
+ Returns:
576
+ Schema-qualified names of the partitions dropped.
577
+
578
+ Raises:
579
+ TypeError: If the manager was built with an ``AsyncEngine``.
580
+ PartitionLockTimeoutError: If a lock was not granted in time.
581
+ """
582
+ if not isinstance(self.engine, Engine):
583
+ raise TypeError("the engine is async; use adrop_expired")
584
+ with self.engine.connect() as conn:
585
+ return drop_expired(
586
+ conn.execution_options(isolation_level="AUTOCOMMIT"),
587
+ self.tables,
588
+ retention,
589
+ transaction_retention=transaction_retention,
590
+ lock_timeout=lock_timeout,
591
+ )
592
+
593
+ async def adrop_expired(
594
+ self,
595
+ retention: Mapping[_Severity, timedelta | None],
596
+ *,
597
+ transaction_retention: timedelta | None = None,
598
+ lock_timeout: str | None = "5s",
599
+ ) -> list[str]:
600
+ """Async ``drop_expired``, for a manager built with an ``AsyncEngine``.
601
+
602
+ Args:
603
+ retention: Retention by severity value; ``None`` keeps forever.
604
+ transaction_retention: Retention of the transaction table.
605
+ lock_timeout: PostgreSQL ``lock_timeout`` for each statement.
606
+
607
+ Returns:
608
+ Schema-qualified names of the partitions dropped.
609
+
610
+ Raises:
611
+ TypeError: If the manager was built with a sync ``Engine``.
612
+ PartitionLockTimeoutError: If a lock was not granted in time.
613
+ """
614
+ if isinstance(self.engine, Engine):
615
+ raise TypeError("the engine is sync; use drop_expired")
616
+ async with self.engine.connect() as conn:
617
+ auto = await conn.execution_options(isolation_level="AUTOCOMMIT")
618
+ return await auto.run_sync(
619
+ lambda sync_conn: drop_expired(
620
+ sync_conn,
621
+ self.tables,
622
+ retention,
623
+ transaction_retention=transaction_retention,
624
+ lock_timeout=lock_timeout,
625
+ )
626
+ )
627
+
628
+ def health(self, min_months_ahead: int = 2) -> HealthReport:
629
+ """Report partition health; see ``health``.
630
+
631
+ Args:
632
+ min_months_ahead: Coverage threshold in months after the current one.
633
+
634
+ Returns:
635
+ The report.
636
+
637
+ Raises:
638
+ TypeError: If the manager was built with an ``AsyncEngine``.
639
+ """
640
+ if not isinstance(self.engine, Engine):
641
+ raise TypeError("the engine is async; use ahealth")
642
+ with self.engine.connect() as conn:
643
+ return health(
644
+ conn, self.tables, self.severities, min_months_ahead=min_months_ahead
645
+ )
646
+
647
+ async def ahealth(self, min_months_ahead: int = 2) -> HealthReport:
648
+ """Async ``health``, for a manager built with an ``AsyncEngine``.
649
+
650
+ Args:
651
+ min_months_ahead: Coverage threshold in months after the current one.
652
+
653
+ Returns:
654
+ The report.
655
+
656
+ Raises:
657
+ TypeError: If the manager was built with a sync ``Engine``.
658
+ """
659
+ if isinstance(self.engine, Engine):
660
+ raise TypeError("the engine is sync; use health")
661
+ async with self.engine.connect() as conn:
662
+ return await conn.run_sync(
663
+ lambda sync_conn: health(
664
+ sync_conn,
665
+ self.tables,
666
+ self.severities,
667
+ min_months_ahead=min_months_ahead,
668
+ )
669
+ )
670
+
671
+
672
+ def _ensure(
673
+ conn: Connection,
674
+ tables: AuditTables,
675
+ severities: list[int],
676
+ months_ahead: int,
677
+ now: datetime | None,
678
+ lock_timeout: str | None,
679
+ ) -> list[str]:
680
+ transaction, activity = tables.transaction, tables.activity
681
+ parents = [_qualified(t) for t in (transaction, activity)]
682
+ previous_timeout: str | None = None
683
+ if lock_timeout is not None:
684
+ previous_timeout = _set_local(conn, "lock_timeout", lock_timeout)
685
+ conn.execute(
686
+ text("SELECT pg_advisory_xact_lock(hashtext(:key))"),
687
+ {"key": _lock_key(tables)},
688
+ )
689
+ if now is None:
690
+ now = conn.execute(text("SELECT now()")).scalar_one()
691
+ months = _months(now, months_ahead)
692
+ transaction_oid, activity_oid = (_oid(conn, name) for name in parents)
693
+
694
+ transaction_schema, activity_schema = _shown_schemas(conn, tables)
695
+ created: list[str] = []
696
+ created += _ensure_months(
697
+ conn,
698
+ transaction.schema,
699
+ transaction_schema,
700
+ transaction.name,
701
+ transaction_oid,
702
+ months,
703
+ )
704
+
705
+ by_severity: dict[int, _Child] = {}
706
+ for partition in _children(conn, activity_oid):
707
+ for value in partition.list_values():
708
+ by_severity.setdefault(value, partition)
709
+ for value in severities:
710
+ child = by_severity.get(value)
711
+ if child is None:
712
+ name = severity_partition_name(activity.name, value)
713
+ _execute_ddl(conn, create_severity_partition_sql(tables, value, name))
714
+ created.append(_name(activity_schema, name))
715
+ created += _ensure_months(
716
+ conn, activity.schema, activity_schema, name, None, months
717
+ )
718
+ elif child.relkind == "p":
719
+ created += _ensure_months(
720
+ conn, child.schema, child.schema, child.name, child.oid, months
721
+ )
722
+ # A severity partition that is a plain table takes any date.
723
+
724
+ if previous_timeout is not None:
725
+ _set_local(conn, "lock_timeout", previous_timeout)
726
+ return created
727
+
728
+
729
+ def _ensure_months(
730
+ conn: Connection,
731
+ schema: str | None,
732
+ shown_schema: str,
733
+ parent: str,
734
+ parent_oid: int | None,
735
+ months: list[date],
736
+ ) -> list[str]:
737
+ existing = [] if parent_oid is None else _children(conn, parent_oid)
738
+ created = []
739
+ for month in months:
740
+ start, end = month_bounds(month)
741
+ if any(child.covers(start, end) for child in existing):
742
+ continue
743
+ name = month_partition_name(parent, month)
744
+ if len(name.encode()) > MAX_IDENTIFIER_LENGTH:
745
+ raise PartitionError(
746
+ f"cannot name the {month:%Y-%m} partition of "
747
+ f"{_name(shown_schema, parent)}: "
748
+ f"{name!r} is longer than {MAX_IDENTIFIER_LENGTH} bytes and "
749
+ "PostgreSQL would truncate it; rename the parent partition"
750
+ )
751
+ _execute_ddl(conn, create_month_partition_sql(schema, parent, month, name))
752
+ created.append(_name(shown_schema, name))
753
+ return created
754
+
755
+
756
+ def _children(conn: Connection, parent_oid: int) -> list[_Child]:
757
+ rows = conn.execute(_CHILDREN, {"parent": parent_oid})
758
+ return [_Child(*row) for row in rows]
759
+
760
+
761
+ def _oid(conn: Connection, qualified: str) -> int:
762
+ oid: int | None = conn.execute(
763
+ text("SELECT to_regclass(:name)::oid"), {"name": qualified}
764
+ ).scalar_one()
765
+ if oid is None:
766
+ raise PartitionError(
767
+ f"table {qualified} does not exist; create the audit tables first"
768
+ )
769
+ return oid
770
+
771
+
772
+ def _months(now: datetime, months_ahead: int) -> list[date]:
773
+ utc = now.astimezone(timezone.utc)
774
+ index = utc.year * 12 + utc.month - 1
775
+ return [
776
+ date(i // 12, i % 12 + 1, 1) for i in range(index, index + months_ahead + 1)
777
+ ]
778
+
779
+
780
+ def _set_local(conn: Connection, setting: str, value: str) -> str:
781
+ """Set ``setting`` for the rest of the transaction; return the old value."""
782
+ previous: str = conn.execute(
783
+ text("SELECT current_setting(:name)"), {"name": setting}
784
+ ).scalar_one()
785
+ conn.execute(
786
+ text("SELECT set_config(:name, :value, true)"),
787
+ {"name": setting, "value": value},
788
+ )
789
+ return previous
790
+
791
+
792
+ _DetachMode = Literal["CONCURRENTLY", "FINALIZE"]
793
+
794
+
795
+ def _drop(
796
+ conn: Connection,
797
+ tables: AuditTables,
798
+ retention: Mapping[_Severity, timedelta | None],
799
+ transaction_retention: timedelta | None,
800
+ now: datetime | None,
801
+ lock_timeout: str | None,
802
+ ) -> list[str]:
803
+ transaction, activity = tables.transaction, tables.activity
804
+ transaction_oid = _oid(conn, _qualified(transaction))
805
+ activity_oid = _oid(conn, _qualified(activity))
806
+ limits = {int(k): v for k, v in retention.items()}
807
+
808
+ previous_timeout: str | None = None
809
+ if lock_timeout is not None:
810
+ previous_timeout = _set_session(conn, "lock_timeout", lock_timeout)
811
+ key = {"key": _lock_key(tables)}
812
+ locked = False
813
+ try:
814
+ conn.execute(text("SELECT pg_advisory_lock(hashtext(:key))"), key)
815
+ locked = True
816
+ if now is None:
817
+ now = conn.execute(text("SELECT now()")).scalar_one()
818
+
819
+ targets = [
820
+ _RetentionTarget(
821
+ _qualified(transaction),
822
+ transaction_oid,
823
+ _transaction_limit(limits, transaction_retention),
824
+ )
825
+ ]
826
+ partitioned: set[int] = set()
827
+ for child in _children(conn, activity_oid):
828
+ values = child.list_values()
829
+ partitioned |= values
830
+ if child.relkind == "p":
831
+ targets.append(
832
+ _RetentionTarget(
833
+ child.qualified, child.oid, _longest(limits, values)
834
+ )
835
+ )
836
+ for value in sorted(partitioned - limits.keys()):
837
+ logger.warning(
838
+ "severity %s has no retention; its partitions are kept. "
839
+ "Declare it, with None to keep it forever.",
840
+ value,
841
+ )
842
+ for value in sorted(limits.keys() - partitioned):
843
+ logger.warning(
844
+ "retention names severity %s, which has no partition; "
845
+ "check for a typo or run ensure_partitions",
846
+ value,
847
+ )
848
+
849
+ dropped: list[str] = []
850
+ for target in targets:
851
+ dropped += _drop_months(conn, target, now)
852
+ return dropped
853
+ finally:
854
+ # A broken connection is discarded by the pool, which releases the
855
+ # session's lock and setting; touching it would hide the real error.
856
+ if not conn.invalidated:
857
+ if locked:
858
+ conn.execute(text("SELECT pg_advisory_unlock(hashtext(:key))"), key)
859
+ if previous_timeout is not None:
860
+ _set_session(conn, "lock_timeout", previous_timeout)
861
+
862
+
863
+ def _drop_months(
864
+ conn: Connection, target: _RetentionTarget, now: datetime
865
+ ) -> list[str]:
866
+ cutoff = None if target.limit is None else now - target.limit
867
+
868
+ def expired(child: _Child) -> bool:
869
+ return (
870
+ cutoff is not None
871
+ and child.is_range
872
+ and child.upper is not None
873
+ and child.upper < cutoff
874
+ )
875
+
876
+ children = _children(conn, target.oid)
877
+ dropped: list[str] = []
878
+ # At most one partition per parent can be pending; finish it first.
879
+ for child in (c for c in children if c.pending):
880
+ _execute_ddl(conn, _detach_sql(target.parent, child, "FINALIZE"))
881
+ if expired(child):
882
+ dropped.append(_drop_table(conn, child))
883
+ else:
884
+ logger.warning(
885
+ "finalized the pending detach of %s, which has not expired; "
886
+ "it is left as a standalone table",
887
+ child.display,
888
+ )
889
+ live = [c for c in children if not c.pending and expired(c)]
890
+ for child in sorted(live, key=lambda c: c.upper or now):
891
+ _execute_ddl(conn, _detach_sql(target.parent, child, "CONCURRENTLY"))
892
+ dropped.append(_drop_table(conn, child))
893
+ return dropped
894
+
895
+
896
+ def _drop_table(conn: Connection, child: _Child) -> str:
897
+ _execute_ddl(conn, f"DROP TABLE {child.qualified}")
898
+ logger.info("dropped expired partition %s", child.display)
899
+ return child.display
900
+
901
+
902
+ def _detach_sql(parent: str, child: _Child, mode: _DetachMode) -> str:
903
+ return f"ALTER TABLE {parent} DETACH PARTITION {child.qualified} {mode}"
904
+
905
+
906
+ def _transaction_limit(
907
+ limits: dict[int, timedelta | None], requested: timedelta | None
908
+ ) -> timedelta | None:
909
+ finite = [limit for limit in limits.values() if limit is not None]
910
+ shortest = min(finite, default=None)
911
+ if shortest is None:
912
+ return requested
913
+ if requested is None:
914
+ return shortest
915
+ if requested > shortest:
916
+ logger.warning(
917
+ "transaction_retention %s is longer than the shortest severity "
918
+ "retention %s; using %s, so no transaction row outlives the "
919
+ "activity it describes",
920
+ requested,
921
+ shortest,
922
+ shortest,
923
+ )
924
+ return shortest
925
+ return requested
926
+
927
+
928
+ def _longest(limits: dict[int, timedelta | None], values: set[int]) -> timedelta | None:
929
+ longest = timedelta(0)
930
+ for value in values:
931
+ limit = limits.get(value)
932
+ if limit is None:
933
+ return None
934
+ longest = max(longest, limit)
935
+ return longest if values else None
936
+
937
+
938
+ def _coverage(children: list[_Child], now: datetime) -> _Coverage:
939
+ """Whether the current month is covered, and how many months after it."""
940
+ live = [c for c in children if not c.pending]
941
+ month = _months(now, 0)[0]
942
+ months_ahead = -1
943
+ while True:
944
+ start, end = month_bounds(month)
945
+ covering = next((c for c in live if c.covers(start, end)), None)
946
+ if covering is None:
947
+ return _Coverage(months_ahead >= 0, max(months_ahead, 0))
948
+ if covering.upper is None:
949
+ return _Coverage(True, None)
950
+ months_ahead += 1
951
+ month = end.date()
952
+
953
+
954
+ def _orphans(
955
+ conn: Connection, tables: AuditTables, severity_parents: list[_Child]
956
+ ) -> list[str]:
957
+ prefixes = [
958
+ re.escape(tables.transaction.name),
959
+ re.escape(tables.activity.name) + r"_-?\d+",
960
+ *(re.escape(p.name) for p in severity_parents),
961
+ ]
962
+ pattern = re.compile(rf"^(?:{'|'.join(prefixes)})_p\d{{4}}_\d{{2}}$")
963
+ rows = conn.execute(
964
+ text(
965
+ """
966
+ SELECT n.nspname, c.relname
967
+ FROM pg_catalog.pg_class c
968
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
969
+ WHERE c.relkind IN ('r', 'p') AND NOT c.relispartition
970
+ AND c.relnamespace IN (
971
+ SELECT relnamespace FROM pg_catalog.pg_class
972
+ WHERE oid IN (to_regclass(:transaction), to_regclass(:activity))
973
+ )
974
+ ORDER BY n.nspname, c.relname
975
+ """
976
+ ),
977
+ {
978
+ "transaction": _qualified(tables.transaction),
979
+ "activity": _qualified(tables.activity),
980
+ },
981
+ )
982
+ return [_name(schema, name) for schema, name in rows if pattern.match(name)]
983
+
984
+
985
+ def _check_aware(now: datetime | None) -> None:
986
+ if now is not None and now.tzinfo is None:
987
+ raise ValueError("now must be timezone-aware")
988
+
989
+
990
+ def _qualified(table: Table) -> str:
991
+ return qualified_name(table.schema, table.name)
992
+
993
+
994
+ def _name(schema: str, name: str) -> str:
995
+ """Unquoted ``schema.name`` for returned and logged names."""
996
+ return f"{schema}.{name}"
997
+
998
+
999
+ def _shown_schemas(conn: Connection, tables: AuditTables) -> _ShownSchemas:
1000
+ """Schemas of the transaction and activity tables, for returned names.
1001
+
1002
+ A table declared without a schema lives in the session's
1003
+ ``current_schema()``, looked up once.
1004
+ """
1005
+ declared = (tables.transaction.schema, tables.activity.schema)
1006
+ if None not in declared:
1007
+ return _ShownSchemas(str(declared[0]), str(declared[1]))
1008
+ current: str | None = conn.execute(text("SELECT current_schema()")).scalar_one()
1009
+ if current is None:
1010
+ raise PartitionError("no schema on the search_path holds the audit tables")
1011
+ return _ShownSchemas(declared[0] or current, declared[1] or current)
1012
+
1013
+
1014
+ def _lock_key(tables: AuditTables) -> str:
1015
+ parents = (_qualified(t) for t in (tables.transaction, tables.activity))
1016
+ return "audit_trail.partitions:" + ",".join(parents)
1017
+
1018
+
1019
+ def _set_session(conn: Connection, setting: str, value: str) -> str:
1020
+ """Set ``setting`` for the session; return the old value."""
1021
+ previous: str = conn.execute(
1022
+ text("SELECT current_setting(:name)"), {"name": setting}
1023
+ ).scalar_one()
1024
+ conn.execute(
1025
+ text("SELECT set_config(:name, :value, false)"),
1026
+ {"name": setting, "value": value},
1027
+ )
1028
+ return previous