Skip to content

Commit c3b64cb

Browse files
committed
feat(relay): page thread windows toward newer replies
A thread-mode window could only walk from the newest reply toward older ones, so a client could not open a thread at its first reply or at an unread reply and load forward. `direction: "newer"` walks the same order in reverse, continuing with `since`/`after_id`, under its own signed binding and bounds. Newer pages always read from the writer, since even a recently checked replica can miss a committed reply and sign a false exhausted page. Signed-off-by: Liching Li <liching@squareup.com>
1 parent 832ff39 commit c3b64cb

7 files changed

Lines changed: 239 additions & 47 deletions

File tree

‎crates/buzz-core/src/thread_window.rs‎

Lines changed: 103 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ pub const MAX_LIMIT: u32 = 200;
1313
/// never reply-budget candidates, even if they have thread metadata.
1414
pub const ROW_KINDS: [u32; 4] = [9, 40002, 45001, 45003];
1515

16-
/// A position in `(created_at DESC, id ASC)` order.
16+
/// A position in `(created_at DESC, id ASC)` order. Newer windows walk the
17+
/// same order in reverse, so a cursor from either direction splits one sequence.
1718
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1819
pub struct Cursor {
1920
/// Nonnegative Unix seconds, representable by PostgreSQL/chrono.
@@ -31,6 +32,26 @@ impl Cursor {
3132
}
3233
}
3334

