mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
BUZZ-175: Route serving event writes through the tenant lock (#7828)
## Summary
Route every serving event write through one community-admitted
transaction entry point. `Db::begin_event_write_transaction(community)`
is now the only `Db` constructor for event-write transactions: it takes
the shared community admission lock before returning, so callers that
use it cannot take domain or row locks ahead of tenant admission, and a
quiescing community rejects the write at entry. Database triggers and
commit-time fences remain the authoritative backstop.
This migrates normal, replaceable, roster, relay membership, reaction,
reminder, admin-delete, push-owned, artifact-accept, huddle-join
(48101), workflow-deletion, and command-executor event writes. Coupled
mention writes stay in the same transaction; pool-level
`insert_mentions` now opens its own admitted transaction.
**Review fixes (since `950d5f6`):**
- The unguarded event-write constructor is gone. Removed with it: the
deprecated `begin_transaction` alias, the test-only replica-floor
constructor, and `begin_community_write_transaction` (now identical to
the single constructor). Artifact accept, the huddle join, and both
workflow-deletion paths now admit before any domain or row lock;
`persist_command_event` no longer hand-rolls `guard_transaction`;
read-only `query_artifacts` no longer opens an event-write transaction.
- `insert_channel_head_checked` is now `insert_canvas_head_checked`: it
rejects non-canvas kinds before opening a transaction and always takes
the coordinate lock.
- Source policy now also scans `buzz-relay`: any function that hands a
transaction to an event-write helper must have opened it through the
admitted constructor. The scan drops each `#[cfg(test)]` item instead of
stopping at the first one: it tracks brace depth and ends the item on a
line ending in `;` or `}` (ignoring a trailing `//` comment, even after
a string that contains `//`), with a column-0 `}` as fallback. Fixtures
pin a unit struct, a multi-line static, a `const { … }` block, a struct
with fields, a module, and one-line items with trailing comments,
including after `"https://…"` and `"ws://…"` strings; a raw opener after
each must still be flagged. Known limit: braces inside string or char
literals or comments are still counted, and only `//` trailing comments
are recognized, so a test-only item with unbalanced braces in a literal
or comment, or with a trailing `/* */`, would hide what follows; none
exists today. The scan checks that admission is present; the per-path
PostgreSQL tests pin that it comes before domain locks.
- `just test-unit` (and the non-nextest fallback in
`scripts/run-tests.sh`) now runs `buzz-db --test observability_source`.
Before this, no CI job ran these source-policy tests: the unit lane ran
`buzz-db --lib` only and the PostgreSQL lane runs only ignored tests.
- Renamed or removed since `950d5f6`: `begin_transaction`,
`begin_community_write_transaction`, and the replica-floor test
constructor are gone; `insert_channel_head_checked` →
`insert_canvas_head_checked`; test helper `quiesce_community_for_tests`
now delegates to `main`'s `set_deletion_state`, which reads the real
`deletion_fence_generation` instead of hard-coding `'0'`;
`runtime::insert_mentions` is pinned to the admitted constructor by
`pool_level_insert_mentions_opens_the_tenant_local_chokepoint`.
**What got simpler:** four transaction constructors collapse to one, and
the hand-rolled admission guard is deleted. The compiler rejects callers
of the removed constructors, but a transaction opened from `Db::pool()`
can still reach the public `*_in_transaction` helpers; only the
source-policy scan and the database fences catch that until BUZZ-254.
**Behavior note:** #7932 made `insert_event` skip the transaction for
kinds that are not listener mentions. Every serving event write now has
to run in a transaction that holds the community admission lock, so
`insert_event` always opens the admitted transaction again. `main`'s
`soft_delete_event_and_update_thread` / `_in_tx` split and its
removal-marker guard are kept; the outer function now opens the admitted
transaction.
### Related issue
[BUZZ-175](https://linear.app/squareup/issue/BUZZ-175). Caller-migration
stage following #7706 (merged); rebased onto `main` at `5173fad66`.
Follow-up: [BUZZ-254](https://linear.app/squareup/issue/BUZZ-254) makes
event-write helpers require a type-level admitted transaction.
**Known debt, out of scope:** `create_channel`, `update_channel`, and
`insert_thread_metadata` write channel and thread rows (not events)
outside the admitted constructor.
### Testing
At `efe4a94623dd69973780a3c39f16dd972cf7cb76` on a cloud workstation:
fmt; `buzz-db` clippy (all targets, `-D warnings`);
`observability_source` 14/14; `just --dry-run test-unit` includes the
new step. Reverting just the end-of-item check to an earlier rule makes
a trailing-comment fixture fail.
At `eaf190ae59d1595741c3d19dc4c23ce492b5f4d4` (the commit after it only
changes this test file, `Justfile`, and `scripts/run-tests.sh`): full
GitHub CI green; on the workstation, clippy for `buzz-db` and
`buzz-relay`, ordinary `buzz-db` 154/154, `just test-unit` green, and
the PostgreSQL lane 805 of 806 (exception below). An end-to-end run
against a local relay and the built desktop app covered artifact accept,
huddle join, and workflow deletion for both a healthy and a quiescing
community, plus p-tag reaction rollback and replay of the same signed
event.
New tests: one fenced-community test per migrated path (artifact accept,
huddle join, both workflow deletions) puts the community into
`quiescing`, holds the lock the path takes next, and asserts rejection
at entry with nothing stored; a DB-free test pins the non-canvas
rejection.
Exceptions:
-
`runtime::postgres_tests::writer_pool_rejects_non_read_committed_database_default`
hangs on that workstation's local Postgres 16 at both this head and an
earlier `main` base, `f0eb5575f` (2/2 runs each). The test, `Db::new`,
and the pool setup are unchanged by this PR, and the test passes in
GitHub CI. Live traces put the hang in the client, not the database: the
1 s acquire timeout stops firing after sqlx's `after_connect` rejection
path under tokio's `current_thread` runtime. No database lock waits were
observed.
- Two `observability_source` assertions were already failing on `main`,
unnoticed because no CI job ran that test binary: a stale
`fetch_optional` pin after #8005, and lease-seam attribution that now
lives in the `bounded_serving_lease_sql` helper. Both are corrected
here, and the binary now runs in `just test-unit`.
Generated with Codex
---------
Signed-off-by: tornquist <tornquist@squareup.com>
Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
Co-authored-by: Codex <noreply@openai.com>
Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -21,19 +21,26 @@ use buzz_core::{CommunityId, StoredEvent};
|
||||
|
||||
/// Extract p-tag mentions from an event and insert into the `event_mentions` table.
|
||||
///
|
||||
/// This pool-owning wrapper propagates failures to its caller. Replacement writes
|
||||
/// use the transaction-bound helper below so event storage and mention indexing
|
||||
/// commit or roll back together. Duplicate inserts are silently skipped with
|
||||
/// `INSERT ... ON CONFLICT DO NOTHING`.
|
||||
/// This pool-owning wrapper indexes mentions in its own admitted transaction,
|
||||
/// after the event has already committed. Writes that need event storage and
|
||||
/// mention indexing to commit or roll back together should open
|
||||
/// `begin_community_event_write_transaction` and call
|
||||
/// `insert_mentions_in_transaction` instead.
|
||||
///
|
||||
/// Duplicate inserts are silently skipped with `INSERT ... ON CONFLICT DO
|
||||
/// NOTHING`.
|
||||
pub async fn insert_mentions(
|
||||
pool: &PgPool,
|
||||
community_id: CommunityId,
|
||||
event: &nostr::Event,
|
||||
channel_id: Option<Uuid>,
|
||||
) -> Result<()> {
|
||||
let connection =
|
||||
observability::acquire_writer(pool, observability::WriterOperation::EventWrite).await?;
|
||||
let mut tx = sqlx::Transaction::begin(connection, None).await?;
|
||||
let mut tx = begin_community_event_write_transaction(
|
||||
pool,
|
||||
community_id,
|
||||
observability::WriterOperation::EventWrite,
|
||||
)
|
||||
.await?;
|
||||
insert_mentions_in_transaction(&mut tx, community_id, event, channel_id).await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
@@ -121,6 +128,63 @@ pub(crate) async fn insert_mentions_in_transaction(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start a tenant-local event-write transaction and take the shared community
|
||||
/// deletion lock before any serving mutation.
|
||||
async fn begin_community_event_write_transaction_with_metric_population(
|
||||
pool: &PgPool,
|
||||
community: CommunityId,
|
||||
operation: observability::WriterOperation,
|
||||
metric_population: CommunityEventWriteMetricPopulation,
|
||||
) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
let connection = match metric_population {
|
||||
CommunityEventWriteMetricPopulation::TypedOnly => {
|
||||
observability::acquire_writer(pool, operation).await?
|
||||
}
|
||||
CommunityEventWriteMetricPopulation::LegacyCompatibility => {
|
||||
observability::acquire_writer_with_legacy_metrics(pool, operation).await?
|
||||
}
|
||||
};
|
||||
let mut tx = sqlx::Transaction::begin(connection, None).await?;
|
||||
deletion::DeletionStore::new(pool.clone())
|
||||
.guard_transaction(&mut tx, community)
|
||||
.await?;
|
||||
Ok(tx)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CommunityEventWriteMetricPopulation {
|
||||
TypedOnly,
|
||||
LegacyCompatibility,
|
||||
}
|
||||
|
||||
pub(crate) async fn begin_community_event_write_transaction(
|
||||
pool: &PgPool,
|
||||
community: CommunityId,
|
||||
operation: observability::WriterOperation,
|
||||
) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
begin_community_event_write_transaction_with_metric_population(
|
||||
pool,
|
||||
community,
|
||||
operation,
|
||||
CommunityEventWriteMetricPopulation::TypedOnly,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn begin_community_event_write_transaction_with_legacy_metrics(
|
||||
pool: &PgPool,
|
||||
community: CommunityId,
|
||||
operation: observability::WriterOperation,
|
||||
) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
begin_community_event_write_transaction_with_metric_population(
|
||||
pool,
|
||||
community,
|
||||
operation,
|
||||
CommunityEventWriteMetricPopulation::LegacyCompatibility,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Database handle. Clone is cheap (Arc-backed pool).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Db {
|
||||
@@ -1220,60 +1284,29 @@ impl Db {
|
||||
})
|
||||
}
|
||||
|
||||
/// Begin a database transaction for atomic multi-statement operations.
|
||||
/// Begin an event-write transaction admitted for `community`.
|
||||
///
|
||||
/// This is the only `Db` constructor for event-write transactions. It takes
|
||||
/// the shared community admission lock before returning, so callers that use
|
||||
/// it cannot take domain or row locks ahead of tenant admission, and a
|
||||
/// quiescing community rejects the write at entry rather than at its first
|
||||
/// fenced statement. The compiler does not enforce this: a transaction
|
||||
/// opened from [`Db::pool`] can still reach the public `*_in_transaction`
|
||||
/// helpers, and only the source-policy tests and the commit-time database
|
||||
/// fences, which remain the authoritative backstop, catch it.
|
||||
///
|
||||
/// Returns a `'static` transaction because `PgPool` is `Arc`-backed internally.
|
||||
/// The transaction holds an owned pool handle, not a borrow.
|
||||
pub async fn begin_event_write_transaction(
|
||||
&self,
|
||||
) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
let connection = observability::acquire_writer_with_legacy_metrics(
|
||||
&self.pool,
|
||||
observability::WriterOperation::EventWrite,
|
||||
)
|
||||
.await?;
|
||||
sqlx::Transaction::begin(connection, None)
|
||||
.await
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Begin an event-write transaction and guard its community against
|
||||
/// concurrent deletion.
|
||||
pub async fn begin_community_write_transaction(
|
||||
&self,
|
||||
community: CommunityId,
|
||||
) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
let mut tx = self.begin_event_write_transaction().await?;
|
||||
self.deletion_store()
|
||||
.guard_transaction(&mut tx, community)
|
||||
.await?;
|
||||
Ok(tx)
|
||||
}
|
||||
|
||||
/// Begin an event-write transaction that takes the shared replica-floor
|
||||
/// advisory lock.
|
||||
///
|
||||
/// This is a lock-ordering foundation only. Floor correctness remains
|
||||
/// authoritative at commit time via the existing trigger/GUC contract.
|
||||
pub async fn begin_replica_floor_locked_event_write_transaction(
|
||||
&self,
|
||||
) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
let mut tx = self.begin_event_write_transaction().await?;
|
||||
sqlx::query("SELECT pg_advisory_xact_lock_shared($1)")
|
||||
.bind(replica_fence::REPLICA_FLOOR_LOCK_KEY)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(tx)
|
||||
}
|
||||
|
||||
/// Begin an event-write transaction through the pre-operation API name.
|
||||
///
|
||||
/// New callers should use [`Self::begin_event_write_transaction`] so the
|
||||
/// semantic intent is explicit. This alias preserves the crate's public
|
||||
/// API while emitting the same operation-aware and compatibility metrics.
|
||||
#[deprecated(note = "use Db::begin_event_write_transaction")]
|
||||
pub async fn begin_transaction(&self) -> Result<sqlx::Transaction<'static, sqlx::Postgres>> {
|
||||
self.begin_event_write_transaction().await
|
||||
begin_community_event_write_transaction_with_legacy_metrics(
|
||||
&self.pool,
|
||||
community,
|
||||
observability::WriterOperation::EventWrite,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Insert an event while holding and validating an admitted serving-write
|
||||
@@ -1305,6 +1338,8 @@ impl Db {
|
||||
self.deletion_store()
|
||||
.guard_transaction_with_serving_lease(&mut tx, lease)
|
||||
.await?;
|
||||
event::acquire_canvas_event_write_lock_if_needed(&mut tx, community_id, event, channel_id)
|
||||
.await?;
|
||||
let result = event::insert_event_with_thread_metadata_tx(
|
||||
&mut tx,
|
||||
community_id,
|
||||
|
||||
@@ -1479,14 +1479,9 @@ mod tests {
|
||||
let _ = writer_db
|
||||
.query_events_routed("pool_operation_matrix_writer", &query)
|
||||
.await;
|
||||
let write_tx = writer_db
|
||||
.begin_event_write_transaction()
|
||||
.await
|
||||
.expect("event-write semantic entry point begins a real transaction");
|
||||
write_tx
|
||||
.rollback()
|
||||
.await
|
||||
.expect("rollback operation-label fixture");
|
||||
// The scope is not a live community, so admission rejects it after the
|
||||
// writer acquisition has been attributed to `event_write`.
|
||||
let _ = writer_db.begin_event_write_transaction(test_scope).await;
|
||||
let _ = writer_db
|
||||
.is_community_active_for_maintenance(test_scope)
|
||||
.await;
|
||||
|
||||
@@ -78,7 +78,7 @@ async fn setup_db() -> Db {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_transaction_compatibility_alias_is_preserved() {
|
||||
async fn event_write_transaction_preserves_legacy_acquisition_metrics() {
|
||||
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
|
||||
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
@@ -90,8 +90,9 @@ async fn begin_transaction_compatibility_alias_is_preserved() {
|
||||
let snapshotter = recorder.snapshotter();
|
||||
let _guard = metrics::set_default_local_recorder(&recorder);
|
||||
|
||||
#[allow(deprecated)]
|
||||
let result = db.begin_transaction().await;
|
||||
let result = db
|
||||
.begin_event_write_transaction(CommunityId::from_uuid(Uuid::new_v4()))
|
||||
.await;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(DbError::Sqlx(sqlx::Error::PoolClosed))
|
||||
@@ -169,6 +170,69 @@ fn nip43_reconciliation_compatibility_alias_is_preserved() {
|
||||
let _ = call;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn community_write_transaction_compatibility_metrics_are_limited_to_legacy_entrypoints() {
|
||||
use metrics_util::debugging::DebuggingRecorder;
|
||||
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.connect_lazy(&crate::test_support::database_url())
|
||||
.expect("construct lazy compatibility pool");
|
||||
pool.close().await;
|
||||
let db = Db::from_pool(pool);
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
let _guard = metrics::set_default_local_recorder(&recorder);
|
||||
let community = CommunityId::from_uuid(Uuid::new_v4());
|
||||
|
||||
let direct = begin_community_event_write_transaction(
|
||||
&db.pool,
|
||||
community,
|
||||
observability::WriterOperation::EventWrite,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(
|
||||
direct,
|
||||
Err(DbError::Sqlx(sqlx::Error::PoolClosed))
|
||||
));
|
||||
assert_eq!(
|
||||
legacy_acquisition_count(&snapshotter.snapshot().into_vec()),
|
||||
0,
|
||||
"typed-only tenant-local chokepoint must not emit legacy compatibility metrics"
|
||||
);
|
||||
|
||||
let legacy = db.begin_event_write_transaction(community).await;
|
||||
assert!(matches!(
|
||||
legacy,
|
||||
Err(DbError::Sqlx(sqlx::Error::PoolClosed))
|
||||
));
|
||||
assert_eq!(
|
||||
legacy_acquisition_count(&snapshotter.snapshot().into_vec()),
|
||||
1,
|
||||
"Db::begin_event_write_transaction must preserve the legacy compatibility population"
|
||||
);
|
||||
}
|
||||
|
||||
fn legacy_acquisition_count(
|
||||
snapshot: &[(
|
||||
metrics_util::CompositeKey,
|
||||
Option<metrics::Unit>,
|
||||
Option<metrics::SharedString>,
|
||||
metrics_util::debugging::DebugValue,
|
||||
)],
|
||||
) -> u64 {
|
||||
snapshot
|
||||
.iter()
|
||||
.filter_map(|(key, _, _, value)| {
|
||||
(key.key().name() == "buzz_db_pool_acquisitions_total")
|
||||
.then_some(value)
|
||||
.map(|value| match value {
|
||||
metrics_util::debugging::DebugValue::Counter(value) => *value,
|
||||
_ => panic!("legacy acquisitions must be a counter"),
|
||||
})
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn readiness_check_distinguishes_pool_exhaustion_from_success() {
|
||||
@@ -3118,6 +3182,22 @@ async fn armed_pool_rejects_old_channel_inserts_through_public_api() {
|
||||
db.pool.close().await;
|
||||
}
|
||||
|
||||
/// A writer transaction holding the shared replica-floor advisory lock, the
|
||||
/// shape a floor-compliant writer takes before the exclusive probe can run.
|
||||
async fn begin_replica_floor_locked_writer(db: &Db) -> sqlx::Transaction<'static, sqlx::Postgres> {
|
||||
let mut tx = db
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.expect("begin floor-guarded writer tx");
|
||||
sqlx::query("SELECT pg_advisory_xact_lock_shared($1)")
|
||||
.bind(crate::replica_fence::REPLICA_FLOOR_LOCK_KEY)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.expect("take shared replica-floor lock");
|
||||
tx
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires Postgres"]
|
||||
async fn replica_floor_writer_transaction_holds_shared_lock() {
|
||||
@@ -3137,10 +3217,7 @@ async fn replica_floor_writer_transaction_holds_shared_lock() {
|
||||
.await
|
||||
.expect("connect armed Db");
|
||||
|
||||
let writer = db
|
||||
.begin_replica_floor_locked_event_write_transaction()
|
||||
.await
|
||||
.expect("open compliant floor-guarded writer tx");
|
||||
let writer = begin_replica_floor_locked_writer(&db).await;
|
||||
|
||||
let mut shared_contender = db.pool.begin().await.expect("begin shared contender");
|
||||
let shared_taken: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock_shared($1)")
|
||||
@@ -3201,10 +3278,7 @@ async fn replica_floor_probe_waits_for_shared_writer_and_records_after_release()
|
||||
.await
|
||||
.expect("read token before probe");
|
||||
|
||||
let writer = db
|
||||
.begin_replica_floor_locked_event_write_transaction()
|
||||
.await
|
||||
.expect("open compliant floor-guarded writer tx");
|
||||
let writer = begin_replica_floor_locked_writer(&db).await;
|
||||
|
||||
let probe_pool = db.pool.clone();
|
||||
let probe_fence = std::sync::Arc::clone(db.fence());
|
||||
|
||||
Reference in New Issue
Block a user