From 3fab9ce0fa7f7decc3873fe74953b501d798d4e9 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Tue, 17 Nov 2026 01:25:31 -0500 Subject: [PATCH 01/12] 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/event.rs | 2 + crates/buzz-db/src/store/recent_pass.rs | 377 ++++++++++- crates/buzz-db/src/store/thread.rs | 613 +++++++++++++++--- 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 | 8 +- docs/bridge-channel-window.md | 19 + docs/nips/NIP-CW.md | 69 +- 14 files changed, 1560 insertions(+), 212 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 667c906b4bd..3a6b6765d1c 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/event.rs b/crates/buzz-db/src/store/event.rs index 59b0222c9bf..7d93bdb4191 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -5127,6 +5127,7 @@ mod postgres_tests { community, channel, LIMIT as u32, + buzz_core::thread_window::Direction::Older, window_cursor, Some(&[9]), ReadDeadline::PerRead, @@ -5175,6 +5176,7 @@ mod postgres_tests { community, channel, LIMIT as u32, + buzz_core::thread_window::Direction::Older, cursor, Some(&[9]), ) 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 4ad9db702ec..29ed74c372a 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,16 +642,21 @@ 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. The redundant inclusive timestamp bound + // gives PostgreSQL an index range start instead of filtering every row + // before a deep cursor. + let (order, start, 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). - // The redundant upper bound gives PostgreSQL an index range start - // instead of filtering every newer row at a deep cursor. let ts_idx = param_idx; let id_idx = param_idx + 1; sql.push_str(&format!( - " AND e.created_at <= ${ts_idx} \ - AND (e.created_at < ${ts_idx} OR (e.created_at = ${ts_idx} AND e.id > ${id_idx}))" + " AND e.created_at {start} ${ts_idx} \ + AND (e.created_at {past} ${ts_idx} OR (e.created_at = ${ts_idx} AND e.id {tiebreak} ${id_idx}))" )); param_idx += 2; } @@ -665,15 +674,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| { @@ -681,9 +713,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); @@ -692,8 +722,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), @@ -701,12 +731,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); @@ -1068,7 +1098,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. @@ -1080,9 +1111,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 @@ -1098,7 +1136,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 @@ -1119,18 +1158,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? @@ -1141,6 +1181,7 @@ impl Db { community_id, channel_id, limit, + direction, cursor.clone(), kind_filter, crate::event::ReadDeadline::Session, @@ -1188,6 +1229,7 @@ impl Db { community_id, channel_id, limit, + direction, cursor, kind_filter, ) @@ -2132,6 +2174,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, @@ -2199,9 +2256,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 @@ -2261,29 +2326,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 @@ -2314,22 +2382,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 @@ -2392,6 +2470,7 @@ mod postgres_tests { community, channel.id, 1, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2411,6 +2490,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2429,6 +2509,7 @@ mod postgres_tests { community, channel.id, 4, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2442,6 +2523,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2455,6 +2537,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, Some(cursor), None, ReadDeadline::PerRead, @@ -2503,6 +2586,7 @@ mod postgres_tests { community, channel.id, 1, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2515,6 +2599,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2532,6 +2617,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. @@ -2562,6 +2993,7 @@ mod postgres_tests { community, channel_id, 10, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2656,7 +3088,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 { @@ -2741,9 +3182,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 @@ -2841,9 +3290,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 39a2ab97181..fb19eee9fa3 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) @@ -2166,7 +2189,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, @@ -4530,7 +4553,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"), } @@ -4539,31 +4562,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 7feb2e4c5d9..81d5e3f3cee 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -267,6 +267,8 @@ impl RelayInfo { "buzz-unlisted-channels".to_string(), // kind:9050 edits an existing Solo member's access. "buzz-solo-member-role".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()); @@ -819,8 +821,9 @@ mod tests { } /// Clients refuse NIP-CL labels and system channels, newest-first - /// search, unlisted channels, and Solo role edits unless the relay says it - /// supports them, so every document must advertise these extensions. + /// search, unlisted channels, Solo role edits and oldest-first windows + /// unless the relay says it supports them, so every document must + /// advertise these extensions. #[test] fn advertises_channel_and_search_extensions() { let info = RelayInfo::build( @@ -837,6 +840,7 @@ mod tests { assert!(extensions.contains(&"buzz-search-sort".to_string())); assert!(extensions.contains(&"buzz-unlisted-channels".to_string())); assert!(extensions.contains(&"buzz-solo-member-role".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. From 3cc7aeef4013ff9a8d0735723685dcb1bda34d16 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Wed, 18 Nov 2026 01:57:44 -0500 Subject: [PATCH 02/12] test(db): share the oldest-first window tests' setup The two Postgres tests of oldest-first windows built the same dated channel, paged with the same eight-argument read, and locked partitions the same way. They now share helpers for each, with the same assertions. 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-db/src/store/thread.rs | 449 +++++++++++++---------------- 1 file changed, 204 insertions(+), 245 deletions(-) diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 29ed74c372a..6a5885220fd 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -2189,6 +2189,142 @@ mod postgres_tests { .expect("backdate channel"); } + /// Seconds since the epoch at an RFC 3339 time. + fn unix(rfc3339: &str) -> u64 { + DateTime::parse_from_rfc3339(rfc3339) + .expect("date") + .timestamp() as u64 + } + + /// A channel created at `created` holding a top-level row by `author` at + /// each of `times`: its id, its community and the rows, in `times` order. + async fn dated_channel( + pool: &PgPool, + author: &Keys, + created: &str, + times: &[u64], + ) -> (Uuid, CommunityId, Vec) { + let (channel, community) = create_test_channel( + pool, + &format!("dated-{}", 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, created).await; + let mut rows = Vec::new(); + for &created_at in times { + let event = EventBuilder::new(Kind::Custom(9), format!("at {created_at}")) + .custom_created_at(nostr::Timestamp::from(created_at)) + .sign_with_keys(author) + .expect("sign"); + insert_historical_root(pool, community, channel.id, &event).await; + rows.push(event); + } + (channel.id, community, rows) + } + + /// The cursor of a window page that ends at `event`. + fn cursor_at(event: &nostr::Event) -> Option<(DateTime, Vec)> { + Some((event_created_at(event), event.id.as_bytes().to_vec())) + } + + /// An oldest-first window page: from the head, or after `cursor`. + async fn newer_page( + conn: &mut sqlx::PgConnection, + community: CommunityId, + channel_id: Uuid, + limit: u32, + cursor: Option<(DateTime, Vec)>, + ) -> Result { + get_channel_window_on( + conn, + community, + channel_id, + limit, + Direction::Newer, + cursor, + None, + ReadDeadline::PerRead, + ) + .await + } + + fn row_ids(window: &ChannelWindow) -> Vec { + window + .rows + .iter() + .map(|r| r.stored_event.event.id) + .collect() + } + + /// The partitions holding `ids`, which the fixture must put in distinct + /// ones. + async fn distinct_partitions( + pool: &PgPool, + ids: [nostr::EventId; N], + ) -> [String; N] { + let mut partitions = Vec::with_capacity(N); + for id in ids { + partitions.push( + 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 distinct = partitions + .iter() + .collect::>() + .len(); + assert_eq!( + distinct, N, + "fixture rows must sit in distinct partitions: {partitions:?}" + ); + partitions.try_into().expect("a partition per row") + } + + /// Another session locks `partitions`, and reads on `conn` give up on a + /// lock after 200 ms, until [`unlock`]. + async fn lock( + pool: &PgPool, + conn: &mut sqlx::PgConnection, + partitions: impl IntoIterator, + ) -> sqlx::Transaction<'static, sqlx::Postgres> { + let mut locker = pool.begin().await.expect("begin locker"); + for partition in partitions { + 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"); + locker + } + + async fn unlock( + locker: sqlx::Transaction<'static, sqlx::Postgres>, + conn: &mut sqlx::PgConnection, + ) { + locker.rollback().await.expect("release locks"); + sqlx::query("RESET lock_timeout") + .execute(&mut *conn) + .await + .expect("reset lock_timeout"); + } + /// Insert a depth-1 reply under `root`, with the given broadcast flag. async fn insert_reply( pool: &PgPool, @@ -2624,73 +2760,34 @@ mod postgres_tests { #[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( + let (channel, community, oldest_first) = dated_channel( &pool, - &format!("window-newer-{}", Uuid::new_v4()), - ChannelType::Stream, - ChannelVisibility::Open, - None, - author.public_key().to_bytes().as_slice(), - None, + &Keys::generate(), + "2025-05-15T00:00:00Z", + &[ + unix("2025-06-01T00:00:00Z"), + unix("2026-03-10T12:00:00Z"), + unix("2026-03-20T12:00:00Z"), + unix("2026-04-20T12:00:00Z"), + unix("2026-06-15T12:00:00Z"), + Utc::now().timestamp() as u64 - 10, + ], ) - .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::>() - }; + .await; 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)); + let window = newer_page(&mut conn, community, channel, 2, cursor) + .await + .expect("forward page"); + pages.push(row_ids(&window)); if !window.has_more { break; } @@ -2702,92 +2799,35 @@ mod postgres_tests { // 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) + let [oldest, _march, _april, june] = + distinct_partitions(&pool, [0, 1, 3, 4].map(|at| oldest_first[at].id)).await; + let locker = lock(&pool, &mut conn, [oldest, june]).await; + let after_march = || cursor_at(&oldest_first[1]); + let window = newer_page(&mut conn, community, channel, 1, after_march()) .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)); + .expect("a full early pass never touches the locked partitions"); + assert_eq!(row_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; + let failed = newer_page(&mut conn, community, channel, 2, after_march()).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"); + unlock(locker, &mut conn).await; // 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( + let window = newer_page( &mut conn, community, - channel.id, + channel, 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)); + assert_eq!((row_ids(&window), window.has_more), (expected(rows), more)); } } @@ -2799,81 +2839,32 @@ mod postgres_tests { #[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); - } + let (channel, community, oldest_first) = dated_channel( + &pool, + &author, + "2026-01-10T00:00:00Z", + &[ + unix("2026-01-12T00:00:00Z"), + unix("2026-01-20T00:00:00Z"), + unix("2026-03-10T12:00:00Z"), + unix("2026-04-20T12:00:00Z"), + unix("2026-06-15T12:00:00Z"), + Utc::now().timestamp() as u64 - 10, + ], + ) + .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 (_, _, below) = dated_channel( + &pool, + &author, + "2025-05-15T00:00:00Z", + &[unix("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 { @@ -2882,18 +2873,17 @@ mod postgres_tests { AND deleted_at IS NULL ORDER BY created_at ASC, id DESC LIMIT $3", ) .bind(community.as_uuid()) - .bind(channel.id) + .bind(channel) .bind(i64::from(limit)) .fetch_all(&pool) .await .expect("unbounded read"); - let window = head(&mut conn, community, channel_id, limit) + let window = newer_page(&mut conn, community, channel, limit, None) .await .expect("head page"); - let ids: Vec<_> = window - .rows + let ids: Vec<_> = row_ids(&window) .iter() - .map(|r| r.stored_event.event.id.as_bytes().to_vec()) + .map(|id| id.as_bytes().to_vec()) .collect(); assert_eq!(ids, unbounded, "limit {limit}"); assert_eq!(window.has_more, (limit as usize) < oldest_first.len()); @@ -2901,66 +2891,35 @@ mod postgres_tests { // 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"); + let [below, _first, june, newest] = distinct_partitions( + &pool, + [ + below[0].id, + oldest_first[0].id, + oldest_first[4].id, + oldest_first[5].id, + ], + ) + .await; + let locker = lock(&pool, &mut conn, [below, june, newest]).await; // 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) + let window = newer_page(&mut conn, community, channel, limit, None) .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_eq!(row_ids(&window), expected, "limit {limit}"); assert!(window.has_more, "limit {limit}"); } - let failed = head(&mut conn, community, channel_id, 4).await; + let failed = newer_page(&mut conn, community, channel, 4, None).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"); + unlock(locker, &mut conn).await; } /// The window's passes share one snapshot: a replacement that commits From d9d2770b51b23d7ff3b86a3b1fec45257ec924c4 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Wed, 18 Nov 2026 02:16:43 -0500 Subject: [PATCH 03/12] docs(nip-cw): say when reading from both ends meets A row accepted with a past created_at after a newer page was served can sort behind that page's cursor, so the gapless meeting holds only while no rows are being written. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- docs/bridge-channel-window.md | 5 ++++- docs/nips/NIP-CW.md | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/bridge-channel-window.md b/docs/bridge-channel-window.md index 7d4376f4fa8..e43bfcb706e 100644 --- a/docs/bridge-channel-window.md +++ b/docs/bridge-channel-window.md @@ -83,7 +83,10 @@ 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. +Reading the same channel from both ends meets without a gap or overlap +while no rows are being written. A row accepted with a past `created_at` +after a page was served can sort behind that page's cursor; see NIP-CW +§Direction. `has_more` is a **server fact**: the relay probes `limit + 1` rows after all predicates (access, deletion, top-level, kinds), returns at most diff --git a/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index 75ebe490cdc..0ed07929fdc 100644 --- a/docs/nips/NIP-CW.md +++ b/docs/nips/NIP-CW.md @@ -65,7 +65,7 @@ Both modes accept an optional `direction` field: `"older"` (the default) or `"ne | 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. +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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), so a row written after a `"newer"` page was served can sort behind that page's cursor and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present keeps a live subscription, or reads the newest stretch again. `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. From 3870fe99bc4e48b0f69fc27c60f3ae077f7ff719 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Wed, 18 Nov 2026 21:40:14 -0500 Subject: [PATCH 04/12] fix(db): start every oldest-first channel page at the channel floor A continuation page walked forward two months at a time from its cursor's month with no lower limit, so a cursor at 0 walked from 1970: hundreds of statements, each with its own SQL text. Every page now starts at the later of its cursor and the channel's floor, so a page walks at most one window per two months of the channel's life. Tests cover a row inside the 960 s allowance before the channel's creation on the head page, and a cursor below the floor, which must not plan the partitions under it. The floor rule is documented beside the replica fence's created_at floor, which it rests on. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-db/src/runtime/replica_fence.rs | 6 ++ crates/buzz-db/src/runtime/tests.rs | 8 ++ crates/buzz-db/src/store/recent_pass.rs | 25 +++--- crates/buzz-db/src/store/thread.rs | 85 +++++++++++++++++---- 4 files changed, 100 insertions(+), 24 deletions(-) diff --git a/crates/buzz-db/src/runtime/replica_fence.rs b/crates/buzz-db/src/runtime/replica_fence.rs index c86c8701122..1e3625e6059 100644 --- a/crates/buzz-db/src/runtime/replica_fence.rs +++ b/crates/buzz-db/src/runtime/replica_fence.rs @@ -60,6 +60,12 @@ //! Raw SQL and `session_replication_role = replica` restores bypass the //! application floor check. These operational bypasses are outside the proof //! and require holding the fence closed. +//! +//! Oldest-first channel windows rest on the same floor: a page starts its +//! walk in the month of the channel's creation less [`CREATED_AT_FLOOR_SECS`] +//! (`recent_pass::channel_floor`). A bypass that stores a row in an earlier +//! month also hides it from those reads, which newest-first reads still +//! return. use std::collections::VecDeque; use std::sync::{Arc, Mutex}; diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index 3a6b6765d1c..10ed9f53acf 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -996,6 +996,14 @@ async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { // Shared history (both databases): m1 < m2 < m3. let base = 1_700_000_000u64; + for pool in [&writer, &replica] { + sqlx::query("UPDATE channels SET created_at = $1 WHERE id = $2") + .bind(chrono::DateTime::from_timestamp(base as i64 - 3600, 0).unwrap()) + .bind(channel) + .execute(pool) + .await + .expect("date the channel before its history"); + } let m1 = signed_event_at(&author, "m1", base); let m2 = signed_event_at(&author, "m2", base + 10); let m3 = signed_event_at(&author, "m3", base + 20); diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs index f6b86d26460..adf171b16e2 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -38,10 +38,11 @@ //! 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. +//! stops at the same ceiling; any other read ends with one open window. For a +//! channel read the earliest possible row is [`channel_floor`], or the cursor +//! when that is later, so a page walks at most one window per two months of +//! the channel's life. A read without a floor plans every partition below the +//! ceiling in one window. //! //! 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 @@ -258,17 +259,21 @@ fn regular_only(kinds: Option<&[i32]>) -> bool { } /// 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. +/// floor the write path tolerates ([`CREATED_AT_FLOOR_SECS`]). `created_at` is +/// the database's `NOW()` when the channel row was inserted +/// (`schema/tables/public/channels.sql`), every write of a channel row checks +/// its `created_at` against the database clock, and the channel exists before +/// its first row, so no row of it is older. A write that bypasses that check +/// (see [`crate::replica_fence`]) can store older rows, and oldest-first reads +/// skip those in earlier months than the floor's. Its month starts the walk of +/// an oldest-first channel 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). +/// on the read's rows: [`channel_floor`], or the page's cursor when that is +/// later (`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, diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 6a5885220fd..6902ee6e544 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -685,20 +685,20 @@ pub(crate) async fn get_channel_window_on( .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), - }; + // Every page walks from the month of the channel's creation floor, + // or of its cursor when that is later: no row is older than the + // floor, so a cursor below it would only walk empty windows. Without the + // channel's row there is no floor, and one window unbounded below + // reads the page. + let floor = 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); + let earliest = floor.map(|floor| cursor_ts.map_or(floor, |ts| ts.max(floor))); Range::Forward(crate::store::recent_pass::oldest_for( Utc::now(), kinds.as_deref(), @@ -2922,6 +2922,63 @@ mod postgres_tests { unlock(locker, &mut conn).await; } + /// The head page reads rows written up to the write path's tolerance + /// before the channel was created, here in the month before it. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_newer_head_reads_rows_older_than_the_channel_within_the_floor() { + let pool = setup_pool().await; + let (channel, community, oldest_first) = dated_channel( + &pool, + &Keys::generate(), + "2026-03-01T00:05:00Z", + &[unix("2026-02-28T23:58:00Z"), unix("2026-03-02T00:00:00Z")], + ) + .await; + let mut conn = pool.acquire().await.expect("acquire"); + let window = newer_page(&mut conn, community, channel, 10, None) + .await + .expect("head page"); + let expected: Vec<_> = oldest_first.iter().map(|e| e.id).collect(); + assert_eq!(row_ids(&window), expected); + assert!(!window.has_more); + } + + /// A cursor older than the channel starts the walk at the channel's + /// floor, as the head page does, so the partitions below it are never + /// planned. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_newer_cursor_below_the_floor_walks_from_the_floor() { + let pool = setup_pool().await; + let author = Keys::generate(); + let (channel, community, oldest_first) = dated_channel( + &pool, + &author, + "2026-01-10T00:00:00Z", + &[unix("2026-01-12T00:00:00Z"), unix("2026-03-10T12:00:00Z")], + ) + .await; + // A row of another channel names a partition below the floor. + let (_, _, below) = dated_channel( + &pool, + &author, + "2025-05-15T00:00:00Z", + &[unix("2025-06-01T00:00:00Z")], + ) + .await; + let mut conn = pool.acquire().await.expect("acquire"); + let [below, _first] = distinct_partitions(&pool, [below[0].id, oldest_first[0].id]).await; + let locker = lock(&pool, &mut conn, [below]).await; + let epoch = Some((DateTime::::UNIX_EPOCH, vec![0u8; 32])); + let window = newer_page(&mut conn, community, channel, 10, epoch) + .await + .expect("a cursor below the floor never plans the partitions below it"); + let expected: Vec<_> = oldest_first.iter().map(|e| e.id).collect(); + assert_eq!(row_ids(&window), expected); + unlock(locker, &mut conn).await; + } + /// 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. From a6b71e9de213fbae8f324a30fd5e41bc27bc422c Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Wed, 18 Nov 2026 21:40:20 -0500 Subject: [PATCH 05/12] refactor(relay): drop root_aux from thread windows A plugin gets the same rows and the same edits, reactions and deletions with include_aux false and one read of the page's aux by #e, so the relay does not need a flag that leaves the root's aux out of later pages. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-core/src/thread_window.rs | 28 +++++-------------- .../src/api/bridge/thread_window.rs | 6 +--- .../bridge/thread_window/postgres_tests.rs | 15 +++++----- 3 files changed, 15 insertions(+), 34 deletions(-) diff --git a/crates/buzz-core/src/thread_window.rs b/crates/buzz-core/src/thread_window.rs index 75da0c08469..38a9bc26407 100644 --- a/crates/buzz-core/src/thread_window.rs +++ b/crates/buzz-core/src/thread_window.rs @@ -104,8 +104,6 @@ pub struct Request { 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 { @@ -152,7 +150,6 @@ impl Request { "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()); @@ -204,14 +201,12 @@ impl Request { )) } }; - let flag = |key: &str, default: bool| match raw.get(key) { - None => Ok(default), + let include_aux = match raw.get("include_aux") { + None => false, Some(v) => v .as_bool() - .ok_or_else(|| format!("thread_window: {key} must be boolean")), + .ok_or("thread_window: include_aux must be boolean")?, }; - let include_aux = flag("include_aux", false)?; - let root_aux = flag("root_aux", true)?; Ok(Self { channel, root, @@ -221,7 +216,6 @@ impl Request { direction, cursor, include_aux, - root_aux, }) } @@ -232,7 +226,7 @@ impl Request { /// 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 mut canonical = json!([ + let canonical = json!([ "tw", 1, self.direction.as_str(), @@ -246,9 +240,6 @@ 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())) @@ -272,7 +263,6 @@ 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)), @@ -355,7 +345,6 @@ mod tests { 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 [ @@ -363,7 +352,6 @@ mod tests { ("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()])), @@ -382,16 +370,15 @@ mod tests { assert_ne!(expected, binding(&changed)); } - /// `newer` and `root_aux:false` bind the canonical arrays NIP-CW specifies. + /// `newer` binds the canonical array NIP-CW specifies. #[test] - fn binding_encodes_direction_cursor_and_root_aux_as_specified() { + fn binding_encodes_direction_and_cursor_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, @@ -404,8 +391,7 @@ mod tests { 100, [9], [5, "ef".repeat(32)], - false, - "root_aux:false" + false ]); assert_eq!( Request::parse(&f).unwrap().binding(host, &reader), diff --git a/crates/buzz-relay/src/api/bridge/thread_window.rs b/crates/buzz-relay/src/api/bridge/thread_window.rs index aa17e0819aa..a6861dd1bff 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window.rs @@ -188,11 +188,7 @@ async fn query( let mut events = Vec::new(); let page_start_bytes = budget.bytes; budget.bytes += 2; - let mut targets: Vec = request - .root_aux - .then(|| request.root.clone()) - .into_iter() - .collect(); + let mut targets = vec![request.root.clone()]; for row in &window.rows { if !visible(row) { // This would contradict the SQL's channel and row-kind predicates. 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 40897a0f190..1090c35a02d 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 @@ -341,11 +341,11 @@ 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. +/// A newer window pages forward from the oldest reply; every page carries the +/// root's aux and its own rows' aux. #[tokio::test] #[ignore = "requires Postgres"] -async fn thread_window_newer_pages_forward_and_root_aux_is_optional() { +async fn thread_window_newer_pages_forward() { let f = Fixture::new().await; let mut replies = Vec::new(); for n in 0..51 { @@ -370,11 +370,10 @@ async fn thread_window_newer_pages_forward_and_root_aux_is_optional() { 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(&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!( @@ -382,12 +381,13 @@ async fn thread_window_newer_pages_forward_and_root_aux_is_optional() { (&json!(false), &Value::Null) ); - // Past the last reply, a page without the root's aux is the bounds alone. + // Past the last reply, a page is the root's aux and the bounds. 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!(ids(&page, None)[0], root_edit.id.to_hex(), "{page}"); + assert_eq!(page.as_array().unwrap().len(), 2, "{page}"); assert_eq!(f.bounds(&page, &end)["has_more"], false); } @@ -589,7 +589,6 @@ async fn thread_window_real_query_validation_forgery_and_sql_failure() { ("after", json!(1)), ("after_id", json!("a".repeat(64))), ("direction", json!("up")), - ("root_aux", json!("false")), ] { let mut filter = f.filter(); filter[key] = val; From 332010963060c6df87a44129ff28f8ea69c9607a Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Wed, 18 Nov 2026 21:40:25 -0500 Subject: [PATCH 06/12] docs(nip-cw): start the late-row subscription before the scan Live delivery drops rows older than a subscription's since, so a subscription opened with since: now misses the same late rows an oldest-first scan misses. Drop root_aux from the spec. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- docs/bridge-channel-window.md | 5 ++++- docs/nips/NIP-CW.md | 24 ++++++++++-------------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/docs/bridge-channel-window.md b/docs/bridge-channel-window.md index e43bfcb706e..6b4645f57d1 100644 --- a/docs/bridge-channel-window.md +++ b/docs/bridge-channel-window.md @@ -148,7 +148,10 @@ Both kinds are relay-only: client submission is rejected at ingest. - Pages are immutable authoritative history chained cursor→cursor; live events land in a separate overlay, never spliced into pages. - Reconnect refetches page 0 and re-arms the live subscription - (`since: now`); deeper pages need no repair path. + (`since: now`); deeper pages need no repair path. An oldest-first + (`direction: "newer"`) reader follows NIP-CW's direction rules instead: + its subscription starts before the scan, and on reconnect it reads the + newest rows it missed newest first. - Replies never enter the channel timeline; the thread panel uses the existing `thread_cursor` surface (#1418). Thread filters may opt into `include_aux` to append the same authorized two-hop reactions, edits, and diff --git a/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index 0ed07929fdc..e547f0c19b7 100644 --- a/docs/nips/NIP-CW.md +++ b/docs/nips/NIP-CW.md @@ -65,9 +65,9 @@ Both modes accept an optional `direction` field: `"older"` (the default) or `"ne | 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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), so a row written after a `"newer"` page was served can sort behind that page's cursor and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present keeps a live subscription, or reads the newest stretch again. `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. +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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), so a row written after a `"newer"` page was served can sort behind that page's cursor and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present either reads the newest stretch again or keeps a live subscription that starts before the scan: live delivery also drops rows older than the subscription's `since`, so its `since` MUST be at least as far before the first page's request as the relay accepts past timestamps (900 seconds for Buzz). A subscription with `since: now` misses the same late rows. `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. +A relay that supports `"newer"` SHOULD advertise `"buzz-window-newer"` in its NIP-11 `supported_extensions`. A client MUST NOT send `direction`, `after` or `after_id` to a relay that does not advertise it; without it, the client reads newest first only. ## Channel-mode Request @@ -186,7 +186,7 @@ Exactly one per served window response. The **only** authority on exhaustion. Ta 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` (`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. +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. A `"newer"` reader instead starts its subscription before the scan, as §Direction says, and its head page holds the oldest rows: on reconnect it reads the newest rows it missed with `"older"` pages, then re-arms the subscription. 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. 6. **Overlays are metadata**: never render a `39005`/`39006` as a message, never feed one into cursor math, and key cached summaries by their `d` tag (latest wins). @@ -294,9 +294,7 @@ 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; 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 +(§Direction). Unknown fields, malformed values, and mixing thread windows with another query mode MUST be rejected. A query MAY contain at most four window filters. @@ -319,8 +317,8 @@ For an authorized request the relay MUST: `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 (unless - `root_aux` is `false`) or returned replies, followed by deletions targeting those auxiliary events. Preserve + (`kind:5`/`9005`), and edits (`kind:40003`) targeting the root 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. @@ -378,14 +376,12 @@ The binding is SHA-256 over compact UTF-8 JSON of this ordered array: // 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"`: +For `"older"` (or no `direction`) 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 `[,""]`: ```jsonc -["tw",1,"newer","","","","",50,100,[9],[1751500000,""],true,"root_aux:false"] +["tw",1,"newer","","","","",50,100,[9],[1751500000,""],true] ``` The content's `direction` is the request's: `"older"` or `"newer"`. For a From c505063f7a8151175747f6b35db65ee58f2753e1 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Thu, 19 Nov 2026 01:20:10 -0500 Subject: [PATCH 07/12] fix(db): walk a newer page from its cursor without the channel row When the channel's row is not visible to the connection, as on a replica behind the writer, there is no floor, and the clamp dropped the cursor too: a continuation page read one window unbounded below and planned every partition up to the ceiling. Fall back to the cursor, as before the clamp. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-db/src/store/recent_pass.rs | 8 ++-- crates/buzz-db/src/store/thread.rs | 53 +++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs index adf171b16e2..2bfc4c93df2 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -41,8 +41,9 @@ //! stops at the same ceiling; any other read ends with one open window. For a //! channel read the earliest possible row is [`channel_floor`], or the cursor //! when that is later, so a page walks at most one window per two months of -//! the channel's life. A read without a floor plans every partition below the -//! ceiling in one window. +//! the channel's life. Without the channel's row a page walks from its cursor, +//! and a read with neither plans every partition below the ceiling in one +//! window. //! //! 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 @@ -273,7 +274,8 @@ pub(crate) fn channel_floor(channel_created_at: DateTime) -> DateTime /// The first window of an oldest-first page read. `earliest` is a lower bound /// on the read's rows: [`channel_floor`], or the page's cursor when that is -/// later (`None`: the read has no bound and its first window is unbounded below). +/// later or there is no floor (`None`: the read has neither, and its first +/// window is unbounded below). /// `kinds` are the read's kinds (`None`: any). pub(crate) fn oldest_for( now: DateTime, diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 6902ee6e544..61b87f5a868 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -688,8 +688,8 @@ pub(crate) async fn get_channel_window_on( // Every page walks from the month of the channel's creation floor, // or of its cursor when that is later: no row is older than the // floor, so a cursor below it would only walk empty windows. Without the - // channel's row there is no floor, and one window unbounded below - // reads the page. + // channel's row there is no floor: a page walks from its cursor, and + // a head page reads one window unbounded below. let floor = sqlx::query_scalar::<_, DateTime>( "SELECT created_at FROM channels WHERE community_id = $1 AND id = $2", ) @@ -698,7 +698,10 @@ pub(crate) async fn get_channel_window_on( .fetch_optional(&mut *conn) .await? .map(crate::store::recent_pass::channel_floor); - let earliest = floor.map(|floor| cursor_ts.map_or(floor, |ts| ts.max(floor))); + let earliest = match (floor, cursor_ts) { + (Some(floor), Some(ts)) => Some(ts.max(floor)), + (floor, ts) => floor.or(ts), + }; Range::Forward(crate::store::recent_pass::oldest_for( Utc::now(), kinds.as_deref(), @@ -2979,6 +2982,50 @@ mod postgres_tests { unlock(locker, &mut conn).await; } + /// A cursor page that cannot see its channel's row, as on a replica + /// behind the writer, walks from its cursor: a page that fills in its + /// first window never plans the partitions past it. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_newer_cursor_without_the_channel_row_walks_from_the_cursor() { + let pool = setup_pool().await; + let (channel, community, oldest_first) = dated_channel( + &pool, + &Keys::generate(), + "2026-01-10T00:00:00Z", + &[ + unix("2026-01-12T00:00:00Z"), + unix("2026-01-13T00:00:00Z"), + unix("2026-04-10T00:00:00Z"), + ], + ) + .await; + // The rows' thread metadata references the channel's row, so it goes + // first; a top-level row reads the same without it. + for sql in [ + "DELETE FROM thread_metadata WHERE community_id = $1 AND channel_id = $2", + "DELETE FROM channels WHERE community_id = $1 AND id = $2", + ] { + sqlx::query(sql) + .bind(community.as_uuid()) + .bind(channel) + .execute(&pool) + .await + .expect("hide the channel row"); + } + let mut conn = pool.acquire().await.expect("acquire"); + let [_first, later] = + distinct_partitions(&pool, [oldest_first[0].id, oldest_first[2].id]).await; + let locker = lock(&pool, &mut conn, [later]).await; + let at = DateTime::from_timestamp(unix("2026-01-11T00:00:00Z") as i64, 0).expect("date"); + let window = newer_page(&mut conn, community, channel, 1, Some((at, vec![0u8; 32]))) + .await + .expect("a page that fills in its first window never plans the partitions past it"); + assert_eq!(row_ids(&window), vec![oldest_first[0].id]); + assert!(window.has_more); + unlock(locker, &mut conn).await; + } + /// 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. From 22b0ec7b4e671d60123e743088d5da3ce60c0c7e Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Thu, 19 Nov 2026 12:04:56 -0500 Subject: [PATCH 08/12] fix(db): read every forward page completely and within its deadline Four review findings on oldest-first (`direction: "newer"`) windows: - Rows older than the channel's floor. A restore or backfill can store rows in months before the channel's creation, and the walk from the floor's month skipped them while the relay signed exhaustion. A page whose cursor is below that month, the head page included, now reads every row below it in one pass (`Range::Below`), then walks from it. A cursor at 0 still costs one statement plus the walk over the channel's life, not one window per two months since 1970. - Coverage before advancing a cursor. With the head budget on, a newer continuation could land on a replica that had yet to replay the row the previous page probed, and sign `has_more: false`. Thread and channel newer pages now always read the writer (route reason `forward_scan`). - One deadline for the whole walk. The channel's floor is now read inside the read's transaction, under its deadline, and a read whose deadline is spent stops before its next statement (`DbError::ReadDeadlineExceeded`, reported as a cancelled statement) instead of running each later pass under a 1 ms timeout. - Late rows. The past-timestamp check runs when a row is accepted, not when it commits, so a row can land any distance behind a served cursor. NIP-CW now asks an oldest-first reader for a live subscription with no `since`, established before its first page, or a repair read of the crossed range when its scan reaches the newest rows. Tests: both directions over rows dated before the channel, for every limit, from the head and from a cursor at 0; the newer routing tests turn the head budget on; the shared-deadline test spends the deadline. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-db/src/error.rs | 18 +- crates/buzz-db/src/runtime/replica_fence.rs | 6 - crates/buzz-db/src/runtime/tests.rs | 18 +- .../tests/thread_window_postgres_tests.rs | 7 +- crates/buzz-db/src/store/event.rs | 24 +- crates/buzz-db/src/store/recent_pass.rs | 94 +++++++- crates/buzz-db/src/store/thread.rs | 223 +++++++++--------- crates/buzz-db/src/store/thread_window.rs | 31 ++- docs/bridge-channel-window.md | 5 +- docs/nips/NIP-CW.md | 5 +- 10 files changed, 265 insertions(+), 166 deletions(-) diff --git a/crates/buzz-db/src/error.rs b/crates/buzz-db/src/error.rs index efdadb13cf9..994e1cb048f 100644 --- a/crates/buzz-db/src/error.rs +++ b/crates/buzz-db/src/error.rs @@ -131,11 +131,17 @@ pub enum DbError { /// Operator before demoting or deleting the current one. #[error("operation would remove the last relay operator")] LastOperator, + + /// A multi-statement read spent its deadline before its next statement + /// (see `ReadTransaction`). Treated as a cancelled statement. + #[error("database error: read deadline exceeded")] + ReadDeadlineExceeded, } impl DbError { /// Whether Postgres cancelled the statement (SQLSTATE 57014: - /// `statement_timeout` or an explicit cancel). + /// `statement_timeout` or an explicit cancel), or a read's deadline ran + /// out before its next statement ([`DbError::ReadDeadlineExceeded`]). /// /// Replica-routed reads surface a cancel instead of re-running on the /// writer. Usually the cancel means expensive work that the writer would @@ -146,10 +152,11 @@ impl DbError { /// routed reads record it as the `statement_cancelled` route reason; /// `ReadSession` reads return it to the relay, which logs the failed read. pub fn is_statement_cancelled(&self) -> bool { - matches!( - self, - DbError::Sqlx(sqlx::Error::Database(db)) if db.code().as_deref() == Some("57014") - ) + match self { + DbError::Sqlx(sqlx::Error::Database(db)) => db.code().as_deref() == Some("57014"), + DbError::ReadDeadlineExceeded => true, + _ => false, + } } /// Whether the failure is about reaching the database at all (pool @@ -200,6 +207,7 @@ impl DbError { E::NotFound(_) | E::ChannelNotFound(_) | E::MemberNotFound(_) => "not_found", E::AccessDenied(_) => "access_denied", E::NipFiBindingRequired => "nip_fi_binding_required", + E::ReadDeadlineExceeded => "read_deadline_exceeded", _ => "other", }; kind.to_owned() diff --git a/crates/buzz-db/src/runtime/replica_fence.rs b/crates/buzz-db/src/runtime/replica_fence.rs index 1e3625e6059..c86c8701122 100644 --- a/crates/buzz-db/src/runtime/replica_fence.rs +++ b/crates/buzz-db/src/runtime/replica_fence.rs @@ -60,12 +60,6 @@ //! Raw SQL and `session_replication_role = replica` restores bypass the //! application floor check. These operational bypasses are outside the proof //! and require holding the fence closed. -//! -//! Oldest-first channel windows rest on the same floor: a page starts its -//! walk in the month of the channel's creation less [`CREATED_AT_FLOOR_SECS`] -//! (`recent_pass::channel_floor`). A bypass that stores a row in an earlier -//! month also hides it from those reads, which newest-first reads still -//! return. use std::collections::VecDeque; use std::sync::{Arc, Mutex}; diff --git a/crates/buzz-db/src/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index 10ed9f53acf..d85dd708af6 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -996,14 +996,6 @@ async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { // Shared history (both databases): m1 < m2 < m3. let base = 1_700_000_000u64; - for pool in [&writer, &replica] { - sqlx::query("UPDATE channels SET created_at = $1 WHERE id = $2") - .bind(chrono::DateTime::from_timestamp(base as i64 - 3600, 0).unwrap()) - .bind(channel) - .execute(pool) - .await - .expect("date the channel before its history"); - } let m1 = signed_event_at(&author, "m1", base); let m2 = signed_event_at(&author, "m2", base + 10); let m3 = signed_event_at(&author, "m3", base + 20); @@ -1020,7 +1012,7 @@ async fn channel_window_routes_head_to_writer_and_cursor_pages_to_replica() { let marker = signed_event_at(&author, "replica-only-marker", base + 5); insert_top_level(&replica, community, channel, &marker).await; - let db = Db::from_pools(writer.clone(), replica.clone()); + let mut db = Db::from_pools(writer.clone(), replica.clone()); // Open the fence through "now": the fixture's history is far in the // past, so every cursor falls below the fence and routing is // eligible. Fence-gating itself is pinned by the fence tests below. @@ -1064,8 +1056,12 @@ 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`. + // Newer cursor page → writer, always: a continuation on a replica that + // has yet to replay a probed row would end the walk early. It sees + // `fresh` and never `marker`, and reads the history dated before the + // channel was created. The head budget, which would let a head fetch + // read the replica, does not apply to it. + db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(3600))); let (newer, session) = db .get_channel_window_with_session( cid, 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 c6a8a118f70..50b484865d5 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 @@ -29,7 +29,7 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { insert_thread_reply(pool, cid, channel, &root, &old).await; } insert_thread_reply(&writer, cid, channel, &root, &middle).await; - let db = Db::from_pools(writer.clone(), replica.clone()); + let mut db = Db::from_pools(writer.clone(), replica.clone()); let community = CommunityId::from_uuid(cid); let mut req = request(channel, &root, base + 30); // An old delivered tail does not justify an uncovered request upper bound. @@ -66,7 +66,9 @@ 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. + // So does a newer page, even with the head budget on: a continuation on + // a replica that has yet to replay a probed reply would end the walk. + db.set_replica_read_max_age_for_tests(Some(std::time::Duration::from_secs(3600))); 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)})) @@ -81,6 +83,7 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() { [old.id, middle.id] ); drop(session); + db.set_replica_read_max_age_for_tests(None); // 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/event.rs b/crates/buzz-db/src/store/event.rs index 7d93bdb4191..0d8eae9a437 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -1221,7 +1221,8 @@ pub async fn tighten_session_read_statement_timeout( /// /// The read runs under [`READ_STATEMENT_TIMEOUT`] without changing the /// deadline for anything else on the connection, and its statements share -/// it: each after the first runs under what the earlier ones left. +/// it: each after the first runs under what the earlier ones left, and none +/// starts once it is spent ([`DbError::ReadDeadlineExceeded`]). /// [`ReadDeadline::PerRead`] tightens the deadline in the transaction or /// savepoint. Rolling it back (the read has no writes to keep) reverts every /// tighten. @@ -1263,9 +1264,11 @@ impl<'c> ReadTransaction<'c> { query: sqlx::query::Query<'_, sqlx::Postgres, sqlx::postgres::PgArguments>, ) -> Result> { if self.statements > 0 { - let left = READ_DEADLINE - .saturating_sub(self.started.elapsed()) - .max(std::time::Duration::from_millis(1)); + let left = READ_DEADLINE.saturating_sub(self.started.elapsed()); + if left.is_zero() { + return Err(DbError::ReadDeadlineExceeded); + } + let left = left.max(std::time::Duration::from_millis(1)); tighten_read_deadline(&mut self.tx, &format!("{}ms", left.as_millis())).await?; } self.statements += 1; @@ -4212,8 +4215,8 @@ mod postgres_tests { } /// The statements of one read share its deadline: each after the first - /// runs under what the earlier ones left, and ending the read restores - /// the connection's own. + /// runs under what the earlier ones left, none runs once it is spent, and + /// ending the read restores the connection's own. #[tokio::test] #[ignore = "requires Postgres"] async fn read_statements_share_one_deadline() { @@ -4253,6 +4256,15 @@ mod postgres_tests { .expect("begin read"); let first: f64 = read.fetch(timeout_ms()).await.expect("first")[0].get(0); let second: f64 = read.fetch(timeout_ms()).await.expect("second")[0].get(0); + read.started -= READ_DEADLINE; + let spent = read + .fetch(timeout_ms()) + .await + .expect_err("a spent deadline"); + assert!( + matches!(spent, DbError::ReadDeadlineExceeded) && spent.is_statement_cancelled(), + "{case}: a spent deadline stops the read before its next statement, got {spent}" + ); read.finish().await.expect("finish"); assert_eq!( first, full, diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs index 2bfc4c93df2..72bb23730b4 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -38,9 +38,12 @@ //! 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. For a -//! channel read the earliest possible row is [`channel_floor`], or the cursor -//! when that is later, so a page walks at most one window per two months of +//! stops at the same ceiling; any other read ends with one open window. A +//! channel read starts at the month of [`channel_floor`] ([`oldest_first`]): +//! a page whose cursor is below that month first reads every row below it in +//! one pass ([`Range::Below`]), since a restore or backfill can store rows +//! older than the channel, then walks from it. A later cursor walks from its +//! own month. A page reads at most that pass and one window per two months of //! the channel's life. Without the channel's row a page walks from its cursor, //! and a read with neither plans every partition below the ceiling in one //! window. @@ -148,6 +151,9 @@ pub(crate) enum Range { Older(DateTime), /// One window of an oldest-first walk. Forward(Forward), + /// `created_at <` the window's start, read before the walk from that + /// window. + Below(Forward), } impl Range { @@ -168,6 +174,7 @@ impl Range { Range::Recent(split) => (Some(split.floor), split.ceiling), Range::Older(floor) => (None, Some(floor)), Range::Forward(window) => (window.from, window.to), + Range::Below(window) => (None, window.from), }; let bound = |op: &str, at: Option>| { at.map(|at| { @@ -264,10 +271,10 @@ fn regular_only(kinds: Option<&[i32]>) -> bool { /// the database's `NOW()` when the channel row was inserted /// (`schema/tables/public/channels.sql`), every write of a channel row checks /// its `created_at` against the database clock, and the channel exists before -/// its first row, so no row of it is older. A write that bypasses that check -/// (see [`crate::replica_fence`]) can store older rows, and oldest-first reads -/// skip those in earlier months than the floor's. Its month starts the walk of -/// an oldest-first channel page. +/// its first row, so no write the relay serves stores an older row. A restore +/// or backfill that bypasses that check (see [`crate::replica_fence`]) can, +/// so an oldest-first channel page reads below the floor's month in one pass +/// and walks from it ([`oldest_first`]). pub(crate) fn channel_floor(channel_created_at: DateTime) -> DateTime { channel_created_at - Duration::seconds(CREATED_AT_FLOOR_SECS) } @@ -289,14 +296,40 @@ pub(crate) fn oldest_for( Forward::from(floor, horizon, regular_only(kinds)) } +/// The first pass of an oldest-first channel page read. `floor` is the +/// channel's [`channel_floor`] (`None`: its row is not visible); `cursor` +/// the page's cursor (`None`: the head page). A page whose cursor is below +/// the floor's month reads every row below that month first, then walks from +/// it; a later cursor walks from its own month. Without a floor a page walks +/// from its cursor. +pub(crate) fn oldest_first( + now: DateTime, + kinds: Option<&[i32]>, + floor: Option>, + cursor: Option>, +) -> Range { + match floor.map(|floor| oldest_for(now, kinds, Some(floor))) { + Some(walk) + if walk + .from + .is_some_and(|from| cursor.is_none_or(|ts| ts < from)) => + { + Range::Below(walk) + } + _ => Range::Forward(oldest_for(now, kinds, cursor)), + } +} + /// The pass to run after `range` once the read holds `found` of its `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`. +/// rows, with that pass's limit: the older pass after a short recent pass, +/// the next window after a short window, or the walk after a short pass +/// below it, 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 rest = match range { Range::Recent(split) if split.older => Range::Older(split.floor), Range::Forward(window) => Range::Forward(window.advance()?), + Range::Below(window) => Range::Forward(window), _ => return None, }; let found = i64::try_from(found).unwrap_or(i64::MAX); @@ -550,7 +583,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!(), + Range::Forward(_) | Range::Below(_) => unreachable!(), }) .take(n as usize), ); @@ -681,6 +714,45 @@ mod tests { assert_eq!(window.from, Some(midnight(2026, 2, 1))); } + /// A channel page whose cursor is below its floor's month, the head page + /// included, reads every row below that month in one pass and then walks + /// from it. A later cursor walks from its own month, and so does a page + /// without a floor. + #[test] + fn oldest_first_reads_below_the_floor_month_in_one_pass() { + let now = at(2026, 11, 4); + let kinds = Some(&[9][..]); + let floor = Some(channel_floor(midnight(2026, 3, 1) + Duration::seconds(10))); + let walk = oldest_for(now, kinds, floor); + assert_eq!(walk.from, Some(midnight(2026, 2, 1))); + for cursor in [ + None, + Some(DateTime::::UNIX_EPOCH), + Some(at(2026, 1, 31)), + ] { + let first = oldest_first(now, kinds, floor, cursor); + assert_eq!(first, Range::Below(walk), "{cursor:?}"); + assert_eq!( + first.predicate("created_at").as_deref(), + Some(" AND created_at < '2026-02-01T00:00:00Z'::timestamptz") + ); + assert_eq!(next(first, 2, 5), Some((Range::Forward(walk), 3))); + assert_eq!(next(first, 5, 5), None); + } + for (floor, cursor) in [ + (floor, Some(midnight(2026, 2, 1))), + (floor, Some(at(2026, 6, 20))), + (None, Some(at(2026, 6, 20))), + (None, None), + ] { + assert_eq!( + oldest_first(now, kinds, floor, cursor), + Range::Forward(oldest_for(now, kinds, cursor)), + "{floor:?}, {cursor:?}" + ); + } + } + /// 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, diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 61b87f5a868..93149959777 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -674,40 +674,20 @@ 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. A newer page walks forward from its cursor's - // month (the head page, from the channel's creation) a window at a time. + // what is still missing. A newer page walks forward a window at a time + // from its cursor's month, or reads every row below the month of the + // channel's creation first and walks from there (`oldest_first`). let kinds: Option> = kind_filter.map(|ks| ks.iter().filter_map(|&k| i32::try_from(k).ok()).collect()); let cursor_ts = cursor.as_ref().map(|(ts, _)| *ts); + // A newer page's first pass depends on the channel's floor, which it + // reads in the same transaction as its passes (`None` here). let first = match direction { - Direction::Older => { + Direction::Older => Some( crate::store::recent_pass::split_for(Utc::now(), kinds.as_deref(), None, cursor_ts) - .map_or(Range::All, Range::Recent) - } - Direction::Newer => { - // Every page walks from the month of the channel's creation floor, - // or of its cursor when that is later: no row is older than the - // floor, so a cursor below it would only walk empty windows. Without the - // channel's row there is no floor: a page walks from its cursor, and - // a head page reads one window unbounded below. - let floor = 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); - let earliest = match (floor, cursor_ts) { - (Some(floor), Some(ts)) => Some(ts.max(floor)), - (floor, ts) => floor.or(ts), - }; - Range::Forward(crate::store::recent_pass::oldest_for( - Utc::now(), - kinds.as_deref(), - earliest, - )) - } + .map_or(Range::All, Range::Recent), + ), + Direction::Newer => None, }; // The +1 probe row is the server-internal has_more evidence. let probe_limit = i64::from(limit) + 1; @@ -726,7 +706,7 @@ pub(crate) async fn get_channel_window_on( q.bind(pass_limit) }; let mut db_rows = match first { - Range::All => { + Some(Range::All) => { crate::event::fetch_with_read_deadline( &mut *conn, pass_query(Range::All, probe_limit), @@ -735,9 +715,33 @@ pub(crate) async fn get_channel_window_on( .await? } first => { - // One snapshot and one deadline for both passes (see - // `ReadTransaction`). + // One snapshot and one deadline for every statement of the read, + // the channel's floor included (see `ReadTransaction`). let mut read = crate::event::ReadTransaction::begin(conn, deadline).await?; + let first = match first { + Some(first) => first, + None => { + let floor = read + .fetch( + sqlx::query( + "SELECT created_at FROM channels WHERE community_id = $1 AND id = $2", + ) + .bind(community_id.as_uuid()) + .bind(channel_id), + ) + .await? + .first() + .map(|row| row.try_get::, _>("created_at")) + .transpose()? + .map(crate::store::recent_pass::channel_floor); + crate::store::recent_pass::oldest_first( + Utc::now(), + kinds.as_deref(), + floor, + cursor_ts, + ) + } + }; let mut rows = Vec::new(); let mut pass = Some((first, probe_limit)); while let Some((range, pass_limit)) = pass { @@ -1139,8 +1143,10 @@ 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 and newer pages** (Predicate A — bounded staleness): - /// a newer page reads up to the newest row, like a head. Served by a + /// - **Newer pages** always read the writer: a continuation on a replica + /// that has yet to replay a row the previous page probed would end the + /// walk early. + /// - **Head fetch** (Predicate A — bounded staleness): 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 @@ -1170,14 +1176,21 @@ impl Db { (Direction::Older, None) => ("channel_head", None), (Direction::Older, cursor) => ("channel_cursor", cursor.clone()), }; - match self - .route_read( - path, - RoutePredicate::from_channel_cursor(channel_id, &covered), - crate::observability::ReaderOperation::SubscriptionHistory, - ) - .await? - { + let route = match direction { + Direction::Newer => { + Self::record_route(path, "writer", "forward_scan"); + RouteDecision::Writer + } + Direction::Older => { + self.route_read( + path, + RoutePredicate::from_channel_cursor(channel_id, &covered), + crate::observability::ReaderOperation::SubscriptionHistory, + ) + .await? + } + }; + match route { RouteDecision::Replica(mut tx, _entry, reason) => { match crate::thread::get_channel_window_on( &mut tx, @@ -2835,10 +2848,10 @@ mod postgres_tests { } /// 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. + /// needs. It reads below the month the channel was created in one pass, + /// then walks forward two months at a time, so the newer partitions 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() { @@ -2858,15 +2871,6 @@ mod postgres_tests { ], ) .await; - // A row of another channel in the partition below the head page's - // floor: it only names that partition. - let (_, _, below) = dated_channel( - &pool, - &author, - "2025-05-15T00:00:00Z", - &[unix("2025-06-01T00:00:00Z")], - ) - .await; let mut conn = pool.acquire().await.expect("acquire"); // Unlocked, every limit pages the same rows as a read with no floor. @@ -2894,17 +2898,12 @@ mod postgres_tests { // Another session locks the partitions the page must not plan. A // page needing a locked one fails instead of returning a short page. - let [below, _first, june, newest] = distinct_partitions( + let [_first, june, newest] = distinct_partitions( &pool, - [ - below[0].id, - oldest_first[0].id, - oldest_first[4].id, - oldest_first[5].id, - ], + [oldest_first[0].id, oldest_first[4].id, oldest_first[5].id], ) .await; - let locker = lock(&pool, &mut conn, [below, june, newest]).await; + let locker = lock(&pool, &mut conn, [june, newest]).await; // 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. @@ -2925,66 +2924,68 @@ mod postgres_tests { unlock(locker, &mut conn).await; } - /// The head page reads rows written up to the write path's tolerance - /// before the channel was created, here in the month before it. + /// Rows older than the channel, as a restore or backfill stores them, and + /// one inside the write path's tolerance before its creation page the + /// same from both ends, for every limit: oldest first from the head and + /// from a cursor at 0, newest first in the reverse order. #[tokio::test] #[ignore = "requires Postgres"] - async fn channel_window_newer_head_reads_rows_older_than_the_channel_within_the_floor() { + async fn channel_window_pages_rows_older_than_the_channel_from_both_ends() { let pool = setup_pool().await; let (channel, community, oldest_first) = dated_channel( &pool, &Keys::generate(), "2026-03-01T00:05:00Z", - &[unix("2026-02-28T23:58:00Z"), unix("2026-03-02T00:00:00Z")], - ) - .await; - let mut conn = pool.acquire().await.expect("acquire"); - let window = newer_page(&mut conn, community, channel, 10, None) - .await - .expect("head page"); - let expected: Vec<_> = oldest_first.iter().map(|e| e.id).collect(); - assert_eq!(row_ids(&window), expected); - assert!(!window.has_more); - } - - /// A cursor older than the channel starts the walk at the channel's - /// floor, as the head page does, so the partitions below it are never - /// planned. - #[tokio::test] - #[ignore = "requires Postgres"] - async fn channel_window_newer_cursor_below_the_floor_walks_from_the_floor() { - let pool = setup_pool().await; - let author = Keys::generate(); - let (channel, community, oldest_first) = dated_channel( - &pool, - &author, - "2026-01-10T00:00:00Z", - &[unix("2026-01-12T00:00:00Z"), unix("2026-03-10T12:00:00Z")], - ) - .await; - // A row of another channel names a partition below the floor. - let (_, _, below) = dated_channel( - &pool, - &author, - "2025-05-15T00:00:00Z", - &[unix("2025-06-01T00:00:00Z")], + &[ + unix("2025-06-01T00:00:00Z"), + unix("2026-02-28T23:58:00Z"), + unix("2026-03-02T00:00:00Z"), + unix("2026-05-10T00:00:00Z"), + ], ) .await; + let oldest: Vec<_> = oldest_first.iter().map(|e| e.id).collect(); + let newest: Vec<_> = oldest.iter().rev().copied().collect(); + let epoch = (DateTime::::UNIX_EPOCH, vec![0u8; 32]); let mut conn = pool.acquire().await.expect("acquire"); - let [below, _first] = distinct_partitions(&pool, [below[0].id, oldest_first[0].id]).await; - let locker = lock(&pool, &mut conn, [below]).await; - let epoch = Some((DateTime::::UNIX_EPOCH, vec![0u8; 32])); - let window = newer_page(&mut conn, community, channel, 10, epoch) - .await - .expect("a cursor below the floor never plans the partitions below it"); - let expected: Vec<_> = oldest_first.iter().map(|e| e.id).collect(); - assert_eq!(row_ids(&window), expected); - unlock(locker, &mut conn).await; + for limit in 1..=oldest.len() as u32 { + for (direction, start, expected) in [ + (Direction::Newer, None, &oldest), + (Direction::Newer, Some(epoch.clone()), &oldest), + (Direction::Older, None, &newest), + ] { + let mut cursor = start.clone(); + let mut rows = Vec::new(); + loop { + let window = get_channel_window_on( + &mut conn, + community, + channel, + limit, + direction, + cursor, + None, + ReadDeadline::PerRead, + ) + .await + .expect("page"); + rows.extend(row_ids(&window)); + if !window.has_more { + break; + } + cursor = Some(window.next_cursor.expect("has_more implies next_cursor")); + } + assert_eq!( + &rows, expected, + "{direction:?} from {start:?}, limit {limit}" + ); + } + } } - /// A cursor page that cannot see its channel's row, as on a replica - /// behind the writer, walks from its cursor: a page that fills in its - /// first window never plans the partitions past it. + /// A cursor page whose channel's row is gone walks from its cursor: a + /// page that fills in its first window never plans the partitions past + /// it. #[tokio::test] #[ignore = "requires Postgres"] async fn channel_window_newer_cursor_without_the_channel_row_walks_from_the_cursor() { diff --git a/crates/buzz-db/src/store/thread_window.rs b/crates/buzz-db/src/store/thread_window.rs index 87069362db5..d0724cc89e6 100644 --- a/crates/buzz-db/src/store/thread_window.rs +++ b/crates/buzz-db/src/store/thread_window.rs @@ -222,9 +222,11 @@ async fn writer_window( impl Db { /// 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, + /// delivered row is newest" inference is used. Head pages read up to the + /// newest reply, which no cursor bounds, so their routing inherits the + /// existing default-off budget. Newer pages always read the writer: a + /// continuation on a replica that has yet to replay a row the previous + /// page probed would end the walk early. 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. #[datastore_span(name = "get_thread_window", system = "postgresql")] @@ -240,14 +242,21 @@ impl Db { (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, &covered), - crate::observability::ReaderOperation::SubscriptionHistory, - ) - .await? - { + let route = match request.direction { + Direction::Newer => { + Self::record_route(path, "writer", "forward_scan"); + RouteDecision::Writer + } + Direction::Older => { + self.route_read( + path, + RoutePredicate::from_channel_cursor(request.channel, &covered), + crate::observability::ReaderOperation::SubscriptionHistory, + ) + .await? + } + }; + if let RouteDecision::Replica(mut tx, _, reason) = route { let result = async { set_deadline(&mut tx).await?; select_window(&mut tx, community, request, budget).await diff --git a/docs/bridge-channel-window.md b/docs/bridge-channel-window.md index 6b4645f57d1..47c60975dcb 100644 --- a/docs/bridge-channel-window.md +++ b/docs/bridge-channel-window.md @@ -150,8 +150,9 @@ Both kinds are relay-only: client submission is rejected at ingest. - Reconnect refetches page 0 and re-arms the live subscription (`since: now`); deeper pages need no repair path. An oldest-first (`direction: "newer"`) reader follows NIP-CW's direction rules instead: - its subscription starts before the scan, and on reconnect it reads the - newest rows it missed newest first. + a live subscription with no `since`, established before the scan, or a + repair read of the crossed range once the scan reaches the newest rows; + on reconnect it reads the newest rows it missed newest first. - Replies never enter the channel timeline; the thread panel uses the existing `thread_cursor` surface (#1418). Thread filters may opt into `include_aux` to append the same authorized two-hop reactions, edits, and diff --git a/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index e547f0c19b7..4fc0bfda149 100644 --- a/docs/nips/NIP-CW.md +++ b/docs/nips/NIP-CW.md @@ -65,7 +65,10 @@ Both modes accept an optional `direction` field: `"older"` (the default) or `"ne | 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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), so a row written after a `"newer"` page was served can sort behind that page's cursor and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present either reads the newest stretch again or keeps a live subscription that starts before the scan: live delivery also drops rows older than the subscription's `since`, so its `since` MUST be at least as far before the first page's request as the relay accepts past timestamps (900 seconds for Buzz). A subscription with `since: now` misses the same late rows. `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. +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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), and it checks that when it accepts the row, not when the row commits. A row that commits after a `"newer"` page was served can therefore sort behind that page's cursor, by any distance, and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present MUST cover those rows in one of two ways: + +- Hold a live subscription with no `since` (for example with `limit: 0`), established (its EOSE received) before the first page's request. Every row that commits after that is delivered live, and every row that committed before it is in the pages. A subscription with a `since` drops late rows older than it. +- Read the crossed range again when the scan reaches the newest rows: every row whose `created_at` is at or after the first page's request time, less the relay's past-timestamp allowance (960 seconds for Buzz, its write path's limit). This catches every row that committed before the repair read, except one whose write was already in progress when the first page's request ran; the live subscription delivers rows that commit after it, subject to its own `since`. `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` or `after_id` to a relay that does not advertise it; without it, the client reads newest first only. From 11160b8f2a44c18a6261645b3aac086bc7195df1 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Thu, 19 Nov 2026 12:54:11 -0500 Subject: [PATCH 09/12] docs(nip-cw): require the repair read for an oldest-first reader A REQ's EOSE does not mean that every relay node delivers to the subscription: another node starts when Redis confirms it, which can be after EOSE. A late row that commits in between reaches neither the subscription nor a later page, so a live subscription cannot replace the repair read of the crossed range. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- docs/bridge-channel-window.md | 3 +-- docs/nips/NIP-CW.md | 7 +++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/bridge-channel-window.md b/docs/bridge-channel-window.md index 47c60975dcb..95d4aa0ed0a 100644 --- a/docs/bridge-channel-window.md +++ b/docs/bridge-channel-window.md @@ -150,8 +150,7 @@ Both kinds are relay-only: client submission is rejected at ingest. - Reconnect refetches page 0 and re-arms the live subscription (`since: now`); deeper pages need no repair path. An oldest-first (`direction: "newer"`) reader follows NIP-CW's direction rules instead: - a live subscription with no `since`, established before the scan, or a - repair read of the crossed range once the scan reaches the newest rows; + a repair read of the crossed range once the scan reaches the newest rows; on reconnect it reads the newest rows it missed newest first. - Replies never enter the channel timeline; the thread panel uses the existing `thread_cursor` surface (#1418). Thread filters may opt into diff --git a/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index 4fc0bfda149..4fcb5fa0142 100644 --- a/docs/nips/NIP-CW.md +++ b/docs/nips/NIP-CW.md @@ -65,10 +65,9 @@ Both modes accept an optional `direction` field: `"older"` (the default) or `"ne | 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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), and it checks that when it accepts the row, not when the row commits. A row that commits after a `"newer"` page was served can therefore sort behind that page's cursor, by any distance, and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present MUST cover those rows in one of two ways: +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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), and it checks that when it accepts the row, not when the row commits. A row that commits after a `"newer"` page was served can therefore sort behind that page's cursor, by any distance, and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present MUST read the crossed range again when the scan reaches the newest rows: every row whose `created_at` is at or after the first page's request time, less the relay's past-timestamp allowance (960 seconds for Buzz, its write path's limit). This catches every row that committed before the repair read, except one whose write was already in progress when the first page's request ran. Open the live subscription before the repair read, so that it delivers the rows that commit after it. A live subscription does not replace the repair read: its EOSE does not mean that every relay node delivers to it. On Buzz, another node starts to deliver when Redis confirms the subscription, which can be after EOSE and is not reported to the client, so a late row that commits on another node after the repair read and before that confirmation reaches neither the subscription nor a later page. -- Hold a live subscription with no `since` (for example with `limit: 0`), established (its EOSE received) before the first page's request. Every row that commits after that is delivered live, and every row that committed before it is in the pages. A subscription with a `since` drops late rows older than it. -- Read the crossed range again when the scan reaches the newest rows: every row whose `created_at` is at or after the first page's request time, less the relay's past-timestamp allowance (960 seconds for Buzz, its write path's limit). This catches every row that committed before the repair read, except one whose write was already in progress when the first page's request ran; the live subscription delivers rows that commit after it, subject to its own `since`. `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. +`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` or `after_id` to a relay that does not advertise it; without it, the client reads newest first only. @@ -189,7 +188,7 @@ Exactly one per served window response. The **only** authority on exhaustion. Ta 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` (`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. A `"newer"` reader instead starts its subscription before the scan, as §Direction says, and its head page holds the oldest rows: on reconnect it reads the newest rows it missed with `"older"` pages, then re-arms the subscription. +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. A `"newer"` reader instead reads late rows again, as §Direction says, and its head page holds the oldest rows: on reconnect it re-arms the subscription, then reads the newest rows it missed with `"older"` pages. 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. 6. **Overlays are metadata**: never render a `39005`/`39006` as a message, never feed one into cursor math, and key cached summaries by their `d` tag (latest wins). From 822e79f9937812611c4a33f0f6c834fa37b10d76 Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Thu, 19 Nov 2026 14:11:37 -0500 Subject: [PATCH 10/12] docs(nip-cw): qualify the repair read and the newer reader's live filter The repair read catches every row that committed before it only when the relay serves it from its writer. Buzz does unless the operator sets BUZZ_REPLICA_READ_MAX_AGE_MS; then a read without `until` can come from a replica up to that age behind. Say so. A live subscription with `since: now` never delivers a row dated before now, and the relay accepts rows dated up to 900 seconds back. A newer reader's subscription therefore starts at the repair range's start. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- docs/nips/NIP-CW.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index 4fcb5fa0142..79b60d63d80 100644 --- a/docs/nips/NIP-CW.md +++ b/docs/nips/NIP-CW.md @@ -65,7 +65,7 @@ Both modes accept an optional `direction` field: `"older"` (the default) or `"ne | 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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), and it checks that when it accepts the row, not when the row commits. A row that commits after a `"newer"` page was served can therefore sort behind that page's cursor, by any distance, and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present MUST read the crossed range again when the scan reaches the newest rows: every row whose `created_at` is at or after the first page's request time, less the relay's past-timestamp allowance (960 seconds for Buzz, its write path's limit). This catches every row that committed before the repair read, except one whose write was already in progress when the first page's request ran. Open the live subscription before the repair read, so that it delivers the rows that commit after it. A live subscription does not replace the repair read: its EOSE does not mean that every relay node delivers to it. On Buzz, another node starts to deliver when Redis confirms the subscription, which can be after EOSE and is not reported to the client, so a late row that commits on another node after the repair read and before that confirmation reaches neither the subscription nor a later page. +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, as long as no rows are being written. A relay can accept a row whose `created_at` is in the past (the Buzz relay accepts up to 900 seconds), and it checks that when it accepts the row, not when the row commits. A row that commits after a `"newer"` page was served can therefore sort behind that page's cursor, by any distance, and never appear on a later page. Near the newest rows, `has_more: false` therefore means the read caught up when it ran. A client that reads oldest first up to the present MUST read the crossed range again when the scan reaches the newest rows: every row whose `created_at` is at or after the first page's request time, less the relay's past-timestamp allowance (960 seconds for Buzz, its write path's limit). If the relay serves the repair read from its writer, this catches every row that committed before the read, except one whose write was already in progress when the first page's request ran. Buzz serves it from the writer unless the operator sets `BUZZ_REPLICA_READ_MAX_AGE_MS` (off by default); then a read without `until` can come from a replica up to that age behind and miss the rows that committed in that time. Open the live subscription before the repair read, with `since` no later than the repair range's start, so that it delivers the rows that commit after it: a relay does not deliver a live event older than a filter's `since`. A live subscription does not replace the repair read: its EOSE does not mean that every relay node delivers to it. On Buzz, another node starts to deliver when Redis confirms the subscription, which can be after EOSE and is not reported to the client, so a late row that commits on another node after the repair read and before that confirmation reaches neither the subscription nor a later page. `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. @@ -188,7 +188,7 @@ Exactly one per served window response. The **only** authority on exhaustion. Ta 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` (`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. A `"newer"` reader instead reads late rows again, as §Direction says, and its head page holds the oldest rows: on reconnect it re-arms the subscription, then reads the newest rows it missed with `"older"` pages. +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. A `"newer"` reader instead reads late rows again, as §Direction says, gives its live subscription the repair range's start as `since` rather than now, and its head page holds the oldest rows: on reconnect it re-arms the subscription, then reads the newest rows it missed with `"older"` pages. 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. 6. **Overlays are metadata**: never render a `39005`/`39006` as a message, never feed one into cursor math, and key cached summaries by their `d` tag (latest wins). From 0331ed5e1ccd09e849944174b71be89d2feefc6b Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Fri, 20 Nov 2026 13:20:00 -0500 Subject: [PATCH 11/12] test(db): pin the channel floor's tolerance and the newer pages' failures The floor test now checks both sides of the write path's tolerance: a channel created exactly that long after midnight starts its first window that month, and one second earlier starts it the month before. A table row that repeated another row's shape is gone. The two newer-page tests that lock a partition now require the lock timeout, not any error. The thread test checks that the first page leaves out the aux of a reply on the second. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-db/src/store/recent_pass.rs | 19 ++++++------------- crates/buzz-db/src/store/thread.rs | 10 ++++++++-- .../bridge/thread_window/postgres_tests.rs | 7 ++++++- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs index 72bb23730b4..03c5a79ac8a 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -667,13 +667,6 @@ mod tests { 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); @@ -704,14 +697,14 @@ mod tests { /// 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); + let now = at(2026, 11, 4); + let first = |created| oldest_for(now, Some(&[9]), Some(channel_floor(created))).from; + let edge = midnight(2026, 3, 1) + Duration::seconds(CREATED_AT_FLOOR_SECS); + assert_eq!(first(edge), Some(midnight(2026, 3, 1))); assert_eq!( - channel_floor(created), - midnight(2026, 3, 1) + Duration::seconds(10 - CREATED_AT_FLOOR_SECS) + first(edge - Duration::seconds(1)), + Some(midnight(2026, 2, 1)) ); - 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))); } /// A channel page whose cursor is below its floor's month, the head page diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 93149959777..8494ab51082 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -2330,6 +2330,12 @@ mod postgres_tests { locker } + /// Whether a read gave up on a lock that [`lock`] holds. + fn lock_timed_out(result: &Result) -> bool { + matches!(result, Err(crate::error::DbError::Sqlx(sqlx::Error::Database(db))) + if db.code().as_deref() == Some("55P03")) + } + async fn unlock( locker: sqlx::Transaction<'static, sqlx::Postgres>, conn: &mut sqlx::PgConnection, @@ -2826,7 +2832,7 @@ mod postgres_tests { assert!(window.has_more); let failed = newer_page(&mut conn, community, channel, 2, after_march()).await; assert!( - failed.is_err(), + lock_timed_out(&failed), "a failed later pass must fail the window, got {:?}", failed.map(|w| (w.rows.len(), w.has_more)) ); @@ -2917,7 +2923,7 @@ mod postgres_tests { } let failed = newer_page(&mut conn, community, channel, 4, None).await; assert!( - failed.is_err(), + lock_timed_out(&failed), "a page that needs the June window must fail on its lock, got {:?}", failed.map(|w| (w.rows.len(), w.has_more)) ); 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 1090c35a02d..a7774f58213 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 @@ -358,7 +358,12 @@ async fn thread_window_newer_pages_forward() { 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 first = ids(&page, None); + assert!(first.contains(&root_edit.id.to_hex().as_str()), "{page}"); + assert!( + !first.contains(&reply_reaction.id.to_hex().as_str()), + "{page}" + ); let bounds = f.bounds(&page, &filter); assert_eq!(bounds["direction"], "newer"); assert_eq!(bounds["has_more"], true); From bf4bd04f2d05efb89eeab3dd4c45e0a3a6123bfd Mon Sep 17 00:00:00 2001 From: Krish Ray Date: Sat, 21 Nov 2026 08:43:43 -0500 Subject: [PATCH 12/12] fix(db): skip the partitions before a channel the relay created An oldest-first channel head read every row below the month of the channel's floor in one pass before walking forward, because a restore or backfill can store rows older than the channel. That pass has no lower bound, so a young channel's first newer page planned and locked every older partition, and failed while maintenance held one of them. A new nullable channels.history_from_creation column records which channels can have no such rows. The three insert paths that create a channel set it true; existing rows stay NULL, and the column has no default in the migration or the declarative schema, so adding it marks nothing. Only true lets a head, or a cursor below the floor's month, walk from that month with nothing read below it. NULL and false keep the pass, so restored and backfilled rows still page. A repair that stores an older row must set the channel false, as the replica-fence docs and docs/database.md now say. Tests: a channel, a channel with its own id and a DM, each created on the write path, page both heads and a newer page from a cursor at 0 with every partition before July 2026 locked, in custom and generic plans; the rows-older-than-the-channel test runs for NULL and false. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: Krish Ray --- crates/buzz-db/src/runtime/migration.rs | 5 +- crates/buzz-db/src/runtime/replica_fence.rs | 5 +- crates/buzz-db/src/store/channel.rs | 8 +- crates/buzz-db/src/store/dm.rs | 4 +- crates/buzz-db/src/store/recent_pass.rs | 122 +++++++--- crates/buzz-db/src/store/thread.rs | 224 ++++++++++++++---- docs/database.md | 5 +- .../0106_channel_history_from_creation.sql | 8 + schema/tables/public/channels.sql | 6 + 9 files changed, 299 insertions(+), 88 deletions(-) create mode 100644 migrations/0106_channel_history_from_creation.sql diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 560a1f031e2..9521b48d371 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -1036,7 +1036,10 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 105); + assert_eq!(migrations.len(), 106); + assert_eq!(migrations[105].version, 106); + assert!(strip_sql_comments(migrations[105].sql.as_str()) + .contains("ALTER TABLE channels ADD COLUMN history_from_creation BOOLEAN;")); assert_eq!(migrations[104].version, 105); assert!(strip_sql_comments(migrations[104].sql.as_str()) .contains("ADD COLUMN finished BOOLEAN NOT NULL DEFAULT true;")); diff --git a/crates/buzz-db/src/runtime/replica_fence.rs b/crates/buzz-db/src/runtime/replica_fence.rs index c86c8701122..b819a851d86 100644 --- a/crates/buzz-db/src/runtime/replica_fence.rs +++ b/crates/buzz-db/src/runtime/replica_fence.rs @@ -59,7 +59,10 @@ //! //! Raw SQL and `session_replication_role = replica` restores bypass the //! application floor check. These operational bypasses are outside the proof -//! and require holding the fence closed. +//! and require holding the fence closed. One that stores a row in a channel +//! older than the channel's creation, less [`CREATED_AT_FLOOR_SECS`], must +//! also set the channel's `history_from_creation` to false in the same +//! transaction, or an oldest-first channel page skips the row. use std::collections::VecDeque; use std::sync::{Arc, Mutex}; diff --git a/crates/buzz-db/src/store/channel.rs b/crates/buzz-db/src/store/channel.rs index c294c9f0271..59c2cbecd9b 100644 --- a/crates/buzz-db/src/store/channel.rs +++ b/crates/buzz-db/src/store/channel.rs @@ -143,9 +143,9 @@ pub async fn create_channel( sqlx::query( r#" - INSERT INTO channels (id, community_id, name, channel_type, visibility, description, created_by, ttl_seconds, ttl_deadline, labels, unlisted) + INSERT INTO channels (id, community_id, name, channel_type, visibility, description, created_by, ttl_seconds, ttl_deadline, labels, unlisted, history_from_creation) VALUES ($1, $2, $3, $4::channel_type, $5::channel_visibility, $6, $7, $8, - CASE WHEN $8 IS NOT NULL THEN NOW() + ($8 || ' seconds')::interval ELSE NULL END, $9, $10) + CASE WHEN $8 IS NOT NULL THEN NOW() + ($8 || ' seconds')::interval ELSE NULL END, $9, $10, true) "#, ) .bind(id) @@ -388,9 +388,9 @@ async fn insert_channel_rows( let rows_affected = sqlx::query( r#" - INSERT INTO channels (id, community_id, name, channel_type, visibility, description, created_by, ttl_seconds, ttl_deadline, labels, unlisted) + INSERT INTO channels (id, community_id, name, channel_type, visibility, description, created_by, ttl_seconds, ttl_deadline, labels, unlisted, history_from_creation) VALUES ($1, $2, $3, $4::channel_type, $5::channel_visibility, $6, $7, $8, - CASE WHEN $8 IS NOT NULL THEN NOW() + ($8 || ' seconds')::interval ELSE NULL END, $9, $10) + CASE WHEN $8 IS NOT NULL THEN NOW() + ($8 || ' seconds')::interval ELSE NULL END, $9, $10, true) ON CONFLICT (community_id, id) DO NOTHING "#, ) diff --git a/crates/buzz-db/src/store/dm.rs b/crates/buzz-db/src/store/dm.rs index 39cbd6b1fd1..6fe45dfa7bc 100644 --- a/crates/buzz-db/src/store/dm.rs +++ b/crates/buzz-db/src/store/dm.rs @@ -382,8 +382,8 @@ async fn find_or_create_dm( let inserted = sqlx::query( r#" INSERT INTO channels - (id, community_id, name, channel_type, visibility, created_by, participant_hash) - VALUES ($1, $2, $3, 'dm', 'private', $4, $5) + (id, community_id, name, channel_type, visibility, created_by, participant_hash, history_from_creation) + VALUES ($1, $2, $3, 'dm', 'private', $4, $5, true) "#, ) .bind(id) diff --git a/crates/buzz-db/src/store/recent_pass.rs b/crates/buzz-db/src/store/recent_pass.rs index 03c5a79ac8a..a4dce483ebc 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -39,14 +39,15 @@ //! 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. A -//! channel read starts at the month of [`channel_floor`] ([`oldest_first`]): -//! a page whose cursor is below that month first reads every row below it in -//! one pass ([`Range::Below`]), since a restore or backfill can store rows -//! older than the channel, then walks from it. A later cursor walks from its -//! own month. A page reads at most that pass and one window per two months of -//! the channel's life. Without the channel's row a page walks from its cursor, -//! and a read with neither plans every partition below the ceiling in one -//! window. +//! channel read starts at the month of [`channel_floor`] ([`oldest_first`]), +//! and a page whose cursor is below that month walks from it. A channel the +//! write path created holds no row below it, so it reads nothing older. Any +//! other channel can: a restore or backfill can store rows older than the +//! channel, so its page first reads every row below that month in one pass +//! ([`Range::Below`]), then walks. A later cursor walks from its own month. A +//! page reads at most that pass and one window per two months of the +//! channel's life. Without the channel's row a page walks from its cursor, and +//! a read with neither plans every partition below the ceiling in one window. //! //! 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 @@ -273,8 +274,8 @@ fn regular_only(kinds: Option<&[i32]>) -> bool { /// its `created_at` against the database clock, and the channel exists before /// its first row, so no write the relay serves stores an older row. A restore /// or backfill that bypasses that check (see [`crate::replica_fence`]) can, -/// so an oldest-first channel page reads below the floor's month in one pass -/// and walks from it ([`oldest_first`]). +/// so only a channel row marked `history_from_creation` bounds a read at the +/// floor ([`ChannelFloor`]). pub(crate) fn channel_floor(channel_created_at: DateTime) -> DateTime { channel_created_at - Duration::seconds(CREATED_AT_FLOOR_SECS) } @@ -296,25 +297,59 @@ pub(crate) fn oldest_for( Forward::from(floor, horizon, regular_only(kinds)) } -/// The first pass of an oldest-first channel page read. `floor` is the -/// channel's [`channel_floor`] (`None`: its row is not visible); `cursor` -/// the page's cursor (`None`: the head page). A page whose cursor is below -/// the floor's month reads every row below that month first, then walks from -/// it; a later cursor walks from its own month. Without a floor a page walks -/// from its cursor. +/// What a channel's row says about the channel's oldest rows, for +/// [`oldest_first`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ChannelFloor { + /// The channel's row is not visible. + Unknown, + /// The channel's [`channel_floor`], with no row of the channel below it: + /// the write path created the channel and marked its row + /// `history_from_creation`. + FromCreation(DateTime), + /// The channel's [`channel_floor`], which rows can be older than: a channel + /// from before the mark, or one a restore or import stored older rows in. + SplitAt(DateTime), +} + +impl ChannelFloor { + /// The floor for a channel row created at `created_at` and marked + /// `history_from_creation` (only `true` bounds it). + pub(crate) fn of(created_at: DateTime, history_from_creation: Option) -> Self { + let floor = channel_floor(created_at); + if history_from_creation == Some(true) { + Self::FromCreation(floor) + } else { + Self::SplitAt(floor) + } + } +} + +/// The first pass of an oldest-first channel page read. `cursor` is the +/// page's cursor (`None`: the head page). A page whose cursor is below the +/// month of the channel's floor walks from that month, first reading every +/// row below it when the floor is [`ChannelFloor::SplitAt`]; a later cursor +/// walks from its own month. Without the channel's row a page walks from its +/// cursor. pub(crate) fn oldest_first( now: DateTime, kinds: Option<&[i32]>, - floor: Option>, + floor: ChannelFloor, cursor: Option>, ) -> Range { - match floor.map(|floor| oldest_for(now, kinds, Some(floor))) { - Some(walk) - if walk - .from - .is_some_and(|from| cursor.is_none_or(|ts| ts < from)) => - { - Range::Below(walk) + let (floor, rows_below) = match floor { + ChannelFloor::Unknown => return Range::Forward(oldest_for(now, kinds, cursor)), + ChannelFloor::FromCreation(floor) => (floor, false), + ChannelFloor::SplitAt(floor) => (floor, true), + }; + let walk = oldest_for(now, kinds, Some(floor)); + match walk.from { + Some(from) if cursor.is_none_or(|ts| ts < from) => { + if rows_below { + Range::Below(walk) + } else { + Range::Forward(walk) + } } _ => Range::Forward(oldest_for(now, kinds, cursor)), } @@ -708,35 +743,44 @@ mod tests { } /// A channel page whose cursor is below its floor's month, the head page - /// included, reads every row below that month in one pass and then walks - /// from it. A later cursor walks from its own month, and so does a page - /// without a floor. + /// included, walks from that month. Unless the channel's row is marked + /// `history_from_creation`, it first reads every row below that month in + /// one pass. A later cursor walks from its own month, and so does a page + /// without the channel's row. #[test] fn oldest_first_reads_below_the_floor_month_in_one_pass() { let now = at(2026, 11, 4); let kinds = Some(&[9][..]); - let floor = Some(channel_floor(midnight(2026, 3, 1) + Duration::seconds(10))); - let walk = oldest_for(now, kinds, floor); + let created = midnight(2026, 3, 1) + Duration::seconds(10); + let walk = oldest_for(now, kinds, Some(channel_floor(created))); assert_eq!(walk.from, Some(midnight(2026, 2, 1))); for cursor in [ None, Some(DateTime::::UNIX_EPOCH), Some(at(2026, 1, 31)), ] { - let first = oldest_first(now, kinds, floor, cursor); - assert_eq!(first, Range::Below(walk), "{cursor:?}"); + for mark in [None, Some(false)] { + let first = oldest_first(now, kinds, ChannelFloor::of(created, mark), cursor); + assert_eq!(first, Range::Below(walk), "{mark:?}, {cursor:?}"); + assert_eq!( + first.predicate("created_at").as_deref(), + Some(" AND created_at < '2026-02-01T00:00:00Z'::timestamptz") + ); + assert_eq!(next(first, 2, 5), Some((Range::Forward(walk), 3))); + assert_eq!(next(first, 5, 5), None); + } assert_eq!( - first.predicate("created_at").as_deref(), - Some(" AND created_at < '2026-02-01T00:00:00Z'::timestamptz") + oldest_first(now, kinds, ChannelFloor::of(created, Some(true)), cursor), + Range::Forward(walk), + "{cursor:?}" ); - assert_eq!(next(first, 2, 5), Some((Range::Forward(walk), 3))); - assert_eq!(next(first, 5, 5), None); } for (floor, cursor) in [ - (floor, Some(midnight(2026, 2, 1))), - (floor, Some(at(2026, 6, 20))), - (None, Some(at(2026, 6, 20))), - (None, None), + (ChannelFloor::of(created, None), Some(midnight(2026, 2, 1))), + (ChannelFloor::of(created, None), Some(at(2026, 6, 20))), + (ChannelFloor::of(created, Some(true)), Some(at(2026, 6, 20))), + (ChannelFloor::Unknown, Some(at(2026, 6, 20))), + (ChannelFloor::Unknown, None), ] { assert_eq!( oldest_first(now, kinds, floor, cursor), diff --git a/crates/buzz-db/src/store/thread.rs b/crates/buzz-db/src/store/thread.rs index 8494ab51082..6326de6a599 100644 --- a/crates/buzz-db/src/store/thread.rs +++ b/crates/buzz-db/src/store/thread.rs @@ -675,8 +675,10 @@ 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. A newer page walks forward a window at a time - // from its cursor's month, or reads every row below the month of the - // channel's creation first and walks from there (`oldest_first`). + // from its cursor's month or the month of the channel's floor, whichever + // is later. Unless the channel is marked `history_from_creation`, a page + // that starts below that month first reads every row below it + // (`oldest_first`). let kinds: Option> = kind_filter.map(|ks| ks.iter().filter_map(|&k| i32::try_from(k).ok()).collect()); let cursor_ts = cursor.as_ref().map(|(ts, _)| *ts); @@ -721,19 +723,24 @@ pub(crate) async fn get_channel_window_on( let first = match first { Some(first) => first, None => { - let floor = read + let floor = match read .fetch( sqlx::query( - "SELECT created_at FROM channels WHERE community_id = $1 AND id = $2", + "SELECT created_at, history_from_creation FROM channels \ + WHERE community_id = $1 AND id = $2", ) .bind(community_id.as_uuid()) .bind(channel_id), ) .await? .first() - .map(|row| row.try_get::, _>("created_at")) - .transpose()? - .map(crate::store::recent_pass::channel_floor); + { + Some(row) => crate::store::recent_pass::ChannelFloor::of( + row.try_get("created_at")?, + row.try_get("history_from_creation")?, + ), + None => crate::store::recent_pass::ChannelFloor::Unknown, + }; crate::store::recent_pass::oldest_first( Utc::now(), kinds.as_deref(), @@ -2854,10 +2861,11 @@ mod postgres_tests { } /// The head page of an oldest-first window reads only the partitions it - /// needs. It reads below the month the channel was created in one pass, - /// then walks forward two months at a time, so the newer partitions are - /// planned only when the page is still short. Its rows are the oldest rows - /// of an unbounded read, for every limit. + /// needs. For a channel from before `history_from_creation`, it reads + /// below the month the channel was created in one pass, then walks + /// forward two months at a time, so the newer partitions 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() { @@ -2933,7 +2941,9 @@ mod postgres_tests { /// Rows older than the channel, as a restore or backfill stores them, and /// one inside the write path's tolerance before its creation page the /// same from both ends, for every limit: oldest first from the head and - /// from a cursor at 0, newest first in the reverse order. + /// from a cursor at 0, newest first in the reverse order. That holds for + /// a channel from before `history_from_creation` (NULL) and one an import + /// unmarked (false). #[tokio::test] #[ignore = "requires Postgres"] async fn channel_window_pages_rows_older_than_the_channel_from_both_ends() { @@ -2954,39 +2964,173 @@ mod postgres_tests { let newest: Vec<_> = oldest.iter().rev().copied().collect(); let epoch = (DateTime::::UNIX_EPOCH, vec![0u8; 32]); let mut conn = pool.acquire().await.expect("acquire"); - for limit in 1..=oldest.len() as u32 { - for (direction, start, expected) in [ - (Direction::Newer, None, &oldest), - (Direction::Newer, Some(epoch.clone()), &oldest), - (Direction::Older, None, &newest), - ] { - let mut cursor = start.clone(); - let mut rows = Vec::new(); - loop { - let window = get_channel_window_on( - &mut conn, - community, - channel, - limit, - direction, - cursor, - None, - ReadDeadline::PerRead, - ) + for mark in [None, Some(false)] { + sqlx::query( + "UPDATE channels SET history_from_creation = $3 \ + WHERE community_id = $1 AND id = $2", + ) + .bind(community.as_uuid()) + .bind(channel) + .bind(mark) + .execute(&pool) + .await + .expect("mark channel"); + for limit in 1..=oldest.len() as u32 { + for (direction, start, expected) in [ + (Direction::Newer, None, &oldest), + (Direction::Newer, Some(epoch.clone()), &oldest), + (Direction::Older, None, &newest), + ] { + let mut cursor = start.clone(); + let mut rows = Vec::new(); + loop { + let window = get_channel_window_on( + &mut conn, + community, + channel, + limit, + direction, + cursor, + None, + ReadDeadline::PerRead, + ) + .await + .expect("page"); + rows.extend(row_ids(&window)); + if !window.has_more { + break; + } + cursor = Some(window.next_cursor.expect("has_more implies next_cursor")); + } + assert_eq!( + &rows, expected, + "{mark:?}: {direction:?} from {start:?}, limit {limit}" + ); + } + } + } + } + + /// Every channel the write path creates (a channel, one with its own id, + /// a DM) pages both heads, and oldest first from a cursor before it, with + /// no partition from before its creation planned: a lock on one delays no + /// page, in a custom or a generic plan. + #[tokio::test] + #[ignore = "requires Postgres"] + async fn channel_window_pages_of_a_new_channel_skip_older_partitions() { + let pool = setup_pool().await; + let author = Keys::generate(); + let creator = author.public_key().to_bytes(); + let peer = Keys::generate().public_key().to_bytes(); + let community = CommunityId::from_uuid(make_test_community(&pool).await); + let channels = [ + crate::channel::create_channel( + &pool, + community, + &format!("new-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + &creator, + None, + &[], + false, + ) + .await + .expect("create channel") + .id, + crate::channel::create_channel_with_id( + &pool, + community, + Uuid::new_v4(), + &format!("new-{}", Uuid::new_v4()), + ChannelType::Stream, + ChannelVisibility::Open, + None, + &creator, + None, + &[], + ) + .await + .expect("create channel with id") + .0 + .id, + crate::dm::create_dm( + &pool, + community, + &[creator.as_slice(), peer.as_slice()], + &creator, + false, + &|_: &str, _: &[u8]| Ok(()), + ) + .await + .expect("create DM") + .0 + .id, + ]; + let now = Utc::now().timestamp() as u64; + let mut pages = Vec::new(); + for channel in channels { + let mut oldest_first = Vec::new(); + for age in (1..=8).rev() { + let event = EventBuilder::new(Kind::Custom(9), format!("{channel} {age}s ago")) + .custom_created_at(nostr::Timestamp::from(now - age)) + .sign_with_keys(&author) + .expect("sign"); + insert_root(&pool, community, channel, &event).await; + oldest_first.push(event.id); + } + let newest_first: Vec<_> = oldest_first.iter().rev().copied().collect(); + pages.push((channel, oldest_first, newest_first)); + } + let epoch = (DateTime::::UNIX_EPOCH, vec![0u8; 32]); + let mut conn = pool.acquire().await.expect("acquire"); + // Every partition below July 2026, all of them before these channels. + let older = ["events_p_past"] + .into_iter() + .map(String::from) + .chain((1..=6).map(|month| format!("events_p2026_{month:02}"))); + let locker = lock(&pool, &mut conn, older).await; + for generic in [false, true] { + if generic { + sqlx::query("SET plan_cache_mode = force_generic_plan") + .execute(&mut *conn) .await - .expect("page"); - rows.extend(row_ids(&window)); - if !window.has_more { - break; + .expect("force generic plans"); + } + for (channel, oldest_first, newest_first) in &pages { + for limit in [1, 2, 4] { + for (direction, cursor, expected) in [ + (Direction::Older, None, newest_first), + (Direction::Newer, None, oldest_first), + (Direction::Newer, Some(epoch.clone()), oldest_first), + ] { + let case = format!( + "{channel} {direction:?} from {cursor:?}, limit {limit}, generic {generic}" + ); + let window = get_channel_window_on( + &mut conn, + community, + *channel, + limit as u32, + direction, + cursor, + None, + ReadDeadline::PerRead, + ) + .await + .unwrap_or_else(|e| panic!("{case}: {e:?}")); + assert_eq!(row_ids(&window), expected[..limit].to_vec(), "{case}"); + assert!(window.has_more, "{case}"); } - cursor = Some(window.next_cursor.expect("has_more implies next_cursor")); } - assert_eq!( - &rows, expected, - "{direction:?} from {start:?}, limit {limit}" - ); } } + sqlx::query("RESET plan_cache_mode") + .execute(&mut *conn) + .await + .expect("reset plan_cache_mode"); + unlock(locker, &mut conn).await; } /// A cursor page whose channel's row is gone walks from its cursor: a diff --git a/docs/database.md b/docs/database.md index 2f9a51ea278..dc79f054b4b 100644 --- a/docs/database.md +++ b/docs/database.md @@ -267,7 +267,10 @@ holding a write-blocking lock. Scans that do not block writes, such as enforces the floor, and an operator session runs none of it, so nothing in the database stops the write. Its PR MUST document a reviewed procedure that keeps replica routing closed from before the first - batch until its WAL has replayed on every replica. + batch until its WAL has replayed on every replica. When such a row is also + older than its channel's `created_at` less the floor's tolerance, the same + transaction MUST set that channel's `history_from_creation` to false: an + oldest-first page of a channel marked true reads nothing older. - A script MUST NOT disable triggers or set `session_replication_role`. - The normal write path that maintains the new invariant MUST be fully rolled out, with old writers drained, before the backfill starts. The backfill spec diff --git a/migrations/0106_channel_history_from_creation.sql b/migrations/0106_channel_history_from_creation.sql new file mode 100644 index 00000000000..922dcb465c0 --- /dev/null +++ b/migrations/0106_channel_history_from_creation.sql @@ -0,0 +1,8 @@ +-- Marks a channel whose rows are all at or after its creation, less the write +-- path's created_at tolerance, so an oldest-first page skips the partitions +-- before it. The relay sets it true when it creates a channel. Existing rows +-- stay NULL, which, like false, keeps the read below the channel's floor: a +-- restore or backfill may have stored older rows there. No default, so no +-- existing row is marked. +SET LOCAL lock_timeout = '5s'; +ALTER TABLE channels ADD COLUMN history_from_creation BOOLEAN; diff --git a/schema/tables/public/channels.sql b/schema/tables/public/channels.sql index c3347114fe7..991cb754f27 100644 --- a/schema/tables/public/channels.sql +++ b/schema/tables/public/channels.sql @@ -42,6 +42,12 @@ CREATE TABLE channels ( -- channel listings for non-members. Matters only while the channel is open. unlisted BOOLEAN NOT NULL DEFAULT FALSE, auto_join BOOLEAN NOT NULL DEFAULT false, + -- True when every row of the channel is at or after its creation, less + -- the write path's created_at tolerance: the relay sets it when it creates + -- the channel. NULL or false lets rows be older (a channel from before + -- this column, or one a restore or import stored older rows in). No + -- default, so adding the column marks no existing channel. + history_from_creation BOOLEAN, PRIMARY KEY (community_id, id), CONSTRAINT chk_channels_id_not_nil CHECK (id <> '00000000-0000-0000-0000-000000000000'::uuid) );