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 42dc2a8c5 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>
This commit is contained in:
Bradley Axen
2026-11-23 13:22:27 -08:00
committed by GitHub
parent 8cc7e94392
commit 5884965a47
9 changed files with 330 additions and 14 deletions

View File

@@ -89,7 +89,11 @@ Clients **partition by kind before any cursor math**:
deletions targeting those aux events (the transitive second hop, e.g.
a delete-of-a-reaction). One round trip; no client `#e` fan-out. Each
hop is drained server-side across the DB page clamp, so the closure is
complete rather than newest-1000.
complete rather than newest-1000. Both hops read only events dated at
most one day before the oldest retained row
(`WINDOW_AUX_SINCE_MARGIN_SECS`), so they can skip older `events`
partitions; ingest's ±15 min clock check keeps aux events within that
margin of their targets.
3. **Thread summaries** (`include_summaries`) — one relay-signed
`kind:39005` per row that has replies.
4. **Window bounds** — exactly one relay-signed `kind:39006` per window

View File

@@ -101,7 +101,7 @@ For a valid window filter on an accessible channel (§Channel-mode Access Scopin
1. **Select rows.** From the target channel, take events that are top-level (§Channel-mode Top-level Classification), not deleted, and matching `kinds` if present, in the total order `created_at DESC, id ASC` (`id` compared bytewise). With a cursor `(ts, id)`, retain only events where `created_at < ts OR (created_at = ts AND id > id)`.
2. **Probe exhaustion.** Evaluate the query with an internal budget of `limit + 1` rows *after all predicates*. If `limit + 1` rows match, `has_more = true` and the sentinel row is discarded — it MUST NOT appear on the wire, in overlays, or in the aux closure. Otherwise `has_more = false`.
3. **Derive the next cursor.** If `has_more`, `next_cursor` is the **scan position**: the composite cursor of the last retained candidate, captured *before* any serving-time reconstruction or filtering of individual events. Otherwise `next_cursor = null`. The invariant `next_cursor = null ⇔ has_more = false` MUST hold. Because it is a scan position, `next_cursor` MAY reference an event that does not appear in the response (e.g. one skipped by the relay as unreconstructable); it is authoritative regardless, and deriving it from delivered rows instead would stall pagination on every skipped event.
4. **Append the aux closure** (if `include_aux` and at least one row): two hops of events referencing the rows by `e` tag. Hop 1: reactions (`kind:7`), deletions (`kind:5`, `kind:9005`), and edits (Buzz `kind:40003`) whose `e` tag is a row id. Hop 2: deletions whose `e` tag is a hop-1 event id (a delete-of-a-reaction). Each event appears at most once; access-scoped events the requester cannot read are omitted. Relays MAY cap each hop (Buzz: 1000 events per hop).
4. **Append the aux closure** (if `include_aux` and at least one row): two hops of events referencing the rows by `e` tag. Hop 1: reactions (`kind:7`), deletions (`kind:5`, `kind:9005`), and edits (Buzz `kind:40003`) whose `e` tag is a row id. Hop 2: deletions whose `e` tag is a hop-1 event id (a delete-of-a-reaction). Each event appears at most once; access-scoped events the requester cannot read are omitted. Relays MAY cap each hop (Buzz: 1000 events per hop). Relays MAY also omit, from both hops, events whose `created_at` is more than a fixed margin before the oldest row's (Buzz: one day), so the lookups need not scan the channel's whole history; the margin MUST exceed twice the relay's accepted clock drift, since a target and its aux event may each be stamped up to that drift away from real time in opposite directions.
5. **Append thread summaries** (if `include_summaries`): one `kind:39005` per row that has at least one reply. Rows without replies get none.
6. **Append window bounds**: exactly one `kind:39006` per served window response, always — including empty and exhausted pages.
@@ -299,6 +299,8 @@ For an authorized request the relay MUST:
original signatures, deduplicate by event ID, and apply access control to
every event. A target reference requires an `e` tag with the target ID
in its second position; containing both strings elsewhere is insufficient.
As in channel mode, relays MAY omit auxiliary events dated more than a fixed
margin before the oldest target, which always includes the root.
5. Append one bounds event to each served page, including empty and exhausted
pages. Refresh access for the **entire query batch** before releasing any
events or bounds. If the reader's accessible-channel set changed while any