Skip to content

Commit e9af5fe

Browse files
baxenmbotclaudebradseilerHarrington
authored
Republish channel discovery events a failed emission left missing (#9805)
## Summary The relay publishes a channel's discovery events (kind:39000 metadata, kind:39001 admins, kind:39002 members) after the channel's write commits, and only best-effort. During a relay outage some channels got their rows but not all of these events. The database was healthy, but clients could not read the roster. A 1.x client confirms a DM against its signed kind:39002 roster, so opening one of these DMs failed with "participants could not be confirmed" every time. Retrying didn't help: reopening an existing DM published nothing. Users can't repair it either, because the relay refuses kind:9000 on DMs, which rules out the no-op re-add. This PR adds two repair paths and one shared check. **Shared check** (`buzz_db::group_discovery`). A channel is missing discovery when, for any of 39000/39001/39002, it has no live relay-signed event. Each kind is one probe on `idx_events_addressable`, bounded below by the channel's `created_at` (less an hour of clock slack), so Postgres prunes the monthly `events` partitions to the ones since the channel was created. That bound is what keeps the check cheap: without it, every probe visits every partition. **1. A DM reopen heals the DM.** When kind:41010 returns an existing DM and adds nobody, the relay runs the check and republishes all three events only if one is missing. A healthy reopen costs one indexed read and no writes. When agents are added, the additions already republish discovery. So a client retry now repairs the DM. **2. Startup sweep.** In the background after startup, the relay scans live channels in active communities created in the last `BUZZ_DISCOVERY_REPAIR_LOOKBACK_HOURS` (default 72; `0` turns it off). It skips channels created in the last minute, whose creation may still be publishing, and republishes each one missing a kind. Its probes also carry a constant floor (the window start, less the slack), so the partitions prune whichever join the planner picks. Each query returns up to 200 channels that need repair and uses a `(created_at, id)` cursor. PostgreSQL may examine more than 200 channels in the window. The sweep moves past a channel whose repair fails, so it ends after one pass. Replicas racing on one channel are fenced by the existing replacement locks. Measured cost: on a production database with ~90k channels (~25k created in the past week), `EXPLAIN ANALYZE` of one 3-day page took 310 ms. That's ~48k index probes, all from cache, and run-time pruning skipped every earlier partition. An ad-hoc `NOT EXISTS` scan without the `created_at` bound hit the 30 s statement timeout on the same data. The dev/CI reconciler (`BUZZ_RECONCILE_CHANNELS`) now uses the same check, so it also catches a missing 39001 or 39002, not just a missing 39000. Startup logs the effective lookback and the outcome, including disabled runs and runs that repair zero channels. A malformed setting such as `336h` logs a warning and falls back to 72 hours. ### Related issue N/A. [Related DM membership repair proposal](#7079). ### Rollout For known channels older than 72 hours, set `BUZZ_DISCOVERY_REPAIR_LOOKBACK_HOURS` to a whole number that covers the oldest affected channel at rollout. For example, `336` covers channels created within the preceding 14 days. Before widening the window, run the read-only sweep query to verify the affected channels and measure the query cost. After rollout, check the startup logs for the effective window and repair results, confirm the affected channels have signed discovery events, and restore the default lookback after the one-time sweep. ### Testing `handlers::discovery_repair_postgres_tests`: - `reopening_a_dm_republishes_its_missing_roster`: a DM keeps 39000 and loses 39002, and a reopen republishes the roster with both people. A healthy reopen first leaves every live event untouched. - `the_sweep_republishes_recent_channels_missing_any_discovery_kind`: the sweep runs with one channel per page. It repairs a channel left with only 39000 (its 39001 and 39002 soft-deleted) and one left with nothing, and leaves alone a healthy channel, one older than the lookback, and one inside the in-flight grace. A read-only run of the sweep's query against the production data above, over the past 3 days, returned exactly the 11 channels known to be broken by the outage, and no others. Mutation checks, each of which turns a test red: - drop the reopen repair - republish without the check - check only 39000 - count deleted events as live - stop after one page - start the scan before the lookback - drop the grace bound The discovery repair, DM growth, and group-state suites passed in a local PostgreSQL 16 instance on the rebased code. The published head is `e452374a3`. Four local relay starts with `0`, `-1`, `336h`, and `336` verified disabled runs, the malformed-value warning and fallback, and the zero-repair summary. The live startup runs exercised logging and configuration. The repair itself was verified in the PostgreSQL tests. 🤖 Generated with [Claude Code](https://claude.com/claude-code). Updated with Codex. --------- Signed-off-by: Bradley Axen <baxen@squareup.com> Signed-off-by: Brad Seiler <seiler@squareup.com> Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Brad Seiler <seiler@squareup.com> Co-authored-by: Harrington <91868d0cc0b8144564e350ce0a9e46447f654ad3fe93b23e39fe71314c911781@buzz.block.builderlab.xyz> Co-authored-by: Henke <b494f0778682c83a1faae59541cfd2c2d2060dc1d5b3c2dc819fdc529840b8a4@buzz.block.builderlab.xyz>
1 parent b9cccf8 commit e9af5fe

12 files changed

Lines changed: 712 additions & 50 deletions

File tree

‎.env.example‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,14 @@ BUZZ_S3_ADDRESSING_STYLE=path
278278
# How often the reaper checks for expired ephemeral channels (default: 60s).
279279
# BUZZ_REAPER_INTERVAL_SECS=5
280280

281+
# -----------------------------------------------------------------------------
282+
# Channel discovery repair
283+
# -----------------------------------------------------------------------------
284+
# On startup, republish relay-signed discovery events (kinds 39000-39002) for
285+
# channels created in this many past hours that are missing any of them, as a
286+
# failed post-commit emission leaves them (default: 72; 0 turns it off).
287+
# BUZZ_DISCOVERY_REPAIR_LOOKBACK_HOURS=72
288+
281289
# -----------------------------------------------------------------------------
282290
# Logging / Tracing
283291
# -----------------------------------------------------------------------------

‎crates/buzz-db/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ pub(crate) use runtime::{
9696
pub use store::{
9797
admin_moderation, allowlist, api_token, archived_identities, artifact, artifact_sync, channel,
9898
channel_members, community, community_auth, deletion, dm, entity_deletion, event, feed,
99-
git_repo, leader_lock, media, membership_snapshot, moderation, nip_fi_binding,
99+
git_repo, group_discovery, leader_lock, media, membership_snapshot, moderation, nip_fi_binding,
100100
operator_listener, partition, personal_read, pins, product_feedback, push, reaction,
101101
read_state, relay_admin_actions, relay_invite, relay_members, relay_operators, reminder,
102102
replaceable, search_backfill, search_outbox, storage_accounting, thread, thread_window, user,

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

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2483,17 +2483,6 @@ impl Db {
24832483
.await
24842484
}
24852485

2486-
/// Query authoritative event state for startup reconciliation.
2487-
#[datastore_span(name = "query_events_for_bootstrap", system = "postgresql")]
2488-
pub async fn query_events_for_bootstrap(&self, q: &EventQuery) -> Result<Vec<StoredEvent>> {
2489-
crate::event::query_events_with_operation(
2490-
&self.pool,
2491-
q,
2492-
crate::observability::WriterOperation::Bootstrap,
2493-
)
2494-
.await
2495-
}
2496-
24972486
/// Query authoritative event state for background reconciliation or repair.
24982487
#[datastore_span(name = "query_events_for_maintenance", system = "postgresql")]
24992488
pub async fn query_events_for_maintenance(&self, q: &EventQuery) -> Result<Vec<StoredEvent>> {
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
//! Finding channels whose relay-signed discovery events are missing.
2+
//!
3+
//! The relay publishes a channel's kind:39000 (metadata), kind:39001
4+
//! (admins) and kind:39002 (members) after the channel's own write commits,
5+
//! so a failure in between leaves a healthy channel that clients cannot
6+
//! confirm. These reads find such channels so the relay can publish them
7+
//! again.
8+
9+
use buzz_core::CommunityId;
10+
use buzz_datastore_tracing::datastore_span;
11+
use chrono::{DateTime, Utc};
12+
use sqlx::{PgPool, Row};
13+
use uuid::Uuid;
14+
15+
use crate::{observability, Db, Result};
16+
17+
/// The relay-signed kinds every live channel has one live event of.
18+
pub const GROUP_DISCOVERY_KINDS: [i32; 3] = [39000, 39001, 39002];
19+
20+
/// A live channel with at least one of [`GROUP_DISCOVERY_KINDS`] missing.
21+
#[derive(Debug, Clone, PartialEq, Eq)]
22+
pub struct ChannelMissingDiscovery {
23+
/// Community that owns the channel.
24+
pub community_id: CommunityId,
25+
/// Canonical host for the owning community.
26+
pub host: String,
27+
/// The channel.
28+
pub channel_id: Uuid,
29+
/// When the channel was created; with `channel_id`, the scan's cursor.
30+
pub created_at: DateTime<Utc>,
31+
}
32+
33+
// One probe per kind on `idx_events_addressable`. A channel's discovery
34+
// events are written after its row, so `created_at` bounds them from below
35+
// and, at run time, prunes the monthly `events` partitions to the ones since
36+
// the channel was created. The hour of slack covers a relay clock behind the
37+
// database's: events carry the relay's time, the channel row the database's.
38+
// `$also` adds further conditions on `e`, such as a constant floor the
39+
// planner can prune with whatever join it picks.
40+
//
41+
// Expands to the probe as a string literal, with the kinds array and relay
42+
// pubkey as the given bind parameters, so each query stays static SQL.
43+
macro_rules! missing_kind_probe {
44+
($kinds:literal, $relay:literal, $also:literal) => {
45+
concat!(
46+
"SELECT 1 FROM unnest(",
47+
$kinds,
48+
"::int[]) AS wanted(kind)
49+
WHERE NOT EXISTS (
50+
SELECT 1 FROM events e
51+
WHERE e.community_id = ch.community_id
52+
AND e.kind = wanted.kind
53+
AND e.pubkey = ",
54+
$relay,
55+
"
56+
AND e.channel_id = ch.id
57+
AND e.deleted_at IS NULL
58+
AND e.created_at >= ch.created_at - INTERVAL '1 hour'
59+
",
60+
$also,
61+
"
62+
)"
63+
)
64+
};
65+
}
66+
67+
const CHANNEL_MISSING_DISCOVERY_SQL: &str = concat!(
68+
"SELECT EXISTS (
69+
SELECT 1 FROM channels ch
70+
WHERE ch.community_id = $1 AND ch.id = $2 AND ch.deleted_at IS NULL
71+
AND EXISTS (",
72+
missing_kind_probe!("$4", "$3", ""),
73+
"))"
74+
);
75+
76+
const LIST_CHANNELS_MISSING_DISCOVERY_SQL: &str = concat!(
77+
"SELECT ch.community_id, community.host, ch.id, ch.created_at
78+
FROM channels ch
79+
JOIN communities community
80+
ON community.id = ch.community_id
81+
AND community.archived_at IS NULL
82+
AND community.deleted_at IS NULL
83+
AND community.deletion_state = 'active'
84+
WHERE ch.deleted_at IS NULL
85+
AND ch.created_at >= $1
86+
AND ch.created_at < $2
87+
AND (ch.created_at, ch.id) > ($3, $4)
88+
AND EXISTS (",
89+
missing_kind_probe!(
90+
"$6",
91+
"$5",
92+
"AND e.created_at >= $1::timestamptz - INTERVAL '1 hour'"
93+
),
94+
")
95+
ORDER BY ch.created_at, ch.id
96+
LIMIT $7"
97+
);
98+
99+
/// Whether the live channel `channel_id` lacks a live relay-signed event of
100+
/// any of [`GROUP_DISCOVERY_KINDS`]. A deleted or unknown channel lacks
101+
/// nothing.
102+
pub async fn channel_missing_discovery(
103+
pool: &PgPool,
104+
community_id: CommunityId,
105+
channel_id: Uuid,
106+
relay_pubkey: &[u8],
107+
) -> Result<bool> {
108+
let mut connection =
109+
observability::acquire_writer(pool, observability::WriterOperation::EventWrite).await?;
110+
let missing: bool = sqlx::query_scalar(CHANNEL_MISSING_DISCOVERY_SQL)
111+
.bind(community_id.as_uuid())
112+
.bind(channel_id)
113+
.bind(relay_pubkey)
114+
.bind(GROUP_DISCOVERY_KINDS.as_slice())
115+
.fetch_one(&mut *connection)
116+
.await?;
117+
Ok(missing)
118+
}
119+
120+
/// One page, in `(created_at, id)` order, of live channels in active
121+
/// communities created from `created_since` until `created_before` that
122+
/// lack a live relay-signed event of any of [`GROUP_DISCOVERY_KINDS`].
123+
///
124+
/// `after` is the previous page's last `(created_at, channel_id)`. A page
125+
/// shorter than `limit` is the last one. This is an internal
126+
/// cross-community maintenance read: callers must keep each channel's
127+
/// community when publishing for it.
128+
pub async fn list_channels_missing_discovery(
129+
pool: &PgPool,
130+
relay_pubkey: &[u8],
131+
created_since: DateTime<Utc>,
132+
created_before: DateTime<Utc>,
133+
after: Option<(DateTime<Utc>, Uuid)>,
134+
limit: i64,
135+
) -> Result<Vec<ChannelMissingDiscovery>> {
136+
let mut connection =
137+
observability::acquire_writer(pool, observability::WriterOperation::Maintenance).await?;
138+
let (after_created_at, after_id) = after.unwrap_or((created_since, Uuid::nil()));
139+
let rows = sqlx::query(LIST_CHANNELS_MISSING_DISCOVERY_SQL)
140+
.bind(created_since)
141+
.bind(created_before)
142+
.bind(after_created_at)
143+
.bind(after_id)
144+
.bind(relay_pubkey)
145+
.bind(GROUP_DISCOVERY_KINDS.as_slice())
146+
.bind(limit)
147+
.fetch_all(&mut *connection)
148+
.await?;
149+
rows.into_iter()
150+
.map(|row| {
151+
Ok(ChannelMissingDiscovery {
152+
community_id: CommunityId::from_uuid(row.try_get("community_id")?),
153+
host: row.try_get("host")?,
154+
channel_id: row.try_get("id")?,
155+
created_at: row.try_get("created_at")?,
156+
})
157+
})
158+
.collect()
159+
}
160+
161+
impl Db {
162+
/// Whether a live channel lacks any of its relay-signed discovery events.
163+
/// See [`channel_missing_discovery`].
164+
#[datastore_span(name = "channel_missing_discovery", system = "postgresql")]
165+
pub async fn channel_missing_discovery(
166+
&self,
167+
community_id: CommunityId,
168+
channel_id: Uuid,
169+
relay_pubkey: &[u8],
170+
) -> Result<bool> {
171+
channel_missing_discovery(&self.pool, community_id, channel_id, relay_pubkey).await
172+
}
173+
174+
/// One page of channels lacking relay-signed discovery events. See
175+
/// [`list_channels_missing_discovery`].
176+
#[datastore_span(name = "list_channels_missing_discovery", system = "postgresql")]
177+
pub async fn list_channels_missing_discovery(
178+
&self,
179+
relay_pubkey: &[u8],
180+
created_since: DateTime<Utc>,
181+
created_before: DateTime<Utc>,
182+
after: Option<(DateTime<Utc>, Uuid)>,
183+
limit: i64,
184+
) -> Result<Vec<ChannelMissingDiscovery>> {
185+
list_channels_missing_discovery(
186+
&self.pool,
187+
relay_pubkey,
188+
created_since,
189+
created_before,
190+
after,
191+
limit,
192+
)
193+
.await
194+
}
195+
}

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ mod event_floor_postgres_tests;
5050
pub mod feed;
5151
/// Git repository name registry (NIP-34 kind:30617).
5252
pub mod git_repo;
53+
/// Channels missing their relay-signed discovery events (kinds 39000–39002).
54+
pub mod group_discovery;
5355
/// Deployment-wide leader election over session advisory locks.
5456
pub mod leader_lock;
5557
/// Compact viewer membership projections.

‎crates/buzz-db/tests/observability_source.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,9 @@ fn p0_pool_acquisitions_use_typed_operation_pairs_without_other() {
206206
.0;
207207
assert!(dm_snapshot.contains("tx: &mut buzz_db::AdmittedTx"));
208208
assert!(dm_snapshot.contains("buzz_db::dm::lock_dm_visibility(tx,"));
209-
assert!(side_effects.contains("query_events_for_bootstrap"));
209+
let group_discovery = include_str!("../src/store/group_discovery.rs");
210+
assert!(group_discovery
211+
.contains("acquire_writer(pool, observability::WriterOperation::Maintenance)"));
210212
assert!(side_effects.contains(".list_channels_for_bootstrap("));
211213

212214
let deletion = include_str!("../src/store/deletion.rs");

‎crates/buzz-relay/src/handlers/command_executor.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use buzz_workflow::executor::TriggerContext;
2929
use crate::state::AppState;
3030
use crate::webhook_secret;
3131

32+
use super::discovery_repair::republish_missing_discovery;
3233
use super::ingest::{extract_channel_id, IngestAuth, IngestError, IngestResult};
3334
use super::side_effects::{
3435
emit_group_discovery_events, emit_membership_notification, emit_system_message,
@@ -582,6 +583,16 @@ async fn handle_dm_open(
582583
if let Err(e) = publish_dm_visibility_snapshot(tenant, state, &self_bytes).await {
583584
warn!("DM re-open: visibility snapshot failed: {e}");
584585
}
586+
if added.is_empty() {
587+
// Additions publish discovery anyway. Otherwise a retry repairs
588+
// discovery that a failed post-commit emission left missing,
589+
// which clients need to confirm the DM's members.
590+
if let Err(e) =
591+
republish_missing_discovery(tenant, state, channel.id, "dm_reopen").await
592+
{
593+
warn!(channel = %channel.id, "DM re-open: discovery repair failed: {e}");
594+
}
595+
}
585596
announce_dm_additions(tenant, state, channel.id, &self_bytes, &added).await;
586597
}
587598

0 commit comments

Comments
 (0)