runlimit-postgres 0.3.1

Replica-safe PostgreSQL rate-limit storage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use std::{future::Future, time::Duration};

use runlimit_core::{BatchDecision, Check, Decision, Denial, QuotaDenial, QuotaMode};
use sqlx::{
    Acquire, PgPool, Postgres, Row, Transaction,
    pool::PoolConnection,
    postgres::{PgArguments, PgQueryResult, PgRow, types::PgInterval},
    query::Query,
    types::chrono::{DateTime, Utc},
};
use tokio::time::{Instant, timeout, timeout_at};

use crate::{
    CheckError, ConnectionOutcome,
    protocol::{
        BATCH_ADVISORY_LOCK_SQL, BATCH_CAPACITY_LOCK_SQL, BATCH_PREFLIGHT_SQL, BATCH_ROW_LOCK_SQL,
        BATCH_UPSERT_SQL, CAPACITY_SHARD_COUNT, SET_LOCAL_TIMEOUTS_SQL, advisory_lock_id,
        capacity_shard, is_server_timeout, remaining_server_timeout_settings,
    },
};

pub(crate) fn single_decision_from_batch(batch: BatchDecision) -> Result<Decision, CheckError> {
    batch.try_into_single_decision().map_err(|invalid| {
        if invalid.would_deny() {
            return CheckError::ResponseInvariant;
        }
        // A future outcome may describe already-committed quota, so keep
        // the public error's consumption classification conservative.
        CheckError::CommittedResponseInvariant
    })
}

#[derive(Debug)]
enum PendingBatchOutcome {
    Allowed(Vec<PendingAllowance>),
    Denied { index: usize, denial: PendingDenial },
}

#[derive(Debug)]
pub(crate) struct BatchSqlInput {
    policy_ids: Vec<String>,
    scope_ids: Vec<String>,
    fingerprints: Vec<Vec<u8>>,
    subjects: Vec<Vec<u8>>,
    capacity_shards: Vec<i16>,
    pub(crate) lock_input_positions: Vec<i64>,
    advisory_lock_ids: Vec<i64>,
    windows: Vec<PgInterval>,
    costs: Vec<i64>,
    limits: Vec<i64>,
}

