Skip to content

Commit b14ef9b

Browse files
committed
perf(relay): elect single scheduled-send leader with horizon sleep and pubsub wake
replace fixed 1s fleet-wide polling in scheduled_release::run with postgres sessionleader election (scheduled_release_lock_key), single-seek horizon sleep via db::next_schedule_wake_at capped at 60s, and fire-and-forget local plus redis pub/sub wake nudges (buzz:scheduled-send:wake) on near-term schedule accepts and relay cancellations (ban, channel deletion, nip-fi disconnect). standby pods poll only the session advisory lock every 12-15s and touch zero scheduled_sends rows, while transactional cas remains the duplicate-proof floor. also route admittedtx::try_admit through deletionstore::guard_transaction_classified so buzz-db observability_source passes all 46 gates, and add unit plus postgres integration tests. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
1 parent fafb00f commit b14ef9b

16 files changed

Lines changed: 971 additions & 101 deletions

‎crates/buzz-db/src/runtime/admitted_tx.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,10 +121,13 @@ impl AdmittedTx {
121121
/// (`quiescing`/`fenced`) communities.
122122
pub(crate) async fn try_admit(
123123
mut tx: Transaction<'static, Postgres>,
124-
_store: &DeletionStore,
124+
store: &DeletionStore,
125125
community: CommunityId,
126126
) -> Result<AdmitAttempt> {
127-
match crate::store::deletion::check_community_write_guard(&mut tx, community).await? {
127+
match store
128+
.guard_transaction_classified(&mut tx, community)
129+
.await?
130+
{
128131
crate::store::deletion::CommunityWriteGuard::Active => {
129132
Ok(AdmitAttempt::Admitted(Self {
130133
tx,

‎crates/buzz-db/src/store/deletion.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3066,6 +3066,17 @@ impl DeletionStore {
30663066
guard_community_write(tx, community).await
30673067
}
30683068

3069+
/// Take the shared community deletion lock inside an existing transaction
3070+
/// and return its classified write-guard state (`Active`,
3071+
/// `MissingOrTombstoned`, or `Fenced`).
3072+
pub(crate) async fn guard_transaction_classified(
3073+
&self,
3074+
tx: &mut Transaction<'_, Postgres>,
3075+
community: CommunityId,
3076+
) -> Result<CommunityWriteGuard> {
3077+
check_community_write_guard(tx, community).await
3078+
}
3079+
30693080
/// Take the shared community deletion lock inside an existing transaction
30703081
/// and authorize a final mutation under an already-admitted serving lease.
30713082
///

‎crates/buzz-db/src/store/scheduled_send.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1026,6 +1026,53 @@ impl Db {
10261026
.collect()
10271027
}
10281028

1029+
/// Earliest Unix timestamp (seconds) after which scheduled-send work may
1030+
/// become actionable, or `None` when no active community has future pending
1031+
/// sends, overdue claimed retries, or unpublished cancellations.
1032+
///
1033+
/// Uses `idx_scheduled_sends_work (state, status_id, not_before)` for
1034+
/// single-seek future lookup (`ORDER BY s.not_before ASC LIMIT 1`) rather
1035+
/// than scanning all pending rows. Overdue unclaimed pending rows
1036+
/// (`not_before <= now` with no active claim) are deliberately excluded:
1037+
/// the release leader calls this immediately after `release_due`, so any
1038+
/// row still unclaimed belongs to a community whose Send Later flag is off
1039+
/// and is bounded by the leader's backstop sleep instead of hot-spinning.
1040+
#[datastore_span(name = "next_schedule_wake_at", system = "postgresql")]
1041+
pub async fn next_schedule_wake_at(&self, now: i64) -> Result<Option<i64>> {
1042+
let mut conn =
1043+
crate::observability::acquire_writer(&self.pool, WriterOperation::Maintenance).await?;
1044+
let next: Option<i64> = sqlx::query_scalar(
1045+
"SELECT MIN(wake_at) FROM ( \
1046+
(SELECT CASE \
1047+
WHEN s.claimed_until IS NULL OR s.claimed_until <= $1 THEN $1 \
1048+
ELSE s.claimed_until \
1049+
END AS wake_at \
1050+
FROM scheduled_sends s JOIN communities c ON c.id = s.community_id \
1051+
WHERE c.deleted_at IS NULL AND c.deletion_state = 'active' \
1052+
AND s.state = 'cancelled' AND s.status_id IS NULL \
1053+
ORDER BY 1 ASC LIMIT 1) \
1054+
UNION ALL \
1055+
(SELECT s.not_before AS wake_at \
1056+
FROM scheduled_sends s JOIN communities c ON c.id = s.community_id \
1057+
WHERE c.deleted_at IS NULL AND c.deletion_state = 'active' \
1058+
AND s.state = 'pending' AND s.status_id IS NULL \
1059+
AND s.not_before > $1 \
1060+
ORDER BY s.not_before ASC LIMIT 1) \
1061+
UNION ALL \
1062+
(SELECT MIN(s.claimed_until) AS wake_at \
1063+
FROM scheduled_sends s JOIN communities c ON c.id = s.community_id \
1064+
WHERE c.deleted_at IS NULL AND c.deletion_state = 'active' \
1065+
AND s.state = 'pending' AND s.status_id IS NULL \
1066+
AND s.not_before <= $1 \
1067+
AND s.claimed_until > $1) \
1068+
) AS candidates",
1069+
)
1070+
.bind(now)
1071+
.fetch_one(&mut *conn)
1072+
.await?;
1073+
Ok(next)
1074+
}
1075+
10291076
/// Claim an unpublished cancellation row until `until` so only one relay
10301077
/// process signs and stores its `kind:30361` status at a time.
10311078
#[datastore_span(name = "claim_cancellation_status", system = "postgresql")]

‎crates/buzz-db/src/store/scheduled_send/postgres_tests.rs‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1387,3 +1387,128 @@ async fn withdraw_all_pending_schedules_cancels_as_withdrawn_and_flags_fenced()
13871387
assert_eq!(second.remaining_pending, 0);
13881388
assert_eq!(second.awaiting_status, 3);
13891389
}
1390+
1391+
#[tokio::test]
1392+
#[ignore = "requires Postgres"]
1393+
async fn next_schedule_wake_at_tracks_horizon_retries_and_cancellations() {
1394+
let admin_url = crate::test_support::database_url();
1395+
let (pool, _scratch) =
1396+
crate::test_support::ScratchDb::migrated(&admin_url, "sched_next_wake").await;
1397+
let db = Db::from_pool(pool);
1398+
let active_community = db
1399+
.ensure_configured_community("sched-wake-active.test")
1400+
.await
1401+
.expect("active community")
1402+
.id;
1403+
let deleted_community = db
1404+
.ensure_configured_community("sched-wake-deleted.test")
1405+
.await
1406+
.expect("deleted community")
1407+
.id;
1408+
1409+
// 1. Empty table -> None.
1410+
assert_eq!(db.next_schedule_wake_at(T).await.expect("empty wake"), None);
1411+
1412+
let author = Keys::generate();
1413+
let author_bytes = author.public_key().to_bytes();
1414+
1415+
// 2. Future pending sends return the earliest `not_before` among active communities.
1416+
let s_far = schedule_id();
1417+
let s_near = schedule_id();
1418+
let s_deleted = schedule_id();
1419+
for (community, sched, due) in [
1420+
(active_community, &s_far, T + 3_600),
1421+
(active_community, &s_near, T + 120),
1422+
(deleted_community, &s_deleted, T + 10),
1423+
] {
1424+
let ev = instruction_event(&author, sched, 1);
1425+
assert_eq!(
1426+
db.store_schedule_instruction(
1427+
community,
1428+
&ScheduleInstruction {
1429+
event: &ev,
1430+
schedule_id: sched,
1431+
generation: 1,
1432+
active: Some(ActiveSchedule {
1433+
not_before: due,
1434+
channel_id: Uuid::from_u128(1),
1435+
owner: None,
1436+
}),
1437+
nip_fi: None,
1438+
max_pending: 100,
1439+
},
1440+
T,
1441+
)
1442+
.await
1443+
.expect("store future"),
1444+
InstructionOutcome::Stored
1445+
);
1446+
}
1447+
crate::test_support::set_deletion_state(db.pool(), *deleted_community.as_uuid(), "tombstone")
1448+
.await;
1449+
assert_eq!(
1450+
db.next_schedule_wake_at(T).await.expect("future wake"),
1451+
Some(T + 120),
1452+
"must pick earliest active future schedule and ignore tombstoned community"
1453+
);
1454+
1455+
// 3. Overdue unclaimed pending rows are excluded (prevents hot-spin when a
1456+
// community's Send Later flag is off); overdue claimed retries ARE included.
1457+
assert_eq!(
1458+
db.next_schedule_wake_at(T + 120)
1459+
.await
1460+
.expect("overdue unclaimed ignored"),
1461+
Some(T + 3_600)
1462+
);
1463+
assert!(db
1464+
.claim_schedule(
1465+
active_community,
1466+
&PendingSchedule {
1467+
author: &author_bytes,
1468+
schedule_id: &s_near,
1469+
generation: 1,
1470+
},
1471+
T + 120,
1472+
T + 135,
1473+
)
1474+
.await
1475+
.expect("claim overdue"));
1476+
assert_eq!(
1477+
db.next_schedule_wake_at(T + 120)
1478+
.await
1479+
.expect("overdue claimed retry"),
1480+
Some(T + 135)
1481+
);
1482+
1483+
// 4. Unpublished cancellation: unclaimed -> immediate (`now`), claimed -> `claimed_until`.
1484+
let cancelled = db
1485+
.cancel_schedules(
1486+
active_community,
1487+
CancelTarget::Pubkey(&author_bytes),
1488+
"banned",
1489+
T + 125,
1490+
)
1491+
.await
1492+
.expect("cancel");
1493+
assert_eq!(cancelled, 2);
1494+
assert_eq!(
1495+
db.next_schedule_wake_at(T + 125)
1496+
.await
1497+
.expect("unclaimed cancellation wakes immediately"),
1498+
Some(T + 125)
1499+
);
1500+
assert!(db
1501+
.claim_cancellation_status(active_community, &author_bytes, &s_near, T + 125, T + 140)
1502+
.await
1503+
.expect("claim first cancel"));
1504+
assert!(db
1505+
.claim_cancellation_status(active_community, &author_bytes, &s_far, T + 125, T + 145)
1506+
.await
1507+
.expect("claim second cancel"));
1508+
assert_eq!(
1509+
db.next_schedule_wake_at(T + 125)
1510+
.await
1511+
.expect("claimed cancellations return earliest claim expiry"),
1512+
Some(T + 140)
1513+
);
1514+
}

‎crates/buzz-db/tests/observability_source.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,6 +1158,7 @@ fn admitted_tx_constructors(source: &str) -> Vec<(String, bool)> {
11581158
.filter(|function| function.contains("Self {") || function.contains("AdmittedTx {"))
11591159
.map(|function| {
11601160
let admits = function.contains(".guard_transaction(&mut tx, community)")
1161+
|| function.contains(".guard_transaction_classified(&mut tx, community)")
11611162
|| function.contains(".guard_transaction_with_serving_lease(&mut tx, lease)");
11621163
(function.to_string(), admits)
11631164
})

‎crates/buzz-pubsub/src/lib.rs‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ pub mod presence;
4444
pub mod publisher;
4545
/// Redis-backed rate limiter (fixed-window INCR + EXPIRE).
4646
pub mod rate_limiter;
47+
/// Cross-pod wake nudges for the NIP-SL scheduled-send release leader.
48+
pub mod scheduled_send;
4749
/// Redis SUBSCRIBE for channel event delivery.
4850
pub mod subscriber;
4951
/// Community-scoped Redis event topics.
@@ -65,6 +67,10 @@ use crate::cache_invalidation::{
6567
use crate::conn_control::{conn_control_channel, ConnControl, ScopedConnControl};
6668
pub use crate::conn_control::{decode_nip_fi_disconnect, encode_nip_fi_disconnect};
6769
pub use crate::conn_control::{NipFiDisconnect, NipFiSubscription};
70+
pub use crate::scheduled_send::{
71+
decode_scheduled_send_wake, encode_scheduled_send_wake, ScheduledSendWake,
72+
SCHEDULED_SEND_WAKE_CHANNEL,
73+
};
6874
pub use crate::topic::{channel_key, global_key, EventTopic, EventTopicKey};
6975

7076
/// A Nostr event received on a scoped Redis event topic, broadcast to local subscribers.
@@ -141,6 +147,7 @@ pub struct PubSubManager {
141147
cache_invalidation_tx: broadcast::Sender<ScopedCacheInvalidation>,
142148
conn_control_tx: broadcast::Sender<ScopedConnControl>,
143149
nip_fi_disconnect_tx: broadcast::Sender<NipFiDisconnect>,
150+
scheduled_send_wake_tx: broadcast::Sender<ScheduledSendWake>,
144151
nip_fi_subscription: watch::Sender<NipFiSubscription>,
145152
link: watch::Sender<LinkState>,
146153
}
@@ -160,6 +167,7 @@ impl PubSubManager {
160167
let (cache_invalidation_tx, _) = broadcast::channel(4096);
161168
let (conn_control_tx, _) = broadcast::channel(4096);
162169
let (nip_fi_disconnect_tx, _) = broadcast::channel(4096);
170+
let (scheduled_send_wake_tx, _) = broadcast::channel(256);
163171
let (subscription_tx, subscription_rx) = mpsc::channel(SUBSCRIPTION_COMMAND_CAPACITY);
164172

165173
Ok(Self {
@@ -174,6 +182,7 @@ impl PubSubManager {
174182
cache_invalidation_tx,
175183
conn_control_tx,
176184
nip_fi_disconnect_tx,
185+
scheduled_send_wake_tx,
177186
nip_fi_subscription: watch::Sender::new(NipFiSubscription::default()),
178187
link: watch::Sender::new(LinkState::default()),
179188
})
@@ -239,6 +248,16 @@ impl PubSubManager {
239248
.await;
240249
}
241250

251+
/// Starts the scheduled-send wake subscriber loop with automatic
252+
/// reconnection. Runs forever — spawn this in a background task.
253+
pub async fn run_scheduled_send_wake_subscriber(self: Arc<Self>) {
254+
scheduled_send::run_scheduled_send_wake_subscriber(
255+
self.redis_url.clone(),
256+
self.scheduled_send_wake_tx.clone(),
257+
)
258+
.await;
259+
}
260+
242261
/// Returns a new broadcast receiver for locally-published channel events.
243262
pub fn subscribe_local(&self) -> broadcast::Receiver<ChannelEvent> {
244263
self.broadcast_tx.subscribe()
@@ -367,6 +386,35 @@ impl PubSubManager {
367386
self.nip_fi_disconnect_tx.subscribe()
368387
}
369388

389+
/// Returns a new broadcast receiver for scheduled-send release wake nudges.
390+
pub fn subscribe_scheduled_send_wake(&self) -> broadcast::Receiver<ScheduledSendWake> {
391+
self.scheduled_send_wake_tx.subscribe()
392+
}
393+
394+
/// Deliver a scheduled-send wake hint directly to local receivers on this
395+
/// process without waiting on Redis loopback.
396+
pub fn notify_scheduled_send_wake_local(&self, wake: ScheduledSendWake) {
397+
let _ = self.scheduled_send_wake_tx.send(wake);
398+
}
399+
400+
/// Publish a scheduled-send wake hint to all pods over Redis pub/sub.
401+
///
402+
/// Pure latency hint: the database remains the source of truth and the
403+
/// leader's backstop sleep handles any dropped message.
404+
pub async fn publish_scheduled_send_wake(
405+
&self,
406+
wake: ScheduledSendWake,
407+
) -> Result<i64, PubSubError> {
408+
let mut conn = self.pool.clone();
409+
let payload = encode_scheduled_send_wake(wake)?;
410+
let subscriber_count: i64 = redis::cmd("PUBLISH")
411+
.arg(SCHEDULED_SEND_WAKE_CHANNEL)
412+
.arg(&payload)
413+
.query_async(&mut conn)
414+
.await?;
415+
Ok(subscriber_count)
416+
}
417+
370418
/// Watch the NIP-FI disconnect subscription: every confirmed subscribe
371419
/// and every loss bumps its epoch.
372420
pub fn watch_nip_fi_subscription(&self) -> watch::Receiver<NipFiSubscription> {

0 commit comments

Comments
 (0)