35+
/// Which way a window walks from its cursor.
36+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37+
pub enum Direction {
38+
/// Newest first: `created_at DESC, id ASC`, continuing with `until`/`before_id`.
39+
#[default]
40+
Older,
41+
/// Oldest first: `created_at ASC, id DESC`, continuing with `since`/`after_id`.
42+
Newer,
43+
}
44+
45+
impl Direction {
46+
/// The wire name used in the request, the binding and the bounds content.
47+
pub fn as_str(self) -> &'static str {
48+
match self {
49+
Self::Older => "older",
50+
Self::Newer => "newer",
51+
}
52+
}
53+
}
54+
3455
/// Validated pagination and response-affecting arguments. Construct with
3556
/// [`Request::parse`]; the database also validates public inputs defensively.
3657
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -45,7 +66,10 @@ pub struct Request {
4566
pub depth: u32,
4667
/// Sorted, deduplicated conversation row kinds.
4768
pub kinds: Vec<u32>,
48-
/// Request upper bound; absent means newest page.
69+
/// Traversal direction; absent on the wire means older.
70+
pub direction: Direction,
71+
/// Exclusive start position; absent means the newest page (older) or the
72+
/// oldest page (newer).
4973
pub cursor: Option<Cursor>,
5074
/// Include root/retained-row edits, reactions and deletion closure.
5175
pub include_aux: bool,
@@ -89,8 +113,11 @@ impl Request {
89113
"kinds",
90114
"limit",
91115
"depth_limit",
116+
"direction",
92117
"until",
93118
"before_id",
119+
"since",
120+
"after_id",
94121
"include_aux",
95122
];
96123
if object.keys().any(|key| !FIELDS.contains(&key.as_str())) {
@@ -123,20 +150,39 @@ impl Request {
123150
.collect::<Result<Vec<_>, _>>()?;
124151
kinds.sort_unstable();
125152
kinds.dedup();
126-
let cursor = match (raw.get("until"), raw.get("before_id")) {
153+
let direction = match raw.get("direction") {
154+
None => Direction::Older,
155+
Some(v) if v == "older" => Direction::Older,
156+
Some(v) if v == "newer" => Direction::Newer,
157+
Some(_) => return Err("thread_window: direction must be \"older\" or \"newer\"".into()),
158+
};
159+
let (time_key, id_key, other_time, other_id) = match direction {
160+
Direction::Older => ("until", "before_id", "since", "after_id"),
161+
Direction::Newer => ("since", "after_id", "until", "before_id"),
162+
};
163+
if raw.get(other_time).is_some() || raw.get(other_id).is_some() {
164+
return Err(format!(
165+
"thread_window: {} windows continue with {time_key} and {id_key}",
166+
direction.as_str()
167+
));
168+
}
169+
let cursor = match (raw.get(time_key), raw.get(id_key)) {
127170
(None, None) => None,
128171
(Some(ts), Some(id)) => {
129172
let cursor = Cursor {
130-
created_at: ts
131-
.as_i64()
132-
.filter(|n| *n >= 0)
133-
.ok_or("thread_window: until must be nonnegative integer seconds")?,
173+
created_at: ts.as_i64().filter(|n| *n >= 0).ok_or_else(|| {
174+
format!("thread_window: {time_key} must be nonnegative integer seconds")
175+
})?,
134176
id: event_id(id)?,
135177
};
136178
cursor.timestamp()?;
137179
Some(cursor)
138180
}
139-
_ => return Err("thread_window requires both until and before_id, or neither".into()),
181+
_ => {
182+
return Err(format!(
183+
"thread_window requires both {time_key} and {id_key}, or neither"
184+
))
185+
}
140186
};
141187
let include_aux = match raw.get("include_aux") {
142188
None => false,
@@ -150,6 +196,7 @@ impl Request {
150196
limit,
151197
depth,
152198
kinds,
199+
direction,
153200
cursor,
154201
include_aux,
155202
})
@@ -164,7 +211,7 @@ impl Request {
164211
let canonical = json!([
165212
"tw",
166213
1,
167-
"older",
214+
self.direction.as_str(),
168215
resolved_host,
169216
reader_hex,
170217
self.channel.to_string(),
@@ -205,6 +252,9 @@ mod tests {
205252
("offset", json!(0)),
206253
("authors", json!([])),
207254
("since", json!(1)),
255+
("after_id", json!("ab".repeat(32))),
256+
("direction", json!("both")),
257+
("direction", json!(null)),
208258
("#p", json!([])),
209259
("kinds", json!([7])),
210260
("kinds", json!([])),
@@ -228,6 +278,36 @@ mod tests {
228278
f["before_id"] = json!("a".repeat(64));
229279
assert!(Request::parse(&f).is_err(), "{f}");
230280
}
281+
// A newer window continues only with since/after_id.
282+
for (key, value) in [
283+
("since", json!(1)),
284+
("after_id", json!("ab".repeat(32))),
285+
("until", json!(1)),
286+
("before_id", json!("ab".repeat(32))),
287+
] {
288+
let mut f = filter();
289+
f["direction"] = json!("newer");
290+
f[key] = value;
291+
assert!(Request::parse(&f).is_err(), "{f}");
292+
}
293+
let mut f = filter();
294+
f["direction"] = json!("newer");
295+
f["until"] = json!(1);
296+
f["before_id"] = json!("ab".repeat(32));
297+
assert!(Request::parse(&f).is_err(), "{f}");
298+
f.as_object_mut().unwrap().remove("until");
299+
f.as_object_mut().unwrap().remove("before_id");
300+
f["since"] = json!(1);
301+
f["after_id"] = json!("AB".repeat(32));
302+
let request = Request::parse(&f).unwrap();
303+
assert_eq!(request.direction, Direction::Newer);
304+
assert_eq!(
305+
request.cursor,
306+
Some(Cursor {
307+
created_at: 1,
308+
id: "ab".repeat(32)
309+
})
310+
);
231311
}
232312
#[test]
233313
fn binding_normalizes_defaults_and_binds_every_argument() {
@@ -246,6 +326,7 @@ mod tests {
246326
explicit["limit"] = json!(50);
247327
explicit["depth_limit"] = json!(100);
248328
explicit["include_aux"] = json!(false);
329+
explicit["direction"] = json!("older");
249330
explicit["#e"] = json!(["AB".repeat(32)]);
250331
assert_eq!(expected, binding(&explicit));
251332
for (key, val) in [
@@ -264,9 +345,21 @@ mod tests {
264345
for (host, reader) in [("other.example", "ab"), ("relay.example", "cd")] {
265346
assert_ne!(expected, request.binding(host, &reader.repeat(32)));
266347
}
267-
let mut changed = f;
348+
let mut changed = f.clone();
268349
changed["until"] = json!(0);
269350
changed["before_id"] = json!("ab".repeat(32));
270351
assert_ne!(expected, binding(&changed));
352+
let mut newer = f.clone();
353+
newer["direction"] = json!("newer");
354+
assert_eq!(
355+
binding(&newer),
356+
"tw:1:e403992cd5cdaed6fd7ed2a6eda2d60b1cd73e0932b56a22ba5eb863fb6aa397"
357+
);
358+
let mut newer_cursor = newer.clone();
359+
newer_cursor["since"] = json!(0);
360+
newer_cursor["after_id"] = json!("ab".repeat(32));
361+
// The same cursor walking the other way is a different request.
362+
assert_ne!(binding(&changed), binding(&newer_cursor));
363+
assert_ne!(binding(&newer), binding(&newer_cursor));
271364
}
272365
}

‎crates/buzz-db/src/runtime/tests/thread_window_postgres_tests.rs‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() {
2929
insert_thread_reply(pool, cid, channel, &root, &old).await;
3030
}
3131
insert_thread_reply(&writer, cid, channel, &root, &middle).await;
32-
let db = Db::from_pools(writer.clone(), replica.clone());
32+
let mut db = Db::from_pools(writer.clone(), replica.clone());
3333
let community = CommunityId::from_uuid(cid);
3434
let mut req = request(channel, &root, base + 30);
3535
// An old delivered tail does not justify an uncovered request upper bound.
@@ -66,6 +66,35 @@ async fn thread_window_upper_fence_terminal_snapshot_and_fallback() {
6666
assert!(!session.is_replica());
6767
assert_eq!(head.rows[0].event.id, middle.id);
6868
drop(session);
69+
// A newer page ends at the newest reply, so neither a cursor below a
70+
// covered upper bound nor a freshly checked replica may sign exhaustion.
71+
db.set_replica_read_max_age_for_tests(Some(Duration::from_secs(30)));
72+
let (_, session) = db
73+
.get_thread_window_with_session(community, &req, &mut ScanBudget::default())
74+
.await
75+
.unwrap();
76+
assert!(session.is_replica(), "the max age admits this replica");
77+
drop(session);
78+
let mut later = req.clone();
79+
later.direction = buzz_core::thread_window::Direction::Newer;
80+
for cursor in [
81+
None,
82+
Some(buzz_core::thread_window::Cursor {
83+
created_at: base as i64 + 10,
84+
id: old.id.to_hex(),
85+
}),
86+
] {
87+
later.cursor = cursor;
88+
let (page, session) = db
89+
.get_thread_window_with_session(community, &later, &mut ScanBudget::default())
90+
.await
91+
.unwrap();
92+
assert!(!session.is_replica());
93+
assert_eq!(page.rows.last().map(|e| e.event.id), Some(middle.id));
94+
assert!(!page.has_more);
95+
drop(session);
96+
}
97+
db.set_replica_read_max_age_for_tests(None);
6998

7099
// Complete the reply fixture, then lag *recent* edits and channel-less
71100
// deletions. Coverage of old replies is not a freshness proof for aux.

‎crates/buzz-db/src/store/thread_window.rs‎

Lines changed: 49 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
//! NIP-CW thread-mode newest-first reply windows. This path deliberately does not change
1+
//! NIP-CW thread-mode reply windows, newest-first or oldest-first. This path deliberately does not change
22
//! legacy forward threads or the permissive generic event reconstruction path.
33
44
use buzz_core::{
5-
thread_window::{Cursor, Request, MAX_LIMIT, ROW_KINDS},
5+
thread_window::{Cursor, Direction, Request, MAX_LIMIT, ROW_KINDS},
66
CommunityId, StoredEvent,
77
};
88
use chrono::{DateTime, Utc};
@@ -20,7 +20,8 @@ use buzz_datastore_tracing::datastore_span;
2020
/// authoritative scan bounds.
2121
#[derive(Debug)]
2222
pub struct ThreadWindow {
23-
/// Reconstructed replies, newest first (id ascending for ties).
23+
/// Reconstructed replies in the request's direction: newest first (id
24+
/// ascending for ties), or the exact reverse for newer windows.
2425
pub rows: Vec<StoredEvent>,
2526
/// Another eligible raw reply exists after this page.
2627
pub has_more: bool,
@@ -121,33 +122,38 @@ async fn select_window(
121122
.push_bind(request.channel)
122123
.push(" AND tm.depth BETWEEN 1 AND ")
123124
.push_bind(request.depth as i32);
125+
// Newer windows scan the same index backwards.
126+
let (before, after, order) = match request.direction {
127+
Direction::Older => ("<", ">", "tm.event_created_at DESC, tm.event_id ASC"),
128+
Direction::Newer => (">", "<", "tm.event_created_at ASC, tm.event_id DESC"),
129+
};
124130
if let Some(cursor) = &request.cursor {
125131
let (ts, id) = cursor_key(cursor)?;
126-
// The redundant upper timestamp bound gives PostgreSQL an index range
127-
// start instead of filtering all newer keys at a deep cursor.
128-
q.push(" AND tm.event_created_at <= ")
132+
// The redundant timestamp bound gives PostgreSQL an index range start
133+
// instead of filtering every key on the far side of a deep cursor.
134+
q.push(format!(" AND tm.event_created_at {before}= "))
129135
.push_bind(ts)
130-
.push(" AND (tm.event_created_at < ")
136+
.push(format!(" AND (tm.event_created_at {before} "))
131137
.push_bind(ts)
132138
.push(" OR (tm.event_created_at = ")
133139
.push_bind(ts)
134-
.push(" AND tm.event_id > ")
140+
.push(format!(" AND tm.event_id {after} "))
135141
.push_bind(id)
136142
.push("))");
137143
}
138144
// Fetch by the event PK before testing visibility, so missing statistics
139145
// cannot turn a selective live/kind index into a root-wide scan per reply.
140146
// PK uniqueness makes the inner LIMIT 1 exact. All eligibility predicates
141147
// still precede the *outer* limit+1 that establishes page bounds.
142-
q.push(" ORDER BY tm.event_created_at DESC, tm.event_id ASC OFFSET 0) tm \
148+
q.push(format!(" ORDER BY {order} OFFSET 0) tm \
143149
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 \
144150
FROM events e WHERE e.community_id = tm.community_id \
145151
AND e.created_at = tm.event_created_at AND e.id = tm.event_id LIMIT 1) e ON true \
146-
WHERE e.channel_id = ")
152+
WHERE e.channel_id = "))
147153
.push_bind(request.channel)
148154
.push(" AND e.deleted_at IS NULL AND e.kind = ANY(")
149155
.push_bind(request.kinds.iter().map(|k| *k as i32).collect::<Vec<_>>())
150-
.push(") ORDER BY tm.event_created_at DESC, tm.event_id ASC LIMIT ")
156+
.push(format!(") ORDER BY {order} LIMIT "))
151157
.push_bind(i64::from(request.limit) + 1);
152158
// Selectivity varies drastically with root/depth/cursor. A cached generic
153159
// plan can sort the entire root (and exceeded the SQL deadline in paging
@@ -204,10 +210,11 @@ async fn writer_window(
204210
}
205211

206212
impl Db {
207-
/// Newest-first thread page and its proved replica transaction. Backward
208-
/// cursors supply an upper bound, including terminal pages; no forward
209-
/// thread "last delivered row is newest" inference is used. Head routing
210-
/// inherits the existing default-off budget. Writer follow-ups are pooled,
213+
/// Thread page and its proved replica transaction. Older cursors supply
214+
/// an upper bound, including terminal pages; no forward thread "last
215+
/// delivered row is newest" inference is used. Head pages end at the
216+
/// newest reply, so they inherit the existing default-off budget. Newer
217+
/// pages always read the writer. Writer follow-ups are pooled,
211218
/// not a snapshot spanning the response or subsequent history pages. The
212219
/// caller must share `budget` with every window and auxiliary scan in the request.
213220
#[datastore_span(name = "get_thread_window", system = "postgresql")]
@@ -218,19 +225,34 @@ impl Db {
218225
budget: &mut ScanBudget,
219226
) -> Result<(ThreadWindow, ReadSession)> {
220227
let cursor = request.cursor.as_ref().map(cursor_key).transpose()?;
221-
let path = if cursor.is_some() {
222-
"thread_window_cursor"
223-
} else {
224-
"thread_window_head"
228+
let (path, predicate) = match (request.direction, &cursor) {
229+
// Even a freshly checked replica can miss a committed reply and
230+
// sign a false exhausted newer page.
231+
(Direction::Newer, _) => ("thread_window_newer", None),
232+
(Direction::Older, Some(_)) => (
233+
"thread_window_cursor",
234+
Some(RoutePredicate::from_channel_cursor(
235+
request.channel,
236+
&cursor,
237+
)),
238+
),
239+
(Direction::Older, None) => ("thread_window_head", Some(RoutePredicate::Bounded)),
225240
};
226-
if let RouteDecision::Replica(mut tx, _, reason) = self
227-
.route_read(
228-
path,
229-
RoutePredicate::from_channel_cursor(request.channel, &cursor),
230-
crate::observability::ReaderOperation::SubscriptionHistory,
231-
)
232-
.await?
233-
{
241+
let decision = match predicate {
242+
Some(predicate) => Some(
243+
self.route_read(
244+
path,
245+
predicate,
246+
crate::observability::ReaderOperation::SubscriptionHistory,
247+
)
248+
.await?,
249+
),
250+
None => {
251+
Self::record_route(path, "writer", "newer_direction");
252+
None
253+
}
254+
};
255+
if let Some(RouteDecision::Replica(mut tx, _, reason)) = decision {
234256
let result = async {
235257
set_deadline(&mut tx).await?;
236258
select_window(&mut tx, community, request, budget).await

0 commit comments

Comments
 (0)