impl BatchSqlInput {
    pub(crate) fn from_checks(checks: &[Check<'_>]) -> Self {
        let counter_keys = checks.iter().map(Check::counter_key).collect::<Vec<_>>();
        let mut ordered_indices = (0..checks.len()).collect::<Vec<_>>();
        ordered_indices.sort_unstable_by_key(|index| counter_keys[*index]);

        let mut input = Self {
            policy_ids: Vec::with_capacity(checks.len()),
            scope_ids: Vec::with_capacity(checks.len()),
            fingerprints: Vec::with_capacity(checks.len()),
            subjects: Vec::with_capacity(checks.len()),
            capacity_shards: Vec::with_capacity(checks.len()),
            lock_input_positions: ordered_indices
                .into_iter()
                .map(|index| {
                    i64::try_from(index + 1)
                        .expect("bounded batch input positions fit PostgreSQL BIGINT")
                })
                .collect(),
            advisory_lock_ids: counter_keys.iter().copied().map(advisory_lock_id).collect(),
            windows: Vec::with_capacity(checks.len()),
            costs: Vec::with_capacity(checks.len()),
            limits: Vec::with_capacity(checks.len()),
        };
        input.advisory_lock_ids.sort_unstable();
        input.advisory_lock_ids.dedup();

        for (check, counter_key) in checks.iter().zip(counter_keys) {
            let policy = check.policy();
            input.policy_ids.push(policy.id().as_str().to_owned());
            input.scope_ids.push(policy.scope().as_str().to_owned());
            input
                .fingerprints
                .push(counter_key.fingerprint().as_bytes().to_vec());
            input
                .subjects
                .push(counter_key.subject().as_bytes().to_vec());
            input.capacity_shards.push(capacity_shard(counter_key));
            input.windows.push(
                PgInterval::try_from(policy.window())
                    .expect("core policy windows fit PostgreSQL INTERVAL exactly"),
            );
            input.costs.push(database_integer(check.cost()));
            input.limits.push(database_integer(policy.limit()));
        }
        input
    }
}

#[derive(Debug)]
struct BatchPreflight {
    database_now: DateTime<Utc>,
    response_now: DateTime<Utc>,
    denial: Option<(usize, PendingDenial)>,
}

#[derive(Debug)]
pub(crate) struct PendingAllowance {
    pub(crate) limit: u64,
    pub(crate) remaining: u64,
    pub(crate) reset_from_sample: Duration,
}

impl PendingAllowance {
    pub(crate) fn finish(self, authoritative_elapsed: Duration) -> Decision {
        Decision::allowed(
            self.limit,
            self.remaining,
            self.reset_from_sample.saturating_sub(authoritative_elapsed),
        )
    }
}

#[derive(Debug)]
pub(crate) struct PendingQuotaDenial {
    pub(crate) limit: u64,
    pub(crate) retry_from_sample: Duration,
}

impl PendingQuotaDenial {
    fn finish(self, authoritative_elapsed: Duration) -> QuotaDenial {
        QuotaDenial::try_new(
            self.limit,
            self.retry_from_sample.saturating_sub(authoritative_elapsed),
        )
        .expect("persisted policy limits were validated before evaluation")
    }
}

#[derive(Debug)]
pub(crate) enum PendingDenial {
    Quota(PendingQuotaDenial),
    StorageCapacity,
}

impl PendingDenial {
    pub(crate) fn finish(self, authoritative_elapsed: Duration) -> Denial {
        match self {
            Self::Quota(denial) => Denial::quota_exceeded(denial.finish(authoritative_elapsed)),
            Self::StorageCapacity => Denial::storage_capacity(None),
        }
    }
}

#[derive(Debug)]
pub(crate) enum PendingBatchDenial {
    Enforced {
        index: usize,
        denial: PendingDenial,
    },
    Shadow {
        index: usize,
        denial: PendingQuotaDenial,
    },
}

pub(crate) async fn acquire_check_connection(
    pool: &PgPool,
    acquire_timeout: Duration,
) -> Result<PoolConnection<Postgres>, CheckError> {
    timeout(acquire_timeout, pool.acquire())
        .await
        .map_err(|_| CheckError::TimedOutBeforeCommit {
            operation: "acquiring database connection",
        })?
        .map_err(CheckError::DefinitelyNotConsumed)
}

pub(crate) async fn run_check_transaction(
    connection: &mut PoolConnection<Postgres>,
    input: &BatchSqlInput,
    checks: &[Check<'_>],
    maximum_rows_per_shard: u32,
    deadline: Instant,
) -> ConnectionOutcome<Result<BatchDecision, CheckError>> {
    match run_check_transaction_inner(connection, input, checks, maximum_rows_per_shard, deadline)
        .await
    {
        Ok(outcome) => outcome.map(Ok),
        Err(outcome) => outcome.map(Err),
    }
}

/// Keeps every SQL phase on the same remaining operation budget. `PostgreSQL`
/// timeouts are per statement/lock, so a value set once at BEGIN is stale after
/// an earlier phase waits. No query method exposes the underlying transaction.
struct CheckTransaction<'c> {
    inner: Transaction<'c, Postgres>,
    deadline: Instant,
}

impl<'c> CheckTransaction<'c> {
    async fn begin(
        connection: &'c mut PoolConnection<Postgres>,
        deadline: Instant,
    ) -> Result<Self, ConnectionOutcome<CheckError>> {
        let inner =
            check_before_commit(deadline, "beginning transaction", connection.begin()).await?;
        Ok(Self { inner, deadline })
    }

    async fn prepare(
        &mut self,
        operation: &'static str,
    ) -> Result<(), ConnectionOutcome<CheckError>> {
        set_check_server_timeouts(&mut self.inner, self.deadline, operation).await
    }

    async fn execute(
        &mut self,
        operation: &'static str,
        query: Query<'_, Postgres, PgArguments>,
    ) -> Result<PgQueryResult, ConnectionOutcome<CheckError>> {
        self.prepare(operation).await?;
        check_before_commit(self.deadline, operation, query.execute(&mut *self.inner)).await
    }

    async fn fetch_all(
        &mut self,
        operation: &'static str,
        query: Query<'_, Postgres, PgArguments>,
    ) -> Result<Vec<PgRow>, ConnectionOutcome<CheckError>> {
        self.prepare(operation).await?;
        check_before_commit(self.deadline, operation, query.fetch_all(&mut *self.inner)).await
    }

