Skip to content

Commit 890824f

Browse files
wpfleger96Duncanbrow
authored
feat(read-state): sync mark read, channel mark unread and thread follows (#9501)
Reading, mark read, whole-channel mark unread and thread follow choices now sync across a person's installations. This PR specifies the rules in NIP-RS and implements them in the mobile app. ## Spec (`docs/nips/NIP-RS.md`) - Defines *catch-up* and *displayed*. - A catch-up advances the channel's own frontier (top-level messages) or `thread:<root>`. `activity:` and `thread-activity:` become read-only legacy keys. - Explicit mark read is synchronized state. A first explicit read of a message with no override group writes only its `msg:` frontier. Display, dwell, scroll, catch-up and mention visibility create no `msg:` entries. - Only whole-channel override groups are published, merged and cleared with the counter. Readers ignore peer `msg:` and `thread:` groups. - Single-message and thread mark unread stay on the device. They end once the merged frontier covering them passes their baseline, from any installation, or on display, catch-up or explicit read. The section also states clearing scope, the accepted concurrency limitation and capacity. - When the merged override union no longer fits the primary, the client rewrites the primary compactly from the groups its last published primary carried, each canonical against current frontiers. It never omits merged groups or tombstone floors that primary carried, and override actions fail visibly. - Adds Buzz Thread Follow Choices: `thread-follows:<32hex>` coordinates, validation, three-state verdict, last-writer merge with ties going to unfollow, publication and recovery, legacy import at `at = 0`, and capacity. ## Mobile - Catch-up writes the main frontier. A flat timeline reads up to the newest top-level message it reached. - Explicit mark read publishes. Passive `msg:` marks stay on the device. - Whole-channel mark unread publishes an override group and merges peer groups. An explicit read or catch-up clears it, even when no frontier moves. The action fails visibly at the uint32 limit or when the primary is full. A synced clear the primary can't carry is rolled back, and the channel view reports it once while the failure stands. - Device-local message and Inbox unread overrides record a baseline and clear when a covering frontier passes it, including one merged from a peer. - Thread follows move from local storage to the synced `thread-follows:` slots. They share the read-state `client_id`, journal, `created_at` sequence, snapshot and live subscription, and spill across up to 16 slots with stable placement. An unreadable coordinate marks follow state incomplete and blocks this installation's follow publication. - Follow and unfollow are refused on every cold start of the writer until its first complete recovery of its own state succeeds and every owned follow head is readable. Cached follows show at once. A refused tap changes nothing and shows "Follow choices are not ready. Connect and try again." Reads, catch-up and both kinds of mark unread are not gated. - A follow tap is accepted only once journaled. The accepted own head, pending edits and the exact in-flight packet are kept apart, so a retry or restore never drops or re-attributes an edit. - Pre-sync local follows are imported at `at = 0` after a complete merge, once their channel is known from a relay event. An imported key is settled, and its legacy copy retired, only when the journal write the import awaited covered it and that entry is still current. - An explicit unfollow suppresses ordinary replies at live and catch-up admission. A change in follow choices drops the unread replies already counted for an unfollowed thread. A newly followed thread re-runs catch-up only for its own channel. - A reading clear refused because the view hasn't completely loaded is retried after the next complete snapshot, including when publishing was shut off at the time. The view also counts as not completely loaded while the live subscription is reconnecting, so a read made while the phone is offline can't erase a newer unread mark set on another device. Offline, whole-channel mark unread is still refused, with a message. - Read-state events, including live ones, are verified with native libsecp256k1 before they are used. - A pending unread packet is counted as published only when no newer own head outranks it. When a newer head supersedes it, a successor is built above that head from the saved intent, and a late echo of a replaced packet doesn't overwrite what was published. - When the merged unread state overfills the primary and the compact fallback can't carry a pending mark, the packet stays pending and the "read state full" error shows. Other queued reads and follows in the same flush still publish. - When this installation's own unread record can't be decoded, only the unread step is held: that record isn't overwritten, its pending marks stay queued and the sync error shows. Other queued reads and follows in the same flush still publish. - The sync notice stays up after an unsupported refusal until a new session. Offline, it can't be tapped and says it will retry when back online. - Two-device fixtures against an in-memory relay cover channel round-trips and clears, stray message groups, the first explicit message read, the primary cap, follow propagation, same-second and backward-clock follow publication, legacy import, retry after a failed publish, unreadable coordinates and slot packing. Recovery fixtures cover the startup gate, journal failures during flush, interleaved legacy imports, and restore of an older journal. ## Relay - Conforming `thread-follows:<32 hex>` records get the NIP-RS treatment: a replaced record is purged, and a stale resend of an older one is refused. Records with a mismatched `t` tag keep ordinary replaceable-event behavior. ## Known gap - An unread packet held for capacity can age past the relay's timestamp window. The relay then refuses it, and the refusal path retires it without the capacity check, so the error clears and other installations don't get that mark. The mark stays on the device. Related: [block/buzz-app#3552](block/buzz-app#3552) --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Signed-off-by: Will Pfleger <wpfleger@squareup.com> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz>
1 parent cda68a9 commit 890824f

55 files changed

Lines changed: 7872 additions & 936 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,16 @@ use crate::{
1111
};
1212

1313
/// SQL predicate over an `events` row for a conforming NIP-RS read-state
14-
/// coordinate: kind 30078, a `read-state:<32 lowercase hex>` d-tag carried by
15-
/// exactly one `d` tag, and exactly one `["t", "read-state"]` tag.
14+
/// coordinate: kind 30078, a `read-state:<32 lowercase hex>` (read positions),
15+
/// `read-state-unread-v2:<32 lowercase hex>` (unread record) or
16+
/// `thread-follows:<32 lowercase hex>` (thread follows) d-tag carried by
17+
/// exactly one `d` tag, and exactly one tag naming that same namespace
18+
/// (`["t", "read-state"]`, `["t", "read-state-unread-v2"]` or
19+
/// `["t", "thread-follows"]`).
1620
macro_rules! nip_rs_event_predicate {
1721
() => {
1822
"(kind = 30078 \
19-
AND d_tag ~ '^read-state:[0-9a-f]{32}$' \
23+
AND d_tag ~ '^(read-state(-unread-v2)?|thread-follows):[0-9a-f]{32}$' \
2024
AND (SELECT count(*) \
2125
FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \
2226
WHERE jsonb_typeof(tag) = 'array' AND tag->0 = '\"d\"'::jsonb) = 1 \
@@ -26,7 +30,7 @@ macro_rules! nip_rs_event_predicate {
2630
AND jsonb_typeof(tag->1) = 'string' AND tag->>0 = 'd' AND tag->>1 = d_tag) \
2731
AND (SELECT count(*) \
2832
FROM jsonb_array_elements(CASE WHEN jsonb_typeof(tags) = 'array' THEN tags ELSE '[]'::jsonb END) tag \
29-
WHERE tag = '[\"t\", \"read-state\"]'::jsonb) = 1)"
33+
WHERE tag = jsonb_build_array('t', split_part(d_tag, ':', 1))) = 1)"
3034
};
3135
}
3236

