## 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>
6.7 KiB
Bridge /query Extension: Channel Window
Normative spec: NIP-CW is the canonical, standalone specification of the channel window (kinds 39005/39006, filter extension, cursor and trust semantics). This document remains as the ratified engineering contract and internal design record; where wording differs, NIP-CW governs.
Status: frozen contract v2 (2026-07-03) — GUI read-model overhaul.
Reviewed by: Mari (relay ground truth), Wren (client core), Quinn (spec
guardian), Perci (NIP landscape). Ratified in
#buzz-gui-formal-relay-interaction-spec, thread a7c68013.
The channel window is how Buzz clients page a channel timeline by
top-level rows instead of raw events. It is a raw-filter extension on
the existing HTTP bridge POST /query — the same extension family as
before_id and thread_cursor. There is no new endpoint, and the wire
carries only signed nostr events.
Vanilla NIP-01 cannot express "messages with no reply e-tag" (filters have
no negation), which is why generic nostr clients page raw events and
reassemble threads client-side. This relay computes thread_metadata
(depth, root, reply counts) at ingest, so it can serve the top-level view
directly. The WS REQ path ignores all fields below via nostr::Filter's
unknown-field behavior — generic clients degrade gracefully to a normal
full-event query; they never see a wrong-but-plausible timeline.
Request
A standard bridge filter plus extension fields:
{
"kinds": [9],
"#h": ["<channel-uuid>"],
"limit": 50,
"top_level": true,
"include_summaries": true,
"include_aux": true,
"until": 1751500000,
"before_id": "<64-hex event id>"
}
top_level: true— routes this filter to the top-level SQL view. Requires exactly one#hchannel the caller can access.limit— row budget. Counts row events only; summaries, aux, and bounds overlays never consume it.until+before_id— the composite request cursor(created_at, id)of the last retained row from the previous page. Both or neither.top_levelwithuntilbut nobefore_idis rejected (400): the window path has no timestamp-only fallback, ever. Neither = head request.include_summaries/include_aux— opt-in overlay/closure appends.
page/OFFSET is not honored on the window path.
Top-level predicate
A row is top-level iff depth IS NULL OR depth = 0 OR (depth = 1 AND broadcast = true) in thread_metadata (v1 ruling: NULL — an event
ingested before thread metadata existed — counts as top-level; the harness
legacyReply scenario decides whether a backfill migration is needed).
Deleted rows (deleted_at IS NOT NULL) are excluded before the limit.
Ordering and cursor
Rows are ordered (created_at DESC, id ASC) — the same composite every
other read path uses. The next-page cursor is the (created_at, id) of the
last retained row; the server echoes it in the 39006 bounds overlay
as next_cursor. Keyset comparison is
created_at < $ts OR (created_at = $ts AND id > $id); dense seconds
paginate without loss or duplication by construction.
has_more is a server fact: the relay probes limit + 1 rows after
all predicates (access, deletion, top-level, kinds), returns at most
limit, and reports the probe result in 39006. The sentinel row never
reaches the wire, and no closure is computed for it. Clients must not
infer exhaustion from row count (rows < limit does not imply anything on
an exact-multiple final page) — 39006.has_more is the only authority.
Response
The existing flat bridge shape: a JSON array of signed nostr events. Clients partition by kind before any cursor math:
- Rows — the top-level events, in keyset order.
- Aux closure (
include_aux) — reactions (7), deletions (5, 9005), and edits (40003) targeting the retained rows by#e, plus deletions targeting those aux events (the transitive second hop, e.g. a delete-of-a-reaction). One round trip; no client#efan-out. Each hop is drained server-side across the DB page clamp, so the closure is 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 oldereventspartitions; ingest's ±15 min clock check keeps aux events within that margin of their targets. - Thread summaries (
include_summaries) — one relay-signedkind:39005per row that has replies. - Window bounds — exactly one relay-signed
kind:39006per window response.
kind:39005 — thread summary overlay
- tags:
["e", <root-id>],["d", <root-id>],["h", <channel-id>] - content:
{"reply_count":n,"descendant_count":n,"last_reply_at":ts|null,"participants":["<hex-pubkey>",...]}(participants: up to 10 from the newest 1000 replies, deleted ones included, most recent first) - Signed by the relay keypair. Synthesized at query time, never stored.
Clients treat it as replace-by-target metadata keyed by the
e/dtag (thedtag gives parameterized-replaceable semantics natively); it is never a row, never a cursor input, never durable timeline history.
kind:39006 — window bounds overlay
- tags:
["d", "<channel_id>:<request-cursor-or-head>"],["h", "<channel_id>"] - content:
{"has_more": bool, "next_cursor": {"created_at": ts, "id": "<hex>"} | null} next_cursor = null ⇔ has_more = false.d-tag suffix serialization (canonical):headfor a head request, else<created_at>:<event_id>— decimal unix seconds, then the full 64-char lowercase hex id, colon-delimited. Clients must verify the suffix equals the cursor they sent and reject the overlay on mismatch.- Reserved field:
oldest_retained(retention gap), added without a wire break if needed. - Same overlay rules as 39005: relay-signed, query-time, never stored, never a row or cursor input.
Both kinds are relay-only: client submission is rejected at ingest.
Client obligations (frozen)
- Pages are immutable authoritative history chained cursor→cursor; live events land in a separate overlay, never spliced into pages.
- Reconnect refetches page 0 and re-arms the live subscription
(
since: now); deeper pages need no repair path. - Replies never enter the channel timeline; the thread panel uses the
existing
thread_cursorsurface (#1418). Thread filters may opt intoinclude_auxto append the same authorized two-hop reactions, edits, and deletions closure as a channel-window response.
Siblings
before_id (requires until), thread_cursor/thread_cursor_id,
depth_limit, feed_types — see bridge.rs. All are bridge-only raw
filter extensions invisible to vanilla relays and clients.