Plan: Day partitions for the audit tables
Status
Done (2026-11-28) — audit_log is range-partitioned by UTC month and identity_issuance_log by UTC day (the month
erratum: day partitions made the detection scan’s span statement plan 30–40× its unpartitioned cost, months
1.3–2.3×). Retention archives a whole closed partition and drops it in one count-checked transaction, with no row
DELETE, through craig-retention’s Partitions unit; a partition-maintenance worker keeps 30 days ahead, and horizon
and overrun invariants watch both. dead_letter_audit stays on row batches. The issuance log’s capacity gates held
at #3151’s figures (#3173, note 4344549538). Resuming an interrupted archive attempt is #3179.
Closes: #3173. Relates to: ADR-058 (retention), ADR-085 D2 and D13 (the issuer’s log), #3151.
Maintainer (2026-11-27): the unit of retention is the whole partition. Once a day’s partition is past the hot
window it is archived, its row count is checked, and it is dropped in one transaction; no row is deleted.
Context
audit_log and identity_issuance_log are insert-only and retained by archive-then-DELETE (ADR-058): the shared
engine (crates/craig-retention/src/engine.rs) selects a batch past the hot window, writes it as NDJSON with a
manifest, and deletes the batch by id in one transaction. At the issuer’s design load the issuance log grows by
about 52 million rows a day (deployment-guide.adoc § Identity capacity, G8). Deleting at that rate means constant
dead tuples, vacuum work and WAL. Dropping a partition costs almost nothing.
No table in the tree is partitioned. A large live table is expensive to convert, so the cheap time is now, before
production data exists. The devstack runs PostgreSQL 18 (devstack/postgres/Dockerfile).
Three facts shape the design:
-
Both tables stamp their time column at insert (
clock_timestamp()), so a past day’s partition receives no rows. -
A partitioned table’s unique indexes must contain the partition key, and a
BEFORE INSERTrow trigger may not move a row to another partition. Todayidentity_issuance_log’s trigger assigns `recorded_at. -
The owner’s default privileges grant the app login
SELECT, INSERT, UPDATE, DELETEon every new table (devstack/postgres/init.sql), so a new partition is writable by the app login unless that is revoked.
Scope
In: the partitioned shape (D1); the database functions that make, list and drop partitions (D2); the two migrations (D3); the worker that keeps future partitions in place (D4); the engine’s partition unit (D5); readers, the capacity harness and invariants (D6).
Out:
-
dead_letter_audit. Its dedupe is a unique index onoccurrence_tokenalone (services/craig-security/src/store/dead_letter.rs,ON CONFLICT). PostgreSQL does not allow a unique index without the partition key on a partitioned table, and the table’s volume is small. It stays on row batches. -
pg_partmanor any other extension: two small functions we own do the work, with no new dependency in every deployment’s database. -
An attempt that resumes after a restart (#3179). An interrupted attempt starts again (D5).
-
craig-rules' and craig-exchange’s archived tables, and the purge of archived objects.
Design
D1. The shape
Both tables become PARTITION BY RANGE on their insert-time column, one partition per UTC day, named
<table>_pYYYYMMDD, with bounds at 00:00 UTC. There is no default partition.
| Table | Key and primary key | Indexes |
|---|---|---|
|
|
Every current index is re-created on the parent, except |
|
|
None besides the key: it replaces both the old key and |
id alone is no longer unique by constraint. Audit ids come from the column default (uuidv7()) and issuance ids
from Uuid::now_v7(), and neither writer handles a duplicate-key error on these tables.
identity_issuance_log.recorded_at gains DEFAULT clock_timestamp(). The issuer still holds no INSERT privilege
on the column, so the default is what it gets. identity_issuance_log_stamp stops assigning recorded_at and
computes row_digest from the defaulted value. The immutability guard becomes a row-level BEFORE UPDATE trigger
on the parent, which every partition inherits, plus a BEFORE TRUNCATE statement trigger on the parent and on each
partition.
D2. The database functions
For each table, three functions owned by the table’s owner. Shared private helpers hold the logic; the app login may execute only these wrappers, and the issuer login none of them.
| Function | Contract |
|---|---|
|
Creates each missing day’s partition in the range, at most 400 days a call, and is idempotent. A partition is
created standalone with a |
|
The days that have a partition, read from the catalog by the naming rule. |
|
Refuses a day that is not before the current UTC date. Sets |
identity_prune_issuance_log(UUID[]) is dropped: the partition drop replaces it.
D3. The migrations
One migration per table, in services/craig-security/migrations/:
-
Rename the table aside and drop its indexes.
-
Create the partitioned table with the same columns, defaults and CHECKs, the key and indexes of D1, and the functions of D2. For the issuance log, re-create its triggers and its grants: column-level
INSERTfor the issuer,SELECTfor the app login. -
ensure_partitionsfrom the oldest existing row’s day, or yesterday if that is later, to today plus 30 days. -
Copy every row across, then drop the renamed table.
The copy holds an exclusive lock for its length. That is acceptable only because no deployment holds production
data; the release note says so. The schema-floor handling follows cargo xtask validate-migration-constraints. The
issuance migration bumps the floor, because it drops the prune function an older archiver calls.
D4. Keeping future partitions in place
A new supervised worker in craig-security, partition-maintenance (src/partition_maintenance.rs, registered in
EXPECTED_WORKERS in src/lib.rs), calls both ensure_partitions functions for yesterday to today plus 30 days,
at start and then hourly. It runs whether or not archiving is enabled. The issuer process does not call it: its
login stays insert-only (ADR-085 D2).
Tests and seeds that insert rows with older timestamps call ensure_partitions for those days first
(tests/e2e/.seed-sql/craig_security.sql, services/craig-security/tests/archive_engine.rs, the detection tests).
D5. The engine’s partition unit
ArchiveTableSpec (crates/craig-retention/src/spec.rs) carries a unit in place of its two SQL fields:
pub enum ArchiveUnit {
/// Archive row batches past the hot window and delete each by id.
Rows { select_batch_sql: &'static str, delete_by_ids_sql: &'static str },
/// Archive a whole closed partition, then drop it.
Partitions {
/// `$1` hot-window days: the oldest day whose partition ends at or before now minus the window.
oldest_closed_sql: &'static str,
/// `$1` day, `$2` and `$3` the last row's time and id, `$4` limit: the next rows by (time, id).
select_page_sql: &'static str,
/// `$1` day, `$2` expected rows: the count found; the partition is dropped when they are equal.
drop_sql: &'static str,
},
}
Every existing spec moves its two strings into Rows unchanged. A Partitions spec’s page query reads through
the parent with the day’s bounds, since the app login holds no privilege on an issuance partition. For a
Partitions table one step of the round-robin is one attempt at the oldest closed partition:
-
A fresh attempt id. Objects go under
<prefix>/<service>/<table>/<day>/<attempt>/. -
Pages are read by keyset on (time, id) and written exactly as a row batch is today: NDJSON then its manifest, no-overwrite puts, under a fresh archive id each. The attempt keeps the manifests in memory.
-
A row larger than the byte cap holds the partition: the attempt stops, nothing is dropped, and the table is set aside for the pass with a warning and the existing quarantine metric.
-
After the last page a partition manifest is written to
<attempt>/partition.manifest.json: formatcraig.partition-manifest.v1, the table, day and attempt, the row total, and each object’s keys, digest and count. -
One transaction: the service’s bookkeep closure runs for each object manifest, then
drop_sqlwith the row total. A returned count that differs rolls the transaction back asPruneCountMismatch.
An empty partition is dropped with expected 0 and no objects. An attempt is not cut by the per-pass batch budget,
since a partition is the unit (test an_attempt_longer_than_the_pass_budget_completes). Cancellation is observed
between pages and abandons the attempt. An abandoned or
failed attempt leaves its objects unreferenced by the ledger, as a crashed batch does today, and the next pass
starts a new attempt.
D6. Readers, the harness and invariants
-
Queries bounded by time prune to their partitions. The detection scan’s span query filters on
xact_idalone (services/craig-security/src/detection_sql.rs), so it probes every partition’sxact_idindex. Step 3 times that scan against about 120 partitions and against the unpartitioned table, and records both on #3173. -
log_bytes_per_row(xtask/src/cmd/perf/identity/rig.rs) sumspg_total_relation_sizeover the partitions: on the parent alone it reads 0. -
Invariants in
crates/craig-invariants/sql/craig-security/:audit_log_partition_horizonandidentity_issuance_log_partition_horizonfire when fewer than 7 future days have a partition;identity_issuance_log_hot_window_overrunjoins the two that exist;identity_execute_matrix.sqlcovers the new functions and the partitions' privileges.
Steps
Each step is one MR from main, with its tests, docs and a changelog.d/ fragment.
-
Plan. This page and its nav entry; the issue for resumable attempts is #3179.
-
Engine. D5, tested on a test-local partitioned table with D2’s drop contract. Every spec moves to
Rows. -
audit_log. D1 to D4 for
audit_log, its spec moved toPartitions, D6’s scan timing and its two invariants. -
identity_issuance_log. D1 to D3 for the log, the worker extended to it, its spec moved to
Partitions, the harness fix and the remaining invariants. Starts after #3151’s last MR merges. Its MR runsissuer-capacity --steps gates --r 3; G1, G3 and G4 must be no worse than #3151’s final figures. -
Close. The plan to
plans/archive/, StatusDone, #3173 closed.
Risks
-
A partition is dropped with rows that were not archived (fail-open, the worst case). Mitigation: the drop function counts under a lock that stops writers and drops only on an equal count, and refuses today’s partition; tests
a_count_mismatch_keeps_the_partitionandthe_drop_refuses_a_day_that_is_not_past. -
A row lands in a closed partition after it was read (silent loss). Mitigation: the same count check; test
an_insert_racing_the_drop_keeps_the_partition_or_is_archived. -
No partition exists for today (fail-closed: audit inserts retry, and mints answer 503). Mitigation: 30 days are made at every migration, at start and hourly, and the horizon invariants fire at 7; tests
the_worker_keeps_thirty_days_aheadandthe_horizon_invariant_fires_below_seven_days. -
A new issuance partition is writable by the app login (fail-open for the log’s immutability). Mitigation:
ensure_partitionsrevokes on each partition; testsa_new_issuance_partition_grants_nothing_directlyandupdate_and_truncate_are_refused_on_a_partition. -
The drop’s lock on the parent stalls writers (fail-closed: latency, bounded by the 2 s
lock_timeout, after which the drop gives up until the next pass). Mitigation: the count runs before the parent is locked; testa_partition_drop_fails_no_concurrent_insert, and step 4’s capacity run. -
A cancelled attempt repeats, or a row past the byte cap holds its partition, and retention falls behind (silent backlog; nothing is lost). Mitigation: the hot-window overrun invariants fire. For a held partition the deployment guide tells the operator to raise
RETENTION_ARCHIVE__MAX_BATCH_BYTES; for repeats, #3179. -
Making a partition stalls writers (fail-closed: latency). Mitigation: a partition is attached, not created in place, so the parent is never locked against inserts; test
making_a_partition_waits_for_no_open_insert. -
Readers without a time bound get slower (silent). Mitigation: step 3’s timing, raised with the maintainer before landing if the scan is more than twice as slow.
-
A duplicate id is no longer refused (silent). Mitigation: both id sources are UUIDv7 generators, and no code depends on the refusal; the data-model page records the change.
-
The harness reports zero bytes a row (silent wrong figure). Mitigation: D6’s sum; test
the_log_size_sums_its_partitions. -
The migration’s copy locks a large table (fail-closed). Mitigation: no production data exists; the release note.
Tests
Engine (crates/craig-retention/tests/, devstack database).
-
a_closed_partition_is_archived_whole_then_dropped: the objects hold every row; the ledger has one row an object. -
a_partition_inside_the_hot_window_is_left_alone, anda_partition_closes_only_when_its_last_instant_leaves_the_window. -
a_count_mismatch_keeps_the_partition,a_cancelled_attempt_drops_nothing_and_the_next_pass_completes,a_row_past_the_byte_cap_holds_its_partition,an_empty_partition_is_dropped_without_objects. -
an_attempt_longer_than_the_pass_budget_completes: a partition with more pages than the pass’s batch budget is archived and dropped in one pass. -
Every existing row-mode engine test passes unchanged on
Rows.
Property. the_objects_of_a_partition_hold_exactly_its_rows: over generated row counts, page sizes and equal
timestamps at page edges, the objects' lines equal the rows in (time, id) order, with none repeated or missing.
Concurrency.
-
an_insert_racing_the_drop_keeps_the_partition_or_is_archived. -
a_partition_drop_fails_no_concurrent_insert: a writer inserts into today’s partition throughout a drop. -
making_a_partition_waits_for_no_open_insert: with a transaction holding an uncommitted insert on the parent,ensure_partitionsmakes a new day under a 1 slock_timeoutand succeeds.
Contract. The partition manifest’s round trip and pinned JSON; the per-object manifest is unchanged.
Schema (services/craig-security/tests/constraints/).
-
the_migration_keeps_every_row, for each table, over rows on several days. -
a_row_routes_to_its_days_partition,ensure_partitions_is_idempotent,the_worker_keeps_thirty_days_ahead. -
the_drop_refuses_a_day_that_is_not_past,only_the_app_login_may_drop_a_partition. -
the_issuer_still_cannot_set_recorded_at_or_read_the_log,the_row_digest_covers_the_defaulted_time,a_new_issuance_partition_grants_nothing_directly,update_and_truncate_are_refused_on_a_partition.
Regression. the_log_size_sums_its_partitions, the case the parent-only size reading would have failed.
End to end (services/craig-security/tests/archive_engine.rs). Both real tables archive a closed partition and
drop it; dead_letter_audit still archives by rows.
Delivery
-
ADRs: ADR-058 gains an amendment: for a partitioned source the crash-atomic unit is the partition, and a count-checked drop replaces the id-keyed delete. ADR-085 gains one: the log is partitioned,
recorded_atcomes from a column default, the prune function is replaced, and the issuer’s privileges are unchanged. -
Docs, each in the step that changes its surface:
data-model-security.adoc(both tables and the functions),deployment-guide.adoc(retention, the partition horizon and its alarm, G8’s size reading) andshared-crates.adoc(the engine’s unit). -
CHANGELOG entry: one
changelog.d/3173.<slug>.changed.adocfragment per step, folded intoCHANGELOG.adocat release. Steps 3 and 4 are schema changes and carry operations notes. -
Close: step 5 closes #3173 and archives the page.
Erratum (2026-11-27): audit_log is partitioned by UTC month, not day: on day partitions the detection scan’s span statement, which filters on xact_id and so plans against every partition, measured ≈30–40× its unpartitioned cost through sqlx, and on month partitions ≈1.3–2.3× (#3173). Its partitions are audit_log_pYYYYMM, its functions take a month’s first day, and a month drops once its last instant leaves the hot window. identity_issuance_log stays daily.
Review log
| Round | Vendor | Resolved model | Verdict |
|---|---|---|---|
1 |
Anthropic (Vertex) |
|
FLAGS on the second question: two assertions named no test, an attempt that outlasts the pass budget and attaching a partition without blocking inserts. Each now has one, and the risks say how an operator clears a partition held by an oversized row. |
2 |
Google (Vertex) |
|
CLEAN on all four questions; the maintainer then approved the plan for implementation. |