Skip to content

Commit 5884965

Browse files
baxenkalvinnchauclaude
authored
perf(relay): bound channel- and thread-window aux hops to a day before the oldest target (#9874)
## Summary Both window aux closures, the channel window and the thread window, now read their `#e` hops from one day before the window's oldest aux target. That lets Postgres prune older `events` partitions instead of probing the community's whole history. ### Channel window `handle_channel_window_filter` runs two `#e` aux hops for a channel window: hop 1 fetches the reactions, edits and deletions of the window rows, and hop 2 fetches the deletions of those aux events. Neither hop had a lower time bound, so each `#e` GIN probe ran against every `events` partition in the community's history. Both hops now read from `since = oldest retained window row's created_at − 1 day` (`WINDOW_AUX_SINCE_MARGIN_SECS`), which lets Postgres prune the older partitions. A hop-2 deletion postdates the aux event it deletes, so one bound covers both hops. An empty window has no bound, and no hops run for it. **Why it's safe** - Ingest rejects events more than ±15 min from the relay clock (`MAX_TIMESTAMP_DRIFT_SECS`), so an aux event can predate its target by at most about 30 min. The day of margin covers that, plus data that reached the store some other way. - In a sample of about 86.6k aux events across every partition, none was dated more than 1 day before its target. **Measured** - Channel 029f8049: both lookups went from 927 to 230 ms. - Channel a9cb3f0a: 256 to 46 ms. - Prod `pg_stat_statements`: hop 2 averages 147 ms over 2.9M calls and returns 0 rows on average, so most of that time is spent scanning partitions it can now skip. **Known risk:** a tighter bound can flip the planner to a worse plan on busy channels. A 1-hour margin did this in testing. The 1-day margin is the one that measured well. ### Thread window `thread_window::query` → `buzz_db` `thread_window_aux` runs the same two hops. `AuxQuery` gains an optional `since`, which `select_aux` adds as `created_at >= since`. In a thread window, `rows` holds only replies, but the root is always a hop-1 target, so the bound is `min(root created_at, oldest reply) − 1 day`. `select_window` now reads the root's `MIN(created_at)` in the query that already checked the root exists in the channel (it used to be `EXISTS`), and returns it as `ThreadWindow::root_created_at`. Both paths share `window_aux_since`. **Measured** on the prod reader with `EXPLAIN (ANALYZE, BUFFERS)`, warm, with the exact `select_aux` SQL: 50-reply windows (51 targets), and an accessible set of 974 channels (a real user's). Times are execution + planning ms; rows were identical with and without the bound in every case: | Thread | Hop | Unbounded | Bounded | |---|---|---|---| | 244d0894: 1570 replies, root Nov 16 | hop 1 | 352 (45.0k buf) | 108 (13.4k buf) | | 0fdaa9bb: busy channel 638c53ca | hop 1 | 357 (45.0k buf) | 111 (12.5k buf) | | 346a47e6: busy channel 029f8049 | hop 1 / hop 2 | 100 / 53 | 45 / 14 | | f7c2c2f9: root Sep 22, still active | hop 1 / hop 2 | 330 / 53 | 259 / 37 | With only the thread's own channel accessible, the same cases went 216 → 15, 218 → 21, 76 → 31 (hop 2 35 → 5), and 214 → 151. None of the bounded plans was worse: they use the Nov partition's `kind_created_at` btree plus its tags GIN. An old root gains less, because the bound still has to reach back to the root's month. Prod `pg_stat_statements` (reader, since Nov 2): the thread aux shape ran 1.03M calls, averaging 50 ms, 8.5k buffers and 3.9 rows per call, 14.4 h in total. Cost grows by about 4.5 ms and 800 buffers per target: 11 targets averaged 52 ms over 268k calls, and 51 targets averaged 250 ms over 43k calls. Caveat: I measured with literals, which gives custom plans. If sqlx's prepared statements switch to a generic plan, partitions are still pruned, but at execution time rather than at planning time. ### Related issue N/A. This comes from the structural first-paint investigation of prod head-read latency. No existing issue or PR found. ### Testing - New thread test `thread_window_aux_hops_read_from_a_day_before_the_root`: its only reply is 2 days newer than the root, so a bound anchored on the replies alone would fail it. A reaction and a delete-of-reaction dated inside the bound come back, and ones dated more than a day before the root do not. Two mutation checks fail as expected: dropping the SQL clause fails on "hop 1 past the bound", and leaving the root out of the bound fails on "hop 1 inside the bound". - New channel test `channel_window_aux_hops_read_from_a_day_before_the_oldest_row`: a reaction and a delete-of-reaction dated inside the bound come back, and ones dated more than a day before the oldest row do not. As a mutation check, removing `aux_query.since` makes it fail on "hop 1 past the bound". - `scripts/postgres-test-run.sh`: `buzz-relay` `api::bridge::` 135/135 pass and `buzz-db` `thread_window|thread::` 28/28 pass. The workflow-webhook test needs `REDIS_URL` set. - The Security check fails on a new advisory, RUSTSEC-2026-0592 (`url` 2.5.8, in `Cargo.lock`). This PR doesn't touch dependencies, and main's run of that workflow at 42dc2a8 failed too. - `cargo fmt --all -- --check` and `cargo clippy -p buzz-db -p buzz-relay --all-targets -- -D warnings` are clean, and the pre-push hooks passed. --------- Signed-off-by: Bradley Axen <baxen@squareup.com> Signed-off-by: Kalvin Chau <kalvin@block.xyz> Co-authored-by: Kalvin Chau <kalvin@block.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 8cc7e94 commit 5884965

9 files changed

Lines changed: 330 additions & 14 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3594,6 +3594,7 @@ async fn thread_window_statement_cancel_propagates_without_writer_rerun() {
35943594
kinds: &[7],
35953595
accessible: &accessible,
35963596
cursor: None,
3597+
since: None,
35973598
};
35983599
match session
35993600
.thread_window_aux(&aux, &mut ScanBudget::default())

‎crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() {
9999
kinds: &[5, 40003],
100100
accessible: &[channel],
101101
cursor: None,
102+
since: None,
102103
};
103104
let mut budget = ScanBudget::default();
104105
let stale = session

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ pub struct ThreadWindow {
2929
/// A supported conversation root exists in this channel, possibly as a
3030
/// tombstone. Only then may the bridge serve rows, auxiliary events or bounds.
3131
pub root_in_channel: bool,
32+
/// The root's `created_at` when [`Self::root_in_channel`]. The root is
33+
/// always an auxiliary target, so it anchors the auxiliary time bound.
34+
pub root_created_at: Option<DateTime<Utc>>,
3235
}
3336

3437
fn invalid(message: impl Into<String>) -> DbError {
@@ -87,17 +90,19 @@ async fn select_window(
8790
}
8891
// Retain tombstones: deleting a root must not make its readable replies
8992
// disappear. Never follow a root belonging to another channel/community.
90-
let root_in_channel: bool = sqlx::query_scalar(
91-
"SELECT EXISTS(SELECT 1 FROM events WHERE community_id = $1 AND channel_id = $2 AND id = $3 AND kind = ANY($4))")
93+
let root_created_at: Option<DateTime<Utc>> = sqlx::query_scalar(
94+
"SELECT MIN(created_at) FROM events WHERE community_id = $1 AND channel_id = $2 AND id = $3 AND kind = ANY($4)")
9295
.bind(community.as_uuid()).bind(request.channel).bind(&root)
9396
.bind(ROW_KINDS.map(|k| k as i32).to_vec())
9497
.fetch_one(&mut *conn).await?;
98+
let root_in_channel = root_created_at.is_some();
9599
if !root_in_channel {
96100
return Ok(ThreadWindow {
97101
rows: vec![],
98102
has_more: false,
99103
next_cursor: None,
100104
root_in_channel,
105+
root_created_at,
101106
});
102107
}
103108
// Order metadata before event lookups. With stale statistics a root-wide
@@ -176,6 +181,7 @@ async fn select_window(
176181
has_more,
177182
next_cursor,
178183
root_in_channel,
184+
root_created_at,
179185
})
180186
}
181187