    async fn fetch_one(
        &mut self,
        operation: &'static str,
        query: Query<'_, Postgres, PgArguments>,
    ) -> Result<PgRow, ConnectionOutcome<CheckError>> {
        self.prepare(operation).await?;
        check_before_commit(self.deadline, operation, query.fetch_one(&mut *self.inner)).await
    }

    async fn commit(mut self) -> Result<(), ConnectionOutcome<CheckError>> {
        self.prepare("preparing commit").await?;
        commit_check(self.deadline, self.inner).await
    }
}

async fn run_check_transaction_inner(
    connection: &mut PoolConnection<Postgres>,
    input: &BatchSqlInput,
    checks: &[Check<'_>],
    maximum_rows_per_shard: u32,
    deadline: Instant,
) -> Result<ConnectionOutcome<BatchDecision>, ConnectionOutcome<CheckError>> {
    let mut transaction = CheckTransaction::begin(connection, deadline).await?;

    // Advisory locks cover logical keys that do not have rows yet. Their
    // stable numeric IDs are sorted independently from exact storage keys so
    // deliberately colliding batches cannot acquire them in opposite orders.
    // Singles deliberately use this separate statement too: a statement
    // snapshot taken before an advisory-lock wait cannot safely decide whether
    // a capacity slot is needed.
    acquire_advisory_locks(&mut transaction, &input.advisory_lock_ids).await?;

    // Existing rows may be held by cleanup or a transaction predating the
    // advisory-lock protocol. Wait for all row locks before sampling database
    // time or deciding which keys need capacity.
    acquire_existing_row_locks(&mut transaction, input).await?;

    let (pending, authoritative_elapsed) =
        execute_batch(&mut transaction, input, checks, maximum_rows_per_shard).await?;

    match pending {
        PendingBatchOutcome::Denied { index, denial } => {
            let denial = match (denial, checks[0].policy().quota_mode()) {
                (PendingDenial::Quota(denial), QuotaMode::Shadow) => {
                    PendingBatchDenial::Shadow { index, denial }
                }
                (denial, _) => PendingBatchDenial::Enforced { index, denial },
            };
            Ok(finish_denied_transaction(
                deadline,
                denial,
                authoritative_elapsed,
                transaction.inner.rollback(),
            )
            .await)
        }
        PendingBatchOutcome::Allowed(allowances) => {
            transaction.commit().await?;
            Ok(ConnectionOutcome::Reusable(BatchDecision::allowed(
                allowances
                    .into_iter()
                    .map(|allowance| allowance.finish(authoritative_elapsed))
                    .collect(),
            )))
        }
    }
}

pub(crate) async fn finish_denied_transaction<F>(
    deadline: Instant,
    pending: PendingBatchDenial,
    authoritative_elapsed: Duration,
    rollback: F,
) -> ConnectionOutcome<BatchDecision>
where
    F: Future<Output = Result<(), sqlx::Error>>,
{
    let decision = match pending {
        PendingBatchDenial::Enforced { index, denial } => {
            BatchDecision::denied(index, denial.finish(authoritative_elapsed))
        }
        PendingBatchDenial::Shadow { index, denial } => {
            BatchDecision::shadow_denied(index, denial.finish(authoritative_elapsed))
        }
    };
    if denied_rollback_succeeded(deadline, rollback).await {
        ConnectionOutcome::Reusable(decision)
    } else {
        ConnectionOutcome::MustClose(decision)
    }
}

async fn denied_rollback_succeeded<F>(deadline: Instant, rollback: F) -> bool
where
    F: Future<Output = Result<(), sqlx::Error>>,
{
    matches!(timeout_at(deadline, rollback).await, Ok(Ok(())))
}

async fn check_before_commit<T, F>(
    deadline: Instant,
    operation: &'static str,
    future: F,
) -> Result<T, ConnectionOutcome<CheckError>>
where
    F: Future<Output = Result<T, sqlx::Error>>,
{
    timeout_at(deadline, future)
        .await
        .map_err(|_| ConnectionOutcome::MustClose(CheckError::TimedOutBeforeCommit { operation }))?
        .map_err(|error| ConnectionOutcome::Reusable(map_check_database_error(error, operation)))
}

async fn commit_check(
    deadline: Instant,
    transaction: Transaction<'_, Postgres>,
) -> Result<(), ConnectionOutcome<CheckError>> {
    if Instant::now() >= deadline {
        return Err(ConnectionOutcome::Reusable(
            CheckError::TimedOutBeforeCommit {
                operation: "starting commit",
            },
        ));
    }

    timeout_at(deadline, transaction.commit())
        .await
        .map_err(|_| ConnectionOutcome::MustClose(CheckError::CommitTimedOut))?
        .map_err(|error| ConnectionOutcome::Reusable(CheckError::CommitOutcomeUnknown(error)))
}

fn map_check_database_error(error: sqlx::Error, operation: &'static str) -> CheckError {
    if is_server_timeout(&error) {
        CheckError::TimedOutBeforeCommit { operation }
    } else {
        CheckError::DefinitelyNotConsumed(error)
    }
}

const fn reusable_check_error(error: CheckError) -> ConnectionOutcome<CheckError> {
    ConnectionOutcome::Reusable(error)
}

async fn set_check_server_timeouts(
    transaction: &mut Transaction<'_, Postgres>,
    deadline: Instant,
    operation: &'static str,
) -> Result<(), ConnectionOutcome<CheckError>> {
    let (statement_timeout, lock_timeout) = remaining_server_timeout_settings(deadline).ok_or(
        ConnectionOutcome::Reusable(CheckError::TimedOutBeforeCommit { operation }),
    )?;
    check_before_commit(
        deadline,
        operation,
        sqlx::query(SET_LOCAL_TIMEOUTS_SQL)
            .bind(statement_timeout)
            .bind(lock_timeout)
            .execute(&mut **transaction),
    )
    .await
    .map(|_| ())
}

async fn acquire_advisory_locks(
    transaction: &mut CheckTransaction<'_>,
    advisory_lock_ids: &[i64],
) -> Result<(), ConnectionOutcome<CheckError>> {
    transaction
        .execute(
            "acquiring logical key lock",
            sqlx::query(BATCH_ADVISORY_LOCK_SQL).bind(advisory_lock_ids),
        )
        .await
        .map(|_| ())
}

async fn acquire_existing_row_locks(
    transaction: &mut CheckTransaction<'_>,
    input: &BatchSqlInput,
) -> Result<(), ConnectionOutcome<CheckError>> {
    transaction
        .execute(
            "acquiring counter row lock",
            sqlx::query(BATCH_ROW_LOCK_SQL)
                .bind(input.fingerprints.as_slice())
                .bind(input.subjects.as_slice())
                .bind(input.lock_input_positions.as_slice()),
        )
        .await
        .map(|_| ())
}

async fn first_capacity_denial(
    transaction: &mut CheckTransaction<'_>,
    input: &BatchSqlInput,
    maximum_rows_per_shard: u32,
) -> Result<Option<(usize, PendingDenial)>, ConnectionOutcome<CheckError>> {
    let rows = transaction
        .fetch_all(
            "acquiring capacity shard lock",
            sqlx::query(BATCH_CAPACITY_LOCK_SQL)
                .bind(input.fingerprints.as_slice())
                .bind(input.subjects.as_slice())
                .bind(input.capacity_shards.as_slice()),
        )
        .await?;

    let mut pending_insertions = [0_u32; CAPACITY_SHARD_COUNT];
    for row in rows {
        let input_index: i64 = row
            .try_get("input_index")
            .map_err(CheckError::DefinitelyNotConsumed)
            .map_err(reusable_check_error)?;
        let input_index = usize::try_from(input_index)
            .map_err(|_| {
                CheckError::StorageInvariant("capacity preflight returned an invalid input index")
            })
            .map_err(reusable_check_error)?;
        let expected_shard = input
            .capacity_shards
            .get(input_index)
            .ok_or(CheckError::StorageInvariant(
                "capacity preflight returned an out-of-range input index",
            ))
            .map_err(reusable_check_error)?;
        let returned_shard: i16 = row
            .try_get("capacity_shard")
            .map_err(CheckError::DefinitelyNotConsumed)
            .map_err(reusable_check_error)?;
        if &returned_shard != expected_shard {
            return Err(reusable_check_error(CheckError::StorageInvariant(
                "capacity preflight returned a mismatched shard",
            )));
        }
        let shard_index = usize::try_from(returned_shard)
            .map_err(|_| {
                CheckError::StorageInvariant("capacity preflight returned a negative shard")
            })
            .map_err(reusable_check_error)?;
        let pending = pending_insertions
            .get_mut(shard_index)
            .ok_or(CheckError::StorageInvariant(
                "capacity preflight returned an out-of-range shard",
            ))
            .map_err(reusable_check_error)?;
        let stored_rows: Option<i64> = row
            .try_get("row_count")
            .map_err(CheckError::DefinitelyNotConsumed)
            .map_err(reusable_check_error)?;
        let stored_rows = stored_rows
            .ok_or(CheckError::StorageInvariant(
                "capacity shard ledger row is missing",
            ))
            .map_err(reusable_check_error)?;
        let stored_rows = u64::try_from(stored_rows)
            .map_err(|_| CheckError::StorageInvariant("capacity shard ledger count is negative"))
            .map_err(reusable_check_error)?;
        let projected_rows = stored_rows
            .checked_add(u64::from(*pending))
            .and_then(|rows| rows.checked_add(1))
            .ok_or(CheckError::StorageInvariant(
                "capacity shard ledger count overflowed",
            ))
            .map_err(reusable_check_error)?;
        if projected_rows > u64::from(maximum_rows_per_shard) {
            return Ok(Some((input_index, PendingDenial::StorageCapacity)));
        }
        *pending += 1;
    }

    Ok(None)
}
fn authoritative_elapsed(start: DateTime<Utc>, end: DateTime<Utc>) -> Duration {
    end.signed_duration_since(start)
        .to_std()
        .unwrap_or(Duration::ZERO)
}

async fn execute_batch(
    transaction: &mut CheckTransaction<'_>,
    input: &BatchSqlInput,
    checks: &[Check<'_>],
    maximum_rows_per_shard: u32,
) -> Result<(PendingBatchOutcome, Duration), ConnectionOutcome<CheckError>> {
    let capacity_denial = first_capacity_denial(transaction, input, maximum_rows_per_shard).await?;
    let preflight = preflight_batch(transaction, input, checks).await?;
    let first_denial = match (capacity_denial, preflight.denial) {
        (Some(capacity), Some(quota)) => Some(if capacity.0 < quota.0 {
            capacity
        } else {
            quota
        }),
        (Some(capacity), None) => Some(capacity),
        (None, Some(quota)) => Some(quota),
        (None, None) => None,
    };
    if let Some((index, denial)) = first_denial {
        return Ok((
            PendingBatchOutcome::Denied { index, denial },
            authoritative_elapsed(preflight.database_now, preflight.response_now),
        ));
    }
    let (allowances, response_now) =
        upsert_batch(transaction, input, checks, preflight.database_now).await?;
    Ok((
        PendingBatchOutcome::Allowed(allowances),
        authoritative_elapsed(preflight.database_now, response_now),
    ))
}

async fn preflight_batch(
    transaction: &mut CheckTransaction<'_>,
    input: &BatchSqlInput,
    checks: &[Check<'_>],
) -> Result<BatchPreflight, ConnectionOutcome<CheckError>> {
    let preflight_row = transaction
        .fetch_one(
            "preflighting counter batch",
            sqlx::query(BATCH_PREFLIGHT_SQL)
                .bind(input.fingerprints.as_slice())
                .bind(input.subjects.as_slice())
                .bind(input.costs.as_slice())
                .bind(input.limits.as_slice()),
        )
        .await?;

    let database_now: DateTime<Utc> = preflight_row
        .try_get("database_now")
        .map_err(CheckError::DefinitelyNotConsumed)
        .map_err(reusable_check_error)?;
    let preflight_response_now: DateTime<Utc> = preflight_row
        .try_get("response_now")
        .map_err(CheckError::DefinitelyNotConsumed)
        .map_err(reusable_check_error)?;
    let denied_index: Option<i64> = preflight_row
        .try_get("input_index")
        .map_err(CheckError::DefinitelyNotConsumed)
        .map_err(reusable_check_error)?;
    let denied_expiry: Option<DateTime<Utc>> = preflight_row
        .try_get("window_expires_at")
        .map_err(CheckError::DefinitelyNotConsumed)
        .map_err(reusable_check_error)?;

    let denial = match (denied_index, denied_expiry) {
        (Some(input_index), Some(expires_at)) => {
            let input_index = usize::try_from(input_index)
                .map_err(|_| {
                    CheckError::StorageInvariant("batch preflight returned an invalid input index")
                })
                .map_err(reusable_check_error)?;
            let check = checks
                .get(input_index)
                .ok_or(CheckError::StorageInvariant(
                    "batch preflight returned an out-of-range input index",
                ))
                .map_err(reusable_check_error)?;
            Some((
                input_index,
                PendingDenial::Quota(PendingQuotaDenial {
                    limit: check.policy().limit(),
                    retry_from_sample: duration_until(expires_at, database_now)
                        .map_err(reusable_check_error)?,
                }),
            ))
        }
        (None, None) => None,
        _ => {
            return Err(reusable_check_error(CheckError::StorageInvariant(
                "batch preflight returned an incomplete denial",
            )));
        }
    };

    Ok(BatchPreflight {
        database_now,
        response_now: preflight_response_now,
        denial,
    })
}

async fn upsert_batch(
    transaction: &mut CheckTransaction<'_>,
    input: &BatchSqlInput,
    checks: &[Check<'_>],
    database_now: DateTime<Utc>,
) -> Result<(Vec<PendingAllowance>, DateTime<Utc>), ConnectionOutcome<CheckError>> {
    let rows = transaction
        .fetch_all(
            "updating counter batch",
            sqlx::query(BATCH_UPSERT_SQL)
                .bind(input.policy_ids.as_slice())
                .bind(input.scope_ids.as_slice())
                .bind(input.fingerprints.as_slice())
                .bind(input.subjects.as_slice())
                .bind(input.windows.as_slice())
                .bind(input.costs.as_slice())
                .bind(input.limits.as_slice())
                .bind(database_now),
        )
        .await?;

    if rows.is_empty() {
        return Err(reusable_check_error(CheckError::StorageInvariant(
            "allowed batch update returned no decisions",
        )));
    }
    let response_now: DateTime<Utc> = rows[0]
        .try_get("response_now")
        .map_err(CheckError::DefinitelyNotConsumed)
        .map_err(reusable_check_error)?;

    let mut allowances = Vec::with_capacity(checks.len());
    for (output_position, row) in rows.iter().enumerate() {
        let input_index: i64 = row
            .try_get("input_index")
            .map_err(CheckError::DefinitelyNotConsumed)
            .map_err(reusable_check_error)?;
        let input_index = usize::try_from(input_index)
            .map_err(|_| {
                CheckError::StorageInvariant("batch evaluation returned an invalid input index")
            })
            .map_err(reusable_check_error)?;
        let Some(check) = checks.get(input_index) else {
            return Err(reusable_check_error(CheckError::StorageInvariant(
                "batch evaluation returned an out-of-range input index",
            )));
        };
        let expires_at = read_expiry(row).map_err(reusable_check_error)?;
        let remaining_from_sample =
            duration_until(expires_at, database_now).map_err(reusable_check_error)?;

        if input_index != output_position {
            return Err(reusable_check_error(CheckError::StorageInvariant(
                "allowed batch decisions were not returned in caller order",
            )));
        }
        let used = read_used(row).map_err(reusable_check_error)?;
        let remaining = check
            .policy()
            .limit()
            .checked_sub(used)
            .ok_or(CheckError::StorageInvariant(
                "stored usage exceeds its policy limit",
            ))
            .map_err(reusable_check_error)?;
        allowances.push(PendingAllowance {
            limit: check.policy().limit(),
            remaining,
            reset_from_sample: remaining_from_sample,
        });
    }

    if allowances.len() != checks.len() {
        return Err(reusable_check_error(CheckError::StorageInvariant(
            "allowed batch returned an incomplete decision set",
        )));
    }
    Ok((allowances, response_now))
}

pub(crate) fn database_integer(value: u64) -> i64 {
    i64::try_from(value)
        .expect("core policy and check validation keep database integers within i64")
}

fn read_used(row: &PgRow) -> Result<u64, CheckError> {
    let used: i64 = row
        .try_get("used")
        .map_err(CheckError::DefinitelyNotConsumed)?;
    u64::try_from(used).map_err(|_| CheckError::StorageInvariant("stored usage is negative"))
}

fn read_expiry(row: &PgRow) -> Result<DateTime<Utc>, CheckError> {
    row.try_get("window_expires_at")
        .map_err(CheckError::DefinitelyNotConsumed)
}

fn duration_until(
    expires_at: DateTime<Utc>,
    database_now: DateTime<Utc>,
) -> Result<Duration, CheckError> {
    expires_at
        .signed_duration_since(database_now)
        .to_std()
        .map_err(|_| CheckError::StorageInvariant("stored window is already expired"))
}