Skip to content

Commit c01241c

Browse files
committed
chore(relay): align nip-sl schema, tracing, docs and poller with repo guidelines
drop redundant scheduled_sends author index and lead owner index with community_id in 0112_scheduled_sends.sql and schema/tables/public/scheduled_sends.sql. document the deliberate multi-community nip-fi disconnect exception in architecture.md and admitted_tx.rs. instrument impl db scheduled_send methods with datastore_span. add startup jitter and capped exponential backoff with jitter to scheduled_release::run. Signed-off-by: Kalvin Chau <kalvin@block.xyz>
1 parent 67efa49 commit c01241c

6 files changed

Lines changed: 72 additions & 15 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,13 @@ Relay-owned write APIs provide the supported mutation path for tenant data:
496496
- **Community fence:** supported serving writers admit each tenant transaction
497497
through the runtime API, which takes one shared community deletion lock and
498498
checks active, undeleted state. Deletion lifecycle transitions take the
499-
matching exclusive lock. A serving transaction never spans communities.
499+
matching exclusive lock. Ordinary serving transactions never span communities;
500+
the one deliberate exception is `Db::record_nip_fi_disconnect_and_cancel`,
501+
which `docs/nips/NIP-FI.md` § *Deferred actions* requires to record an
502+
issuer disconnect and cancel matching pending scheduled sends across all
503+
communities in one atomic transaction. It admits every affected community
504+
through `AdmittedTx::try_admit` in ascending `community_id` order under the
505+
exclusive issuer lock and skips fenced communities.
500506
The universal per-table write-fence triggers and their functions have been
501507
retired after writer coverage and fleet gates. New tenant-owned tables rely
502508
on this admission alone.

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

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,11 @@ impl AdmittedTx {
9898
}
9999

