Files
buzz/crates/buzz-relay/src/api/artifact_postgres_tests.rs
Daniel Rouleau a57349b237 feat(relay): add incremental artifact reads (#8523)
## Summary

Buzz clients need to recover task changes after a disconnect. This adds
incremental reads of changed artifacts with database modification
timestamps and a 120-second overlap. Each result contains the current
revision or an explicit removal. A separate read of known IDs confirms
accepted edits and restores access state.

Pages use a timestamp and a stable ID to handle equal timestamps. Access
grants include older records. Access policy changes require discovery
and revalidation of saved IDs. The reader does not load a list of all
readable channels. Ordinary artifact writes update their own rows.

### Incremental reads and WebSocket Sync

This HTTP protocol maintains an eventually consistent local store. It
uses `artifacts.incremental` and `"artifact":"incremental"`. It does not
prove a complete set at one database snapshot. Absence never proves
deletion or loss of access.

[WebSocket Sync](https://github.com/block/buzz/pull/8522) serves a
separate use case: a complete set at `EOSE`, followed by live updates.
It owns `artifacts.sync`. Both protocols can coexist. The second PR to
merge must reuse the shared access helper in `artifact_query.rs` when it
resolves the overlapping edits.

The gate is `BUZZ_ARTIFACT_INCREMENTAL_ENABLED`. Errors use the
`incremental_` prefix. Unlisted open channels require membership or an
explicit `#h` scope. Listing changes reset incremental progress.
Incremental reads exclude TTL artifacts. Known-ID reads return `remove`
for them. The `#h` scope limits candidates before pagination. Initial
reads omit deleted heads. Later reads retain deletion removals.

### Why the new timestamps are needed

`created_at` comes from the event signer. `received_at` records event
arrival. Neither advances when access changes or an event is redacted.
Sync needs database timestamps for those changes:

| Column | Why sync needs it |
| --- | --- |
| `artifact_heads.modified_at` | Finds current records that change
through an edit, deletion, or redaction. |
| `artifact_revisions.modified_at` | Dates retained move records. This
lets sync remove a task from its former channel when the reader cannot
access its new channel. |
| `channel_members.sync_modified_at` | Finds grants, rejoins, and
removals. A grant must include older tasks whose own timestamps do not
change. |
| `communities.artifact_policy_modified_at` | Requests recovery after a
relevant channel visibility, TTL, or deletion change. Clients revalidate
saved IDs. Ordinary task writes do not update it. |

The database sets these timestamps with `clock_timestamp()`. The
120-second overlap covers the accepted delay between timestamp
assignment and commit visibility.

`BUZZ_ARTIFACT_INCREMENTAL_ENABLED` defaults to off. Apply migrations
`0076`–`0078` and upgrade all writers before enablement. The 120-second
delay bound is an operating assumption. [Deployment
steps](https://github.com/block/buzz/blob/drouleau/artifact-snapshots/docs/artifact-sync-deployment.md)
cover index prebuilds and rollback.

### Related issue

No duplicate found. Related work: [read
permissions](https://github.com/block/buzz/pull/8338), [statement
limits](https://github.com/block/buzz/pull/8461), and [atomic channel
settings](https://github.com/block/buzz/pull/8516).

### Testing

Signed HTTP E2E passes on `f3d6ac852e7ce4e2cc53bd891cef87832a868d72`
after CI passes. It includes main through `ef4130da4`. A standalone
local relay uses a fresh PostgreSQL 17 database, Redis, and signed
NIP-98 HTTP requests. All 78 migrations apply through relay startup. All
behavioral writes and reads use HTTP.

The tests cover create, edit, delta reads, known-ID recovery, private
moves, access grants, removals, rejoins, visibility resets, redaction,
and deletion. Unlisted tests cover hidden broad discovery, named scope,
known-ID reads, member access, and policy resets. They also cover
bootstrap across two pages, overlap replay, and 101 move removals across
pages. Decoded cursors contain no private revision IDs. With the
incremental gate off, `artifacts.incremental` is absent and a signed
incremental request returns `503 incremental_unavailable`. Unsigned
requests are rejected. Signed tests also cover TTL exclusion, current-ID
removals for TTL artifacts, moves into TTL channels, deleted initial
heads, and scoped pages with exactly 100 and 3 upserts.

A separate local scale test on `babcdb766` reads 10,050 tasks across
60,002 memberships. It uses seeded fixtures and a second relay state
with the same signing key. The initial read takes 8.31 seconds over 101
pages with 4,923-byte events. A read with no changes takes 5.70
milliseconds. The candidate keeps the same database query. These are
local measurements, not production limits. Cold pages repeat candidate
scans and access checks. Writer load needs validation before fleet
enablement.

```sh
cargo test -p buzz-relay sync_downloads_ten_thousand_tasks_with_sixty_thousand_memberships -- --ignored --nocapture
```

The behavioral run uses `cargo build -p buzz-relay --bin buzz-relay`,
then `cargo run -p buzz-relay --example
artifact_incremental_final_oct30_f3`. The temporary harness drives the
built relay and is removed after the run. The worktree is clean at the
tested SHA. It does not exercise a native client. Git and S3 behavior
are outside this validation.

The
[protocol](https://github.com/block/buzz/blob/drouleau/artifact-snapshots/docs/nips/NIP-AR.md#incremental-reads)
defines progress, removals, limits, and recovery. Relay verification
covers the signed HTTP path. Native client verification belongs to [the
client PR](https://github.com/block/buzz-app/pull/1507).

Generated with Codex

---------

Signed-off-by: Daniel Rouleau <drouleau@squareup.com>
2026-10-30 08:30:46 -07:00

492 lines
19 KiB
Rust

// Exercises the production HTTP router and ingest gates for artifacts.
use super::postgres_tests::bridge_handler_test_state;
use super::*;
use nostr::{Event, EventBuilder, Keys, Kind, Tag};
use serde_json::{json, Value};
use uuid::Uuid;
struct Fixture {
state: Arc<crate::state::AppState>,
pool: sqlx::PgPool,
host: String,
community: buzz_core::CommunityId,
home: Uuid,
private: Uuid,
owner: Keys,
peer: Keys,
}
impl Fixture {
async fn new() -> Self {
let state = bridge_handler_test_state()
.await
.expect("Postgres and Redis");
let pool = sqlx::PgPool::connect(&crate::test_support::database_url())
.await
.unwrap();
let host = format!("artifact-review-{}.local", Uuid::new_v4());
state.db.ensure_configured_community(&host).await.unwrap();
state
.db
.maintain_partitions(
1,
buzz_db::partition::PartitionMaintenancePolicy {
create_enabled: true,
advance_enabled: false,
},
)
.await
.unwrap();
let tenant = crate::tenant::bind_community(&state.db, &host)
.await
.unwrap();
let community = tenant.community();
let home = Uuid::new_v4();
let private = Uuid::new_v4();
let owner = Keys::generate();
for (id, visibility) in [(home, "open"), (private, "private")] {
sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by) VALUES($1,$2,$2::text,$3::channel_visibility,'stream',$4)")
.bind(community.as_uuid()).bind(id).bind(visibility).bind(owner.public_key().as_bytes().as_slice()).execute(&pool).await.unwrap();
sqlx::query("INSERT INTO channel_members(community_id,channel_id,pubkey,role) VALUES($1,$2,$3,'owner')")
.bind(community.as_uuid()).bind(id).bind(owner.public_key().as_bytes().as_slice()).execute(&pool).await.unwrap();
}
Self {
state,
pool,
host,
community,
home,
private,
owner,
peer: Keys::generate(),
}
}
fn revision(&self, id: Uuid, op: &str, prev: Option<&Event>) -> Event {
self.revision_as(&self.owner, self.home, id, op, prev)
}
fn revision_as(
&self,
key: &Keys,
home: Uuid,
id: Uuid,
op: &str,
prev: Option<&Event>,
) -> Event {
let mut tags = vec![
vec!["ar".into(), "1".into()],
vec!["d".into(), id.to_string()],
vec!["h".into(), home.to_string()],
vec!["type".into(), "buzz.task".into()],
vec!["op".into(), op.into()],
];
if op != "delete" {
tags.push(vec!["title".into(), "Review task".into()]);
}
if let Some(prev) = prev {
tags.push(vec!["prev".into(), prev.id.to_hex()]);
}
EventBuilder::new(
Kind::Custom(45010),
if op == "delete" {
""
} else {
"review searchable"
},
)
.tags(tags.into_iter().map(|t| Tag::parse(t).unwrap()))
.sign_with_keys(key)
.unwrap()
}
async fn request(&self, path: &str, body: Value) -> (axum::http::StatusCode, Value) {
self.request_as(&self.owner, path, body).await
}
async fn request_as(
&self,
key: &Keys,
path: &str,
body: Value,
) -> (axum::http::StatusCode, Value) {
use tower::ServiceExt;
let response = crate::router::build_router(self.state.clone())
.oneshot(
axum::http::Request::builder()
.method("POST")
.uri(path)
.header("host", &self.host)
.header("content-type", "application/json")
.header("x-pubkey", key.public_key().to_hex())
.body(axum::body::Body::from(body.to_string()))
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let bytes = axum::body::to_bytes(response.into_body(), 8 * 1024 * 1024)
.await
.unwrap();
(status, serde_json::from_slice(&bytes).unwrap())
}
async fn publish(&self, event: &Event) {
let (status, body) = self.try_publish(event).await;
assert!(status.is_success(), "{status}: {body}");
assert_eq!(body["accepted"], true, "{body}");
}
async fn try_publish(&self, event: &Event) -> (axum::http::StatusCode, Value) {
let key = if event.pubkey == self.peer.public_key() {
&self.peer
} else {
&self.owner
};
self.request_as(key, "/events", json!(event)).await
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn project_filter_survives_artifact_query_hook() {
let f = Fixture::new().await;
let home = f.home.to_string();
// 30621 projects and 30617 repositories bind a channel via `buzz-channel`.
for kind in [30621u16, 30617] {
let event = |tag: &[&str], at: u64| {
EventBuilder::new(Kind::Custom(kind), "")
.tags([
Tag::parse(["d", &Uuid::new_v4().to_string()]).unwrap(),
Tag::parse(tag.iter().copied()).unwrap(),
])
.custom_created_at(nostr::Timestamp::from(at))
.sign_with_keys(&f.owner)
.unwrap()
};
let now = nostr::Timestamp::now().as_secs();
let bound = event(&["buzz-channel", &home], now - 10);
// Newer, unbound: `buzz-channel` and the wanted id sit in an unrelated tag.
let decoy = event(&["x", "buzz-channel", &home], now);
for e in [&bound, &decoy] {
f.state.db.insert_event(f.community, e, None).await.unwrap();
}
let filter = json!([{"kinds":[kind],"#buzz-channel":[f.home],"limit":1}]);
let (status, body) = f.request("/query", filter.clone()).await;
assert!(status.is_success(), "{kind} {status}: {body}");
assert_eq!(body.as_array().unwrap().len(), 1, "{kind}: {body}");
assert_eq!(body[0]["id"], bound.id.to_hex(), "{kind}: {body}");
let (status, body) = f.request("/count", filter).await;
assert!(status.is_success(), "{kind} {status}: {body}");
assert_eq!(body["count"], 1, "{kind}: {body}");
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn count_honors_buzz_channel_filter() {
let f = Fixture::new().await;
// Two projects bound to `home`, one bound to `private`, all stored in
// `home` so the explicit `#h` scope alone would count all three.
for channel in [f.home, f.home, f.private] {
let event = EventBuilder::new(Kind::Custom(30621), "")
.tags([
Tag::parse(["d", &Uuid::new_v4().to_string()]).unwrap(),
Tag::parse(["buzz-channel", &channel.to_string()]).unwrap(),
Tag::parse(["t", "proj"]).unwrap(),
])
.sign_with_keys(&f.owner)
.unwrap();
f.state
.db
.insert_event(f.community, &event, Some(f.home))
.await
.unwrap();
}
for filter in [
// Fast COUNT over the reader's accessible channels.
json!([{"kinds":[30621],"#buzz-channel":[f.home]}]),
// Fast COUNT on the explicit-channel path.
json!([{"kinds":[30621],"#h":[f.home],"#buzz-channel":[f.home]}]),
// `#t` is not fully pushable, forcing the per-event fallback on both paths.
json!([{"kinds":[30621],"#t":["proj"],"#buzz-channel":[f.home]}]),
json!([{"kinds":[30621],"#h":[f.home],"#t":["proj"],"#buzz-channel":[f.home]}]),
] {
let (status, body) = f.request("/query", filter.clone()).await;
assert!(status.is_success(), "{filter} {status}: {body}");
assert_eq!(body.as_array().unwrap().len(), 2, "{filter}: {body}");
let (status, body) = f.request("/count", filter.clone()).await;
assert!(status.is_success(), "{filter} {status}: {body}");
assert_eq!(body["count"], 2, "{filter}: {body}");
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn unsupported_predicates_fail_explicitly() {
let f = Fixture::new().await;
let create = f.revision(Uuid::new_v4(), "create", None);
f.publish(&create).await;
let (status, body) = f.request("/query", json!([{"ids":[create.id]}])).await;
assert!(status.is_success(), "{status}: {body}");
assert_eq!(body[0]["id"], create.id.to_hex());
// A readable artifact must not match a predicate it does not carry.
for path in ["/query", "/count"] {
for filter in [
json!({"ids":[create.id],"#project":["P"]}),
json!({"artifact":"current","#assignee":[]}),
] {
let (status, body) = f.request(path, json!([filter])).await;
assert_eq!(
status,
axum::http::StatusCode::BAD_REQUEST,
"{filter}: {body}"
);
}
}
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn lifecycle_routes_duplicate_replay_delete_and_redaction() {
let f = Fixture::new().await;
let d = Uuid::new_v4();
let create = f.revision(d, "create", None);
f.publish(&create).await;
let update = f.revision(d, "update", Some(&create));
f.publish(&update).await;
f.publish(&create).await;
// The production ingest duplicate path must precede timestamp freshness.
let old = EventBuilder::new(Kind::Custom(45010), "old")
.tags(create.tags.iter().cloned())
.custom_created_at(nostr::Timestamp::from(1))
.sign_with_keys(&f.owner)
.unwrap();
sqlx::query(
"INSERT INTO artifact_revisions(community_id,event_id,artifact_id) VALUES($1,$2,$3)",
)
.bind(f.community.as_uuid())
.bind(old.id.as_bytes().as_slice())
.bind(Uuid::new_v4())
.execute(&f.pool)
.await
.unwrap();
f.publish(&old).await;
let delete = f.revision(d, "delete", Some(&update));
f.publish(&delete).await;
// WebSocket replay's production filter-to-query and store seams.
let filter = serde_json::from_value(json!({"kinds":[45010],"#h":[f.home],"since":0})).unwrap();
let query = crate::handlers::req::build_event_query_from_filter(
&filter,
f.owner.public_key().as_bytes(),
&f.state,
f.community,
)
.await;
let replay = f.state.db.query_events(&query).await.unwrap();
assert_eq!(replay.len(), 1);
assert_eq!(replay[0].event.id, delete.id);
for path in ["/query", "/count"] {
let (status, body) = f
.request(path, json!([{"artifact":"current","#d":[d]}]))
.await;
assert!(status.is_success(), "{body}");
if path == "/query" {
assert_eq!(body, json!([]));
} else {
assert_eq!(body["count"], 0);
}
}
// Multi-character predicates are never silently dropped on the generic path.
let (status, _) = f
.request("/query", json!([{"kinds":[45010],"#project":["p"]}]))
.await;
assert_eq!(status, axum::http::StatusCode::BAD_REQUEST);
let (_, search) = f
.request(
"/query",
json!([{"kinds":[9],"search":"review searchable","#h":[f.home]}]),
)
.await;
assert_eq!(search, json!([]));
let restore = f.revision(d, "restore", Some(&delete));
f.publish(&restore).await;
let command = |kind| {
EventBuilder::new(Kind::Custom(kind), "")
.tags([
Tag::parse(["e", &restore.id.to_hex()]).unwrap(),
Tag::parse(["h", &f.home.to_string()]).unwrap(),
])
.sign_with_keys(&f.owner)
.unwrap()
};
let (status, body) = f.request("/events", json!(command(5))).await;
assert!(!status.is_success(), "{body}");
assert!(
body.to_string()
.contains("artifacts cannot be deleted with kind 5"),
"{body}"
);
// Redaction is the ordinary 9005 removal; the head stays editable.
f.publish(&command(9005)).await;
let current = json!([{"artifact":"current","#d":[d]}]);
let (_, body) = f.request("/query", current.clone()).await;
assert_eq!(body, json!([]));
let (_, body) = f
.request("/count", json!([{"artifact":"history","#d":[d]}]))
.await;
assert_eq!(body["count"], 3);
let edit = f.revision(d, "update", Some(&restore));
f.publish(&edit).await;
let (_, body) = f.request("/query", current).await;
assert_eq!(body[0]["id"], edit.id.to_hex());
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn writes_use_channel_gates_for_home_and_move_source() {
let f = Fixture::new().await;
let d = Uuid::new_v4();
let create = f.revision(d, "create", None);
f.publish(&create).await;
// Open-channel nonmembers may edit, as they may post kind 9.
let peer_edit = f.revision_as(&f.peer, f.home, d, "update", Some(&create));
f.publish(&peer_edit).await;
let other = f.revision_as(&f.peer, f.private, Uuid::new_v4(), "create", None);
let (status, body) = f.try_publish(&other).await;
assert!(!status.is_success() || body["accepted"] == false, "{body}");
let moved = f.revision_as(&f.owner, f.private, d, "move", Some(&peer_edit));
f.publish(&moved).await;
let (_, removals) = f
.request("/query", json!([{"kinds":[45011],"#h":[f.home]}]))
.await;
assert_eq!(removals.as_array().unwrap().len(), 1, "{removals}");
assert!(!removals.to_string().contains(&f.private.to_string()));
// The marker names only the source-readable revision it replaced.
assert!(removals[0]["tags"]
.as_array()
.unwrap()
.contains(&json!(["prev", peer_edit.id.to_hex()])));
// An unwritable source answers exactly like a move of a missing artifact.
let missing_move =
|key: &Keys| f.revision_as(key, f.home, Uuid::new_v4(), "move", Some(&moved));
let (status, body) = f.try_publish(&missing_move(&f.peer)).await;
let peer_missing = (status, without_event_id(body));
assert!(!peer_missing.0.is_success(), "{peer_missing:?}");
// The peer can write the destination but not the private source.
let back = f.revision_as(&f.peer, f.home, d, "move", Some(&moved));
let (status, body) = f.try_publish(&back).await;
assert_eq!((status, without_event_id(body)), peer_missing);
sqlx::query("UPDATE channels SET archived_at=now() WHERE community_id=$1 AND id=$2")
.bind(f.community.as_uuid())
.bind(f.private)
.execute(&f.pool)
.await
.unwrap();
let (status, body) = f.try_publish(&missing_move(&f.owner)).await;
let owner_missing = (status, without_event_id(body));
assert!(!owner_missing.0.is_success(), "{owner_missing:?}");
let archived_source = f.revision_as(&f.owner, f.home, d, "move", Some(&moved));
let (status, body) = f.try_publish(&archived_source).await;
assert_eq!((status, without_event_id(body)), owner_missing);
}
/// Drop the per-event id so rejections of different events compare exactly.
fn without_event_id(mut body: Value) -> Value {
if let Some(object) = body.as_object_mut() {
object.remove("event_id");
}
body
}
/// Re-sign an artifact revision with extra tags and an explicit timestamp.
fn resign(event: &Event, key: &Keys, extra: &[[&str; 2]], created_at: u64) -> Event {
EventBuilder::new(event.kind, event.content.clone())
.tags(
event
.tags
.iter()
.cloned()
.chain(extra.iter().map(|t| Tag::parse(*t).unwrap())),
)
.custom_created_at(nostr::Timestamp::from(created_at))
.sign_with_keys(key)
.unwrap()
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn generic_p_reads_find_mentioned_artifacts() {
let f = Fixture::new().await;
let tagged = f.peer.public_key().to_hex();
let create = f.revision(Uuid::new_v4(), "create", None);
let create = resign(
&create,
&f.owner,
&[["p", &tagged]],
create.created_at.as_secs(),
);
f.publish(&create).await;
let filter = json!([{"kinds":[45010],"#h":[f.home],"#p":[tagged]}]);
let (status, body) = f.request("/query", filter.clone()).await;
assert!(status.is_success(), "{status}: {body}");
assert_eq!(body.as_array().unwrap().len(), 1, "{body}");
assert_eq!(body[0]["id"], create.id.to_hex());
let (status, body) = f.request("/count", filter).await;
assert!(status.is_success(), "{status}: {body}");
assert_eq!(body["count"], 1, "{body}");
}
#[tokio::test]
#[ignore = "requires Postgres"]
async fn generic_d_lookup_matches_before_limit() {
let f = Fixture::new().await;
let (a, b) = (Uuid::new_v4(), Uuid::new_v4());
let now = nostr::Timestamp::now().as_secs();
// Kindless reads are p-gated to the reader, so every row tags the peer.
let reader = f.peer.public_key().to_hex();
let tag_reader = [["p", reader.as_str()]];
let older = resign(
&f.revision(a, "create", None),
&f.owner,
&tag_reader,
now - 60,
);
f.publish(&older).await;
let newer = resign(&f.revision(b, "create", None), &f.owner, &tag_reader, now);
f.publish(&newer).await;
for filter in [
json!([{"kinds":[45010],"#h":[f.home],"#d":[a],"limit":1}]),
json!([{"kinds":[45010,45011],"#h":[f.home],"#d":[a],"limit":1}]),
json!([{"#h":[f.home],"#p":[reader],"#d":[a],"limit":1}]),
] {
let (status, body) = f.request_as(&f.peer, "/query", filter.clone()).await;
assert!(status.is_success(), "{status}: {body}");
assert_eq!(body.as_array().unwrap().len(), 1, "{filter}: {body}");
assert_eq!(body[0]["id"], older.id.to_hex(), "{filter}");
let (status, body) = f.request_as(&f.peer, "/count", filter.clone()).await;
assert!(status.is_success(), "{status}: {body}");
assert_eq!(body["count"], 1, "{filter}: {body}");
}
// Non-artifact rows still reach the generic `#d` post-filter.
let message = EventBuilder::new(Kind::Custom(9), "d-tagged chat")
.tags([
Tag::parse(["h", &f.home.to_string()]).unwrap(),
Tag::parse(["d", &a.to_string()]).unwrap(),
Tag::parse(["p", &reader]).unwrap(),
])
.sign_with_keys(&f.owner)
.unwrap();
f.publish(&message).await;
let filter = json!([{"#h":[f.home],"#p":[reader],"#d":[a]}]);
let (status, body) = f.request_as(&f.peer, "/query", filter).await;
assert!(status.is_success(), "{status}: {body}");
let mut ids: Vec<_> = body
.as_array()
.unwrap()
.iter()
.map(|e| e["id"].as_str().unwrap().to_owned())
.collect();
ids.sort();
let mut expected = vec![older.id.to_hex(), message.id.to_hex()];
expected.sort();
assert_eq!(ids, expected, "{body}");
}
#[path = "artifact_postgres_tests/sync_postgres_tests.rs"]
mod sync_postgres_tests;