push-gateway: lock expired installations before reaping (#9627)

## What

The push gateway reaper deletes expired delegations and then expired
installations in two statements. A delegation writer
(`upsert_delegation`) that holds the installation lock can commit a new
child between them. With the foreign key, the installation delete then
fails, and the reap transaction rolls back.

This PR locks the expired installations with `FOR UPDATE` first, as
every authority mutation does. It then deletes their delegations and the
installations by id. A writer that was holding the lock commits first,
and the delete sees its child. A later writer finds the parent gone and
is rejected.

No schema change. This is the code half of #9610. The gateway image with
this change must run everywhere before the delegation foreign key is
dropped.

## Tests

Blox at `20b66f8f`: fmt, clippy, and the push-gateway PostgreSQL tests
(15/15) pass.

- `reaper_deletes_delegation_committed_while_it_waits`: a writer holds
the installation lock and inserts a child. The reaper starts and waits.
The writer commits. The reaper deletes both rows.
- `delegation_for_missing_installation_is_rejected`: `upsert_delegation`
for an unknown installation returns `Rejected` and writes nothing.

## What got simpler

The reaper now uses the same lock order as every other authority write.
The child delete no longer needs a correlated subquery.

buzz-review-completed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Luke Tornquist <tornquist@squareup.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Luke Tornquist
2026-11-17 17:17:57 -05:00
committed by GitHub
parent b568d9bf95
commit 44cdd9feef

View File

@@ -550,23 +550,29 @@ impl AuthorityStore for PostgresAuthorityStore {
.map_err(db)?;
// Revoked rows are idempotency tombstones for cleanup retries, so keep
// them for the full authority lifetime. A parent may expire before an
// otherwise-active child; reap every child of an expired parent first
// so the installation delete cannot violate the delegation FK.
sqlx::query(
"DELETE FROM push_gateway_delegations d
WHERE d.expires_at < $1
OR EXISTS (
SELECT 1 FROM push_gateway_installations i
WHERE i.id = d.installation_id
AND i.expires_at < $1
)",
// otherwise-active child, so delete every child of an expired parent.
// Lock the expired parents first, as every authority mutation does:
// `upsert_delegation` holds this lock while it writes a child, so the
// next statement sees every child that was committed, and a later
// writer finds the parent gone.
let expired: Vec<Uuid> = sqlx::query_scalar(
"SELECT id FROM push_gateway_installations WHERE expires_at < $1 FOR UPDATE",
)
.bind(at(now)?)
.fetch_all(&mut *tx)
.await
.map_err(db)?;
sqlx::query(
"DELETE FROM push_gateway_delegations
WHERE expires_at < $1 OR installation_id = ANY($2)",
)
.bind(at(now)?)
.bind(&expired)
.execute(&mut *tx)
.await
.map_err(db)?;
sqlx::query("DELETE FROM push_gateway_installations WHERE expires_at < $1")
.bind(at(now)?)
sqlx::query("DELETE FROM push_gateway_installations WHERE id = ANY($1)")
.bind(&expired)
.execute(&mut *tx)
.await
.map_err(db)?;
@@ -1062,6 +1068,131 @@ mod postgres_tests {
drop_schema(&schema).await;
}
#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn delegation_for_missing_installation_is_rejected() {
let (pool, schema) = full_schema(1).await;
let store = PostgresAuthorityStore::new(pool.clone());
let now = Utc::now().timestamp();
let result = store
.upsert_delegation(Delegation {
id: Uuid::from_u128(DELEGATION_ID),
installation_id: Uuid::from_u128(1),
relay_pubkey: RELAY_HEX.to_owned(),
endpoint_epoch: 1,
generation: 1,
not_before: now,
expires_at: now + 1_000,
revoked: false,
})
.await;
assert_eq!(result, Err(AuthorityError::Rejected));
let delegations: i64 = sqlx::query_scalar("SELECT count(*) FROM push_gateway_delegations")
.fetch_one(&pool)
.await
.expect("count delegations");
assert_eq!(delegations, 0);
pool.close().await;
drop_schema(&schema).await;
}
// A delegation writer holds the installation lock while the reaper starts.
// The reaper must wait for it and then delete the new child with its
// expired parent, so no delegation outlives its installation.
#[tokio::test]
#[ignore = "requires PostgreSQL"]
async fn reaper_deletes_delegation_committed_while_it_waits() {
let (pool, schema) = full_schema(3).await;
let store = PostgresAuthorityStore::new(pool.clone());
let now = Utc::now();
let installation_id = Uuid::from_u128(1);
sqlx::query(
"INSERT INTO push_gateway_installations(id,app_attest_key_id,app_attest_public_key,assertion_counter,token_ciphertext,token_fingerprint,endpoint_epoch,expires_at)
VALUES ($1,$2,$3,0,$4,$5,1,$6)",
)
.bind(installation_id)
.bind(vec![1u8])
.bind(vec![2u8; 33])
.bind(vec![3u8])
.bind(vec![4u8; 32])
.bind(now - chrono::Duration::days(1))
.execute(&pool)
.await
.expect("insert expired installation");
// The same statements upsert_delegation runs, held open. The child
// expires before the reap time, so the parent stays expired.
let mut writer = pool.begin().await.expect("begin delegation writer");
let writer_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&mut *writer)
.await
.expect("read writer pid");
sqlx::query("SELECT id FROM push_gateway_installations WHERE id=$1 FOR UPDATE")
.bind(installation_id)
.execute(&mut *writer)
.await
.expect("lock installation");
sqlx::query(
"INSERT INTO push_gateway_delegations(id,installation_id,relay_pubkey,endpoint_epoch,generation,not_before,expires_at)
VALUES ($1,$2,$3,1,1,$4,$5)",
)
.bind(Uuid::from_u128(DELEGATION_ID))
.bind(installation_id)
.bind(hex::decode(RELAY_HEX).unwrap())
.bind(now - chrono::Duration::hours(1))
.bind(now - chrono::Duration::minutes(1))
.execute(&mut *writer)
.await
.expect("insert delegation");
sqlx::query(
"UPDATE push_gateway_installations SET expires_at=GREATEST(expires_at,$2) WHERE id=$1",
)
.bind(installation_id)
.bind(now - chrono::Duration::minutes(1))
.execute(&mut *writer)
.await
.expect("extend installation");
let commit_once_reaper_waits = async {
let mut waited = 0;
loop {
let blocked: i64 = sqlx::query_scalar(
"SELECT count(*) FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid))",
)
.bind(writer_pid)
.fetch_one(&pool)
.await
.expect("read lock waiters");
if blocked > 0 {
break;
}
waited += 1;
assert!(waited < 400, "reaper never waited for the writer");
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
}
writer.commit().await.expect("commit delegation writer");
};
let (reaped, ()) = tokio::join!(
store.reap_expired(now.timestamp()),
commit_once_reaper_waits
);
reaped.expect("reap expired authority");
let delegations: i64 = sqlx::query_scalar("SELECT count(*) FROM push_gateway_delegations")
.fetch_one(&pool)
.await
.expect("count delegations");
let installations: i64 =
sqlx::query_scalar("SELECT count(*) FROM push_gateway_installations")
.fetch_one(&pool)
.await
.expect("count installations");
assert_eq!((delegations, installations), (0, 0));
pool.close().await;
drop_schema(&schema).await;
}
fn admit<'a>(
store: &'a PostgresAuthorityStore,
event_hex: &'a str,