100100
/// Take the shared community admission lock on `tx` and wrap it, returning
101-
/// `Ok(Err((tx, err)))` if `community` is fenced or deleted so a
102-
/// multi-community transaction (such as NIP-FI disconnect cancellation)
103-
/// can skip a fenced community and continue atomically.
101+
/// `Ok(Err((tx, err)))` if `community` is fenced or deleted so the
102+
/// multi-community NIP-FI deferred-action disconnect transaction
103+
/// (`ARCHITECTURE.md` § *Supported Writer Contract*, `docs/nips/NIP-FI.md`
104+
/// § *Deferred actions*) can admit affected communities in ascending
105+
/// `community_id` order, skip fenced ones, and commit atomically.
104106
pub(crate) async fn try_admit(
105107
mut tx: Transaction<'static, Postgres>,
106108
store: &DeletionStore,

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
1010
use buzz_core::kind::{KIND_SCHEDULE_INSTRUCTION, KIND_SCHEDULE_STATUS};
1111
use buzz_core::CommunityId;
12+
use buzz_datastore_tracing::datastore_span;
1213
use chrono::DateTime;
1314
use nostr::Event;
1415
use sqlx::Row;
@@ -742,6 +743,7 @@ async fn expire_in_transaction(
742743

743744
impl Db {
744745
/// The stored head of a schedule address, if the address holds a schedule.
746+
#[datastore_span(name = "schedule_head", system = "postgresql")]
745747
pub async fn schedule_head(
746748
&self,
747749
community: CommunityId,
@@ -773,6 +775,7 @@ impl Db {
773775
/// head at the next generation. The cancel form replaces a pending head
774776
/// and ends the schedule as cancelled by its author. Either way the replaced instruction
775777
/// is deleted. `now` is the end time a cancel records.
778+
#[datastore_span(name = "store_schedule_instruction", system = "postgresql")]
776779
pub async fn store_schedule_instruction(
777780
&self,
778781
community: CommunityId,
@@ -806,6 +809,7 @@ impl Db {
806809
/// Pending schedules whose release time is at or before `now` and that
807810
/// no process holds, oldest first, after the schedule `after` names when
808811
/// given.
812+
#[datastore_span(name = "due_schedules", system = "postgresql")]
809813
pub async fn due_schedules(
810814
&self,
811815
now: i64,
@@ -863,6 +867,7 @@ impl Db {
863867
/// The claim keeps several processes from running one release at once
864868
/// and spaces the attempts at it. It decides nothing: whether a release
865869
/// applies is decided by the change that ends the schedule.
870+
#[datastore_span(name = "claim_schedule", system = "postgresql")]
866871
pub async fn claim_schedule(
867872
&self,
868873
community: CommunityId,
@@ -898,6 +903,7 @@ impl Db {
898903
/// Cancel the pending schedules `target` selects in one transaction: see
899904
/// [`cancel_schedules_in_transaction`]. For a cause that a release finds
900905
/// already in force.
906+
#[datastore_span(name = "cancel_schedules", system = "postgresql")]
901907
pub async fn cancel_schedules(
902908
&self,
903909
community: CommunityId,
@@ -921,6 +927,7 @@ impl Db {
921927
/// instruction stays readable until text retention passes or the author
922928
/// holds more than `max_pending` ended instructions. Returns `false` when
923929
/// the schedule is no longer pending at that generation.
930+
#[datastore_span(name = "end_schedule", system = "postgresql")]
924931
pub async fn end_schedule(
925932
&self,
926933
community: CommunityId,
@@ -947,6 +954,7 @@ impl Db {
947954
}
948955

949956
/// Schedules the relay cancelled whose status is not stored yet.
957+
#[datastore_span(name = "schedules_awaiting_status", system = "postgresql")]
950958
pub async fn schedules_awaiting_status(
951959
&self,
952960
limit: i64,
@@ -981,6 +989,7 @@ impl Db {
981989

982990
/// Store the status of a schedule the relay cancelled. Returns `false`
983991
/// when another process stored one first.
992+
#[datastore_span(name = "store_cancellation_status", system = "postgresql")]
984993
pub async fn store_cancellation_status(
985994
&self,
986995
community: CommunityId,
@@ -1021,6 +1030,7 @@ impl Db {
10211030
/// NIP-FI §Deferred actions requires reading every admission's time and
10221031
/// `recorded_at` from one clock — that of the durable storage — so skew
10231032
/// between relay processes cannot leave an admission unfenced.
1033+
#[datastore_span(name = "storage_clock_now", system = "postgresql")]
10241034
pub async fn storage_clock_now(&self) -> Result<(i64, i32)> {
10251035
let mut conn =
10261036
crate::observability::acquire_writer(&self.pool, WriterOperation::Authorization)
@@ -1036,6 +1046,7 @@ impl Db {
10361046
/// cancelling anything if inserting the record would exceed
10371047
/// `max_records_per_issuer`.
10381048
#[allow(clippy::too_many_arguments)]
1049+
#[datastore_span(name = "record_nip_fi_disconnect_and_cancel", system = "postgresql")]
10391050
pub async fn record_nip_fi_disconnect_and_cancel(
10401051
&self,
10411052
issuer: &str,
@@ -1203,6 +1214,7 @@ impl Db {
12031214

12041215
/// Apply the retention periods in every community that has something past
12051216
/// them: see `expire_in_transaction`. Returns how many schedules changed.
1217+
#[datastore_span(name = "expire_schedules", system = "postgresql")]
12061218
pub async fn expire_schedules(&self, text_cutoff: i64, status_cutoff: i64) -> Result<u64> {
12071219
let mut conn =
12081220
crate::observability::acquire_writer(&self.pool, WriterOperation::Maintenance).await?;

‎crates/buzz-relay/src/handlers/scheduled_release.rs‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,11 @@ use crate::state::AppState;
2929

3030
/// Time between passes over the due schedules.
3131
const PASS_EVERY: Duration = Duration::from_secs(1);
32-
/// Time before the next pass when one could not read the schedules.
33-
const FAILED_PASS_PAUSE: Duration = Duration::from_secs(30);
32+
/// Initial pause after a failed pass; doubles on consecutive failures up to
33+
/// [`FAILED_PASS_MAX_PAUSE`].
34+
const FAILED_PASS_MIN_PAUSE: Duration = Duration::from_secs(2);
35+
/// Maximum pause after consecutive failed passes.
36+
const FAILED_PASS_MAX_PAUSE: Duration = Duration::from_secs(30);
3437
/// Schedules read at a time.
3538
const PAGE: i64 = 100;
3639
/// Passes between retention sweeps.
@@ -117,20 +120,37 @@ pub(crate) async fn store(
117120
Ok(Some((stored, inserted, snapshots)))
118121
}
119122

123+
/// Pause before the next pass: [`PASS_EVERY`] after a healthy pass, or capped
124+
/// exponential backoff jittered down by up to 20% after consecutive failures
125+
/// so pods recovering from a shared DB outage do not retry in lockstep.
126+
fn next_pass_pause(consecutive_failures: u32, jitter_unit: f64) -> Duration {
127+
let base = match consecutive_failures {
128+
0 => return PASS_EVERY,
129+
n => FAILED_PASS_MIN_PAUSE
130+
.saturating_mul(1u32 << (n - 1).min(16))
131+
.min(FAILED_PASS_MAX_PAUSE),
132+
};
133+
base.mul_f64(1.0 - jitter_unit.clamp(0.0, 1.0) * 0.2)
134+
}
135+
120136
/// Release due schedules until the process stops. Intended for `tokio::spawn`.
121137
pub async fn run(state: Arc<AppState>) {
138+
// Spread pods across the poll interval on startup / rolling restart.
139+
tokio::time::sleep(PASS_EVERY.mul_f64(rand::random::<f64>())).await;
122140
let clock = || chrono::Utc::now().timestamp();
123141
let mut pass: u32 = 0;
142+
let mut consecutive_failures: u32 = 0;
124143
loop {
125144
let retention = pass.is_multiple_of(RETENTION_EVERY);
126145
pass = pass.wrapping_add(1);
127-
let pause = match run_pass(&state, &clock, retention).await {
128-
Ok(()) => PASS_EVERY,
146+
match run_pass(&state, &clock, retention).await {
147+
Ok(()) => consecutive_failures = 0,
129148
Err(e) => {
130-
error!("scheduled send pass failed: {e}");
131-
FAILED_PASS_PAUSE
149+
consecutive_failures = consecutive_failures.saturating_add(1);
150+
error!(consecutive_failures, "scheduled send pass failed: {e}");
132151
}
133-
};
152+
}
153+
let pause = next_pass_pause(consecutive_failures, rand::random::<f64>());
134154
tokio::time::sleep(pause).await;
135155
}
136156
}
@@ -532,3 +552,22 @@ async fn refusal(
532552
_ => Ok(Refusal::Failed("attachment")),
533553
}
534554
}
555+
556+
#[cfg(test)]
557+
mod tests {
558+
use super::*;
559+
560+
#[test]
561+
fn next_pass_pause_backs_off_with_cap_and_jitter() {
562+
assert_eq!(next_pass_pause(0, 0.0), PASS_EVERY);
563+
assert_eq!(next_pass_pause(0, 1.0), PASS_EVERY);
564+
assert_eq!(next_pass_pause(1, 0.0), Duration::from_secs(2));
565+
assert_eq!(next_pass_pause(1, 1.0), Duration::from_millis(1_600));
566+
assert_eq!(next_pass_pause(2, 0.0), Duration::from_secs(4));
567+
assert_eq!(next_pass_pause(3, 0.0), Duration::from_secs(8));
568+
assert_eq!(next_pass_pause(4, 0.0), Duration::from_secs(16));
569+
assert_eq!(next_pass_pause(5, 0.0), FAILED_PASS_MAX_PAUSE);
570+
assert_eq!(next_pass_pause(u32::MAX, 0.0), FAILED_PASS_MAX_PAUSE);
571+
assert_eq!(next_pass_pause(u32::MAX, 1.0), Duration::from_secs(24));
572+
}
573+
}

‎migrations/0112_scheduled_sends.sql‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,7 @@ CREATE TABLE scheduled_sends (
4040
CREATE INDEX idx_scheduled_sends_work ON scheduled_sends (state, status_id, not_before);
4141
CREATE INDEX idx_scheduled_sends_ended ON scheduled_sends (ended_at);
4242
CREATE INDEX idx_scheduled_sends_channel ON scheduled_sends (community_id, channel_id);
43-
CREATE INDEX idx_scheduled_sends_author ON scheduled_sends (author, community_id);
44-
CREATE INDEX idx_scheduled_sends_owner ON scheduled_sends (owner, community_id);
43+
CREATE INDEX idx_scheduled_sends_owner ON scheduled_sends (community_id, owner);
4544
CREATE INDEX idx_scheduled_sends_issuer_author ON scheduled_sends (issuer, author);
4645
CREATE INDEX idx_scheduled_sends_issuer_owner ON scheduled_sends (issuer, owner);
4746

‎schema/tables/public/scheduled_sends.sql‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ CREATE TABLE scheduled_sends (
3535
CREATE INDEX idx_scheduled_sends_work ON scheduled_sends (state, status_id, not_before);
3636
CREATE INDEX idx_scheduled_sends_ended ON scheduled_sends (ended_at);
3737
CREATE INDEX idx_scheduled_sends_channel ON scheduled_sends (community_id, channel_id);
38-
CREATE INDEX idx_scheduled_sends_author ON scheduled_sends (author, community_id);
39-
CREATE INDEX idx_scheduled_sends_owner ON scheduled_sends (owner, community_id);
38+
CREATE INDEX idx_scheduled_sends_owner ON scheduled_sends (community_id, owner);
4039
CREATE INDEX idx_scheduled_sends_issuer_author ON scheduled_sends (issuer, author);
4140
CREATE INDEX idx_scheduled_sends_issuer_owner ON scheduled_sends (issuer, owner);

0 commit comments

Comments
 (0)