‎crates/buzz-db/src/store/event_deletion/postgres_tests.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,12 @@ async fn retention_free_contract() {
167167
let (db, community, channel) = fixture().await;
168168
let (other, other_channel) = tenant(&db.pool).await;
169169
let slot = format!("read-state:{}", "b".repeat(32));
170+
let unread = format!("read-state-unread-v2:{}", "b".repeat(32));
170171
let marker = event(45011, JAN, vec![]);
171172
seed(&db, community, &marker, channel).await;
172173
for (kind, d, extra) in [
173174
(30078, slot.as_str(), ["t", "read-state"]),
175+
(30078, unread.as_str(), ["t", "read-state-unread-v2"]),
174176
(
175177
30003,
176178
"buzz-mesh-member-status:test",

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1271,6 +1271,42 @@ mod postgres_tests {
12711271
people_p(),
12721272
true,
12731273
),
1274+
(
1275+
"NIP-RS unread record",
1276+
Path::Parameterized,
1277+
buzz_core::kind::KIND_READ_STATE as u16,
1278+
Some(format!("read-state-unread-v2:{}", "a".repeat(32))),
1279+
vec![["t", "read-state-unread-v2"]],
1280+
people_p(),
1281+
true,
1282+
),
1283+
(
1284+
"NIP-RS unread prefix with read-state tag",
1285+
Path::Parameterized,
1286+
buzz_core::kind::KIND_READ_STATE as u16,
1287+
Some(format!("read-state-unread-v2:{}", "b".repeat(32))),
1288+
vec![["t", "read-state"]],
1289+
people_p(),
1290+
false,
1291+
),
1292+
(
1293+
"NIP-RS thread follows",
1294+
Path::Parameterized,
1295+
buzz_core::kind::KIND_READ_STATE as u16,
1296+
Some(format!("thread-follows:{}", "a".repeat(32))),
1297+
vec![["t", "thread-follows"]],
1298+
people_p(),
1299+
true,
1300+
),
1301+
(
1302+
"NIP-RS thread follows with read-state tag",
1303+
Path::Parameterized,
1304+
buzz_core::kind::KIND_READ_STATE as u16,
1305+
Some(format!("thread-follows:{}", "b".repeat(32))),
1306+
vec![["t", "read-state"]],
1307+
people_p(),
1308+
false,
1309+
),
12741310
(
12751311
"mesh status",
12761312
Path::Parameterized,
@@ -1467,6 +1503,73 @@ mod postgres_tests {
14671503
);
14681504
}
14691505

1506+
#[tokio::test]
1507+
#[ignore = "requires Postgres"]
1508+
async fn thread_follows_replacement_purges_and_refuses_stale_replay() {
1509+
use nostr::{EventBuilder, Keys, Kind, Tag, Timestamp};
1510+
1511+
let db = setup_db().await;
1512+
let community = CommunityId::from_uuid(make_community(&db.pool).await);
1513+
let keys = Keys::generate();
1514+
let base = Timestamp::now().as_secs();
1515+
let rows = |d_tag: String| {
1516+
let pool = db.pool.clone();
1517+
let pubkey = keys.public_key().to_bytes();
1518+
async move {
1519+
let count: i64 = sqlx::query_scalar(
1520+
"SELECT count(*) FROM events WHERE community_id=$1 AND kind=30078 AND pubkey=$2 AND d_tag=$3",
1521+
)
1522+
.bind(community.as_uuid())
1523+
.bind(pubkey)
1524+
.bind(&d_tag)
1525+
.fetch_one(&pool)
1526+
.await
1527+
.expect("count rows");
1528+
count
1529+
}
1530+
};
1531+
// Only the matching `t` tag makes a thread-follows record retention
1532+
// free; a mismatched one stays an ordinary replaceable event.
1533+
for (slot, t, conforming) in [("a", "thread-follows", true), ("b", "read-state", false)] {
1534+
let d_tag = format!("thread-follows:{}", slot.repeat(32));
1535+
let version = |offset: u64, content: &str| {
1536+
EventBuilder::new(
1537+
Kind::Custom(buzz_core::kind::KIND_READ_STATE as u16),
1538+
content,
1539+
)
1540+
.tags(vec![
1541+
Tag::parse(["d", d_tag.as_str()]).expect("d tag"),
1542+
Tag::parse(["t", t]).expect("t tag"),
1543+
])
1544+
.custom_created_at(Timestamp::from(base + offset))
1545+
.sign_with_keys(&keys)
1546+
.expect("sign")
1547+
};
1548+
let (old, new) = (version(0, "old"), version(1, "new"));
1549+
for ev in [&old, &new] {
1550+
assert!(
1551+
db.replace_parameterized_event(community, ev, &d_tag, None)
1552+
.await
1553+
.expect("publish")
1554+
.1
1555+
);
1556+
}
1557+
assert_eq!(
1558+
rows(d_tag.clone()).await,
1559+
if conforming { 1 } else { 2 },
1560+
"{t}: only a conforming replaced record is purged"
1561+
);
1562+
assert!(
1563+
!db.replace_parameterized_event(community, &old, &d_tag, None)
1564+
.await
1565+
.expect("stale replay")
1566+
.1,
1567+
"{t}: a stale resend must be refused"
1568+
);
1569+
assert_eq!(rows(d_tag.clone()).await, if conforming { 1 } else { 2 });
1570+
}
1571+
}
1572+
14701573
#[tokio::test]
14711574
#[ignore = "requires Postgres"]
14721575
async fn replaceable_writes_fail_closed_when_community_is_fenced() {
@@ -2247,6 +2350,7 @@ mod postgres_tests {
22472350
let nip_rs = buzz_core::kind::KIND_READ_STATE as u16;
22482351
let mesh = buzz_core::kind::KIND_BOOKMARK_SET as u16;
22492352
let read_state_d = format!("read-state:{}", "b".repeat(32));
2353+
let unread_d = format!("read-state-unread-v2:{}", "b".repeat(32));
22502354
let mesh_d = "buzz-mesh-member-status:purge-test".to_string();
22512355
let tag = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::<Vec<_>>();
22522356
let t_read_state = tag(&["t", "read-state"]);
@@ -2261,6 +2365,30 @@ mod postgres_tests {
22612365
vec![tag(&["d", &read_state_d]), t_read_state.clone()],
22622366
true,
22632367
),
2368+
(
2369+
"nip-rs unread record",
2370+
nip_rs,
2371+
unread_d.clone(),
2372+
vec![tag(&["d", &unread_d]), tag(&["t", "read-state-unread-v2"])],
2373+
true,
2374+
),
2375+
(
2376+
"nip-rs unread record with read-state tag",
2377+
nip_rs,
2378+
unread_d.clone(),
2379+
vec![tag(&["d", &unread_d]), t_read_state.clone()],
2380+
false,
2381+
),
2382+
(
2383+
"nip-rs read-state slot with unread tag",
2384+
nip_rs,
2385+
read_state_d.clone(),
2386+
vec![
2387+
tag(&["d", &read_state_d]),
2388+
tag(&["t", "read-state-unread-v2"]),
2389+
],
2390+
false,
2391+
),
22642392
(
22652393
"nip-rs without t tag",
22662394
nip_rs,

0 commit comments

Comments
 (0)