Plan: Exact detection windows

Status

Done (2026-11-26) — every detection rule fires whenever some window of its length holds its threshold of matching audit rows, at the first scan that sees all of them, however the scans fall and however late a row’s transaction commits. Each audit row records its inserting transaction (audit_log.xact_id), one row records the last scan’s snapshot (detection_scan_watermark), and a scan is one transaction that locks it and counts the windows holding a row committed since. An acknowledged burst does not fire again, and a new rule’s first scan reports the windows holding a row committed since the scan before it. On a devstack, the first scan over 1,517 new audit rows took under 0.1 s through the route, and the index added about 0.006 ms to the median audit insert.

Closes: #2771. Relates to: #2765 (plan audit-batched-claims D8, whose documented guarantee this replaces).
Prerequisite: #3163 merges first (a window_minutes under 1 is refused, by a CHECK D3 relies on). Tree: main at 8914f1210.
Rulings (maintainer, 2026-11-26, on #2771): a transaction-id watermark, not a lookback padded by an assumed commit delay; an acknowledged burst does not fire again, where a row no scan had evaluated at the acknowledgement still can (D4); a new or re-enabled rule reports the windows holding a row committed after the scan before its first; the after-hours rule is made exact too, its classification unchanged.

Context

A detection rule (detection_rules) has a type, a threshold and a window_minutes (W). Each scan (services/craig-security/src/detection.rs run_detection_scan, every CRAIG_SECURITY__DETECTION_INTERVAL_SECS or on POST /v1/security/detection/run) counts the matching audit_log rows stamped in the W minutes before it (detection_sql.rs count_within_window, timestamp > now() - W) and fires when the count reaches the threshold.

A trailing count taken at sampled instants misses clusters. A row stamped at T (clock_timestamp() at its insert, #2765) is visible only from its commit at T + d, and scans are I seconds apart, so a cluster is certain to fire only when its span is under W − I − d (data-model-security.adoc § detection_rules). Two rows 115 s apart under a 120 s window are missed when no scan falls between the second row’s commit and the first row’s 120th second. detection_misses_a_cluster_whose_older_row_leaves_the_window_before_the_commit (audit_batch_tests.rs) pins it.

No lookback by a commit-delay allowance closes the gap: a stalled commit flush has no bound a timeout can enforce. What is exact is to ask, at each scan, which rows were committed since the scan before it, by transaction id.

Scope

In:

  1. audit_log.xact_id, the inserting transaction’s id, and a one-row watermark: the snapshot of the last scan.

  2. One scan is one transaction that holds the watermark row’s lock, so scans run one at a time.

  3. All four rule types count by windows anchored at rows, among windows holding a row committed since the watermark.

  4. The tests, the plan pin of the index use, the scan route’s documented 504, and the docs.

Out: a per-actor or per-resource count (each rule still counts system-wide); what any rule type matches (detection_sql.rs predicates) and the after-hours classification; alert content beyond the count it reports (D4).

Design

D1. The transaction id on each row

Migration services/craig-security/migrations/<stamp>_detection_exact_windows.sql, with the timeouts and the lock note of 20261117120000_detection_closed_tokens.sql (the index build holds a SHARE lock on audit_log):

ALTER TABLE audit_log ADD COLUMN xact_id BIGINT NOT NULL DEFAULT 0;
ALTER TABLE audit_log ALTER COLUMN xact_id SET DEFAULT (pg_current_xact_id()::text)::bigint;
CREATE INDEX idx_audit_log_xact_id ON audit_log (xact_id);
  • Two statements for the column. A constant default in ADD COLUMN is kept in the catalog and rewrites nothing, where a volatile one rewrites the table; the second statement changes the default for new rows only. Existing rows read 0, which is no transaction’s id and means "committed before this migration" (the ALTER waits out every open writer of the table). By D2’s definitions a row with id 0 is seen by every scan and fresh in none.

  • A default, not an insert column. store::audit::insert_audit_entry does not name the column, so a released binary’s inserts are stamped too, and no insert path can leave the id out.

  • BIGINT. pg_current_xact_id() is the top-level transaction’s 64-bit id, also inside the batched subscription’s savepoints, and it does not wrap. Core PostgreSQL casts xid8 to bigint only through text.

  • A B-tree. Each scan reads the ids above the watermark, a short range at the index’s right edge. BRIN costs less per insert, but retention deletes old rows and new ids reuse their space, which takes its selectivity.

  • store::models::AuditEntry does not gain the field and no API serves it. The retention archive copies whole rows (retention_archive.rs, to_jsonb(t)), so archived rows carry xact_id from here on.

  • Schema floor. None expected (cargo xtask validate-migration-constraints settles it in step 2): an N−1 binary’s inserts take the default; its scans count as today, take no lock and leave the watermark alone, and its alert is the standing alert a new scan’s probe or insert then finds (fire_alert_for_rule’s `None arm).

D2. The scan transaction and the watermark

The same migration:

CREATE TABLE detection_scan_watermark (
    singleton   BOOLEAN PRIMARY KEY DEFAULT true CHECK (singleton),
    xmax        BIGINT NOT NULL,
    in_progress BIGINT[] NOT NULL,
    scanned_at  TIMESTAMPTZ NOT NULL
);
INSERT INTO detection_scan_watermark (xmax, in_progress, scanned_at)
SELECT (pg_snapshot_xmax(s)::text)::bigint,
       ARRAY(SELECT (x::text)::bigint FROM pg_snapshot_xip(s) AS x), now()
  FROM pg_current_snapshot() AS s;

A snapshot is (xmax, in_progress): transaction x had completed in it when x < xmax AND x <> ALL(in_progress). New services/craig-security/src/store/detection_scan.rs holds Snapshot { xmax: i64, in_progress: Vec<i64> } and three functions over a transaction. run_detection_scan keeps its signature and becomes one READ COMMITTED transaction (stated with SET TRANSACTION), in this order:

  1. lock_watermark: SELECT xmax, in_progress FROM detection_scan_watermark FOR UPDATE. This is P, the snapshot of the last committed scan, and the row lock makes a second scan wait here until the first commits. No row is an error naming the table.

  2. current_snapshot: the SELECT above without the INSERT. This is S. Taken after the lock, it is later than P.

  3. List the rules; for each enabled rule: the standing-alert probe, the count (D3), and the alert with its event. All run on the transaction: store::detection_rules::list_rules and store::alerts::has_unacknowledged_for_rule take an executor in place of the pool, and fire_alert_for_rule takes the transaction and neither commits nor rolls back.

  4. advance_watermark: UPDATE detection_scan_watermark SET xmax = $1, in_progress = $2, scanned_at = now().

  5. Commit, then dispatch the webhooks of the alerts created.

A row is seen by the scan when its transaction had completed in S. It is fresh when its transaction had completed in S and had not in P.

Why this is exact. A transaction that had completed in one snapshot has completed in every later one, and scans are serialized, so each row with an id is fresh in exactly one committed scan, and that scan sees every row committed before it. Take any set of matching rows whose span is under W, and the member a scan sees last: it is fresh in that scan, the others are seen, and the window anchored at the set’s earliest row holds them all.

One transaction. The alerts, their events and the new watermark commit together. A scan that fails rolls all of it back, so the rows stay fresh for the next scan and nothing is evaluated twice. A scan uses one connection for its whole length, the wait included, so the scan holding the lock needs no second one that waiting scans could hold.

The wait is bounded. Every pooled connection has a statement_timeout (crates/craig-db/src/lib.rs: 30 s unless CRAIG_SECURITY__DB_STATEMENT_TIMEOUT_MS says otherwise), so a scan waiting on the lock, or a count that runs long, is cancelled (SQLSTATE 57014). The scheduler logs it and the route answers the existing 504 db-timeout, which its responses(…​) now lists.

D3. The two statements of a count

detection_sql.rs replaces count_within_window and the three COUNT_* statics with two builders, window_bounds(predicate, first_snapshot_bind) and largest_window(predicate, first_snapshot_bind); pattern_indexes returns each rule’s pair. $1 is W in minutes; the four snapshot binds (P’s two, then S’s two) follow at $2 for the pattern rules and at $5 for after-hours, whose AFTER_HOURS_PREDICATE keeps $2–$4 and its text; largest_window takes its two bounds after them.

-- window_bounds: the span in which a fresh matching row can share a window
WITH recent AS MATERIALIZED (
    SELECT timestamp, action, success, xact_id FROM audit_log WHERE xact_id >= $P.xmax
    UNION ALL
    SELECT timestamp, action, success, xact_id FROM audit_log WHERE xact_id = ANY($P.in_progress))
SELECT min(timestamp) - make_interval(mins := $1), max(timestamp) + make_interval(mins := $1)
  FROM recent WHERE <predicate> AND <seen>;
-- largest_window: run when the bounds are not NULL
SELECT COALESCE(max(held), 0)
  FROM (SELECT count(*) OVER w AS held, count(*) FILTER (WHERE <fresh>) OVER w AS fresh_held
          FROM audit_log WHERE <predicate> AND timestamp > $lo AND timestamp < $hi AND <seen>
        WINDOW w AS (ORDER BY timestamp RANGE BETWEEN CURRENT ROW
                     AND make_interval(mins := $1) - interval '1 microsecond' FOLLOWING)) AS windows
 WHERE fresh_held > 0

<seen> is xact_id < $S.xmax AND xact_id <> ALL($S.in_progress); <fresh> is (xact_id >= $P.xmax OR xact_id = ANY($P.in_progress)) AND <seen>.

  • recent is every row not completed in P, with the columns the four predicates read, reached by xact_id alone: MATERIALIZED keeps the planner from pushing the predicate in and reading the rule’s whole partial index for it. The two branches share no row. NULL bounds mean no fresh matching row: the count is 0 and the second statement does not run. The second reads the rule’s partial index over a bounded range, as today’s count does.

  • Each window is [a, a + W) from a seen matching row a: half-open, as today’s timestamp > now() - W is, and timestamptz resolves microseconds. Any window of length W slides right onto its first row and keeps its rows, so the windows anchored at rows find the largest count. The frame offset is positive because W ≥ 1 (#3163).

  • The result is the largest count among windows holding a fresh row, and 0 with no fresh row. A threshold-0 rule therefore still fires on every scan it is not suppressed in, as the devstack tests that use one expect. count_for_rule takes the transaction and both snapshots beside the rule and the timezone.

D4. What the scan does with the count

Unchanged: the standing-alert probe first, then count >= threshold, then the alert with that count; details.count and the description now give the largest window’s count. While an alert stands, the rule’s fresh rows pass with each scan. After the acknowledgement the rule can fire only on a window holding a row no scan had yet evaluated: one committed after the last scan before the acknowledgement, so up to one scan interval before the acknowledgement itself. A rule created or re-enabled between two scans is first evaluated at the next, on the rows fresh then.

D5. Existing tests that change

  • audit_batch_tests.rs: detection_misses_a_cluster_whose_older_row_leaves_the_window_before_the_commit becomes detection_fires_on_a_cluster_whose_older_row_left_the_window_before_the_commit and asserts one alert of count 2 on the scan after the delayed commit. It pinned the defect this plan removes; its premises stay asserted, and its control leg goes (the fire it controlled for now happens without shifting the rows). detection_fires_on_a_cluster_whose_span_fits_w_minus_i_minus_d stays; its doc loses the W − I − d premise.

  • detection.rs concurrent_fire_creates_exactly_one_alert_and_one_staged_event: each of its four tasks opens its own transaction around fire_alert_for_rule and commits on Some. What it asserts is unchanged.

  • detection_fire_tests.rs and null_band_after_hours_rule_counts_zero: pass a transaction and the snapshots taken before and after filing their rows. What each asserts is unchanged.

  • detection_sql.rs each_pattern_predicate_names_exactly_its_tokens: the pinned statement text. tests/api/detection.rs detection_counts_use_their_partial_indexes: see Tests, plan pin.

D6. Documentation

data-model-security.adoc: § audit_log gains xact_id (and that archived rows carry it); § detection_rules replaces the threshold / window_minutes note with the exact rule (a set of at least threshold matching rows with span under W fires at the first scan that sees all of them, unless an unacknowledged alert stands), D4’s two sentences, and one scan at a time; a new § detection_scan_watermark; idx_audit_log_xact_id. Two operator notes there: set xact_id to 0 on rows restored from another cluster, which keep its ids; and the statement that moves the watermark to now, for a backlog too large to read.

Steps

Each step is one MR on the train; step 2 stacks on step 1 and starts after #3163 has merged.

  1. Plan page. This file under docs/modules/ROOT/pages/plans/, the nav entry.

  2. Exact windows (D1–D6). The migration, store/detection_scan.rs, detection_sql.rs, detection.rs, the route’s responses(…​) and cargo xtask api-docs, the tests, the docs and the release note. Before the MR lands, on a devstack on luchs: the craig-security suite; one scan’s time; and examples/inbox_latency_probe before and after the migration, for the index’s cost per audit insert. Both figures go on the issue. The plan is archived on this branch.

Risks

Risk Mode Mitigation

A new row carries id 0, so no scan finds it fresh

silent

the column default, which no insert names past; a_filed_row_carries_its_transaction_id files a row through handle_inbound_event under a savepoint and compares it with the transaction’s id

A row committed after a scan’s snapshot is missed, or evaluated twice

silent

D2; the two regression tests, a_row_is_fresh_in_exactly_one_scan, and the batched-commit leg of D5 through the real subscriber

Two scans overlap (two replicas' schedulers, or the route) and both evaluate a row

silent

the watermark row’s lock; overlapping_scans_fire_once_and_evaluate_each_row_once; concurrent_scan_volley_yields_exactly_one_standing_alert still holds

A scan stuck holding the lock stops every other scan

fail-closed

each waiter is cancelled at the statement timeout and errors; the scheduler logs each failure and its heartbeat goes stale; the route answers 504; a_scan_waiting_behind_another_fails_at_the_statement_timeout

One rule’s statement or insert fails, so the scan rolls back and no rule fires

fail-closed

the rows stay fresh, so nothing is lost; the failure is logged on every tick and the heartbeat goes stale; today’s scan also stops at the failing rule; a_failed_scan_fires_nothing_and_leaves_the_watermark

The watermark row is gone

fail-closed

the scan errors naming the table; the migration seeds it and the singleton key admits one row; a_missing_watermark_fails_the_scan

After a long time with no scan, the fresh rows outgrow one statement’s timeout

fail-closed

every scan then fails, logged, and the heartbeat goes stale; D6’s operator note gives the statement that moves the watermark to now, which gives up the backlog knowingly

A count reads a rule’s whole partial index, so a scan grows with the table

fail-closed

window_bounds reaches audit_log by xact_id alone (D3); the plan pin holds both statements; step 2 records a scan’s time

The new index slows audit inserts, or its build blocks them

fail-closed

the probe’s before and after figures; inserts wait out the build and the consumer redelivers, as migration 20261117120000 documents

Rows restored from another cluster are fresh once and fire a rule on an old burst

silent

bounded to once per row; D6’s operator note, whose statement a_row_set_to_id_zero_is_counted_and_starts_no_window runs

An operator expects an acknowledged burst, or one older than a new rule, to fire

silent

ruled; the release note and § detection_rules state both; a_standing_alert_suppresses_and_acknowledging_rearms_on_new_rows and a_new_rule_reports_a_window_completed_after_it_exists

Tests

The new tests each clone a migrated craig-security database (craig_test_lib::template_db, as detection_fire_tests.rs does), insert matching rows with explicit timestamps, one transaction each, and drive run_detection_scan. They go in src/detection_window_tests.rs, carry // @axis:, and need the devstack’s PostgreSQL for the clone, so they are #[ignore = "requires devstack"].

  • Regression (the cases that would have caught the gap): rows_115_seconds_apart_fire_whatever_the_scan_times (W = 2, threshold 2: a scan; a row stamped 200 s back; a scan; a row stamped 115 s after it; the next scan fires with count 2) and a_row_committed_after_a_scan_joins_its_window_at_the_next_scan (the second row’s transaction stays open across a scan, and the first row is older than W when it commits). Both are written first and fail on main, where run_detection_scan has the same signature.

  • Concurrency: overlapping_scans_fire_once_and_evaluate_each_row_once: four barrier-synchronized scans over two fresh rows and a threshold-2 rule leave one alert and one staged event; after its acknowledgement a scan with no new row fires nothing. a_scan_waiting_behind_another_fails_at_the_statement_timeout: with the watermark row locked by the test and a 200 ms statement timeout, the scan fails with SQLSTATE 57014, and succeeds once released.

  • Boundary (@axis: boundary): rows_a_window_apart_are_not_in_one_window: 120 s apart, no; 119.999999 s, yes.

  • Exactly once: a_row_is_fresh_in_exactly_one_scan: a row counts in the scan after its commit and in no later one. a_snapshot_tells_a_completed_transaction_from_an_open_one.

  • After hours: the DST test unchanged; after_hours_fires_on_a_window_of_out_of_band_rows.

  • Suppression, new rule, threshold 0: a_standing_alert_suppresses_and_acknowledging_rearms_on_new_rows; a_new_rule_reports_a_window_completed_after_it_exists; a_threshold_zero_rule_fires_on_a_scan_with_no_fresh_row.

  • Failure (@axis: evil): a_failed_scan_fires_nothing_and_leaves_the_watermark (a CHECK added to the clone refuses the second rule’s alert; the first rule’s alert and event are absent and the watermark is as it was; with the CHECK dropped the next scan fires both); a_missing_watermark_fails_the_scan.

  • Property (@axis: prop): the_largest_window_equals_a_brute_force_count: up to 30 rows at random microseconds of one hour, a random fresh subset and W, against a Rust oracle over every row-anchored window.

  • Migration (constraints suite): audit_log_xact_id_migration: existing rows read 0, audit_log’s `pg_relation_filenode is unchanged (no rewrite), a new insert carries its transaction’s id, the watermark row is seeded. Id 0: a_row_set_to_id_zero_is_counted_and_starts_no_window (the operator note’s UPDATE).

  • Contract (wire): the route’s 504 in the generated OpenAPI, cargo xtask api-docs --check. Nothing else on the wire changes; the 57014 → 504 mapping has its tests in craig-common.

  • Plan pin: detection_counts_use_their_partial_indexes, with every parameter written as a literal the way $1 is today, asserts idx_audit_log_xact_id in each window_bounds plan and the rule’s partial index in each largest_window plan.

Every always / never / exactly above and its test: "each row with an id is fresh in exactly one committed scan" → a_row_is_fresh_in_exactly_one_scan and overlapping_scans_fire_once_and_evaluate_each_row_once; "a set under W fires at the first scan that sees all of it" → the two regression tests and the property test; "a failed scan rolls all of it back" → a_failed_scan_fires_nothing_and_leaves_the_watermark; "no insert path can leave the id out" → a_filed_row_carries_its_transaction_id, the migration test; "id 0 is fresh in none" → the id-0 test.

Delivery

  • Doc page: docs/modules/ROOT/pages/data-model-security.adoc (D6); the generated api/craig-security.adoc.

  • CHANGELOG entry: changelog.d/2771.changed.adoc: the exact rule, D4, and an Ops: clause (the index build’s lock and D6’s two notes).

  • Close: Closes #2771 on step 2; milestone; a closing note (merge sha, car, both figures); the plan archived.

Review log

Round Vendor Resolved model Verdict

1

Anthropic (Vertex)

vertex-anthropic/claude-fable-5-2

FLAGS on the second question: the operator note that set restored rows' xact_id to NULL was refused by the draft’s own NOT NULL CHECK; the rule list and the standing-alert probe took the pool, not the scan’s transaction. The column became NOT NULL DEFAULT 0 with 0 meaning committed before the migration, and both store functions take an executor.

2

Google (Vertex)

vertex-gemini/gemini-4-carbon

FLAGS on the second question: one statement mixing the fresh-row test with the rule’s predicate let the planner read the rule’s whole partial index instead of the transaction-id index. D3 split the count into a bounds statement that reaches audit_log by xact_id alone and a bounded window statement, each held by the plan pin; the maintainer then approved the edited plan for implementation.

Erratum (2026-11-26, step 2): the watermark’s xmax column is snapshot_xmax, because xmax is a PostgreSQL system column name and the migration’s CREATE TABLE refused it. D2’s SQL reads with that name.

Edit this page · latest