From 73d76b314a341d1ed5f29456f331721d511ba07a Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 01:25:31 -0500 Subject: [PATCH] feat(relay): read NIP-CW windows oldest first Add `direction: "newer"` to both NIP-CW window modes. A newer window pages from the oldest row in `created_at ASC, id DESC` order, continued by `after`/`after_id`; the other direction's cursor fields are rejected. - Thread mode scans idx_thread_metadata_window backward (no migration), binds the direction and cursor into the tw:1 hash, and accepts `root_aux: false` to leave the root's aux out of the closure. Default requests keep their exact binding. - Channel mode walks the monthly partitions forward two months at a time (`oldest_for`, `Forward::advance`), mirroring the recent-first split, and stops at the first window that fills the page. The head page starts at the month the channel was created, less the write path's created_at tolerance (`channel_floor`), so it never plans the older partitions. Newer 39006 bounds carry a `newer:` d-tag prefix and a `direction` field; older bounds are byte-identical. - Newer pages route to the writer: no cursor bounds the rows they read. - NIP-11 advertises `buzz-window-newer`; NIP-CW and the bridge channel window doc describe both directions. Made with human guidance from the maintainer driving this work. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-core/src/thread_window.rs | 174 ++++- crates/buzz-db/src/runtime/tests.rs | 115 +++- .../tests/thread_window_postgres_tests.rs | 15 + crates/buzz-db/src/store/recent_pass.rs | 377 ++++++++++- crates/buzz-db/src/store/thread.rs | 607 +++++++++++++++--- crates/buzz-db/src/store/thread_window.rs | 59 +- .../src/store/thread_window/postgres_tests.rs | 33 +- crates/buzz-relay/src/api/bridge.rs | 98 ++- .../src/api/bridge/thread_window.rs | 8 +- .../bridge/thread_window/postgres_tests.rs | 182 +++++- crates/buzz-relay/src/nip11.rs | 7 +- docs/bridge-channel-window.md | 19 + docs/nips/NIP-CW.md | 69 +- 13 files changed, 1554 insertions(+), 209 deletions(-) diff --git a/crates/buzz-core/src/thread_window.rs b/crates/buzz-core/src/thread_window.rs index c7526d245ec..75da0c08469 100644 --- a/crates/buzz-core/src/thread_window.rs +++ b/crates/buzz-core/src/thread_window.rs @@ -13,7 +13,7 @@ pub const MAX_LIMIT: u32 = 200; /// never reply-budget candidates, even if they have thread metadata. pub const ROW_KINDS: [u32; 4] = [9, 40002, 45001, 45003]; -/// A position in `(created_at DESC, id ASC)` order. +/// A position in a window's keyset order (see [`Direction`]). #[derive(Clone, Debug, PartialEq, Eq, Serialize)] pub struct Cursor { /// Nonnegative Unix seconds, representable by PostgreSQL/chrono. @@ -31,6 +31,59 @@ impl Cursor { } } +/// Paging direction of a NIP-CW window, in both channel and thread mode. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Direction { + /// Newest first, `created_at DESC, id ASC`, continued by `until`/`before_id`. + #[default] + Older, + /// Oldest first, `created_at ASC, id DESC`, continued by `after`/`after_id`. + Newer, +} + +impl Direction { + /// Parse the optional `direction` field (absent means `"older"`) and reject + /// the other direction's cursor fields. + pub fn parse(raw: &Value) -> Result { + let direction = match raw.get("direction") { + None => Self::Older, + Some(v) => match v.as_str() { + Some("older") => Self::Older, + Some("newer") => Self::Newer, + _ => return Err("direction must be \"older\" or \"newer\"".into()), + }, + }; + let (ts, id) = match direction { + Self::Older => Self::Newer, + Self::Newer => Self::Older, + } + .cursor_fields(); + match [ts, id].into_iter().find(|key| raw.get(key).is_some()) { + Some(key) => Err(format!( + "{key} conflicts with direction {}", + direction.as_str() + )), + None => Ok(direction), + } + } + + /// The wire name. + pub fn as_str(self) -> &'static str { + match self { + Self::Older => "older", + Self::Newer => "newer", + } + } + + /// The request cursor's timestamp and id field names. + pub fn cursor_fields(self) -> (&'static str, &'static str) { + match self { + Self::Older => ("until", "before_id"), + Self::Newer => ("after", "after_id"), + } + } +} + /// Validated pagination and response-affecting arguments. Construct with /// [`Request::parse`]; the database also validates public inputs defensively. #[derive(Clone, Debug, PartialEq, Eq)] @@ -45,10 +98,14 @@ pub struct Request { pub depth: u32, /// Sorted, deduplicated conversation row kinds. pub kinds: Vec, - /// Request upper bound; absent means newest page. + /// Paging direction. + pub direction: Direction, + /// Request cursor in `direction`; absent means the first page. pub cursor: Option, /// Include root/retained-row edits, reactions and deletion closure. pub include_aux: bool, + /// Include the root in the aux closure's targets. + pub root_aux: bool, } fn event_id(v: &Value) -> Result { @@ -89,9 +146,13 @@ impl Request { "kinds", "limit", "depth_limit", + "direction", "until", "before_id", + "after", + "after_id", "include_aux", + "root_aux", ]; if object.keys().any(|key| !FIELDS.contains(&key.as_str())) { return Err("thread_window: unsupported or conflicting filter field".into()); @@ -123,48 +184,58 @@ impl Request { .collect::, _>>()?; kinds.sort_unstable(); kinds.dedup(); - let cursor = match (raw.get("until"), raw.get("before_id")) { + let direction = Direction::parse(raw).map_err(|e| format!("thread_window: {e}"))?; + let (ts_key, id_key) = direction.cursor_fields(); + let cursor = match (raw.get(ts_key), raw.get(id_key)) { (None, None) => None, (Some(ts), Some(id)) => { let cursor = Cursor { - created_at: ts - .as_i64() - .filter(|n| *n >= 0) - .ok_or("thread_window: until must be nonnegative integer seconds")?, + created_at: ts.as_i64().filter(|n| *n >= 0).ok_or_else(|| { + format!("thread_window: {ts_key} must be nonnegative integer seconds") + })?, id: event_id(id)?, }; cursor.timestamp()?; Some(cursor) } - _ => return Err("thread_window requires both until and before_id, or neither".into()), + _ => { + return Err(format!( + "thread_window requires both {ts_key} and {id_key}, or neither" + )) + } }; - let include_aux = match raw.get("include_aux") { - None => false, + let flag = |key: &str, default: bool| match raw.get(key) { + None => Ok(default), Some(v) => v .as_bool() - .ok_or("thread_window: include_aux must be boolean")?, + .ok_or_else(|| format!("thread_window: {key} must be boolean")), }; + let include_aux = flag("include_aux", false)?; + let root_aux = flag("root_aux", true)?; Ok(Self { channel, root, limit, depth, kinds, + direction, cursor, include_aux, + root_aux, }) } /// Canonical NIP-CW thread-mode v1 request identity. SHA-256 over a compact JSON array /// avoids ambiguous separators and binds all normalized response options. /// The host is server-resolved; the reader is the authenticated lowercase - /// public key. Neither may be taken from filter-supplied fields. + /// public key. Neither may be taken from filter-supplied fields. Default + /// options keep the original array, so existing bindings are unchanged. pub fn binding(&self, resolved_host: &str, reader_hex: &str) -> String { let cursor = self.cursor.as_ref().map(|c| json!([c.created_at, c.id])); - let canonical = json!([ + let mut canonical = json!([ "tw", 1, - "older", + self.direction.as_str(), resolved_host, reader_hex, self.channel.to_string(), @@ -175,6 +246,9 @@ impl Request { cursor, self.include_aux ]); + if let (false, Some(items)) = (self.root_aux, canonical.as_array_mut()) { + items.push(json!("root_aux:false")); + } format!( "tw:1:{}", hex::encode(Sha256::digest(canonical.to_string().as_bytes())) @@ -198,6 +272,11 @@ mod tests { ("depth_limit", json!(101)), ("depth_limit", json!(-1)), ("include_aux", json!("true")), + ("root_aux", json!("false")), + ("direction", json!("up")), + ("direction", json!(null)), + ("after", json!(1)), + ("after_id", json!("ab".repeat(32))), ("thread_cursor", json!(0)), ("threadCursorId", json!(null)), ("top_level", json!(false)), @@ -228,6 +307,35 @@ mod tests { f["before_id"] = json!("a".repeat(64)); assert!(Request::parse(&f).is_err(), "{f}"); } + let mut newer = filter(); + newer["direction"] = json!("newer"); + for (key, value) in [ + ("until", json!(1)), + ("before_id", json!("ab".repeat(32))), + ("after", json!(1)), + ("after_id", json!("ab".repeat(32))), + ] { + let mut f = newer.clone(); + f[key] = value; + assert!(Request::parse(&f).is_err(), "{f}"); + } + for ts in [json!(-1), json!(1.5), json!(null), json!(i64::MAX)] { + let mut f = newer.clone(); + f["after"] = ts; + f["after_id"] = json!("a".repeat(64)); + assert!(Request::parse(&f).is_err(), "{f}"); + } + newer["after"] = json!(7); + newer["after_id"] = json!("AB".repeat(32)); + let request = Request::parse(&newer).unwrap(); + assert_eq!(request.direction, Direction::Newer); + assert_eq!( + request.cursor, + Some(Cursor { + created_at: 7, + id: "ab".repeat(32) + }) + ); } #[test] fn binding_normalizes_defaults_and_binds_every_argument() { @@ -246,12 +354,16 @@ mod tests { explicit["limit"] = json!(50); explicit["depth_limit"] = json!(100); explicit["include_aux"] = json!(false); + explicit["direction"] = json!("older"); + explicit["root_aux"] = json!(true); explicit["#e"] = json!(["AB".repeat(32)]); assert_eq!(expected, binding(&explicit)); for (key, val) in [ ("limit", json!(49)), ("depth_limit", json!(1)), ("include_aux", json!(true)), + ("direction", json!("newer")), + ("root_aux", json!(false)), ("kinds", json!([40002])), ("#e", json!(["cd".repeat(32)])), ("#h", json!([Uuid::new_v4()])), @@ -269,4 +381,38 @@ mod tests { changed["before_id"] = json!("ab".repeat(32)); assert_ne!(expected, binding(&changed)); } + + /// `newer` and `root_aux:false` bind the canonical arrays NIP-CW specifies. + #[test] + fn binding_encodes_direction_cursor_and_root_aux_as_specified() { + let (host, reader, root) = ("relay.example", "ab".repeat(32), "cd".repeat(32)); + let mut f = filter(); + f["#e"] = json!([root]); + f["direction"] = json!("newer"); + f["after"] = json!(5); + f["after_id"] = json!("ef".repeat(32)); + f["root_aux"] = json!(false); + let expected = json!([ + "tw", + 1, + "newer", + host, + reader, + Uuid::nil().to_string(), + root, + 50, + 100, + [9], + [5, "ef".repeat(32)], + false, + "root_aux:false" + ]); + assert_eq!( + Request::parse(&f).unwrap().binding(host, &reader), + format!( + "tw:1:{}", + hex::encode(Sha256::digest(expected.to_string().as_bytes())) + ) + ); + } } diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index 77c209eec32..0593581d236 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -1055,6 +1055,34 @@ async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { ], "cursor page must be served by the replica" ); + + // Newer cursor page → writer: it reads up to the newest row, which no + // cursor bound proves, so it sees `fresh` and never `marker`. + let (newer, session) = db + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Newer, + Some(( + chrono::DateTime::from_timestamp(base as i64 + 10, 0).unwrap(), + m2.id.as_bytes().to_vec(), + )), + None, + ) + .await + .expect("newer window"); + assert!( + !session.is_replica(), + "a newer page must not take the covered arm" + ); + let newer_contents: Vec = newer + .rows + .iter() + .map(|r| r.stored_event.event.content.clone()) + .collect(); + assert_eq!(newer_contents, ["m3", "fresh-writer-only"]); + assert!(!newer.has_more); } /// Fail-closed on a mid-request replica failure (Dawn, review of @@ -1244,7 +1272,14 @@ async fn read_session_degrades_to_writer_when_replica_connection_dies() { .expect("head window"); let cursor = head.next_cursor.expect("has_more implies next_cursor"); let (_window, mut session) = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor), + None, + ) .await .expect("routed cursor window"); assert!( @@ -1324,7 +1359,14 @@ async fn history_permit_follows_the_read_session_and_a_full_gate_rejects() { .expect("head window"); let cursor = head.next_cursor.expect("has_more implies next_cursor"); let (_window, session) = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor.clone()), + None, + ) .await .expect("routed cursor window"); assert!(session.is_replica(), "fixture must route to the replica"); @@ -1349,8 +1391,15 @@ async fn history_permit_follows_the_read_session_and_a_full_gate_rejects() { let started = Instant::now(); let rejected = { let _guard = metrics::set_default_local_recorder(&recorder); - db.get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) - .await + db.get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor.clone()), + None, + ) + .await } .err() .expect("a full gate must reject the history read"); @@ -1388,7 +1437,14 @@ async fn history_permit_follows_the_read_session_and_a_full_gate_rejects() { drop(session); assert_eq!(db.history_reads.available(), 1); let (_window, session) = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor.clone()), + None, + ) .await .expect("a released permit admits the next read"); assert!(session.is_replica()); @@ -1399,12 +1455,26 @@ async fn history_permit_follows_the_read_session_and_a_full_gate_rejects() { // An operator lowering the cap at runtime holds new reads to the new // limit while one is in flight, and raising it readmits them. let (_window, held) = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor.clone()), + None, + ) .await .expect("routed cursor window"); assert_eq!(db.history_read_gate().set_limit(1), 1); let rejected = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor.clone()), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor.clone()), + None, + ) .await .err() .expect("a lowered cap must reject the next history read"); @@ -1414,7 +1484,14 @@ async fn history_permit_follows_the_read_session_and_a_full_gate_rejects() { ); assert_eq!(db.history_read_gate().set_limit(cap), cap); let (_window, second) = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor), + None, + ) .await .expect("a raised cap admits the next read"); drop((held, second)); @@ -1463,7 +1540,14 @@ async fn routed_request_holds_one_snapshot_across_page_and_aux() { // Route the cursor page to the replica and HOLD the session. let (window, mut session) = db - .get_channel_window_with_session(cid, channel, 10, Some(cursor), None) + .get_channel_window_with_session( + cid, + channel, + 10, + buzz_core::thread_window::Direction::Older, + Some(cursor), + None, + ) .await .expect("routed cursor window"); assert!( @@ -3428,9 +3512,16 @@ async fn replica_statement_cancel_propagates_without_writer_rerun() { "get_thread_replies", ); cancelled( - db.get_channel_window_with_session(fx.cid, fx.channel, 10, None, None) - .await - .map(drop), + db.get_channel_window_with_session( + fx.cid, + fx.channel, + 10, + buzz_core::thread_window::Direction::Older, + None, + None, + ) + .await + .map(drop), "get_channel_window_with_session", ); cancelled( diff --git a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs index ac31f6043f0..c6a8a118f70 100644 --- a/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs +++ b/crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs @@ -66,6 +66,21 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { assert!(!session.is_replica()); assert_eq!(head.rows[0].event.id, middle.id); drop(session); + // So does a newer page: it reads up to the newest reply, which no cursor proves. + let newer = Request::parse(&serde_json::json!({"thread_window":true,"#h":[channel], + "#e":[root.id.to_hex()],"kinds":[9],"direction":"newer", + "after":base,"after_id":"ff".repeat(32)})) + .unwrap(); + let (page, session) = db + .get_thread_window_with_session(community, &newer, &mut ScanBudget::default()) + .await + .unwrap(); + assert!(!session.is_replica()); + assert_eq!( + page.rows.iter().map(|e| e.event.id).collect::>(), + [old.id, middle.id] + ); + drop(session); // Complete the reply fixture, then lag *recent* edits and channel-less // deletions. Coverage of old replies is not a freshness proof for aux. diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs index a4dd5d2ef33..f6b86d26460 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -32,10 +32,29 @@ //! The bounds are SQL literals, so Postgres prunes when it plans the //! statement, cached generic plans included. They change about once a month, //! so the prepared-statement cache keeps one statement per pass and shape. +//! +//! An oldest-first page (`ORDER BY created_at ASC … LIMIT n`) is the mirror +//! image ([`oldest_for`], [`Forward::advance`]), and it never reads more +//! partitions than it needs. It walks fixed two-month windows forward from a +//! literal floor, the start of the month of the read's earliest possible row, +//! and stops at the first window that completes the page. A regular-kind read +//! stops at the same ceiling; any other read ends with one open window. The +//! earliest possible row is the cursor after the first page. The first page +//! has no cursor, so a channel read uses [`channel_floor`]. A read with +//! neither plans every partition below the ceiling. +//! +//! The walk locks one more partition set per window it reads, and the locks +//! stay until the read's transaction ends, so a read that must reach the +//! newest rows (a channel with fewer rows than the page) still locks every +//! partition from its floor on. The floor follows the channel's creation +//! month and the cursor's month, so the cache keeps one statement per +//! window, shape and month read. use buzz_core::kind::{is_parameterized_replaceable, is_replaceable}; use chrono::{DateTime, Datelike, Duration, TimeZone, Utc}; +use crate::replica_fence::CREATED_AT_FLOOR_SECS; + /// How far ahead of a relay's clock a regular-kind row's `created_at` can be, /// with margin. /// @@ -65,6 +84,57 @@ pub(crate) struct Split { pub(crate) older: bool, } +/// Months one window of an oldest-first walk covers. +const WINDOW_MONTHS: i32 = 2; + +/// One window of an oldest-first page read: see the module docs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Forward { + /// The window reads at or above it. `None` for a read with no known + /// earliest row, which is one window. + pub(crate) from: Option>, + /// The window reads below it. `None` when the window is open ended. + pub(crate) to: Option>, + /// Where the walk of fixed windows ends: [`ceiling_at`] at the read's + /// `now`. + horizon: DateTime, + /// Whether no row of the read sits at or above the horizon (every kind + /// is regular): the walk stops there. Otherwise one open window follows. + closed: bool, +} + +impl Forward { + /// The window starting at `from`, which ends [`WINDOW_MONTHS`] later, at + /// the horizon, or never, whichever comes first. + fn from(from: Option>, horizon: DateTime, closed: bool) -> Self { + let to = match from { + None => closed.then_some(horizon), + Some(from) => { + let to = month_start(from, WINDOW_MONTHS); + if to < horizon { + Some(to) + } else { + closed.then_some(horizon) + } + } + }; + Forward { + from, + to, + horizon, + closed, + } + } + + /// The window that follows this one, or `None` when this one reached the + /// end of the read: it is open ended, or it ended at the horizon of a + /// closed read. + pub(crate) fn advance(self) -> Option { + let to = self.to.filter(|to| *to < self.horizon)?; + Some(Forward::from(Some(to), self.horizon, self.closed)) + } +} + /// The `created_at` range one pass of a page read covers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Range { @@ -74,6 +144,8 @@ pub(crate) enum Range { Recent(Split), /// `created_at < floor`. Older(DateTime), + /// One window of an oldest-first walk. + Forward(Forward), } impl Range { @@ -84,23 +156,28 @@ impl Range { /// literal while it plans, including in a cached generic plan, while a /// generic plan with a bind parameter prunes only at execution, after it /// has locked every partition. The text is chrono's fixed-format - /// rendering of a UTC timestamp, digits and separators only, so it - /// carries no caller input. + /// rendering of a UTC month start, digits and separators only. A forward + /// window derives from the caller's cursor or channel, clamped to the + /// ceiling at `now` (see [`oldest_for`]), so it is still a four-digit-year + /// month. pub(crate) fn predicate(self, column: &str) -> Option { - let bound = |op: &str, at: DateTime| { - format!( - " AND {column} {op} '{}'::timestamptz", - at.format("%Y-%m-%dT%H:%M:%SZ") - ) + let (from, to) = match self { + Range::All => (None, None), + Range::Recent(split) => (Some(split.floor), split.ceiling), + Range::Older(floor) => (None, Some(floor)), + Range::Forward(window) => (window.from, window.to), }; - match self { - Range::All => None, - Range::Recent(split) => { - let ceiling = split.ceiling.map(|c| bound("<", c)); - Some(bound(">=", split.floor) + ceiling.as_deref().unwrap_or("")) - } - Range::Older(floor) => Some(bound("<", floor)), - } + let bound = |op: &str, at: Option>| { + at.map(|at| { + format!( + " AND {column} {op} '{}'::timestamptz", + at.format("%Y-%m-%dT%H:%M:%SZ") + ) + }) + .unwrap_or_default() + }; + let predicate = bound(">=", from) + &bound("<", to); + (!predicate.is_empty()).then_some(predicate) } } @@ -149,14 +226,10 @@ pub(crate) fn split_for( until: Option>, ) -> Option { let floor = floor_at(now); - // Replaceable and addressable rows are latest-state records, often months - // old, and few per author. - let latest_state = |k: i32| { - u32::try_from(k).is_ok_and(|k| is_replaceable(k) || is_parameterized_replaceable(k)) - }; - let kinds = kinds.filter(|ks| !ks.is_empty()); - let latest_state_only = kinds.is_some_and(|ks| ks.iter().all(|&k| latest_state(k))); - let regular_only = kinds.is_some_and(|ks| !ks.iter().any(|&k| latest_state(k))); + let latest_state_only = kinds + .filter(|ks| !ks.is_empty()) + .is_some_and(|ks| ks.iter().all(|&k| latest_state(k))); + let regular_only = regular_only(kinds); let since_prunes = since.is_some_and(|s| s >= floor); let until_before_floor = until.is_some_and(|u| u < floor); let split = |older| Split { @@ -170,15 +243,57 @@ pub(crate) fn split_for( (!latest_state_only && !until_before_floor).then(|| split(true)) } +/// Replaceable and addressable rows are latest-state records, often months +/// old, and few per author. +fn latest_state(kind: i32) -> bool { + u32::try_from(kind).is_ok_and(|k| is_replaceable(k) || is_parameterized_replaceable(k)) +} + +/// Whether every one of a read's kinds is regular, so its rows lie below +/// [`ceiling_at`]. +fn regular_only(kinds: Option<&[i32]>) -> bool { + kinds + .filter(|ks| !ks.is_empty()) + .is_some_and(|ks| !ks.iter().any(|&k| latest_state(k))) +} + +/// The channel's earliest possible row: the instant it was created, less the +/// floor the write path tolerates ([`CREATED_AT_FLOOR_SECS`]). Every write of a +/// channel row checks `created_at` against the database clock, and the channel +/// exists before its first row, so no row of it is older. Its month starts the +/// walk of a channel's first oldest-first page. +pub(crate) fn channel_floor(channel_created_at: DateTime) -> DateTime { + channel_created_at - Duration::seconds(CREATED_AT_FLOOR_SECS) +} + +/// The first window of an oldest-first page read. `earliest` is a lower bound +/// on the read's rows: the cursor of a later page, else [`channel_floor`] +/// (`None`: the read has no bound and its first window is unbounded below). +/// `kinds` are the read's kinds (`None`: any). +pub(crate) fn oldest_for( + now: DateTime, + kinds: Option<&[i32]>, + earliest: Option>, +) -> Forward { + let horizon = ceiling_at(now); + // Clamped so a far-future bound keeps a literal Postgres accepts; any + // floor at or below the bound is exact. + let floor = earliest.map(|at| month_start(at.min(horizon), 0)); + Forward::from(floor, horizon, regular_only(kinds)) +} + /// The pass to run after `range` once the read holds `found` of its `limit` -/// rows, with that pass's limit: the older pass for the rows still missing -/// after a short recent pass, otherwise none. `limit` is the SQL `LIMIT`. +/// rows, with that pass's limit: the older pass after a short recent pass, or +/// the next window after a short window, for the rows still missing; +/// otherwise none. `limit` is the SQL `LIMIT`. pub(crate) fn next(range: Range, found: usize, limit: i64) -> Option<(Range, i64)> { - let Range::Recent(split) = range else { - return None; + let rest = match range { + Range::Recent(split) if split.older => Range::Older(split.floor), + Range::Forward(window) => Range::Forward(window.advance()?), + _ => return None, }; let found = i64::try_from(found).unwrap_or(i64::MAX); - (split.older && found < limit).then(|| (Range::Older(split.floor), limit - found)) + (found < limit).then(|| (rest, limit - found)) } #[cfg(test)] @@ -428,6 +543,7 @@ mod tests { Range::All => true, Range::Recent(s) => s.floor <= t && s.ceiling.is_none_or(|c| t < c), Range::Older(f) => t < f, + Range::Forward(_) => unreachable!(), }) .take(n as usize), ); @@ -446,4 +562,209 @@ mod tests { } } } + + /// The first window of an oldest-first read starts in the month of its + /// earliest possible row and covers two months, unless that reaches the + /// horizon: a regular-kind read ends there, any other read stays open. A + /// far-future bound's floor never passes the horizon, so it stays a + /// literal Postgres parses. A read with no bound is one window. + #[test] + fn oldest_window_follows_the_earliest_month() { + let now = at(2026, 11, 4); + let horizon = ceiling_at(now); + assert_eq!(horizon, midnight(2026, 12, 1)); + let far = DateTime::::MAX_UTC; + // (label, kinds, earliest, from, to) + type Case<'a> = ( + &'a str, + Option<&'a [i32]>, + Option>, + Option>, + Option>, + ); + let cases: &[Case] = &[ + ("no bound", Some(&[9]), None, None, Some(horizon)), + ("no bound, any kind", None, None, None, None), + ( + "old bound", + Some(&[9]), + Some(at(2025, 6, 20)), + Some(midnight(2025, 6, 1)), + Some(midnight(2025, 8, 1)), + ), + ( + "bound last month", + Some(&[9]), + Some(at(2026, 10, 9)), + Some(midnight(2026, 10, 1)), + Some(horizon), + ), + ( + "bound last month, any kind", + None, + Some(at(2026, 10, 9)), + Some(midnight(2026, 10, 1)), + None, + ), + ( + "bound in the last window month", + Some(&[9]), + Some(at(2026, 11, 2)), + Some(midnight(2026, 11, 1)), + Some(horizon), + ), + ( + "far-future bound", + Some(&[9]), + Some(far), + Some(horizon), + Some(horizon), + ), + ( + "far-future bound, any kind", + None, + Some(far), + Some(horizon), + None, + ), + ( + "channel floor", + Some(&[9]), + Some(channel_floor(at(2026, 3, 1))), + Some(midnight(2026, 3, 1)), + Some(midnight(2026, 5, 1)), + ), + ]; + for &(label, kinds, earliest, from, to) in cases { + let window = oldest_for(now, kinds, earliest); + assert_eq!((window.from, window.to), (from, to), "{label}"); + } + let far = oldest_for(now, None, Some(far)); + assert_eq!( + Range::Forward(far).predicate("created_at").as_deref(), + Some(" AND created_at >= '2026-12-01T00:00:00Z'::timestamptz") + ); + let old = oldest_for(now, Some(&[9]), Some(at(2025, 6, 20))); + assert_eq!( + Range::Forward(old).predicate("created_at").as_deref(), + Some( + " AND created_at >= '2025-06-01T00:00:00Z'::timestamptz \ + AND created_at < '2025-08-01T00:00:00Z'::timestamptz" + ) + ); + assert_eq!( + Range::Forward(oldest_for(now, None, None)) + .predicate("created_at") + .as_deref(), + None + ); + } + + /// A channel's floor is its creation less the write path's tolerance, so + /// a row stamped just before the channel existed stays in its first window. + #[test] + fn channel_floor_allows_the_write_tolerance() { + let created = midnight(2026, 3, 1) + Duration::seconds(10); + assert_eq!( + channel_floor(created), + midnight(2026, 3, 1) + Duration::seconds(10 - CREATED_AT_FLOOR_SECS) + ); + let now = at(2026, 11, 4); + let window = oldest_for(now, Some(&[9]), Some(channel_floor(created))); + assert_eq!(window.from, Some(midnight(2026, 2, 1))); + } + + /// The oldest-first windows against an in-memory table, driven the way + /// the stores drive them: the oldest `limit` rows at or after the + /// bound, in order, for every limit, every kind shape and several bounds, + /// reading each row at most once and no window past the one that fills + /// the page. + #[test] + fn oldest_windows_return_the_oldest_rows_and_stop_when_full() { + let now = at(2026, 11, 4); + let horizon = ceiling_at(now); + let after = at(2025, 6, 20); + // Oldest first: gaps of several windows, one row past the horizon + // (only an any-kind read can match it). + let table = [ + after, + midnight(2025, 7, 31), + midnight(2025, 8, 1), + midnight(2026, 1, 9), + at(2026, 11, 30), + horizon + Duration::days(40), + ]; + let regular = Some(&[9][..]); + for (kinds, earliest) in [ + (regular, Some(after)), + (None, Some(after)), + (regular, Some(midnight(2025, 6, 1))), + (regular, None), + (None, None), + (None, Some(DateTime::::MAX_UTC)), + ] { + let first = oldest_for(now, kinds, earliest); + let matching: Vec<_> = table + .iter() + .copied() + .filter(|&t| first.from.is_none_or(|f| f <= t)) + .filter(|&t| kinds.is_none() || t < horizon) + .collect(); + for limit in 0..=table.len() as i64 + 1 { + let mut windows = Vec::new(); + let mut rows = Vec::new(); + let mut pass = Some((Range::Forward(first), limit)); + while let Some((range, n)) = pass { + let Range::Forward(window) = range else { + unreachable!("{range:?}") + }; + windows.push(window); + rows.extend( + table + .iter() + .copied() + .filter(|&t| { + window.from.is_none_or(|f| f <= t) + && window.to.is_none_or(|c| t < c) + }) + .take(n as usize), + ); + pass = next(range, rows.len(), limit); + } + let expected: Vec<_> = matching.iter().copied().take(limit as usize).collect(); + assert_eq!( + rows, expected, + "kinds {kinds:?}, from {earliest:?}, limit {limit}" + ); + // The windows tile the walk: each starts where the last + // ended, and the last one only exists because the page was + // still short when the one before it ended. + for pair in windows.windows(2) { + assert_eq!(pair[1].from, pair[0].to, "{kinds:?}, {earliest:?}"); + } + let last = windows.last().expect("one window"); + if rows.len() as i64 >= limit { + assert!( + windows.len() == 1 + || windows[windows.len() - 2].to.is_some_and(|to| matching + .iter() + .filter(|&&t| t < to) + .count() + < limit as usize), + "a window ran after the page was full: {windows:?}" + ); + } else { + assert!( + last.to.is_none_or(|to| to >= horizon), + "the walk ended short of the horizon: {last:?}" + ); + } + } + } + // A read with no bound is one window, and so is an open one. + let head = oldest_for(now, Some(&[9]), None); + assert_eq!(next(Range::Forward(head), 0, 5), None); + let open = oldest_for(now, None, Some(DateTime::::MAX_UTC)); + assert_eq!(next(Range::Forward(open), 0, 5), None); + } } diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 108865e66a6..e3a328f20cd 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -4,7 +4,7 @@ //! nested threads. The `thread_metadata` table is populated when events are //! ingested and updated as replies arrive or are deleted. -use buzz_core::StoredEvent; +use buzz_core::{thread_window::Direction, StoredEvent}; use chrono::{DateTime, Utc}; use sqlx::{PgPool, Row}; use uuid::Uuid; @@ -131,7 +131,7 @@ pub struct ChannelWindowRow { /// A page of top-level channel rows plus the server-side exhaustion fact. #[derive(Debug, Clone)] pub struct ChannelWindow { - /// Retained rows in `(created_at DESC, id ASC)` order — at most `limit`. + /// Retained rows in the request's [`Direction`] order — at most `limit`. pub rows: Vec, /// Whether more rows exist past the last retained row. Computed from an /// internal `limit + 1` probe; the sentinel row never leaves this module. @@ -555,12 +555,12 @@ pub async fn get_thread_summary( } /// Fetch one channel window: top-level rows (depth = 0, missing metadata, or -/// broadcast depth-1 replies) in `(created_at DESC, id ASC)` keyset order, -/// with thread summaries joined in, plus the server-side `has_more` fact. +/// broadcast depth-1 replies) in `direction` keyset order, with thread +/// summaries joined in, plus the server-side `has_more` fact. /// /// `cursor` is the composite `(created_at, id)` of the last retained row from /// the previous page — there is no timestamp-only fallback on this path (the -/// bridge rejects `until` without `before_id`). `None` = head of the channel. +/// bridge rejects half a cursor). `None` = the first page in `direction`. /// /// `has_more` comes from an internal `limit + 1` probe evaluated after all /// predicates (deletion, top-level, kinds). The sentinel row is dropped here @@ -571,6 +571,7 @@ pub async fn get_channel_window( community_id: CommunityId, channel_id: Uuid, limit: u32, + direction: Direction, cursor: Option<(DateTime, Vec)>, kind_filter: Option<&[u32]>, ) -> Result { @@ -584,6 +585,7 @@ pub async fn get_channel_window( community_id, channel_id, limit, + direction, cursor, kind_filter, crate::event::ReadDeadline::PerRead, @@ -597,11 +599,13 @@ pub async fn get_channel_window( /// connection-local; a different pooled session may sit at a different /// replay position). The page runs under the event read deadline, shared by /// its passes (see `ReadTransaction`). +#[allow(clippy::too_many_arguments)] pub(crate) async fn get_channel_window_on( conn: &mut sqlx::PgConnection, community_id: CommunityId, channel_id: Uuid, limit: u32, + direction: Direction, cursor: Option<(DateTime, Vec)>, kind_filter: Option<&[u32]>, deadline: crate::event::ReadDeadline, @@ -638,13 +642,18 @@ pub(crate) async fn get_channel_window_on( "#, ); + // Composite keyset: with ORDER BY created_at DESC, id ASC, the page after + // (ts, id) is created_at < ts OR (created_at = ts AND id > id); newer + // pages mirror both comparisons. + let (order, past, tiebreak) = match direction { + Direction::Older => ("e.created_at DESC, e.id ASC", "<", ">"), + Direction::Newer => ("e.created_at ASC, e.id DESC", ">", "<"), + }; if cursor.is_some() { - // Composite keyset: with ORDER BY created_at DESC, id ASC, the page - // after (ts, id) is created_at < ts OR (created_at = ts AND id > id). let ts_idx = param_idx; let id_idx = param_idx + 1; sql.push_str(&format!( - " AND (e.created_at < ${ts_idx} OR (e.created_at = ${ts_idx} AND e.id > ${id_idx}))" + " AND (e.created_at {past} ${ts_idx} OR (e.created_at = ${ts_idx} AND e.id {tiebreak} ${id_idx}))" )); param_idx += 2; } @@ -662,15 +671,38 @@ pub(crate) async fn get_channel_window_on( // Recent-first (see `recent_pass`): the newest partitions answer a window // that fills there (with its +1 probe row); older rows are read only for - // what is still missing. + // what is still missing. A newer page walks forward from its cursor's + // month (the head page, from the channel's creation) a window at a time. let kinds: Option> = kind_filter.map(|ks| ks.iter().filter_map(|&k| i32::try_from(k).ok()).collect()); - let split = crate::store::recent_pass::split_for( - Utc::now(), - kinds.as_deref(), - None, - cursor.as_ref().map(|(ts, _)| *ts), - ); + let cursor_ts = cursor.as_ref().map(|(ts, _)| *ts); + let first = match direction { + Direction::Older => { + crate::store::recent_pass::split_for(Utc::now(), kinds.as_deref(), None, cursor_ts) + .map_or(Range::All, Range::Recent) + } + Direction::Newer => { + // The head page has no cursor to start its walk from; the + // channel's creation does. Without the row (no floor), the walk + // is unbounded below, as before. + let earliest = match cursor_ts { + Some(ts) => Some(ts), + None => sqlx::query_scalar::<_, DateTime>( + "SELECT created_at FROM channels WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id) + .fetch_optional(&mut *conn) + .await? + .map(crate::store::recent_pass::channel_floor), + }; + Range::Forward(crate::store::recent_pass::oldest_for( + Utc::now(), + kinds.as_deref(), + earliest, + )) + } + }; // The +1 probe row is the server-internal has_more evidence. let probe_limit = i64::from(limit) + 1; let pass_query = |range: Range, pass_limit: i64| { @@ -678,9 +710,7 @@ pub(crate) async fn get_channel_window_on( if let Some(bound) = range.predicate("e.created_at") { pass_sql.push_str(&bound); } - pass_sql.push_str(&format!( - " ORDER BY e.created_at DESC, e.id ASC LIMIT ${param_idx}" - )); + pass_sql.push_str(&format!(" ORDER BY {order} LIMIT ${param_idx}")); let mut q = sqlx::query(sqlx::AssertSqlSafe(pass_sql)) .bind(community_id.as_uuid()) .bind(channel_id); @@ -689,8 +719,8 @@ pub(crate) async fn get_channel_window_on( } q.bind(pass_limit) }; - let mut db_rows = match split { - None => { + let mut db_rows = match first { + Range::All => { crate::event::fetch_with_read_deadline( &mut *conn, pass_query(Range::All, probe_limit), @@ -698,12 +728,12 @@ pub(crate) async fn get_channel_window_on( ) .await? } - Some(split) => { + first => { // One snapshot and one deadline for both passes (see // `ReadTransaction`). let mut read = crate::event::ReadTransaction::begin(conn, deadline).await?; let mut rows = Vec::new(); - let mut pass = Some((Range::Recent(split), probe_limit)); + let mut pass = Some((first, probe_limit)); while let Some((range, pass_limit)) = pass { rows.extend(read.fetch(pass_query(range, pass_limit)).await?); pass = crate::store::recent_pass::next(range, rows.len(), probe_limit); @@ -1065,7 +1095,8 @@ impl Db { .collect() } - /// One channel window: top-level rows + summaries + server `has_more`. + /// One newest-first channel window: top-level rows + summaries + server + /// `has_more`. /// /// Convenience wrapper over [`Db::get_channel_window_with_session`] for /// callers with no follow-up queries; the serving session is released. @@ -1077,9 +1108,16 @@ impl Db { cursor: Option<(DateTime, Vec)>, kind_filter: Option<&[u32]>, ) -> Result { - self.get_channel_window_with_session(community_id, channel_id, limit, cursor, kind_filter) - .await - .map(|(window, _session)| window) + self.get_channel_window_with_session( + community_id, + channel_id, + limit, + Direction::Older, + cursor, + kind_filter, + ) + .await + .map(|(window, _session)| window) } /// [`Db::get_channel_window`], additionally returning the session that @@ -1095,7 +1133,8 @@ impl Db { /// coverage of the cursor timestamp: the heartbeat token/epoch is /// observed on the exact connection that will serve the page and /// resolved against the fence's retained ring ([`crate::replica_fence`]). - /// - **Head fetch** (Predicate A — bounded staleness): served by a + /// - **Head fetch and newer pages** (Predicate A — bounded staleness): + /// a newer page reads up to the newest row, like a head. Served by a /// proved replica session only when the head gate is configured /// ([`crate::DbConfig::replica_read_max_age_ms`], default off) and the /// proved entry is within the budget. This trades a bounded staleness @@ -1116,18 +1155,19 @@ impl Db { community_id: CommunityId, channel_id: Uuid, limit: u32, + direction: Direction, cursor: Option<(DateTime, Vec)>, kind_filter: Option<&[u32]>, ) -> Result<(crate::thread::ChannelWindow, ReadSession)> { - let path: &'static str = if cursor.is_some() { - "channel_cursor" - } else { - "channel_head" + let (path, covered): (&'static str, _) = match (direction, &cursor) { + (Direction::Newer, _) => ("channel_newer", None), + (Direction::Older, None) => ("channel_head", None), + (Direction::Older, cursor) => ("channel_cursor", cursor.clone()), }; match self .route_read( path, - RoutePredicate::from_channel_cursor(channel_id, &cursor), + RoutePredicate::from_channel_cursor(channel_id, &covered), crate::observability::ReaderOperation::SubscriptionHistory, ) .await? @@ -1138,6 +1178,7 @@ impl Db { community_id, channel_id, limit, + direction, cursor.clone(), kind_filter, crate::event::ReadDeadline::Session, @@ -1185,6 +1226,7 @@ impl Db { community_id, channel_id, limit, + direction, cursor, kind_filter, ) @@ -2129,6 +2171,21 @@ mod postgres_tests { .await; } + /// A channel whose history these fixtures load: stored rows older than the + /// channel are out of the write path's contract, so the channel predates + /// them, as a real one does. + async fn backdate_channel(pool: &PgPool, community: CommunityId, channel_id: Uuid, at: &str) { + sqlx::query( + "UPDATE channels SET created_at = $3::timestamptz WHERE community_id = $1 AND id = $2", + ) + .bind(community.as_uuid()) + .bind(channel_id) + .bind(at) + .execute(pool) + .await + .expect("backdate channel"); + } + /// Insert a depth-1 reply under `root`, with the given broadcast flag. async fn insert_reply( pool: &PgPool, @@ -2196,9 +2253,17 @@ mod postgres_tests { let quiet_reply = make_stream_event(&author, "quiet reply"); insert_reply(&pool, community, channel.id, &root, &quiet_reply, false).await; - let window = get_channel_window(&pool, community, channel.id, 50, None, None) - .await - .expect("fetch window"); + let window = get_channel_window( + &pool, + community, + channel.id, + 50, + Direction::Older, + None, + None, + ) + .await + .expect("fetch window"); let ids: Vec = window .rows @@ -2258,29 +2323,32 @@ mod postgres_tests { insert_root(&pool, community, channel.id, &event).await; } - let mut collected: Vec> = Vec::new(); - let mut cursor: Option<(DateTime, Vec)> = None; - loop { - let window = get_channel_window(&pool, community, channel.id, 2, cursor, None) - .await - .expect("fetch window page"); - for row in &window.rows { - collected.push(row.stored_event.event.id.as_bytes().to_vec()); + // Tied rows sort by id: ascending newest-first, descending oldest-first. + expected_ids.sort(); + for direction in [Direction::Older, Direction::Newer] { + let mut collected: Vec> = Vec::new(); + let mut cursor: Option<(DateTime, Vec)> = None; + loop { + let window = + get_channel_window(&pool, community, channel.id, 2, direction, cursor, None) + .await + .expect("fetch window page"); + for row in &window.rows { + collected.push(row.stored_event.event.id.as_bytes().to_vec()); + } + if !window.has_more { + break; + } + cursor = Some(window.next_cursor.expect("has_more implies next_cursor")); } - if !window.has_more { - break; + if direction == Direction::Newer { + collected.reverse(); } - cursor = Some(window.next_cursor.expect("has_more implies next_cursor")); + assert_eq!( + collected, expected_ids, + "{direction:?} paging lost, duplicated or misordered rows" + ); } - - assert_eq!(collected.len(), row_count, "paged set lost or grew rows"); - let mut unique = collected.clone(); - unique.sort(); - unique.dedup(); - assert_eq!(unique.len(), row_count, "paging produced duplicates"); - let mut expected_sorted = expected_ids.clone(); - expected_sorted.sort(); - assert_eq!(unique, expected_sorted, "paged set != inserted tied set"); } /// The exact-multiple final page: when the channel's row count is an @@ -2311,22 +2379,32 @@ mod postgres_tests { insert_root(&pool, community, channel.id, &event).await; } - let page1 = get_channel_window(&pool, community, channel.id, 2, None, None) - .await - .expect("fetch page 1"); - assert_eq!(page1.rows.len(), 2); - assert!(page1.has_more, "two more rows exist past page 1"); - let cursor = page1.next_cursor.expect("has_more implies next_cursor"); + for direction in [Direction::Older, Direction::Newer] { + let page1 = get_channel_window(&pool, community, channel.id, 2, direction, None, None) + .await + .expect("fetch page 1"); + assert_eq!(page1.rows.len(), 2); + assert!(page1.has_more, "two more rows exist past page 1"); + let cursor = page1.next_cursor.expect("has_more implies next_cursor"); - let page2 = get_channel_window(&pool, community, channel.id, 2, Some(cursor), None) + let page2 = get_channel_window( + &pool, + community, + channel.id, + 2, + direction, + Some(cursor), + None, + ) .await .expect("fetch page 2"); - assert_eq!(page2.rows.len(), 2, "final page is exactly full"); - assert!( - !page2.has_more, - "exact-multiple final page must report exhausted despite rows == limit" - ); - assert!(page2.next_cursor.is_none(), "no cursor past the last row"); + assert_eq!(page2.rows.len(), 2, "final page is exactly full"); + assert!( + !page2.has_more, + "exact-multiple final page must report exhausted despite rows == limit" + ); + assert!(page2.next_cursor.is_none(), "no cursor past the last row"); + } } /// The window is split at the floor: a recent pass that fills the page @@ -2389,6 +2467,7 @@ mod postgres_tests { community, channel.id, 1, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2408,6 +2487,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2426,6 +2506,7 @@ mod postgres_tests { community, channel.id, 4, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2439,6 +2520,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2452,6 +2534,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, Some(cursor), None, ReadDeadline::PerRead, @@ -2500,6 +2583,7 @@ mod postgres_tests { community, channel.id, 1, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2512,6 +2596,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2529,6 +2614,352 @@ mod postgres_tests { .expect("reset lock_timeout"); } + /// An oldest-first window pages forward over the monthly partitions, and + /// a cursor page plans only the partitions it reads: its early pass + /// covers the cursor's month and the next, and the later pass runs only + /// when that is short. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_newer_pages_forward_across_partitions() { + use nostr::Timestamp; + + let pool = setup_pool().await; + let author = Keys::generate(); + let (channel, community) = create_test_channel( + &pool, + &format!("window-newer-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + author.public_key().to_bytes().as_slice(), + None, + ) + .await + .expect("create channel"); + backdate_channel(&pool, community, channel.id, "2025-05-15T00:00:00Z").await; + let at = |rfc3339: &str| { + DateTime::parse_from_rfc3339(rfc3339) + .expect("date") + .timestamp() as u64 + }; + let mut oldest_first = Vec::new(); + for created_at in [ + at("2025-06-01T00:00:00Z"), + at("2026-03-10T12:00:00Z"), + at("2026-03-20T12:00:00Z"), + at("2026-04-20T12:00:00Z"), + at("2026-06-15T12:00:00Z"), + Utc::now().timestamp() as u64 - 10, + ] { + let event = EventBuilder::new(Kind::Custom(9), format!("at {created_at}")) + .custom_created_at(Timestamp::from(created_at)) + .sign_with_keys(&author) + .expect("sign"); + insert_historical_root(&pool, community, channel.id, &event).await; + oldest_first.push(event); + } + let ids = |w: &ChannelWindow| { + w.rows + .iter() + .map(|r| r.stored_event.event.id) + .collect::>() + }; + let expected = |range: std::ops::Range| { + oldest_first[range].iter().map(|e| e.id).collect::>() + }; + let cursor_at = + |event: &nostr::Event| Some((event_created_at(event), event.id.as_bytes().to_vec())); + let mut conn = pool.acquire().await.expect("acquire"); + + // From the head, two rows a page, to the newest row. + let mut cursor = None; + let mut pages = Vec::new(); + loop { + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 2, + Direction::Newer, + cursor, + None, + ReadDeadline::PerRead, + ) + .await + .expect("forward page"); + pages.push(ids(&window)); + if !window.has_more { + break; + } + cursor = Some(window.next_cursor.expect("has_more implies next_cursor")); + } + assert_eq!(pages, [expected(0..2), expected(2..4), expected(4..6)]); + + // Another session locks the partitions of the oldest row and of the + // June row. A page after the 10 March row that its early pass fills + // (March and April) never plans them; one that needs the later pass + // does, and fails rather than return a short page. + let partition_of = |id: nostr::EventId| { + let pool = pool.clone(); + async move { + sqlx::query_scalar::<_, String>( + "SELECT tableoid::regclass::text FROM events WHERE id = $1", + ) + .bind(id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition") + } + }; + let oldest = partition_of(oldest_first[0].id).await; + let june = partition_of(oldest_first[4].id).await; + let march = partition_of(oldest_first[1].id).await; + let april = partition_of(oldest_first[3].id).await; + assert!( + [&oldest, &march, &april].iter().all(|p| *p != &june) + && oldest != march + && march != april, + "fixture rows must sit in distinct partitions: {oldest}, {march}, {april}, {june}" + ); + let mut locker = pool.begin().await.expect("begin locker"); + for partition in [&oldest, &june] { + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {partition} IN ACCESS EXCLUSIVE MODE" + ))) + .execute(&mut *locker) + .await + .expect("lock partition"); + } + sqlx::query("SET lock_timeout = '200ms'") + .execute(&mut *conn) + .await + .expect("set lock_timeout"); + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + 1, + Direction::Newer, + cursor_at(&oldest_first[1]), + None, + ReadDeadline::PerRead, + ) + .await + .expect("a full early pass never touches the locked partitions"); + assert_eq!(ids(&window), expected(2..3)); + assert!(window.has_more); + let failed = get_channel_window_on( + &mut conn, + community, + channel.id, + 2, + Direction::Newer, + cursor_at(&oldest_first[1]), + None, + ReadDeadline::PerRead, + ) + .await; + assert!( + failed.is_err(), + "a failed later pass must fail the window, got {:?}", + failed.map(|w| (w.rows.len(), w.has_more)) + ); + locker.rollback().await.expect("release locks"); + sqlx::query("RESET lock_timeout") + .execute(&mut *conn) + .await + .expect("reset lock_timeout"); + + // Unlocked, the later pass supplies the probe row and the tail. + for (after, limit, rows, more) in [(1, 2, 2..4, true), (3, 5, 4..6, false)] { + let window = get_channel_window_on( + &mut conn, + community, + channel.id, + limit, + Direction::Newer, + cursor_at(&oldest_first[after]), + None, + ReadDeadline::PerRead, + ) + .await + .expect("cursor page"); + assert_eq!((ids(&window), window.has_more), (expected(rows), more)); + } + } + + /// The head page of an oldest-first window reads only the partitions it + /// needs. It starts at the month the channel was created, so the older + /// partitions are never planned, and it walks forward two months at a + /// time, so the newer ones are planned only when the page is still short. + /// Its rows are the oldest rows of an unbounded read, for every limit. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_newer_head_plans_only_the_partitions_it_reads() { + use nostr::Timestamp; + + let pool = setup_pool().await; + let author = Keys::generate(); + let new_channel = |name: &'static str| { + let pool = pool.clone(); + let creator = author.public_key().to_bytes(); + async move { + create_test_channel( + &pool, + &format!("{name}-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + creator.as_slice(), + None, + ) + .await + .expect("create channel") + } + }; + let (channel, community) = new_channel("window-head").await; + backdate_channel(&pool, community, channel.id, "2026-01-10T00:00:00Z").await; + let at = |rfc3339: &str| { + DateTime::parse_from_rfc3339(rfc3339) + .expect("date") + .timestamp() as u64 + }; + let insert = |community: CommunityId, channel_id: Uuid, created_at: u64| { + let pool = pool.clone(); + let event = EventBuilder::new(Kind::Custom(9), format!("at {created_at}")) + .custom_created_at(Timestamp::from(created_at)) + .sign_with_keys(&author) + .expect("sign"); + async move { + insert_historical_root(&pool, community, channel_id, &event).await; + event + } + }; + let mut oldest_first = Vec::new(); + for created_at in [ + at("2026-01-12T00:00:00Z"), + at("2026-01-20T00:00:00Z"), + at("2026-03-10T12:00:00Z"), + at("2026-04-20T12:00:00Z"), + at("2026-06-15T12:00:00Z"), + Utc::now().timestamp() as u64 - 10, + ] { + oldest_first.push(insert(community, channel.id, created_at).await); + } + // A row of another channel in the partition below the head page's + // floor: it only names that partition. + let (other, other_community) = new_channel("window-head-other").await; + let below = insert(other_community, other.id, at("2025-06-01T00:00:00Z")).await; + + let mut conn = pool.acquire().await.expect("acquire"); + let channel_id = channel.id; + async fn head( + conn: &mut sqlx::PgConnection, + community: CommunityId, + channel_id: Uuid, + limit: u32, + ) -> Result { + get_channel_window_on( + conn, + community, + channel_id, + limit, + Direction::Newer, + None, + None, + ReadDeadline::PerRead, + ) + .await + } + + // Unlocked, every limit pages the same rows as a read with no floor. + for limit in 1..=oldest_first.len() as u32 + 1 { + let unbounded: Vec> = sqlx::query_scalar( + "SELECT id FROM events WHERE community_id = $1 AND channel_id = $2 \ + AND deleted_at IS NULL ORDER BY created_at ASC, id DESC LIMIT $3", + ) + .bind(community.as_uuid()) + .bind(channel.id) + .bind(i64::from(limit)) + .fetch_all(&pool) + .await + .expect("unbounded read"); + let window = head(&mut conn, community, channel_id, limit) + .await + .expect("head page"); + let ids: Vec<_> = window + .rows + .iter() + .map(|r| r.stored_event.event.id.as_bytes().to_vec()) + .collect(); + assert_eq!(ids, unbounded, "limit {limit}"); + assert_eq!(window.has_more, (limit as usize) < oldest_first.len()); + } + + // Another session locks the partitions the page must not plan. A + // page needing a locked one fails instead of returning a short page. + let partition_of = |id: nostr::EventId| { + let pool = pool.clone(); + async move { + sqlx::query_scalar::<_, String>( + "SELECT tableoid::regclass::text FROM events WHERE id = $1", + ) + .bind(id.as_bytes().to_vec()) + .fetch_one(&pool) + .await + .expect("partition") + } + }; + let below = partition_of(below.id).await; + let first = partition_of(oldest_first[0].id).await; + let june = partition_of(oldest_first[4].id).await; + let newest = partition_of(oldest_first[5].id).await; + let distinct = [&below, &first, &june, &newest] + .iter() + .collect::>() + .len(); + assert_eq!( + distinct, 4, + "fixture rows must sit in distinct partitions: {below}, {first}, {june}, {newest}" + ); + let mut locker = pool.begin().await.expect("begin locker"); + for partition in [&below, &june, &newest] { + sqlx::query(sqlx::AssertSqlSafe(format!( + "LOCK TABLE {partition} IN ACCESS EXCLUSIVE MODE" + ))) + .execute(&mut *locker) + .await + .expect("lock partition"); + } + sqlx::query("SET lock_timeout = '200ms'") + .execute(&mut *conn) + .await + .expect("set lock_timeout"); + // One row and its probe fill the first window (January and + // February); three rows need the second (March and April) and stop + // there, before the locked June and the newest partition. + for (limit, rows) in [(1, 1), (3, 3)] { + let window = head(&mut conn, community, channel_id, limit) + .await + .expect("a page that fills early never plans the locked partitions"); + let ids: Vec<_> = window + .rows + .iter() + .map(|r| r.stored_event.event.id) + .collect(); + let expected: Vec<_> = oldest_first[..rows].iter().map(|e| e.id).collect(); + assert_eq!(ids, expected, "limit {limit}"); + assert!(window.has_more, "limit {limit}"); + } + let failed = head(&mut conn, community, channel_id, 4).await; + assert!( + failed.is_err(), + "a page that needs the June window must fail on its lock, got {:?}", + failed.map(|w| (w.rows.len(), w.has_more)) + ); + locker.rollback().await.expect("release locks"); + } + /// The window's passes share one snapshot: a replacement that commits /// between them neither drops the row it replaces nor shows the row it /// adds. @@ -2559,6 +2990,7 @@ mod postgres_tests { community, channel_id, 10, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2653,7 +3085,16 @@ mod postgres_tests { let started = std::time::Instant::now(); let window_pool = pool.clone(); let mut task = tokio::spawn(async move { - get_channel_window(&window_pool, community, channel.id, 10, None, None).await + get_channel_window( + &window_pool, + community, + channel.id, + 10, + Direction::Older, + None, + None, + ) + .await }); let waiting = tokio::time::timeout(std::time::Duration::from_secs(10), async { loop { @@ -2738,9 +3179,17 @@ mod postgres_tests { insert_reply(&pool, community, channel.id, &discussed, &reply, false).await; } - let window = get_channel_window(&pool, community, channel.id, 50, None, None) - .await - .expect("fetch window"); + let window = get_channel_window( + &pool, + community, + channel.id, + 50, + Direction::Older, + None, + None, + ) + .await + .expect("fetch window"); let discussed_row = window .rows @@ -2838,9 +3287,17 @@ mod postgres_tests { .expect("root has thread metadata"); assert_eq!(summary.participants, expected, "live summary"); - let window = get_channel_window(&pool, community, channel.id, 50, None, None) - .await - .expect("fetch window"); + let window = get_channel_window( + &pool, + community, + channel.id, + 50, + Direction::Older, + None, + None, + ) + .await + .expect("fetch window"); let row = window .rows .iter() diff --git a/crates/buzz-db/src/store/thread_window.rs b/crates/buzz-db/src/store/thread_window.rs index daf37f7e941..87069362db5 100644 --- a/crates/buzz-db/src/store/thread_window.rs +++ b/crates/buzz-db/src/store/thread_window.rs @@ -1,8 +1,8 @@ -//! NIP-CW thread-mode newest-first reply windows. This path deliberately does not change +//! NIP-CW thread-mode reply windows, newest or oldest first. This path deliberately does not change //! legacy forward threads or the permissive generic event reconstruction path. use buzz_core::{ - thread_window::{Cursor, Request, MAX_LIMIT, ROW_KINDS}, + thread_window::{Cursor, Direction, Request, MAX_LIMIT, ROW_KINDS}, CommunityId, StoredEvent, }; use chrono::{DateTime, Utc}; @@ -20,7 +20,7 @@ use buzz_datastore_tracing::datastore_span; /// authoritative scan bounds. #[derive(Debug)] pub struct ThreadWindow { - /// Reconstructed replies, newest first (id ascending for ties). + /// Reconstructed replies in the request's [`Direction`] order. pub rows: Vec, /// Another eligible raw reply exists after this page. pub has_more: bool, @@ -116,17 +116,35 @@ async fn select_window( .push_bind(request.channel) .push(" AND tm.depth BETWEEN 1 AND ") .push_bind(request.depth as i32); + // Newer pages scan idx_thread_metadata_window backward. + let (order, start, past, tiebreak) = match request.direction { + Direction::Older => ( + "tm.event_created_at DESC, tm.event_id ASC", + " <= ", + " < ", + " > ", + ), + Direction::Newer => ( + "tm.event_created_at ASC, tm.event_id DESC", + " >= ", + " > ", + " < ", + ), + }; if let Some(cursor) = &request.cursor { let (ts, id) = cursor_key(cursor)?; - // The redundant upper timestamp bound gives PostgreSQL an index range - // start instead of filtering all newer keys at a deep cursor. - q.push(" AND tm.event_created_at <= ") + // The redundant inclusive timestamp bound gives PostgreSQL an index + // range start instead of filtering every key before a deep cursor. + q.push(" AND tm.event_created_at") + .push(start) .push_bind(ts) - .push(" AND (tm.event_created_at < ") + .push(" AND (tm.event_created_at") + .push(past) .push_bind(ts) .push(" OR (tm.event_created_at = ") .push_bind(ts) - .push(" AND tm.event_id > ") + .push(" AND tm.event_id") + .push(tiebreak) .push_bind(id) .push("))"); } @@ -134,7 +152,9 @@ async fn select_window( // cannot turn a selective live/kind index into a root-wide scan per reply. // PK uniqueness makes the inner LIMIT 1 exact. All eligibility predicates // still precede the *outer* limit+1 that establishes page bounds. - q.push(" ORDER BY tm.event_created_at DESC, tm.event_id ASC OFFSET 0) tm \ + q.push(" ORDER BY ") + .push(order) + .push(" OFFSET 0) tm \ JOIN LATERAL (SELECT e.id, e.pubkey, e.created_at, e.kind, e.tags, e.content, e.sig, e.received_at, e.channel_id, e.deleted_at \ FROM events e WHERE e.community_id = tm.community_id \ AND e.created_at = tm.event_created_at AND e.id = tm.event_id LIMIT 1) e ON true \ @@ -142,7 +162,9 @@ async fn select_window( .push_bind(request.channel) .push(" AND e.deleted_at IS NULL AND e.kind = ANY(") .push_bind(request.kinds.iter().map(|k| *k as i32).collect::>()) - .push(") ORDER BY tm.event_created_at DESC, tm.event_id ASC LIMIT ") + .push(") ORDER BY ") + .push(order) + .push(" LIMIT ") .push_bind(i64::from(request.limit) + 1); // Selectivity varies drastically with root/depth/cursor. A cached generic // plan can sort the entire root (and exceeded the SQL deadline in paging @@ -198,9 +220,10 @@ async fn writer_window( } impl Db { - /// Newest-first thread page and its proved replica transaction. Backward - /// cursors supply an upper bound, including terminal pages; no forward - /// thread "last delivered row is newest" inference is used. Head routing + /// Thread page and its proved replica transaction. Older cursors supply + /// an upper bound, including terminal pages; no forward thread "last + /// delivered row is newest" inference is used. Head and newer pages read + /// up to the newest reply, which no cursor bounds, so their routing /// inherits the existing default-off budget. Writer follow-ups are pooled, /// not a snapshot spanning the response or subsequent history pages. The /// caller must share `budget` with every window and auxiliary scan in the request. @@ -212,15 +235,15 @@ impl Db { budget: &mut ScanBudget, ) -> Result<(ThreadWindow, ReadSession)> { let cursor = request.cursor.as_ref().map(cursor_key).transpose()?; - let path = if cursor.is_some() { - "thread_window_cursor" - } else { - "thread_window_head" + let (path, covered) = match (request.direction, cursor) { + (Direction::Newer, _) => ("thread_window_newer", None), + (Direction::Older, None) => ("thread_window_head", None), + (Direction::Older, cursor) => ("thread_window_cursor", cursor), }; if let RouteDecision::Replica(mut tx, _, reason) = self .route_read( path, - RoutePredicate::from_channel_cursor(request.channel, &cursor), + RoutePredicate::from_channel_cursor(request.channel, &covered), crate::observability::ReaderOperation::SubscriptionHistory, ) .await? diff --git a/crates/buzz-db/src/store/thread_window/postgres_tests.rs b/crates/buzz-db/src/store/thread_window/postgres_tests.rs index a2bda65123a..85cad2c9deb 100644 --- a/crates/buzz-db/src/store/thread_window/postgres_tests.rs +++ b/crates/buzz-db/src/store/thread_window/postgres_tests.rs @@ -170,18 +170,21 @@ async fn cardinalities() { root.created_at.as_secs(), ); db.insert_event(cid, &root, Some(ch)).await.unwrap(); - let expected = replies(&db, cid, ch, &keys, &root, count).await; - assert_pages(&db, cid, request(ch, &root, 50), &expected).await; - let (head, _) = db - .get_thread_window_with_session( - cid, - &request(ch, &root, 50), - &mut ScanBudget::default(), - ) - .await - .unwrap(); - assert_eq!(head.has_more, count > 50); - assert_eq!(head.rows.len(), count.min(50)); + let mut expected = replies(&db, cid, ch, &keys, &root, count).await; + for direction in [Direction::Older, Direction::Newer] { + let mut req = request(ch, &root, 50); + req.direction = direction; + if direction == Direction::Newer { + expected.reverse(); + } + assert_pages(&db, cid, req.clone(), &expected).await; + let (head, _) = db + .get_thread_window_with_session(cid, &req, &mut ScanBudget::default()) + .await + .unwrap(); + assert_eq!(head.has_more, count > 50); + assert_eq!(head.rows.len(), count.min(50)); + } } let index: (bool,bool,String) = sqlx::query_as("SELECT indisvalid,indisready,pg_get_indexdef(indexrelid) FROM pg_index WHERE indexrelid='idx_thread_metadata_window'::regclass") .fetch_one(&db.pool).await.unwrap(); @@ -283,6 +286,12 @@ async fn thread_window_predicates_corruption_and_legacy() { assert!(page.has_more); assert_eq!(page.next_cursor.unwrap().id, expected[49].id.to_hex()); assert_pages(&db, cid, req.clone(), expected).await; + // Oldest first, the eligible rows come first and the second page reads + // past all 600 ineligible ones to its last row and the end. + let mut newer = req.clone(); + newer.direction = Direction::Newer; + let oldest_first: Vec<_> = expected.iter().rev().cloned().collect(); + assert_pages(&db, cid, newer, &oldest_first).await; sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2") .bind(cid.as_uuid()) .bind(expected[50].id.to_bytes().to_vec()) diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 3357dbf32b8..460ab531023 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -19,7 +19,7 @@ use base64::Engine; use serde_json::Value; use buzz_auth::{LimitType, Nip98ReplayGuard, DEFAULT_REPLAY_TTL_SECS}; -use buzz_core::TenantContext; +use buzz_core::{thread_window::Direction, TenantContext}; use crate::access::{AccessSlot, AuthResult}; use crate::handlers::ingest::{IngestAuth, IngestError}; @@ -715,17 +715,18 @@ fn extract_channel_from_filter(filter: &nostr::Filter) -> Option { const BRIDGE_FEED_MAX_LIMIT: u32 = 100; const BRIDGE_THREAD_MAX_LIMIT: u32 = 500; -/// The `before_id` extension field, with "present but malformed" kept distinct -/// from "absent": NIP-CW's cursor grammar says a malformed value MUST reject -/// the request, never silently demote it to a half cursor or a head request. +/// A cursor id extension field (`before_id`, `after_id`), with "present but +/// malformed" kept distinct from "absent": NIP-CW's cursor grammar says a +/// malformed value MUST reject the request, never silently demote it to a +/// half cursor or a head request. enum BeforeId { Absent, Valid(Vec), Malformed, } -fn extract_before_id(raw: &Value) -> BeforeId { - let Some(value) = raw.get("before_id") else { +fn extract_event_id(raw: &Value, key: &str) -> BeforeId { + let Some(value) = raw.get(key) else { return BeforeId::Absent; }; match value @@ -1034,33 +1035,46 @@ async fn handle_channel_window_filter( return Ok(()); } - // Composite request cursor: `until` + `before_id`, both or neither. The - // window path has no timestamp-only fallback — that ambiguity is the - // dense-second dup/loss bug this surface exists to kill. A malformed - // `before_id` is likewise rejected outright (NIP-CW cursor grammar), - // never demoted to a half cursor or a head request. - let before_id = match extract_before_id(raw) { + // Composite request cursor: `until` + `before_id` (`after` + `after_id` + // for a newer page), both or neither. The window path has no + // timestamp-only fallback — that ambiguity is the dense-second dup/loss + // bug this surface exists to kill. A malformed id is likewise rejected + // outright (NIP-CW cursor grammar), never demoted to a half cursor or a + // head request. + let direction = Direction::parse(raw) + .map_err(|e| api_error(StatusCode::BAD_REQUEST, &format!("top_level: {e}")))?; + let (ts_key, id_key) = direction.cursor_fields(); + let id = match extract_event_id(raw, id_key) { BeforeId::Malformed => { return Err(api_error( StatusCode::BAD_REQUEST, - "top_level: before_id must be a 64-hex event id", + &format!("top_level: {id_key} must be a 64-hex event id"), )); } BeforeId::Valid(id) => Some(id), BeforeId::Absent => None, }; - let cursor = match (filter.until, before_id) { - (Some(ts), Some(id)) => { - let ts = chrono::DateTime::from_timestamp(ts.as_secs() as i64, 0).ok_or_else(|| { - api_error(StatusCode::BAD_REQUEST, "top_level: until is out of range") - })?; - Some((ts, id)) - } + let ts = raw + .get(ts_key) + .map(|ts| { + ts.as_i64() + .and_then(|ts| chrono::DateTime::from_timestamp(ts, 0)) + .filter(|ts| ts.timestamp() >= 0) + .ok_or_else(|| { + api_error( + StatusCode::BAD_REQUEST, + &format!("top_level: {ts_key} is out of range"), + ) + }) + }) + .transpose()?; + let cursor = match (ts, id) { + (Some(ts), Some(id)) => Some((ts, id)), (None, None) => None, _ => { return Err(api_error( StatusCode::BAD_REQUEST, - "top_level cursor requires both until and before_id, or neither", + &format!("top_level cursor requires both {ts_key} and {id_key}, or neither"), )); } }; @@ -1082,6 +1096,7 @@ async fn handle_channel_window_filter( tenant.community(), ch_id, limit, + direction, cursor.clone(), kind_filter.as_deref(), ) @@ -1183,18 +1198,26 @@ async fn handle_channel_window_filter( // 4. Window bounds: exactly one 39006 per window response — the only // authority on exhaustion. `rows < limit` proves nothing on an // exact-multiple final page. + // A newer page binds its direction into both, so it can never be + // mistaken for an older page (or one from a relay that ignores it). let cursor_suffix = match &cursor { Some((ts, id)) => format!("{}:{}", ts.timestamp(), hex::encode(id)), None => "head".to_owned(), }; - let d_val = format!("{ch_hex}:{cursor_suffix}"); - let content = serde_json::json!({ + let mut content = serde_json::json!({ "has_more": window.has_more, "next_cursor": window.next_cursor.as_ref().map(|(ts, id)| serde_json::json!({ "created_at": ts.timestamp(), "id": hex::encode(id), })), }); + let d_val = match direction { + Direction::Older => format!("{ch_hex}:{cursor_suffix}"), + Direction::Newer => { + content["direction"] = "newer".into(); + format!("{ch_hex}:newer:{cursor_suffix}") + } + }; let tags = vec![parse_tag(["d", &d_val])?, parse_tag(["h", &ch_hex])?]; let overlay = sign_overlay(KIND_WINDOW_BOUNDS, tags, content.to_string())?; let v = serde_json::to_value(&overlay) @@ -2174,7 +2197,7 @@ async fn query_member_events( query.shared_gated_reader = Some(pubkey_bytes.clone()); } - match extract_before_id(raw) { + match extract_event_id(raw, "before_id") { BeforeId::Malformed => { return Err(api_error( StatusCode::BAD_REQUEST, @@ -4536,7 +4559,7 @@ pub(crate) mod postgres_tests { fn extract_before_id_valid_hex() { let hex = "a".repeat(64); let raw = serde_json::json!({ "before_id": hex }); - match extract_before_id(&raw) { + match extract_event_id(&raw, "before_id") { BeforeId::Valid(id) => assert_eq!(id.len(), 32), _ => panic!("64-char hex must parse as Valid"), } @@ -4545,31 +4568,46 @@ pub(crate) mod postgres_tests { #[test] fn extract_before_id_short_hex() { let raw = serde_json::json!({ "before_id": "a".repeat(63) }); - assert!(matches!(extract_before_id(&raw), BeforeId::Malformed)); + assert!(matches!( + extract_event_id(&raw, "before_id"), + BeforeId::Malformed + )); } #[test] fn extract_before_id_long_hex() { let raw = serde_json::json!({ "before_id": "a".repeat(65) }); - assert!(matches!(extract_before_id(&raw), BeforeId::Malformed)); + assert!(matches!( + extract_event_id(&raw, "before_id"), + BeforeId::Malformed + )); } #[test] fn extract_before_id_invalid_hex_chars() { let raw = serde_json::json!({ "before_id": "z".repeat(64) }); - assert!(matches!(extract_before_id(&raw), BeforeId::Malformed)); + assert!(matches!( + extract_event_id(&raw, "before_id"), + BeforeId::Malformed + )); } #[test] fn extract_before_id_absent() { let raw = serde_json::json!({}); - assert!(matches!(extract_before_id(&raw), BeforeId::Absent)); + assert!(matches!( + extract_event_id(&raw, "before_id"), + BeforeId::Absent + )); } #[test] fn extract_before_id_non_string() { let raw = serde_json::json!({ "before_id": 12345 }); - assert!(matches!(extract_before_id(&raw), BeforeId::Malformed)); + assert!(matches!( + extract_event_id(&raw, "before_id"), + BeforeId::Malformed + )); } #[test] diff --git a/crates/buzz-relay/src/api/bridge/thread_window.rs b/crates/buzz-relay/src/api/bridge/thread_window.rs index fc5989172b4..aa17e0819aa 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window.rs @@ -188,7 +188,11 @@ async fn query( let mut events = Vec::new(); let page_start_bytes = budget.bytes; budget.bytes += 2; - let mut targets = vec![request.root.clone()]; + let mut targets: Vec = request + .root_aux + .then(|| request.root.clone()) + .into_iter() + .collect(); for row in &window.rows { if !visible(row) { // This would contradict the SQL's channel and row-kind predicates. @@ -271,7 +275,7 @@ async fn query( .map_err(|e| internal_error(&format!("thread bounds tags: {e}")))?; let bounds = nostr::EventBuilder::new( nostr::Kind::Custom(buzz_core::kind::KIND_THREAD_WINDOW_BOUNDS as u16), - json!({"version":1,"direction":"older","has_more":window.has_more, + json!({"version":1,"direction":request.direction.as_str(),"has_more":window.has_more, "next_cursor":window.next_cursor}) .to_string(), ) diff --git a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs index 7430d7d7a99..40897a0f190 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window/postgres_tests.rs @@ -171,7 +171,7 @@ impl Fixture { ); let content: Value = serde_json::from_str(&event.content).unwrap(); assert_eq!(content["version"], 1); - assert_eq!(content["direction"], "older"); + assert_eq!(content["direction"], request.direction.as_str()); assert_eq!( content["has_more"].as_bool().unwrap(), !content["next_cursor"].is_null() @@ -341,6 +341,175 @@ async fn thread_window_real_query_signed_bounds_and_sentinel_aux() { } } +/// A newer window pages forward from the oldest reply, and `root_aux: false` +/// leaves the root's aux out while the rows keep theirs. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn thread_window_newer_pages_forward_and_root_aux_is_optional() { + let f = Fixture::new().await; + let mut replies = Vec::new(); + for n in 0..51 { + replies.push(f.reply(n).await); + } + let root_edit = f.aux(40003, &f.root, Some(f.channel)).await; + let reply_reaction = f.aux(7, &replies[50], Some(f.channel)).await; + let hex = |events: &[Event]| events.iter().map(|e| e.id.to_hex()).collect::>(); + let mut filter = f.filter(); + filter["direction"] = json!("newer"); + let page = f.query(&filter).await; + assert_eq!(ids(&page, Some(9)), hex(&replies[..50])); + assert!(ids(&page, None).contains(&root_edit.id.to_hex().as_str())); + let bounds = f.bounds(&page, &filter); + assert_eq!(bounds["direction"], "newer"); + assert_eq!(bounds["has_more"], true); + assert_eq!( + bounds["next_cursor"], + json!({"created_at": replies[49].created_at.as_secs(), "id": replies[49].id.to_hex()}) + ); + + let mut tail = filter.clone(); + tail["after"] = bounds["next_cursor"]["created_at"].clone(); + tail["after_id"] = bounds["next_cursor"]["id"].clone(); + tail["root_aux"] = json!(false); + let page = f.query(&tail).await; + assert_eq!(ids(&page, Some(9)), hex(&replies[50..])); + let all = ids(&page, None); + assert!(!all.contains(&root_edit.id.to_hex().as_str()), "{page}"); + assert!(all.contains(&reply_reaction.id.to_hex().as_str()), "{page}"); + let bounds = f.bounds(&page, &tail); + assert_eq!( + (&bounds["has_more"], &bounds["next_cursor"]), + (&json!(false), &Value::Null) + ); + + // Past the last reply, a page without the root's aux is the bounds alone. + let mut end = tail.clone(); + end["after"] = json!(replies[50].created_at.as_secs()); + end["after_id"] = json!(replies[50].id.to_hex()); + let page = f.query(&end).await; + assert_eq!(page.as_array().unwrap().len(), 1, "{page}"); + assert_eq!(f.bounds(&page, &end)["has_more"], false); +} + +/// A channel window's 39006 bounds: older pages keep their d-tag and exact +/// content bytes; newer pages add `newer` to both. +#[tokio::test] +#[ignore = "requires Postgres"] +async fn channel_window_newer_pages_forward_with_distinct_bounds() { + let f = Fixture::new().await; + let mut tops = vec![f.root.clone()]; + for n in 1..=2 { + let top = event( + &f.keys, + f.channel, + 9, + &format!("top {n}"), + None, + f.root.created_at.as_secs() + n, + ); + f.state + .db + .insert_event(f.community, &top, Some(f.channel)) + .await + .unwrap(); + tops.push(top); + } + let f = &f; + let ch = f.channel.to_string(); + let hex = |events: &[&Event]| events.iter().map(|e| e.id.to_hex()).collect::>(); + let cursor = |e: &Event| format!("{}:{}", e.created_at.as_secs(), e.id.to_hex()); + let window = |extra: Value| { + let mut filter = json!({"top_level":true,"#h":[f.channel],"kinds":[9],"limit":2}); + for (key, val) in extra.as_object().unwrap() { + filter[key] = val.clone(); + } + filter + }; + // Each page: its rows, then exactly one relay-signed 39006 (d-tag, content). + let page = |filter: Value| async move { + let page = f.query(&filter).await; + let bounds: Vec = page + .as_array() + .unwrap() + .iter() + .filter(|v| v["kind"] == 39006) + .map(|v| serde_json::from_value(v.clone()).unwrap()) + .collect(); + assert_eq!(bounds.len(), 1, "{page}"); + bounds[0].verify().unwrap(); + assert_eq!(bounds[0].pubkey, f.state.relay_keypair.public_key()); + let d = bounds[0] + .tags + .iter() + .find(|t| t.kind().to_string() == "d") + .unwrap(); + ( + ids(&page, Some(9)) + .iter() + .map(|s| s.to_string()) + .collect::>(), + d.content().unwrap().to_owned(), + bounds[0].content.clone(), + ) + }; + let (t0, t1, t2) = (&tops[0], &tops[1], &tops[2]); + + let (rows, d, content) = page(window(json!({"limit":3}))).await; + assert_eq!(rows, hex(&[t2, t1, t0])); + assert_eq!( + (d, content), + ( + format!("{ch}:head"), + r#"{"has_more":false,"next_cursor":null}"#.to_owned() + ) + ); + let (rows, d, content) = page(window( + json!({"until":t2.created_at.as_secs(),"before_id":t2.id.to_hex()}), + )) + .await; + assert_eq!(rows, hex(&[t1, t0])); + assert_eq!( + (d, content), + ( + format!("{ch}:{}", cursor(t2)), + r#"{"has_more":false,"next_cursor":null}"#.to_owned() + ) + ); + + let (rows, d, content) = page(window(json!({"direction":"newer"}))).await; + assert_eq!(rows, hex(&[t0, t1])); + assert_eq!(d, format!("{ch}:newer:head")); + assert_eq!( + serde_json::from_str::(&content).unwrap(), + json!({"direction":"newer","has_more":true, + "next_cursor":{"created_at":t1.created_at.as_secs(),"id":t1.id.to_hex()}}) + ); + let (rows, d, content) = page(window( + json!({"direction":"newer","after":t1.created_at.as_secs(),"after_id":t1.id.to_hex()}), + )) + .await; + assert_eq!(rows, hex(&[t2])); + assert_eq!(d, format!("{ch}:newer:{}", cursor(t1))); + assert_eq!( + serde_json::from_str::(&content).unwrap(), + json!({"direction":"newer","has_more":false,"next_cursor":null}) + ); + + for extra in [ + json!({"direction":"up"}), + json!({"after":1,"after_id":t1.id.to_hex()}), + json!({"direction":"newer","until":1,"before_id":t1.id.to_hex()}), + json!({"direction":"newer","after":1}), + json!({"direction":"newer","after":-1,"after_id":t1.id.to_hex()}), + json!({"direction":"newer","after":1,"after_id":"z".repeat(64)}), + ] { + let (status, body) = f + .post(&f.keys, "/query", json!([window(extra.clone())])) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{extra}: {body}"); + } +} + #[tokio::test] #[ignore = "requires Postgres"] async fn thread_window_real_query_denial_revocation_and_colliding_tenants() { @@ -417,12 +586,23 @@ async fn thread_window_real_query_validation_forgery_and_sql_failure() { ("depth_limit", json!(0)), ("authors", json!([f.keys.public_key().to_hex()])), ("page", json!(1)), + ("after", json!(1)), + ("after_id", json!("a".repeat(64))), + ("direction", json!("up")), + ("root_aux", json!("false")), ] { let mut filter = f.filter(); filter[key] = val; let (status, body) = f.post(&f.keys, "/query", json!([filter])).await; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); } + for (key, val) in [("until", json!(1)), ("before_id", json!("a".repeat(64)))] { + let mut filter = f.filter(); + filter["direction"] = json!("newer"); + filter[key] = val; + let (status, body) = f.post(&f.keys, "/query", json!([filter])).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + } let forged = event( &f.keys, f.channel, diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index e58ec300961..69a8725cee6 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -265,6 +265,8 @@ impl RelayInfo { // without it ignores the tag beside `visibility`, so a client // checks this before opening a channel as unlisted. "buzz-unlisted-channels".to_string(), + // NIP-CW `direction: "newer"` windows, read oldest first. + "buzz-window-newer".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -817,8 +819,8 @@ mod tests { } /// Clients refuse NIP-CL labels and system channels, newest-first - /// search, and unlisted channels unless the relay says it supports them, - /// so every document must advertise all three. + /// search, unlisted channels and oldest-first windows unless the relay + /// says it supports them, so every document must advertise all four. #[test] fn advertises_nip_cl_search_sort_and_unlisted_extensions() { let info = RelayInfo::build( @@ -834,6 +836,7 @@ mod tests { assert!(extensions.contains(&"nip-cl".to_string())); assert!(extensions.contains(&"buzz-search-sort".to_string())); assert!(extensions.contains(&"buzz-unlisted-channels".to_string())); + assert!(extensions.contains(&"buzz-window-newer".to_string())); } /// NIP-WP → NIP-11 mirror: a set workspace icon is served in the standard diff --git a/docs/bridge-channel-window.md b/docs/bridge-channel-window.md index 1f2470866ad..7d4376f4fa8 100644 --- a/docs/bridge-channel-window.md +++ b/docs/bridge-channel-window.md @@ -50,6 +50,14 @@ A standard bridge filter plus extension fields: of the last retained row from the previous page. **Both or neither.** `top_level` with `until` but no `before_id` is rejected (`400`): the window path has no timestamp-only fallback, ever. Neither = head request. +- `direction` — `"older"` (default) pages newest first; `"newer"` pages + oldest first, from the channel's first row. A relay that supports + `"newer"` advertises `buzz-window-newer` in NIP-11 + `supported_extensions`; clients send it only then. +- `after` + `after_id` — the `"newer"` cursor, with the same rules as + `until` + `before_id`: both or neither, no timestamp-only fallback. A + `"newer"` request with `until`/`before_id`, or an `"older"` one with + `after`/`after_id`, is rejected (`400`). - `include_summaries` / `include_aux` — opt-in overlay/closure appends. `page`/OFFSET is not honored on the window path. @@ -71,6 +79,12 @@ 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. +A `"newer"` window is the exact mirror: rows are ordered `(created_at ASC, +id DESC)`, and the keyset is +`created_at > $after OR (created_at = $after AND id < $after_id)`. Its +`next_cursor` is the last retained row, sent back as `after` + `after_id`. +Reading the same channel from both ends meets without a gap or overlap. + `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 @@ -114,6 +128,11 @@ Clients **partition by kind before any cursor math**: else `:` — 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. +- A `"newer"` page puts `newer:` before the suffix + (`:newer:head`, `:newer::`) + and adds `"direction":"newer"` to the content. An `"older"` page carries + neither, so its overlay is byte-identical to one from a relay without + `"newer"`. - Reserved field: `oldest_retained` (retention gap), added without a wire break if needed. - Same overlay rules as 39005: relay-signed, query-time, never stored, diff --git a/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index c5ad73ad66d..75ebe490cdc 100644 --- a/docs/nips/NIP-CW.md +++ b/docs/nips/NIP-CW.md @@ -13,7 +13,9 @@ Channel and Thread Windows This NIP defines two relay-computed, cursor-paged views served as ordinary signed Nostr events through extended NIP-01 filters: - **channel mode** pages a channel's top-level timeline; -- **thread mode** pages one root's descendants newest-first. +- **thread mode** pages one root's descendants. + +Both modes read newest first by default. A relay that advertises `buzz-window-newer` also reads them oldest first (§Direction). Both modes use stable keyset order and explicit relay-signed exhaustion bounds. A channel-mode request may also include the aux closure and thread-summary overlays: @@ -37,7 +39,7 @@ A relay that computes thread structure at ingest already knows which events are This NIP does not change ingest, storage, or fan-out. Rows returned in a window are ordinary stored events; the overlays are computed per query and never stored. -This NIP does not define around-target retrieval or cross-page snapshot isolation. It defines protocol compatibility and fallback rules, but the Buzz thread-mode implementation ships no client opt-in or fallback implementation. Thread mode starts at the newest reply and continues toward older replies. +This NIP does not define around-target retrieval or cross-page snapshot isolation. It defines protocol compatibility and fallback rules, but the Buzz thread-mode implementation ships no client opt-in or fallback implementation. A window starts at one end of its channel or thread: the newest row, or the oldest (§Direction). It never starts at an arbitrary target. This NIP does not require WebSocket REQ support. A relay MAY serve window filters only on an HTTP query surface and ignore the extension fields on REQ (see §Degradation). @@ -52,6 +54,21 @@ This document uses MUST, MUST NOT, SHOULD, MAY, and RECOMMENDED as defined in RF - **composite cursor**: The pair `(created_at, id)` identifying a position in the total order. `created_at` is unix seconds; `id` is a 64-character lowercase hex event id. - **scan position**: The composite cursor of the last event the relay's query *retained*, whether or not that event was ultimately delivered as a row (see §Channel-mode Relay Processing Algorithm step 3). The cursor tracks where the scan stopped, not what the client received. +## Direction + +Both modes accept an optional `direction` field: `"older"` (the default) or `"newer"`. Any other value MUST be rejected. + +| | `"older"` (default) | `"newer"` | +|---|---|---| +| first page | the newest rows | the oldest rows | +| total order | `created_at DESC, id ASC` | `created_at ASC, id DESC` | +| cursor fields | `until` + `before_id` | `after` + `after_id` | +| rows after cursor `(ts, id)` | `created_at < ts OR (created_at = ts AND id > id)` | `created_at > ts OR (created_at = ts AND id < id)` | + +The `"newer"` order is the exact reverse of the `"older"` order, so a client can read a channel or thread from both ends and meet without a gap or an overlap. `after` and `after_id` have the same grammar and rules as `until` and `before_id`: both or neither, `after` a non-negative integer of unix seconds, `after_id` exactly 64 hexadecimal characters. A `"newer"` request with `until` or `before_id`, or an `"older"` request (or one without `direction`) with `after` or `after_id`, MUST be rejected. `next_cursor` is the scan position in the request's own order; the client echoes it in that direction's cursor fields. `limit`, `kinds`, `has_more`, the aux closure and summaries mean the same in both directions. + +A relay that supports `"newer"` SHOULD advertise `"buzz-window-newer"` in its NIP-11 `supported_extensions`. A client MUST NOT send `direction`, `after`, `after_id` or `root_aux` to a relay that does not advertise it; without it, the client reads newest first only. + ## Channel-mode Request A channel-mode window request is a standard filter plus extension fields, submitted wherever the relay accepts filters (for Buzz: the NIP-98-authenticated HTTP bridge `POST /query`): @@ -74,6 +91,7 @@ A channel-mode window request is a standard filter plus extension fields, submit - `limit` — the row budget. Overlays and aux events MUST NOT count against it. Relays SHOULD clamp it to a documented range (Buzz: default 50, maximum 200, minimum 1). - `until` + `before_id` — the request cursor: the `next_cursor` from the previous page's `kind:39006` overlay, echoed verbatim — `until` = `next_cursor.created_at`, `before_id` = `next_cursor.id`. **Both present or both absent.** Exactly one present MUST be rejected: a timestamp-only cursor silently loses or duplicates same-second rows, which is the failure mode this NIP exists to remove. Both absent = head-of-channel request. - `kinds` — optional; restricts which kinds may be rows. It does not affect overlay or aux kinds. +- `direction`, `after` + `after_id` — optional; read the channel oldest first (§Direction). Cursor grammar: `until` MUST be a non-negative integer of unix seconds representable by the relay's timestamp type; `before_id` MUST be exactly 64 hexadecimal characters (the lowercase form emitted in `next_cursor.id` is canonical). A malformed value MUST cause rejection of the request — it MUST NOT be ignored and demoted to a half cursor or a head request. @@ -98,7 +116,7 @@ Storage fallback (fail-open): a relay that indexes this classification at ingest For a valid window filter on an accessible channel (§Channel-mode Access Scoping) the relay MUST: -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)`. +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)`. A `"newer"` request uses that direction's order and keyset instead (§Direction). 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). @@ -159,13 +177,14 @@ Exactly one per served window response. The **only** authority on exhaustion. Ta ``` - `d`-tag suffix (canonical serialization): the literal string `head` for a head request, else `:` — decimal unix seconds, colon, full 64-character lowercase hex id — identifying the *request* cursor this page answered. Clients MUST verify the suffix equals the cursor they sent and discard the overlay (and the page) on mismatch; this binds each bounds overlay to its request and makes concurrent-page responses unambiguous. -- `next_cursor` — the composite cursor to echo as `until` + `before_id` for the next page, or `null` iff `has_more` is `false`. +- `next_cursor` — the composite cursor to echo as `until` + `before_id` (`after` + `after_id` for `"newer"`) for the next page, or `null` iff `has_more` is `false`. +- A `"newer"` page puts `newer:` before the suffix — `:newer:head` or `:newer::` — and adds `"direction":"newer"` to the content. An `"older"` page has neither, so its overlay is byte-identical to one from a relay without `"newer"`. Clients MUST verify both, so a page from one direction can never be taken for one from the other. - Reserved: an `oldest_retained` content field may be added (retention gap signaling) without a wire break. Clients MUST ignore unknown content fields. ## Channel-mode Client Behavior 1. **Head request**: send the window filter with no cursor. Render rows in received order. -2. **Continue**: read `kind:39006`; if `has_more`, send the same filter with `until = next_cursor.created_at`, `before_id = next_cursor.id`. Repeat until `has_more = false`. +2. **Continue**: read `kind:39006`; if `has_more`, send the same filter with `until = next_cursor.created_at`, `before_id = next_cursor.id` (`after` and `after_id` for `"newer"`). Repeat until `has_more = false`. 3. **Exhaustion**: `39006.has_more` is the only exhaustion signal. `rows < limit` proves nothing — an exact-multiple final page returns `limit` rows with `has_more = false`, and predicate filtering can shrink any page. A client MUST NOT stop paging on row count, and MUST NOT treat a full page as "more available." 4. **Immutability**: fetched pages are immutable history chained cursor→cursor. New live events MUST NOT be spliced into fetched pages; deliver them through a separate live subscription (`since: now`) and merge at render time. On reconnect, refetch the head page and re-arm the live subscription; deeper pages need no repair. 5. **Bounds integrity**: a window response missing its `kind:39006`, or carrying more than one, or carrying one whose `d`-tag binding does not echo the request cursor, whose content is not parseable JSON, or whose content violates `has_more = true ⇔ next_cursor ≠ null`, is not a usable page — the client MUST discard it (and MAY retry) rather than guess at exhaustion. Clients SHOULD additionally reject overlays that violate the exact tag cardinality of §Channel-mode Overlay Event Formats or whose content fields have the wrong runtime types (hardening against a malformed or hostile serializer). Cryptographic verification is governed by §Overlay Trust. @@ -201,7 +220,7 @@ with `thread_window` absent or false: `threadCursor` and `threadCursorId` are also accepted. - Timestamp-only continuation remains accepted for compatibility but skips other replies in the same second; clients SHOULD send the composite pair. -- This path traverses stored thread metadata, not the newest-first mode's strict +- This path traverses stored thread metadata, not thread mode's strict row-kind filter. Clients SHOULD supply explicit `kinds` for query authorization but MUST NOT assume this legacy thread path restricts its reply rows by them. - `include_aux` appends root/reply reactions, edits and deletions, followed by @@ -245,7 +264,8 @@ difference is intended. ## Thread Mode -`thread_window: true` requests a newest-first page of replies to one root. It is +`thread_window: true` requests a page of replies to one root, newest first unless +`direction` is `"newer"` (§Direction). It is served through Buzz's NIP-98-authenticated `POST /query`; channel mode, `kind:39006`, and the legacy oldest-first thread path are unchanged. The response is a flat array of reply events, optional auxiliary events, and exactly one @@ -273,7 +293,10 @@ four entries from `9`, `40002`, `45001`, and `45003`; relays normalize them to a sorted, distinct list. `limit` defaults to 50 and MUST be 1–200; `depth_limit` defaults to 100 and MUST be 1–100; `include_aux` defaults to false. A continuation MUST provide both `until` and `before_id`, or neither for -the head page. Unknown fields, malformed values, and mixing thread windows with +the head page; a `"newer"` request uses `after` and `after_id` instead +(§Direction). `root_aux` is an optional boolean, default `true`; `false` leaves +the root's own edits, reactions and deletions out of the aux closure, so a client +reads them once, on its first page, rather than on every page. Unknown fields, malformed values, and mixing thread windows with another query mode MUST be rejected. A query MAY contain at most four window filters. @@ -289,13 +312,15 @@ For an authorized request the relay MUST: 2. Select non-deleted replies in that channel at depths 1 through `depth_limit`, restricted by `kinds`, ordered by `created_at DESC, id ASC`. A continuation retains rows where `created_at < until OR (created_at = until - AND id > before_id)`. + AND id > before_id)`. A `"newer"` request orders by `created_at ASC, id DESC` + and retains rows where `created_at > after OR (created_at = after AND + id < after_id)`. 3. Evaluate `limit + 1` after all predicates. Discard the extra row and set `has_more`; when more rows exist, `next_cursor` is the last retained scan candidate, captured before event reconstruction. Otherwise it is `null`. 4. If `include_aux` is true, append reactions (`kind:7`), deletions - (`kind:5`/`9005`), and edits (`kind:40003`) targeting the root or returned - replies, followed by deletions targeting those auxiliary events. Preserve + (`kind:5`/`9005`), and edits (`kind:40003`) targeting the root (unless + `root_aux` is `false`) or returned replies, followed by deletions targeting those auxiliary events. Preserve 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. @@ -349,15 +374,29 @@ The binding is SHA-256 over compact UTF-8 JSON of this ordered array: ```jsonc ["tw",1,"older","","","","",50,100,[9,40002],null,true] -// host, reader, channel, root, limit, depth, sorted kinds, request cursor, include_aux +// direction, host, reader, channel, root, limit, depth, sorted kinds, request cursor, include_aux // cursor is null or [,""] ``` +For `"older"` (or no `direction`) and `root_aux` `true` (or absent), the array +is exactly as above, so these bindings keep their hashes. A `"newer"` request +puts `"newer"` in place of `"older"` and its cursor element carries +`[,""]`. `root_aux: false` appends one trailing element, +`"root_aux:false"`: + +```jsonc +["tw",1,"newer","","","","",50,100,[9],[1751500000,""],true,"root_aux:false"] +``` + +The content's `direction` is the request's: `"older"` or `"newer"`. For a +`"newer"` page, `next_cursor` is the next `after` cursor. + `host` is the server-resolved normalized authority and `reader` is the authenticated lowercase pubkey. Clients MUST verify the expected relay signer and signature, exact tags and request binding, version, direction, and `next_cursor == null` iff `has_more == false`. Only validated bounds determine -exhaustion; clients MUST echo `next_cursor` as `until` and `before_id`. +exhaustion; clients MUST echo `next_cursor` as `until` and `before_id` (`after` +and `after_id` for `"newer"`). An extension-unaware relay may return legacy oldest-first history without bounds. A client that explicitly falls back MUST restart with clean legacy @@ -373,7 +412,7 @@ The channel-mode extension fields in this NIP are *additional* keys on a standar - **Extension-unaware relay**: a tolerant filter parser (one that ignores unknown keys, as common NIP-01 implementations do) serves the filter as a plain `kinds` + `#h` query — a complete, correct, standard event stream. A strict parser may instead reject the filter outright. Both are safe: neither produces a wrong-but-plausible top-level timeline. A client MUST treat *either* signal — a response with no valid `kind:39006`, or an error/unsupported-filter response — as a downgrade, and fall back by reissuing a clean standard filter with all extension keys removed and assembling threads client-side. (Buzz's own WebSocket REQ path is such a tolerant parser: the filter deserializer drops the extension fields, so a window filter on REQ serves the standard query.) - **Extension-unaware client**: never sends `top_level`, never sees an overlay kind, and observes a completely standard relay. -A relay implementing this NIP MAY advertise it in its NIP-11 relay information document; the discovery mechanism is out of scope for this NIP. A client needs no advertisement to probe safely: send one head window request and apply the downgrade rule above — the presence of a valid `kind:39006` is the capability signal. +A relay implementing this NIP MAY advertise it in its NIP-11 relay information document; the discovery mechanism is out of scope for this NIP, except for `"newer"` windows, which a client sends only to a relay that advertises `buzz-window-newer` (§Direction). A client needs no advertisement to probe safely: send one head window request and apply the downgrade rule above — the presence of a valid `kind:39006` is the capability signal. ## Security and Privacy Considerations @@ -395,7 +434,7 @@ A channel-mode client with neither an authenticated transport nor a verifiable r ## Implementation Gotchas - The `limit + 1` probe MUST run after *all* predicates: access, deletion and `kinds` in both modes; top-level classification in channel mode only; root, channel and depth restrictions in thread mode. A probe over a superset produces false `has_more = true` on the last page. -- The cursor comparison uses `id > $id` (bytewise ascending) because the total order is `created_at DESC, id ASC`. Getting the id inequality backwards drops or duplicates same-second rows — precisely the bug the composite cursor removes. +- The cursor comparison uses `id > $id` (bytewise ascending) because the total order is `created_at DESC, id ASC`. Getting the id inequality backwards drops or duplicates same-second rows — precisely the bug the composite cursor removes. The `"newer"` order reverses both comparisons: `created_at > $ts OR (created_at = $ts AND id < $id)`. - `next_cursor` is the last retained *scan candidate*, not the last delivered row: capture the scan position before per-event reconstruction so a skipped event cannot stall pagination. Clients echo it verbatim and never derive or validate it against the rows they received. - **Channel mode only:** events ingested before the relay computed thread metadata have no depth; they MUST be treated as top-level rather than vanishing from channel windows. Thread mode instead requires metadata at depths 1..`depth_limit`. - The `d` tag on `39006` differs per request cursor by design: concurrent pages of one channel coexist in a replaceable-event cache instead of clobbering each other. The per-channel-singleton alternative would make page N overwrite page N+1's bounds.