@@ -288,6 +294,9 @@ pub struct AuxQuery<'a> {
288294
pub accessible: &'a [Uuid],
289295
/// Last raw auxiliary scan position, not last delivered event.
290296
pub cursor: Option<Cursor>,
297+
/// Optional lower `created_at` bound, so the `#e` probes can prune older
298+
/// `events` partitions. `None` scans the community's whole history.
299+
pub since: Option<DateTime<Utc>>,
291300
}
292301

293302
/// Fixed raw auxiliary page budget (the probe is one extra row).
@@ -373,6 +382,9 @@ async fn select_aux(
373382
)
374383
.push_bind(query.targets)
375384
.push("))");
385+
if let Some(since) = query.since {
386+
q.push(" AND created_at >= ").push_bind(since);
387+
}
376388
if let Some(cursor) = &query.cursor {
377389
let (ts, id) = cursor_key(cursor)?;
378390
q.push(" AND (created_at < ")

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@ async fn thread_aux_tombstone_ids_and_raw_cursor_survive_damaged_payload() {
340340
kinds: &[40003],
341341
accessible: &accessible,
342342
cursor: None,
343+
since: None,
343344
};
344345
let mut session = ReadSession {
345346
inner: ReadSessionInner::Writer(db.pool.clone()),
@@ -379,6 +380,7 @@ async fn thread_aux_query_budget_fails_on_65th_real_scan() {
379380
kinds: &[7],
380381
accessible: &[channel],
381382
cursor: None,
383+
since: None,
382384
};
383385
let mut session = ReadSession {
384386
inner: ReadSessionInner::Writer(db.pool.clone()),
@@ -427,6 +429,7 @@ async fn thread_aux_byte_budget_stops_consumption_and_survives_retry() {
427429
kinds: &[40003],
428430
accessible: &[channel],
429431
cursor: None,
432+
since: None,
430433
};
431434
let mut session = ReadSession {
432435
inner: ReadSessionInner::Writer(db.pool.clone()),
@@ -538,6 +541,7 @@ async fn thread_reply_byte_budget_stops_before_collecting_page() {
538541
kinds: &[7],
539542
accessible: &[channel],
540543
cursor: None,
544+
since: None,
541545
},
542546
&mut budget,
543547
)

‎crates/buzz-relay/src/api/bridge.rs‎

Lines changed: 200 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,34 @@ const AUX_PAGE_LIMIT: i64 = buzz_db::DEFAULT_MAX_PAGE_LIMIT;
936936
/// loop forever against a pathological write pattern.
937937
const AUX_MAX_PAGES: usize = 64;
938938

939+
/// How far before the oldest retained window row the aux hops still look.
940+
/// Ingest rejects any event more than 900 s from the relay clock
941+
/// (`MAX_TIMESTAMP_DRIFT_SECS` in `handlers/ingest.rs`), so an aux event can
942+
/// predate its target by at most ~30 min; a day covers that with room for
943+
/// data that reached the store another way. The bound lets the `#e` GIN
944+
/// probes prune older `events` partitions instead of scanning the
945+
/// community's whole history.
946+
const WINDOW_AUX_SINCE_MARGIN_SECS: i64 = 24 * 60 * 60;
947+
948+
/// Lower `created_at` bound for both window aux hops: the oldest aux target
949+
/// (Unix seconds) minus [`WINDOW_AUX_SINCE_MARGIN_SECS`]. Every aux event, in
950+
/// either hop, really happened after the row it chains back to, so its
951+
/// timestamp is at most twice the ingest drift before that row's; the same
952+
/// bound covers both hops.
953+
/// `None` when there are no targets (no hops run).
954+
fn window_aux_since(
955+
target_created_at: impl IntoIterator<Item = i64>,
956+
) -> Option<chrono::DateTime<chrono::Utc>> {
957+
let oldest = target_created_at.into_iter().min()?;
958+
let since = oldest.saturating_sub(WINDOW_AUX_SINCE_MARGIN_SECS).max(0);
959+
chrono::DateTime::from_timestamp(since, 0)
960+
}
961+
962+
/// Unix seconds of a stored event, for [`window_aux_since`].
963+
fn stored_event_secs(event: &buzz_core::StoredEvent) -> i64 {
964+
i64::try_from(event.event.created_at.as_secs()).unwrap_or(i64::MAX)
965+
}
966+
939967
fn build_aux_query(
940968
community: buzz_core::CommunityId,
941969
target_ids: Vec<String>,
@@ -1109,9 +1137,16 @@ async fn handle_channel_window_filter(
11091137
let mut seen_aux: std::collections::HashSet<nostr::EventId> =
11101138
std::collections::HashSet::new();
11111139
let mut hop_ids = row_ids_hex.clone();
1140+
let aux_since = window_aux_since(
1141+
window
1142+
.rows
1143+
.iter()
1144+
.map(|row| stored_event_secs(&row.stored_event)),
1145+
);
11121146
for hop_kinds in [&WINDOW_AUX_KINDS[..], &WINDOW_AUX_DELETE_KINDS[..]] {
1113-
let aux_query =
1147+
let mut aux_query =
11141148
build_aux_query(tenant.community(), std::mem::take(&mut hop_ids), hop_kinds);
1149+
aux_query.since = aux_since;
11151150
let aux_events = query_all_pages(
11161151
aux_query,
11171152
AUX_PAGE_LIMIT,
@@ -5617,6 +5652,170 @@ pub(crate) mod postgres_tests {
56175652
);
56185653
}
56195654

5655+
/// The channel-window aux closure reads both hops from one day before the
5656+
/// oldest retained row, not before the newest row or the wall clock. The
5657+
/// window holds a row from now and one from 40 days ago; aux on the old
5658+
/// row inside that bound still comes back, on the two-row page and on the
5659+
/// cursor page holding only the old row, and aux dated more than a day
5660+
/// before the old row is not read. Mutations: drop `aux_query.since`, or
5661+
/// widen the margin by more than a minute → the out-of-bound events return
5662+
/// → RED; anchor on the newest row (`.max()`) or on `Utc::now()` → the
5663+
/// in-bound events vanish → RED.
5664+
#[tokio::test]
5665+
#[ignore = "requires Postgres and Redis"]
5666+
async fn channel_window_aux_hops_read_from_a_day_before_the_oldest_row() {
5667+
use buzz_core::kind::{KIND_DELETION, KIND_REACTION};
5668+
use buzz_db::channel::{ChannelType, ChannelVisibility};
5669+
5670+
let state = bridge_handler_test_state()
5671+
.await
5672+
.expect("local Postgres and Redis");
5673+
let host = format!("window-aux-bound-{}.local", uuid::Uuid::new_v4().simple());
5674+
let community = state
5675+
.db
5676+
.ensure_configured_community(&host)
5677+
.await
5678+
.expect("ensure community");
5679+
let author = Keys::generate();
5680+
let (channel, _) = state
5681+
.db
5682+
.create_channel_with_id(
5683+
community.id,
5684+
uuid::Uuid::new_v4(),
5685+
&format!("window-aux-bound-{}", uuid::Uuid::new_v4().simple()),
5686+
ChannelType::Stream,
5687+
ChannelVisibility::Open,
5688+
None,
5689+
author.public_key().to_bytes().as_slice(),
5690+
None,
5691+
)
5692+
.await
5693+
.expect("create channel");
5694+
let ch = channel.id.to_string();
5695+
5696+
// Ingest's ±900 s clock check and the store's channel-event floor
5697+
// both refuse backdated events, so the backdated aux events are
5698+
// stored channel-less, as a NIP-09 deletion may be; the aux hops are
5699+
// community-wide `#e` lookups and still find them. The old row must
5700+
// be in the channel, so it is written as historical data would be.
5701+
let now = chrono::Utc::now().timestamp() as u64;
5702+
let day = 86_400;
5703+
let build = |kind: u32, at: u64, target: Option<&nostr::EventId>| {
5704+
let mut builder = EventBuilder::new(Kind::Custom(kind as u16), "+")
5705+
.tag(Tag::parse(["h", ch.as_str()]).expect("h"));
5706+
if let Some(target) = target {
5707+
builder = builder.tag(Tag::parse(["e", &target.to_hex()]).expect("e"));
5708+
}
5709+
builder
5710+
.custom_created_at(nostr::Timestamp::from(at))
5711+
.sign_with_keys(&author)
5712+
.expect("sign")
5713+
};
5714+
let store = |kind: u32, at: u64, target: &nostr::EventId| {
5715+
let event = build(kind, at, Some(target));
5716+
let state = state.clone();
5717+
async move {
5718+
state
5719+
.db
5720+
.insert_event(community.id, &event, None)
5721+
.await
5722+
.expect("insert");
5723+
event.id
5724+
}
5725+
};
5726+
let new_row = build(9, now, None);
5727+
state
5728+
.db
5729+
.insert_event(community.id, &new_row, Some(channel.id))
5730+
.await
5731+
.expect("insert new row");
5732+
let old_at = now - 40 * day;
5733+
let old_row = build(9, old_at, None);
5734+
let pool = sqlx::PgPool::connect(&crate::test_support::database_url())
5735+
.await
5736+
.expect("pool");
5737+
sqlx::query(
5738+
"INSERT INTO events (community_id,id,pubkey,created_at,kind,tags,content,sig,received_at,channel_id) \
5739+
VALUES ($1,$2,$3,to_timestamp($4),$5,$6,$7,$8,now(),$9)",
5740+
)
5741+
.bind(community.id.as_uuid())
5742+
.bind(old_row.id.to_bytes().to_vec())
5743+
.bind(old_row.pubkey.to_bytes().to_vec())
5744+
.bind(old_at as f64)
5745+
.bind(9_i32)
5746+
.bind(serde_json::to_value(&old_row.tags).expect("tags"))
5747+
.bind(&old_row.content)
5748+
.bind(old_row.sig.serialize().to_vec())
5749+
.bind(channel.id)
5750+
.execute(&pool)
5751+
.await
5752+
.expect("insert old row");
5753+
let reaction_in = store(KIND_REACTION, old_at - day + 60, &old_row.id).await;
5754+
let reaction_out = store(KIND_REACTION, old_at - day - 60, &old_row.id).await;
5755+
let delete_in = store(KIND_DELETION, old_at - day + 120, &reaction_in).await;
5756+
let delete_out = store(KIND_DELETION, old_at - day - 120, &reaction_in).await;
5757+
5758+
let query = |filter: Value| {
5759+
let state = state.clone();
5760+
let host = host.clone();
5761+
let pubkey = author.public_key().to_hex();
5762+
async move {
5763+
let body = serde_json::to_vec(&[filter]).expect("json");
5764+
let (status, bytes) = post_query(state, &host, &pubkey, &body).await;
5765+
assert_eq!(
5766+
status,
5767+
StatusCode::OK,
5768+
"{}",
5769+
String::from_utf8_lossy(&bytes)
5770+
);
5771+
serde_json::from_slice::<Vec<Value>>(&bytes).expect("event array")
5772+
}
5773+
};
5774+
let assert_old_row_aux = |events: &[Value], page: &str| {
5775+
let has = |id: &nostr::EventId| {
5776+
events
5777+
.iter()
5778+
.any(|e| e["id"].as_str() == Some(id.to_hex().as_str()))
5779+
};
5780+
assert!(has(&old_row.id), "{page}: old row: {events:?}");
5781+
assert!(
5782+
has(&reaction_in),
5783+
"{page}: hop 1 inside the bound: {events:?}"
5784+
);
5785+
assert!(
5786+
has(&delete_in),
5787+
"{page}: hop 2 inside the bound: {events:?}"
5788+
);
5789+
assert!(
5790+
!has(&reaction_out),
5791+
"{page}: hop 1 past the bound: {events:?}"
5792+
);
5793+
assert!(
5794+
!has(&delete_out),
5795+
"{page}: hop 2 past the bound: {events:?}"
5796+
);
5797+
};
5798+
5799+
let filter = serde_json::json!({
5800+
"kinds": [9], "#h": [&ch], "top_level": true, "include_aux": true,
5801+
});
5802+
assert_old_row_aux(&query(filter.clone()).await, "two-row page");
5803+
5804+
let mut paged = filter;
5805+
paged["limit"] = serde_json::json!(1);
5806+
let first = query(paged.clone()).await;
5807+
let bounds: Value = first
5808+
.iter()
5809+
.find(|e| e["kind"] == 39006)
5810+
.and_then(|e| e["content"].as_str())
5811+
.map(|content| serde_json::from_str(content).expect("bounds content"))
5812+
.expect("window bounds");
5813+
assert_eq!(bounds["has_more"], true, "{first:?}");
5814+
paged["until"] = bounds["next_cursor"]["created_at"].clone();
5815+
paged["before_id"] = bounds["next_cursor"]["id"].clone();
5816+
assert_old_row_aux(&query(paged).await, "cursor page");
5817+
}
5818+
56205819
// ──────────────────────────────────────────────────────────────────────────
56215820
// Log-capture helpers and attribution-invariant tests
56225821
//

‎crates/buzz-relay/src/api/bridge/thread_window.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,15 @@ async fn query(
203203
if request.include_aux {
204204
let row_count = events.len();
205205
let original_targets = targets;
206+
// The root is always a target and the rows are replies, so the root
207+
// anchors the bound (see `window_aux_since`).
208+
let aux_since = super::window_aux_since(
209+
window
210+
.root_created_at
211+
.map(|at| at.timestamp())
212+
.into_iter()
213+
.chain(window.rows.iter().map(super::stored_event_secs)),
214+
);
206215
// A writer retry at an older aux cursor alone would miss newer writer
207216
// edits. Restart both closure hops once after permanent degradation;
208217
// preserve the request ledger/deadline, never reset work allowances.
@@ -219,6 +228,7 @@ async fn query(
219228
kinds,
220229
accessible,
221230
cursor: None,
231+
since: aux_since,
222232
};
223233
loop {
224234
let was_replica = session.is_replica();

0 commit comments

Comments
 (0)