Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ TYPESENSE_URL=http://localhost:8108
BUZZ_BIND_ADDR=0.0.0.0:3000
# Public WebSocket URL — used in NIP-42 auth challenges
RELAY_URL=ws://localhost:3000
# Deploy deletion compatibility before migration, then replace all probes while off.
# Scheduling requires BUZZ_DB_POOL_SIZE of at least 2.
# See docs/scheduled-messages.md before enabling or downgrading with pending work.
# BUZZ_SCHEDULED_MESSAGES=on
# Stable relay signing key (required). `just bootstrap` generates a random key in
# the gitignored .env file. Preserve that value across restarts and backups.
# BUZZ_RELAY_PRIVATE_KEY=<32-byte hex private key>
Expand Down
6 changes: 6 additions & 0 deletions crates/buzz-db/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ pub enum DbError {
#[error("database error: {0}")]
Sqlx(#[from] sqlx::Error),

/// The resolved reply parent vanished before the event could be persisted.
#[error("reply parent disappeared before persistence")]
ReplyParentMissing,

/// A SQLx migration error.
#[error("migration error: {0}")]
Migrate(#[from] sqlx::migrate::MigrateError),
Expand Down Expand Up @@ -254,6 +258,7 @@ impl DatastoreSpanError for DbError {
match self {
E::MediaAuthorizationCapacity => "media_authorization_capacity",
E::Sqlx(e) => sqlx_error_type(e),
E::ReplyParentMissing => "reply_parent_missing",
E::Migrate(_) => "migrate",
E::AuthEventRejected => "auth_event_rejected",
E::EphemeralEventRejected(_) => "ephemeral_event_rejected",
Expand Down Expand Up @@ -301,6 +306,7 @@ impl DbError {
E::InvalidData(_) => "invalid_data",
E::NotFound(_) | E::ChannelNotFound(_) | E::MemberNotFound(_) => "not_found",
E::AccessDenied(_) => "access_denied",
E::ReplyParentMissing => "reply_parent_missing",
E::NipFiBindingRequired => "nip_fi_binding_required",
_ => "other",
};
Expand Down
3 changes: 3 additions & 0 deletions crates/buzz-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ extern crate self as buzz_db;
mod runtime;
mod store;

/// Durable scheduled-message records and dispatch claims.
pub use store::scheduled;

/// Concurrency caps whose limit can change at runtime.
pub mod concurrency_gate;

Expand Down
13 changes: 13 additions & 0 deletions crates/buzz-db/src/runtime/admitted_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ pub struct AdmittedTx {
ttl_refresh_channels: BTreeSet<Uuid>,
push_enqueue: Option<super::push_enqueue::PushEnqueue>,
push_events: Vec<StagedPushEvent>,
scheduled_event: Option<nostr::EventId>,
}

struct StagedPushEvent {
Expand All @@ -98,6 +99,7 @@ impl AdmittedTx {
ttl_refresh_channels: BTreeSet::new(),
push_enqueue: None,
push_events: Vec::new(),
scheduled_event: None,
})
}

Expand All @@ -117,9 +119,20 @@ impl AdmittedTx {
ttl_refresh_channels: BTreeSet::new(),
push_enqueue: None,
push_events: Vec::new(),
scheduled_event: None,
})
}

/// Permit only the exact event protected by this transaction's locked queue
/// claim and durable replica reservation. Called only by scheduled delivery.
pub(crate) fn authorize_scheduled_event(&mut self, id: nostr::EventId) {
self.scheduled_event = Some(id);
}

pub(crate) fn has_scheduled_event_reservation(&self, id: &nostr::EventId) -> bool {
self.scheduled_event.as_ref() == Some(id)
}

pub(crate) fn set_push_enqueue(&mut self, producer: Option<super::push_enqueue::PushEnqueue>) {
self.push_enqueue = producer;
}
Expand Down
19 changes: 14 additions & 5 deletions crates/buzz-db/src/runtime/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ pub(crate) async fn run_migrations_through(pool: &PgPool, target: i64) -> Result
/// the historical fence objects. These fixtures never migrate further.
#[cfg(test)]
pub(crate) async fn add_catalog_schema_after_fence_retirement(pool: &PgPool) -> Result<()> {
// Tenant tables (0106, 0107) and upload lease attribution (0111).
for version in [106, 107, 111] {
// Tenant tables (0106, 0107, 0112) and upload lease attribution (0111).
for version in [106, 107, 111, 112] {
let migration = MIGRATOR
.iter()
.find(|migration| migration.version == version)
Expand Down Expand Up @@ -1200,7 +1200,13 @@ mod postgres_tests {
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
migrations.sort_by_key(|migration| migration.version);

assert_eq!(migrations.len(), 111);
assert_eq!(migrations.len(), 113);
assert_eq!(migrations[112].version, 113);
assert!(strip_sql_comments(migrations[112].sql.as_str())
.contains("CREATE INDEX scheduled_messages_expiry"));
assert_eq!(migrations[111].version, 112);
assert!(strip_sql_comments(migrations[111].sql.as_str())
.contains("CREATE TABLE scheduled_messages"));
assert_eq!(migrations[110].version, 111);
assert!(migrations[110]
.sql
Expand Down Expand Up @@ -1891,6 +1897,7 @@ mod postgres_tests {
"nip_fi_profile_heads",
"media_uploaders",
"media_publications",
"scheduled_messages",
"search_outbox",
"search_backfill",
];
Expand Down Expand Up @@ -3746,6 +3753,7 @@ mod postgres_tests {
.expect("apply migrations for schema parity");

for table in [
"scheduled_messages",
"community_serving_write_leases",
"media_uploaders",
"audit_log",
Expand Down Expand Up @@ -3839,6 +3847,7 @@ mod postgres_tests {
for table in [
"communities",
"community_auth_upgrades",
"scheduled_messages",
"community_serving_write_leases",
"entity_deletion_requests",
"entity_deletion_stage_history",
Expand Down Expand Up @@ -4746,7 +4755,7 @@ mod postgres_tests {
.expect_err("deletion refuses a catalog missing later tenant tables")
.to_string();
assert!(
drift.contains("(missing=search_backfill,search_outbox, unknown=)"),
drift.contains("(missing=scheduled_messages,search_backfill,search_outbox, unknown=)"),
"deletion must accept the pre-retirement fences: {drift}"
);
run_migrations(&pool).await.expect("apply all migrations");
Expand Down Expand Up @@ -4835,7 +4844,7 @@ mod postgres_tests {
.expect_err("deletion refuses a catalog missing later tenant tables")
.to_string();
assert!(
drift.contains("(missing=search_backfill,search_outbox, unknown=)"),
drift.contains("(missing=scheduled_messages,search_backfill,search_outbox, unknown=)"),
"deletion must accept the catalog before the drop: {drift}"
);
run_migrations(&pool).await.expect("apply all migrations");
Expand Down
29 changes: 23 additions & 6 deletions crates/buzz-db/src/runtime/replica_fence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
//!
//! 1. **Insert-time floor**: supported channel-event writers check `created_at`
//! against database `clock_timestamp()` on their admitted transaction for
//! each new row. Duplicate INSERTs need no floor check. This is the only
//! guard: migration 0089 retired 0021's deferred trigger and the
//! writer-pool `buzz.created_at_floor` GUC.
//! each new row. Duplicate INSERTs need no floor check. A locked scheduled
//! claim permits its exact reserved event to retain its original timestamp;
//! pending reservations cap the heartbeat wall until delivery commits.
//! 2. **Ordered heartbeat handshake** (this module): on one pinned writer
//! connection, one transaction first takes the exclusive replica-floor
//! advisory lock (draining compliant shared-lock channel writers), then
Expand All @@ -31,7 +31,9 @@
//! There is no fourth bucket. Each committed token `M` therefore proves a
//! **fence wall** of `min(oldest_xact_start, S) - floor - clock_margin`:
//! every channel-window row with `created_at <= fence_wall(M)` is present
//! on any reader session observing `token >= M`.
//! on any reader session observing `token >= M`. Before committing the
//! heartbeat, the probe also caps that wall strictly below every pending
//! scheduled event's timestamp.
//!
//! Unlike the previous WAL-LSN observation (`pg_last_wal_replay_lsn()`, which
//! Aurora reader endpoints hide), the token observation is portable and —
Expand Down Expand Up @@ -96,8 +98,11 @@ pub(crate) async fn guard_event_created_at_floor(
tx: &mut crate::AdmittedTx,
created_at: DateTime<Utc>,
channel_id: Option<Uuid>,
event_id: &nostr::EventId,
) -> crate::Result<()> {
if channel_id.is_none() {
// A locked scheduled claim reserves this exact signed event below the
// published fence wall; ordinary writes retain the fixed timestamp floor.
if channel_id.is_none() || tx.has_scheduled_event_reservation(event_id) {
return Ok(());
}
let below_floor: bool = sqlx::query_scalar(
Expand Down Expand Up @@ -440,6 +445,8 @@ impl ReplicaFence {
/// One writer-side sample of the ordered handshake.
#[derive(Debug)]
struct WriterSample {
/// Below every pending scheduled timestamp (including send-now clock slack).
scheduled_wall: Option<DateTime<Utc>>,
/// `S`: writer `clock_timestamp()` captured first.
sampled_at: DateTime<Utc>,
/// Oldest open transaction among other client backends at scan time,
Expand Down Expand Up @@ -735,6 +742,12 @@ async fn sample_writer(
})
.await?;

let scheduled_wall: Option<DateTime<Utc>> = sqlx::query_scalar(
"SELECT to_timestamp(min(send_at)-301) FROM scheduled_messages WHERE status='scheduled'",
)
.fetch_one(&mut *tx)
.await?;

// 3. Token commit LAST, on the same pinned connection. The single-row
// UPDATE serializes concurrent pods' probes, so RETURNING token is
// globally commit-ordered. `committed_at` is captured before the
Expand All @@ -752,6 +765,7 @@ async fn sample_writer(
.ok_or(ProbeError::HeartbeatRowMissing)?;

let sample = WriterSample {
scheduled_wall,
sampled_at,
oldest_xact_start,
token: row.get("token"),
Expand Down Expand Up @@ -851,7 +865,10 @@ async fn probe_untraced(
timings: &mut ProbeTimings,
) -> Result<TokenEntry, ProbeError> {
let sample = sample_writer(writer, timings).await?;
let wall = fence_wall(sample.sampled_at, sample.oldest_xact_start);
let ordinary_wall = fence_wall(sample.sampled_at, sample.oldest_xact_start);
let wall = sample
.scheduled_wall
.map_or(ordinary_wall, |reservation| ordinary_wall.min(reservation));
match fence.record(sample.token, sample.epoch, sample.committed_at, wall) {
RecordOutcome::Recorded => Ok(TokenEntry {
token: sample.token,
Expand Down
1 change: 1 addition & 0 deletions crates/buzz-db/src/store/channel_members.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,7 @@ impl LockedMemberSnapshot {
&mut self.tx,
created_at,
Some(channel_id),
&event.id,
)
.await?;
// A superseded roster is deleted, not soft-deleted.
Expand Down
18 changes: 18 additions & 0 deletions crates/buzz-db/src/store/deletion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ pub const PURGE_BATCH_ROWS: i64 = 5_000;
/// [`PENDING_SCOPED_TABLES`] and [`RETIRING_SCOPED_TABLES`] are accepted present
/// or absent and are not listed here.
pub const EXPECTED_SCOPED_TABLES: &[&str] = &[
"scheduled_messages",
"nip_fi_profile_heads",
"api_tokens",
"archived_identities",
Expand Down Expand Up @@ -212,6 +213,7 @@ const PROVENANCE_TABLES: [(&str, &str, &str); 2] = [
/// key needs the order, but the list must stay complete
/// ([`EXPECTED_SCOPED_TABLES`] gates it).
pub const PURGE_SCOPED_TABLES: &[&str] = &[
"scheduled_messages",
"nip_fi_profile_heads",
"personal_read_frontiers",
"personal_read_accounts",
Expand Down Expand Up @@ -11846,6 +11848,12 @@ DROP FUNCTION protect_community_deletion_manifest_keys();
.as_uuid()
.to_owned();
seed_relay_admin_rows(&db, bystander).await;
for tenant in [community, bystander] {
sqlx::query("INSERT INTO scheduled_messages(community_id,owner,id,event,event_id,send_at,next_attempt_at) VALUES($1,$2,$3,'{}',$4,1,1)")
.bind(tenant).bind([7u8;32].as_slice()).bind(Uuid::new_v4())
.bind([8u8;32].as_slice()).execute(&db.pool).await.unwrap();
}

// Operator workflow history is retained even when its provenance
// community is purged; it is not a tenant-owned serving table.
let entity = db
Expand Down Expand Up @@ -11955,6 +11963,16 @@ DROP FUNCTION protect_community_deletion_manifest_keys();
serde_json::to_value(approvals_after).unwrap()
);

assert_eq!(deleted.get("scheduled_messages"), Some(&1));
let survivors: Vec<Uuid> = sqlx::query_scalar(
"SELECT community_id FROM scheduled_messages WHERE community_id IN ($1,$2)",
)
.bind(community)
.bind(bystander)
.fetch_all(&db.pool)
.await
.unwrap();
assert_eq!(survivors, vec![bystander]);
assert_eq!(deleted.get("relay_admin_outbox"), Some(&2));
assert_eq!(deleted.get("relay_admin_actions"), Some(&2));
assert_eq!(relay_admin_row_counts(&db, community).await, (0, 0));
Expand Down
10 changes: 5 additions & 5 deletions crates/buzz-db/src/store/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,8 @@ async fn insert_event_on(

let was_inserted = result.rows_affected() > 0;
if was_inserted {
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?;
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id, &event.id)
.await?;
crate::store::event_follow_up::after_admitted_insert(
tx,
id_bytes.as_slice(),
Expand Down Expand Up @@ -2023,9 +2024,7 @@ pub(crate) async fn insert_event_with_thread_metadata_tx(
.bind(community_id.as_uuid()).bind(parent).bind(created)
.fetch_one(tx.conn()).await?;
if !exists {
return Err(DbError::InvalidData(
"reply parent disappeared before persistence".into(),
));
return Err(DbError::ReplyParentMissing);
}
}
}
Expand Down Expand Up @@ -2055,7 +2054,8 @@ pub(crate) async fn insert_event_with_thread_metadata_tx(
let was_inserted = result.rows_affected() > 0;

if was_inserted {
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?;
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id, &event.id)
.await?;
crate::store::event_follow_up::after_admitted_insert(
tx,
id_bytes.as_slice(),
Expand Down
3 changes: 3 additions & 0 deletions crates/buzz-db/src/store/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
//! Domain-owned persistence implementations.

/// Durable scheduled messages.
pub mod scheduled;

/// Explicit deployment-global admin report reads.
pub mod admin_moderation;
/// Community-scoped authentication allowlist persistence.
Expand Down
5 changes: 3 additions & 2 deletions crates/buzz-db/src/store/replaceable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ async fn replace_parameterized_event_in_transaction_impl(
// After the replay exit: a stored id (even soft-deleted) is a
// duplicate, not a floor rejection. Failure rolls back to the
// savepoint, restoring the previous live head.
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?;
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id, &event.id).await?;

if is_nip_rs {
sqlx::query(
Expand Down Expand Up @@ -580,7 +580,8 @@ pub(crate) async fn replace_addressable_event_under_lock(
}
// After the replay exit, as in the parameterized path; the caller's
// rollback restores the previous head on failure.
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id).await?;
crate::replica_fence::guard_event_created_at_floor(tx, created_at, channel_id, &event.id)
.await?;

crate::store::event_follow_up::after_admitted_insert(
tx,
Expand Down
Loading
Loading