From 9b0e325fdd1b9bc96a83be866924ad403c7002a0 Mon Sep 17 00:00:00 2001 From: Riley Crane Date: Thu, 3 Sep 2026 17:19:05 -0700 Subject: [PATCH] =?UTF-8?q?accumulator:=20channel=20exclusion=20=E2=80=94?= =?UTF-8?q?=20persistent=20flag,=20sync=20skip,=20broad-scope=20query=20om?= =?UTF-8?q?ission?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Excluded channels keep their mirrored events (existing folds and artifact provenance stay truthful) but receive no live subscription, backfill, or gap-fill. Broad (authors-only) selections omit them inside the one shared signal_query, so preview, the events browser, and fold plan/coverage/run cannot disagree; explicitly naming an excluded channel or a thread anchor inside it still queries the stale mirror. Re-including resets the backfill cursor to now so the paged walk repairs the gap by construction. PUT /channels/{id}/excluded toggles the flag (404 unknown) and nudges the sync loop into an immediate resync; GET /channels now carries excluded on every row. Discovery upserts never touch the flag. Legacy mirrors gain the column via idempotent migration. Co-Authored-By: Claude Fable 5 Signed-off-by: Riley Crane --- crates/buzz-accumulator/README.md | 3 +- crates/buzz-accumulator/src/daemon/http.rs | 107 ++++++++++ crates/buzz-accumulator/src/daemon/mod.rs | 3 + crates/buzz-accumulator/src/daemon/store.rs | 209 +++++++++++++++++++- crates/buzz-accumulator/src/daemon/sync.rs | 56 +++++- crates/buzz-accumulator/ui/src/api.ts | 1 + 6 files changed, 374 insertions(+), 5 deletions(-) diff --git a/crates/buzz-accumulator/README.md b/crates/buzz-accumulator/README.md index ba9a36986d..419eb83956 100644 --- a/crates/buzz-accumulator/README.md +++ b/crates/buzz-accumulator/README.md @@ -105,7 +105,8 @@ so any non-loopback bind must add authentication first. | Route | What | |---|---| | `GET /status` | Connection, backfill, mirror counts. | -| `GET /channels` | Discovered channels. | +| `GET /channels` | Discovered channels, each with its `excluded` flag. | +| `PUT /channels/{id}/excluded` | `{excluded: bool}` — toggle exclusion. Excluded: no live subscription/backfill, omitted from broad (authors-only) selections; mirrored events kept, still queryable when the channel or a thread in it is named explicitly. Re-include restarts the backfill walk to repair the gap. | | `GET /events/{id}` | One mirrored event (the citation-chip endpoint), with `parent` + `thread_root` reply lineage. | | `POST /select/preview` | `{selection, since?, until_exclusive?}` → count, size, daily rhythm. $0. | | `POST /select/events` | Same body + `limit`, `after` keyset cursor → the actual events, paged. | diff --git a/crates/buzz-accumulator/src/daemon/http.rs b/crates/buzz-accumulator/src/daemon/http.rs index 0c439c3398..c82c5bd970 100644 --- a/crates/buzz-accumulator/src/daemon/http.rs +++ b/crates/buzz-accumulator/src/daemon/http.rs @@ -35,6 +35,8 @@ pub struct AppState { pub runs: RunGuard, /// Publishes artifacts back into channels as messages. pub publisher: Arc, + /// Nudges the sync loop into an immediate clean resync (exclusion toggles). + pub resync: Arc, } /// Builds the router. Separated from serving for tests. @@ -42,6 +44,10 @@ pub fn router(state: AppState) -> Router { Router::new() .route("/status", get(get_status)) .route("/channels", get(get_channels)) + .route( + "/channels/{id}/excluded", + axum::routing::put(set_channel_excluded), + ) .route("/events/{id}", get(get_event)) .route("/select/preview", post(select_preview)) .route("/select/events", post(select_events)) @@ -123,6 +129,40 @@ async fn get_channels(State(s): State) -> Result, ApiError Ok(Json(json!({ "channels": channels }))) } +#[derive(Debug, serde::Deserialize)] +struct ExcludedBody { + excluded: bool, +} + +/// Toggles a channel's exclusion. Excluded channels keep their mirrored +/// events (folds stay truthful) but get no live subscription or backfill; +/// re-including restarts the backfill walk so the gap is repaired. Either +/// direction nudges the sync loop into an immediate resync. +async fn set_channel_excluded( + State(s): State, + Path(id): Path, + Json(body): Json, +) -> Result, ApiError> { + let id = id.trim().to_lowercase(); + let now = chrono::Utc::now().timestamp(); + let known = s + .store + .set_channel_excluded(&id, body.excluded, now) + .await?; + if !known { + return Err(ApiError( + StatusCode::NOT_FOUND, + format!("channel not found: {id}"), + )); + } + s.resync.notify_one(); + Ok(Json(json!({ + "channel": id, + "excluded": body.excluded, + "resync": true, + }))) +} + /// Optional window clamp shared by preview/preflight/run bodies. The /// selection's own window is authoritative; these bounds can only narrow it /// (this is how a run stays pinned to its priced preflight window). @@ -578,6 +618,7 @@ mod tests { runner: Arc::new(NoRunner), runs: RunGuard::default(), publisher, + resync: Arc::new(tokio::sync::Notify::new()), } } @@ -647,6 +688,72 @@ mod tests { ); } + #[tokio::test] + async fn channel_exclusion_toggle_over_http() { + let state = test_state().await; + let store = state.store.clone(); + let resync = state.resync.clone(); + store + .upsert_channel(CHANNEL, Some("Test"), "stream", 50) + .await + .expect("ch"); + let app = router(state); + + // Unknown channel → 404 and no resync nudge. + let put = Request::put("/channels/11111111-1111-1111-1111-111111111111/excluded") + .header("content-type", "application/json") + .body(Body::from(json!({ "excluded": true }).to_string())) + .expect("req"); + assert_eq!( + app.clone().oneshot(put).await.expect("resp").status(), + StatusCode::NOT_FOUND + ); + assert!( + tokio::time::timeout(std::time::Duration::ZERO, resync.notified()) + .await + .is_err(), + "404 must not nudge the sync loop" + ); + + // Known channel toggles (uppercase id normalizes) and nudges resync. + let put = Request::put(format!("/channels/{}/excluded", CHANNEL.to_uppercase())) + .header("content-type", "application/json") + .body(Body::from(json!({ "excluded": true }).to_string())) + .expect("req"); + let resp = app.clone().oneshot(put).await.expect("resp"); + assert_eq!(resp.status(), StatusCode::OK); + let v = body_json(resp).await; + assert_eq!(v["excluded"], true); + tokio::time::timeout(std::time::Duration::ZERO, resync.notified()) + .await + .expect("toggle nudges the sync loop"); + + // /channels carries the flag for every row. + let resp = app + .clone() + .oneshot(Request::get("/channels").body(Body::empty()).expect("req")) + .await + .expect("resp"); + let v = body_json(resp).await; + assert_eq!(v["channels"][0]["excluded"], true); + + // And toggles back off. + let put = Request::put(format!("/channels/{CHANNEL}/excluded")) + .header("content-type", "application/json") + .body(Body::from(json!({ "excluded": false }).to_string())) + .expect("req"); + assert_eq!( + app.clone().oneshot(put).await.expect("resp").status(), + StatusCode::OK + ); + let resp = app + .oneshot(Request::get("/channels").body(Body::empty()).expect("req")) + .await + .expect("resp"); + let v = body_json(resp).await; + assert_eq!(v["channels"][0]["excluded"], false); + } + #[tokio::test] async fn invalid_fold_spec_is_422() { let app = router(test_state().await); diff --git a/crates/buzz-accumulator/src/daemon/mod.rs b/crates/buzz-accumulator/src/daemon/mod.rs index a2cea06640..672528b317 100644 --- a/crates/buzz-accumulator/src/daemon/mod.rs +++ b/crates/buzz-accumulator/src/daemon/mod.rs @@ -158,10 +158,12 @@ pub async fn run(cfg: Config) -> anyhow::Result<()> { keys: keys.clone(), auth_tag: auth_tag.clone(), }); + let resync = Arc::new(tokio::sync::Notify::new()); let sync_cfg = sync::SyncConfig { relay_url: cfg.relay.clone(), keys, auth_tag, + resync: resync.clone(), }; let sync_task = tokio::spawn(sync::run_sync(sync_cfg, store.clone(), registry.clone())); @@ -171,6 +173,7 @@ pub async fn run(cfg: Config) -> anyhow::Result<()> { runner: Arc::new(crate::SubprocessRunner::new()), runs: folds::RunGuard::default(), publisher, + resync, }; let addr: std::net::SocketAddr = cfg .http_addr diff --git a/crates/buzz-accumulator/src/daemon/store.rs b/crates/buzz-accumulator/src/daemon/store.rs index 75ea967e9c..f0c9b5e003 100644 --- a/crates/buzz-accumulator/src/daemon/store.rs +++ b/crates/buzz-accumulator/src/daemon/store.rs @@ -51,6 +51,10 @@ pub struct ChannelRow { pub backfill_done: bool, /// False once the relay revoked access (kept for local history). pub active: bool, + /// True when the person excluded this channel: mirrored events are kept + /// and queryable, but the sync loop opens no live subscription and runs + /// no backfill until it is re-included. + pub excluded: bool, /// Unix seconds when the daemon first discovered the channel. pub discovered_at: i64, } @@ -105,6 +109,7 @@ CREATE TABLE IF NOT EXISTS channels ( backfill_cursor INTEGER, backfill_done INTEGER NOT NULL DEFAULT 0, active INTEGER NOT NULL DEFAULT 1, + excluded INTEGER NOT NULL DEFAULT 0, discovered_at INTEGER NOT NULL ); @@ -153,6 +158,7 @@ impl Store { sqlx::raw_sql(SCHEMA).execute(&pool).await?; let store = Self { pool }; store.migrate_parent_column().await?; + store.migrate_excluded_column().await?; Ok(store) } @@ -220,6 +226,25 @@ impl Store { Ok(()) } + /// Adds the `excluded` column to mirrors created before channel exclusion + /// existed. No backfill needed: the default (not excluded) is correct for + /// every pre-existing row. + async fn migrate_excluded_column(&self) -> Result<(), sqlx::Error> { + let has = sqlx::query( + "SELECT COUNT(*) AS n FROM pragma_table_info('channels') WHERE name = 'excluded'", + ) + .fetch_one(&self.pool) + .await? + .get::("n") + > 0; + if !has { + sqlx::raw_sql("ALTER TABLE channels ADD COLUMN excluded INTEGER NOT NULL DEFAULT 0") + .execute(&self.pool) + .await?; + } + Ok(()) + } + // ---- events ---- /// Idempotently persists a batch of events. Returns how many were new. @@ -404,7 +429,7 @@ impl Store { /// All channel rows. pub async fn channels(&self) -> Result, sqlx::Error> { let rows = sqlx::query( - "SELECT id, name, channel_type, backfill_cursor, backfill_done, active, discovered_at + "SELECT id, name, channel_type, backfill_cursor, backfill_done, active, excluded, discovered_at FROM channels ORDER BY id", ) .fetch_all(&self.pool) @@ -418,6 +443,7 @@ impl Store { backfill_cursor: r.get("backfill_cursor"), backfill_done: r.get::("backfill_done") != 0, active: r.get::("active") != 0, + excluded: r.get::("excluded") != 0, discovered_at: r.get("discovered_at"), }) .collect()) @@ -448,6 +474,35 @@ impl Store { Ok(()) } + /// Sets a channel's exclusion flag. Returns false when the channel is + /// unknown. Re-including resets backfill (cursor at `now`, not done) so + /// the paged walk repairs the excluded-period gap by construction — + /// idempotent inserts skip the history it already holds. Mirrored events + /// are never touched either way. + pub async fn set_channel_excluded( + &self, + id: &str, + excluded: bool, + now: i64, + ) -> Result { + let done = if excluded { + sqlx::query("UPDATE channels SET excluded = 1 WHERE id = ?") + .bind(id) + .execute(&self.pool) + .await? + } else { + sqlx::query( + "UPDATE channels SET excluded = 0, backfill_cursor = ?, backfill_done = 0 + WHERE id = ?", + ) + .bind(now) + .bind(id) + .execute(&self.pool) + .await? + }; + Ok(done.rows_affected() > 0) + } + // ---- profiles ---- /// Records a kind-0 profile name; newest `created_at` wins. @@ -668,6 +723,12 @@ impl Store { /// The subtree is resolved by a recursive CTE over the mirror's `parent` /// links; `UNION` (not `UNION ALL`) makes it terminate even on a pathological /// parent cycle. +/// +/// Exclusion rule: a broad selection (no channels, no threads — i.e. +/// authors-only) omits events from excluded channels. Explicitly naming a +/// channel or thread anchor overrides: its (stale) mirror stays queryable, so +/// a fold that names an excluded channel keeps returning exactly the events +/// it was defined over. fn signal_query( selection: &Selection, since: i64, @@ -708,7 +769,16 @@ fn signal_query( (true, false) => { qb.push(" AND id IN (SELECT id FROM thread_scope)"); } - (true, true) => {} + (true, true) => { + // Broad scope: no explicit channel or thread grant, so excluded + // channels are omitted here — the one query every consumer + // (preview, events browser, fold plan/coverage/run) shares. + // NOT EXISTS keeps channel-less events, unlike NOT IN over NULL. + qb.push( + " AND NOT EXISTS (SELECT 1 FROM channels x \ + WHERE x.id = events.channel AND x.excluded != 0)", + ); + } } if !selection.authors.is_empty() { qb.push(" AND pubkey IN ("); @@ -1257,4 +1327,139 @@ mod tests { assert!(store.delete_fold("weekly").await.expect("delete")); assert!(store.get_fold("weekly").await.expect("get").is_none()); } + + #[tokio::test] + async fn broad_scope_omits_excluded_channels_but_explicit_naming_overrides() { + let store = Store::open(":memory:").await.expect("open"); + store + .upsert_channel("cha", None, "stream", 50) + .await + .expect("cha"); + store + .upsert_channel("chb", None, "stream", 50) + .await + .expect("chb"); + store + .upsert_events(&[ + ev("1", Some("cha"), 9, 100), + ev("2", Some("chb"), 9, 101), + reply("3", "2", Some("chb"), 102), + ev("4", None, 9, 103), // channel-less event + ev("5", Some("chz"), 9, 104), // channel with no row at all + ]) + .await + .expect("insert"); + assert!(store + .set_channel_excluded("chb", true, 200) + .await + .expect("exclude")); + let ids = |signals: Vec| -> Vec { + signals.into_iter().map(|s| s.id).collect() + }; + let broad = Selection { + authors: vec!["a".repeat(64)], + ..Selection::default() + }; + + // Broad (authors-only) scope omits the excluded channel on BOTH query + // paths — fold plan/coverage/run go through query_signals, the events + // browser pages. Channel-less and unlisted-channel events survive. + let expect_broad = vec![full_id("1"), full_id("4"), full_id("5")]; + let got = store.query_signals(&broad, 0, 300).await.expect("query"); + assert_eq!(ids(got), expect_broad); + let got = store + .page_signals(&broad, 0, 300, None, 10) + .await + .expect("page"); + assert_eq!(ids(got), expect_broad); + + // Explicitly naming the excluded channel still queries its stale + // mirror, so a fold defined over it keeps its exact signal set. + let got = store + .query_signals(&selection(&["chb"]), 0, 300) + .await + .expect("query"); + assert_eq!(ids(got), vec![full_id("2"), full_id("3")]); + + // An explicit thread anchor inside the excluded channel overrides too. + let anchored = Selection { + threads: vec![full_id("2")], + ..Selection::default() + }; + let got = store.query_signals(&anchored, 0, 300).await.expect("query"); + assert_eq!(ids(got), vec![full_id("2"), full_id("3")]); + + // Re-including restores broad visibility. + assert!(store + .set_channel_excluded("chb", false, 250) + .await + .expect("include")); + let got = store.query_signals(&broad, 0, 300).await.expect("query"); + assert_eq!(got.len(), 5); + } + + #[tokio::test] + async fn exclusion_state_survives_rediscovery_and_reinclude_restarts_backfill() { + let store = Store::open(":memory:").await.expect("open"); + assert!( + !store + .set_channel_excluded("nope", true, 100) + .await + .expect("unknown"), + "unknown channel reports false" + ); + store + .upsert_channel("cha", Some("A"), "stream", 50) + .await + .expect("ch"); + store + .upsert_events(&[ev("1", Some("cha"), 9, 100)]) + .await + .expect("insert"); + store.set_backfill("cha", None, true).await.expect("done"); + + assert!(store + .set_channel_excluded("cha", true, 200) + .await + .expect("exclude")); + // Discovery upserts must not clear the flag. + store + .upsert_channel("cha", Some("A"), "stream", 60) + .await + .expect("rediscover"); + let ch = &store.channels().await.expect("channels")[0]; + assert!(ch.excluded, "rediscovery preserved exclusion"); + assert!(ch.backfill_done, "exclusion alone does not touch backfill"); + let (total, _) = store.event_counts().await.expect("counts"); + assert_eq!(total, 1, "mirrored events are never deleted"); + + // Re-include restarts the backfill walk from `now`. + assert!(store + .set_channel_excluded("cha", false, 300) + .await + .expect("include")); + let ch = &store.channels().await.expect("channels")[0]; + assert!(!ch.excluded); + assert_eq!(ch.backfill_cursor, Some(300)); + assert!(!ch.backfill_done); + } + + #[tokio::test] + async fn excluded_column_migration_is_idempotent_and_defaults_off() { + let store = Store::open(":memory:").await.expect("open"); + store + .upsert_channel("cha", None, "stream", 50) + .await + .expect("ch"); + // Simulate a mirror created before exclusion existed, then migrate. + sqlx::raw_sql("ALTER TABLE channels DROP COLUMN excluded") + .execute(&store.pool) + .await + .expect("drop"); + store.migrate_excluded_column().await.expect("migrate"); + store.migrate_excluded_column().await.expect("idempotent"); + let chans = store.channels().await.expect("channels"); + assert_eq!(chans.len(), 1); + assert!(!chans[0].excluded, "pre-existing rows default to included"); + } } diff --git a/crates/buzz-accumulator/src/daemon/sync.rs b/crates/buzz-accumulator/src/daemon/sync.rs index 6ffa4593de..52ff7dd6e1 100644 --- a/crates/buzz-accumulator/src/daemon/sync.rs +++ b/crates/buzz-accumulator/src/daemon/sync.rs @@ -18,8 +18,11 @@ //! frames for subscriptions it does not own. Observed live 2026-08-31. use std::collections::BTreeSet; +use std::sync::Arc; use std::time::Duration; +use tokio::sync::Notify; + use buzz_ws_client::{build_auth_event, NostrWsConnection, RelayMessage}; use nostr::{Keys, Tag}; use serde_json::{json, Value}; @@ -58,6 +61,9 @@ pub struct SyncConfig { pub keys: Keys, /// Optional NIP-OA ownership tag (agent identities only). pub auth_tag: Option, + /// Nudged by the HTTP layer (e.g. an exclusion toggle) to request an + /// immediate clean resync instead of waiting for relay traffic. + pub resync: Arc, } /// Runs the sync loop forever, reconnecting with capped exponential backoff. @@ -103,6 +109,11 @@ async fn sync_once( registry.connected(now); info!(relay = %cfg.relay_url, "connected and authenticated"); + // Absorb any resync nudge issued before this point: its store write + // happened before the notify, so the reads below already reflect it. A + // nudge arriving after this line stores a permit the live loop picks up. + let _ = tokio::time::timeout(Duration::ZERO, cfg.resync.notified()).await; + discover_channels(&mut conn, cfg, store, registry).await?; // Discovery just read the authoritative rosters, so membership is known // current as of `now` (captured before the roster query). Advancing the @@ -217,6 +228,13 @@ fn channel_type_from_meta(ev: &nostr::Event) -> &'static str { } } +/// Whether the sync loop backfills and tails a channel: it must be active +/// (access not revoked) and not excluded by the person. Excluded channels +/// stay in the mirror, listable and queryable, but receive no traffic. +pub(crate) fn sync_eligible(c: &super::store::ChannelRow) -> bool { + c.active && !c.excluded +} + /// Pages every not-yet-complete channel from its persisted cursor down to the /// beginning of history. Progress survives restarts: the cursor is persisted /// after every page. @@ -227,6 +245,13 @@ async fn backfill( ) -> anyhow::Result<()> { let channels = store.channels().await?; for ch in channels.iter().filter(|c| c.active) { + if ch.excluded { + registry.channel(&ch.id, |c| { + c.backfill = "excluded".into(); + c.live = false; + }); + continue; + } if ch.backfill_done { // Already complete in a prior run; reflect that in status. registry.channel(&ch.id, |c| c.backfill = "done".into()); @@ -386,7 +411,7 @@ async fn live_tail( let me = cfg.keys.public_key().to_hex(); let now = chrono::Utc::now().timestamp(); let channels = store.channels().await?; - for ch in channels.iter().filter(|c| c.active) { + for ch in channels.iter().filter(|c| sync_eligible(c)) { tokio::time::sleep(REQ_PACING).await; let newest = store.newest_ts(&ch.id).await?; let since = newest @@ -439,7 +464,16 @@ async fn live_tail( info!("live tail active"); loop { - let msg = match conn.next_event(LIVE_TICK).await { + // A dropped ws frame at this cancellation point is repaired by the + // resync itself (fresh connection, discovery, gap-fill). + let next = tokio::select! { + _ = cfg.resync.notified() => { + info!("resync requested (exclusion change)"); + return Ok(()); + } + next = conn.next_event(LIVE_TICK) => next, + }; + let msg = match next { Ok(msg) => msg, Err(buzz_ws_client::WsClientError::Timeout) => continue, // quiet period Err(e) => return Err(e.into()), @@ -643,6 +677,24 @@ mod tests { assert_eq!(advance_cursor(1000, Some(900), 10), 900); } + #[test] + fn excluded_or_revoked_channels_are_not_sync_eligible() { + let row = |active: bool, excluded: bool| super::super::store::ChannelRow { + id: "cha".into(), + name: None, + channel_type: "stream".into(), + backfill_cursor: None, + backfill_done: false, + active, + excluded, + discovered_at: 0, + }; + assert!(sync_eligible(&row(true, false))); + assert!(!sync_eligible(&row(true, true))); + assert!(!sync_eligible(&row(false, false))); + assert!(!sync_eligible(&row(false, true))); + } + #[test] fn cursor_steps_past_wedged_same_second_stratum() { // Full page, nothing new, oldest == cursor: without the step the loop diff --git a/crates/buzz-accumulator/ui/src/api.ts b/crates/buzz-accumulator/ui/src/api.ts index 386455eb2a..dd950551f5 100644 --- a/crates/buzz-accumulator/ui/src/api.ts +++ b/crates/buzz-accumulator/ui/src/api.ts @@ -43,6 +43,7 @@ export type Channel = { backfill_cursor: number | null; backfill_done: boolean; active: boolean; + excluded: boolean; discovered_at: number; };