diff --git a/crates/buzz-core/src/thread_window.rs b/crates/buzz-core/src/thread_window.rs index c7526d245ec..38a9bc26407 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,7 +98,9 @@ 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, @@ -89,8 +144,11 @@ impl Request { "kinds", "limit", "depth_limit", + "direction", "until", "before_id", + "after", + "after_id", "include_aux", ]; if object.keys().any(|key| !FIELDS.contains(&key.as_str())) { @@ -123,20 +181,25 @@ 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, @@ -150,6 +213,7 @@ impl Request { limit, depth, kinds, + direction, cursor, include_aux, }) @@ -158,13 +222,14 @@ impl Request { /// 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!([ "tw", 1, - "older", + self.direction.as_str(), resolved_host, reader_hex, self.channel.to_string(), @@ -198,6 +263,10 @@ mod tests { ("depth_limit", json!(101)), ("depth_limit", json!(-1)), ("include_aux", json!("true")), + ("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 +297,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 +344,14 @@ mod tests { explicit["limit"] = json!(50); explicit["depth_limit"] = json!(100); explicit["include_aux"] = json!(false); + explicit["direction"] = json!("older"); 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")), ("kinds", json!([40002])), ("#e", json!(["cd".repeat(32)])), ("#h", json!([Uuid::new_v4()])), @@ -269,4 +369,36 @@ mod tests { changed["before_id"] = json!("ab".repeat(32)); assert_ne!(expected, binding(&changed)); } + + /// `newer` binds the canonical array NIP-CW specifies. + #[test] + 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)); + let expected = json!([ + "tw", + 1, + "newer", + host, + reader, + Uuid::nil().to_string(), + root, + 50, + 100, + [9], + [5, "ef".repeat(32)], + 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/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/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/runtime/tests.rs b/crates/buzz-db/src/runtime/tests.rs index 667c906b4bd..d85dd708af6 100644 --- a/crates/buzz-db/src/runtime/tests.rs +++ b/crates/buzz-db/src/runtime/tests.rs @@ -1012,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. @@ -1055,6 +1055,38 @@ 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, 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, + 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 +1276,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 +1363,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 +1395,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 +1441,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 +1459,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 +1488,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 +1544,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 +3516,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..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,6 +66,24 @@ 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, 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)})) + .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); + 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/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/event.rs b/crates/buzz-db/src/store/event.rs index 59b0222c9bf..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, @@ -5127,6 +5139,7 @@ mod postgres_tests { community, channel, LIMIT as u32, + buzz_core::thread_window::Direction::Older, window_cursor, Some(&[9]), ReadDeadline::PerRead, @@ -5175,6 +5188,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..a4dce483ebc 100644 --- a/crates/buzz-db/src/store/recent_pass.rs +++ b/crates/buzz-db/src/store/recent_pass.rs @@ -32,10 +32,35 @@ //! 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. A +//! 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 +//! 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 +90,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 +150,11 @@ pub(crate) enum Range { Recent(Split), /// `created_at < floor`. 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 { @@ -84,23 +165,29 @@ 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), + Range::Below(window) => (None, window.from), }; - 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 +236,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 +253,122 @@ 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`]). `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 write the relay serves stores an older row. A restore +/// or backfill that bypasses that check (see [`crate::replica_fence`]) can, +/// 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) +} + +/// 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 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, + 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)) +} + +/// 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: ChannelFloor, + cursor: Option>, +) -> Range { + 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)), + } +} + /// 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, +/// 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 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()?), + Range::Below(window) => Range::Forward(window), + _ => 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 +618,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(_) | Range::Below(_) => unreachable!(), }) .take(n as usize), ); @@ -446,4 +637,250 @@ 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, + ), + ]; + 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 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!( + first(edge - Duration::seconds(1)), + Some(midnight(2026, 2, 1)) + ); + } + + /// A channel page whose cursor is below its floor's month, the head page + /// 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 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)), + ] { + 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!( + oldest_first(now, kinds, ChannelFloor::of(created, Some(true)), cursor), + Range::Forward(walk), + "{cursor:?}" + ); + } + for (floor, cursor) in [ + (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), + 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, + /// 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..6326de6a599 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,23 @@ 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 a window at a time + // 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 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); + // 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 => Some( + crate::store::recent_pass::split_for(Utc::now(), kinds.as_deref(), None, cursor_ts) + .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; let pass_query = |range: Range, pass_limit: i64| { @@ -681,9 +698,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 +707,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 { + Some(Range::All) => { crate::event::fetch_with_read_deadline( &mut *conn, pass_query(Range::All, probe_limit), @@ -701,12 +716,41 @@ pub(crate) async fn get_channel_window_on( ) .await? } - Some(split) => { - // One snapshot and one deadline for both passes (see - // `ReadTransaction`). + first => { + // 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 = match read + .fetch( + sqlx::query( + "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() + { + 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(), + floor, + cursor_ts, + ) + } + }; 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 +1112,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 +1125,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,6 +1150,9 @@ 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`]). + /// - **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 @@ -1119,28 +1174,37 @@ 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), - 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, community_id, channel_id, limit, + direction, cursor.clone(), kind_filter, crate::event::ReadDeadline::Session, @@ -1188,6 +1252,7 @@ impl Db { community_id, channel_id, limit, + direction, cursor, kind_filter, ) @@ -2132,6 +2197,163 @@ 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"); + } + + /// 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 + } + + /// 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, + ) { + 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, @@ -2199,9 +2421,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 +2491,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 +2547,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 +2635,7 @@ mod postgres_tests { community, channel.id, 1, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2411,6 +2655,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2429,6 +2674,7 @@ mod postgres_tests { community, channel.id, 4, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2442,6 +2688,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2455,6 +2702,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, Some(cursor), None, ReadDeadline::PerRead, @@ -2503,6 +2751,7 @@ mod postgres_tests { community, channel.id, 1, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2515,6 +2764,7 @@ mod postgres_tests { community, channel.id, 2, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2532,6 +2782,401 @@ 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() { + let pool = setup_pool().await; + let (channel, community, oldest_first) = dated_channel( + &pool, + &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; + let expected = |range: std::ops::Range| { + oldest_first[range].iter().map(|e| e.id).collect::>() + }; + 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 = newer_page(&mut conn, community, channel, 2, cursor) + .await + .expect("forward page"); + pages.push(row_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 [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("a full early pass never touches the locked partitions"); + assert_eq!(row_ids(&window), expected(2..3)); + assert!(window.has_more); + let failed = newer_page(&mut conn, community, channel, 2, after_march()).await; + assert!( + lock_timed_out(&failed), + "a failed later pass must fail the window, got {:?}", + failed.map(|w| (w.rows.len(), w.has_more)) + ); + 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 = newer_page( + &mut conn, + community, + channel, + limit, + cursor_at(&oldest_first[after]), + ) + .await + .expect("cursor page"); + assert_eq!((row_ids(&window), window.has_more), (expected(rows), more)); + } + } + + /// The head page of an oldest-first window reads only the partitions it + /// 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() { + 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-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; + let mut conn = pool.acquire().await.expect("acquire"); + + // 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) + .bind(i64::from(limit)) + .fetch_all(&pool) + .await + .expect("unbounded read"); + let window = newer_page(&mut conn, community, channel, limit, None) + .await + .expect("head page"); + let ids: Vec<_> = row_ids(&window) + .iter() + .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()); + } + + // Another session locks the partitions the page must not plan. A + // page needing a locked one fails instead of returning a short page. + let [_first, june, newest] = distinct_partitions( + &pool, + [oldest_first[0].id, oldest_first[4].id, oldest_first[5].id], + ) + .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. + for (limit, rows) in [(1, 1), (3, 3)] { + let window = newer_page(&mut conn, community, channel, limit, None) + .await + .expect("a page that fills early never plans the locked partitions"); + let expected: Vec<_> = oldest_first[..rows].iter().map(|e| e.id).collect(); + assert_eq!(row_ids(&window), expected, "limit {limit}"); + assert!(window.has_more, "limit {limit}"); + } + let failed = newer_page(&mut conn, community, channel, 4, None).await; + assert!( + 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)) + ); + unlock(locker, &mut conn).await; + } + + /// 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. 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() { + let pool = setup_pool().await; + let (channel, community, oldest_first) = dated_channel( + &pool, + &Keys::generate(), + "2026-03-01T00:05: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"); + 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("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}"); + } + } + } + } + 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 + /// 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. @@ -2562,6 +3207,7 @@ mod postgres_tests { community, channel_id, 10, + Direction::Older, None, None, ReadDeadline::PerRead, @@ -2656,7 +3302,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 +3396,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 +3504,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..d0724cc89e6 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,10 +220,13 @@ 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 - /// inherits the existing default-off budget. Writer follow-ups are pooled, + /// 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 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")] @@ -212,19 +237,26 @@ 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), - 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/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..a6861dd1bff 100644 --- a/crates/buzz-relay/src/api/bridge/thread_window.rs +++ b/crates/buzz-relay/src/api/bridge/thread_window.rs @@ -271,7 +271,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..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 @@ -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,180 @@ async fn thread_window_real_query_signed_bounds_and_sentinel_aux() { } } +/// 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() { + 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])); + 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); + 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(); + 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 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!(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); +} + +/// 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 +591,22 @@ 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")), ] { 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..95d4aa0ed0a 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,15 @@ 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 +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 `limit`, and reports the probe result in `39006`. The sentinel row never @@ -114,6 +131,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, @@ -126,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: + 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/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/docs/nips/NIP-CW.md b/docs/nips/NIP-CW.md index c5ad73ad66d..79b60d63d80 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,23 @@ 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, 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. + +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 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 +93,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 +118,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,15 +179,16 @@ 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. +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). @@ -201,7 +222,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 +266,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 +295,8 @@ 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). 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,7 +312,9 @@ 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`. @@ -349,15 +374,27 @@ 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`) 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] +``` + +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 +410,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 +432,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. 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) );